001 package net.minecraftforge.common; 002 003 import java.io.DataInputStream; 004 import java.io.File; 005 import java.io.FileInputStream; 006 import java.io.IOException; 007 import java.util.HashSet; 008 import java.util.LinkedHashSet; 009 import java.util.LinkedList; 010 import java.util.List; 011 import java.util.Map; 012 import java.util.Set; 013 import java.util.UUID; 014 import java.util.logging.Level; 015 016 import com.google.common.cache.Cache; 017 import com.google.common.cache.CacheBuilder; 018 import com.google.common.collect.ArrayListMultimap; 019 import com.google.common.collect.BiMap; 020 import com.google.common.collect.HashBiMap; 021 import com.google.common.collect.HashMultimap; 022 import com.google.common.collect.ImmutableList; 023 import com.google.common.collect.ImmutableSet; 024 import com.google.common.collect.ImmutableSetMultimap; 025 import com.google.common.collect.LinkedHashMultimap; 026 import com.google.common.collect.ListMultimap; 027 import com.google.common.collect.Lists; 028 import com.google.common.collect.MapMaker; 029 import com.google.common.collect.Maps; 030 import com.google.common.collect.Multimap; 031 import com.google.common.collect.Multiset; 032 import com.google.common.collect.SetMultimap; 033 import com.google.common.collect.Sets; 034 import com.google.common.collect.TreeMultiset; 035 036 import cpw.mods.fml.common.FMLLog; 037 import cpw.mods.fml.common.Loader; 038 import cpw.mods.fml.common.ModContainer; 039 040 import net.minecraft.src.Chunk; 041 import net.minecraft.src.ChunkCoordIntPair; 042 import net.minecraft.src.CompressedStreamTools; 043 import net.minecraft.src.Entity; 044 import net.minecraft.src.EntityPlayer; 045 import net.minecraft.src.MathHelper; 046 import net.minecraft.src.NBTBase; 047 import net.minecraft.src.NBTTagCompound; 048 import net.minecraft.src.NBTTagList; 049 import net.minecraft.src.World; 050 import net.minecraft.src.WorldServer; 051 import net.minecraftforge.common.ForgeChunkManager.Ticket; 052 053 /** 054 * Manages chunkloading for mods. 055 * 056 * The basic principle is a ticket based system. 057 * 1. Mods register a callback {@link #setForcedChunkLoadingCallback(Object, LoadingCallback)} 058 * 2. Mods ask for a ticket {@link #requestTicket(Object, World, Type)} and then hold on to that ticket. 059 * 3. Mods request chunks to stay loaded {@link #forceChunk(Ticket, ChunkCoordIntPair)} or remove chunks from force loading {@link #unforceChunk(Ticket, ChunkCoordIntPair)}. 060 * 4. When a world unloads, the tickets associated with that world are saved by the chunk manager. 061 * 5. When a world loads, saved tickets are offered to the mods associated with the tickets. The {@link Ticket#getModData()} that is set by the mod should be used to re-register 062 * chunks to stay loaded (and maybe take other actions). 063 * 064 * The chunkloading is configurable at runtime. The file "config/forgeChunkLoading.cfg" contains both default configuration for chunkloading, and a sample individual mod 065 * specific override section. 066 * 067 * @author cpw 068 * 069 */ 070 public class ForgeChunkManager 071 { 072 private static int defaultMaxCount; 073 private static int defaultMaxChunks; 074 private static boolean overridesEnabled; 075 076 private static Map<World, Multimap<String, Ticket>> tickets = new MapMaker().weakKeys().makeMap(); 077 private static Map<String, Integer> ticketConstraints = Maps.newHashMap(); 078 private static Map<String, Integer> chunkConstraints = Maps.newHashMap(); 079 080 private static SetMultimap<String, Ticket> playerTickets = HashMultimap.create(); 081 082 private static Map<String, LoadingCallback> callbacks = Maps.newHashMap(); 083 084 private static Map<World, SetMultimap<ChunkCoordIntPair,Ticket>> forcedChunks = new MapMaker().weakKeys().makeMap(); 085 private static BiMap<UUID,Ticket> pendingEntities = HashBiMap.create(); 086 087 private static Map<World,Cache<Long, Chunk>> dormantChunkCache = new MapMaker().weakKeys().makeMap(); 088 089 private static File cfgFile; 090 private static Configuration config; 091 private static int playerTicketLength; 092 private static int dormantChunkCacheSize; 093 /** 094 * All mods requiring chunkloading need to implement this to handle the 095 * re-registration of chunk tickets at world loading time 096 * 097 * @author cpw 098 * 099 */ 100 public interface LoadingCallback 101 { 102 /** 103 * Called back when tickets are loaded from the world to allow the 104 * mod to re-register the chunks associated with those tickets. The list supplied 105 * here is truncated to length prior to use. Tickets unwanted by the 106 * mod must be disposed of manually unless the mod is an OrderedLoadingCallback instance 107 * in which case, they will have been disposed of by the earlier callback. 108 * 109 * @param tickets The tickets to re-register. The list is immutable and cannot be manipulated directly. Copy it first. 110 * @param world the world 111 */ 112 public void ticketsLoaded(List<Ticket> tickets, World world); 113 } 114 115 /** 116 * This is a special LoadingCallback that can be implemented as well as the 117 * LoadingCallback to provide access to additional behaviour. 118 * Specifically, this callback will fire prior to Forge dropping excess 119 * tickets. Tickets in the returned list are presumed ordered and excess will 120 * be truncated from the returned list. 121 * This allows the mod to control not only if they actually <em>want</em> a ticket but 122 * also their preferred ticket ordering. 123 * 124 * @author cpw 125 * 126 */ 127 public interface OrderedLoadingCallback extends LoadingCallback 128 { 129 /** 130 * Called back when tickets are loaded from the world to allow the 131 * mod to decide if it wants the ticket still, and prioritise overflow 132 * based on the ticket count. 133 * WARNING: You cannot force chunks in this callback, it is strictly for allowing the mod 134 * to be more selective in which tickets it wishes to preserve in an overflow situation 135 * 136 * @param tickets The tickets that you will want to select from. The list is immutable and cannot be manipulated directly. Copy it first. 137 * @param world The world 138 * @param maxTicketCount The maximum number of tickets that will be allowed. 139 * @return A list of the tickets this mod wishes to continue using. This list will be truncated 140 * to "maxTicketCount" size after the call returns and then offered to the other callback 141 * method 142 */ 143 public List<Ticket> ticketsLoaded(List<Ticket> tickets, World world, int maxTicketCount); 144 } 145 public enum Type 146 { 147 148 /** 149 * For non-entity registrations 150 */ 151 NORMAL, 152 /** 153 * For entity registrations 154 */ 155 ENTITY 156 } 157 public static class Ticket 158 { 159 private String modId; 160 private Type ticketType; 161 private LinkedHashSet<ChunkCoordIntPair> requestedChunks; 162 private NBTTagCompound modData; 163 private World world; 164 private int maxDepth; 165 private String entityClazz; 166 private int entityChunkX; 167 private int entityChunkZ; 168 private Entity entity; 169 private String player; 170 171 Ticket(String modId, Type type, World world) 172 { 173 this.modId = modId; 174 this.ticketType = type; 175 this.world = world; 176 this.maxDepth = getMaxChunkDepthFor(modId); 177 this.requestedChunks = Sets.newLinkedHashSet(); 178 } 179 180 Ticket(String modId, Type type, World world, EntityPlayer player) 181 { 182 this(modId, type, world); 183 if (player != null) 184 { 185 this.player = player.getEntityName(); 186 } 187 else 188 { 189 FMLLog.log(Level.SEVERE, "Attempt to create a player ticket without a valid player"); 190 throw new RuntimeException(); 191 } 192 } 193 /** 194 * The chunk list depth can be manipulated up to the maximal grant allowed for the mod. This value is configurable. Once the maximum is reached, 195 * the least recently forced chunk, by original registration time, is removed from the forced chunk list. 196 * 197 * @param depth The new depth to set 198 */ 199 public void setChunkListDepth(int depth) 200 { 201 if (depth > getMaxChunkDepthFor(modId) || (depth <= 0 && getMaxChunkDepthFor(modId) > 0)) 202 { 203 FMLLog.warning("The mod %s tried to modify the chunk ticket depth to: %d, its allowed maximum is: %d", modId, depth, getMaxChunkDepthFor(modId)); 204 } 205 else 206 { 207 this.maxDepth = depth; 208 } 209 } 210 211 /** 212 * Gets the current max depth for this ticket. 213 * Should be the same as getMaxChunkListDepth() 214 * unless setChunkListDepth has been called. 215 * 216 * @return Current max depth 217 */ 218 public int getChunkListDepth() 219 { 220 return maxDepth; 221 } 222 223 /** 224 * Get the maximum chunk depth size 225 * 226 * @return The maximum chunk depth size 227 */ 228 public int getMaxChunkListDepth() 229 { 230 return getMaxChunkDepthFor(modId); 231 } 232 233 /** 234 * Bind the entity to the ticket for {@link Type#ENTITY} type tickets. Other types will throw a runtime exception. 235 * 236 * @param entity The entity to bind 237 */ 238 public void bindEntity(Entity entity) 239 { 240 if (ticketType!=Type.ENTITY) 241 { 242 throw new RuntimeException("Cannot bind an entity to a non-entity ticket"); 243 } 244 this.entity = entity; 245 } 246 247 /** 248 * Retrieve the {@link NBTTagCompound} that stores mod specific data for the chunk ticket. 249 * Example data to store would be a TileEntity or Block location. This is persisted with the ticket and 250 * provided to the {@link LoadingCallback} for the mod. It is recommended to use this to recover 251 * useful state information for the forced chunks. 252 * 253 * @return The custom compound tag for mods to store additional chunkloading data 254 */ 255 public NBTTagCompound getModData() 256 { 257 if (this.modData == null) 258 { 259 this.modData = new NBTTagCompound(); 260 } 261 return modData; 262 } 263 264 /** 265 * Get the entity associated with this {@link Type#ENTITY} type ticket 266 * @return 267 */ 268 public Entity getEntity() 269 { 270 return entity; 271 } 272 273 /** 274 * Is this a player associated ticket rather than a mod associated ticket? 275 */ 276 public boolean isPlayerTicket() 277 { 278 return player != null; 279 } 280 281 /** 282 * Get the player associated with this ticket 283 */ 284 public String getPlayerName() 285 { 286 return player; 287 } 288 289 /** 290 * Get the associated mod id 291 */ 292 public String getModId() 293 { 294 return modId; 295 } 296 297 /** 298 * Gets the ticket type 299 */ 300 public Type getType() 301 { 302 return ticketType; 303 } 304 305 /** 306 * Gets a list of requested chunks for this ticket. 307 */ 308 public ImmutableSet getChunkList() 309 { 310 return ImmutableSet.copyOf(requestedChunks); 311 } 312 } 313 314 static void loadWorld(World world) 315 { 316 ArrayListMultimap<String, Ticket> newTickets = ArrayListMultimap.<String, Ticket>create(); 317 tickets.put(world, newTickets); 318 319 SetMultimap<ChunkCoordIntPair,Ticket> forcedChunkMap = LinkedHashMultimap.create(); 320 forcedChunks.put(world, forcedChunkMap); 321 322 if (!(world instanceof WorldServer)) 323 { 324 return; 325 } 326 327 dormantChunkCache.put(world, CacheBuilder.newBuilder().maximumSize(dormantChunkCacheSize).<Long, Chunk>build()); 328 WorldServer worldServer = (WorldServer) world; 329 File chunkDir = worldServer.getChunkSaveLocation(); 330 File chunkLoaderData = new File(chunkDir, "forcedchunks.dat"); 331 332 if (chunkLoaderData.exists() && chunkLoaderData.isFile()) 333 { 334 ArrayListMultimap<String, Ticket> loadedTickets = ArrayListMultimap.<String, Ticket>create(); 335 ArrayListMultimap<String, Ticket> playerLoadedTickets = ArrayListMultimap.<String, Ticket>create(); 336 NBTTagCompound forcedChunkData; 337 try 338 { 339 forcedChunkData = CompressedStreamTools.read(chunkLoaderData); 340 } 341 catch (IOException e) 342 { 343 FMLLog.log(Level.WARNING, e, "Unable to read forced chunk data at %s - it will be ignored", chunkLoaderData.getAbsolutePath()); 344 return; 345 } 346 NBTTagList ticketList = forcedChunkData.getTagList("TicketList"); 347 for (int i = 0; i < ticketList.tagCount(); i++) 348 { 349 NBTTagCompound ticketHolder = (NBTTagCompound) ticketList.tagAt(i); 350 String modId = ticketHolder.getString("Owner"); 351 boolean isPlayer = "Forge".equals(modId); 352 353 if (!isPlayer && !Loader.isModLoaded(modId)) 354 { 355 FMLLog.warning("Found chunkloading data for mod %s which is currently not available or active - it will be removed from the world save", modId); 356 continue; 357 } 358 359 if (!isPlayer && !callbacks.containsKey(modId)) 360 { 361 FMLLog.warning("The mod %s has registered persistent chunkloading data but doesn't seem to want to be called back with it - it will be removed from the world save", modId); 362 continue; 363 } 364 365 NBTTagList tickets = ticketHolder.getTagList("Tickets"); 366 for (int j = 0; j < tickets.tagCount(); j++) 367 { 368 NBTTagCompound ticket = (NBTTagCompound) tickets.tagAt(j); 369 modId = ticket.hasKey("ModId") ? ticket.getString("ModId") : modId; 370 Type type = Type.values()[ticket.getByte("Type")]; 371 byte ticketChunkDepth = ticket.getByte("ChunkListDepth"); 372 Ticket tick = new Ticket(modId, type, world); 373 if (ticket.hasKey("ModData")) 374 { 375 tick.modData = ticket.getCompoundTag("ModData"); 376 } 377 if (ticket.hasKey("Player")) 378 { 379 tick.player = ticket.getString("Player"); 380 playerLoadedTickets.put(tick.modId, tick); 381 playerTickets.put(tick.player, tick); 382 } 383 else 384 { 385 loadedTickets.put(modId, tick); 386 } 387 if (type == Type.ENTITY) 388 { 389 tick.entityChunkX = ticket.getInteger("chunkX"); 390 tick.entityChunkZ = ticket.getInteger("chunkZ"); 391 UUID uuid = new UUID(ticket.getLong("PersistentIDMSB"), ticket.getLong("PersistentIDLSB")); 392 // add the ticket to the "pending entity" list 393 pendingEntities.put(uuid, tick); 394 } 395 } 396 } 397 398 for (Ticket tick : ImmutableSet.copyOf(pendingEntities.values())) 399 { 400 if (tick.ticketType == Type.ENTITY && tick.entity == null) 401 { 402 // force the world to load the entity's chunk 403 // the load will come back through the loadEntity method and attach the entity 404 // to the ticket 405 world.getChunkFromChunkCoords(tick.entityChunkX, tick.entityChunkZ); 406 } 407 } 408 for (Ticket tick : ImmutableSet.copyOf(pendingEntities.values())) 409 { 410 if (tick.ticketType == Type.ENTITY && tick.entity == null) 411 { 412 FMLLog.warning("Failed to load persistent chunkloading entity %s from store.", pendingEntities.inverse().get(tick)); 413 loadedTickets.remove(tick.modId, tick); 414 } 415 } 416 pendingEntities.clear(); 417 // send callbacks 418 for (String modId : loadedTickets.keySet()) 419 { 420 LoadingCallback loadingCallback = callbacks.get(modId); 421 int maxTicketLength = getMaxTicketLengthFor(modId); 422 List<Ticket> tickets = loadedTickets.get(modId); 423 if (loadingCallback instanceof OrderedLoadingCallback) 424 { 425 OrderedLoadingCallback orderedLoadingCallback = (OrderedLoadingCallback) loadingCallback; 426 tickets = orderedLoadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world, maxTicketLength); 427 } 428 if (tickets.size() > maxTicketLength) 429 { 430 FMLLog.warning("The mod %s has too many open chunkloading tickets %d. Excess will be dropped", modId, tickets.size()); 431 tickets.subList(maxTicketLength, tickets.size()).clear(); 432 } 433 ForgeChunkManager.tickets.get(world).putAll(modId, tickets); 434 loadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world); 435 } 436 for (String modId : playerLoadedTickets.keySet()) 437 { 438 LoadingCallback loadingCallback = callbacks.get(modId); 439 List<Ticket> tickets = playerLoadedTickets.get(modId); 440 ForgeChunkManager.tickets.get(world).putAll("Forge", tickets); 441 loadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world); 442 } 443 } 444 } 445 446 /** 447 * Set a chunkloading callback for the supplied mod object 448 * 449 * @param mod The mod instance registering the callback 450 * @param callback The code to call back when forced chunks are loaded 451 */ 452 public static void setForcedChunkLoadingCallback(Object mod, LoadingCallback callback) 453 { 454 ModContainer container = getContainer(mod); 455 if (container == null) 456 { 457 FMLLog.warning("Unable to register a callback for an unknown mod %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod)); 458 return; 459 } 460 461 callbacks.put(container.getModId(), callback); 462 } 463 464 /** 465 * Discover the available tickets for the mod in the world 466 * 467 * @param mod The mod that will own the tickets 468 * @param world The world 469 * @return The count of tickets left for the mod in the supplied world 470 */ 471 public static int ticketCountAvailableFor(Object mod, World world) 472 { 473 ModContainer container = getContainer(mod); 474 if (container!=null) 475 { 476 String modId = container.getModId(); 477 int allowedCount = getMaxTicketLengthFor(modId); 478 return allowedCount - tickets.get(world).get(modId).size(); 479 } 480 else 481 { 482 return 0; 483 } 484 } 485 486 private static ModContainer getContainer(Object mod) 487 { 488 ModContainer container = Loader.instance().getModObjectList().inverse().get(mod); 489 return container; 490 } 491 492 private static int getMaxTicketLengthFor(String modId) 493 { 494 int allowedCount = ticketConstraints.containsKey(modId) && overridesEnabled ? ticketConstraints.get(modId) : defaultMaxCount; 495 return allowedCount; 496 } 497 498 private static int getMaxChunkDepthFor(String modId) 499 { 500 int allowedCount = chunkConstraints.containsKey(modId) && overridesEnabled ? chunkConstraints.get(modId) : defaultMaxChunks; 501 return allowedCount; 502 } 503 504 public static Ticket requestPlayerTicket(Object mod, EntityPlayer player, World world, Type type) 505 { 506 ModContainer mc = getContainer(mod); 507 if (mc == null) 508 { 509 FMLLog.log(Level.SEVERE, "Failed to locate the container for mod instance %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod)); 510 return null; 511 } 512 if (playerTickets.get(player.getEntityName()).size()>playerTicketLength) 513 { 514 FMLLog.warning("Unable to assign further chunkloading tickets to player %s (on behalf of mod %s)", player.getEntityName(), mc.getModId()); 515 return null; 516 } 517 Ticket ticket = new Ticket(mc.getModId(),type,world,player); 518 playerTickets.put(player.getEntityName(), ticket); 519 tickets.get(world).put("Forge", ticket); 520 return ticket; 521 } 522 /** 523 * Request a chunkloading ticket of the appropriate type for the supplied mod 524 * 525 * @param mod The mod requesting a ticket 526 * @param world The world in which it is requesting the ticket 527 * @param type The type of ticket 528 * @return A ticket with which to register chunks for loading, or null if no further tickets are available 529 */ 530 public static Ticket requestTicket(Object mod, World world, Type type) 531 { 532 ModContainer container = getContainer(mod); 533 if (container == null) 534 { 535 FMLLog.log(Level.SEVERE, "Failed to locate the container for mod instance %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod)); 536 return null; 537 } 538 String modId = container.getModId(); 539 if (!callbacks.containsKey(modId)) 540 { 541 FMLLog.severe("The mod %s has attempted to request a ticket without a listener in place", modId); 542 throw new RuntimeException("Invalid ticket request"); 543 } 544 545 int allowedCount = ticketConstraints.containsKey(modId) ? ticketConstraints.get(modId) : defaultMaxCount; 546 547 if (tickets.get(world).get(modId).size() >= allowedCount) 548 { 549 FMLLog.info("The mod %s has attempted to allocate a chunkloading ticket beyond it's currently allocated maximum : %d", modId, allowedCount); 550 return null; 551 } 552 Ticket ticket = new Ticket(modId, type, world); 553 tickets.get(world).put(modId, ticket); 554 555 return ticket; 556 } 557 558 /** 559 * Release the ticket back to the system. This will also unforce any chunks held by the ticket so that they can be unloaded and/or stop ticking. 560 * 561 * @param ticket The ticket to release 562 */ 563 public static void releaseTicket(Ticket ticket) 564 { 565 if (ticket == null) 566 { 567 return; 568 } 569 if (ticket.isPlayerTicket() ? !playerTickets.containsValue(ticket) : !tickets.get(ticket.world).containsEntry(ticket.modId, ticket)) 570 { 571 return; 572 } 573 if (ticket.requestedChunks!=null) 574 { 575 for (ChunkCoordIntPair chunk : ImmutableSet.copyOf(ticket.requestedChunks)) 576 { 577 unforceChunk(ticket, chunk); 578 } 579 } 580 if (ticket.isPlayerTicket()) 581 { 582 playerTickets.remove(ticket.player, ticket); 583 tickets.get(ticket.world).remove("Forge",ticket); 584 } 585 else 586 { 587 tickets.get(ticket.world).remove(ticket.modId, ticket); 588 } 589 } 590 591 /** 592 * Force the supplied chunk coordinate to be loaded by the supplied ticket. If the ticket's {@link Ticket#maxDepth} is exceeded, the least 593 * recently registered chunk is unforced and may be unloaded. 594 * It is safe to force the chunk several times for a ticket, it will not generate duplication or change the ordering. 595 * 596 * @param ticket The ticket registering the chunk 597 * @param chunk The chunk to force 598 */ 599 public static void forceChunk(Ticket ticket, ChunkCoordIntPair chunk) 600 { 601 if (ticket == null || chunk == null) 602 { 603 return; 604 } 605 if (ticket.ticketType == Type.ENTITY && ticket.entity == null) 606 { 607 throw new RuntimeException("Attempted to use an entity ticket to force a chunk, without an entity"); 608 } 609 if (ticket.isPlayerTicket() ? !playerTickets.containsValue(ticket) : !tickets.get(ticket.world).containsEntry(ticket.modId, ticket)) 610 { 611 FMLLog.severe("The mod %s attempted to force load a chunk with an invalid ticket. This is not permitted.", ticket.modId); 612 return; 613 } 614 ticket.requestedChunks.add(chunk); 615 forcedChunks.get(ticket.world).put(chunk, ticket); 616 if (ticket.maxDepth > 0 && ticket.requestedChunks.size() > ticket.maxDepth) 617 { 618 ChunkCoordIntPair removed = ticket.requestedChunks.iterator().next(); 619 unforceChunk(ticket,removed); 620 } 621 } 622 623 /** 624 * Reorganize the internal chunk list so that the chunk supplied is at the *end* of the list 625 * This helps if you wish to guarantee a certain "automatic unload ordering" for the chunks 626 * in the ticket list 627 * 628 * @param ticket The ticket holding the chunk list 629 * @param chunk The chunk you wish to push to the end (so that it would be unloaded last) 630 */ 631 public static void reorderChunk(Ticket ticket, ChunkCoordIntPair chunk) 632 { 633 if (ticket == null || chunk == null || !ticket.requestedChunks.contains(chunk)) 634 { 635 return; 636 } 637 ticket.requestedChunks.remove(chunk); 638 ticket.requestedChunks.add(chunk); 639 } 640 /** 641 * Unforce the supplied chunk, allowing it to be unloaded and stop ticking. 642 * 643 * @param ticket The ticket holding the chunk 644 * @param chunk The chunk to unforce 645 */ 646 public static void unforceChunk(Ticket ticket, ChunkCoordIntPair chunk) 647 { 648 if (ticket == null || chunk == null) 649 { 650 return; 651 } 652 ticket.requestedChunks.remove(chunk); 653 forcedChunks.get(ticket.world).remove(chunk, ticket); 654 } 655 656 static void loadConfiguration() 657 { 658 for (String mod : config.categories.keySet()) 659 { 660 if (mod.equals("Forge") || mod.equals("defaults")) 661 { 662 continue; 663 } 664 Property modTC = config.get(mod, "maximumTicketCount", 200); 665 Property modCPT = config.get(mod, "maximumChunksPerTicket", 25); 666 ticketConstraints.put(mod, modTC.getInt(200)); 667 chunkConstraints.put(mod, modCPT.getInt(25)); 668 } 669 config.save(); 670 } 671 672 /** 673 * The list of persistent chunks in the world. This set is immutable. 674 * @param world 675 * @return 676 */ 677 public static SetMultimap<ChunkCoordIntPair, Ticket> getPersistentChunksFor(World world) 678 { 679 return forcedChunks.containsKey(world) ? ImmutableSetMultimap.copyOf(forcedChunks.get(world)) : ImmutableSetMultimap.<ChunkCoordIntPair,Ticket>of(); 680 } 681 682 static void saveWorld(World world) 683 { 684 // only persist persistent worlds 685 if (!(world instanceof WorldServer)) { return; } 686 WorldServer worldServer = (WorldServer) world; 687 File chunkDir = worldServer.getChunkSaveLocation(); 688 File chunkLoaderData = new File(chunkDir, "forcedchunks.dat"); 689 690 NBTTagCompound forcedChunkData = new NBTTagCompound(); 691 NBTTagList ticketList = new NBTTagList(); 692 forcedChunkData.setTag("TicketList", ticketList); 693 694 Multimap<String, Ticket> ticketSet = tickets.get(worldServer); 695 for (String modId : ticketSet.keySet()) 696 { 697 NBTTagCompound ticketHolder = new NBTTagCompound(); 698 ticketList.appendTag(ticketHolder); 699 700 ticketHolder.setString("Owner", modId); 701 NBTTagList tickets = new NBTTagList(); 702 ticketHolder.setTag("Tickets", tickets); 703 704 for (Ticket tick : ticketSet.get(modId)) 705 { 706 NBTTagCompound ticket = new NBTTagCompound(); 707 ticket.setByte("Type", (byte) tick.ticketType.ordinal()); 708 ticket.setByte("ChunkListDepth", (byte) tick.maxDepth); 709 if (tick.isPlayerTicket()) 710 { 711 ticket.setString("ModId", tick.modId); 712 ticket.setString("Player", tick.player); 713 } 714 if (tick.modData != null) 715 { 716 ticket.setCompoundTag("ModData", tick.modData); 717 } 718 if (tick.ticketType == Type.ENTITY && tick.entity != null) 719 { 720 ticket.setInteger("chunkX", MathHelper.floor_double(tick.entity.chunkCoordX)); 721 ticket.setInteger("chunkZ", MathHelper.floor_double(tick.entity.chunkCoordZ)); 722 ticket.setLong("PersistentIDMSB", tick.entity.getPersistentID().getMostSignificantBits()); 723 ticket.setLong("PersistentIDLSB", tick.entity.getPersistentID().getLeastSignificantBits()); 724 tickets.appendTag(ticket); 725 } 726 else if (tick.ticketType != Type.ENTITY) 727 { 728 tickets.appendTag(ticket); 729 } 730 } 731 } 732 try 733 { 734 CompressedStreamTools.write(forcedChunkData, chunkLoaderData); 735 } 736 catch (IOException e) 737 { 738 FMLLog.log(Level.WARNING, e, "Unable to write forced chunk data to %s - chunkloading won't work", chunkLoaderData.getAbsolutePath()); 739 return; 740 } 741 } 742 743 static void loadEntity(Entity entity) 744 { 745 UUID id = entity.getPersistentID(); 746 Ticket tick = pendingEntities.get(id); 747 if (tick != null) 748 { 749 tick.bindEntity(entity); 750 pendingEntities.remove(id); 751 } 752 } 753 754 public static void putDormantChunk(long coords, Chunk chunk) 755 { 756 Cache<Long, Chunk> cache = dormantChunkCache.get(chunk.worldObj); 757 if (cache != null) 758 { 759 cache.put(coords, chunk); 760 } 761 } 762 763 public static Chunk fetchDormantChunk(long coords, World world) 764 { 765 Cache<Long, Chunk> cache = dormantChunkCache.get(world); 766 return cache == null ? null : cache.getIfPresent(coords); 767 } 768 769 static void captureConfig(File configDir) 770 { 771 cfgFile = new File(configDir,"forgeChunkLoading.cfg"); 772 config = new Configuration(cfgFile, true); 773 config.categories.clear(); 774 try 775 { 776 config.load(); 777 } 778 catch (Exception e) 779 { 780 File dest = new File(cfgFile.getParentFile(),"forgeChunkLoading.cfg.bak"); 781 if (dest.exists()) 782 { 783 dest.delete(); 784 } 785 cfgFile.renameTo(dest); 786 FMLLog.log(Level.SEVERE, e, "A critical error occured reading the forgeChunkLoading.cfg file, defaults will be used - the invalid file is backed up at forgeChunkLoading.cfg.bak"); 787 } 788 config.addCustomCategoryComment("defaults", "Default configuration for forge chunk loading control"); 789 Property maxTicketCount = config.get("defaults", "maximumTicketCount", 200); 790 maxTicketCount.comment = "The default maximum ticket count for a mod which does not have an override\n" + 791 "in this file. This is the number of chunk loading requests a mod is allowed to make."; 792 defaultMaxCount = maxTicketCount.getInt(200); 793 794 Property maxChunks = config.get("defaults", "maximumChunksPerTicket", 25); 795 maxChunks.comment = "The default maximum number of chunks a mod can force, per ticket, \n" + 796 "for a mod without an override. This is the maximum number of chunks a single ticket can force."; 797 defaultMaxChunks = maxChunks.getInt(25); 798 799 Property playerTicketCount = config.get("defaults", "playetTicketCount", 500); 800 playerTicketCount.comment = "The number of tickets a player can be assigned instead of a mod. This is shared across all mods and it is up to the mods to use it."; 801 playerTicketLength = playerTicketCount.getInt(500); 802 803 Property dormantChunkCacheSizeProperty = config.get("defaults", "dormantChunkCacheSize", 0); 804 dormantChunkCacheSizeProperty.comment = "Unloaded chunks can first be kept in a dormant cache for quicker\n" + 805 "loading times. Specify the size of that cache here"; 806 dormantChunkCacheSize = dormantChunkCacheSizeProperty.getInt(0); 807 FMLLog.info("Configured a dormant chunk cache size of %d", dormantChunkCacheSizeProperty.getInt(0)); 808 809 Property modOverridesEnabled = config.get("defaults", "enabled", true); 810 modOverridesEnabled.comment = "Are mod overrides enabled?"; 811 overridesEnabled = modOverridesEnabled.getBoolean(true); 812 813 config.addCustomCategoryComment("Forge", "Sample mod specific control section.\n" + 814 "Copy this section and rename the with the modid for the mod you wish to override.\n" + 815 "A value of zero in either entry effectively disables any chunkloading capabilities\n" + 816 "for that mod"); 817 818 Property sampleTC = config.get("Forge", "maximumTicketCount", 200); 819 sampleTC.comment = "Maximum ticket count for the mod. Zero disables chunkloading capabilities."; 820 sampleTC = config.get("Forge", "maximumChunksPerTicket", 25); 821 sampleTC.comment = "Maximum chunks per ticket for the mod."; 822 for (String mod : config.categories.keySet()) 823 { 824 if (mod.equals("Forge") || mod.equals("defaults")) 825 { 826 continue; 827 } 828 Property modTC = config.get(mod, "maximumTicketCount", 200); 829 Property modCPT = config.get(mod, "maximumChunksPerTicket", 25); 830 } 831 } 832 833 834 public static Map<String,Property> getConfigMapFor(Object mod) 835 { 836 ModContainer container = getContainer(mod); 837 if (container != null) 838 { 839 Map<String, Property> map = config.categories.get(container.getModId()); 840 if (map == null) 841 { 842 map = Maps.newHashMap(); 843 config.categories.put(container.getModId(), map); 844 } 845 return map; 846 } 847 848 return null; 849 } 850 851 public static void addConfigProperty(Object mod, String propertyName, String value, Property.Type type) 852 { 853 ModContainer container = getContainer(mod); 854 if (container != null) 855 { 856 Map<String, Property> props = config.categories.get(container.getModId()); 857 props.put(propertyName, new Property(propertyName, value, type)); 858 } 859 } 860 }