下面列出了怎么用net.minecraftforge.common.DimensionManager的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void update() {
this.handleEnergy();
if (world.getTotalWorldTime() % 20 == 0 && this.targetPos != null) {
WorldServer targetWorld = DimensionManager.getWorld(this.targetDim);
if (targetWorld == null) {
setTarget(null);
return;
}
TileEntity destination = targetWorld.getTileEntity(this.targetPos);
if (destination instanceof GTTileTesseractMaster && ((GTTileTesseractMaster) destination).getActive()) {
setTarget((GTTileTesseractMaster) destination);
return;
}
setTarget(null);
}
}
@Override
public File getWorldContainer() {
// Cauldron start - return the proper container
if (DimensionManager.getWorld(0) != null) {
return ((SaveHandler) DimensionManager.getWorld(0).getSaveHandler()).getWorldDirectory();
}
// Cauldron end
if (this.getServer().anvilFile != null) {
return this.getServer().anvilFile;
}
if (container == null) {
container = new File(configuration.getString("settings.world-container", "."));
}
return container;
}
/**
* These entities are excluded from Activation range checks.
*
* @param entity
* @return boolean If it should always tick.
*/
public static boolean initializeEntityActivationState(Entity entity, SpigotWorldConfig config) {
if (config == null && DimensionManager.getWorld(0) != null) {
config = DimensionManager.getWorld(0).spigotConfig;
} else {
return true;
}
return ((entity.activationType == 3 && config.miscActivationRange == 0)
|| (entity.activationType == 2 && config.animalActivationRange == 0)
|| (entity.activationType == 1 && config.monsterActivationRange == 0)
|| entity instanceof EntityPlayer
|| entity instanceof EntityThrowable
|| entity instanceof MultiPartEntityPart
|| entity instanceof EntityWither
|| entity instanceof EntityFireball
|| entity instanceof EntityFallingBlock
|| entity instanceof EntityWeatherEffect
|| entity instanceof EntityTNTPrimed
|| entity instanceof EntityEnderCrystal
|| entity instanceof EntityFireworkRocket
|| (entity.getClass().getSuperclass() == Entity.class && !entity.isCreatureType(EnumCreatureType.CREATURE, false))
&& !entity.isCreatureType(EnumCreatureType.AMBIENT, false) && !entity.isCreatureType(EnumCreatureType.MONSTER, false)
&& !entity.isCreatureType(EnumCreatureType.WATER_CREATURE, false)
);
}
@Override
public ForgeChunkManager.Ticket get(Object key) {
if (key instanceof Integer) {
if (super.get(key) == null) {
World world = DimensionManager.getWorld((Integer) key);
if (world == null) {
return null;
}
ForgeChunkManager.Ticket ticket = ForgeChunkManager.requestTicket(MyTown.instance, world, ForgeChunkManager.Type.NORMAL);
ticket.getModData().setString("townName", town.getName());
ticket.getModData().setTag("chunkCoords", new NBTTagList());
put((Integer) key, ticket);
return ticket;
} else {
return super.get(key);
}
}
return null;
}
/**
* Changes the orbiting body of the space object
* @param station
* @param dimId
* @param timeDelta time in ticks to fully make the jump
*/
public void moveStationToBody(ISpaceObject station, int dimId, int timeDelta) {
//Remove station from the planet it's in orbit around before moving it!
if(station.getOrbitingPlanetId() != WARPDIMID && spaceStationOrbitMap.get(station.getOrbitingPlanetId()) != null) {
spaceStationOrbitMap.get(station.getOrbitingPlanetId()).remove(station);
}
if(spaceStationOrbitMap.get(WARPDIMID) == null)
spaceStationOrbitMap.put(WARPDIMID,new LinkedList<ISpaceObject>());
if(!spaceStationOrbitMap.get(WARPDIMID).contains(station))
spaceStationOrbitMap.get(WARPDIMID).add(station);
station.setOrbitingBody(WARPDIMID);
//if(FMLCommonHandler.instance().getSide().isServer()) {
PacketHandler.sendToAll(new PacketStationUpdate(station, PacketStationUpdate.Type.ORBIT_UPDATE));
//}
AdvancedRocketry.proxy.fireFogBurst(station);
((DimensionProperties)station.getProperties()).setAtmosphereDensityDirect(0);
nextStationTransitionTick = (int)(Configuration.travelTimeMultiplier*timeDelta) + DimensionManager.getWorld(Configuration.spaceDimId).getTotalWorldTime();
station.beginTransition(nextStationTransitionTick);
}
@Override
public World convert(String worldName) throws TypeConversionException {
World[] worlds = DimensionManager.getWorlds();
Optional<World> matchingWorld = Arrays.stream(worlds)
.filter(world -> world.provider.getDimensionType().getName().equals(worldName))
.findFirst();
return matchingWorld.orElseThrow(() -> {
String validWorlds = Arrays.stream(worlds)
.map(world -> world.provider.getDimensionType().getName())
.collect(Collectors.joining(", "));
return new TypeConversionException(
String.format("Invalid world name! Available options: %s", validWorlds));
});
}
/**
* The initial nodes used to build out the network from.
* Signals, Station Markers, rail links. Only used when force rebuilding the network.
* @return
*/
private Set<MCPos> getStartNodes(){
Set<MCPos> nodes = new HashSet<>();
for(World world : DimensionManager.getWorlds()) {
for(TileEntity te : world.loadedTileEntityList) {
if(te instanceof TileEntityBase) { //Any Signals TE for testing purposes
nodes.add(new MCPos(world, te.getPos()));
for(EnumFacing facing : EnumFacing.VALUES) {
BlockPos pos = te.getPos().offset(facing);
nodes.add(new MCPos(world, pos));
}
}
}
}
return nodes;
}
@Override
public Iterable<String[]> dump(int mode) {
List<String[]> list = new LinkedList<String[]>();
List<Integer> ids = new ArrayList<Integer>();
ids.addAll(Arrays.asList(DimensionManager.getStaticDimensionIDs()));
Collections.sort(ids);
for (int id : ids) {
int providerId = DimensionManager.getProviderType(id);
Map<Integer, Class> providers = ReflectionHelper.getPrivateValue(DimensionManager.class, null, "providers");
Class providerClass = providers.get(providerId);
list.add(new String[] { String.valueOf(id), String.valueOf(providerId), providerClass.getName() });
}
return list;
}
public static WorldView createWorldView(int dimid, ChunkCoordinates spawn, int width, int height) {
if (ModConfigs.disabled) return null;
if (!DimensionManager.isDimensionRegistered(dimid)) return null;
WorldClient proxyworld = ProxyWorldManager.getProxyworld(dimid);
if (proxyworld == null) return null;
Collection<WorldView> worldviews = worldviewsets.get(dimid);
if (worldviews == null) return null;
WorldView view = new WorldView(proxyworld, spawn, width, height);
// Initialize the view rendering system
Minecraft mc = Minecraft.getMinecraft();
EntityLivingBase backup = mc.renderViewEntity;
mc.renderViewEntity = view.camera;
view.getRenderGlobal().setWorldAndLoadRenderers(proxyworld);
mc.renderViewEntity = backup;
// Inform the server of the new view
LookingGlassPacketManager.bus.sendToServer(PacketCreateView.createPacket(view));
worldviews.add(view);
return view;
}
public void initalize() {
NetworkRegistry.INSTANCE.registerGuiHandler(Gadomancy.instance, this);
MinecraftForge.EVENT_BUS.register(EVENT_HANDLER_GOLEM);
FMLCommonHandler.instance().bus().register(new EventHandlerNetwork());
EventHandlerWorld worldEventHandler = new EventHandlerWorld();
MinecraftForge.EVENT_BUS.register(worldEventHandler);
FMLCommonHandler.instance().bus().register(worldEventHandler);
MinecraftForge.EVENT_BUS.register(new EventHandlerEntity());
RegisteredEnchantments.init();
RegisteredRecipes.init();
SyncDataHolder.initialize();
ModSubstitutions.init();
RegisteredEntities.init();
DimensionManager.registerProviderType(ModConfig.dimOuterId, WorldProviderTCEldrich.class, true);
DimensionManager.registerDimension(ModConfig.dimOuterId, ModConfig.dimOuterId);
}
public MissionResourceCollection(long duration, EntityRocket entity, LinkedList<IInfrastructure> infrastructureCoords) {
super();
missionPersistantNBT = new NBTTagCompound();
entity.writeMissionPersistantNBT(missionPersistantNBT);
satelliteProperties.setId(zmaster587.advancedRocketry.dimension.DimensionManager.getInstance().getNextSatelliteId());
startWorldTime = DimensionManager.getWorld(0).getTotalWorldTime();
this.duration = duration;
this.launchDimension = entity.world.provider.getDimension();
rocketStorage = entity.storage;
rocketStats = entity.stats;
x = entity.posX;
y = entity.posY;
z = entity.posZ;
worldId = entity.world.provider.getDimension();
this.infrastructureCoords = new LinkedList<HashedBlockPosition>();
for(IInfrastructure tile : infrastructureCoords)
this.infrastructureCoords.add(new HashedBlockPosition(((TileEntity)tile).getPos()));
}
@EventHandler
public void preInit(FMLPreInitializationEvent event) {
proxy.preInit(event);
logger = event.getModLog();
TofuEntityRegister.entitySpawn();
TofuCompat.preInit();
GameRegistry.registerWorldGenerator(new TofuOreGenerator(), 0);
MapGenStructureIO.registerStructure(MapGenTofuVillage.Start.class,"TofuVillage");
StructureTofuVillagePieces.registerVillagePieces();
MapGenStructureIO.registerStructure(StructureTofuMineshaftStart.class,"TofuMineshaft");
StructureTofuMineshaftPieces.registerStructurePieces();
MapGenStructureIO.registerStructure(MapGenTofuCastle.Start.class, "TofuCastle");
TofuCastlePiece.registerTofuCastlePiece();
NetworkRegistry.INSTANCE.registerGuiHandler(this, new TofuGuiHandler());
zunda = new DamageSource("zunda") {
@Override
public ITextComponent getDeathMessage(EntityLivingBase entityLivingBaseIn) {
String s = "death.attack.zunda";
String s1 = s + ".player";
return new TextComponentString(entityLivingBaseIn.getDisplayName().getFormattedText() + " ").appendSibling(new TextComponentTranslation(s1, new Object[]{entityLivingBaseIn.getDisplayName()}));
}
}.setDamageIsAbsolute();
TOFU_DIMENSION = DimensionType.register("Tofu World", "_tofu", TofuConfig.dimensionID, WorldProviderTofu.class, false);
DimensionManager.registerDimension(TofuConfig.dimensionID, TOFU_DIMENSION);
TofuVillages.register();
}
public BaseVehicleEntity(World worldIn, Area a, BlockPos os) {
super(worldIn);
this.setSize(0.5F, 0.5F);
storage = new ShipStorage(os, worldIn);
dataManager.set(QUBE, a);
dataManager.set(OFFSET, os);
getArea().loadShipIntoStorage(DimensionManager.getWorld(StorageDimReg.storageDimensionType.getId()), this);
}
public BaseVehicleEntity(World worldIn) {
super(worldIn);
storage = new ShipStorage(getOffset(), worldIn);
Ticket tic = ForgeChunkManager.requestTicket(CommunityMod.INSTANCE,
DimensionManager.getWorld(StorageDimReg.storageDimensionType.getId()), Type.NORMAL);
loadTicket = tic;
}
@Override
public void writeSpawnData(ByteBuf buffer) {
World w = DimensionManager.getWorld(StorageDimReg.storageDimensionType.getId());
List<BlockPos> bpl = getArea().scanArea(w);
buffer.writeInt(bpl.size());
for (Entry<BlockPos, BlockStorage> e : storage.blockMap.entrySet()) {
buffer.writeLong(e.getKey().toLong());
e.getValue().toBuf(buffer);
}
setEntityBoundingBox(getEncompassingBoundingBox());
getChunksToLoad();
}
@Override
protected void readEntityFromNBT(NBTTagCompound compound) {
Area a = new Area();
a.deserialize(compound.getIntArray("qube"));
dataManager.set(QUBE, a);
int[] o = compound.getIntArray("offset");
BlockPos offset = new BlockPos(o[0], o[1], o[2]);
dataManager.set(OFFSET, offset);
getArea().loadShipIntoStorage(DimensionManager.getWorld(StorageDimReg.storageDimensionType.getId()), this);
}
private FakeWorldServer(World world) {
super(MinecraftServer.getServer(), new NonSavingHandler(), world.getWorldInfo().getWorldName(), world.provider.dimensionId,
new WorldSettings(world.getWorldInfo()), world.theProfiler);
DimensionManager.setWorld(world.provider.dimensionId, (WorldServer) world);
chunkProvider = world.getChunkProvider();
}
public void readFromNBT(NBTTagCompound nbt) {
NBTTagList list = nbt.getTagList("spaceContents", NBT.TAG_COMPOUND);
nextId = nbt.getInteger("nextInt");
nextStationTransitionTick = nbt.getLong("nextStationTransitionTick");
for(int i = 0; i < list.tagCount(); i++) {
NBTTagCompound tag = list.getCompoundTagAt(i);
try {
ISpaceObject object = (ISpaceObject)nameToClass.get(tag.getString("type")).newInstance();
object.readFromNbt(tag);
if(tag.hasKey("expireTime")) {
long expireTime = tag.getLong("expireTime");
int numPlayers = tag.getInteger("numPlayers");
if (DimensionManager.getWorld(Configuration.spaceDimId).getTotalWorldTime() >= expireTime && numPlayers == 0)
continue;
temporaryDimensions.put(object.getId(), expireTime);
temporaryDimensionPlayerNumber.put(object.getId(), numPlayers);
}
registerSpaceObject(object, object.getOrbitingPlanetId(), object.getId() );
} catch (Exception e) {
System.out.println(tag.getString("type"));
e.printStackTrace();
}
}
}
public static void readFromDisk()
{
// Clear the data structures when reading the data for a world/save, so that valid Energy Bridges
// from another world won't carry over to a world/save that doesn't have the file yet.
BRIDGE_LOCATIONS.clear();
BRIDGE_COUNTS.clear();
bridgeCountInEndDimensions = 0;
try
{
File saveDir = DimensionManager.getCurrentSaveRootDirectory();
if (saveDir == null)
{
return;
}
File file = new File(new File(saveDir, Reference.MOD_ID), "energybridges.dat");
if (file.exists() && file.isFile())
{
FileInputStream is = new FileInputStream(file);
readFromNBT(CompressedStreamTools.readCompressed(is));
is.close();
}
}
catch (Exception e)
{
EnderUtilities.logger.warn("Failed to read Energy Bridge data from file!", e);
}
}
@SuppressWarnings("unchecked")
public static void cleanChunks(WorldServer world) {
int dim = CommonUtils.getDimension(world);
int viewdist = ServerUtils.mc().getConfigurationManager().getViewDistance();
HashSet<ChunkCoordIntPair> loadedChunks = new HashSet<ChunkCoordIntPair>();
for (EntityPlayer player : ServerUtils.getPlayersInDimension(dim)) {
int playerChunkX = (int) player.posX >> 4;
int playerChunkZ = (int) player.posZ >> 4;
for (int cx = playerChunkX - viewdist; cx <= playerChunkX + viewdist; cx++)
for (int cz = playerChunkZ - viewdist; cz <= playerChunkZ + viewdist; cz++)
loadedChunks.add(new ChunkCoordIntPair(cx, cz));
}
ImmutableSetMultimap<ChunkCoordIntPair, Ticket> persistantChunks = world.getPersistentChunks();
PlayerManager manager = world.getPlayerManager();
for (Chunk chunk : (List<Chunk>) world.theChunkProviderServer.loadedChunks) {
ChunkCoordIntPair coord = chunk.getChunkCoordIntPair();
if (!loadedChunks.contains(coord) && !persistantChunks.containsKey(coord) && world.theChunkProviderServer.chunkExists(coord.chunkXPos, coord.chunkZPos)) {
PlayerInstance instance = manager.getOrCreateChunkWatcher(coord.chunkXPos, coord.chunkZPos, false);
if (instance == null) {
world.theChunkProviderServer.unloadChunksIfNotNearSpawn(coord.chunkXPos, coord.chunkZPos);
} else {
while (instance.playersWatchingChunk.size() > 0)
instance.removePlayer((EntityPlayerMP) instance.playersWatchingChunk.get(0));
}
}
}
if (ServerUtils.getPlayersInDimension(dim).isEmpty() && world.getPersistentChunks().isEmpty() && !DimensionManager.shouldLoadSpawn(dim)) {
DimensionManager.unloadWorld(dim);
}
}
public boolean add(int id) {
try {
return add(DimensionManager.getProviderType(id));
} catch (Exception e) {
// will throw exception if id does not exist
return false;
}
}
public boolean remove(int id) {
try {
return remove(DimensionManager.getProviderType(id));
} catch (Exception e) {
return false; // will throw exception if id does not exist
}
}
private static void saveWorld(int dim) {
try {
File file = new File(getSaveDir(DimensionManager.getWorld(dim)), "world.dat");
NEIServerUtils.writeNBT(dimTags.get(dim), file);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Arena(int worldID, BlockPos center, double radius, double height, int bossID, Set<UUID> players) {
this.worldID = worldID;
this.world = DimensionManager.getWorld(worldID);
this.boss = (EntityAngel) world.getEntityByID(bossID);
this.center = center;
this.radius = radius;
this.height = height;
this.bossID = bossID;
this.players = players;
}
@Override
public IMessage onMessage(UpdateHudColorPacket message, MessageContext ctx)
{
EntityPlayerMP player = ctx.getServerHandler().playerEntity;
DimensionManager.getWorld(player.worldObj.provider.getDimension()).addScheduledTask(new DoSync(message.color, player));
return null;
}
public PlayerChunkViewerTracker(EntityPlayer player, PlayerChunkViewerManager manager)
{
owner = player;
this.manager = manager;
PacketCustom packet = new PacketCustom(ChunkLoaderSPH.channel, 1);
packet.sendToPlayer(player);
for(WorldServer world : DimensionManager.getWorlds())
loadDimension(world);
}
public static void load(World world) {
if (MinecraftServer.getServer() != server) {
logger.debug("Loading NEI Server");
server = MinecraftServer.getServer();
saveDir = new File(DimensionManager.getCurrentSaveRootDirectory(), "NEI");
dimTags.clear();
loadConfig();
loadBannedItems();
}
loadWorld(world);
}
@Override
public IMessage onMessage(SyncHotkeyPacket message, MessageContext ctx)
{
EntityPlayerMP player = ctx.getServerHandler().playerEntity;
DimensionManager.getWorld(player.worldObj.provider.getDimension()).addScheduledTask(new DoSync(message.selectedPart, message.key, player));
return null;
}
@Override
public IMessage onMessage(SurgeryRemovePacket message, MessageContext ctx)
{
DimensionManager.getWorld(message.dimensionId).addScheduledTask(new DoSync(message.pos, message.dimensionId, message.slotNumber, message.isNull));
return null;
}
@Override
public void run()
{
World world = DimensionManager.getWorld(dimensionId);
TileEntity te = world.getTileEntity(pos);
if (te instanceof TileEntitySurgery)
{
TileEntitySurgery surgery = (TileEntitySurgery) te;
surgery.discardSlots[slotNumber] = isNull;
if (isNull)
{
surgery.disableDependants(surgery.slotsPlayer.getStackInSlot(slotNumber),
EnumSlot.values()[slotNumber / 10], slotNumber % LibConstants.WARE_PER_SLOT);
}
else
{
surgery.enableDependsOn(surgery.slotsPlayer.getStackInSlot(slotNumber),
EnumSlot.values()[slotNumber / 10], slotNumber % LibConstants.WARE_PER_SLOT);
}
surgery.updateEssential(EnumSlot.values()[slotNumber / LibConstants.WARE_PER_SLOT]);
surgery.updateEssence();
}
}