# 4. Burst Jobs that Write Mesh Buffers Part of [[Runtime Mesh Generation]]. Previous: [[3. The MeshData API and Vertex Layouts]]. Next: [[5. Colliders Chunks and Level Design]]. > [!warning] Code not compiled in Unity > Type-checked against 6000.5.8f1 plus the Burst, Collections and Mathematics assemblies (see the hub). Burst compilation, threading behaviour and visuals weren't tested. Here the payoff arrives. `MeshData.GetVertexData<T>()` returns a `NativeArray<T>` that points straight at the mesh's new buffer, and a `NativeArray` can go into a job. So worker threads write the mesh, with no copy, no `List<Vector3>` and no main-thread loop. ## 4.1 Install 1. **Window → Package Manager → Unity Registry → Burst**, version **1.8.31** (the version the 6000.5 manual lists as released for 6000.5). 2. **Collections** (6.5.0) and **Mathematics** (1.4.0) are built into the 6000.5 Editor. Check that they appear under *In Project*. If they don't, add them by name. 3. Restart the Editor if Burst asks you to. ## 4.2 The jobs ```csharp // Assets/Scripts/Meshes/HeightfieldJobs.cs using System.Runtime.InteropServices; using Unity.Burst; using Unity.Collections; using Unity.Jobs; using Unity.Mathematics; /// <summary> /// Burst jobs that write straight into Mesh.MeshData buffers. /// Vertex layout must match HeightfieldMesh.Layout exactly (float3, float3, float2 = 32 bytes). /// </summary> [StructLayout(LayoutKind.Sequential)] public struct HeightfieldVertex { public float3 Position; public float3 Normal; public float2 Uv; } [BurstCompile] public struct HeightfieldVertexJob : IJobParallelFor { public int CellsX; public int CellsZ; public float CellSize; public float Height; public float Frequency; public int Octaves; public float2 Offset; [WriteOnly] public NativeArray<HeightfieldVertex> Vertices; public void Execute(int index) { var x = index % (CellsX + 1); var z = index / (CellsX + 1); var p = new float2(x * CellSize, z * CellSize); var h = SampleHeight(p); // Central differences give a smooth normal without a second pass over triangles. var e = CellSize; var hl = SampleHeight(p - new float2(e, 0f)); var hr = SampleHeight(p + new float2(e, 0f)); var hd = SampleHeight(p - new float2(0f, e)); var hu = SampleHeight(p + new float2(0f, e)); var normal = math.normalize(new float3(hl - hr, 2f * e, hd - hu)); Vertices[index] = new HeightfieldVertex { Position = new float3(p.x, h, p.y), Normal = normal, Uv = new float2((float)x / CellsX, (float)z / CellsZ) }; } float SampleHeight(float2 p) { var sum = 0f; var amp = 1f; var freq = Frequency; var norm = 0f; for (var o = 0; o < Octaves; o++) { sum += noise.snoise((p + Offset) * freq) * amp; norm += amp; amp *= 0.5f; freq *= 2f; } return norm > 0f ? sum / norm * Height : 0f; } } /// <summary>One Execute per cell writes 6 indices. Uses 32-bit indices so any grid size works.</summary> [BurstCompile] public struct HeightfieldIndexJob : IJobParallelFor { public int CellsX; [NativeDisableParallelForRestriction, WriteOnly] public NativeArray<uint> Indices; public void Execute(int cell) { var x = cell % CellsX; var z = cell / CellsX; var bl = (uint)(z * (CellsX + 1) + x); var br = bl + 1; var tl = bl + (uint)(CellsX + 1); var tr = tl + 1; var o = cell * 6; Indices[o + 0] = bl; Indices[o + 1] = tl; Indices[o + 2] = tr; Indices[o + 3] = bl; Indices[o + 4] = tr; Indices[o + 5] = br; } } /// <summary>Bakes PhysX collision data off the main thread (Physics.BakeMesh is thread-safe for this).</summary> public struct BakeColliderJob : IJob { public UnityEngine.EntityId MeshId; public bool Convex; public void Execute() => UnityEngine.Physics.BakeMesh(MeshId, Convex); } ``` ### Reading the jobs - `HeightfieldVertex` uses `float3`/`float2` from Unity.Mathematics. They're Burst's native SIMD types, and they lay out the same as `Vector3`/`Vector2`, so the 32-byte layout from part 3 still holds. - **One `Execute` per vertex.** Index → `(x, z)` with `%` and `/`. Each call writes only `Vertices[index]`, so the safety system is happy with the default parallel-for restriction. - **Normals without a second pass.** `RecalculateNormals()` would run on the main thread *after* the job. Here, each vertex samples the height four more times (left, right, down, up). The normal of a heightfield `y = h(x, z)` is proportional to `(−∂h/∂x, 1, −∂h/∂z)`. Central differences give `(hl − hr, 2e, hd − hu)` before normalizing. It's four extra noise calls per vertex, all in parallel, and no seams between chunks that share an edge (part 5). - **`noise.snoise`** is Unity.Mathematics' 2D simplex noise, which returns roughly −1…1. Octaves sum halving amplitudes and doubling frequencies (fractal Brownian motion), normalized by the total amplitude. - **The index job writes 6 entries per cell.** Each cell writes index range `[cell*6, cell*6+6)`, which isn't the job's own index. So the array needs `[NativeDisableParallelForRestriction]`. That attribute is a promise **you** make that no two iterations touch the same element. The ranges don't overlap, so the promise holds. - `BakeColliderJob` is used in part 5. It isn't Burst-compiled because `Physics.BakeMesh` is a managed engine call. ## 4.3 The driver ```csharp // Assets/Scripts/Meshes/HeightfieldMesh.cs using Unity.Collections; using Unity.Jobs; using Unity.Mathematics; using UnityEngine; using UnityEngine.Rendering; /// <summary> /// Jobified heightfield: allocates writable MeshData, schedules Burst vertex + index jobs, /// completes them in LateUpdate, then applies to the Mesh. Optionally bakes a MeshCollider /// off the main thread. Call Regenerate() with a new offset to scroll the terrain. /// </summary> [RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))] public sealed class HeightfieldMesh : MonoBehaviour { public static readonly VertexAttributeDescriptor[] Layout = { new VertexAttributeDescriptor(VertexAttribute.Position, VertexAttributeFormat.Float32, 3), new VertexAttributeDescriptor(VertexAttribute.Normal, VertexAttributeFormat.Float32, 3), new VertexAttributeDescriptor(VertexAttribute.TexCoord0, VertexAttributeFormat.Float32, 2), }; [SerializeField, Min(1)] int cellsX = 255; [SerializeField, Min(1)] int cellsZ = 255; [SerializeField, Min(0.01f)] float cellSize = 0.5f; [SerializeField] float height = 12f; [SerializeField] float frequency = 0.02f; [SerializeField, Range(1, 8)] int octaves = 5; [SerializeField] Vector2 offset; [SerializeField] MeshCollider meshCollider; Mesh _mesh; Mesh.MeshDataArray _pending; bool _hasPending; JobHandle _handle; JobHandle _bakeHandle; bool _bakePending; public bool IsBuilding => _hasPending || _bakePending; void OnEnable() { _mesh = new Mesh { name = "HeightfieldMesh (runtime)" }; _mesh.MarkDynamic(); GetComponent<MeshFilter>().sharedMesh = _mesh; Regenerate(offset); } void OnDisable() { // Never leave a job writing into memory we are about to free. _handle.Complete(); _bakeHandle.Complete(); if (_hasPending) { _pending.Dispose(); _hasPending = false; } _bakePending = false; if (meshCollider != null) meshCollider.sharedMesh = null; if (_mesh != null) Destroy(_mesh); _mesh = null; } public void Regenerate(Vector2 newOffset) { if (_hasPending) return; // one build in flight at a time keeps ownership simple offset = newOffset; var vertexCount = (cellsX + 1) * (cellsZ + 1); var cellCount = cellsX * cellsZ; _pending = Mesh.AllocateWritableMeshData(1); _hasPending = true; var data = _pending[0]; data.SetVertexBufferParams(vertexCount, Layout); data.SetIndexBufferParams(cellCount * 6, IndexFormat.UInt32); var vertexJob = new HeightfieldVertexJob { CellsX = cellsX, CellsZ = cellsZ, CellSize = cellSize, Height = height, Frequency = frequency, Octaves = octaves, Offset = new float2(offset.x, offset.y), Vertices = data.GetVertexData<HeightfieldVertex>(0) }; var indexJob = new HeightfieldIndexJob { CellsX = cellsX, Indices = data.GetIndexData<uint>() }; var vh = vertexJob.Schedule(vertexCount, 256); var ih = indexJob.Schedule(cellCount, 256); _handle = JobHandle.CombineDependencies(vh, ih); JobHandle.ScheduleBatchedJobs(); } void LateUpdate() { if (_hasPending && _handle.IsCompleted) ApplyPending(); if (_bakePending && _bakeHandle.IsCompleted) { _bakeHandle.Complete(); _bakePending = false; // The bake is cached by PhysX, so this assignment is cheap now. meshCollider.sharedMesh = null; meshCollider.sharedMesh = _mesh; } } void ApplyPending() { _handle.Complete(); var vertexCount = (cellsX + 1) * (cellsZ + 1); var indexCount = cellsX * cellsZ * 6; var data = _pending[0]; data.subMeshCount = 1; var bounds = new Bounds( new Vector3(cellsX * cellSize * 0.5f, 0f, cellsZ * cellSize * 0.5f), new Vector3(cellsX * cellSize, height * 2f, cellsZ * cellSize)); data.SetSubMesh(0, new SubMeshDescriptor(0, indexCount) { bounds = bounds, vertexCount = vertexCount }, MeshUpdateFlags.DontRecalculateBounds | MeshUpdateFlags.DontValidateIndices); Mesh.ApplyAndDisposeWritableMeshData(_pending, _mesh, MeshUpdateFlags.DontRecalculateBounds | MeshUpdateFlags.DontValidateIndices); _hasPending = false; _mesh.bounds = bounds; if (meshCollider != null) { _bakeHandle = new BakeColliderJob { MeshId = _mesh.GetEntityId(), Convex = false }.Schedule(); _bakePending = true; } } } ``` ### Step by step 1. Create a GameObject called `Heightfield`, add **HeightfieldMesh**, and give the renderer a Lit material. Leave the defaults: 255 × 255 cells (65,536 vertices, so it uses UInt32 indices), 0.5 m cells, 12 m tall, 5 octaves. 2. Press Play. A 127.5 m square of hills appears after one frame. 3. Add this to scroll the terrain with WASD (test only): ```csharp // Assets/Scripts/Meshes/HeightfieldScroller.cs using UnityEngine; using UnityEngine.InputSystem; [RequireComponent(typeof(HeightfieldMesh))] public sealed class HeightfieldScroller : MonoBehaviour { [SerializeField] float speed = 20f; Vector2 _offset; HeightfieldMesh _field; void Awake() => _field = GetComponent<HeightfieldMesh>(); void Update() { var kb = Keyboard.current; if (kb == null) return; var move = Vector2.zero; if (kb.wKey.isPressed) move.y += 1f; if (kb.sKey.isPressed) move.y -= 1f; if (kb.dKey.isPressed) move.x += 1f; if (kb.aKey.isPressed) move.x -= 1f; if (move == Vector2.zero) return; _offset += move * speed * Time.deltaTime; _field.Regenerate(_offset); } } ``` 4. Open **Profiler → Timeline**. You should see `HeightfieldVertexJob` and `HeightfieldIndexJob` spread across the worker threads, and a short `ApplyAndDisposeWritableMeshData` on the main thread. Toggle **Jobs → Burst → Enable Compilation** off and on to compare. ### Why it's shaped like this - **Schedule in `Update` (or whenever you like), complete in `LateUpdate`.** `JobHandle.ScheduleBatchedJobs()` kicks the workers right away. `IsCompleted` lets the main thread skip waiting if the job isn't done. The mesh then updates on the next frame instead of stalling this one. For a hard one-frame guarantee, call `_handle.Complete()` unconditionally in `LateUpdate`. - **One build in flight.** `Regenerate` returns early while `_hasPending` is set. The writable `MeshDataArray` belongs to exactly one job chain until it's applied. That's the job-system version of *Double Buffer* ([[Game Programming Patterns (Review)]]): the visible mesh is read by the renderer while the next one is written somewhere else, and they're swapped in one call. - **`OnDisable` completes before disposing.** Freeing memory a worker is still writing into is the classic native crash. *Always* `Complete()` before `Dispose()`. - **`CombineDependencies`** lets the vertex and index jobs run **in parallel**, because they write different buffers. - **Batch size 256.** `Schedule(count, innerloopBatchCount)` hands out work in blocks. Small blocks balance better and cost more overhead. 64–1024 is the usual range. Measure. - **Bounds are analytic.** The grid's XZ size is known, and the height is at most `±height` because noise is normalized. So the job never needs a reduction pass. ## 4.4 Common changes - **Vertex colours by height:** add `VertexAttribute.Color, UNorm8, 4` to the layout and a `Color32`-sized field (`uint` or four `byte`s) to the struct. Write it in the vertex job. - **Deterministic worlds:** pass the world seed into `Offset` (for example, a hash of the seed to a `float2`). The same seed then gives the same hills on every machine, which matches [[Procedural Generation]]'s seeded approach. Floating-point noise can still differ slightly *across CPUs*. Don't make networked gameplay depend on exact heights. Sync the seed and let each client generate. - **Spline ribbons (roads, rivers):** the same pattern with one vertex pair per spline sample. Evaluate the spline into a `NativeArray<float3>` first (see [[Splines]]), then run a job that widens it.