1use crate::RenderError;
19
20pub const MAX_MESH_CELLS: u32 = 300;
22
23#[derive(Clone, Debug)]
28pub struct MeshGeometry {
29 pub(crate) gx: u32,
30 pub(crate) gy: u32,
31 pub(crate) aspect_x: f32,
32 pub(crate) aspect_y: f32,
33 pub(crate) x: Vec<f32>,
34 pub(crate) y: Vec<f32>,
35 pub(crate) rad: Vec<f32>,
36 pub(crate) ang: Vec<f32>,
37 pm: Vec<([f32; 2], f32, f32)>,
39}
40
41pub fn aspect_xy(tex_w: u32, tex_h: u32) -> (f32, f32) {
43 let ax = if tex_h > tex_w {
44 tex_w as f32 / tex_h as f32
45 } else {
46 1.0
47 };
48 let ay = if tex_w > tex_h {
49 tex_h as f32 / tex_w as f32
50 } else {
51 1.0
52 };
53 (ax, ay)
54}
55
56impl MeshGeometry {
57 pub fn new(gx: u32, gy: u32, tex_w: u32, tex_h: u32) -> Result<Self, RenderError> {
62 if gx > MAX_MESH_CELLS || gy > MAX_MESH_CELLS {
63 return Err(RenderError::Invalid(format!(
64 "mesh dimensions must be at most {MAX_MESH_CELLS}, got {gx}x{gy}"
65 )));
66 }
67 if gx < 2 || gy < 2 || !gx.is_multiple_of(2) || !gy.is_multiple_of(2) {
68 return Err(RenderError::Invalid(format!(
69 "mesh dimensions must be even and >= 2, got {gx}x{gy}"
70 )));
71 }
72 let (ax, ay) = aspect_xy(tex_w, tex_h);
73 let n = ((gx + 1) * (gy + 1)) as usize;
74 let mut g = MeshGeometry {
75 gx,
76 gy,
77 aspect_x: ax,
78 aspect_y: ay,
79 x: Vec::with_capacity(n),
80 y: Vec::with_capacity(n),
81 rad: Vec::with_capacity(n),
82 ang: Vec::with_capacity(n),
83 pm: Vec::with_capacity(n),
84 };
85 for y in 0..=gy {
86 for x in 0..=gx {
87 let vx = x as f32 / gx as f32 * 2.0 - 1.0;
88 let vy = y as f32 / gy as f32 * 2.0 - 1.0;
89 let rad = (vx * ax).hypot(vy * ay);
90 let ang = if y == gy / 2 && x == gx / 2 {
91 0.0
92 } else {
93 (vy * ay).atan2(vx * ax)
94 };
95 g.x.push(vx);
96 g.y.push(vy);
97 g.rad.push(rad);
98 g.ang.push(ang);
99 g.pm.push(projectm_vertex(gx, gy, ax, ay, x, gy - y));
100 }
101 }
102 Ok(g)
103 }
104
105 pub fn gx(&self) -> u32 {
107 self.gx
108 }
109
110 pub fn gy(&self) -> u32 {
112 self.gy
113 }
114
115 pub fn aspect_x(&self) -> f32 {
117 self.aspect_x
118 }
119
120 pub fn aspect_y(&self) -> f32 {
122 self.aspect_y
123 }
124
125 pub fn x(&self) -> &[f32] {
127 &self.x
128 }
129
130 pub fn y(&self) -> &[f32] {
132 &self.y
133 }
134
135 pub fn rad(&self) -> &[f32] {
137 &self.rad
138 }
139
140 pub fn ang(&self) -> &[f32] {
142 &self.ang
143 }
144
145 pub fn vertex_count(&self) -> usize {
147 ((self.gx + 1) * (self.gy + 1)) as usize
148 }
149
150 #[inline]
152 pub fn index(&self, x: u32, y: u32) -> usize {
153 (y * (self.gx + 1) + x) as usize
154 }
155
156 pub fn pv_x(&self, n: usize) -> f32 {
159 self.x[n] * 0.5 * self.aspect_x + 0.5
160 }
161 pub fn pv_y(&self, n: usize) -> f32 {
163 self.y[n] * -0.5 * self.aspect_y + 0.5
164 }
165
166 #[inline]
172 pub fn projectm_vertex(&self, x: u32, y: u32) -> ([f32; 2], f32, f32) {
173 if x <= self.gx && y <= self.gy {
174 self.pm[self.index(x, y)]
175 } else {
176 projectm_vertex(
177 self.gx,
178 self.gy,
179 self.aspect_x,
180 self.aspect_y,
181 x,
182 self.gy.wrapping_sub(y),
183 )
184 }
185 }
186}
187
188fn projectm_vertex(
190 gx: u32,
191 gy: u32,
192 ax: f32,
193 ay: f32,
194 x: u32,
195 row_pm: u32,
196) -> ([f32; 2], f32, f32) {
197 let vx = x as f32 / gx as f32 * 2.0 - 1.0;
198 let vy = row_pm as f32 / gy as f32 * 2.0 - 1.0;
199 let rad = (vx * ax).hypot(vy * ay);
200 let ang = if row_pm == gy / 2 && x == gx / 2 {
201 0.0
202 } else {
203 (vy * ay).atan2(vx * ax)
204 };
205 ([vx, vy], rad, ang)
206}
207
208#[derive(Clone, Copy, Debug, PartialEq)]
211pub struct VertexVars {
212 pub zoom: f32,
214 pub zoomexp: f32,
216 pub rot: f32,
218 pub warp: f32,
220 pub cx: f32,
222 pub cy: f32,
224 pub dx: f32,
226 pub dy: f32,
228 pub sx: f32,
230 pub sy: f32,
232}
233
234impl Default for VertexVars {
235 fn default() -> Self {
237 Self {
238 zoom: 1.0,
239 zoomexp: 1.0,
240 rot: 0.0,
241 warp: 1.0,
242 cx: 0.5,
243 cy: 0.5,
244 dx: 0.0,
245 dy: 0.0,
246 sx: 1.0,
247 sy: 1.0,
248 }
249 }
250}
251
252#[derive(Clone, Copy, Debug, PartialEq)]
254pub struct WarpAnim {
255 pub y_flip: bool,
259 pub gpu_pow: bool,
262 pub skip_tiny_warp: bool,
265 pub warp_time: f32,
267 pub scale_inv: f32,
269 pub f: [f32; 4],
271}
272
273impl WarpAnim {
274 pub fn new(time: f32, warp_anim_speed: f32, warp_scale: f32) -> Self {
276 let warp_time = time * warp_anim_speed;
277 let f = [
278 11.68 + 4.0 * (warp_time * 1.413 + 10.0).cos(),
279 8.77 + 3.0 * (warp_time * 1.113 + 7.0).cos(),
280 10.54 + 3.0 * (warp_time * 1.233 + 3.0).cos(),
281 11.49 + 4.0 * (warp_time * 0.933 + 5.0).cos(),
282 ];
283 Self {
284 y_flip: false,
285 gpu_pow: false,
286 skip_tiny_warp: false,
287 warp_time,
288 scale_inv: 1.0 / warp_scale,
289 f,
290 }
291 }
292
293 pub fn projectm(time: f32, warp_anim_speed: f32, warp_scale: f32) -> Self {
295 Self {
296 y_flip: true,
297 gpu_pow: true,
298 ..Self::new(time, warp_anim_speed, warp_scale)
299 }
300 }
301}
302
303pub fn warp_vertex_uv(
308 g: &MeshGeometry,
309 n: usize,
310 v: &VertexVars,
311 anim: &WarpAnim,
312 texel_offset_uv: [f32; 2],
313) -> [f32; 2] {
314 let vx = g.x[n];
315 let vy = g.y[n];
316 let wy = if anim.y_flip { -vy } else { vy };
318 let rad = g.rad[n];
319 let f = &anim.f;
320
321 let zoom2 = if anim.gpu_pow && v.zoom < 0.0 {
322 f32::NAN
323 } else {
324 v.zoom.powf(v.zoomexp.powf(rad * 2.0 - 1.0))
325 };
326 let zoom2_inv = 1.0 / zoom2;
327
328 let mut u = vx * g.aspect_x * 0.5 * zoom2_inv + 0.5;
329 let mut vv = -vy * g.aspect_y * 0.5 * zoom2_inv + 0.5;
330
331 u = (u - v.cx) / v.sx + v.cx;
333 vv = (vv - v.cy) / v.sy + v.cy;
334
335 let wt = anim.warp_time;
337 let si = anim.scale_inv;
338 if !anim.skip_tiny_warp || v.warp.abs() > 0.0001 {
339 u += v.warp * 0.0035 * (wt * 0.333 + si * (vx * f[0] - wy * f[3])).sin();
340 vv += v.warp * 0.0035 * (wt * 0.375 - si * (vx * f[2] + wy * f[1])).cos();
341 u += v.warp * 0.0035 * (wt * 0.753 - si * (vx * f[1] - wy * f[2])).cos();
342 vv += v.warp * 0.0035 * (wt * 0.825 + si * (vx * f[0] + wy * f[3])).sin();
343 }
344
345 let u2 = u - v.cx;
347 let v2 = vv - v.cy;
348 let cos_rot = v.rot.cos();
349 let sin_rot = v.rot.sin();
350 u = u2 * cos_rot - v2 * sin_rot + v.cx;
351 vv = u2 * sin_rot + v2 * cos_rot + v.cy;
352
353 u -= v.dx;
355 vv -= v.dy;
356
357 u = (u - 0.5) * (1.0 / g.aspect_x) + 0.5;
359 vv = (vv - 0.5) * (1.0 / g.aspect_y) + 0.5;
360
361 u += texel_offset_uv[0];
363 vv += texel_offset_uv[1];
364 [u, vv]
365}
366
367pub fn warp_mesh_uniform(
369 g: &MeshGeometry,
370 v: &VertexVars,
371 anim: &WarpAnim,
372 texel_offset_uv: [f32; 2],
373) -> Vec<[f32; 2]> {
374 (0..g.vertex_count())
375 .map(|n| warp_vertex_uv(g, n, v, anim, texel_offset_uv))
376 .collect()
377}
378
379pub fn texel_offset_uv(texel_offset: [f32; 2], tex_w: u32, tex_h: u32) -> [f32; 2] {
381 [
382 texel_offset[0] / tex_w as f32,
383 texel_offset[1] / tex_h as f32,
384 ]
385}
386
387#[cfg(test)]
388mod tests {
389 use super::*;
390
391 fn close(a: f32, b: f32) -> bool {
392 (a - b).abs() < 1e-5
393 }
394
395 #[test]
396 fn geometry_matches_md2_setup() {
397 let g = MeshGeometry::new(48, 36, 640, 360).unwrap();
398 assert_eq!(g.vertex_count(), 49 * 37);
399 assert!(close(g.aspect_x, 1.0));
400 assert!(close(g.aspect_y, 360.0 / 640.0));
401 assert!(close(g.x[0], -1.0) && close(g.y[0], -1.0));
403 assert!(close(g.x[48], 1.0) && close(g.y[48], -1.0));
404 let last = g.vertex_count() - 1;
405 assert!(close(g.x[last], 1.0) && close(g.y[last], 1.0));
406 let c = g.index(24, 18);
408 assert!(close(g.rad[c], 0.0) && g.ang[c] == 0.0);
409 let corner = (1.0f32 + (360.0f32 / 640.0).powi(2)).sqrt();
411 assert!(close(g.rad[0], corner));
412 assert!(close(g.pv_y(0), 0.5 + 0.5 * g.aspect_y));
414 assert!(close(g.pv_x(0), 0.0));
415 }
416
417 #[test]
418 fn identity_motion_maps_to_screen_uv() {
419 let g = MeshGeometry::new(48, 36, 640, 360).unwrap();
421 let anim = WarpAnim::new(3.0, 1.0, 1.0);
422 let v = VertexVars {
423 warp: 0.0,
424 ..Default::default()
425 };
426 let uv = warp_mesh_uniform(&g, &v, &anim, [0.0, 0.0]);
427 for n in 0..g.vertex_count() {
428 assert!(close(uv[n][0], g.x[n] * 0.5 + 0.5), "u {n}");
429 assert!(close(uv[n][1], -g.y[n] * 0.5 + 0.5), "v {n}");
430 }
431 assert!(close(uv[0][1], 1.0));
433 }
434
435 #[test]
436 fn zoom_rot_translate_hand_computed() {
437 let g = MeshGeometry::new(2, 2, 100, 100).unwrap(); let anim = WarpAnim::new(0.0, 1.0, 1.0);
439 let v = VertexVars {
441 zoom: 2.0,
442 warp: 0.0,
443 ..Default::default()
444 };
445 let uv = warp_vertex_uv(&g, g.index(2, 0), &v, &anim, [0.0, 0.0]); assert!(close(uv[0], 0.75) && close(uv[1], 0.75));
447 let v = VertexVars {
450 rot: std::f32::consts::FRAC_PI_2,
451 warp: 0.0,
452 ..Default::default()
453 };
454 let uv = warp_vertex_uv(&g, g.index(2, 2), &v, &anim, [0.0, 0.0]);
455 assert!(close(uv[0], 1.0) && close(uv[1], 1.0));
456 let v = VertexVars {
458 dx: 0.1,
459 dy: -0.2,
460 warp: 0.0,
461 ..Default::default()
462 };
463 let uv = warp_vertex_uv(&g, g.index(1, 1), &v, &anim, [0.001, 0.002]);
464 assert!(close(uv[0], 0.5 - 0.1 + 0.001) && close(uv[1], 0.5 + 0.2 + 0.002));
465 }
466
467 #[test]
468 fn warp_terms_are_applied() {
469 let g = MeshGeometry::new(4, 4, 64, 64).unwrap();
470 let anim = WarpAnim::new(1.0, 1.0, 1.0);
471 assert!(close(anim.f[0], 11.68 + 4.0 * (1.413f32 + 10.0).cos()));
472 let a = warp_vertex_uv(
473 &g,
474 7,
475 &VertexVars {
476 warp: 0.0,
477 ..Default::default()
478 },
479 &anim,
480 [0.0; 2],
481 );
482 let b = warp_vertex_uv(
483 &g,
484 7,
485 &VertexVars {
486 warp: 1.0,
487 ..Default::default()
488 },
489 &anim,
490 [0.0; 2],
491 );
492 let (du, dv) = ((b[0] - a[0]).abs(), (b[1] - a[1]).abs());
493 assert!(
494 du > 0.0 && du < 0.0141 && dv < 0.0141,
495 "warp displacement bounded by 2*0.0035: {du} {dv}"
496 );
497 }
498
499 #[test]
502 fn tiny_warp_skips_the_terms_under_md3() {
503 let g = MeshGeometry::new(4, 4, 64, 64).unwrap();
504 let md2 = WarpAnim::new(1.0, 1.0, 1.0);
505 let md3 = WarpAnim {
506 skip_tiny_warp: true,
507 ..md2
508 };
509 let uv = |warp: f32, anim: &WarpAnim| {
510 warp_vertex_uv(
511 &g,
512 7,
513 &VertexVars {
514 warp,
515 ..Default::default()
516 },
517 anim,
518 [0.0; 2],
519 )
520 };
521 let base = uv(0.0, &md3);
522 assert_eq!(uv(0.0001, &md3), base, "|warp| <= 1e-4: skipped");
523 assert_eq!(uv(-0.0001, &md3), base);
524 assert_ne!(uv(0.0001, &md2), base, "MD2 adds the terms");
525 let big = uv(0.0002, &md3);
526 assert_eq!(big, uv(0.0002, &md2), "above the threshold both add them");
527 assert_ne!(big, base);
528 assert_eq!(uv(1.0, &md3), uv(1.0, &md2));
529 }
530
531 #[test]
535 fn projectm_vertex_follows_initialize_mesh() {
536 let g = MeshGeometry::new(48, 36, 640, 360).unwrap();
537 let (p0, rad0, _) = g.projectm_vertex(0, 0);
538 assert_eq!(p0, [-1.0, 1.0]);
539 assert!(close(rad0, (1.0f32 + (360.0f32 / 640.0).powi(2)).sqrt()));
540 let (pc, radc, angc) = g.projectm_vertex(24, 18);
541 assert_eq!((pc, radc, angc), ([0.0, 0.0], 0.0, 0.0));
542 let (p, rad, ang) = g.projectm_vertex(24, 34);
544 assert_eq!(p[1], 2.0f32 / 36.0 * 2.0 - 1.0);
545 assert_eq!(rad, (p[1] * g.aspect_y).abs());
546 assert!(ang < 0.0, "top half has negative atan2(y, x)");
547 assert_eq!(g.projectm_vertex(3, 18).2, std::f32::consts::PI);
549 }
550
551 #[test]
552 fn negative_zoom_is_nan_on_the_gpu_but_finite_in_md2() {
553 let g = MeshGeometry::new(4, 4, 64, 64).unwrap();
554 let v = VertexVars {
555 zoom: -0.5,
556 ..Default::default()
557 };
558 let uv = warp_vertex_uv(&g, 7, &v, &WarpAnim::projectm(1.0, 1.0, 1.0), [0.0; 2]);
559 assert!(uv[0].is_nan() && uv[1].is_nan());
560 let uv = warp_vertex_uv(&g, 7, &v, &WarpAnim::new(1.0, 1.0, 1.0), [0.0; 2]);
561 assert!(uv[0].is_finite() && uv[1].is_finite());
562 let v = VertexVars {
564 zoom: 1.5,
565 ..Default::default()
566 };
567 let uv = warp_vertex_uv(&g, 7, &v, &WarpAnim::projectm(1.0, 1.0, 1.0), [0.0; 2]);
568 assert!(uv[0].is_finite() && uv[1].is_finite());
569 }
570}