diff --git a/Terrain2/Shaders.metal b/Terrain2/Shaders.metal index 57a7c3b..e59000d 100644 --- a/Terrain2/Shaders.metal +++ b/Terrain2/Shaders.metal @@ -30,7 +30,7 @@ typedef struct } ColorInOut; vertex ColorInOut vertexShader(Vertex in [[stage_in]], - texture2d heights [[texture(0)]], + texture2d heights [[texture(0)]], constant Uniforms & uniforms [[buffer(BufferIndexUniforms)]]) { constexpr sampler s(coord::pixel, address::clamp_to_zero, filter::linear); @@ -39,9 +39,9 @@ vertex ColorInOut vertexShader(Vertex in [[stage_in]], // TODO: Concerned about this. uint2 gridCoord(in.texCoord.x * heights.get_width(), in.texCoord.y * heights.get_height()); - half4 height = heights.read(gridCoord).rrrr; + float4 height = heights.read(gridCoord).rrrr; - float4 position(in.position.x, float(height.r), in.position.z, 1.0); + float4 position(in.position.x, height.r, in.position.z, 1.0); out.position = uniforms.projectionMatrix * uniforms.modelViewMatrix * position; out.texCoord = in.texCoord; diff --git a/Terrain2/Terrain.swift b/Terrain2/Terrain.swift index 459e95c..58be84c 100644 --- a/Terrain2/Terrain.swift +++ b/Terrain2/Terrain.swift @@ -70,6 +70,28 @@ class Terrain: NSObject { return try MTKMesh(mesh:plane, device:device) } + class func buildHeightsTexture(dimensions: uint2, device: MTLDevice) -> MTLTexture? { + let heightsDesc = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .r32Float, width: Int(dimensions.x), height: Int(dimensions.y), mipmapped: false) + heightsDesc.usage = [.shaderRead, .shaderWrite] + let tex = device.makeTexture(descriptor: heightsDesc) + + if let tex = tex { + var initialHeights = [Float]() + let numberOfHeights = tex.height * tex.width + initialHeights.reserveCapacity(numberOfHeights) + for _ in 0...stride * tex.width + tex.replace(region: region, mipmapLevel: 0, withBytes: initialHeights, bytesPerRow: bytesPerRow) + } + + return tex + } + let dimensions: float2 let segments: uint2 let vertexDescriptor: MTLVertexDescriptor @@ -88,9 +110,8 @@ class Terrain: NSObject { return nil } - let heightsDesc = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .r16Float, width: Int(segments.x), height: Int(segments.y), mipmapped: false) - heightsDesc.usage = [.shaderRead, .shaderWrite] - guard let tex = device.makeTexture(descriptor: heightsDesc) else { + let heightsDimensions = segments + guard let tex = Terrain.buildHeightsTexture(dimensions: heightsDimensions, device: device) else { print("Couldn't create heights texture") return nil }