(Voxel game) Only part of the mesh is generated

[SOLVED]

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:

    private MarchResult calculateBlockSide(Block block, string side, float3[] blockCorners)
    {
        MarchResult result = new MarchResult();

        switch (side)
        {
            case "top":

                result.vertices.Add(blockCorners[5]);
                result.vertices.Add(blockCorners[4]);
                result.vertices.Add(blockCorners[7]);
                result.vertices.Add(blockCorners[6]);

                break;
            case "bottom":

                result.vertices.Add(blockCorners[0]);
                result.vertices.Add(blockCorners[1]);
                result.vertices.Add(blockCorners[2]);
                result.vertices.Add(blockCorners[3]);

                break;
            case "left":

                result.vertices.Add(blockCorners[7]);
                result.vertices.Add(blockCorners[4]);
                result.vertices.Add(blockCorners[0]);
                result.vertices.Add(blockCorners[3]);

                break;
            case "right":

                result.vertices.Add(blockCorners[5]);
                result.vertices.Add(blockCorners[6]);
                result.vertices.Add(blockCorners[2]);
                result.vertices.Add(blockCorners[1]);

                break;
            case "back":

                result.vertices.Add(blockCorners[4]);
                result.vertices.Add(blockCorners[5]);
                result.vertices.Add(blockCorners[1]);
                result.vertices.Add(blockCorners[0]);

                break;
            case "front":

                result.vertices.Add(blockCorners[6]);
                result.vertices.Add(blockCorners[7]);
                result.vertices.Add(blockCorners[3]);
                result.vertices.Add(blockCorners[2]);

                break;
        }

        result.triangles.Add(0);
        result.triangles.Add(1);
        result.triangles.Add(3);

        result.triangles.Add(1);
        result.triangles.Add(2);
        result.triangles.Add(3);

        return result;
    }

    public List<MarchResult> calculateBlockMesh(Block block, List<BlockNeighbor> neighbors)
    {     
        List<MarchResult> result = new List<MarchResult>(8);
     
        float3[] blockCorners = new float3[]
        {
            CornerTable[0] + block.position,
            CornerTable[1] + block.position,
            CornerTable[2] + block.position,
            CornerTable[3] + block.position,
            CornerTable[4] + block.position,
            CornerTable[5] + block.position,
            CornerTable[6] + block.position,
            CornerTable[7] + block.position,
        };

        for (int i = 0; i < neighbors.Count; i++)
        {
            string name = NormalDefinitions[Normals.IndexOf(neighbors[i].position)];
            MarchResult sideResult = calculateBlockSide(block, name, blockCorners);
         
            result.Add(sideResult);
        }



        /*result.uvs.AddRange(uvs);
        result.normals.AddRange(normals);*/

        /*result.uvs.Add(new Vector2(0, 0));
        result.uvs.Add(new Vector2(0, 1));
        result.uvs.Add(new Vector2(1, 1));*/
     
        return result;
    }

(2) This is the code for deciding for which blocks to create a mesh:

public List<MarchResult> chunkMesh = new List<MarchResult>();

    private void __built_mesh(Chunk[,,] ChunkList, Action func)
    { 
        chunkMesh.Clear();
     
        for (int x = 0; x < chunk_size.x; x++)
        {
            for (int z = 0; z < chunk_size.z; z++)
            {
                for (int y = 0; y < chunk_size.y; y++)
                {
                    Block block = blocks[x, y, z];

                    if (block.material != Material.Air)
                    {
                        List<Block> neighbors = __get_neighbors(block, ChunkList, x, y, z);
                        List<BlockNeighbor> VisibleNeighbors = new List<BlockNeighbor>();
                        bool isVisible = false;

                        for (int i = 0; i < neighbors.Count; i++)
                        {
                            Block neighbor = neighbors[i];
                            //if (neighbor.material != Material.Air)
                            if (neighbor.material == Material.Air)
                            {
                                BlockNeighbor bN = new BlockNeighbor();
                                bN.block = neighbor;
                                bN.position = neighbor.position - block.position;
                                VisibleNeighbors.Add(bN);
                             
                                block.Visible = true;
                                isVisible = true;
                            }
                        }

                        if (isVisible)
                        {     
                                             
                            List<MarchResult> result = March.calculateBlockMesh(block, VisibleNeighbors);
                            chunkMesh.AddRange(result);
                        }
                    }
                }
            }
        }

        updateMesh = true;
        func();
    }

(3) This is the code for joining all the chunks and actually displaying the mesh:

    public void DisplayChunks(Mesh mesh)
    {
        List<Color> newColors = new List<Color>();
        List<Vector3> newNormals = new List<Vector3>();
        List<Vector3> newVertices = new List<Vector3>();
        List<Vector2> newUV = new List<Vector2>();
        List<int> newTriangles = new List<int>();

        int totalFaces = 0;

        for (int i = 0; i < ChunksBuilt.Count; i++)
        {
            int3 cP = ChunksBuilt[i];
            Chunk chunk = Chunks[cP.x, cP.y, cP.z];
            chunk.updateMesh = false;

            for (int k = 0; k < chunk.chunkMesh.Count; k++)
            {
                MarchResult face = chunk.chunkMesh[k];

                newColors.AddRange(face.colors);
                newNormals.AddRange(face.normals);
                newVertices.AddRange(face.vertices);
                newUV.AddRange(face.uvs);

                for (int x = 0; x < face.triangles.Count; x++)
                {
                    newTriangles.Add((totalFaces * 4) + face.triangles[x]);
                }

                totalFaces++;
            }
        }

        //mesh.Clear();

        mesh.vertices = newVertices.ToArray();
        mesh.triangles = newTriangles.ToArray();

        mesh.colors = newColors.ToArray();
        mesh.normals = newNormals.ToArray();
        mesh.uv = newUV.ToArray();

        mesh.RecalculateNormals();
        //mesh.Optimize();
    }

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:

8920259--1221959--upload_2023-4-1_17-22-7.png

You can see the cutout in the down corner right.

How its supposed to look:

8920259--1221962--upload_2023-4-1_17-23-34.png

Any help is appreciated

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 Debug.Log() 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 Debug.Log("Problem!",this);

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: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

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:

https://discussions.unity.com/t/839300/3

When in doubt, print it out!™

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

2 Likes

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)?

1 Like

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:

https://bitbucket.org/kurtdekker/makegeo

I believe you can flair your post as RESOLVED

1 Like

Thanks, I will look into MakeGeo and continue doing my research. I’ll mark it as resolved, thanks!

1 Like

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 :slight_smile: 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 :stuck_out_tongue:

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.