Skip to content

Commit

Permalink
Entity caching class is now a single object (Part 3)
Browse files Browse the repository at this point in the history
  • Loading branch information
OldSerpskiStalker committed Sep 25, 2024
1 parent 7dab488 commit fb1f7f2
Show file tree
Hide file tree
Showing 6 changed files with 153 additions and 74 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,11 @@ public static final class STRUCT_FILES_EXTENSION
*/
private static File globalDirectory = null;

/**
*
*/
static Cache cache = null;

/**
*
*/
Expand Down Expand Up @@ -199,6 +204,9 @@ public synchronized void preInit(FMLPreInitializationEvent event)
//
cacheStorage = new CacheStorage();

//
cache = new Cache();

//
ParserGenericJsonScripts.setRulePath(event.getModConfigurationDirectory());

Expand Down Expand Up @@ -272,8 +280,9 @@ public synchronized void serverLoad(FMLServerStartingEvent event)
@EventHandler
public synchronized void serverStopped(FMLServerStoppedEvent event)
{
Cache.cleanActualCache();
Cache.cleanBufferCache();
cache.cleanActualCache();
cache.cleanBufferCache();

Structures.STRUCTURES_CACHE.clean();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package org.imesense.dynamicspawncontrol.technical.configs;

import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;

public final class ConfigCacheWorldGame implements IConfig
{
@Override
public void init(FMLPreInitializationEvent event)
{

}

@Override
public void readProperties(Configuration configuration)
{

}

@Override
public void read()
{

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public synchronized void onUpdatePotentialSpawns_0(WorldEvent.PotentialSpawns ev
{
assert entityKey != null;

int currentCount = Cache.getEntitiesByResourceLocation(entityKey).size();
int currentCount = Cache.getInstance().getEntitiesByResourceLocation(entityKey).size();
int maxCount = entityData.getMaxCount();

if (currentCount >= maxCount)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import org.imesense.dynamicspawncontrol.debug.CodeGenericUtils;
import org.imesense.dynamicspawncontrol.technical.customlibrary.Log;
import org.imesense.dynamicspawncontrol.technical.parsers.beta.ParserSingleScriptCheckSpawn;

import javax.annotation.Nonnull;
import java.util.Collections;
Expand All @@ -24,27 +27,47 @@

public final class Cache
{
public static int TickCounter = 0;
public static volatile int DynamicUpdateInterval = 1200; // Сначала 1200, затем 4800
public static final int FIRST_UPDATE_INTERVAL = 1200; // Первое обновление
public static final int SUBSEQUENT_UPDATE_INTERVAL = 4800; // Последующие обновления

public static boolean isFirstUpdate = true; // Флаг для отслеживания первого обновления
public static boolean isPrimaryPlayerLogged = false; // Флаг для главного игрока

public static final Set<ChunkPos> CACHE_VALID_CHUNKS = new HashSet<>();
public static final Set<EntityAnimal> CACHED_ACTUAL_ANIMALS = new HashSet<>();
public static final Set<EntityAnimal> CACHED_BUFFER_ANIMALS = new HashSet<>();
public static final Set<IAnimals> CACHED_ACTUAL_HOSTILES = new HashSet<>();
public static final Set<IAnimals> CACHED_BUFFER_HOSTILES = new HashSet<>();
public static final Set<EntityLivingBase> CACHED_ACTUAL_ALL = new HashSet<>();
public static final Set<EntityLivingBase> CACHED_BUFFER_ALL = new HashSet<>();
public static final ConcurrentMap<String, Set<EntityLivingBase>> ENTITIES_ACTUAL_BY_NAME = new ConcurrentHashMap<>();
public static final ConcurrentMap<String, Set<EntityLivingBase>> ENTITIES_BUFFER_BY_NAME = new ConcurrentHashMap<>();
public static final ConcurrentMap<ResourceLocation, Set<EntityLivingBase>> ENTITIES_ACTUAL_BY_RESOURCE_LOCATION = new ConcurrentHashMap<>();
public static final ConcurrentMap<ResourceLocation, Set<EntityLivingBase>> ENTITIES_BUFFER_BY_RESOURCE_LOCATION = new ConcurrentHashMap<>();

public static void updateCache(@Nonnull World world)
public int TickCounter = 0;
public volatile int DynamicUpdateInterval = 1200;
public final int FIRST_UPDATE_INTERVAL = 1200;
public final int SUBSEQUENT_UPDATE_INTERVAL = 4800;

public boolean isFirstUpdate = true;
public boolean isPrimaryPlayerLogged = false;

public final Set<ChunkPos> CACHE_VALID_CHUNKS = new HashSet<>();
public final Set<EntityAnimal> CACHED_ACTUAL_ANIMALS = new HashSet<>();
public final Set<EntityAnimal> CACHED_BUFFER_ANIMALS = new HashSet<>();
public final Set<IAnimals> CACHED_ACTUAL_HOSTILES = new HashSet<>();
public final Set<IAnimals> CACHED_BUFFER_HOSTILES = new HashSet<>();
public final Set<EntityLivingBase> CACHED_ACTUAL_ALL = new HashSet<>();
public final Set<EntityLivingBase> CACHED_BUFFER_ALL = new HashSet<>();
public final ConcurrentMap<String, Set<EntityLivingBase>> ENTITIES_ACTUAL_BY_NAME = new ConcurrentHashMap<>();
public final ConcurrentMap<String, Set<EntityLivingBase>> ENTITIES_BUFFER_BY_NAME = new ConcurrentHashMap<>();
public final ConcurrentMap<ResourceLocation, Set<EntityLivingBase>> ENTITIES_ACTUAL_BY_RESOURCE_LOCATION = new ConcurrentHashMap<>();
public final ConcurrentMap<ResourceLocation, Set<EntityLivingBase>> ENTITIES_BUFFER_BY_RESOURCE_LOCATION = new ConcurrentHashMap<>();

private static Cache instance = null;

private static boolean instanceExists = false;

public static Cache getInstance() { return instance; }

public Cache()
{
if (instanceExists)
{
Log.writeDataToLogFile(2, String.format("An instance of [%s] already exists!", this.getClass().getSimpleName()));
throw new RuntimeException();
}

instanceExists = true;

instance = this;
CodeGenericUtils.printInitClassToLog(Cache.class);
}

public void updateCache(@Nonnull World world)
{
cleanActualCache();

Expand Down Expand Up @@ -97,7 +120,7 @@ else if (entity instanceof EntityMob)
}
}

private static Set<ChunkPos> totalValidChunksSpawnForPlayer(WorldServer worldServer, EntityPlayer player)
private Set<ChunkPos> totalValidChunksSpawnForPlayer(WorldServer worldServer, EntityPlayer player)
{
Set<ChunkPos> validChunks = new HashSet<>();

Expand All @@ -121,48 +144,48 @@ private static Set<ChunkPos> totalValidChunksSpawnForPlayer(WorldServer worldSer
return validChunks;
}

public static int getActualAnimalCount()
public int getActualAnimalCount()
{
return CACHED_ACTUAL_ANIMALS.size();
}

public static int getActualTotalEntityCount()
public int getActualTotalEntityCount()
{
return CACHED_ACTUAL_ALL.size();
}

public static int getActualHostileEntityCount()
public int getActualHostileEntityCount()
{
return CACHED_ACTUAL_HOSTILES.size();
}

public static int getBufferAnimalCount()
public int getBufferAnimalCount()
{
return CACHED_BUFFER_ANIMALS.size();
}

public static int getBufferTotalEntityCount()
public int getBufferTotalEntityCount()
{
return CACHED_BUFFER_ALL.size();
}

public static int getBufferHostileEntityCount()
public int getBufferHostileEntityCount()
{
return CACHED_BUFFER_HOSTILES.size();
}

public static int getValidChunkCount()
public int getValidChunkCount()
{
return CACHE_VALID_CHUNKS.size();
}

@Nonnull
public static Set<EntityLivingBase> getEntitiesByResourceLocation(@Nonnull ResourceLocation resourceLocation)
public Set<EntityLivingBase> getEntitiesByResourceLocation(@Nonnull ResourceLocation resourceLocation)
{
return ENTITIES_ACTUAL_BY_RESOURCE_LOCATION.getOrDefault(resourceLocation, Collections.emptySet());
}

public static void copyActualToBuffer()
public void copyActualToBuffer()
{
CACHED_BUFFER_ANIMALS.clear();

Expand All @@ -187,7 +210,7 @@ public static void copyActualToBuffer()
ENTITIES_BUFFER_BY_RESOURCE_LOCATION.put(key, new HashSet<>(set)));
}

public static void cleanActualCache()
public void cleanActualCache()
{
CACHED_ACTUAL_ANIMALS.clear();
CACHED_ACTUAL_HOSTILES.clear();
Expand All @@ -198,7 +221,7 @@ public static void cleanActualCache()
CACHE_VALID_CHUNKS.clear();
}

public static void cleanBufferCache()
public void cleanBufferCache()
{
CACHED_BUFFER_ANIMALS.clear();
CACHED_BUFFER_HOSTILES.clear();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@

import java.util.HashSet;

import static org.imesense.dynamicspawncontrol.technical.worldcache.Cache.*;

@Mod.EventBusSubscriber
public final class CacheEvents
{
static CacheMonitor cacheMonitor = null;

private static boolean instanceExists = false;

public CacheEvents()
Expand All @@ -42,6 +42,8 @@ public CacheEvents()

instanceExists = true;

cacheMonitor = new CacheMonitor();

CodeGenericUtils.printInitClassToLog(CacheEvents.class);
}

Expand All @@ -50,20 +52,19 @@ public synchronized void onWorldTick_0(TickEvent.WorldTickEvent event)
{
if (event.phase == TickEvent.Phase.END)
{
Cache.TickCounter++;
Cache.getInstance().TickCounter++;

if (Cache.TickCounter >= Cache.DynamicUpdateInterval)
if (Cache.getInstance().TickCounter >= Cache.getInstance().DynamicUpdateInterval)
{
Cache.TickCounter = 0;
Cache.getInstance().TickCounter = 0;

Cache.copyActualToBuffer();
Cache.updateCache(event.world);
Cache.getInstance().copyActualToBuffer();
Cache.getInstance().updateCache(event.world);

// Если это первое обновление, то меняем интервал на 4800
if (Cache.isFirstUpdate)
if (Cache.getInstance().isFirstUpdate)
{
Cache.DynamicUpdateInterval = Cache.SUBSEQUENT_UPDATE_INTERVAL;
Cache.isFirstUpdate = false;
Cache.getInstance().DynamicUpdateInterval = Cache.getInstance().SUBSEQUENT_UPDATE_INTERVAL;
Cache.getInstance().isFirstUpdate = false;
}
}
}
Expand All @@ -72,22 +73,22 @@ public synchronized void onWorldTick_0(TickEvent.WorldTickEvent event)
@SubscribeEvent
public synchronized void onPlayerLoggedIn_1(PlayerEvent.PlayerLoggedInEvent event)
{
if (!Cache.isPrimaryPlayerLogged)
if (!Cache.getInstance().isPrimaryPlayerLogged)
{
Cache.isPrimaryPlayerLogged = true;
Cache.DynamicUpdateInterval = Cache.FIRST_UPDATE_INTERVAL;
Cache.TickCounter = 0; // Сбрасываем счётчик при первом входе
Cache.isFirstUpdate = true;
Cache.getInstance().isPrimaryPlayerLogged = true;
Cache.getInstance().DynamicUpdateInterval = Cache.getInstance().FIRST_UPDATE_INTERVAL;
Cache.getInstance().TickCounter = 0;
Cache.getInstance().isFirstUpdate = true;
}


Cache.copyActualToBuffer();
Cache.getInstance().copyActualToBuffer();
}

@SubscribeEvent
public synchronized void onPlayerLoggedOut_2(PlayerEvent.PlayerLoggedOutEvent event)
{
Cache.copyActualToBuffer();
Cache.getInstance().copyActualToBuffer();
}

@SubscribeEvent(priority = EventPriority.LOW)
Expand All @@ -100,7 +101,7 @@ public synchronized void onRenderOverlay_3(RenderGameOverlayEvent.Post event)

if (event.getType() == RenderGameOverlayEvent.ElementType.TEXT)
{
CacheMonitor.renderDebugInfo(event.getResolution());
cacheMonitor.renderDebugInfo(event.getResolution());
}
}

Expand All @@ -117,36 +118,36 @@ public synchronized void onEntityJoinWorld_4(EntityJoinWorldEvent event)

WorldServer worldServer = (WorldServer) world;

Cache.updateCache(worldServer);
Cache.getInstance().updateCache(worldServer);

if (Cache.CACHE_VALID_CHUNKS.contains(new ChunkPos(entity.chunkCoordX, entity.chunkCoordZ)))
if (Cache.getInstance().CACHE_VALID_CHUNKS.contains(new ChunkPos(entity.chunkCoordX, entity.chunkCoordZ)))
{
if (entity instanceof IAnimals)
{
if (entity instanceof EntityAnimal)
{
CACHED_ACTUAL_ANIMALS.add((EntityAnimal) entity);
Cache.getInstance().CACHED_ACTUAL_ANIMALS.add((EntityAnimal) entity);
}
else if (entity instanceof EntityMob)
{
Cache.CACHED_ACTUAL_HOSTILES.add((IAnimals) entity);
Cache.getInstance().CACHED_ACTUAL_HOSTILES.add((IAnimals) entity);
}
}

if (entity instanceof EntityLivingBase)
{
String entityName = entity.getName();

Cache.CACHED_ACTUAL_ALL.add((EntityLivingBase) entity);
Cache.getInstance().CACHED_ACTUAL_ALL.add((EntityLivingBase) entity);

Cache.ENTITIES_ACTUAL_BY_NAME.computeIfAbsent(entityName, k ->
Cache.getInstance().ENTITIES_ACTUAL_BY_NAME.computeIfAbsent(entityName, k ->
new HashSet<>()).add((EntityLivingBase) entity);

ResourceLocation entityKey = EntityList.getKey(entity);

if (entityKey != null)
{
Cache.ENTITIES_ACTUAL_BY_RESOURCE_LOCATION.computeIfAbsent(entityKey, k ->
Cache.getInstance().ENTITIES_ACTUAL_BY_RESOURCE_LOCATION.computeIfAbsent(entityKey, k ->
new HashSet<>()).add((EntityLivingBase) entity);
}
}
Expand All @@ -167,7 +168,7 @@ public synchronized void updateEntitySpawnEvent_5(LivingSpawnEvent.CheckSpawn ev
assert entityKey != null;

int maxCount = entityData.getMaxCount();
int currentCount = Cache.getEntitiesByResourceLocation(entityKey).size();
int currentCount = Cache.getInstance().getEntitiesByResourceLocation(entityKey).size();

if (currentCount > maxCount)
{
Expand Down
Loading

0 comments on commit fb1f7f2

Please sign in to comment.