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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use std::convert::TryInto;
use std::ops::RangeInclusive;
use serde::{Deserialize, Serialize};
use smallvec::{smallvec, SmallVec};
use crate::space::{Matrix, Point, Vector};
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum Unit {
Cube,
Sphere,
Cylinder,
}
impl Unit {
pub fn sprite_names(&self) -> &'static [&'static str] {
match self {
Self::Cube => &["xp", "xn", "yp", "yn", "zp", "zn"],
Self::Sphere => &["sphere"],
Self::Cylinder => &["top", "bottom", "curved"],
}
}
pub fn sprite_coords(&self, order: u32) -> (u32, u32) {
let max: u32 = (self.sprite_names().len() - 1).try_into().expect("max is a small number");
debug_assert!(order <= max);
sprite_location(order, spritesheet_side(max))
}
pub fn search_sprite_coord_by_name(&self, name: &str) -> Option<(u32, u32)> {
let order = self.sprite_names().iter().position(|&item| item == name)?;
Some(self.sprite_coords(order.try_into().expect("sprite_names is short")))
}
pub fn spritesheet_side(&self) -> u32 {
spritesheet_side(
(self.sprite_names().len() - 1).try_into().expect("sprite count is a small number"),
)
}
pub fn contains(&self, pos: Point) -> bool {
match self {
Self::Cube => {
(-1. ..=1.).contains(&pos.x)
&& (-1. ..=1.).contains(&pos.y)
&& (-1. ..=1.).contains(&pos.z)
}
Self::Sphere => pos.x.powi(2) + pos.y.powi(2) + pos.z.powi(2) <= 1.,
Self::Cylinder => pos.x.powi(2) + pos.y.powi(2) <= 1. && (0. ..=1.).contains(&pos.z),
}
}
pub fn between(&self, start: Point, end: Point) -> Option<f64> {
match self {
Self::Cube => {
let dir = end - start;
let mut min_w = None;
for dim in 0..3 {
#[allow(clippy::indexing_slicing)]
for &target in &[-1., 1.] {
let w = (target - start[dim]) / dir[dim];
if (0. ..=1.).contains(&w) {
let point = start + dir * w;
let inside = (0..3)
.filter(|&other| other != dim)
.all(|other| (-1. ..=1.).contains(&point[other]));
if inside {
min_w = Some(match min_w {
Some(prev) if prev < w => prev,
_ => w,
});
}
}
}
}
min_w
}
Self::Sphere => {
if self.contains(start) {
return Some(0.);
}
if self.contains(end) {
return Some(1.);
}
let dir = end - start;
let w = (Point::origin() - start).dot(&dir) / dir.norm_squared();
let closest = start + dir * w;
self.contains(closest).then(|| w)
}
Self::Cylinder => {
let delta = end - start;
let dxy2 = delta.x.powi(2) + delta.y.powi(2);
let discrim = (start.x * delta.x + start.y * delta.y).powi(2)
- (start.x.powi(2) + start.y.powi(2) - 1.) * dxy2;
if discrim > 0. {
let dr = discrim.sqrt();
let base = start.x * delta.x + start.y * delta.y;
let w1 = (-base - dr) / dxy2;
let w2 = (-base + dr) / dxy2;
let zw0 = -start.z / delta.z;
let zw1 = (1. - start.z) / delta.z;
fn intersect_ranges(
a: RangeInclusive<f64>,
b: RangeInclusive<f64>,
) -> Option<RangeInclusive<f64>> {
if a.end() < b.start() || b.end() < a.start() {
return None;
}
(a.end() >= b.start() && b.end() >= a.start()).then(|| {
f64::max(*a.start(), *b.start())..=f64::min(*a.end(), *b.end())
})
}
let range = intersect_ranges(
intersect_ranges(0. ..=1., w1..=w2)?,
f64::min(zw0, zw1)..=f64::max(zw0, zw1),
)?;
Some(*range.start())
} else {
None
}
}
}
}
#[allow(clippy::indexing_slicing)]
pub fn bb_under(&self, transform: Matrix) -> (Point, Point) {
use nalgebra::dimension as dim;
match self {
Self::Cube => {
type Storage = nalgebra::storage::Owned<f64, dim::U4, dim::U8>;
type Points = nalgebra::Matrix<f64, dim::U4, dim::U8, Storage>;
fn p01() -> impl Iterator<Item = f64> { [0., 1.].iter().copied() }
fn xyz(x: f64, y: f64, z: f64) -> impl Iterator<Item = f64> {
let vec: SmallVec<[f64; 4]> = smallvec![x, y, z, 1.];
vec.into_iter()
}
let iter = p01()
.flat_map(|x| p01().flat_map(move |y| p01().flat_map(move |z| xyz(x, y, z))));
let mut points = Points::from_iterator(iter);
points = transform * points;
let min: SmallVec<[f64; 3]> = (0_usize..3).map(|i| points.row(i).min()).collect();
let max: SmallVec<[f64; 3]> = (0_usize..3).map(|i| points.row(i).max()).collect();
#[allow(clippy::indexing_slicing)]
(Point::new(min[0], min[1], min[2]), Point::new(max[0], max[1], max[2]))
}
Self::Sphere => {
let extrema: SmallVec<[(f64, f64); 3]> = (0_usize..3)
.map(|i| {
let row = transform.row(i);
let norm = row.fixed_slice::<1, 3>(0, 0).norm();
let points: SmallVec<[f64; 2]> = [-1_f64, 1.]
.iter()
.map(|&sgn| {
let unit = Vector::from_iterator(
(0_usize..3).map(|j| sgn * row[j] / norm),
)
.fixed_resize::<4, 1>(1.);
(row * unit)[0]
})
.collect();
(points[0], points[1])
})
.collect();
let min =
Point::from(Vector::from_iterator(extrema.iter().map(|&(i, j)| i.min(j))));
let max =
Point::from(Vector::from_iterator(extrema.iter().map(|&(i, j)| i.max(j))));
(min, max)
}
Self::Cylinder => {
let extrema: SmallVec<[SmallVec<[f64; 4]>; 3]> = (0_usize..3)
.map(|i| {
let row = transform.row(i);
let norm = row.fixed_slice::<1, 2>(0, 0).norm();
if norm.abs() < 1e-10 {
return smallvec![row[3], row[2] + row[3], row[3], row[2] + row[3]];
}
let points: SmallVec<[f64; 4]> = [-1_f64, 1.]
.iter()
.flat_map(|&sgn| [(sgn, 0_f64), (sgn, 1_f64)])
.map(|(sgn, z)| {
let unit = nalgebra::Vector4::new(
sgn * row[0] / norm,
sgn * row[1] / norm,
z,
1.,
);
(row * unit)[0]
})
.collect();
points
})
.collect();
let min = Point::from(Vector::from_iterator(
extrema.iter().map(|array| array.iter().copied().fold(array[0], f64::min)),
));
let max = Point::from(Vector::from_iterator(
extrema.iter().map(|array| array.iter().copied().fold(array[0], f64::max)),
));
(min, max)
}
}
}
}
fn sprite_location(order: u32, side: u32) -> (u32, u32) {
if order == 0 {
return (0, 0);
}
let subarea = side * side / 4;
let (x, y) = sprite_location(order % subarea, side / 2);
match order / subarea {
0 => (x, y),
1 => (x, y + side / 2),
2 => (x + side / 2, y),
3 => (x + side / 2, y + side / 2),
_ => unreachable!("order > side * side"),
}
}
fn spritesheet_side(max_order: u32) -> u32 {
let power_of_four = u32::BITS - max_order.leading_zeros();
let power_of_two = (power_of_four + 1) / 2;
1 << power_of_two
}
#[cfg(test)]
mod tests {
use std::f64::consts::{PI, SQRT_2};
use std::ops::Range;
use super::Unit;
use crate::space::{Matrix, Point, Vector};
fn assert_pt(pt: Point, [x, y, z]: [f64; 3]) {
let a = &pt.coords;
let b = &Vector::new(x, y, z);
let delta = (a - b).norm();
if !pt.coords.map(f64::is_finite).fold(true, |a, b| a && b) {
panic!("Point is not finite: {}", pt);
}
if delta > 1e-10 {
panic!("{} != {}", a, b);
}
}
fn assert_bb(unit: Unit, trans: Matrix, range: Range<[f64; 3]>) {
let bb = unit.bb_under(trans);
assert_pt(bb.0, range.start);
assert_pt(bb.1, range.end);
}
#[test]
pub fn sphere_bb() {
assert_bb(Unit::Sphere, Matrix::identity(), [-1., -1., -1.]..[1., 1., 1.]);
assert_bb(
Unit::Sphere,
Matrix::new_translation(&Vector::new(0.5, 0.5, 0.5)),
[-0.5, -0.5, -0.5]..[1.5, 1.5, 1.5],
);
assert_bb(
Unit::Sphere,
Matrix::new_nonuniform_scaling(&Vector::new(0.5, 2., 5.)),
[-0.5, -2., -5.]..[0.5, 2., 5.],
);
assert_bb(
Unit::Sphere,
nalgebra::Rotation3::from_axis_angle(&Vector::x_axis(), PI / 2.)
.to_homogeneous()
.prepend_translation(&Vector::new(1., 1., 1.)),
[0., -2., 0.]..[2., 0., 2.],
);
}
#[test]
pub fn cylinder_bb() {
assert_bb(Unit::Cylinder, Matrix::identity(), [-1., -1., 0.]..[1., 1., 1.]);
assert_bb(
Unit::Cylinder,
Matrix::new_translation(&Vector::new(0.5, 0.5, -0.5))
.append_nonuniform_scaling(&Vector::new(2., 3., 4.)),
[-1., -1.5, -2.]..[3., 4.5, 2.],
);
assert_bb(
Unit::Cylinder,
nalgebra::Rotation3::from_axis_angle(&Vector::x_axis(), PI / 4.)
.matrix()
.to_homogeneous()
.prepend_translation(&Vector::new(0., 0., -0.5)),
[-1., -0.75 * SQRT_2, -0.75 * SQRT_2]..[1., 0.75 * SQRT_2, 0.75 * SQRT_2],
);
}
#[test]
pub fn cylinder_between() {
macro_rules! assert_between {
(($x0:expr, $y0:expr, $z0:expr)..($x1:expr, $y1:expr, $z1:expr) => None) => {
let v0 = Point::new($x0, $y0, $z0);
let v1 = Point::new($x1, $y1, $z1);
let option = Unit::Cylinder.between(v0, v1);
if let Some(w) = option {
panic!("{}..{} should not intersect cylinder, got Some({})", v0, v1, w);
}
};
(($x0:expr, $y0:expr, $z0:expr)..($x1:expr, $y1:expr, $z1:expr) => Some($w:expr, $eps:expr)) => {
let v0 = Point::new($x0, $y0, $z0);
let v1 = Point::new($x1, $y1, $z1);
let option = Unit::Cylinder.between(v0, v1);
if let Some(w) = option {
if ($w - w).abs() > $eps {
panic!(
"{}..{} should intersect cylinder at {} (\u{00b1} {}, got Some({})",
v0, v1, $w, $eps, w
);
}
} else {
panic!("{}..{} should intersect cylinder, got None", v0, v1);
}
};
}
assert_between!((-1., -1., 0.5)..(1., 1., 0.5) => Some((2f64.sqrt() - 1.) / (2f64.sqrt() * 2.), 1e-6));
assert_between!((-1., -1., -0.5)..(1., 1., -0.5) => None);
assert_between!((1., -1., 0.5)..(-1., 1., 0.5) => Some((2f64.sqrt() - 1.) / (2f64.sqrt() * 2.), 1e-6));
assert_between!((-1., 1., 0.5)..(1., -1., 0.5) => Some((2f64.sqrt() - 1.) / (2f64.sqrt() * 2.), 1e-6));
assert_between!((-2., 0., 0.5)..(0., 0., 0.5) => Some(0.5, 1e-10));
assert_between!((0., 0., 0.5)..(2., 0., 0.5) => Some(0., 1e-10));
assert_between!((0., 0., 1.5)..(1., 0., 0.5) => Some(0.5, 1e-10));
assert_between!((1., 0., 1.5)..(0., 0., 0.5) => Some(0.5, 1e-10));
assert_between!((0., 0., 0.5)..(1., 0., 1.5) => Some(0., 1e-10));
assert_between!((1., 0., 0.5)..(0., 0., 1.5) => Some(0., 1e-10));
assert_between!((0., 0., 11.)..(37., -12., -753.) => Some((1. - 11.) / (-753. - 11.), 1e-10));
}
}