public AnvilBlockManager(IChunkManager cm) : base(cm) { IChunk c = AnvilChunk.Create(0, 0); chunkXDim = c.Blocks.XDim; chunkYDim = c.Blocks.YDim; chunkZDim = c.Blocks.ZDim; chunkXMask = chunkXDim - 1; chunkYMask = chunkYDim - 1; chunkZMask = chunkZDim - 1; chunkXLog = Log2(chunkXDim); chunkYLog = Log2(chunkYDim); chunkZLog = Log2(chunkZDim); }
/// <summary> /// Constructs a new <see cref="BlockManager"/> instance on top of the given <see cref="IChunkManager"/>. /// </summary> /// <param name="cm">An <see cref="IChunkManager"/> instance.</param> public BlockManager(IChunkManager cm) { chunkMan = cm; Chunk c = Chunk.Create(0, 0); chunkXDim = c.Blocks.XDim; chunkYDim = c.Blocks.YDim; chunkZDim = c.Blocks.ZDim; chunkXMask = chunkXDim - 1; chunkYMask = chunkYDim - 1; chunkZMask = chunkZDim - 1; chunkXLog = Log2(chunkXDim); chunkYLog = Log2(chunkYDim); chunkZLog = Log2(chunkZDim); }
public GenOreBlockManager(IChunkManager bm, OregenOptions o) : base(bm) { opt = o; IChunk c = null; if (bm is AlphaChunkManager) c = AlphaChunk.Create(0, 0); else c = AnvilChunk.Create(0, 0); chunkXDim = c.Blocks.XDim; chunkYDim = c.Blocks.YDim; chunkZDim = c.Blocks.ZDim; chunkXMask = chunkXDim - 1; chunkYMask = chunkYDim - 1; chunkZMask = chunkZDim - 1; chunkXLog = Log2(chunkXDim); chunkYLog = Log2(chunkYDim); chunkZLog = Log2(chunkZDim); }
public ColoredChunkRenderer(EngineConfiguration config, ContentLibrary contentLibrary, GraphicsDevice device, CameraManager cameraManager, IChunkManager chunkManager) { _config = config; _device = device; _terrainColorEffect = contentLibrary.TerrainColorEffect; _camManager = cameraManager; _chunks = chunkManager; _debugOptions = ChunkRendererDebugOptions.NONE; basicEffect = contentLibrary.BasicEffect; _debugRasterizerState = new RasterizerState() { CullMode = Microsoft.Xna.Framework.Graphics.CullMode.None, FillMode = Microsoft.Xna.Framework.Graphics.FillMode.WireFrame }; _rasterizerState = new RasterizerState() { CullMode = Microsoft.Xna.Framework.Graphics.CullMode.CullCounterClockwiseFace }; }
static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("Usage: eina_to_nbt <source> <dest>"); return; } String dest = args[1]; System.Console.WriteLine("Creating EINA map..."); if (!Directory.Exists(dest)) { Directory.CreateDirectory(dest); } NbtWorld world = AnvilWorld.Create(dest); world.Level.LevelName = "EINA"; world.Level.Spawn = new SpawnPoint(292, 70, 270); world.Level.GameType = GameType.CREATIVE; world.Level.Initialized = true; Player p = new Player(); p.Position.X = 292; p.Position.Y = 130; p.Position.Z = 292; IPlayerManager pm = world.GetPlayerManager(); pm.SetPlayer("Player", p); IChunkManager cm = world.GetChunkManager(); string[] lines = System.IO.File.ReadAllLines(args[0]); string[] words; ChunkRef chunk; words = lines[0].Split(' '); int minx = Int32.Parse(words[0]); int maxx = Int32.Parse(words[0]); int miny = Int32.Parse(words[0]); int maxy = Int32.Parse(words[0]); for (int i = 0; i < lines.Length; i++) { words = lines[i].Split(' '); //System.Console.WriteLine(lines[i]); int x = Int32.Parse(words[0]); int y = Int32.Parse(words[1]); int z = Int32.Parse(words[2]); int color = Int32.Parse(words[3]); string text = ""; if (words.Length > 4) { text = words[4]; for (int j = 5; j < words.Length; j++) { text += ' ' + words[j]; } } else { text = ""; } int xLocal = x / 16; int yLocal = y / 16; if (xLocal < minx) { minx = xLocal; } if (xLocal > maxx) { maxx = xLocal; } if (yLocal < miny) { miny = yLocal; } if (yLocal > maxy) { maxy = yLocal; } if (!cm.ChunkExists(xLocal, yLocal)) { //System.Console.WriteLine(xLocal+" "+yLocal); cm.CreateChunk(xLocal, yLocal); } chunk = cm.GetChunkRef(xLocal, yLocal); //System.Console.WriteLine(x+" "+y+" "+z); //System.Console.WriteLine(xLocal+" "+yLocal); if (!chunk.IsDirty) { chunk.IsTerrainPopulated = true; chunk.Blocks.AutoLight = false; //FlatChunk(chunk, 64); chunk.Blocks.RebuildHeightMap(); chunk.Blocks.RebuildBlockLight(); chunk.Blocks.RebuildSkyLight(); //System.Console.WriteLine(chunk.IsDirty); for (int i2 = 0; i2 < 16; i2++) { for (int j = 0; j < 16; j++) { setBlock(chunk, i2, 64, j, 16, ""); } } if (((xLocal % 8) == 0) & ((yLocal % 8) == 0)) { cm.Save(); } setBlock(chunk, x % 16, z + 64, y % 16, color, text); } else { setBlock(chunk, x % 16, z + 64, y % 16, color, text); //System.Console.WriteLine("hola"); } if ((i + 1) % 500000 == 0) { System.Console.WriteLine("Guardando"); world.Save(); //System.Console.WriteLine("Hecho"); } } world.Save(); }
/// <summary> /// Constructs a new <see cref="BlockManager"/> instance on top of the given <see cref="IChunkManager"/>. /// </summary> /// <param name="cm">An <see cref="IChunkManager"/> instance.</param> public BlockManager(IChunkManager cm) { chunkMan = cm; }
/// <summary> /// /// </summary> void Start() { ChunkManager = new ChunkManager <Boid, AggregatedBoidChunk>(ChunkSize); DeltaTimeSamples = new Queue <float>(); }
/// <summary> /// Trims the world to work with only the chuncks within the coordents. /// </summary> /// <param name="xStart"></param> /// <param name="zStart"></param> /// <param name="xEnd"></param> /// <param name="zEnd"></param> /// <param name="yTop"></param> /// <param name="yBottom"></param> /// <returns></returns> public static bool TrimWorld() { //Clear trimmed chunks list TrimedChunks = new List <SimpleChunkRef>(); //Get the higher X int HighX = xStart / 16; int LowX = xEnd / 16; if (xEnd > xStart) { HighX = xEnd / 16; LowX = xStart / 16; } //Get the higher Z int HighZ = zStart / 16; int LowZ = zEnd / 16; if (zEnd > zStart) { HighZ = zEnd / 16; LowZ = zStart / 16; } //Loop through world and grab chuncks IChunkManager cm = importedWorld.GetChunkManager(); for (int x = LowX; x <= HighX; x++) { for (int z = LowZ; z <= HighZ; z++) { string signX = "+"; if (z < 0) { signX = "-"; } string signZ = "+"; if (z < 0) { signZ = "-"; } if (cm.ChunkExists(x, z)) { IChunk chunk = cm.GetChunk(x, z); //Console.WriteLine("Saving: xz[{0}{1},{2}{3}]", signX, Math.Abs(x).ToString("D3"), signZ, Math.Abs(z).ToString("D3")); TrimedChunks.Add(new SimpleChunkRef(x, z, chunk)); } else { //Console.WriteLine("No chunk found: xz[{0}{1},{2}{3}]", signX, Math.Abs(x).ToString("D3"), signZ, Math.Abs(z).ToString("D3")); TrimedChunks.Add(new SimpleChunkRef(x, z, null)); } } } if (TrimedChunks.Count > 0) { return(true); } else { return(false); } }
public override void Initialise(VoxelTypeManager voxelTypeManager, IChunkManager chunkManager, FrameworkEventManager eventManager) { base.Initialise(voxelTypeManager, chunkManager, eventManager); Assert.IsNotNull(bedrockType, $"{typeof(NoisyProvider)} must have a valid reference to a bedrock block type"); Assert.IsNotNull(waterType, $"{typeof(NoisyProvider)} must have a valid reference to a water block type"); Assert.IsNotNull(biomeDatabaseComponent, $"{typeof(NoisyProvider)} must have a valid reference to a biome database component"); if (SceneMessagePasser.TryConsumeMessage <SeedMessage>(out var message)) { worldSettings.seed = GetSeedAsFloat(message.seed); Debug.Log($"Int seed: {message.seed}, derived seed: {worldSettings.seed}"); } InitialiseSeeds(); bedrockID = voxelTypeManager.GetId(bedrockType); waterID = voxelTypeManager.GetId(waterType); chunkDimensions = chunkManager.ChunkDimensions.ToNative(); if (chunkManager.WorldLimits.IsWorldHeightLimited) { minY = chunkManager.WorldLimits.MinChunkY * chunkManager.ChunkDimensions.y; } worldSettings.Initialise(minY, chunkManager.ChunkDimensions.ToNative()); treeSettings.Initialise(); biomeDatabaseComponent.Initialise(); //Setup ocean config try { var oceanZone = biomeDatabaseComponent.config.elevationLowToHigh.Find((zone) => zone.Name.Equals("Ocean")); var oceanBiomes = oceanZone.moistureLevelsLowToHigh.Select((def) => def.biomeDefinition).ToArray(); oceanGenConfig.oceanIDs = new NativeArray <int>(oceanBiomes.Length, Allocator.Persistent); for (int i = 0; i < oceanBiomes.Length; i++) { oceanGenConfig.oceanIDs[i] = biomeDatabaseComponent.GetBiomeID(oceanBiomes[i]); } oceanGenConfig.sealevel = math.floor(math.lerp(worldSettings.minPossibleHmValue, worldSettings.maxPossibleHmValue, biomeDatabaseComponent.GetMaxElevationFraction(oceanBiomes[0]))); oceanGenConfig.waterID = waterID; } catch (Exception e) { throw new Exception($"Failed to find any ocean biomes for biome config {biomeDatabaseComponent.config.name}. Cause {e.Message}"); } noiseMaps = new Dictionary <Vector2Int, ChunkColumnNoiseMaps>(); numActiveChunksInColumn = new Dictionary <Vector2Int, int>(); noiseGenReferenceCounter = new JobReferenceCounter <Vector2Int, NativeChunkColumnNoiseMaps>(MakeNoiseJob); structureGenerator = new StructureGenerator(); structureGenerator.Initalise(voxelTypeManager, biomeDatabaseComponent, treeSettings.TreeThreshold, (int)treemapNoise.Seed); oreSettings.Initialise(voxelTypeManager); eventManager.OnChunkActivated += OnChunkActivated; eventManager.OnChunkDeactivated += OnChunkDeactivated; }
public ChunkGeneratorSurface(IChunkManager chunkManager) { _chunkManager = chunkManager; }
public DeferredColoredChunkRenderer(EngineConfiguration config, ContentLibrary contentLibrary, GraphicsDevice device, CameraManager cameraManager, IChunkManager chunkManager) { _device = device; _sb = new SpriteBatch(_device); _halfPixel = new Vector2(0.5f / _device.PresentationParameters.BackBufferWidth, 0.5f / _device.PresentationParameters.BackBufferHeight); _quadRenderer = new QuadRenderer(_device); _clearEffect = new ClearEffect(contentLibrary.ClearEffect); _renderGBufferEffect = new RenderGBufferColorEffect(contentLibrary.RenderGBufferColorEffect); _renderCombineEffect = new RenderCombineEffect(contentLibrary.RenderCombineEffect); _directionalLightEffect = new DirectionalLightEffect(contentLibrary.DirectionalLightEffect); _pointLightEffect = new PointLightEffect(contentLibrary.PointLightEffect); _ssaoEffect = new SSAOEffect(contentLibrary.SSAOEffect); _camManager = cameraManager; _chunks = chunkManager; _debugOptions = ChunkRendererDebugOptions.NONE; basicEffect = contentLibrary.BasicEffect; _uiFontTiny = contentLibrary.UIFontTiny; _albedoTarget = new RenderTarget2D(_device, _device.PresentationParameters.BackBufferWidth, _device.PresentationParameters.BackBufferHeight, false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8); _lightTarget = new RenderTarget2D(_device, _device.PresentationParameters.BackBufferWidth, _device.PresentationParameters.BackBufferHeight, false, SurfaceFormat.Color, DepthFormat.None); _normalTarget = new RenderTarget2D(_device, _device.PresentationParameters.BackBufferWidth, _device.PresentationParameters.BackBufferHeight, false, SurfaceFormat.Color, DepthFormat.None); _depthTarget = new RenderTarget2D(_device, _device.PresentationParameters.BackBufferWidth, _device.PresentationParameters.BackBufferHeight, false, SurfaceFormat.Single, DepthFormat.Depth24Stencil8); _randomMap = new Texture2D(_device, _device.PresentationParameters.BackBufferWidth, _device.PresentationParameters.BackBufferHeight); CreateRandomNormalTexture(_randomMap); _debugRasterizerState = new RasterizerState() { CullMode = Microsoft.Xna.Framework.Graphics.CullMode.None, FillMode = Microsoft.Xna.Framework.Graphics.FillMode.WireFrame }; _rasterizerState = new RasterizerState() { CullMode = Microsoft.Xna.Framework.Graphics.CullMode.CullCounterClockwiseFace }; }
private void SetupMocks(Vector3Int chunkDimensions, WorldSizeLimits worldSizeLimits = null, bool generateStructures = true) { if (worldSizeLimits == null) { worldSizeLimits = new WorldSizeLimits(false, 0); worldSizeLimits.Initalise(); } mockManager = Substitute.For <IChunkManager>(); mockManager.GenerateStructures.Returns(generateStructures); mockManager.WorldToChunkPosition(Arg.Any <Vector3>()).Returns(args => WorldToChunkPos((Vector3)args[0], chunkDimensions)); mockManager.WorldLimits.Returns(worldSizeLimits); mockManager.GetAllLoadedChunkIds().Returns((_) => statusMap.Keys.ToArray()); mockPipeline = Substitute.For <IChunkPipeline>(); mockPipeline.TerrainDataStage.Returns(0); mockPipeline.OwnStructuresStage.Returns(1); mockPipeline.FullyGeneratedStage.Returns(2); mockPipeline.RenderedStage.Returns(3); mockPipeline.CompleteStage.Returns(4); statusMap = new Dictionary <Vector3Int, int>(); //Mock set target to write to the status map instead mockManager .When(_ => _.SetTargetStageOfChunk(Arg.Any <Vector3Int>(), Arg.Any <int>(), Arg.Any <TargetUpdateMode>())) .Do(args => { Vector3Int pos = (Vector3Int)args[0]; int newStatus = (int)args[1]; var mode = (TargetUpdateMode)args[2]; if (statusMap.TryGetValue(pos, out var currentStatus)) { //If the pos exists, ensure update modes are respected if (newStatus > currentStatus && mode.allowsUpgrade()) { statusMap[pos] = newStatus; } else if (newStatus < currentStatus && mode.allowsDowngrade()) { statusMap[pos] = newStatus; } } else { //Otherwise, add the new pos and status statusMap[pos] = newStatus; } }); //Mock deactivate to remove from the status map mockManager .When(_ => _.TryDeactivateChunk(Arg.Any <Vector3Int>())) .Do(args => { Vector3Int pos = (Vector3Int)args[0]; statusMap.Remove(pos); }); player = Substitute.For <IVoxelPlayer>(); player.Position = Vector3.zero; }
void Start() { _chunkManager = ClientChunkManager.Instance; }
public VoxelMoverServerside(DynamicEntityServerside owner) { _chunkManager = ServerChunkManager.Instance; _owner = owner; }
public void Reset() { maxIntensity = LightValue.MaxIntensity; heightMapYValue = 0; chunkDimensions = new Vector3Int(16, 16, 16); chunkStorage = new Dictionary <Vector3Int, IChunkData>(); lampId = (VoxelTypeID)1; blockerId = (VoxelTypeID)2; voxelTypeManager = Substitute.For <IVoxelTypeManager>(); voxelTypeManager.LastVoxelID.Returns(blockerId); voxelTypeManager.GetLightProperties(Arg.Any <VoxelTypeID>()) .Returns((args) => { var typeId = (VoxelTypeID)args[0]; if (typeId.Equals(lampId)) { return(maxIntensity, maxIntensity); } else if (typeId.Equals(blockerId)) { return(0, maxIntensity); } return(0, 1); }); fullyGenerated = new HashSet <Vector3Int>(); chunkManager = Substitute.For <IChunkManager>(); chunkManager.IsChunkFullyGenerated(Arg.Any <Vector3Int>()) .Returns((args) => { var id = (Vector3Int)args[0]; return(fullyGenerated.Contains(id)); }); var worldLimits = new WorldSizeLimits(false, 0); worldLimits.Initalise(); chunkManager.WorldLimits.Returns(worldLimits); chunkManager.ChunkToWorldPosition(Arg.Any <Vector3Int>()) .Returns((args) => { var chunkId = (Vector3Int)args[0]; return(chunkId * chunkDimensions); }); chunkManager.GetReadOnlyChunkData(Arg.Any <Vector3Int>()) .Returns((args) => { var chunkId = (Vector3Int)args[0]; return(new RestrictedChunkData(GetMockChunkData(chunkId))); }); chunkManager.GetChunkData(Arg.Any <Vector3Int>()) .Returns((args) => { var chunkId = (Vector3Int)args[0]; return(GetMockChunkData(chunkId)); }); chunkManager.ChunkDimensions.Returns(chunkDimensions); IHeightMapProvider heightMapProvider = Substitute.For <IHeightMapProvider>(); heightMapProvider.GetHeightMapForColumn(Arg.Any <Vector2Int>()) .Returns((args) => { return(getFlatHeightMap(heightMapYValue)); }); lightManager = new LightManager(); lightManager.Initialise(voxelTypeManager, chunkManager, heightMapProvider); }
public GameStatePlay(IGameStateManager gameStateManager, IWorldManager worldManager, IChunkManager chunkManager, IChunkPartManager chunkPartManager, IBlockSelector blockSelector, IBlocksProvider blocksProvider, World world) { Debug = new DebugObjects(); _world = world; _gameStateManager = gameStateManager; _worldManager = worldManager; _chunkManager = chunkManager; _chunkPartManager = chunkPartManager; _blockSelector = blockSelector; _blocksProvider = blocksProvider; _selectedBlockId = _blockSelector.GetNextBlock(0); _selectedBlockMetadata = 0; _aabbShader = ShaderManager.GetWithGeometry("AabbShader"); _baseShader = ShaderManager.GetWithGeometry("BaseShader"); _debugShader = ShaderManager.GetWithGeometry("Debug"); _guiShader = ShaderManager.Get("GuiShader"); _skyboxShader = ShaderManager.Get("SkyboxShader"); _player = new Player() { Position = new Vector3(0, 90, 0) }; _camera = new Camera(new Vector3(0), new Vector3(0), (float)(80f * (Math.PI / 180f))); _frustum = new Plane[6]; for (int i = 0; i < _frustum.Length; i++) { _frustum[i] = new Plane(); } _terrainTexture = TextureManager.Get("terrain.png", TextureMinFilter.Nearest, TextureMagFilter.Nearest); _iconsTexture = TextureManager.Get("icons.png", TextureMinFilter.Nearest, TextureMagFilter.Nearest); _skyTexture = TextureManager.Get("skybox.png", TextureMinFilter.Nearest, TextureMagFilter.Nearest); _text = new Text(new Vector2(5, 0), FontManager.Get("glyphs"), _guiShader, ""); _renderDistance = 16; _crosshair = new Sprite(new Vector2(36, 36), new Vector2(0), new Vector2(16 / 256f), _guiShader); _crosshair.UploadInGl(); _selectedBlocks = new AABBObjects(); _skybox = new Mesh() { Vertices = new List <Vertex>() { // FRONT new Vertex(new Vector3(-10, -10, -10), Vector3.One, new Vector2(1 / 4f, 2 / 3f)), new Vertex(new Vector3(10, -10, -10), Vector3.One, new Vector2(2 / 4f, 2 / 3f)), new Vertex(new Vector3(-10, 10, -10), Vector3.One, new Vector2(1 / 4f, 1 / 3f)), new Vertex(new Vector3(-10, 10, -10), Vector3.One, new Vector2(1 / 4f, 1 / 3f)), new Vertex(new Vector3(10, -10, -10), Vector3.One, new Vector2(2 / 4f, 2 / 3f)), new Vertex(new Vector3(10, 10, -10), Vector3.One, new Vector2(2 / 4f, 1 / 3f)), // RIGHT new Vertex(new Vector3(10, -10, -10), Vector3.One, new Vector2(2 / 4f, 2 / 3f)), new Vertex(new Vector3(10, -10, 10), Vector3.One, new Vector2(3 / 4f, 2 / 3f)), new Vertex(new Vector3(10, 10, -10), Vector3.One, new Vector2(2 / 4f, 1 / 3f)), new Vertex(new Vector3(10, 10, -10), Vector3.One, new Vector2(2 / 4f, 1 / 3f)), new Vertex(new Vector3(10, -10, 10), Vector3.One, new Vector2(3 / 4f, 2 / 3f)), new Vertex(new Vector3(10, 10, 10), Vector3.One, new Vector2(3 / 4f, 1 / 3f)), // LEFT new Vertex(new Vector3(-10, -10, 10), Vector3.One, new Vector2(0 / 4f, 2 / 3f)), new Vertex(new Vector3(-10, -10, -10), Vector3.One, new Vector2(1 / 4f, 2 / 3f)), new Vertex(new Vector3(-10, 10, 10), Vector3.One, new Vector2(0 / 4f, 1 / 3f)), new Vertex(new Vector3(-10, 10, 10), Vector3.One, new Vector2(0 / 4f, 1 / 3f)), new Vertex(new Vector3(-10, -10, -10), Vector3.One, new Vector2(1 / 4f, 2 / 3f)), new Vertex(new Vector3(-10, 10, -10), Vector3.One, new Vector2(1 / 4f, 1 / 3f)), // TOP new Vertex(new Vector3(-10, 10, -10), Vector3.One, new Vector2(1 / 4f, 1 / 3f)), new Vertex(new Vector3(10, 10, -10), Vector3.One, new Vector2(2 / 4f, 1 / 3f)), new Vertex(new Vector3(-10, 10, 10), Vector3.One, new Vector2(1 / 4f, 0 / 3f)), new Vertex(new Vector3(-10, 10, 10), Vector3.One, new Vector2(1 / 4f, 0 / 3f)), new Vertex(new Vector3(10, 10, -10), Vector3.One, new Vector2(2 / 4f, 1 / 3f)), new Vertex(new Vector3(10, 10, 10), Vector3.One, new Vector2(2 / 4f, 0 / 3f)), // BOTTOM new Vertex(new Vector3(-10, -10, 10), Vector3.One, new Vector2(1 / 4f, 3 / 3f)), new Vertex(new Vector3(10, -10, 10), Vector3.One, new Vector2(2 / 4f, 3 / 3f)), new Vertex(new Vector3(-10, -10, -10), Vector3.One, new Vector2(1 / 4f, 2 / 3f)), new Vertex(new Vector3(-10, -10, -10), Vector3.One, new Vector2(1 / 4f, 2 / 3f)), new Vertex(new Vector3(10, -10, 10), Vector3.One, new Vector2(2 / 4f, 3 / 3f)), new Vertex(new Vector3(10, -10, -10), Vector3.One, new Vector2(2 / 4f, 2 / 3f)), // BACK new Vertex(new Vector3(10, -10, 10), Vector3.One, new Vector2(3 / 4f, 2 / 3f)), new Vertex(new Vector3(-10, -10, 10), Vector3.One, new Vector2(4 / 4f, 2 / 3f)), new Vertex(new Vector3(10, 10, 10), Vector3.One, new Vector2(3 / 4f, 1 / 3f)), new Vertex(new Vector3(10, 10, 10), Vector3.One, new Vector2(3 / 4f, 1 / 3f)), new Vertex(new Vector3(-10, -10, 10), Vector3.One, new Vector2(4 / 4f, 2 / 3f)), new Vertex(new Vector3(-10, 10, 10), Vector3.One, new Vector2(4 / 4f, 1 / 3f)), } }; _skybox.LoadInGl(); _loadingThread = new Thread(new ThreadStart(() => { Func <int, Tuple <int, int> > spiral = (n) => { var k = (int)Math.Ceiling((Math.Sqrt(n) - 1) / 2); var t = 2 * k + 1; var m = t * t; t = t - 1; var mt = m - t; if (n > mt) { return(new Tuple <int, int>(k - (m - n), -k)); } m = mt; mt = m - t; if (n > mt) { return(new Tuple <int, int>(-k, -k + (m - n))); } m = mt; mt = m - t; if (n > mt) { return(new Tuple <int, int>(-k + (m - n), k)); } return(new Tuple <int, int>(k, k - (m - n - t))); }; while (!_stopLoading) { var chunks = _worldManager.GetLoadedChunks(_world); var playerPosition = _player.Position; var playerPos2D = playerPosition.Xz; ChunkPosition?chunkToLoad = null; var renderDistanceTime2Square = _renderDistance * 2; renderDistanceTime2Square = renderDistanceTime2Square * renderDistanceTime2Square; for (var i = 0; i < renderDistanceTime2Square; i++) { var pos = spiral(i); var chunkPositionInLocalCoordinates = new Vector2(pos.Item1, pos.Item2); if (chunkPositionInLocalCoordinates.LengthFast < _renderDistance) { var chunkPosition = new ChunkPosition((int)((chunkPositionInLocalCoordinates.X + Math.Floor(playerPos2D.X / 16f))), (int)((chunkPositionInLocalCoordinates.Y + Math.Floor(playerPos2D.Y / 16f)))); if (!chunks.Any(chunk => chunk.Item1.Equals(chunkPosition))) { chunkToLoad = chunkPosition; break; } } } if (chunkToLoad != null) { _worldManager.GetChunkAt(_world, chunkToLoad.Value.X, chunkToLoad.Value.Z); } else { Thread.Sleep(1000); } } })) { IsBackground = true }; _loadingThread.Start(); }
private static void LoopChunks(NbtWorld world, int dim) { DateTime startTime = DateTime.Now; Console.WriteLine("Searching {0}", dimensions[dim]); int fixedChests = 0; int fixedPotions = 0; int fixedSpawners = 0; IChunkManager chunks = world.GetChunkManager(dim); foreach (ChunkRef chunk in chunks) { for (int x = 0; x < chunk.Blocks.XDim; x++) { for (int z = 0; z < chunk.Blocks.ZDim; z++) { for (int y = 0; y < chunk.Blocks.YDim; y++) { switch (chunk.Blocks.GetID(x, y, z)) { case BlockType.CHEST: if (FixChest(chunk, x, y, z)) { Console.WriteLine("Fixed chest"); fixedChests++; } if (fixPotions) { fixedPotions += FixPotions(chunk, x, y, z); } break; case BlockType.DISPENSER: if (fixPotions) { fixedPotions += FixPotions(chunk, x, y, z); } break; case BlockType.BREWING_STAND: if (fixPotions) { fixedPotions += FixPotions(chunk, x, y, z); } break; case BlockType.MONSTER_SPAWNER: if (fixSpawners && FixSpawner(chunk, x, y, z)) { Console.WriteLine("Fixed Spawner"); fixedSpawners++; } break; } } } } chunks.Save(); } TimeSpan time = DateTime.Now.Subtract(startTime); Console.Write("Finished searching {0} in {1}. Fixed:", dimensions[dim], time.ToString(@"h\:mm\:ss")); Console.Write(" [{0} chest{1}]", fixedChests, fixedChests == 1 ? "" : "s"); Console.Write(" [{0} potion{1}]", fixedPotions, fixedPotions == 1 ? "" : "s"); Console.Write(" [{0} potion spawner{1}]", fixedSpawners, fixedSpawners == 1 ? "" : "s"); Console.WriteLine(); fixedIssues["chest"] += fixedChests; fixedIssues["potion"] += fixedPotions; fixedIssues["spawner"] += fixedSpawners; }
public ChunkEnumerator(IChunkManager cm, IChunkFilter filter) { _cm = cm; _filter = filter; _enum = _cm.GetEnumerator(); }
public GenOreBlockManager(IChunkManager bm, OregenOptions o) : base(bm) { opt = o; }
protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); contentLibrary = new ContentLibrary(); contentLibrary.Load(GraphicsDevice, Content); basicEffect = new BasicEffect(GraphicsDevice); _space = new Space(); _space.ForceUpdater.Gravity = MathConverter.Convert(new Vector3(0, -9.81f, 0)); font = Content.Load <SpriteFont>("Arial"); _fpsCounter = new FPSCounter(this, font); _fpsCounter.LoadContent(); camManager = new CameraManager(); camManager.AddCamera("player", cam); camManager.MainCameraName = "player"; simplexDensityFunction = new SimplexDensityFunction(0.01f, 0.1f); EngineConfiguration config = new EngineConfiguration(); config.ChunkWidth = 16; config.ChunkHeight = 16; config.ChunkLength = 16; config.CPULightingEnabled = true; config.RenderDistance = 5; int worldChunkHeight = 8; SphereDensityFunction sdf = new SphereDensityFunction(new Vector3(8, 8, 8), 7.5f); SineWaveDensityFunction swdf = new SineWaveDensityFunction(5, 10, 0.25f); DualContourIslandChunkGenerator icg = new DualContourIslandChunkGenerator(worldChunkHeight * config.ChunkHeight, new SimplexNoiseGenerator(Environment.TickCount)); DualContourFlatLandGenerator flg = new DualContourFlatLandGenerator(); DensityChunkGenerator dcg = new DensityChunkGenerator(swdf); DebuggerGenerator dg = new DebuggerGenerator(); IChunkGenerator generator; ITerrainGradientFunction grad; generator = icg; grad = icg; _world = new World(config, camManager); _chunkManager = new StaticThreadedChunkManager(config, _world, 5, worldChunkHeight, 5); _chunkManager.ChunkSystem = new DualContourColoredChunkSystem(GraphicsDevice, contentLibrary, _chunkManager, camManager, _world, grad, 0.0f); _chunkManager.ChunkSystem.Builder.MeshBuilt += new MeshBuildEventHandler(BuildPhysicsMesh); _chunkManager.ChunkGenerator = generator; _chunkManager.LightManager = new FloodfillLightManager(_chunkManager, config, worldChunkHeight); _world.ChunkManager = _chunkManager; _chunkManager.GenerateChunks(); _chunkManager.BuildAllChunks(); }
public override void Initialise(VoxelTypeManager voxelTypeManager, IChunkManager chunkManager, FrameworkEventManager eventManager) { base.Initialise(voxelTypeManager, chunkManager, eventManager); CullFaces = true; }
public void simpleWriteTest() { initializeMinecraftWorld(); IChunkManager cm = currentWorld.GetChunkManager(); loadDwarfMaps(); int cropWidth = 40; int cropHeight = 40; Settings.Default.borderWest = 40; Settings.Default.borderEast = Settings.Default.borderWest + cropWidth; Settings.Default.borderNorth = 40; Settings.Default.borderSouth = Settings.Default.borderNorth + cropHeight; //FIXME get rid of this junk Settings.Default.mapCenterX = (Settings.Default.borderWest + Settings.Default.borderEast) / 2; Settings.Default.mapCenterY = (Settings.Default.borderNorth + Settings.Default.borderSouth) / 2; Console.WriteLine("Starting conversion now."); Stopwatch watch = Stopwatch.StartNew(); for (int xi = getChunkStartX(); xi < getChunkFinishX(); xi++) { for (int zi = getChunkStartY(); zi < getChunkFinishY(); zi++) { // This line will create a default empty chunk, and create a // backing region file if necessary (which will immediately be // written to disk) ChunkRef chunk = cm.CreateChunk(xi, zi); // This will make sure all the necessary things like trees and // ores are generated for us. chunk.IsTerrainPopulated = false; // Auto light recalculation is horrifically bad for creating // chunks from scratch, because we're placing thousands // of blocks. Turn it off. chunk.Blocks.AutoLight = false; double xMin = ((xi * 16.0 / (double)Settings.Default.blocksPerEmbarkTile) + Settings.Default.mapCenterX); double xMax = (((xi + 1) * 16.0 / (double)Settings.Default.blocksPerEmbarkTile) + Settings.Default.mapCenterX); double yMin = ((zi * 16.0 / (double)Settings.Default.blocksPerEmbarkTile) + Settings.Default.mapCenterY); double yMax = (((zi + 1) * 16.0 / (double)Settings.Default.blocksPerEmbarkTile) + Settings.Default.mapCenterY); // Make the terrain HeightMapChunk(chunk, xMin, xMax, yMin, yMax); // Reset and rebuild the lighting for the entire chunk at once chunk.Blocks.RebuildHeightMap(); if (Settings.Default.lightGenerationEnable) { chunk.Blocks.RebuildBlockLight(); chunk.Blocks.RebuildSkyLight(); } // Save the chunk to disk so it doesn't hang around in RAM cm.Save(); } //TimeSpan elapsedTime = watch.Elapsed; //int finished = xi - chunkStartX + 1; //int left = chunkFinishX - xi - 1; //TimeSpan remainingTime = TimeSpan.FromTicks(elapsedTime.Ticks / finished * left); //Console.WriteLine("Built Chunk Row {0} of {1}. {2}:{3}:{4} elapsed, {5}:{6}:{7} remaining.", // finished, chunkFinishX - chunkStartX, // elapsedTime.Hours, elapsedTime.Minutes, elapsedTime.Seconds, // remainingTime.Hours, remainingTime.Minutes, remainingTime.Seconds); maxHeight = int.MinValue; minHeight = int.MaxValue; } saveMinecraftWorld(); }
public Chunk(IChunkManager <VoxelT> chunkConfiguration) : this(chunkConfiguration, SideLengthDefault) { }
public GenOreBlockManager (IChunkManager bm, OregenOptions o) : base(bm) { opt = o; }
public void Execute() { IChunkManager cm = cmPoolHolder.Target.Get(Thread.CurrentThread.ManagedThreadId); // Get chunks for (int mc_cx = 0; mc_cx < 2; mc_cx++) { for (int mc_cz = 0; mc_cz < 2; mc_cz++) { if (cm.ChunkExists(cx * 2 + mc_cx, cz * 2 + mc_cz)) { var mc_blocks = cm.GetChunkRef(cx * 2 + mc_cx, cz * 2 + mc_cz).Blocks; if (mc_blocks == null) { continue; } for (int cy = 0; cy < cySize; cy++) { Chunk chunk = chunks.Target[cy]; BoundsInt b = new BoundsInt(0, 0, 0, 16, 32, 16); foreach (var pos in b.allPositionsWithin) { //if (pos.y + cy * 32 < 5) //{ // chunk.chunkData[pos.x * 1024 + pos.y * 32 + pos.z] = 0xffffffff; //} //else //{ // chunk.chunkData[pos.x * 1024 + pos.y * 32 + pos.z] = 0x00000000; //} AlphaBlock blk = mc_blocks.GetBlock(pos.x, pos.y + cy * 32, pos.z); int ix = (pos.x + mc_cx * 16) * 1024 + pos.y * 32 + (pos.z + mc_cz * 16); uint cbk = 0x00000000; switch (blk.ID) { // air case 0: cbk = 0; break; // stone case 1: cbk = 0x6b6b6bff; break; // grass case 2: cbk = 0x71a32aff; break; // dirt case 3: cbk = 0x694429ff; break; // log case 17: cbk = 0x96623bff; break; // leaves case 18: cbk = 0x147a23ff; break; // water case 9: cbk = 0x0000FFFF; break; default: cbk = 0xFFFFFFFF; break; } if (cbk != 0) { chunk.SetBlock(pos.x + mc_cx * 16, pos.y, pos.z + mc_cz * 16, Block.From32bitColor(cbk)); } else { chunk.SetBlock(pos.x + mc_cx * 16, pos.y, pos.z + mc_cz * 16, Block.Empty); } if (useID) { chunk.SetBlock(pos.x + mc_cx * 16, pos.y, pos.z + mc_cz * 16, new Block() { id = (ushort)blk.ID, meta = chunk.blockData[ix].meta }); } } } } } } }
/// <summary> /// Parse the world to output block IDs of intrest. (NOTE THIS IS TO BE REMOVED) /// </summary> /// <returns>False always</returns> public static bool ParseWorld() { // The chunk manager is more efficient than the block manager for // this purpose, since we'll inspect every block IChunkManager cm = importedWorld.GetChunkManager(); foreach (ChunkRef chunk in cm) { int absY = 0; int absZ = 0; int absX = 0; string signX = "+"; if (chunk.X < 0) { signX = "-"; } string signZ = "+"; if (chunk.Z < 0) { signZ = "-"; } string chunkString = string.Format("C xz[{0}{1},{2}{3}]", signX, Math.Abs(chunk.X).ToString("D3"), signZ, Math.Abs(chunk.Z).ToString("D3")); // You could hardcode your dimensions, but maybe some day they // won't always be 16. Also the CLR is a bit stupid and has // trouble optimizing repeated calls to Chunk.Blocks.xx, so we // cache them in locals int xdim = chunk.Blocks.XDim; int ydim = chunk.Blocks.YDim; int zdim = chunk.Blocks.ZDim; // Dont know why this was in the example... chunk.Blocks.AutoFluid = true; // x, z, y is the most efficient order to scan blocks // (not that you should care about internal detail) for (int x = 0; x < xdim; x++) { for (int z = 0; z < zdim; z++) { for (int y = 0; y < ydim; y++) { BlockInfo info = chunk.Blocks.GetInfo(x, y, z); if (info.ID != 0 && info.ID != 2 && info.ID != 3 && info.ID != 7) { absX = ((chunk.X * 16) + x); absZ = ((chunk.Z * 16) + z); absY = y; Console.Write("{0} ", chunkString); Console.Write("xyz[{0},{1},{2}] abs xyz[{3}{4},+{5},{6}{7}] ", x.ToString("D2"), y.ToString("D2"), z.ToString("D2"), signX, Math.Abs(absX).ToString("D4"), absY.ToString("D5"), signZ, Math.Abs(absZ).ToString("D5")); Console.Write("{0} - '{1}'", info.ID.ToString("D4"), info.Name); Console.Write("\n"); } } } } } return(false); }
public World ConvertWorld(String mcDirectory) { String segmentDirectory = Path.Combine(FCEDirectory, "Segments"); if (!Directory.Exists(FCEDirectory)) { Directory.CreateDirectory(FCEDirectory); } if (!Directory.Exists(Path.Combine(FCEDirectory, segmentDirectory))) { Directory.CreateDirectory(segmentDirectory); } Boolean anvil = true; NbtWorld nbtWorld = AnvilWorld.Open(mcDirectory); String worldName = nbtWorld.Level.LevelName; IChunkManager chunkManager = nbtWorld.GetChunkManager(); try { // Try to test for mc world type // Don't know how this is supposed to work, but it presumably throws an exception // on a non-Anvil world. chunkManager.Count(); } catch { anvil = false; nbtWorld = BetaWorld.Open(mcDirectory); worldName = nbtWorld.Level.LevelName; chunkManager = nbtWorld.GetChunkManager(); } Int32 spawnChunkX = nbtWorld.Level.Spawn.X >> 4; Int32 spawnChunkZ = nbtWorld.Level.Spawn.Z >> 4; WorldSettings settings = new WorldSettings(); settings.Name = worldName; var fceWorld = World.Create(FCEDirectory, settings); var segmentManager = fceWorld.SegmentManager; _totalSegments = chunkManager.LongCount() * (anvil ? 16 : 8); _segmentsLeft = _totalSegments; StartSaveThread(fceWorld); foreach (ChunkRef chunk in chunkManager) { // If the save thread is too slow, wait until it has caught up before adding to it to prevent high ram usage while (_saveQueue.Count > 5000) { Thread.Sleep(500); } if (chunk.Blocks == null) { _segmentsLeft -= (anvil ? 16 : 8); continue; } Int32 spawnOffsetX = UseSpawnAsOrigin ? spawnChunkX - chunk.X : -chunk.X; Int32 spawnOffsetZ = UseSpawnAsOrigin ? spawnChunkZ - chunk.Z : -chunk.Z; // Minecraft has different x/y directions so we must reverse z so the world isn't mirrored var chunkCoords = new SegmentCoords(spawnOffsetX, 0, -spawnOffsetZ) + SegmentCoords.WorldCenter; for (Int32 i = 0; i < (anvil ? 16 : 8); i++) { SegmentCoords segCoords = chunkCoords + SegmentCoords.Above * i; var segment = new Segment(segmentManager, segCoords); var array = new Cube[16, 16, 16]; for (Byte x = 0; x < 16; x++) { for (Byte y = 0; y < 16; y++) { for (Byte z = 0; z < 16; z++) { // Minecraft has different x/y directions so we must reverse z so the world isn't mirrored AlphaBlock block = chunk.Blocks.GetBlock(15 - z, y + i * 16, x); UInt32 mcIdData = (UInt32)block.ID << 16 | (UInt16)block.Data; Cube cube; if (!_mcIdDataToFCECube.TryGetValue(mcIdData, out cube)) { cube = new Cube(1, 0, 0, 0); if (!UnknownBlocks.ContainsKey((UInt16)block.ID)) { UnknownBlocks.Add((UInt16)block.ID, block.Info.Name); } } array[z, y, x] = cube; } } } segment.CubeData = array; _segmentsLeft--; _saveQueue.Enqueue(segment); } // Pad the area above the converted world with 11 blank segments to prevent world gen from occuring // Possibly replace this in the future with simply shifting the world up for (Int32 i = (anvil ? 16 : 8); i < 27; i++) { var padding = new Segment(segmentManager, chunkCoords + SegmentCoords.Above * i); padding.CubeData = Segment.GetBlankSegment().CubeData; padding.IsEmpty = true; _saveQueue.Enqueue(padding); } } Task.WaitAll(_saveTask); return(fceWorld); }
static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("Usage: MinecraftExport <type> <target_dir>"); Console.WriteLine("Available Types: alpha, beta, anvil"); return; } string dest = args [1]; int xmin = 0; int xmax = 1; int zmin = -200; int zmaz = 200; NbtVerifier.InvalidTagType += (e) => { throw new Exception("Invalid Tag Type: " + e.TagName + " [" + e.Tag + "]"); }; NbtVerifier.InvalidTagValue += (e) => { throw new Exception("Invalid Tag Value: " + e.TagName + " [" + e.Tag + "]"); }; NbtVerifier.MissingTag += (e) => { throw new Exception("Missing Tag: " + e.TagName); }; if (!Directory.Exists(dest)) { Directory.CreateDirectory(dest); } // This will instantly create any necessary directory structure NbtWorld world; switch (args [0]) { case "alpha": world = AlphaWorld.Create(dest); break; case "beta": world = BetaWorld.Create(dest); break; case "anvil": world = AnvilWorld.Create(dest); break; default: throw new Exception("Invalid world type specified."); } IChunkManager cm = world.GetChunkManager(); // We can set different world parameters world.Level.LevelName = "Tychaia"; world.Level.Spawn = new SpawnPoint(20, 70, 20); world.Level.GameType = GameType.CREATIVE; world.Save(); // world.Level.SetDefaultPlayer(); // We'll let MC create the player for us, but you could use the above // line to create the SSP player entry in level.dat. // We'll create chunks at chunk coordinates xmin,zmin to xmax,zmax for (int xi = xmin; xi < xmax; xi++) { for (int zi = zmin; zi < zmaz; zi++) { // This line will create a default empty chunk, and create a // backing region file if necessary (which will immediately be // written to disk) ChunkRef chunk = cm.CreateChunk(xi, zi); // This will suppress generating caves, ores, and all those // other goodies. chunk.IsTerrainPopulated = true; // Auto light recalculation is horrifically bad for creating // chunks from scratch, because we're placing thousands // of blocks. Turn it off. chunk.Blocks.AutoLight = false; // Set the blocks FlatChunk(chunk, 64); // Reset and rebuild the lighting for the entire chunk at once chunk.Blocks.RebuildHeightMap(); chunk.Blocks.RebuildBlockLight(); chunk.Blocks.RebuildSkyLight(); double total = (xmax - xmin) * (zmaz - zmin); double current = (zi - zmin) + (xi - xmin) * (zmaz - zmin); Console.WriteLine("Built Chunk {0},{1} ({2}%)", chunk.X, chunk.Z, current / total * 100); // Save the chunk to disk so it doesn't hang around in RAM cm.Save(); } } // Save all remaining data (including a default level.dat) // If we didn't save chunks earlier, they would be saved here world.Save(); }
public override void Initialise(VoxelTypeManager voxelTypeManager, IChunkManager chunkManager, FrameworkEventManager eventManager) { base.Initialise(voxelTypeManager, chunkManager, eventManager); dirtID = voxelTypeManager.GetId(dirtType); grassID = voxelTypeManager.GetId(grassType); }
public DualContourDeferredColoredChunkSystem(GraphicsDevice device, ContentLibrary contentLibrary, IChunkManager chunkManager, CameraManager cameraManager, World world, ITerrainGradientFunction densityGradientFunction, float minimumSolidDensity) { _builder = new DualContourChunkBuilder(device, world, densityGradientFunction, minimumSolidDensity); _renderer = new DeferredColoredChunkRenderer(world.EngineConfiguration, contentLibrary, device, cameraManager, chunkManager); }
public AnvilBlockManager(IChunkManager chunkManager) { _chunkCache = chunkManager; }
public override void Run() { NbtWorld world = NbtWorld.Open(opt.OPT_WORLD); IChunkManager cm = world.GetChunkManager(opt.OPT_DIM); FilteredChunkManager fcm = new FilteredChunkManager(cm, opt.GetChunkFilter()); if (opt.OPT_V) { Console.WriteLine("Clearing existing chunk lighting..."); } int affectedChunks = 0; foreach (ChunkRef chunk in fcm) { if (opt.OPT_VV) { Console.WriteLine("Resetting chunk {0},{1}...", chunk.X, chunk.Z); } if (opt.HeightMap) { chunk.Blocks.RebuildHeightMap(); } if (opt.BlockLight) { chunk.Blocks.ResetBlockLight(); } if (opt.SkyLight) { chunk.Blocks.ResetSkyLight(); } fcm.Save(); affectedChunks++; } if (opt.OPT_V) { Console.WriteLine("Rebuilding chunk lighting..."); } foreach (ChunkRef chunk in fcm) { if (opt.OPT_VV) { Console.WriteLine("Lighting chunk {0},{1}...", chunk.X, chunk.Z); } if (opt.BlockLight) { chunk.Blocks.RebuildBlockLight(); } if (opt.SkyLight) { chunk.Blocks.RebuildSkyLight(); } fcm.Save(); } if (opt.OPT_V) { Console.WriteLine("Reconciling chunk edges..."); } foreach (ChunkRef chunk in fcm) { if (opt.OPT_VV) { Console.WriteLine("Stitching chunk {0},{1}...", chunk.X, chunk.Z); } if (opt.BlockLight) { chunk.Blocks.StitchBlockLight(); } if (opt.SkyLight) { chunk.Blocks.StitchSkyLight(); } fcm.Save(); } Console.WriteLine("Relit Chunks: " + affectedChunks); }
public FilteredChunkManager(IChunkManager cm, IChunkFilter filter) { _cm = cm; _filter = filter; }
/// <summary> /// /// </summary> /// <typeparam name="TEntity"></typeparam> /// <typeparam name="TAggregation"></typeparam> /// <param name="manager"></param> public void SetChunkManager <TEntity, TAggregation>(IChunkManager <TEntity, TAggregation> manager) where TEntity : IChunkEntity { ChunkManager = (IChunkManager <Boid, AggregatedBoidChunk>)manager; }