use of org.spongepowered.common.interfaces.world.gen.IMixinChunkProviderServer in project SpongeCommon by SpongePowered.
the class MixinWorldEntitySpawner method findChunksForSpawning.
/**
* @author blood - February 18th, 2017
* @reason Refactor entire method for optimizations and spawn limits.
*
* @param worldServerIn The world
* @param spawnHostileMobs If hostile entities can spawn
* @param spawnPeacefulMobs If passive entities can spawn
* @param spawnOnSetTickRate If tickrate has been reached for spawning passives
* @return The amount of entities spawned
*/
@Overwrite
public int findChunksForSpawning(WorldServer worldServerIn, boolean spawnHostileMobs, boolean spawnPeacefulMobs, boolean spawnOnSetTickRate) {
if (!spawnHostileMobs && !spawnPeacefulMobs) {
return 0;
}
try (PhaseContext<?> context = GenerationPhase.State.WORLD_SPAWNER_SPAWNING.createPhaseContext().world(worldServerIn).buildAndSwitch()) {
Iterator<Chunk> chunkIterator = this.eligibleSpawnChunks.iterator();
while (chunkIterator.hasNext()) {
Chunk chunk = chunkIterator.next();
((IMixinChunk) chunk).setIsSpawning(false);
chunkIterator.remove();
}
IMixinWorldServer spongeWorld = ((IMixinWorldServer) worldServerIn);
spongeWorld.getTimingsHandler().mobSpawn.startTiming();
int chunkSpawnCandidates = 0;
final int mobSpawnRange = Math.min(((IMixinWorldServer) worldServerIn).getActiveConfig().getConfig().getWorld().getMobSpawnRange(), ((org.spongepowered.api.world.World) worldServerIn).getViewDistance());
// Vanilla uses a div count of 289 (17x17) which assumes the view distance is 8.
// Since we allow for custom ranges, we need to adjust the div count based on the
// mob spawn range set by server.
final int MOB_SPAWN_COUNT_DIV = (2 * mobSpawnRange + 1) * (2 * mobSpawnRange + 1);
for (EntityPlayer entityplayer : worldServerIn.playerEntities) {
// We treat players who do not affect spawning as "spectators"
if (!((IMixinEntityPlayer) entityplayer).affectsSpawning() || entityplayer.isSpectator()) {
continue;
}
int playerPosX = MathHelper.floor(entityplayer.posX / 16.0D);
int playerPosZ = MathHelper.floor(entityplayer.posZ / 16.0D);
for (int i = -mobSpawnRange; i <= mobSpawnRange; ++i) {
for (int j = -mobSpawnRange; j <= mobSpawnRange; ++j) {
boolean flag = i == -mobSpawnRange || i == mobSpawnRange || j == -mobSpawnRange || j == mobSpawnRange;
final Chunk chunk = ((IMixinChunkProviderServer) worldServerIn.getChunkProvider()).getLoadedChunkWithoutMarkingActive(i + playerPosX, j + playerPosZ);
if (chunk == null || (chunk.unloadQueued && !((IMixinChunk) chunk).isPersistedChunk())) {
// Don't attempt to spawn in an unloaded chunk
continue;
}
final IMixinChunk spongeChunk = (IMixinChunk) chunk;
++chunkSpawnCandidates;
final ChunkPos chunkPos = chunk.getPos();
if (!flag && worldServerIn.getWorldBorder().contains(chunkPos)) {
PlayerChunkMapEntry playerchunkmapentry = worldServerIn.getPlayerChunkMap().getEntry(chunkPos.x, chunkPos.z);
if (playerchunkmapentry != null && playerchunkmapentry.isSentToPlayers() && !spongeChunk.isSpawning()) {
this.eligibleSpawnChunks.add(chunk);
spongeChunk.setIsSpawning(true);
}
}
}
}
}
// If there are no eligible chunks, return early
if (this.eligibleSpawnChunks.size() == 0) {
spongeWorld.getTimingsHandler().mobSpawn.stopTiming();
return 0;
}
int totalSpawned = 0;
final long worldTotalTime = worldServerIn.getTotalWorldTime();
final SpongeConfig<? extends GeneralConfigBase> activeConfig = ((IMixinWorldServer) worldServerIn).getActiveConfig();
labelOuterLoop: for (EnumCreatureType enumCreatureType : EnumCreatureType.values()) {
int limit = 0;
int tickRate = 0;
if (enumCreatureType == EnumCreatureType.MONSTER) {
limit = activeConfig.getConfig().getSpawner().getMonsterSpawnLimit();
tickRate = activeConfig.getConfig().getSpawner().getMonsterTickRate();
} else if (enumCreatureType == EnumCreatureType.CREATURE) {
limit = activeConfig.getConfig().getSpawner().getAnimalSpawnLimit();
tickRate = activeConfig.getConfig().getSpawner().getAnimalTickRate();
} else if (enumCreatureType == EnumCreatureType.WATER_CREATURE) {
limit = activeConfig.getConfig().getSpawner().getAquaticSpawnLimit();
tickRate = activeConfig.getConfig().getSpawner().getAquaticTickRate();
} else if (enumCreatureType == EnumCreatureType.AMBIENT) {
limit = activeConfig.getConfig().getSpawner().getAmbientSpawnLimit();
tickRate = activeConfig.getConfig().getSpawner().getAmbientTickRate();
}
if (limit == 0 || tickRate == 0 || (worldTotalTime % tickRate) != 0L) {
continue;
}
if ((!enumCreatureType.getPeacefulCreature() || spawnPeacefulMobs) && (enumCreatureType.getPeacefulCreature() || spawnHostileMobs)) {
int entityCount = SpongeImplHooks.countEntities(worldServerIn, enumCreatureType, true);
int maxCount = limit * chunkSpawnCandidates / MOB_SPAWN_COUNT_DIV;
if (entityCount > maxCount) {
continue labelOuterLoop;
}
chunkIterator = this.eligibleSpawnChunks.iterator();
int mobLimit = maxCount - entityCount + 1;
labelChunkStart: while (chunkIterator.hasNext() && mobLimit > 0) {
final Chunk chunk = chunkIterator.next();
final BlockPos.MutableBlockPos mutableBlockPos = new BlockPos.MutableBlockPos();
final BlockPos blockpos = getRandomChunkPosition(worldServerIn, chunk);
int k1 = blockpos.getX();
int l1 = blockpos.getY();
int i2 = blockpos.getZ();
IBlockState iblockstate = worldServerIn.getBlockState(blockpos);
if (!iblockstate.isNormalCube()) {
int spawnCount = 0;
for (int spawnLimit = 0; spawnLimit < 3; ++spawnLimit) {
int l2 = k1;
int i3 = l1;
int j3 = i2;
Biome.SpawnListEntry spawnListEntry = null;
IEntityLivingData ientitylivingdata = null;
int l3 = MathHelper.ceil(Math.random() * 4.0D);
for (int i4 = 0; i4 < l3; ++i4) {
l2 += worldServerIn.rand.nextInt(6) - worldServerIn.rand.nextInt(6);
i3 += worldServerIn.rand.nextInt(1) - worldServerIn.rand.nextInt(1);
j3 += worldServerIn.rand.nextInt(6) - worldServerIn.rand.nextInt(6);
mutableBlockPos.setPos(l2, i3, j3);
final double spawnX = l2 + 0.5F;
final double spawnY = i3;
final double spawnZ = j3 + 0.5F;
if (!worldServerIn.isAnyPlayerWithinRangeAt(spawnX, spawnY, spawnZ, 24.0D) && worldServerIn.getSpawnPoint().distanceSq(spawnX, spawnY, spawnZ) >= 576.0D) {
if (spawnListEntry == null) {
spawnListEntry = worldServerIn.getSpawnListEntryForTypeAt(enumCreatureType, mutableBlockPos);
if (spawnListEntry == null) {
break;
}
}
final EntityType entityType = EntityTypeRegistryModule.getInstance().getForClass(spawnListEntry.entityClass);
if (entityType != null) {
Vector3d vector3d = new Vector3d(spawnX, spawnY, spawnZ);
Transform<org.spongepowered.api.world.World> transform = new Transform<>((org.spongepowered.api.world.World) worldServerIn, vector3d);
ConstructEntityEvent.Pre event = SpongeEventFactory.createConstructEntityEventPre(Sponge.getCauseStackManager().getCurrentCause(), entityType, transform);
if (SpongeImpl.postEvent(event)) {
continue;
}
}
if (worldServerIn.canCreatureTypeSpawnHere(enumCreatureType, spawnListEntry, mutableBlockPos) && WorldEntitySpawner.canCreatureTypeSpawnAtLocation(EntitySpawnPlacementRegistry.getPlacementForEntity(spawnListEntry.entityClass), worldServerIn, mutableBlockPos)) {
EntityLiving entityliving;
try {
entityliving = spawnListEntry.entityClass.getConstructor(new Class<?>[] { World.class }).newInstance(worldServerIn);
} catch (Exception exception) {
exception.printStackTrace();
continue labelOuterLoop;
}
entityliving.setLocationAndAngles(spawnX, spawnY, spawnZ, worldServerIn.rand.nextFloat() * 360.0F, 0.0F);
final boolean entityNotColliding = entityliving.isNotColliding();
final SpawnerSpawnType type = SpongeImplHooks.canEntitySpawnHere(entityliving, entityNotColliding);
if (type != SpawnerSpawnType.NONE) {
if (type == SpawnerSpawnType.NORMAL) {
ientitylivingdata = entityliving.onInitialSpawn(worldServerIn.getDifficultyForLocation(new BlockPos(entityliving)), ientitylivingdata);
}
if (entityNotColliding) {
++spawnCount;
worldServerIn.spawnEntity(entityliving);
} else {
entityliving.setDead();
}
mobLimit--;
if (mobLimit <= 0 || spawnCount >= SpongeImplHooks.getMaxSpawnPackSize(entityliving)) {
continue labelChunkStart;
}
}
totalSpawned += spawnCount;
}
}
}
}
}
}
}
}
spongeWorld.getTimingsHandler().mobSpawn.stopTiming();
return totalSpawned;
}
}
use of org.spongepowered.common.interfaces.world.gen.IMixinChunkProviderServer in project SpongeCommon by SpongePowered.
the class MixinWorldServer method notifyNeighborsOfStateChange.
/**
* @author gabizou - March 12th, 2016
*
* Technically an overwrite to properly track on *server* worlds.
*/
@Override
public void notifyNeighborsOfStateChange(BlockPos pos, Block blockType, boolean updateObserverBlocks) {
if (!isValid(pos)) {
return;
}
final Chunk chunk = ((IMixinChunkProviderServer) this.getChunkProvider()).getLoadedChunkWithoutMarkingActive(pos.getX() >> 4, pos.getZ() >> 4);
// Don't let neighbor updates trigger a chunk load ever
if (chunk == null) {
return;
}
final NotifyNeighborBlockEvent event = SpongeCommonEventFactory.callNotifyNeighborEvent(this, pos, NOTIFY_DIRECTIONS);
if (event == null || !event.isCancelled()) {
final PhaseTracker phaseTracker = PhaseTracker.getInstance();
for (EnumFacing facing : EnumFacing.values()) {
if (event != null) {
final Direction direction = DirectionFacingProvider.getInstance().getKey(facing).get();
if (!event.getNeighbors().keySet().contains(direction)) {
continue;
}
}
phaseTracker.notifyBlockOfStateChange(this, pos.offset(facing), blockType, pos);
}
}
// Copied over to ensure observers retain functionality.
if (updateObserverBlocks) {
this.updateObservingBlocksAt(pos, blockType);
}
}
use of org.spongepowered.common.interfaces.world.gen.IMixinChunkProviderServer in project SpongeCommon by SpongePowered.
the class MixinWorldServer method onConstruct.
@Inject(method = "<init>", at = @At("RETURN"))
private void onConstruct(MinecraftServer server, ISaveHandler saveHandlerIn, WorldInfo info, int dimensionId, Profiler profilerIn, CallbackInfo callbackInfo) {
if (info == null) {
SpongeImpl.getLogger().warn("World constructed without a WorldInfo! This will likely cause problems. Subsituting dummy info.", new RuntimeException("Stack trace:"));
this.worldInfo = new WorldInfo(new WorldSettings(0, GameType.NOT_SET, false, false, WorldType.DEFAULT), "sponge$dummy_world");
}
// Checks to make sure no mod has changed our worldInfo and if so, reverts back to original.
// Mods such as FuturePack replace worldInfo with a custom one for separate world time.
// This change is not needed as all worlds use separate save handlers.
this.worldInfo = info;
this.timings = new WorldTimingsHandler((WorldServer) (Object) this);
this.dimensionId = dimensionId;
this.prevWeather = getWeather();
this.weatherStartTime = this.worldInfo.getWorldTotalTime();
((World) (Object) this).getWorldBorder().addListener(new PlayerBorderListener(this.getMinecraftServer(), dimensionId));
PortalAgentType portalAgentType = ((WorldProperties) this.worldInfo).getPortalAgentType();
if (!portalAgentType.equals(PortalAgentTypes.DEFAULT)) {
try {
this.worldTeleporter = (Teleporter) portalAgentType.getPortalAgentClass().getConstructor(new Class<?>[] { WorldServer.class }).newInstance(new Object[] { this });
} catch (Exception e) {
SpongeImpl.getLogger().log(Level.ERROR, "Could not create PortalAgent of type " + portalAgentType.getId() + " for world " + this.getName() + ": " + e.getMessage() + ". Falling back to default...");
}
}
// Turn on capturing
updateWorldGenerator();
// Need to set the active config before we call it.
this.chunkGCLoadThreshold = SpongeHooks.getActiveConfig((WorldServer) (Object) this).getConfig().getWorld().getChunkLoadThreadhold();
this.chunkGCTickInterval = this.getActiveConfig().getConfig().getWorld().getTickInterval();
this.weatherIceAndSnowEnabled = this.getActiveConfig().getConfig().getWorld().getWeatherIceAndSnow();
this.weatherThunderEnabled = this.getActiveConfig().getConfig().getWorld().getWeatherThunder();
this.updateEntityTick = 0;
this.mixinChunkProviderServer = ((IMixinChunkProviderServer) this.getChunkProvider());
this.setMemoryViewDistance(this.chooseViewDistanceValue(this.getActiveConfig().getConfig().getWorld().getViewDistance()));
}
use of org.spongepowered.common.interfaces.world.gen.IMixinChunkProviderServer in project SpongeCommon by SpongePowered.
the class MixinWorldServer method getBlockState.
/**
* @author gabizou - August 4th, 2016
* @author blood - May 11th, 2017 - Forces chunk requests if TE is ticking.
* @reason Rewrites the check to be inlined to {@link IMixinBlockPos}.
*
* @param pos The position
* @return The block state at the desired position
*/
@Override
public IBlockState getBlockState(BlockPos pos) {
// if (this.isOutsideBuildHeight(pos)) // Vanilla
if (((IMixinBlockPos) pos).isInvalidYPosition()) {
// Sponge end
return Blocks.AIR.getDefaultState();
} else {
// ExtraUtilities 2 expects to get the proper chunk while mining or it gets stuck in infinite loop
// TODO add TE config to disable/enable chunk loads
final boolean forceChunkRequests = this.mixinChunkProviderServer.getForceChunkRequests();
final PhaseTracker phaseTracker = PhaseTracker.getInstance();
final IPhaseState currentState = phaseTracker.getCurrentState();
if (currentState == TickPhase.Tick.TILE_ENTITY) {
((IMixinChunkProviderServer) this.getChunkProvider()).setForceChunkRequests(true);
}
net.minecraft.world.chunk.Chunk chunk = this.getChunkFromBlockCoords(pos);
this.mixinChunkProviderServer.setForceChunkRequests(forceChunkRequests);
return chunk.getBlockState(pos);
}
}
Aggregations