示例#1
0
    void Initiate()
    {
        ChunkGenerator generator = target as ChunkGenerator;

        layersInfo = generator.layersInfo;
        if (layersInfo.Count > 0)
        {
            return;
        }
        else
        {
            Debug.Log("Count less or equal to 0");
        }
        generator.layersInfo = new List <ChunkGenerator.LayerSectionInformation>();
        for (int i = 0; i < 10; i++)
        {
            generator.layersInfo.Add(new ChunkGenerator.LayerSectionInformation());
        }

        if (generator.levelLayers.Count > 0)
        {
            return;
        }
        generator.levelLayers = new List <LevelLayer>(0);
        for (int i = 0; i < 10; i++)
        {
            generator.levelLayers.Add(new LevelLayer());
        }
    }
示例#2
0
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();
        Initiate();
        if (GUILayout.Button("Scan"))
        {
            ScanForLayers();
        }
        if (GUILayout.Button("Instantiate"))
        {
            Generate();
        }
        ChunkGenerator generator = target as ChunkGenerator;

        for (int i = 0; i < 10; i++)
        {
            if (generator.visibleLayers[i])
            {
                CreateLayerSection(i);
            }
            else
            {
                CreateMiniLevelSection(i);
            }
        }
    }
    /// <summary>
    /// render the chunk at the given position, this assumes that the chunk has been generated beforehand,
    /// if not it will call CreateChunk on it... as a safeguard...
    /// and it will create the chunks on each side of this, to be able to render the edges of this chunk properly
    /// </summary>
    /// <param name="pos">position of the chunk</param>
    public IEnumerator RenderChunk(ChunkPos pos)
    {
        generatingChunk = true;
        ChunkGenerator chunk = null;

        chunkDictionary.TryGetValue(pos, out chunk);

        if (chunk == null)
        {
            CreateChunk(pos);
            chunkDictionary.TryGetValue(pos, out chunk);
        }

        //generate the chunks on each side of the chunk, no need to render them, just generate, this is needed to calculate the edges of a chunk
        List <ChunkPos> positionsAroundTheChunk = new List <ChunkPos>();//why a list? why not, faster than arrays, and pretty syntax

        positionsAroundTheChunk.Add(new ChunkPos(pos.x + 1, pos.z));
        positionsAroundTheChunk.Add(new ChunkPos(pos.x - 1, pos.z));
        positionsAroundTheChunk.Add(new ChunkPos(pos.x, pos.z + 1));
        positionsAroundTheChunk.Add(new ChunkPos(pos.x, pos.z - 1));


        foreach (ChunkPos posToGen in positionsAroundTheChunk)
        {
            //make a new thread for each chunk needed to be generated
            CreateChunk(posToGen);
            yield return(new WaitForSeconds(0.1f));
        }


        yield return(new WaitForSeconds(0.05f)); //wait a short while

        chunk.Render();
        generatingChunk = false;
    }
示例#4
0
 private void Awake()
 {
     if (Instance == null)
     {
         Instance = this;
     }
 }
示例#5
0
    public static ChunkGenerator Create(World world, Vector2Int chunkPos)
    {
        if (chunkPos.x >= 0 && chunkPos.x <= world.width)
        {
            if (chunkPos.y >= 0 && chunkPos.y <= world.height)
            {
                GameObject chunkObject = new GameObject();
                chunkObject.name = "Chunk(" + chunkPos.x + ", " + chunkPos.y + ")";
                float chunkWorldSpaceInterval = (float)(world.chunkSize * world.tileSize) / 100;
                chunkObject.transform.position = chunkPos * new Vector2(chunkWorldSpaceInterval, chunkWorldSpaceInterval);

                SpriteRenderer sr = chunkObject.AddComponent<SpriteRenderer>();
                sr.sortingOrder = -1;

                ChunkGenerator cg = chunkObject.AddComponent<ChunkGenerator>();
                cg.world = world;
                cg.chunkPos = chunkPos;
                cg.chunkBiomeLayers = new BiomeLayer[world.chunkSize, world.chunkSize];
                cg.chunkTileTextures = new Texture2D[world.chunkSize, world.chunkSize];
                cg.chunkSpawnableFeatures = new SpawnableFeature[world.chunkSize, world.chunkSize];

                cg.chunkTexture = new Texture2D(world.chunkSize * world.tileSize, world.chunkSize * world.tileSize, TextureFormat.ARGB32, false);
                cg.chunkTexture.filterMode = FilterMode.Point;
                sr.sprite = Sprite.Create(cg.chunkTexture, new Rect(Vector2.zero, new Vector2(world.chunkSize * world.tileSize, world.chunkSize * world.tileSize)), Vector2.zero);

                cg.chunk = new Chunk(world, chunkPos);

                return cg;
            }
        }
        return null;
    }
示例#6
0
    public WorldChunkManager()
    {
        instance = this;

        chunkGenerator = new ChunkGenerator();

        chunkGenerator.GenerateWorld();

        Player.creatureManager.OnChunkPositionsVisibilityGained += (List <Vector2DInt> inSightedChunkPositions) => {
            foreach (Vector2DInt sightedChunkPosition in inSightedChunkPositions)
            {
                if (!_loadedChunks.ContainsKey(sightedChunkPosition))
                {
                    _loadedChunks.Add(sightedChunkPosition, chunkGenerator.LoadChunk(sightedChunkPosition));
                }
            }
        };

        Player.creatureManager.OnChunkPositionsVisibilityLost += (List <Vector2DInt> inLostVisibleChunks) => {
            foreach (Vector2DInt lostChunkPosition in inLostVisibleChunks)
            {
                if (_loadedChunks.ContainsKey(lostChunkPosition))
                {
                    chunkGenerator.UnloadChunk(_loadedChunks[lostChunkPosition]);
                    _loadedChunks.Remove(lostChunkPosition);
                }
            }
        };
    }
示例#7
0
    public MapHandler(World world, Vector2I startingPosition)
    {
        _activeSectors = new List <Sector>();
        _generator     = new ChunkGenerator();
        _saving        = new Queue <Sector>();
        _loading       = new Queue <Vector2I>();
        _world         = world;

        // Work out the bottom left corner from the starting chunk
        int      half         = (_loadedDimension - 1) / 2;
        Vector2I cornerSector = BlockUtil.SectorFromChunk(startingPosition) + new Vector2I(-half, -half);

        Debug.Log("Setting corner to " + cornerSector);

        // Set the starting position
        _position = cornerSector;

        // Create the initial sectors
        for (int i = 0; i < _loadedDimension; i++)
        {
            for (int j = 0; j < _loadedDimension; j++)
            {
                Vector2I pos    = _position + new Vector2I(i, j);
                Sector   sector = getSector(pos);
                _activeSectors.Add(sector);
            }
        }

        updatePosition(startingPosition);
    }
示例#8
0
    public World(IsometricGame game, string worldName)
    {
        _game      = game;
        _worldName = worldName;

        _worldCamera = new WorldCamera(this);

        _worldTime = 0f;

        _chunkGenerator = new ChunkGenerator(this);
        _chunks         = new LinkedList <Chunk>();
        _chunkMap       = new Dictionary <int, Chunk>(256);

        _cosmeticDrawables = new LinkedList <CosmeticRenderer>();

        _targets = new List <ITarget>();

        player = new Player();

        _cameraHUD = new CameraHUDMenu(_game, _worldCamera);
        game.AddSubLoopFlow(_cameraHUD);

        _worldProfiler = new WorldProfiler(this);

        _epicenters = new Queue <Vector4>(NumMaxEpicenters);
        UpdateEpicenters();
    }
示例#9
0
 // Getter for CubeEditor by it's position
 public CubeEditor GetCubeEditorByVector(Vector3 cubeEditorPos)
 {
     if (cubeEditorTable.ContainsKey(cubeEditorPos))
     {
         return(cubeEditorTable[cubeEditorPos]);
     }
     else
     {
         for (int i = 0; i < 4; i++)
         {
             Vector3        neighbourChunkPos = transform.position + directions[i];
             ChunkGenerator neighbourChunk    = worldManager.GetChunkGeneratorByVector(neighbourChunkPos);
             if (neighbourChunk == null)
             {
                 continue;
             }
             cubeEditorPos = TransformCubeToNeighbourPos(cubeEditorPos);
             if (!neighbourChunk.cubeEditorTable.ContainsKey(cubeEditorPos))
             {
                 continue;
             }
             CubeEditor neighbourCube = neighbourChunk.cubeEditorTable[cubeEditorPos];
             return(neighbourCube);
         }
     }
     return(null);
 }
示例#10
0
 private void GenerateBlocks(Vector3 pos)
 {
     if (Singleton <WorldRunner> .Instance.CurrentChunk.Value.Index < 20 && PlayerData.Instance.LifetimePrestiges.Value <= 0)
     {
         string     chunkPrefabPath = GetChunkPrefabPath(Singleton <WorldRunner> .Instance.CurrentChunk.Value.Index);
         GameObject gameObject      = GameObjectExtensions.InstantiateFromResources(chunkPrefabPath, pos, Quaternion.identity);
         ChunkGenerator.GenerateFromPlaceholders(gameObject, BindingManager.Instance.BlockContainer);
         UnityEngine.Object.DestroyImmediate(gameObject);
         CalculateBlocksAndGoldBlocks();
     }
     else if (PersistentSingleton <ARService> .Instance.ARLevel.Value != null && (Singleton <WorldRunner> .Instance.CurrentChunk.Value.Index % 5 == 2 || PersistentSingleton <ARService> .Instance.ShowCustomLevel.Value))
     {
         CustomLevel.Value = true;
         ChunkGenerator.GenerateFromCustomLevel(PersistentSingleton <ARService> .Instance.ARLevel.Value, pos, BindingManager.Instance.BlockContainer);
         PersistentSingleton <ARService> .Instance.ShowCustomLevel.Value = false;
     }
     else
     {
         CustomLevel.Value = false;
         ChunkGenerator.GenerateFromConfig(pos, Singleton <WorldRunner> .Instance.CurrentChunk.Value.Index, PlayerData.Instance.LifetimePrestiges.Value, PlayerData.Instance.RetryLevelNumber.Value, BindingManager.Instance.BlockContainer, bossFight: false);
     }
     (from moving in Singleton <CameraMoveRunner> .Instance.IsCameraMoving
      where !moving
      select moving).Take(1).Subscribe(delegate
     {
         CalculateChunkHealth();
     }).AddTo(SceneLoader.Instance);
 }
    void Start()
    {
        values = new Vector4[terrainSize.x * terrainSize.y * terrainSize.z];
        bounds = new Bounds(gameObject.transform.position, (terrainSize - Vector3.one) * gridSize);

        //initializes the positions, sets all the points values to 0, except the ones on the bottom layer, whose value gets set to 1
        for (int x = 0; x < terrainSize.x; x++)
        {
            for (int y = 0; y < terrainSize.y; y++)
            {
                for (int z = 0; z < terrainSize.z; z++)
                {
                    values[Utility.XYZtoIndex(x, y, z, terrainSize)] = Utility.Vector4FromVector3andValue(Utility.CalculatePointPosition(new Vector3Int(x, y, z), gameObject.transform.position, gridSize, terrainSize), 0);
                    if (y == 0)
                    {
                        values[Utility.XYZtoIndex(x, y, z, terrainSize)].w = 1;
                    }
                }
            }
        }

        if (Camera.current != null)
        {
            rayDistance = Mathf.Sqrt(bounds.SqrDistance(Camera.current.transform.position));
        }

        terrainChunkData = ChunkGenerator.Generate(values, terrainSize, surfaceLevel, true);
        CreateChunks();
    }
示例#12
0
    void LateUpdate()
    {
        float cameraMinX = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, transform.position.z - Camera.main.transform.position.z)).x;
        float cameraMaxX = Camera.main.ViewportToWorldPoint(new Vector3(1, 0, transform.position.z - Camera.main.transform.position.z)).x;

        // Delete old chunk
        foreach (GameObject c in GetChunksToRemove())
        {
            Destroy(c);
        }

        // Create new chunk
        for (float x = Mathf.Floor((cameraMinX - chunkOffset) / chunkWidth) * chunkWidth; x < Mathf.Ceil((cameraMaxX + chunkOffset) / chunkWidth) * chunkWidth; x += chunkWidth)
        {
            if (!IsChunkInInterval(x, x + chunkWidth))
            {
                GameObject     chunk     = Instantiate(chunkPrefab) as GameObject;
                ChunkGenerator generator = chunk.AddComponent <ChunkGenerator>() as ChunkGenerator;
                chunk.transform.parent        = transform;
                chunk.transform.localPosition = new Vector2(x, 0);
                generator.size        = new Vector2(chunkWidth, 0);
                generator.a0          = GetRandomValue(transform.position + new Vector3(x, 0f, 0f), 2);
                generator.a1          = GetRandomValue(transform.position + new Vector3(x + chunkWidth, 0f, 0f), 2);
                generator.iterations  = 11;
                generator.depth       = 1;
                generator.chunkPrefab = chunkPrefab;
                generator.collidable  = collidable;
                generator.offset      = chunkOffset;
            }
        }
    }
示例#13
0
 public static void LoadMap()
 {
     foreach (Chunk chunk in MapData.ChunkObjects)
     {
         ChunkGenerator.RenderChunk(chunk);
     }
 }
    //note i dont want this to be a co-routine because... well... its fairly simple
    /// <summary>
    /// create a chunk if it doesn't exist
    /// </summary>
    /// <param name="pos">position of the chunk</param>
    public void CreateChunk(ChunkPos pos)
    {
        generatingChunk = true;
        ChunkGenerator chunkGen = null;

        chunkDictionary.TryGetValue(pos, out chunkGen);


        if (chunkGen == null)
        {
            //instantiate a chunk at the calculated position

            GameObject chunkObj = (GameObject)Instantiate(chunk, new Vector3(pos.x * chunkSize, 0f, pos.z * chunkSize), Quaternion.identity);
            chunkObj.transform.parent = transform;

            int actualChunkX = pos.x * chunkSize;
            int actualChunkZ = pos.z * chunkSize;

            //add the chunk object spawned to the dictionary... well the ChunkGenerator script part of the object anyways
            chunkDictionary.Add(pos, chunkObj.GetComponent <ChunkGenerator>());

            chunkObj.GetComponent <ChunkGenerator>().init(chunkSize, actualChunkX, actualChunkZ);

            chunkObj.name = "chunk_x" + pos.x + "_z" + pos.z; // set the name property to know where it is in the world through the inspector
//            Debug.Log("derped out around here, name:" + chunkObj.name);
        }

        generatingChunk = false;
    }
示例#15
0
    void InstantiateChunk(int x, int y)
    {
        ChunkGenerator chunk = Instantiate(chunkObject, new Vector3(64 * x, 0, -64 * y), Quaternion.identity);

        chunk.coordX = x;
        chunk.coordY = y;
    }
示例#16
0
    void Start()
    {
        ChunkGenerator generator = GetComponent <ChunkGenerator>() as ChunkGenerator;

        if (generator.depth == 0)
        {
            Vector2 p0  = Vector2.zero;
            Vector2 p3  = generator.size;
            float   dis = Vector2.Distance(p0, p3) / 2;
            Vector2 p1  = p0 + (new Vector2(1, generator.a0)).normalized * dis;
            Vector2 p2  = p3 - (new Vector2(1, generator.a1)).normalized * dis;

            List <Vector2> topline    = new List <Vector2>();
            List <Vector2> bottomline = new List <Vector2>();
            foreach (Vector2 v in BezierCurver.Generate((int)(generator.size.x / precision), p0, p1, p2, p3))
            {
                topline.Add(v);
            }
            foreach (Vector2 v in BezierCurver.Generate((int)(generator.size.x / precision), p0 + Vector2.down * thickness, p1 + Vector2.down * thickness, p2 + Vector2.down * thickness, p3 + Vector2.down * thickness))
            {
                bottomline.Add(v);
            }

            GetComponent <MeshFilter>().mesh = createMesh(topline.ToArray(), bottomline.ToArray());

            GetComponent <EdgeCollider2D>().points = topline.ToArray();
            if (!generator.collidable)
            {
                GetComponent <EdgeCollider2D>().isTrigger = true;
            }
        }
    }
示例#17
0
    void Start()
    {
        GameManager.Instance.WorldGenerator = this;

        lastChunkPosX    = -1;
        readyForChunks   = false;
        chunkWidth       = 50;
        chunkHeight      = 14;
        chunkShapes      = new List <BaseChunkShape>();
        biomes           = new List <BaseBiome>();
        chunkGenerator   = new ChunkGenerator();
        coinGenerator    = new CoinGenerator();
        powerupGenerator = new PowerupGenerator();
        enemyGenerator   = new EnemyGenerator();
        worldChunkPrefab = Resources.Load("WorldChunkPrefab");
        platformPrefab   = Resources.Load("Platform_Prefab");
        tilePrefab       = Resources.Load("Tile_Prefab");

        chunkShapes.Add(new FlatShape());
        chunkShapes.Add(new FlatShape2());
        chunkShapes.Add(new PowerupShape1());
        chunkShapes.Add(new GapyShape1());
        chunkShapes.Add(new GapyShape2());
        chunkShapes.Add(new ChrisShape1());

        biomes.Add(new GrassBiome());
        biomes.Add(new CaveBiome());
        biomes.Add(new StormyBiome());
        biomes.Add(new LavaCaveBiome());
        biomes.Add(new WesternBiome());

        GameManager.Instance.ResetGame();
    }
示例#18
0
 private static void CleanChunks()
 {
     while (instance._dirtyChunks.Count > 0)
     {
         ChunkGenerator.RenderChunk(instance._dirtyChunks.Dequeue());
     }
 }
示例#19
0
 // gets called when this cube is being destroyed
 // Refreshes other surrounding cubes
 private void AdjustNeighbours()
 {
     for (int i = 0; i < 6; i++)
     {
         Vector3 neighbourCube = transform.position + directions[i];
         if (cubeParent == null)
         {
             print("getting parent"); cubeParent = GetComponentInParent <ChunkGenerator>();
         }
         CubeEditor temporaryCubeEditor = cubeParent.GetCubeEditorByVector(neighbourCube);
         if (temporaryCubeEditor == null)
         {
             continue;
         }
         if (temporaryCubeEditor.childTable.ContainsKey(-directions[i]))
         {
             temporaryCubeEditor.childTable[-directions[i]].gameObject.SetActive(true);
         }
         else
         {
             temporaryCubeEditor = cubeParent.GetEditorFromNeighbourChunk(neighbourCube);
             if (temporaryCubeEditor == null)
             {
                 continue;
             }
             if (temporaryCubeEditor.childTable.ContainsKey(-directions[i]))
             {
                 temporaryCubeEditor.HideTransformByVector(-directions[i]);
             }
         }
     }
 }
示例#20
0
 void Awake()
 {
     generator           = new ChunkGenerator(new QuadMapper(), function);
     gameObjectGenerator = new GameObjectGenerator(new PlaneMeshGenerator(scale), this.transform, material);
     map        = new Map(grid, 20, generator, gameObjectGenerator);
     map.player = player;
 }
示例#21
0
    /* Start, Update */
    void Start()
    {
        _chunkGenerator       = GetComponent <ChunkGenerator>();
        _biomeManager         = GetComponent <BiomeManager>();
        _chunkObjectGenerator = GetComponent <ChunkObjectGenerator>();

        _cameraControllerTransform = Camera.main.transform.parent;
    }
示例#22
0
 private void Start()
 {
     REQUIREDDELAY    = new WaitForSeconds(_REQUIREDDELAY);
     chunkGenerator   = FindObjectOfType <ChunkGenerator>();
     particleLifetime = new WaitForSeconds(_particleLifetime);
     sfx = GetComponents <AudioSource>();
     // create the waitforseconds
 }
示例#23
0
 public override bool Equals(object obj)
 {
     return(obj is Span other &&
            Kind.Equals(other.Kind) &&
            EditHandler.Equals(other.EditHandler) &&
            ChunkGenerator.Equals(other.ChunkGenerator) &&
            Tokens.SequenceEqual(other.Tokens, SyntaxTokenComparer.Default));
 }
示例#24
0
    void LateUpdate()
    {
        if (depth > 0)
        {
            // Delete old
            foreach (GameObject chunk in GetChunksToRemove())
            {
                Destroy(chunk);
            }

            // Create new
            Vector2 p0  = Vector2.zero;
            Vector2 p3  = size;
            float   dis = Vector2.Distance(p0, p3) / 2;
            Vector2 p1  = (new Vector2(1, a0)).normalized * dis;
            Vector2 p2  = (new Vector2(1, a1)).normalized * dis;

            Vector2[] points = BezierCurver.Generate(iterations, p0, p1, p2, p3);

            for (int i = 0; i < points.Length - 1; i++)
            {
                Vector2 pointSize = points[i + 1] - points[i];
                if (IsIntervalVisible(points[i].x - offset, points[i].x + pointSize.x + offset) &&
                    !IsChunkInInterval(points[i].x, points[i].x + pointSize.x))
                {
                    GameObject     chunk     = Instantiate(chunkPrefab) as GameObject;
                    ChunkGenerator generator = chunk.AddComponent <ChunkGenerator>() as ChunkGenerator;
                    chunk.transform.parent        = transform;
                    chunk.transform.localPosition = points[i];
                    generator.size = pointSize;
                    if (i == 0)
                    {
                        generator.a0 = a0;
                    }
                    else
                    {
                        generator.a0 = (points[i + 1].y - points[i - 1].y) / (points[i + 1].x - points[i - 1].x);
                    }

                    if (i == points.Length - 2)
                    {
                        generator.a1 = a1;
                    }
                    else
                    {
                        generator.a1 = (points[i + 2].y - points[i].y) / (points[i + 2].x - points[i].x);
                    }
                    generator.a0         += GetRandomValue(transform.position + new Vector3(points[i].x, points[i].y, 0f), generator.depth);
                    generator.a1         += GetRandomValue(transform.position + new Vector3(points[i + 1].x, points[i + 1].y, 0f), generator.depth);
                    generator.iterations  = 5;
                    generator.depth       = depth - 1;
                    generator.chunkPrefab = chunkPrefab;
                    generator.collidable  = collidable;
                    generator.offset      = offset;
                }
            }
        }
    }
示例#25
0
    /// <summary>
    /// Calls the hydraulic erosion method to perform erosion on the chunkData's heightmap
    /// </summary>
    /// <param name="generator">The ChunkGenerator object which holds the array of chunkData objects</param>
    /// <param name="c">The chunkData object to perform erosion on</param>
    private static void HydraulicErosion(ChunkGenerator generator, ChunkData c)
    {
        c.SetHeightMap(generator.GetComponent <HydraulicAction> ().Erode(c));

        /*
         *      The hydraulic erosion algorithm requires the entire ChunkData object, not just the
         *      terrain heightmap. This is because it needs access to the heat and rainfall maps too.
         */
    }
示例#26
0
        private void SetupLevelController(GameConfig config, LevelConfig levelConfig)
        {
            levelScroller?.Destroy();
            var container = transform;
            var pool      = new LevelObjectsPool(levelConfig, 2, container);
            var generator = new ChunkGenerator(levelConfig, pool, config.chunkGraphLength, config.chunkGraphWidth);

            levelScroller = new LevelScroller(generator, container);
        }
示例#27
0
    private IEnumerator BuildChunk(Vector3 chunkWorldPosition)
    {
        byte i = 0;

        for (byte x = 0; x < WorldGenerator.CHUNK_SIZE; x++)
        {
            float blockWorldPositionX = chunkWorldPosition.x + x * WorldGenerator.BLOCK_SIZE;
            float noiseX = blockWorldPositionX / WorldGenerator.CHUNK_SIZE;
            for (byte z = 0; z < WorldGenerator.CHUNK_SIZE; z++)
            {
                if (i > 8)
                {
                    i = 0;
                    yield return(null);
                }
                i++;
                float blockWorldPositionZ = chunkWorldPosition.z + z * WorldGenerator.BLOCK_SIZE;
                float noiseZ = blockWorldPositionZ / WorldGenerator.CHUNK_SIZE;

                /*
                 * TODO: We can optimize this later by first checking all 4 chunk pages.
                 * If all are in the same region, all blocks in that chunk are in the same region.
                 */
                float deltaVoronoi = (float)ChunkGenerator.NoiseGenerator
                                     .Eval(noiseX / 4, noiseZ / 4) * 32;
                Region region = ChunkGenerator.GetNearestRegion(
                    blockWorldPositionX + deltaVoronoi,
                    blockWorldPositionZ + deltaVoronoi
                    );

                float noise = (float)ChunkGenerator.NoiseGenerator.Octave(
                    numIterations: 6,
                    x: noiseX,
                    y: noiseZ,
                    persistence: 0.6f,
                    scale: 0.05f,
                    low: 0,
                    high: 64
                    );

                for (byte y = 0; y < noise; y++)
                {
                    Block block = new Block(
                        name: $"Block x:{x}, y:{y}, z:{z}",
                        chunk: this,
                        blockID: new Vector3Int(x, y, z),
                        region: region
                        );

                    data.Add(block.BlockID, block);
                }
            }
        }

        Dirty = true;
    }
示例#28
0
 private void Awake()
 {
     mainCamera.enabled    = true;
     minimapCamera.enabled = false;
     chunkGenerator        = FindObjectOfType <ChunkGenerator>();
     player  = FindObjectOfType <Player>();
     mapRect = new Rect(0, 0, mapSize, mapSize);
     seed    = chunkGenerator.seed;
     // assign various things needed later on
 }
示例#29
0
文件: Span.cs 项目: yuxi214/Razor
        public override bool Equals(object obj)
        {
            var other = obj as Span;

            return(other != null &&
                   Kind.Equals(other.Kind) &&
                   EditHandler.Equals(other.EditHandler) &&
                   ChunkGenerator.Equals(other.ChunkGenerator) &&
                   Symbols.SequenceEqual(other.Symbols));
        }
示例#30
0
    void Start()
    {
        _camTransform = Camera.main.transform;

        _parameters = GetComponent <Noise>().parameters;

        _chunkGenerator = new ChunkGenerator(_parameters);

        JobSystem.Initialize();
    }
示例#31
0
    void Start () {
        player = GameObject.FindGameObjectWithTag("Player");
        tree_manager = gameObject.GetComponent<TreeManager>();
        chunkGen = gameObject.GetComponent<ChunkGenerator>();
        weather_manager = gameObject.GetComponent<WeatherManager>();
        shrine_manager = gameObject.GetComponent<ShrineManager>();
        chunkGen.chunk_size = chunk_size;
        chunkGen.chunk_resolution = chunk_resolution;
        cur_chunk = new Vector2(-1, -1);
        loaded_chunks = new List<Vector2>();
        loaded_tree_chunks = new List<Vector2>();
		loaded_shrine_chunks = new List<Vector2>();
    }
示例#32
0
    public static void SaveChunk(ChunkGenerator Chunk)
    {
        /*
        string saveFile = SaveLocation(worldName);
        ChunkPos CP = new ChunkPos((int)Chunk.actualChunkCoords.x / Chunk.GetChunkSize(), (int)Chunk.actualChunkCoords.z / Chunk.GetChunkSize());
        saveFile += saveFileName(CP);

        IFormatter formatter = new BinaryFormatter(); //new binary formatter to format serialized input to binary output (for bin save files)
        Stream stream = new FileStream(saveFile, FileMode.Create, FileAccess.Write, FileShare.None); //filestream that writes into saveFile, creates it first ofc, and doesn't share it with anyone >=)

        formatter.Serialize(stream, Chunk.Blocks);

        stream.Close();//always close the stream! always!*/
    }
示例#33
0
    public static bool LoadChunk(ChunkGenerator Chunk)
    {
        return false;
        /*
        string saveFile = SaveLocation(worldName);
        ChunkPos CP = new ChunkPos((int)Chunk.actualChunkCoords.x / Chunk.GetChunkSize(), (int)Chunk.actualChunkCoords.z / Chunk.GetChunkSize());
        saveFile += saveFileName(CP);
        if (!File.Exists(saveFile))
        {
            return false;
        }
        //new binaryformatter to format binary input to serialized output(bin file -> useable stuff)
        IFormatter formatter = new BinaryFormatter();
        //filestream to read from saveFile, it opens it, reads from it, and blocks any other attempt to access it while its reading...
        //probably doesn't need to block access to it when its reading? but meh
        Stream stream = new FileStream(saveFile, FileMode.Open, FileAccess.Read, FileShare.None);

        Chunk.Blocks = (BlockData[, ,])formatter.Deserialize(stream);

        stream.Close(); //always close the stream! always!
        return true;*/
    }
示例#34
0
    public virtual MeshData Blockdata(ChunkGenerator chunk, int x, int y, int z, MeshData meshData)
    {
        if (type != BlockType.air)
        {
            if (!chunk.getBlockAt(x, y + 1, z).IsSolid(Direction.down))
            {
                meshData = FaceDataUp(chunk, x, y, z, meshData);
            }

            if (!chunk.getBlockAt(x, y - 1, z).IsSolid(Direction.up))
            {
                meshData = FaceDataDown(chunk, x, y, z, meshData);
            }

            if (!chunk.getBlockAt(x, y, z + 1).IsSolid(Direction.south))
            {
                meshData = FaceDataNorth(chunk, x, y, z, meshData);
            }

            if (!chunk.getBlockAt(x, y, z - 1).IsSolid(Direction.north))
            {
                meshData = FaceDataSouth(chunk, x, y, z, meshData);
            }

            if (!chunk.getBlockAt(x + 1, y, z).IsSolid(Direction.west))
            {
                meshData = FaceDataEast(chunk, x, y, z, meshData);
            }

            if (!chunk.getBlockAt(x - 1, y, z).IsSolid(Direction.east))
            {
                meshData = FaceDataWest(chunk, x, y, z, meshData);
            }
        }
        return meshData;
    }
示例#35
0
        public ChunkManager(ContentManager content, 
            uint chunkSizeX, uint chunkSizeY, uint chunkSizeZ,
            Camera camera, GraphicsDevice graphics, Texture2D tilemap,
            Texture2D illumMap, Texture2D sunMap, Texture2D ambientMap,
            Texture2D torchMap, ChunkGenerator chunkGen, int maxChunksX, int maxChunksY, int maxChunksZ)
        {
            KilledVoxels = new List<Voxel>();
            ExitThreads = false;
            drawDistSq = DrawDistance * DrawDistance;
            Content = content;

            chunkData = new ChunkData(chunkSizeX, chunkSizeY, chunkSizeZ, 1.0f / chunkSizeX, 1.0f / chunkSizeY, 1.0f / chunkSizeZ, tilemap, illumMap, this);
            ChunkData.ChunkMap = new ConcurrentDictionary<Point3, VoxelChunk>();
            RenderList = new ConcurrentQueue<VoxelChunk>();
            RebuildList = new ConcurrentQueue<VoxelChunk>();
            RebuildLiquidsList = new ConcurrentQueue<VoxelChunk>();
            ChunkGen = chunkGen;

            GeneratedChunks = new ConcurrentQueue<VoxelChunk>();
            GeneratorThread = new Thread(GenerateThread);

            RebuildThread = new Thread(RebuildVoxelsThread);
            RebuildLiquidThread = new Thread(RebuildLiquidsThread);

            WaterThread = new Thread(UpdateWaterThread);

            ToGenerate = new List<Point3>();
            Graphics = graphics;

            chunkGen.Manager = this;

            ChunkData.MaxViewingLevel = chunkSizeY;

            GameSettings.Default.ChunkGenerateTime = 0.5f;
            generateChunksTimer = new Timer(GameSettings.Default.ChunkGenerateTime, false, Timer.TimerMode.Real);
            GameSettings.Default.ChunkRebuildTime = 0.1f;
            Timer rebuildChunksTimer = new Timer(GameSettings.Default.ChunkRebuildTime, false, Timer.TimerMode.Real);
            GameSettings.Default.VisibilityUpdateTime = 0.05f;
            visibilityChunksTimer = new Timer(GameSettings.Default.VisibilityUpdateTime, false, Timer.TimerMode.Real);
            generateChunksTimer.HasTriggered = true;
            rebuildChunksTimer.HasTriggered = true;
            visibilityChunksTimer.HasTriggered = true;
            this.camera = camera;

            Water = new WaterManager(this);

            ChunkData.SunMap = sunMap;
            ChunkData.AmbientMap = ambientMap;
            ChunkData.TorchMap = torchMap;

            DynamicLights = new List<DynamicLight>();

            ChunkData.Slice = SliceMode.Y;
            PauseThreads = false;

            WorldSize = new Point3(maxChunksX, maxChunksY, maxChunksZ);

            Vector3 maxBounds = new Vector3(maxChunksX * chunkSizeX * 0.5f, maxChunksY * chunkSizeY * 0.5f, maxChunksZ * chunkSizeZ * 0.5f);
            Vector3 minBounds = -maxBounds;
            Bounds = new BoundingBox(minBounds, maxBounds);
        }
示例#36
0
    public TextureCompiler texture; //visual represetaion

    #endregion Fields

    #region Methods

    void Start()
    {
        chunk = new ChunkGenerator (1, 1,chunkSize);
        texture = new TextureCompiler (chunk.buildChunk (),this);
        gameObject.GetComponent<Renderer> ().material.mainTexture = texture.mapTexture;
    }
示例#37
0
    protected virtual MeshData FaceDataWest(ChunkGenerator chunk, int x, int y, int z, MeshData meshData)
    {
        meshData.AddVertex(new Vector3(x - 0.5f, y - 0.5f, z + 0.5f));
        meshData.AddVertex(new Vector3(x - 0.5f, y + 0.5f, z + 0.5f));
        meshData.AddVertex(new Vector3(x - 0.5f, y + 0.5f, z - 0.5f));
        meshData.AddVertex(new Vector3(x - 0.5f, y - 0.5f, z - 0.5f));

        meshData.AddQuadTriangles();
        meshData.uv.AddRange(FaceUVs(Direction.west));
        return meshData;
    }
示例#38
0
        /// <summary>
        /// Creates the terrain that is immediately around the player's spawn point.
        /// If loading from a file, loads the existing terrain from a file.
        /// </summary>
        public void GenerateInitialChunks()
        {
            gameFile = null;

            bool fileExists = !string.IsNullOrEmpty(ExistingFile);

            // If we already have a file, we need to load all the chunks from it.
            // This is preliminary stuff that just makes sure the file exists and can be loaded.
            if (fileExists)
            {
                LoadingMessage = "Loading " + ExistingFile;
                gameFile = new GameFile(ExistingFile, true);
                Sky.TimeOfDay = gameFile.Data.Metadata.TimeOfDay;
                WorldOrigin = gameFile.Data.Metadata.WorldOrigin;
                WorldScale = gameFile.Data.Metadata.WorldScale;
                ChunkWidth = gameFile.Data.Metadata.ChunkWidth;
                ChunkHeight = gameFile.Data.Metadata.ChunkHeight;

                if (gameFile.Data.Metadata.OverworldFile != null && gameFile.Data.Metadata.OverworldFile != "flat")
                {
                    LoadingMessage = "Loading world " + gameFile.Data.Metadata.OverworldFile;
                    Overworld.Name = gameFile.Data.Metadata.OverworldFile;
                    DirectoryInfo worldDirectory =
                        Directory.CreateDirectory(DwarfGame.GetGameDirectory() + ProgramData.DirChar + "Worlds" +
                                                  ProgramData.DirChar + Overworld.Name);
                    OverworldFile overWorldFile =
                        new OverworldFile(
                            worldDirectory.FullName + ProgramData.DirChar + "world." + OverworldFile.CompressedExtension,
                            true);
                    Overworld.Map = overWorldFile.Data.CreateMap();
                    Overworld.Name = overWorldFile.Data.Name;
                    WorldWidth = Overworld.Map.GetLength(1);
                    WorldHeight = Overworld.Map.GetLength(0);
                }
                else
                {
                    LoadingMessage = "Generating flat world..";
                    Overworld.CreateUniformLand(Game.GraphicsDevice);
                }

                GameID = gameFile.Data.GameID;

            }
            else
            {
                GameID = Random.Next(0, 1024);
            }

            ChunkGenerator = new ChunkGenerator(VoxelLibrary, Seed, 0.02f, ChunkHeight/2.0f)
            {
                SeaLevel = SeaLevel
            };

            Vector3 globalOffset = new Vector3(WorldOrigin.X, 0, WorldOrigin.Y) * WorldScale;

            if(fileExists)
            {
                globalOffset /= WorldScale;
            }

            // If the file exists, we get the camera's pose from the file.
            // Otherwise, we set it to a pose above the center of the world (0, 0, 0)
            // facing down slightly.
            Camera = fileExists ? gameFile.Data.Camera :
                new OrbitCamera(0, 0, 10f, new Vector3(ChunkWidth, ChunkHeight - 1.0f, ChunkWidth) + globalOffset, new Vector3(0, 50, 0) + globalOffset, MathHelper.PiOver4, AspectRatio, 0.1f, GameSettings.Default.VertexCullDistance);

            Drawer3D.Camera = Camera;

            // Creates the terrain management system.
            ChunkManager = new ChunkManager(Content, (uint) ChunkWidth, (uint) ChunkHeight, (uint) ChunkWidth, Camera,
                GraphicsDevice, Tilesheet,
                TextureManager.GetTexture(ContentPaths.Terrain.terrain_illumination),
                TextureManager.GetTexture(ContentPaths.Gradients.sungradient),
                TextureManager.GetTexture(ContentPaths.Gradients.ambientgradient),
                TextureManager.GetTexture(ContentPaths.Gradients.torchgradient),
                ChunkGenerator, WorldSize.X, WorldSize.Y, WorldSize.Z);

            // Trying to determine the global offset from overworld coordinates (pixels in the overworld) to
            // voxel coordinates.
            globalOffset = ChunkManager.ChunkData.RoundToChunkCoords(globalOffset);
            globalOffset.X *= ChunkWidth;
            globalOffset.Y *= ChunkHeight;
            globalOffset.Z *= ChunkWidth;

            // If there's no file, we have to offset the camera relative to the global offset.
            if(!fileExists)
            {
                WorldOrigin = new Vector2(globalOffset.X, globalOffset.Z);
                Camera.Position = new Vector3(0, 10, 0) + globalOffset;
                Camera.Target = new Vector3(0, 10, 1) + globalOffset;
                Camera.Radius = 0.01f;
                Camera.Phi = -1.57f;
            }

            // If there's no file, we have to initialize the first chunk coordinate
            if(gameFile == null)
            {
                ChunkManager.GenerateInitialChunks(Camera, ChunkManager.ChunkData.GetChunkID(new Vector3(0, 0, 0) + globalOffset), ref LoadingMessage);
            }
            // Otherwise, we just load all the chunks from the file.
            else
            {
                LoadingMessage = "Loading Chunks from Game File";
                ChunkManager.ChunkData.LoadFromFile(gameFile, ref LoadingMessage);
            }

            // If there's no file, for some reason we modify the camera position...
            // TODO: Figure out why the camera keeps needing to be reset.
            if(!fileExists)
            {
                Camera.Radius = 0.01f;
                Camera.Phi = -1.57f / 4.0f;
                Camera.Theta = 0.0f;
            }

            // Finally, the chunk manager's threads are started to allow it to
            // dynamically rebuild terrain
            ChunkManager.RebuildList = new ConcurrentQueue<VoxelChunk>();
            ChunkManager.StartThreads();
        }
示例#39
0
 public ChunkCache(ChunkSource source, ChunkGenerator generator)
 {
     this.source = source;
     this.generator = generator;
 }