Пример #1
0
    public void Generate(IModule module, int _seed, bool _enableCaves, float _amp, float _caveDensity, float _grassOffset)
    {
        try
        {
            Sampler = new TerrainSampler(module, _seed, _enableCaves, _amp, _caveDensity, _grassOffset);;
            Sampler.SetChunkSettings(VoxelsPerMeter,
                                     new Vector3Int(ChunkSizeX, ChunkSizeY, ChunkSizeZ),
                                     new Vector3Int(ChunkMeterSizeX, ChunkMeterSizeY, ChunkMeterSizeZ),
                                     skipDist,
                                     half, new Vector3(xSideLength, ySideLength, zSideLength));


            Vector2Int bottomLeft = new Vector2(location.x * ChunkSizeX, location.z * ChunkSizeZ);
            Vector2Int topRight   = new Vector2(location.x * ChunkSizeX + ChunkSizeX, location.z * ChunkSizeZ + ChunkSizeZ);
            watch.Start();
            Sampler.SetSurfaceData(bottomLeft, topRight);
            watch.Stop();
            noiseGenTime = watch.Elapsed.ToString();

            int bottom = VoxelConversions.ChunkToVoxel(location).y;
            empty = bottom > Sampler.GetMax();
        }
        catch (Exception e)
        {
            SafeDebug.LogError(string.Format("{0}\nFunction: Generate\n Chunk: {1}", e.Message, location.ToString()), e);
        }
    }
Пример #2
0
    public void ChangeBlock(Vector3 globalPosition, byte type)
    {
        Vector3Int voxelPos = VoxelConversions.WorldToVoxel(globalPosition);

        //Debug.LogFormat("globalPostion: {0}", globalPosition);
        ChangeBlock(voxelPos, type);
    }
Пример #3
0
 public void SetScaledIndices(int length)
 {
     for (int i = 0; i < textureIndex.Length; i++)
     {
         ScaledIndex[i] = VoxelConversions.Scale(textureIndex[i], 0, length, 0, 1);
     }
 }
Пример #4
0
    // Update is called once per frame
    void Update()
    {
        if (player != null)
        {
            newPlayerVoxelPos = VoxelConversions.WorldToVoxel(player.transform.position);
            newPlayerChunkPos = VoxelConversions.VoxelToChunk(newPlayerVoxelPos);
            //Debug.Log(generateArroundChunk + ", " + newPlayerChunkPos + ", " + Vector3.Distance(generateArroundChunk, newPlayerChunkPos));
            if (Vector3.Distance(_generateArroundChunk, newPlayerChunkPos) > 0 && !_generating)
            {
                // generate around point.
                //Debug.Log("Debug filling " + newPlayerChunkPos + ".");
                _generateArroundChunk = newPlayerChunkPos;
                GenerateSpherical(_generateArroundChunk, null);
            }

            /*if (Vector3.Distance(_oldPlayerVoxelPos, newPlayerVoxelPos) > 2)
             * {
             *  _oldPlayerVoxelPos = newPlayerVoxelPos;
             *  DeleteGrass();
             *  SpawnGrass();
             * }*/
        }

        if (chunksInQueue > 0)
        {
            GameManager.Status = string.Format("Generating chunk {0}/{1}.", chunksGenerated, chunksInQueue);
        }
    }
Пример #5
0
    public float ValueSample(Vector3Int local, Vector3Int global)
    {
        uint type;

        return((float)Sampler.GetIsoValue(local, global, out type));

        if (IsInBounds(local.x, local.y, local.z))
        {
            return(GetBlockValue(local.x, local.y, local.z));
        }
        else
        {
            Vector3Int         chunk           = VoxelConversions.VoxelToChunk(global);
            Vector3Int         chunklocalVoxel = VoxelConversions.GlobalToLocalChunkCoord(chunk, global);
            SmoothVoxelBuilder builder         = (SmoothVoxelBuilder)controller.GetBuilder(chunk.x, chunk.y, chunk.z);
            if (builder != null)
            {
                return(builder.GetBlockValue(chunklocalVoxel.x, chunklocalVoxel.y, chunklocalVoxel.z));
            }
            else
            {
                return((float)Sampler.GetIsoValue(chunklocalVoxel, global, out type));
            }
        }
    }
Пример #6
0
    /*public void SetSurfacePoints(Vector3Int[] points)
     * {
     *  for (int i = 0; i < points.Length; i++)
     *      if (!surfacePoints.Contains(points[i]))
     *          surfacePoints.Add(points[i]);
     * }*/

    public void SetBlockAtLocation(Vector3 position, byte type)
    {
        Vector3Int voxelPos   = VoxelConversions.WorldToVoxel(position);
        Vector3Int chunk      = VoxelConversions.VoxelToChunk(voxelPos);
        Vector3Int localVoxel = VoxelConversions.GlobalVoxToLocalChunkVoxCoord(chunk, voxelPos);

        if (BuilderExists(chunk.x, chunk.y, chunk.z))
        {
            Chunks[new Vector3Int(chunk.x, chunk.y, chunk.z)].EditNextFrame(new Chunk.BlockChange[] { new Chunk.BlockChange(position, type) });
        }
    }
Пример #7
0
 public void Init(Vector3Int chunkPos, IPageController pageController)
 {
     chunkPosition       = chunkPos;
     this.pageController = pageController;
     transform.position  = VoxelConversions.ChunkCoordToWorld(chunkPos);
     _renderer           = gameObject.GetComponent <MeshRenderer>();
     _filter             = gameObject.GetComponent <MeshFilter>();
     _collider           = gameObject.GetComponent <MeshCollider>();
     _renderer.material.SetTexture("_MainTex", TerrainController.Instance.textureAtlas);
     _player = TerrainController.Instance.player;
     createChunkBuilder();
 }
    public Block GetBlock(int x, int y, int z)
    {
        Vector3Int chunk      = VoxelConversions.VoxelToChunk(new Vector3Int(x, y, z));
        Vector3Int localVoxel = VoxelConversions.GlobalToLocalChunkCoord(chunk, new Vector3Int(x, y, z));
        Block      result     = default(Block);

        if (BuilderExists(chunk.x, chunk.y, chunk.z))
        {
            result = Chunks[chunk].GetBlock(localVoxel.x, localVoxel.y, localVoxel.z);
        }
        return(result);
    }
Пример #9
0
    public void GenerateChunks(int threads)
    {
        Stopwatch watch = new Stopwatch();

        watch.Start();
        List <Vector2Int>[] colCoords = new List <Vector2Int> [threads];

        for (int t = 0; t < threads; t++)
        {
            colCoords[t] = new List <Vector2Int>();
        }

        int i = 0;

        for (int x = 0; x < width; x++)
        {
            for (int z = 0; z < depth; z++)
            {
                Vector2Int col_pos = new Vector2Int(x, z);
                if (!Columns.ContainsKey(col_pos))
                {
                    GameObject obj = Instantiate(ColumnObj, VoxelConversions.ChunkCoordToWorld(new Vector3Int(x, 0, z)), Quaternion.identity, transform);
                    obj.name         = "Column " + col_pos.ToString();
                    Columns[col_pos] = obj.GetComponent <ChunkColumn>();
                    Columns[col_pos].Init(col_pos, this, CreateTerrainSampler());
                }

                colCoords[i % colCoords.Length].Add(col_pos);
                i++;

                /*for (int y = 0; y < height; y++)
                 * {
                 *  Vector3Int pos = new Vector3Int(x, y, z);
                 *  chunkCoords.Add(pos);
                 *
                 *  Vector2Int col_pos = new Vector2Int(pos.x, pos.z);
                 *  if (!Columns.ContainsKey(col_pos))
                 *  {
                 *      GameObject obj = new GameObject("Column " + col_pos.ToString(), typeof(ChunkColumn));
                 *      Columns[col_pos] = obj.GetComponent<ChunkColumn>();
                 *      Columns[col_pos].Init(20, col_pos, CreateTerrainSampler());
                 *  }
                 * }*/
            }
        }
        watch.Stop();
        Debug.Log("Finished spawning columns: " + watch.Elapsed);
        for (int t = 0; t < colCoords.Length; t++)
        {
            //Debug.Log(colCoords[t].Count);
            GenerateChunks("Gen_" + t, colCoords[t].ToArray());
        }
    }
Пример #10
0
    public byte GetBlock(int x, int y, int z)
    {
        Vector3Int chunk      = VoxelConversions.VoxelToChunk(new Vector3Int(x, y, x));
        Vector3Int localVoxel = VoxelConversions.GlobalVoxToLocalChunkVoxCoord(chunk, new Vector3Int(x, y, z));
        byte       result     = 1;

        if (x >= 0 && y >= 0 && z >= 0 && BuilderExists(chunk.x, chunk.y, chunk.z))
        {
            result = Chunks[new Vector3Int(chunk.x, chunk.y, chunk.z)].GetBlock(x, y, z);
        }
        return(result);
    }
Пример #11
0
    } // needs to be changed if using superchunks.

    public byte GetBlock(int x, int y, int z)
    {
        Vector3Int chunk      = VoxelConversions.VoxelToChunk(new Vector3Int(x, y, x));
        Vector3Int localVoxel = VoxelConversions.GlobalVoxToLocalChunkVoxCoord(chunk, new Vector3Int(x, y, z));
        byte       result     = 1;

        if (x >= 0 && y >= 0 && z >= 0 && Chunks.ContainsKey(chunk))
        {
            result = Chunks[chunk].GetBlock(x, y, z);
        }
        return(result);
    }
Пример #12
0
    public static void SpawnChunk(Vector3Int chunkPos, ISampler sampler, IPageController controller)
    {
        Vector3 worldPos       = VoxelConversions.ChunkCoordToWorld(chunkPos);
        double  voxelsPerMeter = SmoothVoxelSettings.voxelsPerMeter;

        SmoothVoxelBuilder builder = new SmoothVoxelBuilder(controller, chunkPos);

        builder.SetBlockTypes(controller.BlockTypes, null);
        builder.CalculateVariables(voxelsPerMeter, SmoothVoxelSettings.MeterSizeX, SmoothVoxelSettings.MeterSizeY, SmoothVoxelSettings.MeterSizeZ);
        builder.Generate(sampler);

        SmoothChunk chunk = GameObject.Instantiate(controller.ChunkPrefab).GetComponent <SmoothChunk>();

        chunk.name = string.Format("Chunk_{0}.{1}.{2}", chunkPos.x, chunkPos.y, chunkPos.z);
        chunk.Init(chunkPos, worldPos, null, controller, 1, builder);
    }
Пример #13
0
    public void UpdateLOD()
    {
        return;

        Loom.QueueAsyncTask("LODupdate", () => {
            if (canUpdateForLOD)
            {
                Vector3 worldPos      = VoxelConversions.ChunkCoordToWorld(chunkPosition);
                float distance        = Vector3.Distance(worldPos, TerrainController.Instance.LODtarget);
                float radius          = SmoothVoxelSettings.radius * SmoothVoxelSettings.MeterSizeX;
                double voxelsPerMeter = SmoothVoxelSettings.voxelsPerMeter;
                int LODlevel          = 1;
                if (distance > (radius / 10f) && distance < (radius / 10f) * 5)
                {
                    voxelsPerMeter /= 2;
                    LODlevel        = 2;
                }
                else if (distance > (radius / 10f) * 5 && distance < radius)
                {
                    voxelsPerMeter /= 4;
                    LODlevel        = 3;
                }

                /*else if (distance > (radius / 10f) * 6 && distance < radius) {
                 *  voxelsPerMeter /= 10;
                 *  LODlevel = 4;
                 * }*/
                else if (distance >= radius)
                {
                    return;
                }

                if (LODlevel != oldLODlevel)
                {
                    oldLODlevel = LODlevel;
                    builderInstance.CalculateVariables(voxelsPerMeter, SmoothVoxelSettings.MeterSizeX, SmoothVoxelSettings.MeterSizeY, SmoothVoxelSettings.MeterSizeZ);
                    builderInstance.Generate(surfaceModule,
                                             SmoothVoxelSettings.seed,
                                             SmoothVoxelSettings.enableCaves && (LODlevel <= 2),
                                             SmoothVoxelSettings.amplitude,
                                             SmoothVoxelSettings.caveDensity,
                                             SmoothVoxelSettings.grassOffset);
                    Render(false);
                }
            }
        });
    }
Пример #14
0
    public void Generate(int height)
    {
        int chunkSizeX = SmoothVoxelSettings.ChunkSizeX;
        int chunkSizeY = SmoothVoxelSettings.ChunkSizeY;
        int chunkSizeZ = SmoothVoxelSettings.ChunkSizeZ;

        int meterSizeX = SmoothVoxelSettings.MeterSizeX;
        int meterSizeY = SmoothVoxelSettings.MeterSizeY;
        int meterSizeZ = SmoothVoxelSettings.MeterSizeZ;

        Sampler.SetChunkSettings(SmoothVoxelSettings.voxelsPerMeter,
                                 new Vector3Int(chunkSizeX, chunkSizeY, chunkSizeZ),
                                 new Vector3Int(meterSizeX, meterSizeY, meterSizeZ),
                                 Mathf.RoundToInt(1 / (float)SmoothVoxelSettings.voxelsPerMeter),
                                 ((1.0f / (float)SmoothVoxelSettings.voxelsPerMeter) / 2.0f),
                                 new Vector3(meterSizeX / (float)chunkSizeX, meterSizeY / (float)chunkSizeY, meterSizeZ / (float)chunkSizeZ));

        Vector3Int topVoxel    = VoxelConversions.WorldToVoxel(new Vector3(0, (float)Sampler.GetMax(), 0));
        Vector3Int bottomVoxel = VoxelConversions.WorldToVoxel(new Vector3(0, (float)Sampler.GetMin(), 0));

        int topChunk    = VoxelConversions.VoxelToChunk(topVoxel).y;
        int bottomChunk = VoxelConversions.VoxelToChunk(bottomVoxel).y;

        if (NetworkMode)
        {
            for (int y = 0; y <= topChunk; y++)
            {
                SmoothChunk.CreateChunk(new Vector3Int(Location.x, y, Location.y), Sampler, Controller);
            }
        }
        else
        {
            Vector2Int bottomLeft = new Vector2(Location.x * chunkSizeX, Location.y * chunkSizeZ);
            Vector2Int topRight   = new Vector2(Location.x * chunkSizeX + chunkSizeX, Location.y * chunkSizeZ + chunkSizeZ);
            Sampler.SetSurfaceData(bottomLeft, topRight);

            for (int y = 0; y <= topChunk; y++)
            {
                SmoothChunk.CreateChunk(new Vector3Int(Location.x, y, Location.y), Sampler, Controller);
            }
            Loom.QueueOnMainThread(() =>
            {
                Debug.Log("Spawning grass...");
                SpawnGrass();
            });
        }
    }
Пример #15
0
    public void Generate(ISampler sampler)
    {
        Sampler = sampler;

        /*Sampler.SetChunkSettings(VoxelsPerMeter,
         *                             new Vector3Int(ChunkSizeX, ChunkSizeY, ChunkSizeZ),
         *                             new Vector3Int(ChunkMeterSizeX, ChunkMeterSizeY, ChunkMeterSizeZ),
         *                             skipDist,
         *                             half, new Vector3(xSideLength, ySideLength, zSideLength));
         * Vector2Int bottomLeft = new Vector2(location.x * ChunkSizeX, location.z * ChunkSizeZ);
         * Vector2Int topRight = new Vector2(location.x * ChunkSizeX + ChunkSizeX, location.z * ChunkSizeZ + ChunkSizeZ);
         * Sampler.SetSurfaceData(bottomLeft, topRight);*/

        int bottom = VoxelConversions.ChunkToVoxel(location).y;

        empty = bottom > Sampler.GetMax();
    }
Пример #16
0
    // Start is called before the first frame update
    void Start()
    {
        uint val = 0;

        uint loc     = 52428;
        uint type_P2 = 255 << 16;
        uint iso_p2  = (uint)VoxelConversions.Scale(Mathf.Clamp(2, -2, 2), -2, 2, byte.MinValue, byte.MaxValue) << 24;

        val  = loc;
        val |= type_P2;
        val |= iso_p2;



        byte[] us_b = System.BitConverter.GetBytes(val);

        Debug.Log(System.BitConverter.ToString(us_b));
    }
Пример #17
0
    public void ChangeBlock(Chunk.BlockChange change)
    {
        Vector3Int chunk      = VoxelConversions.VoxelToChunk(change.position);
        Vector3Int localVoxel = VoxelConversions.GlobalVoxToLocalChunkVoxCoord(chunk, change.position);

        //Debug.LogFormat("voxel: {0}, localVoxel: {1}, chunk: {2}", voxel, localVoxel, chunk);
        if (BuilderExists(chunk.x, chunk.y, chunk.z))
        {
            if (localVoxel.x >= 0 && localVoxel.x < VoxelSettings.ChunkSizeX && localVoxel.y >= 0 && localVoxel.y < VoxelSettings.ChunkSizeY && localVoxel.z >= 0 && localVoxel.z < VoxelSettings.ChunkSizeZ)
            {
                Chunks[chunk].EditNextFrame(new Chunk.BlockChange(localVoxel, change.type));
            }
            else
            {
                SafeDebug.LogError(string.Format("Out of Bounds: chunk: {0}, globalVoxel:{1}, localVoxel: {2}, Function: GenerateExplosion",
                                                 chunk, change.position, localVoxel));
            }
        }
    }
Пример #18
0
    public float[] GetBlockTypeTexture()
    {
        int data_size = (builderInstance.ChunkSizeX + 2) * (builderInstance.ChunkSizeY + 2) * (builderInstance.ChunkSizeZ + 2);

        tex = new Texture3D(builderInstance.ChunkSizeX + 2, builderInstance.ChunkSizeY + 2, builderInstance.ChunkSizeZ + 2, TextureFormat.RGBA32, false);

        Vector3Int orig = VoxelConversions.ChunkToVoxel(chunkPosition);

        Debug.Log(orig);

        //type_data = new Color32[data_size];
        Mat_index_array = new float[data_size];
        for (int x_g = orig.x - 1, x = 0; x < builderInstance.ChunkSizeX + 2; x_g++, x++)
        {
            for (int y_g = orig.y - 1, y = 0; y < builderInstance.ChunkSizeY + 2; y_g++, y++)
            {
                for (int z_g = orig.z - 1, z = 0; z < builderInstance.ChunkSizeZ + 2; z_g++, z++)
                {
                    uint type = SingleChunkController.Instance.GetBlock(x_g, y_g, z_g).type;
                    if (type == 0)
                    {
                        //type_data[builderInstance.Get_Flat_Index(x, y, z)] = new Color32(0, 255, 0, 0);
                        Mat_index_array[builderInstance.Get_Flat_Index(x, y, z)] = -1f;
                    }
                    else
                    {
                        int index = SingleChunkController.Instance.BlockTypes[type].textureIndex[0];
                        Mat_index_array[builderInstance.Get_Flat_Index(x, y, z)] = index;
                        //type_data[builderInstance.Get_Flat_Index(x, y, z)] = new Color32((byte)index, 0, 0, 0);
                    }
                }
            }
        }

        //Debug.Log("pos: " + builderInstance.Get_Flat_Index(8, 8, 10));

        //tex.SetPixels32(type_data, 0);
        //tex.Apply();

        return(Mat_index_array);
    }
Пример #19
0
 public void GenerateExplosion(Vector3 postion, int radius)
 {
     System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
     watch.Start();
     Loom.AddAsyncThread("Explosion");
     Loom.QueueAsyncTask("Explosion", () =>
     {
         Dictionary <Vector3Int, List <Chunk.BlockChange> > changes = new Dictionary <Vector3Int, List <Chunk.BlockChange> >();
         Vector3Int voxelPos = VoxelConversions.WorldToVoxel(postion);
         for (int x = voxelPos.x - radius; x <= voxelPos.x + radius; x++)
         {
             for (int y = voxelPos.y - radius; y <= voxelPos.y + radius; y++)
             {
                 for (int z = voxelPos.z - radius; z <= voxelPos.z + radius; z++)
                 {
                     Vector3Int voxel = new Vector3Int(x, y, z);
                     Vector3Int chunk = VoxelConversions.VoxelToChunk(voxel);
                     if (IsInSphere(voxelPos, radius, voxel))
                     {
                         if (!changes.ContainsKey(chunk))
                         {
                             changes.Add(chunk, new List <Chunk.BlockChange>());
                         }
                         changes[chunk].Add(new Chunk.BlockChange(VoxelConversions.GlobalVoxToLocalChunkVoxCoord(chunk, voxel), 0));
                         //ChangeBlock(new Chunk.BlockChange(voxel, 0));
                     }
                 }
             }
         }
         //Debug.Log("Iterated through exploded blocks: " + watch.Elapsed.ToString());
         Loom.QueueOnMainThread(() =>
         {
             foreach (Vector3Int chunkPos in changes.Keys)
             {
                 ChangeBlock(chunkPos, changes[chunkPos].ToArray());
             }
             watch.Stop();
             //Debug.Log("Blocks changes sent to chunk: " + watch.Elapsed.ToString());
         });
     });
 }
Пример #20
0
    public Block GetBlock(int x, int y, int z)
    {
        Vector3Int chunk      = VoxelConversions.VoxelToChunk(new Vector3Int(x, y, z));
        Vector3Int localVoxel = VoxelConversions.GlobalToLocalChunkCoord(chunk, new Vector3Int(x, y, z));
        Block      result     = default(Block);

        if (BuilderExists(chunk.x, chunk.y, chunk.z))
        {
            try {
                result = Chunks[new Vector3Int(chunk.x, chunk.y, chunk.z)].GetBlock(localVoxel.x, localVoxel.y, localVoxel.z);
            }catch (Exception e) {
                Debug.LogErrorFormat("{0}, globalZ: {1}", e.Message, z);
                throw;
            }
        }
        else
        {
            chunkNoExistError = true;
        }
        return(result);
    }
Пример #21
0
 public void ChangeBlock(Vector3Int[] voxels, byte type)
 {
     foreach (Vector3Int block in voxels)
     {
         Vector3Int chunk      = VoxelConversions.VoxelToChunk(block);
         Vector3Int localVoxel = VoxelConversions.GlobalToLocalChunkCoord(chunk, block);
         //Debug.LogFormat("voxel: {0}, localVoxel: {1}, chunk: {2}", voxel, localVoxel, chunk);
         if (BuilderExists(chunk.x, chunk.y, chunk.z))
         {
             if (localVoxel.x >= 0 && localVoxel.x < SmoothVoxelSettings.ChunkSizeX && localVoxel.y >= 0 && localVoxel.y < SmoothVoxelSettings.ChunkSizeY && localVoxel.z >= 0 && localVoxel.z < SmoothVoxelSettings.ChunkSizeZ)
             {
                 Chunks[chunk].EditNextFrame(new SmoothChunk.BlockChange(localVoxel, type));
             }
             else
             {
                 SafeDebug.LogError(string.Format("Out of Bounds: chunk: {0}, globalVoxel:{1}, localVoxel: {2}, Function: GenerateExplosion",
                                                  chunk, block, localVoxel));
             }
         }
     }
 }
    // Update is called once per frame
    void Update()
    {
        if (cameraObj != null)
        {
            newCameraVoxelPos = VoxelConversions.WorldToVoxel(cameraObj.transform.position);
            newCameraChunkPos = VoxelConversions.VoxelToChunk(newCameraVoxelPos);
            //Debug.Log(generateArroundChunk + ", " + newPlayerChunkPos + ", " + Vector3.Distance(generateArroundChunk, newPlayerChunkPos));

            /*if (Vector3.Distance(_oldPlayerVoxelPos, newPlayerVoxelPos) > 2)
             * {
             *  _oldPlayerVoxelPos = newPlayerVoxelPos;
             *  DeleteGrass();
             *  SpawnGrass();
             * }*/
        }

        if (chunksInQueue > 0)
        {
            GameManager.Status = string.Format("Generating chunk {0}/{1}.", chunksGenerated, chunksInQueue);
        }
    }
Пример #23
0
    public void SpawnGrass()
    {
        int xMin = newPlayerVoxelPos.x - maxGrassDistance;
        int xMax = newPlayerVoxelPos.x + maxGrassDistance;

        int yMin = newPlayerVoxelPos.y - maxGrassDistance;
        int yMax = newPlayerVoxelPos.y + maxGrassDistance;

        int zMin = newPlayerVoxelPos.z - maxGrassDistance;
        int zMax = newPlayerVoxelPos.z + maxGrassDistance;

        Loom.QueueAsyncTask(GrassThreadName, () =>
        {
            List <Vector3Int> grass = new List <Vector3Int>();
            for (int x = xMin; x < xMax; x++)
            {
                for (int z = zMin; z < zMax; z++)
                {
                    Vector3Int pos   = new Vector3Int(x, 0, z);
                    Vector3Int chunk = VoxelConversions.VoxelToChunk(pos);
                    if (Chunks[chunk].surface2D.Contains(new Vector2Int(pos.x, pos.z)) && !grassObj.ContainsKey(new Vector2Int(x, z)) && IsInSphere(newPlayerVoxelPos, maxGrassDistance, new Vector3Int(x, 0, z)))
                    {
                        grass.Add(pos);
                    }
                }
            }

            Loom.QueueOnMainThread(() =>
            {
                for (int i = 0; i < grass.Count; i++)
                {
                    if (!grassObj.ContainsKey(new Vector2Int(grass[i].x, grass[i].z)))
                    {
                        Vector3 globalPos = VoxelConversions.VoxelToWorld(grass[i]);
                        grassObj.Add(new Vector2Int(grass[i].x, grass[i].z), (GameObject)Instantiate(grassPrefab, new Vector3(grass[i].x, 0, grass[i].z), Quaternion.identity));
                    }
                }
            });
        });
    }
    public void GenerateChunks(Vector2Int[] columns)
    {
        try
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            for (int i = 0; i < columns.Length; i++)
            {
                _generating = true;

                if (!Columns.ContainsKey(columns[i]))
                {
                    GameObject obj = Instantiate(ColumnObj, VoxelConversions.ChunkCoordToWorld(new Vector3Int(columns[i].x, 0, columns[i].y)), Quaternion.identity, transform);
                    obj.name            = "Column " + columns[i].ToString();
                    Columns[columns[i]] = obj.GetComponent <ChunkColumn>();
                    Columns[columns[i]].Init(columns[i], this);
                    gameClient.RequestColumn(columns[i], LOD_Mode.ReducedDepth, false);
                }

                Columns[columns[i]].Generate(height);
                chunksGenerated += height;
            }
            watch.Stop();
            Debug.Log("Finished generating chunks in: " + watch.Elapsed);

            if (!renderCompleteCalled)
            {
                renderCompleteCalled = true;
                //if (OnChunksGenerated != null)
                //    Loom.QueueOnMainThread(() => { OnChunksGenerated(columns); });
            }
            _generating = false;
        }
        catch (Exception e)
        {
            SafeDebug.LogError(string.Format("{0}: {1}\n {2}", e.GetType().ToString(), e.Message, e.StackTrace));
        }
    }
Пример #25
0
    public static void CreateChunk(Vector3Int chunkPos, ISampler sampler, IPageController controller)
    {
        Vector3 worldPos       = VoxelConversions.ChunkCoordToWorld(chunkPos);
        double  voxelsPerMeter = SmoothVoxelSettings.voxelsPerMeter;

        SmoothVoxelBuilder builder = new SmoothVoxelBuilder(controller, chunkPos);

        builder.SetBlockTypes(controller.BlockTypes, null);
        builder.CalculateVariables(voxelsPerMeter, SmoothVoxelSettings.MeterSizeX, SmoothVoxelSettings.MeterSizeY, SmoothVoxelSettings.MeterSizeZ);
        builder.Generate(sampler);

        System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
        watch.Start();

        MeshData meshData = builder.Render(false);

        watch.Stop();
        Debug.Log("Chunk Generated at " + watch.Elapsed);
        //if (meshData.vertices.Length == 0)
        //    return;

        Loom.QueueOnMainThread(() => {
            SmoothChunk chunk = GameObject.Instantiate(controller.ChunkPrefab).GetComponent <SmoothChunk>();
            chunk.name        = string.Format("Chunk_{0}.{1}.{2}", chunkPos.x, chunkPos.y, chunkPos.z);
            chunk.Init(chunkPos, worldPos, null, controller, 1, builder);
            chunk.Render(meshData, true);
            Loom.QueueAsyncTask("gen2", () => controller.AddChunk(chunkPos, chunk));

            /*if (!TerrainController.Instance.Chunks.ContainsKey(chunkPos))
             * {
             *  SmoothChunk chunk = GameObject.Instantiate(TerrainController.Instance.chunkPrefab).GetComponent<SmoothChunk>();
             *  chunk.name = string.Format("Chunk_{0}.{1}.{2}", chunkPos.x, chunkPos.y, chunkPos.z);
             *  chunk.Init(chunkPos, worldPos, null, controller, 1, builder);
             *  chunk.Render(meshData);
             *  TerrainController.Instance.AddChunk(chunkPos, chunk);
             * }*/
        });
    }
Пример #26
0
 // Update is called once per frame
 void Update()
 {
     if (player != null)
     {
         _playerCreated    = true;
         _playerPosition   = player.transform.position;
         LODtarget         = _playerPosition;
         newPlayerVoxelPos = VoxelConversions.WorldToVoxel(_playerPosition);
         newPlayerChunkPos = VoxelConversions.VoxelToChunk(newPlayerVoxelPos);
         //Debug.Log(generateArroundChunk + ", " + newPlayerChunkPos + ", " + Vector3.Distance(generateArroundChunk, newPlayerChunkPos));
         if (_oldPlayerChunkPos != newPlayerChunkPos && !_generating)
         {
             // generate around point.
             //Debug.Log("Debug filling " + newPlayerChunkPos + ".");
             _generateArroundChunk = _oldPlayerChunkPos = newPlayerChunkPos;
             GenerateSpherical(newPlayerChunkPos);
         }
         foreach (SmoothChunk chk in Chunks.Values.ToArray())
         {
             chk.ChunkUpdate();
         }
     }
 }
Пример #27
0
    public void GetChunk_Cmd(SocketUser user, Data data)
    {
        User userInst = (User)user.User;

        int  chunkX        = BitConverter.ToInt32(data.Buffer, 0);
        int  chunkY        = BitConverter.ToInt32(data.Buffer, 4);
        int  chunkZ        = BitConverter.ToInt32(data.Buffer, 8);
        int  lod_Version   = BitConverter.ToInt32(data.Buffer, 12);
        bool has_heightmap = BitConverter.ToBoolean(data.Buffer, 16);

        Vector3Int chunkCord = new Vector3Int(chunkX, chunkY, chunkZ);
        Vector2Int Region    = VoxelConversions.ChunkToRegion(chunkCord);

        Region region = Regions.LoadORCreate(Region);

        Logger.Log("User {0} requested {1}.", userInst.Name, chunkCord);

        if (region.ChunkExists(chunkCord))
        {
            Column col = region.GetColumn(user.User, chunkCord, (LOD_Mode)lod_Version);
            if (col.Max_Mode < (LOD_Mode)lod_Version)
            {
                Logger.Log("Requesting chunk update: " + DebugTimer.Elapsed());
                RequestChunkGen(chunkCord, region, (LOD_Mode)lod_Version, userInst, has_heightmap);
            }
            else
            {
                Logger.Log("Transmitting chunk: " + DebugTimer.Elapsed());
                userInst.TransmitColumn(col, has_heightmap);
            }
        }
        else
        {
            Logger.Log("Requesting new chunk: " + DebugTimer.Elapsed());
            RequestChunkGen(chunkCord, region, (LOD_Mode)lod_Version, userInst, has_heightmap);
        }
    }
Пример #28
0
    public GridPoint GetVector4(Vector3 world, Vector3Int local, Vector3Int global, bool generate)
    {
        //Vector3 origin = new Vector3(ChunkSizeX / 2, ChunkSizeY / 2, ChunkSizeX / 2);
        //return new Vector4(world.x, world.y, world.z, Vector3.Distance(origin, world));
        GridPoint result = default(GridPoint);

        Vector3Int chunk = VoxelConversions.VoxelToChunk(global);
        uint       type;

        if (generate)
        {
            if (IsInBounds(local.x, local.y, local.z))
            {
                result = new GridPoint(world.x, world.y, world.z, (float)GetIsoValue(local, global, generate, out type), type);
            }
            else
            {
                result = new GridPoint(world.x, world.y, world.z, (float)Sampler.GetIsoValue(local, global, out type), type);

                //result = new GridPoint(world.x, world.y, world.z, 100);

                /*Vector3Int chunklocalVoxel = VoxelConversions.GlobalToLocalChunkCoord(chunk, global);
                 * SmoothVoxelBuilder builder = (SmoothVoxelBuilder)controller.GetBuilder(chunk.x, chunk.y, chunk.z);
                 * if (builder != null)
                 * {
                 *  result = new GridPoint(world.x, world.y, world.z, (float)builder.Sampler.GetIsoValue(local, global, out type), type);
                 * }
                 * else
                 * {
                 *  //result = new GridPoint(world.x, world.y, world.z, (float)Sampler.GetIsoValue(chunklocalVoxel, global, out type), type);
                 *  result = new GridPoint(world.x, world.y, world.z, (float)Sampler.GetIsoValue(local, global, out type), type);
                 * }*/
            }
        }
        else
        {
            if (chunk != location)
            {
                Vector3Int    chunklocalVoxel = VoxelConversions.GlobalToLocalChunkCoord(chunk, global);
                IVoxelBuilder builder         = controller.GetBuilder(chunk.x, chunk.y, chunk.z);
                if (builder != null)
                {
                    Block builderBlock = builder.GetBlock(chunklocalVoxel.x, chunklocalVoxel.y, chunklocalVoxel.z);
                    result = new GridPoint(world.x, world.y, world.z, (float)builderBlock.iso, builderBlock.type);
                }
                else
                {
                    result = new GridPoint(world.x, world.y, world.z, (float)Sampler.GetIsoValue(chunklocalVoxel, global, out type));
                }
            }
            else
            {
                result = new GridPoint(world.x, world.y, world.z, (float)GetIsoValue(local, global, generate, out type), (byte)type);
            }
        }

        result.OriginLocal  = local;
        result.OriginGlobal = global;

        return(result);
    }
Пример #29
0
        public void Generate()
        {
            if (empty)
            {
                return;
            }

            if (!Initialized)
            {
                return;
            }

            Stopwatch watch = new Stopwatch();

            watch.Start();

            //surfaceBlocksCount = 0;
            GeneratedBlocks = 0;

            int cx = Location.x;
            int cy = Location.y;
            int cz = Location.z;

            int xStart = cx * ChunkSizeX;
            int xEnd   = cx * ChunkSizeX + ChunkSizeX;

            int yStart = cy * ChunkSizeY;
            int yEnd   = cy * ChunkSizeY + ChunkSizeY;

            int zStart = cz * ChunkSizeZ;
            int zEnd   = cz * ChunkSizeZ + ChunkSizeZ;

            int globalLocX = 0;
            int globalLocY = 0;
            int globalLocZ = 0;

            int x = 0;
            int y = 0;
            int z = 0;

            int Y_Min = 0;
            int Y_Max = ChunkSizeY;

            int heightmapMin = VoxelConversions.WorldToVoxel(new Vector3(0, Math.Max(0, (float)Sampler.GetMin() - Depth), 0)).y;

            Logger.Log("heightmapMin: {0}", heightmapMin);

            int heightmapMin_local = VoxelConversions.GlobalToLocalChunkCoord(new Vector3Int(0, heightmapMin, 0)).y;

            Logger.Log("heightmapMin_local: {0}", heightmapMin_local);

            int heightmapMax = VoxelConversions.WorldToVoxel(new Vector3(0, Math.Min(SmoothVoxelSettings.MeterSizeY, (float)Sampler.GetMax()), 0)).y;

            Logger.Log("heightmapMax: {0}", heightmapMax);

            int heightmapMax_local = VoxelConversions.GlobalToLocalChunkCoord(new Vector3Int(0, heightmapMax, 0)).y;

            Logger.Log("heightmapMax_local: {0}", heightmapMax_local);

            Logger.Log("Generating with updated mode {0}: {1}", updateMode.ToString(), DebugTimer.Elapsed());

            if (updateMode == UpdateMode.EmptyToHeightmap)
            {
                return;
            }
            else if (updateMode == UpdateMode.EmptyToReduced || updateMode == UpdateMode.EmptyToFull ||
                     updateMode == UpdateMode.HeightmapToReduced || updateMode == UpdateMode.HeightmapToFull)
            {
                //Min = int.MaxValue;
                //Max = int.MinValue;
                switch (updateMode)
                {
                case UpdateMode.EmptyToReduced:
                case UpdateMode.HeightmapToReduced:
                    Y_Min   = heightmapMin_local;
                    yStart += Y_Min;
                    Y_Max   = heightmapMax_local;
                    break;

                case UpdateMode.EmptyToFull:
                case UpdateMode.HeightmapToFull:
                    Y_Max = heightmapMax_local;
                    break;
                }
            }
            else if (updateMode == UpdateMode.ReducedToFull)
            {
                Y_Max = heightmapMin_local;
                Logger.Log("ReducedToFull: " + heightmapMin_local);
            }

            //else if(updateMode == UpdateMode.)

            //if (LoadedFromDisk && !ReduceDepth && Max_Mode == LOD_Mode.Full)
            //    Y_Max = VoxelConversions.GlobalToLocalChunkCoord(VoxelConversions.WorldToVoxel(new Vector3(0, (float)Sampler.GetMin() - Depth, 0))).y;

            UnityGameServer.Logger.Log("Column: Y_Min: {0}, Y_Max: {1}", Y_Min, Y_Max);

            col_data.Allocate(ChunkSizeX, ChunkSizeY, ChunkSizeZ);
            builder.Generate(Y_Min, Y_Max, xStart, zStart);


            /*for (globalLocY = yStart, y = Y_Min; y < Y_Max; globalLocY++, y++)
             * {
             *
             *  Max = Mathf.Max(y, Max);
             *  Min = Mathf.Min(y, Min);
             *
             *  for (globalLocZ = zStart, z = 0; z < ChunkSizeZ; globalLocZ++, z++)
             *  {
             *      for (globalLocX = xStart, x = 0; x < ChunkSizeX; globalLocX++, x++)
             *      {
             *          if (deactivated)
             *          {
             *              break;
             *          }
             *
             *          Vector3 worldPos = new Vector3(x * xSideLength, y * ySideLength, z * zSideLength);
             *          Vector3Int globalPos = new Vector3Int(globalLocX * skipDist, globalLocY * skipDist, globalLocZ * skipDist);
             *          Vector3Int localPos = new Vector3Int(x, y, z);
             *          GridPoint[] grid = new GridPoint[8];
             *          for (int i = 0; i < grid.Length; i++)
             *              grid[i] = GetGridPoint(worldPos + locOffset[i], localPos + directionOffsets[i], globalPos + globalOffsets[i]);
             *          ProcessBlock(grid, 0);
             *          GeneratedBlocks++;
             *      }
             *  }
             * }*/

            watch.Stop();
            Logger.Log("Generated from {0} to {1}: " + DebugTimer.Elapsed(), Y_Min, Y_Max);
            Logger.Log("Generated surface blocks: {0}", col_data.surfaceBlocksCount);
        }