Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Bug (Voxel game) Only part of the mesh is generated

Discussion in 'Scripting' started by Bloxxy213, Apr 1, 2023.

  1. Bloxxy213


    Mar 24, 2023

    note: this is my first time using the unity forum, so I might have to move this somewhere else

    So I'm working on a procedurally generated voxel game, and it worked fine using cubes, but that was way too laggy, so I switched to using meshes and only showing the faces which have a neighbor air block.

    It all works "fine", but it doesn't matter the chunk, after a few hundred blocks it just doesn't make nothing. Not like in generating, but not showing in the mesh.

    I can provide more details if you'd like. I belive its something about the triangles or vertices, but I'm not too sure.

    (1) This is the code for making triangles/vertices for a single cube:

    Code (CSharp):
    1.     private MarchResult calculateBlockSide(Block block, string side, float3[] blockCorners)
    2.     {
    3.         MarchResult result = new MarchResult();
    5.         switch (side)
    6.         {
    7.             case "top":
    9.                 result.vertices.Add(blockCorners[5]);
    10.                 result.vertices.Add(blockCorners[4]);
    11.                 result.vertices.Add(blockCorners[7]);
    12.                 result.vertices.Add(blockCorners[6]);
    14.                 break;
    15.             case "bottom":
    17.                 result.vertices.Add(blockCorners[0]);
    18.                 result.vertices.Add(blockCorners[1]);
    19.                 result.vertices.Add(blockCorners[2]);
    20.                 result.vertices.Add(blockCorners[3]);
    22.                 break;
    23.             case "left":
    25.                 result.vertices.Add(blockCorners[7]);
    26.                 result.vertices.Add(blockCorners[4]);
    27.                 result.vertices.Add(blockCorners[0]);
    28.                 result.vertices.Add(blockCorners[3]);
    30.                 break;
    31.             case "right":
    33.                 result.vertices.Add(blockCorners[5]);
    34.                 result.vertices.Add(blockCorners[6]);
    35.                 result.vertices.Add(blockCorners[2]);
    36.                 result.vertices.Add(blockCorners[1]);
    38.                 break;
    39.             case "back":
    41.                 result.vertices.Add(blockCorners[4]);
    42.                 result.vertices.Add(blockCorners[5]);
    43.                 result.vertices.Add(blockCorners[1]);
    44.                 result.vertices.Add(blockCorners[0]);
    46.                 break;
    47.             case "front":
    49.                 result.vertices.Add(blockCorners[6]);
    50.                 result.vertices.Add(blockCorners[7]);
    51.                 result.vertices.Add(blockCorners[3]);
    52.                 result.vertices.Add(blockCorners[2]);
    54.                 break;
    55.         }
    57.         result.triangles.Add(0);
    58.         result.triangles.Add(1);
    59.         result.triangles.Add(3);
    61.         result.triangles.Add(1);
    62.         result.triangles.Add(2);
    63.         result.triangles.Add(3);
    65.         return result;
    66.     }
    68.     public List<MarchResult> calculateBlockMesh(Block block, List<BlockNeighbor> neighbors)
    69.     {    
    70.         List<MarchResult> result = new List<MarchResult>(8);
    72.         float3[] blockCorners = new float3[]
    73.         {
    74.             CornerTable[0] + block.position,
    75.             CornerTable[1] + block.position,
    76.             CornerTable[2] + block.position,
    77.             CornerTable[3] + block.position,
    78.             CornerTable[4] + block.position,
    79.             CornerTable[5] + block.position,
    80.             CornerTable[6] + block.position,
    81.             CornerTable[7] + block.position,
    82.         };
    84.         for (int i = 0; i < neighbors.Count; i++)
    85.         {
    86.             string name = NormalDefinitions[Normals.IndexOf(neighbors[i].position)];
    87.             MarchResult sideResult = calculateBlockSide(block, name, blockCorners);
    89.             result.Add(sideResult);
    90.         }
    94.         /*result.uvs.AddRange(uvs);
    95.         result.normals.AddRange(normals);*/
    97.         /*result.uvs.Add(new Vector2(0, 0));
    98.         result.uvs.Add(new Vector2(0, 1));
    99.         result.uvs.Add(new Vector2(1, 1));*/
    101.         return result;
    102.     }
    (2) This is the code for deciding for which blocks to create a mesh:

    Code (CSharp):
    1. public List<MarchResult> chunkMesh = new List<MarchResult>();
    3.     private void __built_mesh(Chunk[,,] ChunkList, Action func)
    4.     {
    5.         chunkMesh.Clear();
    7.         for (int x = 0; x < chunk_size.x; x++)
    8.         {
    9.             for (int z = 0; z < chunk_size.z; z++)
    10.             {
    11.                 for (int y = 0; y < chunk_size.y; y++)
    12.                 {
    13.                     Block block = blocks[x, y, z];
    15.                     if (block.material != Material.Air)
    16.                     {
    17.                         List<Block> neighbors = __get_neighbors(block, ChunkList, x, y, z);
    18.                         List<BlockNeighbor> VisibleNeighbors = new List<BlockNeighbor>();
    19.                         bool isVisible = false;
    21.                         for (int i = 0; i < neighbors.Count; i++)
    22.                         {
    23.                             Block neighbor = neighbors[i];
    24.                             //if (neighbor.material != Material.Air)
    25.                             if (neighbor.material == Material.Air)
    26.                             {
    27.                                 BlockNeighbor bN = new BlockNeighbor();
    28.                                 bN.block = neighbor;
    29.                                 bN.position = neighbor.position - block.position;
    30.                                 VisibleNeighbors.Add(bN);
    32.                                 block.Visible = true;
    33.                                 isVisible = true;
    34.                             }
    35.                         }
    37.                         if (isVisible)
    38.                         {    
    40.                             List<MarchResult> result = March.calculateBlockMesh(block, VisibleNeighbors);
    41.                             chunkMesh.AddRange(result);
    42.                         }
    43.                     }
    44.                 }
    45.             }
    46.         }
    48.         updateMesh = true;
    49.         func();
    50.     }
    (3) This is the code for joining all the chunks and actually displaying the mesh:

    Code (CSharp):
    1.     public void DisplayChunks(Mesh mesh)
    2.     {
    3.         List<Color> newColors = new List<Color>();
    4.         List<Vector3> newNormals = new List<Vector3>();
    5.         List<Vector3> newVertices = new List<Vector3>();
    6.         List<Vector2> newUV = new List<Vector2>();
    7.         List<int> newTriangles = new List<int>();
    9.         int totalFaces = 0;
    11.         for (int i = 0; i < ChunksBuilt.Count; i++)
    12.         {
    13.             int3 cP = ChunksBuilt[i];
    14.             Chunk chunk = Chunks[cP.x, cP.y, cP.z];
    15.             chunk.updateMesh = false;
    17.             for (int k = 0; k < chunk.chunkMesh.Count; k++)
    18.             {
    19.                 MarchResult face = chunk.chunkMesh[k];
    21.                 newColors.AddRange(face.colors);
    22.                 newNormals.AddRange(face.normals);
    23.                 newVertices.AddRange(face.vertices);
    24.                 newUV.AddRange(face.uvs);
    26.                 for (int x = 0; x < face.triangles.Count; x++)
    27.                 {
    28.                     newTriangles.Add((totalFaces * 4) + face.triangles[x]);
    29.                 }
    31.                 totalFaces++;
    32.             }
    33.         }
    35.         //mesh.Clear();
    37.         mesh.vertices = newVertices.ToArray();
    38.         mesh.triangles = newTriangles.ToArray();
    40.         mesh.colors = newColors.ToArray();
    41.         mesh.normals = newNormals.ToArray();
    42.         mesh.uv = newUV.ToArray();
    44.         mesh.RecalculateNormals();
    45.         //mesh.Optimize();
    46.     }
    I belive it might be something with the totalFaces variable since I had trouble with that before, but I'm not too sure.

    How it looks with a mesh:


    You can see the cutout in the down corner right.

    How its supposed to look:


    Any help is appreciated
    Last edited: Apr 1, 2023
  2. Kurt-Dekker


    Mar 16, 2013
    There is a 65000-ish upper limit on vertices per mesh unless you enable 32-bit indexing. Perhaps this is the problem?

    Otherwise, perhaps you have a logic bug.

    Time to start debugging! Here is how you can begin your exciting new debugging adventures:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the names of the GameObjects or Components involved?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as

    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: or this answer for Android:

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    When in doubt, print it out!(tm)

    Note: the
    function is an alias for Debug.Log() provided by the MonoBehaviour class.
    Bunny83 and Bloxxy213 like this.
  3. Bloxxy213


    Mar 24, 2023
    Thanks! It turned out to be a issue with the indexing. Setting it up to 32 bit fixed it up, many thanks!!!

    additional question, is there any way to generate more meshes than one for a single mesh filter? Like a different mesh (with a different LOD) for every chunk, or do I have to code that myself and just make a giant mesh?

    I never used unity forums, is there any way to accept your answer as valid (except for liking)?
    Kurt-Dekker likes this.
  4. Kurt-Dekker


    Mar 16, 2013
    No, it's one Mesh, slotted into a MeshFilter that feeds into a MeshRenderer

    Just make more GameObjects and repeat! GameObjects are sorta just empty vessels anyway.

    If you want more procgen examples you're welcome to sniff around my MakeGeo project.

    MakeGeo is presently hosted at these locations:

    I believe you can flair your post as RESOLVED
    Bloxxy213 likes this.
  5. Bloxxy213


    Mar 24, 2023
    Thanks, I will look into MakeGeo and continue doing my research. I'll mark it as resolved, thanks!
    Kurt-Dekker likes this.
  6. Bunny83


    Oct 18, 2010
    May I ask what your chunk_size actually is? From the image it looks like 40? Minecraft's size of 16 has many practical reasons as it's a power of two number which makes converting between block and chunk coordinates much easier since the offset within the chunk are simply the lower 4 bits and the upper bits in the coordianate is essentially the chunk coordinate just shifted 4 bits. So a power of two size is certainly perferred. 16x16x16 is also a reasonable size for a chunk section. Though unfortunately it's just a bit too large for the worst case scenario to fit into a 16 bit index buffer.

    I also thought about reducing the chunksize to 8. Though that makes a chunk quite small. Note that a mesh with a 32 bit index buffer of course means the index buffer requires twice the memory for the same amount of data.

    Besides that when I think specifically about Minecraft, not every block has 6 faces. Things like fences stairs and some other block types consists of more than 6 faces per block. So to be future proof using a 32 bit index buffer is probably the best choice. You may use a chunk size of 32 or 64, though since a chunk needs to be rebuilded when it's changed, making it too large is probably not a good idea either :) Hopefully you have an older machine at hand where you can test your build game because when developing on a high end machine, the game may not run on average hardware. You don't want to build the next crysis :p
  7. Bloxxy213


    Mar 24, 2023
    In the image I used a 40x255x40 chunk so I could examine the bug further. I switched it to 16x256x16 after I resolved the issue.

    I also have a gtx 970 and a i5 10400, and it runs just as well when using the iGPU, I only gotta test it on my older android phone.