public static Software.Texel.R32F[,] RandomR32F(Random r, int width, int height) { Software.Texel.R32F[,] data = new Software.Texel.R32F[height, width]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { data[y, x] = new Graphics.Software.Texel.R32F { R = (float)r.NextDouble() } } } ; return(data); }
public static Mesh Construct(MeshFromHeightmap metaResource) { if (!metaResource.PointSample) { throw new NotImplementedException("Use point sampling"); } var indexedPlane = Construct(metaResource.Grid); var gridPos = Common.Math.ToVector2(metaResource.Grid.Position); Vector2 gridStep = new Vector2(metaResource.Grid.Size.X / metaResource.Grid.NWidth, metaResource.Grid.Size.Y / metaResource.Grid.NHeight); int heightMapHeight = metaResource.Heightmap.Data.GetLength(0); int heightMapWidth = metaResource.Heightmap.Data.GetLength(1); for (int i = 0; i < indexedPlane.VertexBuffer.Count; i++) { var v = indexedPlane.VertexBuffer[i]; // A value between [0, 1] relative to the mesh Vector2 relativePosition = (Common.Math.ToVector2(v.Position) - gridPos); relativePosition.X /= metaResource.Grid.Size.X; relativePosition.Y /= metaResource.Grid.Size.Y; // And translate that position into the Rectangle square relativePosition.X = metaResource.Rectangle.X + relativePosition.X * metaResource.Rectangle.Width; relativePosition.Y = metaResource.Rectangle.Y + relativePosition.Y * metaResource.Rectangle.Height; int absolutePositionX = (int)(relativePosition.X * heightMapWidth); absolutePositionX = Common.Math.Clamp(absolutePositionX, 0, heightMapWidth - 1); int absolutePositionY = (int)(relativePosition.Y * heightMapHeight); absolutePositionY = Common.Math.Clamp(absolutePositionY, 0, heightMapHeight - 1); Texel.R32F height = metaResource.Heightmap.Data[absolutePositionY, absolutePositionX]; v.Position = new Vector3(v.Position.X, v.Position.Y, metaResource.Grid.Position.Z + height.R * metaResource.Height); // Calculate normal /*float hl = metaResource.Heightmap.Data[absolutePositionY, * Math.Max(absolutePositionX - 1, 0)].R; * float hr = metaResource.Heightmap.Data[absolutePositionY, * Math.Min(absolutePositionX + 1, heightMapWidth - 1)].R; * float ht = metaResource.Heightmap.Data[ * Math.Max(absolutePositionY - 1, 0), * absolutePositionX].R; * float hb = metaResource.Heightmap.Data[ * Math.Min(absolutePositionY + 1, heightMapHeight - 1), * absolutePositionX].R; * Vector3 l = new Vector3(-gridStep.X, 0, hl - height.R); * Vector3 r = new Vector3(+gridStep.X, 0, hr - height.R); * Vector3 t = new Vector3(0, -gridStep.Y, ht - height.R); * Vector3 b = new Vector3(0, +gridStep.Y, hb - height.R); * Vector3 n = Vector3.Cross(l, t) + Vector3.Cross(r, b); * n.Normalize(); * v.Normal = n;*/ v.Normal = TextureUtil.NormalFromHeightmap(metaResource.Heightmap.Data, relativePosition, gridStep, new Size(heightMapWidth, heightMapHeight)); indexedPlane.VertexBuffer[i] = v; } //indexedPlane.RecalcNormals(); return(indexedPlane); }