001    package net.minecraft.src;
002    
003    import java.io.IOException;
004    import java.util.ArrayList;
005    import java.util.HashSet;
006    import java.util.Iterator;
007    import java.util.List;
008    import java.util.Set;
009    
010    import net.minecraftforge.common.DimensionManager;
011    import net.minecraftforge.common.ForgeChunkManager;
012    
013    import cpw.mods.fml.common.registry.GameRegistry;
014    
015    public class ChunkProviderServer implements IChunkProvider
016    {
017        /**
018         * used by unload100OldestChunks to iterate the loadedChunkHashMap for unload (underlying assumption, first in,
019         * first out)
020         */
021        private Set chunksToUnload = new HashSet();
022        private Chunk defaultEmptyChunk;
023        private IChunkProvider currentChunkProvider;
024        IChunkLoader currentChunkLoader;
025    
026        /**
027         * if this is false, the defaultEmptyChunk will be returned by the provider
028         */
029        public boolean loadChunkOnProvideRequest = true;
030        private LongHashMap loadedChunkHashMap = new LongHashMap();
031        private List loadedChunks = new ArrayList();
032        private WorldServer currentServer;
033    
034        public ChunkProviderServer(WorldServer par1WorldServer, IChunkLoader par2IChunkLoader, IChunkProvider par3IChunkProvider)
035        {
036            this.defaultEmptyChunk = new EmptyChunk(par1WorldServer, 0, 0);
037            this.currentServer = par1WorldServer;
038            this.currentChunkLoader = par2IChunkLoader;
039            this.currentChunkProvider = par3IChunkProvider;
040        }
041    
042        /**
043         * Checks to see if a chunk exists at x, y
044         */
045        public boolean chunkExists(int par1, int par2)
046        {
047            return this.loadedChunkHashMap.containsItem(ChunkCoordIntPair.chunkXZ2Int(par1, par2));
048        }
049    
050        /**
051         * marks chunk for unload by "unload100OldestChunks"  if there is no spawn point, or if the center of the chunk is
052         * outside 200 blocks (x or z) of the spawn
053         */
054        public void unloadChunksIfNotNearSpawn(int par1, int par2)
055        {
056            if (this.currentServer.provider.canRespawnHere() && DimensionManager.shouldLoadSpawn(currentServer.provider.dimensionId))
057            {
058                ChunkCoordinates var3 = this.currentServer.getSpawnPoint();
059                int var4 = par1 * 16 + 8 - var3.posX;
060                int var5 = par2 * 16 + 8 - var3.posZ;
061                short var6 = 128;
062    
063                if (var4 < -var6 || var4 > var6 || var5 < -var6 || var5 > var6)
064                {
065                    this.chunksToUnload.add(Long.valueOf(ChunkCoordIntPair.chunkXZ2Int(par1, par2)));
066                }
067            }
068            else
069            {
070                this.chunksToUnload.add(Long.valueOf(ChunkCoordIntPair.chunkXZ2Int(par1, par2)));
071            }
072        }
073    
074        /**
075         * marks all chunks for unload, ignoring those near the spawn
076         */
077        public void unloadAllChunks()
078        {
079            Iterator var1 = this.loadedChunks.iterator();
080    
081            while (var1.hasNext())
082            {
083                Chunk var2 = (Chunk)var1.next();
084                this.unloadChunksIfNotNearSpawn(var2.xPosition, var2.zPosition);
085            }
086        }
087    
088        /**
089         * loads or generates the chunk at the chunk location specified
090         */
091        public Chunk loadChunk(int par1, int par2)
092        {
093            long var3 = ChunkCoordIntPair.chunkXZ2Int(par1, par2);
094            this.chunksToUnload.remove(Long.valueOf(var3));
095            Chunk var5 = (Chunk)this.loadedChunkHashMap.getValueByKey(var3);
096    
097            if (var5 == null)
098            {
099                var5 = ForgeChunkManager.fetchDormantChunk(var3, currentServer);
100                if (var5 == null)
101                {
102                    var5 = this.safeLoadChunk(par1, par2);
103                }
104    
105                if (var5 == null)
106                {
107                    if (this.currentChunkProvider == null)
108                    {
109                        var5 = this.defaultEmptyChunk;
110                    }
111                    else
112                    {
113                        var5 = this.currentChunkProvider.provideChunk(par1, par2);
114                    }
115                }
116    
117                this.loadedChunkHashMap.add(var3, var5);
118                this.loadedChunks.add(var5);
119    
120                if (var5 != null)
121                {
122                    var5.onChunkLoad();
123                }
124    
125                var5.populateChunk(this, this, par1, par2);
126            }
127    
128            return var5;
129        }
130    
131        /**
132         * Will return back a chunk, if it doesn't exist and its not a MP client it will generates all the blocks for the
133         * specified chunk from the map seed and chunk seed
134         */
135        public Chunk provideChunk(int par1, int par2)
136        {
137            Chunk var3 = (Chunk)this.loadedChunkHashMap.getValueByKey(ChunkCoordIntPair.chunkXZ2Int(par1, par2));
138            return var3 == null ? (!this.currentServer.findingSpawnPoint && !this.loadChunkOnProvideRequest ? this.defaultEmptyChunk : this.loadChunk(par1, par2)) : var3;
139        }
140    
141        /**
142         * used by loadChunk, but catches any exceptions if the load fails.
143         */
144        private Chunk safeLoadChunk(int par1, int par2)
145        {
146            if (this.currentChunkLoader == null)
147            {
148                return null;
149            }
150            else
151            {
152                try
153                {
154                    Chunk var3 = this.currentChunkLoader.loadChunk(this.currentServer, par1, par2);
155    
156                    if (var3 != null)
157                    {
158                        var3.lastSaveTime = this.currentServer.getTotalWorldTime();
159    
160                        if (this.currentChunkProvider != null)
161                        {
162                            this.currentChunkProvider.func_82695_e(par1, par2);
163                        }
164                    }
165    
166                    return var3;
167                }
168                catch (Exception var4)
169                {
170                    var4.printStackTrace();
171                    return null;
172                }
173            }
174        }
175    
176        /**
177         * used by saveChunks, but catches any exceptions if the save fails.
178         */
179        private void safeSaveExtraChunkData(Chunk par1Chunk)
180        {
181            if (this.currentChunkLoader != null)
182            {
183                try
184                {
185                    this.currentChunkLoader.saveExtraChunkData(this.currentServer, par1Chunk);
186                }
187                catch (Exception var3)
188                {
189                    var3.printStackTrace();
190                }
191            }
192        }
193    
194        /**
195         * used by saveChunks, but catches any exceptions if the save fails.
196         */
197        private void safeSaveChunk(Chunk par1Chunk)
198        {
199            if (this.currentChunkLoader != null)
200            {
201                try
202                {
203                    par1Chunk.lastSaveTime = this.currentServer.getTotalWorldTime();
204                    this.currentChunkLoader.saveChunk(this.currentServer, par1Chunk);
205                }
206                catch (IOException var3)
207                {
208                    var3.printStackTrace();
209                }
210                catch (MinecraftException var4)
211                {
212                    var4.printStackTrace();
213                }
214            }
215        }
216    
217        /**
218         * Populates chunk with ores etc etc
219         */
220        public void populate(IChunkProvider par1IChunkProvider, int par2, int par3)
221        {
222            Chunk var4 = this.provideChunk(par2, par3);
223    
224            if (!var4.isTerrainPopulated)
225            {
226                var4.isTerrainPopulated = true;
227    
228                if (this.currentChunkProvider != null)
229                {
230                    this.currentChunkProvider.populate(par1IChunkProvider, par2, par3);
231                    GameRegistry.generateWorld(par2, par3, currentServer, currentChunkProvider, par1IChunkProvider);
232                    var4.setChunkModified();
233                }
234            }
235        }
236    
237        /**
238         * Two modes of operation: if passed true, save all Chunks in one go.  If passed false, save up to two chunks.
239         * Return true if all chunks have been saved.
240         */
241        public boolean saveChunks(boolean par1, IProgressUpdate par2IProgressUpdate)
242        {
243            int var3 = 0;
244            Iterator var4 = this.loadedChunks.iterator();
245    
246            while (var4.hasNext())
247            {
248                Chunk var5 = (Chunk)var4.next();
249    
250                if (par1)
251                {
252                    this.safeSaveExtraChunkData(var5);
253                }
254    
255                if (var5.needsSaving(par1))
256                {
257                    this.safeSaveChunk(var5);
258                    var5.isModified = false;
259                    ++var3;
260    
261                    if (var3 == 24 && !par1)
262                    {
263                        return false;
264                    }
265                }
266            }
267    
268            if (par1)
269            {
270                if (this.currentChunkLoader == null)
271                {
272                    return true;
273                }
274    
275                this.currentChunkLoader.saveExtraData();
276            }
277    
278            return true;
279        }
280    
281        /**
282         * Unloads the 100 oldest chunks from memory, due to a bug with chunkSet.add() never being called it thinks the list
283         * is always empty and will not remove any chunks.
284         */
285        public boolean unload100OldestChunks()
286        {
287            if (!this.currentServer.canNotSave)
288            {
289                for (ChunkCoordIntPair forced : currentServer.getPersistentChunks().keySet())
290                {
291                    this.chunksToUnload.remove(ChunkCoordIntPair.chunkXZ2Int(forced.chunkXPos, forced.chunkZPos));
292                }
293    
294                for (int var1 = 0; var1 < 100; ++var1)
295                {
296                    if (!this.chunksToUnload.isEmpty())
297                    {
298                        Long var2 = (Long)this.chunksToUnload.iterator().next();
299                        Chunk var3 = (Chunk)this.loadedChunkHashMap.getValueByKey(var2.longValue());
300                        var3.onChunkUnload();
301                        this.safeSaveChunk(var3);
302                        this.safeSaveExtraChunkData(var3);
303                        this.chunksToUnload.remove(var2);
304                        this.loadedChunkHashMap.remove(var2.longValue());
305                        this.loadedChunks.remove(var3);
306                        ForgeChunkManager.putDormantChunk(ChunkCoordIntPair.chunkXZ2Int(var3.xPosition, var3.zPosition), var3);
307                        if(loadedChunks.size() == 0 && ForgeChunkManager.getPersistentChunksFor(currentServer).size() == 0 && !DimensionManager.shouldLoadSpawn(currentServer.provider.dimensionId)) {
308                            DimensionManager.unloadWorld(currentServer.provider.dimensionId);
309                            return currentChunkProvider.unload100OldestChunks();
310                        }
311                    }
312                }
313    
314                if (this.currentChunkLoader != null)
315                {
316                    this.currentChunkLoader.chunkTick();
317                }
318            }
319    
320            return this.currentChunkProvider.unload100OldestChunks();
321        }
322    
323        /**
324         * Returns if the IChunkProvider supports saving.
325         */
326        public boolean canSave()
327        {
328            return !this.currentServer.canNotSave;
329        }
330    
331        /**
332         * Converts the instance data to a readable string.
333         */
334        public String makeString()
335        {
336            return "ServerChunkCache: " + this.loadedChunkHashMap.getNumHashElements() + " Drop: " + this.chunksToUnload.size();
337        }
338    
339        /**
340         * Returns a list of creatures of the specified type that can spawn at the given location.
341         */
342        public List getPossibleCreatures(EnumCreatureType par1EnumCreatureType, int par2, int par3, int par4)
343        {
344            return this.currentChunkProvider.getPossibleCreatures(par1EnumCreatureType, par2, par3, par4);
345        }
346    
347        /**
348         * Returns the location of the closest structure of the specified type. If not found returns null.
349         */
350        public ChunkPosition findClosestStructure(World par1World, String par2Str, int par3, int par4, int par5)
351        {
352            return this.currentChunkProvider.findClosestStructure(par1World, par2Str, par3, par4, par5);
353        }
354    
355        public int getLoadedChunkCount()
356        {
357            return this.loadedChunkHashMap.getNumHashElements();
358        }
359    
360        public void func_82695_e(int par1, int par2) {}
361    }