#### Mesh generation algorithm gives visual artifacts

Right now I am trying to implement terrain generation. I am using msvc visual studio 2019. And when I got to decreasing level of details in my function, generation started to be very glitchy. Everything is fine when I am not using any of level of details decreasing values. But everything changes after 1 and more – generation starts to be glitchy and generates atifacts. Here is some examples.

This one is correct as it should be. In my function this stands for parameter 0 in LevelOfDetails. And Incorect examples. LevelOfDetails=1: This is a function for generating meshes:

``````static void
GenerateTerrainMesh(world* World, noise_map* NoiseMap, float HeightMultiplier, int LevelOfDetail)
{
int Width  = NoiseMap->Width;
int Height = NoiseMap->Height;
//float TopLeftX = (Width - 1)  / (-2.0f);
//float TopLeftZ = (Height - 1) / ( 2.0f);

if(LevelOfDetail < 0) LevelOfDetail = 0;
if(LevelOfDetail > 6) LevelOfDetail = 6;

int SimplificationInc = (LevelOfDetail == 0) ? 1 : (LevelOfDetail * 2);
int VerticesPerLineX  = (Width  - 1) / SimplificationInc + 1;
int VerticesPerLineY  = (Height - 1) / SimplificationInc + 1;

InitializeMeshTerrain(World, VerticesPerLineX, VerticesPerLineX);

int VertIndex = 0;
int TrigIndex = 0;
for(int Y = 0; Y < Height; Y += SimplificationInc)
{
for(int X = 0; X < Width; X += SimplificationInc)
{
World->Terrain.Vertices[VertIndex] = V3((float)X, HeightMultiplier * HeightFlatten(World->NoiseMap.Values[Y*World->NoiseMap.Width + X]).y * HeightMultiplier, (float)Y);
World->Terrain.UVs[VertIndex]      = V2(X/(float)Width, Y/(float)Height);

if((X < (Width - 1)) && (Y < (Height - 1)))
{
AddTriangle(World, &TrigIndex, VertIndex, VertIndex + VerticesPerLineX + 1, VertIndex + VerticesPerLineX);

AddTriangle(World, &TrigIndex, VertIndex + VerticesPerLineX + 1, VertIndex, VertIndex + 1);
}

VertIndex += 1;
}
}
}
``````

And helper functions, but there should not be any errors:

``````static void
InitializeMeshTerrain(world* World, int Width, int Height)
{
World->Terrain.VerticesCount = Width * Height;
World->Terrain.FacesCount    = (Width - 1)*(Height - 1)*2;
World->Terrain.UVCount       = Width * Height;

World->Terrain.Faces    = (face*)malloc(sizeof(face)*World->Terrain.FacesCount);
World->Terrain.Vertices = (v3*)malloc(sizeof(v3)*World->Terrain.VerticesCount);
World->Terrain.UVs      = (v2*)malloc(sizeof(v2)*World->Terrain.UVCount);
}

static void
AddTriangle(world* World, int* Index, int a, int b, int c)
{
World->Terrain.Faces[*Index].a = a;
World->Terrain.Faces[*Index].b = b;
World->Terrain.Faces[*Index].c = c;

*Index += 1;
}
``````

What problem could be there? Thank you.

Source: Windows Questions C++