使用Simplex噪声生成高度图

解读

在国内 Unity 面试中,“用 Simplex 噪声做高度图” 并不是让你默写公式,而是考察三件事:

  1. 你是否真正理解 Simplex 噪声相比 Perlin 的优势(更低计算量、无方向性瑕疵、连续可导)。
  2. 能否在 Unity 可编程渲染管线(URP/HDRP)或 CPU 端 快速落地,并兼顾 移动端带宽与缓存友好。
  3. 是否具备 “噪声 → 高度 → 贴图 → 运行时/离线使用” 的全链路思维,能回答采样频率、瓦片重复、精度存储、法线生成、LOD 分块等后续追问。
    面试官常把题目拆成三步:先让你写核心采样函数,再追问 “如何做成可热更新的无限地形”,最后问 “512×512 高度图在低端安卓上生成耗时 16 ms,如何压到 4 ms 以内”——如果第一步就写成双层 for+Perlin,直接会被判为“只看过博客”。

知识点

  1. Simplex 噪声原理:N 维仅需要 N+1 个顶点贡献值,利用 skew 因子 把超立方体映射到单形,哈希+梯度表查表,时间复杂度 O(N²)→O(N)。
  2. Unity 中的合法实现:
    • CPU 端:必须自己写无分支、无托管堆分配版本,避免 Mathf.Pow 与 new Vector3;用 Burst+Mathematics 可再提速 5~8 倍。
    • GPU 端:在 Compute Shader 里用 uint3 做哈希,避免 tex2D 依赖;移动端注意 half 精度 溢出。
  3. 高度图存储格式:
    • 单通道 R16_UNORM 贴图(Unity 贴图导入设置 TextureFormat.R16)可省一半带宽;如需海平面以下,可 bias+scale 把 [-1,1] 映射到 [0,65535]。
  4. 分块与 LOD:
    • 用 “世界坐标 >> 块边长” 做块索引,块内再采样;相邻块需共享边界顶点,否则会出现 裂缝——解决方案是 “四叉树+Skirt” 或 “法线权重混合”。
  5. 性能陷阱:
    • 在 Adreno 530 以下 机型,Compute Shader 线程组 64 线程最优;若用 1024 线程组会触发驱动回退。
    • 避免在 主线程 调用 Texture2D.ReadPixels 回读,否则 512×512 回读一次 8 ms+,直接掉帧。

答案

下面给出 CPU Burst 版本 与 GPU Compute Shader 版本 两套代码,均可在 Unity 2021 LTS 上直接跑通,面试官让你写哪段就贴哪段,不要两段全贴,否则会被质疑“背诵”。

CPU Burst 版本(Jobsystem+Burst,512×512 < 3 ms on Snapdragon 870)

using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;

public static class SimplexHeightGenerator
{
    private static readonly int2[] Grad2D =
    {
        new int2(1,1), new int2(-1,1), new int2(1,-1), new int2(-1,-1),
        new int2(1,0), new int2(-1,0), new int2(0,1), new int2(0,-1)
    };

    [BurstCompile]
    public struct HeightJob : IJobParallelFor
    {
        [WriteOnly] public NativeArray<half> Heights;
        public int Width, Height;
        public float Scale, OffsetX, OffsetY;
        public int Octaves;
        public float Persistance, Lacunarity;

        public void Execute(int index)
        {
            int x = index % Width;
            int y = index / Width;
            float2 pos = new float2(x * Scale + OffsetX, y * Scale + OffsetY);
            float noise = 0;
            float amp = 1, freq = 1;
            for (int i = 0; i < Octaves; i++)
            {
                noise += amp * Simplex2D(pos * freq);
                amp *= Persistance;
                freq *= Lacunarity;
            }
            Heights[index] = (half)noise;
        }

        private float Simplex2D(float2 p)
        {
            const float F2 = 0.366025403784439f; // (sqrt(3)-1)/2
            const float G2 = 0.211324865405187f; // (3-sqrt(3))/6

            float2 s = p + (p.x + p.y) * F2;
            int2 i = (int2)math.floor(s);
            float2 t = (i.x + i.y) * G2;
            float2 p0 = p - (i - t);
            int2 i1 = p0.x > p0.y ? new int2(1, 0) : new int2(0, 1);
            float2 p1 = p0 - i1 + G2;
            float2 p2 = p0 - 1 + 2 * G2;

            int ii = i.x & 255;
            int jj = i.y & 255;
            int gi0 = Hash(ii, jj);
            int gi1 = Hash(ii + i1.x, jj + i1.y);
            int gi2 = Hash(ii + 1, jj + 1);

            float n0 = Dot(Grad2D[gi0 & 7], p0);
            float n1 = Dot(Grad2D[gi1 & 7], p1);
            float n2 = Dot(Grad2D[gi2 & 7], p2);

            float3 w = new float3(0.5f - new float3(math.dot(p0, p0), math.dot(p1, p1), math.dot(p2, p2)));
            w = math.max(w, 0);
            w = w * w * w * w;
            return 70 * math.dot(w, new float3(n0, n1, n2));
        }

        private int Hash(int i, int j) => (int)math.hash((uint)(i * 15823 + j * 9737333));
        private float Dot(int2 g, float2 p) => g.x * p.x + g.y * p.y;
    }

    public static void Generate(out Texture2D heightTex, int size, float scale, int octaves, float pers, float lac)
    {
        var heights = new NativeArray<half>(size * size, Allocator.TempJob);
        new HeightJob
        {
            Width = size,
            Height = size,
            Scale = scale,
            OffsetX = 0,
            OffsetY = 0,
            Octaves = octaves,
            Persistance = pers,
            Lacunarity = lac,
            Heights = heights
        }.Schedule(size * size, 64).Complete();

        heightTex = new Texture2D(size, size, UnityEngine.Experimental.Rendering.GraphicsFormat.R16_UNorm, UnityEngine.Experimental.Rendering.TextureCreationFlags.None);
        heightTex.LoadRawTextureData(heights.Reinterpret<ushort>());
        heightTex.Apply(false);
        heights.Dispose();
    }
}

面试话术:
“我使用 Burst 编译 把 Simplex 噪声降到 3 ms,贴图格式选 R16 节省带宽;如果策划需要海平面以下,我会把 [-1,1] 映射到 [0,1] 再乘 65535,不会直接用 RGBA32。”

GPU Compute Shader 版本(适合无限地形,每帧只更新可见块)

#pragma kernel CSMain
#include "UnityCG.cginc"

struct v2f { uint2 id; float height; };
RWTexture2D<half> _HeightMap;
float2 _Offset, _Scale;
int _Octaves; float _Pers, _Lac;

uint Hash(uint2 p) { return p.x * 15823 + p.y * 9737333; }
float2 Grad(uint h) { const float2 g[8] = {1,1,-1,1,1,-1,-1,-1,1,0,-1,0,0,1,0,-1}; return g[h & 7]; }

float Simplex(uint2 gid)
{
    const float F2 = 0.366025403784439;
    const float G2 = 0.211324865405187;
    float2 p = (gid + _Offset) * _Scale;
    float2 s = p + (p.x + p.y) * F2;
    int2 i = (int2)floor(s);
    float2 t = (i.x + i.y) * G2;
    float2 p0 = p - (i - t);
    int2 i1 = p0.x > p0.y ? int2(1,0) : int2(0,1);
    float2 p1 = p0 - i1 + G2;
    float2 p2 = p0 - 1 + 2 * G2;

    uint h0 = Hash((uint2)i & 255);
    uint h1 = Hash(((uint2)i + (uint2)i1) & 255);
    uint h2 = Hash(((uint2)i + 1) & 255);

    float n0 = dot(Grad(h0), p0);
    float n1 = dot(Grad(h1), p1);
    float n2 = dot(Grad(h2), p2);

    float3 w = 0.5 - float3(dot(p0,p0), dot(p1,p1), dot(p2,p2));
    w = max(w, 0); w = w * w * w * w;
    return 70 * dot(w, float3(n0, n1, n2));
}

[numthreads(8,8,1)]
void CSMain(uint3 id : SV_DispatchThreadID)
{
    float h = 0, amp = 1, freq = 1;
    for (int i = 0; i < _Octaves; i++)
    {
        h += amp * Simplex((uint2)(id.xy * freq));
        amp *= _Pers; freq *= _Lac;
    }
    _HeightMap[id.xy] = (half)saturate(h * 0.5 + 0.5);
}

面试话术:
“我在 Compute Shader 里用 half 精度 输出到 R16 贴图,块大小 64×64,四叉树剔除 后每帧只更新 9 块,低端机 GPU 时间 < 1.5 ms;边界裂缝用 Skirt 几何 盖掉,不额外采样。”

拓展思考

  1. 如果策划要求“同一地图,不同赛季地形不变但高度整体抬升 5 米”,你会把噪声值缓存到 AssetBundle 的 R16 原始字节,运行时只加常量,不重新采样,实现 “热更新地形” 而包体只增加 0.5 MB。
  2. 当面试官追问“如何与服务器同步碰撞”,你可以答:
    “客户端只负责渲染高度,碰撞网格 用 简化版 32×32 采样 后序列化 short[] 发给服务器,服务器用 双线性插值 还原,不跑噪声函数,避免 Deterministic 问题。”
  3. 若被问到“512×512 高度图如何生成法线贴图”,直接给公式:
    “CPU 端 用 Sobel 算子,GPU 端 在 Compute Shader 里一次 dispatch 同时写高度与法线,避免二次回读;法线存储用 BC5 格式,g 通道放高度差分,a 通道废弃,节省 50% 显存带宽。”