How to Build a Low Poly Terrain Mesh with Dynamic Resolution
Use small triangles for ridges and gullies, and large ones for flat ground. That's the idea behind dynamic terrain mesh resolution. The left side shows the common approach, a uniform grid with the same density everywhere. The right side shows dynamic resolution. Both meshes can reach the same subdivision depth, but the adaptive mesh spends those splits where the terrain needs detail.

Both wireframes come from one 65 by 65 heightmap in Unity. Uniform subdivision uses 2,048 triangles. Dynamic subdivision uses 473 triangles with the same depth limit and a split tolerance of 0.20 world units. That's about 77% fewer triangles for this heightmap.
1. Start with two triangles
A heightmap is a grid of numbers. Each number tells you how high the ground is at one point. In Unity, X and Z are the ground coordinates, and the number from the heightmap becomes Y.
Take the four corners of the heightmap. Draw a diagonal between the top left and bottom right corners. You now have two triangles that cover the whole terrain. Those are the two roots of the subdivision tree.
The code keeps triangle corners in heightmap coordinates using Vector2Int. In each triangle, a is the right angle, and b and c are the ends of its longest edge in the ground plane. Both roots share that longest edge. We read heights when we test a triangle or turn it into a Unity mesh.
Paste the following code blocks in order into a file called HeightmapMesh.cs. Together they form one class. The first block starts the class and shows the order of the build. The remaining blocks add the functions it calls.
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
public static class HeightmapMesh
{
public static Mesh Build(float[,] heights, int baseDepth, float tolerance, bool flat, int maxDepth)
{
int size = heights.GetLength(0) - 1;
if (size < 1 || heights.GetLength(1) != size + 1 || (size & (size - 1)) != 0)
throw new ArgumentException("Use a square heightmap with 2^n + 1 samples.");
var leaves = new List<(Vector2Int a, Vector2Int b, Vector2Int c)>();
var points = new HashSet<Vector2Int>();
var sharedIndices = new Dictionary<Vector2Int, int>();
var vertices = new List<Vector3>();
var indices = new List<int>();
var bottomLeft = new Vector2Int(0, 0);
var topLeft = new Vector2Int(0, size);
var bottomRight = new Vector2Int(size, 0);
var topRight = new Vector2Int(size, size);
Refine(bottomLeft, topLeft, bottomRight, 0);
Refine(topRight, bottomRight, topLeft, 0);
foreach (var (a, b, c) in leaves)
Stitch(a, b, c);
var mesh = new Mesh { indexFormat = vertices.Count < 65535 ? IndexFormat.UInt16 : IndexFormat.UInt32 };
mesh.SetVertices(vertices);
mesh.SetTriangles(indices, 0);
mesh.RecalculateNormals();
return mesh;2. Split one triangle into two
To split a triangle, find the midpoint of its longest edge. Draw a line from the opposite corner to that midpoint. You get two smaller triangles. Give both children the midpoint as their first corner. Their longest edges are now the other two edges of the parent, so the same split rule works again.

A triangle that splits is a parent. The two triangles it creates are its children. A triangle that stops splitting is a leaf. Save the leaves for the mesh and record their corner points for the seam fix in step 4.
In the demo, baseDepth = 6 gives us a starting mesh of 128 triangles. Beyond that, the error test decides whether to split. maxDepth = 10 caps the amount of subdivision, even if a triangle still exceeds the tolerance.
void Refine(Vector2Int a, Vector2Int b, Vector2Int c, int depth)
{
if (depth < maxDepth && TryMidpoint(b, c, out var middle)
&& (depth < baseDepth || HasError(a, b, c)))
{
Refine(middle, c, a, depth + 1);
Refine(middle, a, b, depth + 1);
return;
}
leaves.Add((a, b, c));
points.Add(a);
points.Add(b);
points.Add(c);
}3. Decide when a triangle needs more detail
Imagine a triangle with all three corners at height 1. The face Unity would draw is flat at height 1. If a heightmap sample inside it says 1.6, the face misses a bump by 0.6 units. With a tolerance of 0.20, split the triangle and test each child.

When the corners have different heights, work out the height on the triangle at each sample point. The code calculates three weights, one per corner. A sample halfway between two corners has weights of 0.5 for each of them and zero for the third. Multiply each corner height by its weight and add the results. If any weight is negative, the point is outside the triangle and the test skips it.
This is a vertical error test. A steep but straight slope can pass because the triangle already represents it well. A small dip on flat ground can fail.
bool HasError(Vector2Int a, Vector2Int b, Vector2Int c)
{
float ha = Height(a), hb = Height(b), hc = Height(c);
float area = Cross(b - a, c - a);
for (int z = Mathf.Min(a.y, b.y, c.y); z <= Mathf.Max(a.y, b.y, c.y); z++)
for (int x = Mathf.Min(a.x, b.x, c.x); x <= Mathf.Max(a.x, b.x, c.x); x++)
{
var p = new Vector2Int(x, z);
float u = Cross(b - p, c - p) / area;
float v = Cross(c - p, a - p) / area;
float w = Cross(a - p, b - p) / area;
if (u < 0 || v < 0 || w < 0) continue;
if (Mathf.Abs(Height(p) - (u * ha + v * hb + w * hc)) > tolerance)
return true;
}
return false;
}4. Close the gaps and build the mesh
Suppose two triangles share edge B to C. Split one triangle and its new edge ends at midpoint M. The neighboring triangle still has one unbroken edge from B to C, so the new edge meets it in a T-junction. If M sits above or below the straight edge in 3D, a crack opens. Split the neighbor at M so both sides follow the same two segments.

The stitch pass checks all three edges of each leaf. If it finds a midpoint already used by another leaf, it splits along that edge and checks the two new triangles again. This can require a split on an edge that is shorter than the longest edge. The goal here is to match the neighboring boundary. The tolerance was tested before stitching, so test the final faces separately if you need a strict error bound.
void Stitch(Vector2Int a, Vector2Int b, Vector2Int c)
{
if (TryMidpoint(b, c, out var bc) && points.Contains(bc))
{
Stitch(a, b, bc);
Stitch(a, bc, c);
}
else if (TryMidpoint(c, a, out var ca) && points.Contains(ca))
{
Stitch(b, c, ca);
Stitch(b, ca, a);
}
else if (TryMidpoint(a, b, out var ab) && points.Contains(ab))
{
Stitch(c, a, ab);
Stitch(c, ab, b);
}
else
{
indices.Add(Index(a));
indices.Add(Index(b));
indices.Add(Index(c));
}
}To draw the terrain, turn grid coordinates into Unity positions by scaling X and Z and reading Y from the heightmap. For flat shading, give each triangle its own three vertices. Then RecalculateNormals gives each face its own lighting direction. For smooth shading, reuse vertex indices when positions match.
float Height(Vector2Int point) => heights[point.y, point.x];
int Index(Vector2Int point)
{
if (!flat && sharedIndices.TryGetValue(point, out int found)) return found;
int index = vertices.Count;
vertices.Add(new Vector3(20f * point.x / size, Height(point), 20f * point.y / size));
if (!flat) sharedIndices.Add(point, index);
return index;
}
}
static int Cross(Vector2Int a, Vector2Int b) => a.x * b.y - a.y * b.x;
static bool TryMidpoint(Vector2Int a, Vector2Int b, out Vector2Int middle)
{
Vector2Int sum = a + b;
middle = sum / 2;
return sum.x % 2 == 0 && sum.y % 2 == 0 && middle != a && middle != b;
}
}On a GameObject with a MeshFilter and MeshRenderer, assign a material and set meshFilter.sharedMesh = HeightmapMesh.Build(heights, 6, 0.20f, true, 10). Use a square heightmap with 65 samples on each side for the example settings. To try the uniform baseline, set both depths to 10.

5. Check the result
Start flat. Set every height to 1. With the demo settings you should get the 128 base triangles, since there is no error to trigger more splits.
Add a bump. Raise a few samples on one side. In the wireframe, look for smaller triangles near the bump and larger triangles elsewhere.
Inspect the joins. Follow a shared edge between coarse and fine triangles. Both sides should use the same segments, with no point sitting partway down an unsplit edge.
This sample builds one chunk on the main thread. Part 2 shows how to distribute terrain work across chunks with Unity Jobs.
Dynamic terrain mesh resolution in Polaris
We implemented adaptive mesh density in Polaris, a mesh terrain editor for Unity. Its Geometry settings expose base and maximum mesh resolution, and its geometry generation uses Unity's C# Job System to run work on worker threads where multithreading is available. You can edit the terrain with the geometry painting tools.

FAQ
Does dynamic resolution change as the camera moves? No. This sample builds the mesh from the heightmap, the height error tolerance, and the subdivision depth settings. Moving the camera doesn't change the mesh.
Can I pass a rectangular heightmap to this sample? No. The sample requires a square heightmap with 2^n + 1 samples per side, such as 65 or 129. To cover a rectangular terrain, build multiple square chunks and match their borders, as described in Part 2.
Why are there small triangles on flat ground? When a neighboring triangle adds a midpoint along a shared edge, the triangle on the flat side also splits there. Both sides then use the same edge segments, which prevents a crack.
Try it
Run the generator twice on the same heightmap with two tolerances, or get Polaris Summit on the Unity Asset Store.



Comments