-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRay Marching Mixing
379 lines (277 loc) · 10.3 KB
/
Ray Marching Mixing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
// Just copy and paste the code into a blank playground template
// in Swift Playgrounds app on an iPad or a Mac
// !!! Turn off Enable Results in the settings, otherwise you'll get an error !!!
// Created by Roman Gaditskiy: https://GitHub.com/gadirom/Art-in-Swift
import MetalKit
import SwiftUI
import PlaygroundSupport
import Combine
import simd
//Sphere colors
let colors:[float3] = [float3(x: 1, y: 0, z: 0),
float3(x: 0, y: 1, z: 0),
float3(x: 0, y: 0, z: 1),
float3(x: 1, y: 1, z: 0),
float3(x: 1, y: 0, z: 1),
float3(x: 0.4, y: 0.3, z: 0.8),
float3(x: 0.9, y: 0.3, z: 0.7),
float3(x: 0.5, y: 0.3, z: 0.1),
float3(x: 0.2, y: 0.5, z: 0.2),
float3(x: 0.6, y: 1.0, z: 0.3)
]
var light: Float = 0
var dist: Float = 0
var sphereBuffer: MTLBuffer?
var spheres: UnsafeMutablePointer<Sphere>?
struct Sphere {
var s: float3
var c: float3
var size: Float
}
struct Uniforms {
//Light Position
var lx: Float = 0
var ly: Float = 0
var lz: Float = 0
//Time
var t: Float = 0
//Blending
var k: Float = 0
//Distance
var d: Float = 0
//Spheres
var sphereCount: Int32 = 10
var size: Float = 0
}
let metalFunctions = """
#include <metal_stdlib>
using namespace metal;
typedef struct
{
float3 s;
float3 c;
float size;
} Sphere;
typedef struct
{
float lx;
float ly;
float lz;
float t;
float k;
float d;
int sc;
float ss;
} Uniforms;
#define MAX_STEPS 100
#define MAX_DIST 7.
#define SURF_DIST 0.1
//distance for softmin:
#define K_Dist 0.5
float4x4 rotationMatrix(float3 axis, float angle) {
axis = normalize(axis);
float s = sin(angle);
float c = cos(angle);
float oc = 1.0 - c;
return float4x4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0,
oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0,
oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0,
0.0, 0.0, 0.0, 1.0);
}
float3 rotate(float3 v, float3 axis, float angle) {
float4x4 m = rotationMatrix(axis, angle);
return (m * float4(v, 1.0)).xyz;
}
float4 smin(float a, float b, float3 ca, float3 cb, float k) {
float h = clamp(0.5 + 0.5*(a-b)/k, 0.0, 1.0);
float d = mix(a, b, h) - k*h*(1.0-h);
float3 c = mix(ca, cb, h) - k*h*(1.0-h);
return float4(c, d);
}
float sdSphere( float3 p, float3 c, float r ) {
return length(p - c) - r;
}
float4 getDist( float3 p, constant Uniforms *u, constant Sphere *sp ) {
float3 c = float3(sp[0].s);
float4 d = float4(sp[0].c, sdSphere(p, c, sp[0].size));
for (int i = 1; i < u->sc; i++) {
c = float3(sp[i].s);
float sphere = sdSphere(p, c, sp[i].size);
d = smin(sphere, d.w, sp[i].c, d.xyz, u->k);
}
return d;
}
float4 castRay( float3 ro, float3 rd, constant Uniforms *u, constant Sphere *sp) {
float d0 = 0.0;
float3 c;
for (int i = 0; i < MAX_STEPS; i++) {
float3 p = ro + d0 * rd;
float4 dS = getDist(p, u, sp);
d0 += dS.w;
c = dS.xyz;
if ( dS.w <= SURF_DIST || d0 >= MAX_DIST ) break;
}
return float4(c, d0);
}
float3 getNormal ( float3 p, constant Uniforms *u, constant Sphere *sp) {
float d = getDist(p, u, sp).w;
float2 e = float2(0.01, 0.);
float3 n = d - float3( getDist(p - e.xyy, u, sp).w,
getDist(p - e.yxy, u, sp).w,
getDist(p - e.yyx, u, sp).w );
return normalize(n);
}
float3 getLight( float3 p, constant Uniforms *u, constant Sphere *sp, float3 bg, float3 rd, float3 c) {
float3 lightPos = float3(u->lx, u->ly, u->lz);
float3 l = normalize( lightPos - p );
float3 n = getNormal(p, u, sp);
float diffl = dot(l, n);
float3 diff = diffl * c + float3(pow(diffl,100.)/2);
float frensel = pow(1. + dot(rd, n), 3);
diff = mix(diff, bg, frensel);
return diff;
}
kernel void ray_march(texture2d<float, access::write> output [[texture(0)]],
constant Sphere* sp [[buffer(0)]],
constant Uniforms* u [[buffer(1)]],
uint2 gid [[thread_position_in_grid]]){
int width = output.get_width();
int height = output.get_height();
float2 uv = (float2(width, height) * 0.5 - float2(gid) ) / height;
float3 ro = float3(0.0, 0.0, 0.0);
float3 rd = normalize (float3(uv, 1.0));
float cdist = 1 - (length(uv));
float3 bg = mix(0, 1, cdist);
float3 light = bg;
float4 d = castRay(ro, rd, u, sp);
if (d.w < MAX_DIST) {
float3 p = ro + d.w * rd;
light = getLight(p, u, sp, bg, rd, d.xyz);
}
float3 col = light;
output.write(float4(col, 1.0), gid);
}
"""
func animationFunc(_ uniforms: inout Uniforms){
light += 0.02354
if light > .pi*2 {light = 0}
//if isOn{
dist += 0.0141
if dist > .pi*2 {dist = 0}
//let d = 3 * newAnim / 1000
_ = (0..<10).indices.map{ i in
let ang = 2 * .pi / Float(uniforms.sphereCount) * Float(i) + dist
spheres![i] = Sphere(
s:float3(sin(ang)*uniforms.d,
cos(ang)*uniforms.d,
6),
c:colors[i],
size: uniforms.size * (1 + sin(ang*2 + dist)))
uniforms.lx = cos(light) * 3
uniforms.ly = sin(light) * 3
uniforms.lz = 0
uniforms.t = dist
}
}
struct MetalView: UIViewRepresentable {
init(_ uniforms: Binding<Uniforms>){
_uniforms = uniforms
}
@Binding var uniforms: Uniforms
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: UIViewRepresentableContext<MetalView>) -> MTKView {
let mtkView = MTKView()
mtkView.delegate = context.coordinator
mtkView.preferredFramesPerSecond = 60
mtkView.enableSetNeedsDisplay = true
if let metalDevice = MTLCreateSystemDefaultDevice() {
mtkView.device = metalDevice
}
mtkView.framebufferOnly = false
//mtkView.clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 0)
mtkView.drawableSize = mtkView.frame.size
mtkView.enableSetNeedsDisplay = false
mtkView.isPaused = false
return mtkView
}
func updateUIView(_ uiView: MTKView, context: UIViewRepresentableContext<MetalView>) {
}
class Coordinator: NSObject, MTKViewDelegate {
var parent: MetalView
var device: MTLDevice!
var rayMarchPass: MTLComputePipelineState!
var commandQueue: MTLCommandQueue!
init(_ parent: MetalView) {
self.parent = parent
if let metalDevice = MTLCreateSystemDefaultDevice() {
self.device = metalDevice
}
self.commandQueue = device.makeCommandQueue()!
var library: MTLLibrary!
do{ library = try self.device?.makeLibrary(source: metalFunctions, options: nil)
}catch{print(error)}
let rayMarchFunc = library?.makeFunction(name: "ray_march")
do{ rayMarchPass = try self.device?.makeComputePipelineState(function: rayMarchFunc!)
}catch{print(error)}
sphereBuffer = device?.makeBuffer(
length: MemoryLayout<Sphere>.stride * parent.uniforms.sphereCount,
options: [])
super.init()
}
func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
}
}
}
extension MetalView.Coordinator{
func draw(in view: MTKView) {
animationFunc(&parent.uniforms)
guard let drawable = view.currentDrawable else { return }
let commandbuffer = commandQueue.makeCommandBuffer()
//Render
let computeCommandEncoder = commandbuffer?.makeComputeCommandEncoder()
computeCommandEncoder?.setComputePipelineState(rayMarchPass)
computeCommandEncoder?.setTexture(drawable.texture, index: 0)
computeCommandEncoder?.setBuffer(sphereBuffer, offset: 0, index: 0)
computeCommandEncoder?.setBytes(&parent.uniforms, length: MemoryLayout<Uniforms>.stride, index: 1)
let w = rayMarchPass.threadExecutionWidth
let h = rayMarchPass.maxTotalThreadsPerThreadgroup / w
let threadsPerThreadGroup = MTLSize(width: w, height: h, depth: 1)
let threadgroupsPerGrid = MTLSize(width: drawable.texture.width / w, height: drawable.texture.height / h, depth: 1)
computeCommandEncoder?.dispatchThreadgroups(threadgroupsPerGrid, threadsPerThreadgroup: threadsPerThreadGroup)
computeCommandEncoder?.endEncoding()
commandbuffer?.present(drawable)
commandbuffer?.commit()
}
}
struct RMView: View {
init(_ uniforms: Binding<Uniforms>){
_uniforms = uniforms
}
@Binding var uniforms: Uniforms
var body: some View{
MetalView($uniforms)
.clipShape(RoundedRectangle(cornerRadius: 10))
.frame(width: 512, height: 512)
.shadow(radius: 5)
.onAppear(){
spheres = sphereBuffer!.contents().bindMemory(to: Sphere.self, capacity: MemoryLayout<Sphere>.stride * uniforms.sphereCount)
DispatchQueue.global().asyncAfter(deadline: .now() + 0.5){
}
light = 0
}
}
}
struct ContentView:View {
@State var uniforms = Uniforms()
var body: some View{
VStack{
RMView($uniforms)
Slider(value: $uniforms.d, in: 0...2)
Slider(value: $uniforms.k, in: 0...1)
Slider(value: $uniforms.size, in: 0...1)
}
}
}
PlaygroundPage.current.setLiveView(ContentView())