下面列出了怎么用net.minecraft.util.math.ChunkPos的API类实例代码及写法,或者点击链接到github查看源代码。
public static Set<ChunkPos> getTouchedChunksForBoxes(Collection<? extends Box> boxes)
{
Set<ChunkPos> set = new HashSet<>();
for (Box box : boxes)
{
final int boxXMin = Math.min(box.getPos1().getX(), box.getPos2().getX()) >> 4;
final int boxZMin = Math.min(box.getPos1().getZ(), box.getPos2().getZ()) >> 4;
final int boxXMax = Math.max(box.getPos1().getX(), box.getPos2().getX()) >> 4;
final int boxZMax = Math.max(box.getPos1().getZ(), box.getPos2().getZ()) >> 4;
for (int cz = boxZMin; cz <= boxZMax; ++cz)
{
for (int cx = boxXMin; cx <= boxXMax; ++cx)
{
set.add(new ChunkPos(cx, cz));
}
}
}
return set;
}
protected void addPlacement(SchematicPlacement placement, LayerRange range)
{
Set<ChunkPos> touchedChunks = placement.getTouchedChunks();
for (ChunkPos pos : touchedChunks)
{
int count = 0;
for (IntBoundingBox box : placement.getBoxesWithinChunk(pos.x, pos.z).values())
{
box = range.getClampedBox(box);
if (box != null)
{
this.boxesInChunks.put(pos, box);
++count;
}
}
if (count > 0)
{
this.individualChunks.add(pos);
this.onChunkAddedForHandling(pos, placement);
}
}
}
private void injectChunkIntoWorld(int x, int z, Chunk chunk) {
ChunkProviderServer provider = (ChunkProviderServer) this.getWorldObj().getChunkProvider();
chunk.dirty = true;
// claimedChunks[x - getgetOwnedChunks().getMinX()][z - getgetOwnedChunks().getMinZ()] = chunk;
loadedChunksMap.put(ChunkPos.asLong(x, z), chunk);
provider.loadedChunks.put(ChunkPos.asLong(x, z), chunk);
chunk.onLoad();
PlayerChunkMap map = ((WorldServer) this.getWorldObj()).getPlayerChunkMap();
PlayerChunkMapEntry entry = new PlayerChunkMapEntry(map, x, z);
long i = PlayerChunkMap.getIndex(x, z);
// TODO: In future we need to do better to account for concurrency.
map.entryMap.put(i, entry);
map.entries.add(entry);
entry.sentToPlayers = true;
// TODO: In future we need to do better to account for concurrency.
entry.players = Collections.unmodifiableList(shipHolder.getWatchingPlayers());
}
@Override
public void ticketsLoaded(List<Ticket> tickets, World world)
{
for (Ticket ticket : tickets)
{
//System.out.println("void ticketsLoaded(): looping tickets");
if (ticket != null)
{
for (ChunkPos chunk : ticket.getChunkList())
{
//System.out.println("void ticketsLoaded(): forcing chunk: " + chunk + " in dimension: " + ticket.world.provider.getDimensionId());
ForgeChunkManager.forceChunk(ticket, chunk);
}
}
}
}
public boolean loadChunkForcedWithTicket(Ticket ticket, int dimension, int chunkX, int chunkZ, int unloadDelay)
{
if (ticket == null)
{
EnderUtilities.logger.warn("loadChunkForcedWithTicket(): ticket == null");
return false;
}
ForgeChunkManager.forceChunk(ticket, new ChunkPos(chunkX, chunkZ));
if (unloadDelay > 0)
{
//System.out.println("loadChunkForcedWithTicket() adding timeout: " + unloadDelay);
this.addChunkTimeout(ticket, dimension, chunkX, chunkZ, unloadDelay);
}
return this.loadChunkWithoutForce(dimension, chunkX, chunkZ);
}
void addTouchedChunksFor(SchematicPlacement placement, boolean updateOverlay)
{
if (placement.matchesRequirement(RequiredEnabled.PLACEMENT_ENABLED))
{
Set<ChunkPos> chunks = placement.getTouchedChunks();
for (ChunkPos pos : chunks)
{
if (this.schematicsTouchingChunk.containsEntry(pos, placement) == false)
{
this.schematicsTouchingChunk.put(pos, placement);
this.updateTouchedBoxesInChunk(pos);
}
this.chunksToUnload.remove(pos);
}
this.markChunksForRebuild(chunks);
if (updateOverlay)
{
this.updateOverlayRendererIfEnabled(placement);
}
}
}
protected void countBlocksInChunk(ChunkPos pos)
{
BlockPos.MutableBlockPos posMutable = new BlockPos.MutableBlockPos();
for (IntBoundingBox bb : this.getBoxesInChunk(pos))
{
final int startX = bb.minX;
final int startY = bb.minY;
final int startZ = bb.minZ;
final int endX = bb.maxX;
final int endY = bb.maxY;
final int endZ = bb.maxZ;
for (int y = startY; y <= endY; ++y)
{
for (int z = startZ; z <= endZ; ++z)
{
for (int x = startX; x <= endX; ++x)
{
posMutable.setPos(x, y, z);
this.countAtPosition(posMutable);
}
}
}
}
}
public float getManaInfluence(World world, BlockPos pos) {
ChunkPos chunkPos = new ChunkPos(pos);
float mana = 0.0f;
for (int dx = -4 ; dx <= 4 ; dx++) {
for (int dz = -4 ; dz <= 4 ; dz++) {
ChunkPos cp = new ChunkPos(chunkPos.x + dx, chunkPos.z + dz);
ManaSphere sphere = getOrCreateSphereAt(world, cp);
if (sphere.getRadius() > 0) {
double distanceSq = pos.distanceSq(sphere.getCenter());
if (distanceSq < sphere.getRadius() * sphere.getRadius()) {
double distance = Math.sqrt(distanceSq);
mana += (sphere.getRadius() - distance) / sphere.getRadius();
}
}
}
}
return mana;
}
public float getManaStrength(World world, BlockPos pos) {
ChunkPos chunkPos = new ChunkPos(pos);
float mana = 0.0f;
for (int dx = -4 ; dx <= 4 ; dx++) {
for (int dz = -4 ; dz <= 4 ; dz++) {
ChunkPos cp = new ChunkPos(chunkPos.x + dx, chunkPos.z + dz);
ManaSphere sphere = getOrCreateSphereAt(world, cp);
if (sphere.getRadius() > 0) {
double distanceSq = pos.distanceSq(sphere.getCenter());
if (distanceSq < sphere.getRadius() * sphere.getRadius()) {
double distance = Math.sqrt(distanceSq);
double influence = (sphere.getRadius() - distance) / sphere.getRadius();
mana += influence * sphere.getCurrentMana();
}
}
}
}
return mana;
}
private void growMana(World world) {
for (Map.Entry<ChunkPos, ManaSphere> entry : spheres.entrySet()) {
ManaSphere sphere = entry.getValue();
if (sphere.getRadius() > 0) {
if (world.isBlockLoaded(sphere.getCenter())) {
float currentMana = sphere.getCurrentMana();
currentMana += .01f;
if (currentMana >= 5) {
currentMana = 5;
}
sphere.setCurrentMana(currentMana);
markDirty();
}
}
}
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
NBTTagList list = new NBTTagList();
for (Map.Entry<ChunkPos, ManaSphere> entry : spheres.entrySet()) {
NBTTagCompound sphereNBT = new NBTTagCompound();
ChunkPos pos = entry.getKey();
ManaSphere sphere = entry.getValue();
sphereNBT.setInteger("cx", pos.x);
sphereNBT.setInteger("cz", pos.z);
sphereNBT.setInteger("posx", sphere.getCenter().getX());
sphereNBT.setInteger("posy", sphere.getCenter().getY());
sphereNBT.setInteger("posz", sphere.getCenter().getZ());
sphereNBT.setFloat("radius", sphere.getRadius());
sphereNBT.setFloat("mana", sphere.getCurrentMana());
list.appendTag(sphereNBT);
}
compound.setTag("spheres", list);
return compound;
}
public static void markSchematicChunksForRenderUpdate(ChunkPos chunkPos)
{
World world = SchematicWorldHandler.getSchematicWorld();
if (world != null)
{
Long2ObjectMap<Chunk> schematicChunks = ((IMixinChunkProviderClient) (Object) world.getChunkProvider()).getLoadedChunks();
Long2ObjectMap<Chunk> clientChunks = ((IMixinChunkProviderClient) (Object) Minecraft.getMinecraft().world.getChunkProvider()).getLoadedChunks();
long key = ChunkPos.asLong(chunkPos.x, chunkPos.z);
if (schematicChunks.containsKey(key) && clientChunks.containsKey(key))
{
RenderGlobal rg = LitematicaRenderer.getInstance().getWorldRenderer();
rg.markBlockRangeForRenderUpdate((chunkPos.x << 4) - 1, 0, (chunkPos.z << 4) - 1,
(chunkPos.x << 4) + 1, 255, (chunkPos.z << 4) + 1);
}
}
}
public static void markSchematicChunkForRenderUpdate(BlockPos pos)
{
World world = SchematicWorldHandler.getSchematicWorld();
if (world != null)
{
Long2ObjectMap<Chunk> schematicChunks = ((IMixinChunkProviderClient) (Object) world.getChunkProvider()).getLoadedChunks();
Long2ObjectMap<Chunk> clientChunks = ((IMixinChunkProviderClient) (Object) Minecraft.getMinecraft().world.getChunkProvider()).getLoadedChunks();
long key = ChunkPos.asLong(pos.getX() >> 4, pos.getZ() >> 4);
if (schematicChunks.containsKey(key) && clientChunks.containsKey(key))
{
RenderGlobal rg = LitematicaRenderer.getInstance().getWorldRenderer();
rg.markBlockRangeForRenderUpdate(pos.getX() - 1, pos.getY() - 1, pos.getZ() - 1,pos.getX() + 1, pos.getY() + 1, pos.getZ() + 1);
}
}
}
@Override
public void populateEntities(ChunkRegion region) {
int centreX = region.getCenterChunkX();
int centreZ = region.getCenterChunkZ();
Biome biome = region.getBiome((new ChunkPos(centreX, centreZ)).getCenterBlockPos());
ChunkRandom chunkRandom = new ChunkRandom();
chunkRandom.setSeed(region.getSeed(), centreX << 4, centreZ << 4);
SpawnHelper.populateEntities(region, biome, centreX, centreZ, chunkRandom);
}
@Override
public void onUpdate()
{
Block currentBlock = block.getBlock();
BlockPos eyesPos = new BlockPos(RotationUtils.getEyesPos());
ChunkPos center = getPlayerChunkPos(eyesPos);
int range = area.getSelected().chunkRange;
// 20w21a: Assuming class_5321 is the new Dimension and using its
// toString() as an ID. Not sure why it has two Identifiers, but the
// combination should be unique for every dimension.
int dimensionId = MC.world.getRegistryKey().toString().hashCode();
addSearchersInRange(center, range, currentBlock, dimensionId);
removeSearchersOutOfRange(center, range);
replaceSearchersWithDifferences(currentBlock, dimensionId);
replaceSearchersWithChunkUpdate(currentBlock, dimensionId);
if(!areAllChunkSearchersDone())
return;
checkIfLimitChanged();
if(getMatchingBlocksTask == null)
startGetMatchingBlocksTask(eyesPos);
if(!getMatchingBlocksTask.isDone())
return;
if(compileVerticesTask == null)
startCompileVerticesTask();
if(!compileVerticesTask.isDone())
return;
if(!displayListUpToDate)
setDisplayListFromTask();
}
@Override
protected void onChunkAddedForHandling(ChunkPos pos, SchematicPlacement placement)
{
super.onChunkAddedForHandling(pos, placement);
this.placementsPerChunk.put(pos, placement);
}
ChunkData(SPacketChunkData packet) {
pos = new ChunkPos(packet.getChunkX(), packet.getChunkZ());
bbox =
new AxisAlignedBB(pos.getXStart(), 0, pos.getZStart(), pos.getXEnd(), 255, pos.getZEnd());
isFullChunk = packet.isFullChunk();
update(packet);
}
private void removeSearchersOutOfRange(ChunkPos center, int chunkRange)
{
for(ChunkSearcher searcher : new ArrayList<>(searchers.values()))
{
if(Math.abs(searcher.chunk.getPos().x - center.x) <= chunkRange
&& Math.abs(searcher.chunk.getPos().z - center.z) <= chunkRange)
continue;
removeSearcher(searcher);
}
}
public boolean update(){
if(ticket.getEntity() == null || ticket.getEntity().isDead) {
Log.warning("No or dead cart for chunkloading ticket found! Disposing...");
dispose();
return true;
}
ChunkPos newPos = new ChunkPos(ticket.getEntity().chunkCoordX, ticket.getEntity().chunkCoordZ);
if(!newPos.equals(curPos)) { // When the cart changed from chunk
//Select a 3x3 area centered around the cart.
Set<ChunkPos> newForced = new HashSet<>();
for(int x = newPos.x - 1; x <= newPos.x + 1; x++) {
for(int z = newPos.z - 1; z <= newPos.z + 1; z++) {
newForced.add(new ChunkPos(x, z));
}
}
//Unforce chunks we don't need anymore
curForced.stream().filter(pos -> !newForced.contains(pos)).forEach(pos -> {
ForgeChunkManager.unforceChunk(ticket, pos);
});
//Force new chunks
newForced.stream().filter(pos -> !curForced.contains(pos)).forEach(pos -> {
ForgeChunkManager.forceChunk(ticket, pos);
});
curForced = newForced;
}
return false;
}
private void removeSearchersOutOfRange(ChunkPos center, int chunkRange)
{
for(ChunkSearcher searcher : new ArrayList<>(searchers.values()))
{
if(Math.abs(searcher.chunk.getPos().x - center.x) <= chunkRange
&& Math.abs(searcher.chunk.getPos().z - center.z) <= chunkRange)
continue;
removeSearcher(searcher);
}
}
private void searchNow()
{
if(status == Status.IDLE || status == Status.DONE
|| !matchingBlocks.isEmpty())
throw new IllegalStateException();
ChunkPos chunkPos = chunk.getPos();
int minX = chunkPos.getStartX();
int minY = 0;
int minZ = chunkPos.getStartZ();
int maxX = chunkPos.getEndX();
int maxY = 255;
int maxZ = chunkPos.getEndZ();
for(int x = minX; x <= maxX; x++)
for(int y = minY; y <= maxY; y++)
for(int z = minZ; z <= maxZ; z++)
{
if(status == Status.INTERRUPTED || Thread.interrupted())
return;
BlockPos pos = new BlockPos(x, y, z);
Block block = BlockUtils.getBlock(pos);
if(!this.block.equals(block))
continue;
matchingBlocks.add(pos);
}
status = Status.DONE;
}
public static void setInstance(int chunkX, int chunkZ, PendingLightData instance) {
synchronized (instances) {
if (instance == null)
instances.remove(new ChunkPos(chunkX, chunkZ));
else
instances.put(new ChunkPos(chunkX, chunkZ), instance);
}
}
public void injectChunkIntoWorld(Chunk chunk, int x, int z, boolean putInId2ChunkMap) {
VSChunkClaim chunkClaim = parent.getOwnedChunks();
chunk.generateSkylightMap();
chunk.checkLight();
// Make sure this chunk knows we own it.
((IPhysicsChunk) chunk).setParentPhysicsObject(Optional.of(this.parent));
ChunkProviderServer provider = (ChunkProviderServer) world.getChunkProvider();
chunk.dirty = true;
claimedChunks[x - chunkClaim.minX()][z - chunkClaim.minZ()] = chunk;
if (putInId2ChunkMap) {
provider.loadedChunks.put(ChunkPos.asLong(x, z), chunk);
}
chunk.onLoad();
// We need to set these otherwise certain events like Sponge's PhaseTracker will refuse to work properly with ships!
chunk.setTerrainPopulated(true);
chunk.setLightPopulated(true);
// Inject the entry into the player chunk map.
// Sanity check first
if (!((WorldServer) world).isCallingFromMinecraftThread()) {
throw new IllegalThreadStateException("We cannot call this crap from another thread!");
}
PlayerChunkMap map = ((WorldServer) world).getPlayerChunkMap();
PlayerChunkMapEntry entry = map.getOrCreateEntry(x, z);
entry.sentToPlayers = true;
entry.players = parent.getWatchingPlayers();
}
private void queueRetrogen(String retro, World world, ChunkPos chunkCoords)
{
if (world instanceof WorldServer)
{
ListMultimap<ChunkPos, String> currentWork = pendingWork.get(world);
if (currentWork == null)
{
currentWork = ArrayListMultimap.create();
pendingWork.put(world, currentWork);
}
currentWork.put(chunkCoords, retro);
}
}
@Inject(method = "serialize", slice = @Slice(from = @At(value = "INVOKE", target = "Lnet/minecraft/entity/Entity;saveToTag(Lnet/minecraft/nbt/CompoundTag;)Z"), to = @At(value = "INVOKE", target = "Lnet/minecraft/world/chunk/ProtoChunk;getEntities()Ljava/util/List;")), at = @At(value = "JUMP", opcode = Opcodes.GOTO, ordinal = 2), locals = LocalCapture.CAPTURE_FAILHARD)
private static void serializeCapabilities(ServerWorld serverWorld, Chunk chunk, CallbackInfoReturnable<CompoundTag> callbackInfoReturnable, ChunkPos chunkPos, CompoundTag compoundTag, CompoundTag level) {
CompoundTag tag = ((CapabilityProviderHolder) chunk).serializeCaps();
if (tag != null) {
level.put("ForgeCaps", tag);
}
}
public static Set<Claim> getNearbyClaims(Location<World> location, int blockDistance) {
Set<Claim> claims = new HashSet<>();
GPClaimManager claimWorldManager = GriefPreventionPlugin.instance.dataStore.getClaimWorldManager(location.getExtent().getProperties());
if (claimWorldManager == null) {
return claims;
}
org.spongepowered.api.world.Chunk lesserChunk = location.getExtent().getChunkAtBlock(location.sub(blockDistance, 0, blockDistance).getBlockPosition()).orElse(null);
org.spongepowered.api.world.Chunk greaterChunk = location.getExtent().getChunkAtBlock(location.add(blockDistance, 0, blockDistance).getBlockPosition()).orElse(null);
if (lesserChunk != null && greaterChunk != null) {
for (int chunkX = lesserChunk.getPosition().getX(); chunkX <= greaterChunk.getPosition().getX(); chunkX++) {
for (int chunkZ = lesserChunk.getPosition().getZ(); chunkZ <= greaterChunk.getPosition().getZ(); chunkZ++) {
org.spongepowered.api.world.Chunk chunk = location.getExtent().getChunk(chunkX, 0, chunkZ).orElse(null);
if (chunk != null) {
Set<Claim> claimsInChunk = claimWorldManager.getInternalChunksToClaimsMap().get(ChunkPos.asLong(chunkX, chunkZ));
if (claimsInChunk != null) {
for (Claim claim : claimsInChunk) {
final GPClaim gpClaim = (GPClaim) claim;
if (gpClaim.parent == null && !claims.contains(claim)) {
claims.add(claim);
}
}
}
}
}
}
}
return claims;
}
@Inject(method = "sendWatchPackets", at = @At("HEAD"))
private void fireWatchEvents(ServerPlayerEntity player, ChunkPos pos, Packet<?>[] packets, boolean withinMaxWatchDistance, boolean withinViewDistance, CallbackInfo callback) {
if (withinViewDistance && !withinMaxWatchDistance) {
ChunkWatchEvent.Watch event = new ChunkWatchEvent.Watch(player, pos, world);
MinecraftForge.EVENT_BUS.post(event);
}
}
@SubscribeEvent
public void tickEnd(TickEvent.WorldTickEvent event) {
if (event.side != Side.SERVER) {
return;
}
if (event.phase == TickEvent.Phase.END) {
World world = event.world;
int dim = world.provider.getDimension();
ArrayDeque<ChunkPos> chunks = chunksToGen.get(dim);
if (chunks != null && !chunks.isEmpty()) {
ChunkPos c = chunks.pollFirst();
long worldSeed = world.getSeed();
Random rand = new Random(worldSeed);
long xSeed = rand.nextLong() >> 2 + 1L;
long zSeed = rand.nextLong() >> 2 + 1L;
rand.setSeed(xSeed * c.x + zSeed * c.z ^ worldSeed);
OreGenerator.instance.generateWorld(rand, c.x, c.z, world, false);
chunksToGen.put(dim, chunks);
} else if (chunks != null) {
chunksToGen.remove(dim);
}
}
}
@Override
public void onChunkGenerated(ServerWorld world, Chunk chunk)
{
handler.call( () ->
{
ChunkPos pos = chunk.getPos();
return Arrays.asList(
((c, t) -> new NumericValue(pos.x << 4)),
((c, t) -> new NumericValue(pos.z << 4))
);
}, () -> CarpetServer.minecraft_server.getCommandSource().withWorld(world)
);
}
public static void changeSpawnSize(int size)
{
ServerWorld overworld = CarpetServer.minecraft_server.getWorld(DimensionType.OVERWORLD);
if (overworld != null) {
ChunkPos centerChunk = new ChunkPos(new BlockPos(
overworld.getLevelProperties().getSpawnX(),
overworld.getLevelProperties().getSpawnY(),
overworld.getLevelProperties().getSpawnZ()
));
SpawnChunks.changeSpawnChunks(overworld.getChunkManager(), centerChunk, size);
}
}