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