title: How to create a 3D mesh from a heightmap represented as a float array
body: <p>I am attempting to understand how a 3D mesh has been constructed from a heightmap stored as a one dimensional float array. The only examples I have seen previously have made use of a 2D float array, and I am struggling to wrap my head around the math involved here. Any insight into it would be appreciated. I have commented the code which I do not quite understand yet for your convenience.</p>
  <p>Source of code: <a href="https://github.com/SebLague/Hydraulic-Erosion" rel="nofollow noreferrer">https://github.com/SebLague/Hydraulic-Erosion</a></p>
  <pre><code>public void ContructMesh () {
      Vector3[] verts = new Vector3[mapSize * mapSize];
      int[] triangles = new int[(mapSize - 1) * (mapSize - 1) * 6];
      int t = 0;
      //Note that default mapSize is 255
      for (int i = 0; i &lt; mapSize * mapSize; i++) {
          //Following code is not properly understood
          int x = i % mapSize;
          int y = i / mapSize;
          int meshMapIndex = y * mapSize + x;
  
          Vector2 percent = new Vector2 (x / (mapSize - 1f), y / (mapSize - 1f));
          Vector3 pos = new Vector3 (percent.x * 2 - 1, 0, percent.y * 2 - 1) * scale;
  
          pos += Vector3.up * map[meshMapIndex] * elevationScale; //Elevation scale is 20 by default
          verts[meshMapIndex] = pos;
  
          //End of misunderstood code
          if (x != mapSize - 1 &amp;&amp; y != mapSize - 1) {
              t = (y * (mapSize - 1) + x) * 3 * 2;
  
              triangles[t + 0] = meshMapIndex + mapSize;
              triangles[t + 1] = meshMapIndex + mapSize + 1;
              triangles[t + 2] = meshMapIndex;
  
              triangles[t + 3] = meshMapIndex + mapSize + 1;
              triangles[t + 4] = meshMapIndex + 1;
              triangles[t + 5] = meshMapIndex;
              t += 6;
          }
      }
      Mesh mesh = new Mesh();
      mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
      mesh.vertices = verts;
      mesh.triangles = triangles;
      mesh.RecalculateNormals ();
  </code></pre>