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
//use super::Material;
use super::Opcode;
//use super::SignedDistance;
use crate::sdf;
use crate::structs::Material;
use crate::structs::SignedDistance;
use macaw::Quat;
use macaw::Vec3;
use macaw::Vec4;

#[derive(Copy, Clone)]
pub struct Interpreter<SD: SignedDistance, const STACK_DEPTH: usize = 64> {
    marker: core::marker::PhantomData<SD>,
}

impl<SD: SignedDistance> Default for Interpreter<SD> {
    fn default() -> Self {
        Self {
            marker: Default::default(),
        }
    }
}

pub struct InterpreterContext<'a, SD: SignedDistance, const STACK_DEPTH: usize = 64> {
    opcodes: &'a [Opcode],
    constants: &'a [f32],

    stack: [SD; STACK_DEPTH],
    stack_ptr: usize,
    constant_idx: usize,
    position_stack: [Vec3; STACK_DEPTH],
    position_stack_ptr: usize,
}

fn uninit<T>(_t: T) -> T {
    #[cfg(not(target_arch = "spirv"))]
    // SAFETY: We're using this for a stack where we don't care about initialized state.
    let ret = unsafe { core::mem::MaybeUninit::<T>::zeroed().assume_init() };

    #[cfg(target_arch = "spirv")]
    let ret = _t; // https://github.com/EmbarkStudios/rust-gpu/issues/981

    ret
}

impl<'a, SD: SignedDistance + Copy + Clone, const STACK_DEPTH: usize>
    InterpreterContext<'a, SD, STACK_DEPTH>
{
    fn new(opcodes: &'a [Opcode], constants: &'a [f32]) -> Self {
        Self {
            opcodes,
            constants,
            stack: uninit([SignedDistance::infinity(); STACK_DEPTH]),
            stack_ptr: 0,
            constant_idx: 0,
            position_stack: uninit([Vec3::ZERO; STACK_DEPTH]),
            position_stack_ptr: 0,
        }
    }

    fn reset(&mut self) {
        self.stack_ptr = 0;
        self.position_stack_ptr = 0;
        self.constant_idx = 0;
    }

    fn float32(&mut self) -> f32 {
        let ret = self.constants[self.constant_idx];
        self.constant_idx += 1;
        ret
    }

    fn vec3(&mut self) -> Vec3 {
        Vec3::new(self.float32(), self.float32(), self.float32())
    }

    // TODO (nummelin): How much faster is it to only allow 16-bytes alignment
    // when running through spirv?
    fn vec4(&mut self) -> Vec4 {
        Vec4::new(
            self.float32(),
            self.float32(),
            self.float32(),
            self.float32(),
        )
    }

    fn quat(&mut self) -> Quat {
        Quat::from_xyzw(
            self.float32(),
            self.float32(),
            self.float32(),
            self.float32(),
        )
    }

    fn material(&mut self) -> Material {
        self.vec3().into()
    }

    fn push_sd(&mut self, v: SD) {
        self.stack[self.stack_ptr] = v;
        self.stack_ptr += 1;
    }

    fn pop_sd(&mut self) -> Option<SD> {
        self.stack_ptr -= 1;
        self.stack.get(self.stack_ptr).copied()
    }

    fn pop_sd_unchecked(&mut self) -> SD {
        self.stack_ptr -= 1;
        self.stack[self.stack_ptr]
    }

    fn push_position(&mut self, pos: Vec3) {
        self.position_stack[self.position_stack_ptr] = pos;
        self.position_stack_ptr += 1;
    }

    fn pop_position_unchecked(&mut self) -> Vec3 {
        self.position_stack_ptr -= 1;
        self.position_stack[self.position_stack_ptr]
    }

    // See comment at the end of the `interpret` function below.
    #[allow(dead_code)]
    fn top_is_finite(&self) -> bool {
        if self.stack_ptr > 0 {
            if let Some(value) = self.stack.get(self.stack_ptr - 1) {
                value.is_distance_finite()
            } else {
                // Wacky
                false
            }
        } else {
            false
        }
    }
}

impl<SD: SignedDistance + Copy + Clone, const STACK_DEPTH: usize> Interpreter<SD, STACK_DEPTH> {
    pub fn new_context<'a>(
        opcodes: &'a [Opcode],
        constants: &'a [f32],
    ) -> InterpreterContext<'a, SD, STACK_DEPTH> {
        InterpreterContext::<SD, STACK_DEPTH>::new(opcodes, constants)
    }
    pub fn interpret(
        ctx: &mut InterpreterContext<'_, SD, STACK_DEPTH>,
        position: Vec3,
    ) -> Option<SD> {
        Self::interpret_internal(ctx, position);
        ctx.pop_sd()
    }

    pub fn interpret_unchecked(
        ctx: &mut InterpreterContext<'_, SD, STACK_DEPTH>,
        position: Vec3,
    ) -> SD {
        Self::interpret_internal(ctx, position);
        ctx.pop_sd_unchecked()
    }

    fn interpret_internal(ctx: &mut InterpreterContext<'_, SD, STACK_DEPTH>, position: Vec3) {
        #[allow(clippy::enum_glob_use)]
        use Opcode::*;

        let mut current_position = position;

        ctx.reset();

        let mut pc = 0;

        loop {
            let opcode = ctx.opcodes[pc];
            pc += 1;

            match opcode {
                Plane => {
                    let sd = sdf::sd_plane(current_position, ctx.vec4());
                    ctx.push_sd(sd);
                }
                Sphere => {
                    let sd = sdf::sd_sphere(current_position, ctx.vec3(), ctx.float32());
                    ctx.push_sd(sd);
                }
                Capsule => {
                    let sd =
                        sdf::sd_capsule(current_position, &[ctx.vec3(), ctx.vec3()], ctx.float32());
                    ctx.push_sd(sd);
                }
                RoundedCylinder => {
                    let sd = sdf::sd_rounded_cylinder(
                        current_position,
                        ctx.float32(),
                        ctx.float32(),
                        ctx.float32(),
                    );
                    ctx.push_sd(sd);
                }
                TaperedCapsule => {
                    let p0 = ctx.vec3();
                    let r0 = ctx.float32();
                    let p1 = ctx.vec3();
                    let r1 = ctx.float32();
                    let sd = sdf::sd_tapered_capsule(current_position, &[p0, p1], [r0, r1]);
                    ctx.push_sd(sd);
                }
                Cone => {
                    let r = ctx.float32();
                    let h = ctx.float32();
                    let sd = sdf::sd_cone(current_position, r, h);
                    ctx.push_sd(sd);
                }
                RoundedBox => {
                    let half_size = ctx.vec3();
                    let radius = ctx.float32();
                    let sd = sdf::sd_rounded_box(current_position, half_size, radius);
                    ctx.push_sd(sd);
                }
                Torus => {
                    let big_r = ctx.float32();
                    let small_r = ctx.float32();
                    ctx.push_sd(sdf::sd_torus(current_position, big_r, small_r));
                }
                TorusSector => {
                    let big_r = ctx.float32();
                    let small_r = ctx.float32();
                    let sin_cos_half_angle = (ctx.float32(), ctx.float32());
                    ctx.push_sd(sdf::sd_torus_sector(
                        current_position,
                        big_r,
                        small_r,
                        sin_cos_half_angle,
                    ));
                }
                BiconvexLens => {
                    let lower_sagitta = ctx.float32();
                    let upper_sagitta = ctx.float32();
                    let chord = ctx.float32();
                    let sd = sdf::sd_biconvex_lens(
                        current_position,
                        lower_sagitta,
                        upper_sagitta,
                        chord,
                    );
                    ctx.push_sd(sd);
                }
                Material => {
                    let sd = ctx.pop_sd_unchecked();
                    let material = ctx.material();
                    ctx.push_sd(sdf::sd_material(sd, material));
                }
                Union => {
                    let sd1 = ctx.pop_sd_unchecked();
                    let sd2 = ctx.pop_sd_unchecked();
                    ctx.push_sd(sdf::sd_op_union(sd1, sd2));
                }
                UnionSmooth => {
                    let sd1 = ctx.pop_sd_unchecked();
                    let sd2 = ctx.pop_sd_unchecked();
                    let width = ctx.float32();
                    ctx.push_sd(sdf::sd_op_union_smooth(sd1, sd2, width));
                }
                Subtract => {
                    let sd1 = ctx.pop_sd_unchecked();
                    let sd2 = ctx.pop_sd_unchecked();
                    ctx.push_sd(sdf::sd_op_subtract(sd1, sd2));
                }
                SubtractSmooth => {
                    let sd1 = ctx.pop_sd_unchecked();
                    let sd2 = ctx.pop_sd_unchecked();
                    let width = ctx.float32();
                    ctx.push_sd(sdf::sd_op_subtract_smooth(sd1, sd2, width));
                }
                Intersect => {
                    let sd1 = ctx.pop_sd_unchecked();
                    let sd2 = ctx.pop_sd_unchecked();
                    ctx.push_sd(sdf::sd_op_intersect(sd1, sd2));
                }
                IntersectSmooth => {
                    let sd1 = ctx.pop_sd_unchecked();
                    let sd2 = ctx.pop_sd_unchecked();
                    let width = ctx.float32();
                    ctx.push_sd(sdf::sd_op_intersect_smooth(sd1, sd2, width));
                }
                PushTranslation => {
                    let translation = ctx.vec3();
                    ctx.push_position(current_position);
                    current_position += translation;
                }
                PopTransform => {
                    current_position = ctx.pop_position_unchecked();
                }
                PushRotation => {
                    let rotation = ctx.quat();
                    ctx.push_position(current_position);
                    current_position = rotation * current_position;
                }
                PushScale => {
                    let inv_scale = ctx.float32();
                    ctx.push_position(current_position);
                    current_position *= inv_scale;
                }
                PopScale => {
                    current_position = ctx.pop_position_unchecked();
                    let scale = ctx.float32();
                    let sd = ctx.pop_sd_unchecked();
                    ctx.push_sd(sd.copy_with_distance(scale * sd.distance()));
                }
                End => {
                    break;
                }
            }

            // NaN check for debugging! Don't want the overhead by default, so disabled.
            // if !ctx.top_is_finite() {
            //    panic!("Hit infinity at {:?}", opcode);
            // }
        }
    }
}