Integrate DICOM series and Metal volume viewer
This commit is contained in:
1 parent
48177fc7fb
commit
c7f9af8025
7 files changed
+696
-6
No files matched your search
@@ -0,0 +1,179 @@
|
||||
import MetalKit
|
||||
import SwiftUI
|
||||
import simd
|
||||
|
||||
struct VolumeProjection: NSViewRepresentable {
|
||||
let renderer: VolumeRenderer
|
||||
let rotation: SIMD2<Float>
|
||||
let zoom: Float
|
||||
let window: SIMD2<Float>
|
||||
let surface: Bool
|
||||
|
||||
func makeNSView(context: Context) -> MTKView {
|
||||
let view = MTKView(frame: .zero, device: renderer.device)
|
||||
view.framebufferOnly = false
|
||||
view.colorPixelFormat = .bgra8Unorm
|
||||
view.isPaused = true
|
||||
view.enableSetNeedsDisplay = true
|
||||
view.delegate = renderer
|
||||
return view
|
||||
}
|
||||
|
||||
func updateNSView(_ view: MTKView, context: Context) {
|
||||
renderer.rotation = rotation
|
||||
renderer.zoom = zoom
|
||||
renderer.window = window
|
||||
renderer.surface = surface
|
||||
view.needsDisplay = true
|
||||
}
|
||||
}
|
||||
|
||||
final class VolumeRenderer: NSObject, MTKViewDelegate {
|
||||
let device: MTLDevice
|
||||
private let queue: MTLCommandQueue
|
||||
private let pipeline: MTLComputePipelineState
|
||||
private let texture: MTLTexture
|
||||
private let proportions: SIMD4<Float>
|
||||
private let range: SIMD2<Float>
|
||||
var rotation = SIMD2<Float>(0, 0)
|
||||
var zoom: Float = 1
|
||||
var window = SIMD2<Float>(0, 1)
|
||||
var surface = true
|
||||
|
||||
init?(volume: DICOMVolume) {
|
||||
guard let device = MTLCreateSystemDefaultDevice(),
|
||||
let queue = device.makeCommandQueue(),
|
||||
let library = try? device.makeLibrary(source: Self.shader, options: nil),
|
||||
let function = library.makeFunction(name: "project"),
|
||||
let pipeline = try? device.makeComputePipelineState(function: function),
|
||||
let spacing = volume.spacing else { return nil }
|
||||
|
||||
let original = volume.size
|
||||
let longest = max(original.x, original.y, original.z)
|
||||
let reduction = max(1, Double(longest) / 256)
|
||||
let size = SIMD3(max(1, Int(Double(original.x) / reduction)),
|
||||
max(1, Int(Double(original.y) / reduction)),
|
||||
max(1, Int(Double(original.z) / reduction)))
|
||||
let descriptor = MTLTextureDescriptor()
|
||||
descriptor.textureType = .type3D
|
||||
descriptor.pixelFormat = .r16Unorm
|
||||
descriptor.width = size.x
|
||||
descriptor.height = size.y
|
||||
descriptor.depth = size.z
|
||||
descriptor.usage = .shaderRead
|
||||
guard let texture = device.makeTexture(descriptor: descriptor) else { return nil }
|
||||
|
||||
let span = max(1, volume.maximum - volume.minimum)
|
||||
var samples = [UInt16](repeating: 0, count: size.x * size.y * size.z)
|
||||
for z in 0..<size.z {
|
||||
for y in 0..<size.y {
|
||||
let row = (z * original.z / size.z * original.y + y * original.y / size.y) * original.x
|
||||
let target = (z * size.y + y) * size.x
|
||||
for x in 0..<size.x {
|
||||
let value = volume.pixels[row + x * original.x / size.x]
|
||||
samples[target + x] = UInt16(((value - volume.minimum) / span * 65535).rounded())
|
||||
}
|
||||
}
|
||||
}
|
||||
samples.withUnsafeBytes { bytes in
|
||||
texture.replace(region: MTLRegionMake3D(0, 0, 0, size.x, size.y, size.z),
|
||||
mipmapLevel: 0, slice: 0, withBytes: bytes.baseAddress!,
|
||||
bytesPerRow: size.x * 2, bytesPerImage: size.x * size.y * 2)
|
||||
}
|
||||
|
||||
let dimensions = SIMD3(Double(original.x), Double(original.y), Double(original.z)) * spacing
|
||||
let scale = max(dimensions.x, dimensions.y, dimensions.z)
|
||||
let normalized = SIMD3<Float>(dimensions / scale)
|
||||
proportions = SIMD4(normalized.x, normalized.y, normalized.z, volume.inverted ? 1 : 0)
|
||||
range = SIMD2(volume.minimum, span)
|
||||
self.device = device
|
||||
self.queue = queue
|
||||
self.pipeline = pipeline
|
||||
self.texture = texture
|
||||
}
|
||||
|
||||
func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {}
|
||||
|
||||
func draw(in view: MTKView) {
|
||||
guard let drawable = view.currentDrawable, let commands = queue.makeCommandBuffer(),
|
||||
encodeProjection(to: drawable.texture, using: commands) else { return }
|
||||
commands.present(drawable)
|
||||
commands.commit()
|
||||
}
|
||||
|
||||
func encodeProjection(to output: MTLTexture, using commands: MTLCommandBuffer) -> Bool {
|
||||
guard let encoder = commands.makeComputeCommandEncoder() else { return false }
|
||||
var box = proportions
|
||||
var camera = SIMD4(rotation.x, rotation.y, zoom, surface ? 1 : 0)
|
||||
var levels = SIMD4((window.x - window.y / 2 - range.x) / range.y, window.y / range.y, 0, 0)
|
||||
encoder.setComputePipelineState(pipeline)
|
||||
encoder.setTexture(texture, index: 0)
|
||||
encoder.setTexture(output, index: 1)
|
||||
encoder.setBytes(&box, length: 16, index: 0)
|
||||
encoder.setBytes(&camera, length: 16, index: 1)
|
||||
encoder.setBytes(&levels, length: 16, index: 2)
|
||||
let group = MTLSize(width: 8, height: 8, depth: 1)
|
||||
let width = output.width
|
||||
let height = output.height
|
||||
encoder.dispatchThreadgroups(MTLSize(width: (width + 7) / 8, height: (height + 7) / 8, depth: 1),
|
||||
threadsPerThreadgroup: group)
|
||||
encoder.endEncoding()
|
||||
return true
|
||||
}
|
||||
|
||||
private static let shader = """
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
|
||||
kernel void project(texture3d<float, access::sample> volume [[texture(0)]],
|
||||
texture2d<float, access::write> output [[texture(1)]],
|
||||
constant float4 &box [[buffer(0)]], constant float4 &camera [[buffer(1)]],
|
||||
constant float4 &levels [[buffer(2)]], uint2 pixel [[thread_position_in_grid]]) {
|
||||
if (pixel.x >= output.get_width() || pixel.y >= output.get_height()) return;
|
||||
float2 size = float2(output.get_width(), output.get_height());
|
||||
float2 xy = (float2(pixel) + 0.5 - size * 0.5) * (1.8 / min(size.x, size.y)) / camera.z;
|
||||
float sy = sin(camera.x), cy = cos(camera.x);
|
||||
float sx = sin(camera.y), cx = cos(camera.y);
|
||||
float3 origin = float3(cy * xy.x + sy * sx * xy.y, cx * xy.y, -sy * xy.x + cy * sx * xy.y);
|
||||
float3 ray = float3(sy * cx, -sx, cy * cx);
|
||||
float3 safeRay = select(ray, copysign(float3(0.00001), ray), abs(ray) < 0.00001);
|
||||
float3 hitA = (-box.xyz * 0.5 - origin) / safeRay;
|
||||
float3 hitB = ( box.xyz * 0.5 - origin) / safeRay;
|
||||
float3 nearHit = min(hitA, hitB), farHit = max(hitA, hitB);
|
||||
float enter = max(nearHit.x, max(nearHit.y, nearHit.z));
|
||||
float leave = min(farHit.x, min(farHit.y, farHit.z));
|
||||
float intensity = 0;
|
||||
if (leave > enter) {
|
||||
constexpr sampler sampleVolume(coord::normalized, address::clamp_to_edge, filter::linear);
|
||||
const int steps = 320;
|
||||
float extreme = box.w > 0 ? 1 : 0;
|
||||
for (int i = 0; i < steps; ++i) {
|
||||
float t = mix(enter, leave, (float(i) + 0.5) / float(steps));
|
||||
float3 samplePosition = (origin + t * ray) / box.xyz + 0.5;
|
||||
float value = volume.sample(sampleVolume, samplePosition).r;
|
||||
if (camera.w > 0) {
|
||||
float threshold = levels.x + levels.y * 0.5;
|
||||
if (box.w > 0 ? value > threshold : value < threshold) continue;
|
||||
float3 pitch = 1.0 / float3(volume.get_width(), volume.get_height(), volume.get_depth());
|
||||
float3 dx = float3(pitch.x, 0, 0), dy = float3(0, pitch.y, 0), dz = float3(0, 0, pitch.z);
|
||||
float3 gradient = float3(
|
||||
volume.sample(sampleVolume, samplePosition + dx).r - volume.sample(sampleVolume, samplePosition - dx).r,
|
||||
volume.sample(sampleVolume, samplePosition + dy).r - volume.sample(sampleVolume, samplePosition - dy).r,
|
||||
volume.sample(sampleVolume, samplePosition + dz).r - volume.sample(sampleVolume, samplePosition - dz).r
|
||||
) / (box.xyz * pitch);
|
||||
float magnitude = length(gradient);
|
||||
float light = magnitude > 0.00001 ? abs(dot(gradient / magnitude, ray)) : 0.65;
|
||||
intensity = 0.23 + 0.77 * light;
|
||||
break;
|
||||
}
|
||||
extreme = box.w > 0 ? min(extreme, value) : max(extreme, value);
|
||||
}
|
||||
if (camera.w == 0) {
|
||||
intensity = clamp((extreme - levels.x) / max(levels.y, 0.000001), 0.0, 1.0);
|
||||
if (box.w > 0) intensity = 1 - intensity;
|
||||
}
|
||||
}
|
||||
output.write(float4(float3(intensity), 1), pixel);
|
||||
}
|
||||
"""
|
||||
}
|
||||
Reference in new issue
Block a user