1use glam::Vec3;
19
20pub fn octahedral_encode(n: Vec3) -> [f32; 2] {
26 let sum = n.x.abs() + n.y.abs() + n.z.abs();
27 if sum <= f32::EPSILON {
28 return [0.5, 0.5]; }
30 let p = n / sum;
31 let mut e = [p.x, p.y];
32 if p.z < 0.0 {
33 let sx = if e[0] >= 0.0 { 1.0 } else { -1.0 };
34 let sy = if e[1] >= 0.0 { 1.0 } else { -1.0 };
35 e = [(1.0 - e[1].abs()) * sx, (1.0 - e[0].abs()) * sy];
36 }
37 [e[0] * 0.5 + 0.5, e[1] * 0.5 + 0.5]
38}
39
40pub fn octahedral_decode(uv: [f32; 2]) -> Vec3 {
45 let e = [
46 uv[0].clamp(0.0, 1.0) * 2.0 - 1.0,
47 uv[1].clamp(0.0, 1.0) * 2.0 - 1.0,
48 ];
49 let z = 1.0 - e[0].abs() - e[1].abs();
50 let v = if z >= 0.0 {
51 Vec3::new(e[0], e[1], z)
52 } else {
53 let sx = if e[0] >= 0.0 { 1.0 } else { -1.0 };
54 let sy = if e[1] >= 0.0 { 1.0 } else { -1.0 };
55 Vec3::new((1.0 - e[1].abs()) * sx, (1.0 - e[0].abs()) * sy, z)
56 };
57 let len = v.length();
59 if len <= f32::EPSILON {
60 Vec3::Z
61 } else {
62 v / len
63 }
64}
65
66pub fn quantize_uv(uv: [f32; 2], bits: u32) -> [f32; 2] {
69 let steps = (1u32 << bits) - 1;
70 uv.map(|c| (c.clamp(0.0, 1.0) * steps as f32).round() / steps as f32)
71}
72
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
82pub enum GfxFormat {
83 Rgba8Unorm,
85 Rg16Float,
87 R32Uint,
89 Depth32Float,
91}
92
93impl GfxFormat {
94 pub fn bytes_per_pixel(&self) -> u32 {
96 match self {
97 GfxFormat::Rgba8Unorm
98 | GfxFormat::Rg16Float
99 | GfxFormat::R32Uint
100 | GfxFormat::Depth32Float => 4,
101 }
102 }
103
104 pub fn channel_count(&self) -> usize {
106 match self {
107 GfxFormat::Rgba8Unorm => 4,
108 GfxFormat::Rg16Float => 2,
109 GfxFormat::R32Uint | GfxFormat::Depth32Float => 1,
110 }
111 }
112
113 fn is_quantized8(&self) -> bool {
115 matches!(self, GfxFormat::Rgba8Unorm)
116 }
117}
118
119#[derive(Clone, Copy, Debug, PartialEq, Eq)]
121pub enum ChannelSemantic {
122 AlbedoR,
123 AlbedoG,
124 AlbedoB,
125 Metallic,
126 NormalOctX,
127 NormalOctY,
128 Roughness,
129 MaterialId,
130 VelocityX,
131 VelocityY,
132 VisibilityId,
134 Unused,
135}
136
137#[derive(Clone, Copy, Debug, PartialEq, Eq)]
139pub struct GBufferTarget {
140 pub format: GfxFormat,
141 pub channels: [ChannelSemantic; 4],
142}
143
144#[derive(Clone, Debug, PartialEq, Eq)]
146pub struct GBufferLayout {
147 pub targets: Vec<GBufferTarget>,
148 pub depth: GfxFormat,
149}
150
151impl GBufferLayout {
152 pub fn deferred_v1() -> Self {
156 Self {
157 targets: vec![
158 GBufferTarget {
159 format: GfxFormat::Rgba8Unorm,
160 channels: [
161 ChannelSemantic::AlbedoR,
162 ChannelSemantic::AlbedoG,
163 ChannelSemantic::AlbedoB,
164 ChannelSemantic::Metallic,
165 ],
166 },
167 GBufferTarget {
168 format: GfxFormat::Rgba8Unorm,
169 channels: [
170 ChannelSemantic::NormalOctX,
171 ChannelSemantic::NormalOctY,
172 ChannelSemantic::Roughness,
173 ChannelSemantic::MaterialId,
174 ],
175 },
176 GBufferTarget {
177 format: GfxFormat::Rg16Float,
178 channels: [
179 ChannelSemantic::VelocityX,
180 ChannelSemantic::VelocityY,
181 ChannelSemantic::Unused,
182 ChannelSemantic::Unused,
183 ],
184 },
185 ],
186 depth: GfxFormat::Depth32Float,
187 }
188 }
189
190 pub fn visibility_v1() -> Self {
193 Self {
194 targets: vec![GBufferTarget {
195 format: GfxFormat::R32Uint,
196 channels: [
197 ChannelSemantic::VisibilityId,
198 ChannelSemantic::Unused,
199 ChannelSemantic::Unused,
200 ChannelSemantic::Unused,
201 ],
202 }],
203 depth: GfxFormat::Depth32Float,
204 }
205 }
206
207 pub fn bytes_per_pixel(&self) -> u32 {
209 self.targets
210 .iter()
211 .map(|t| t.format.bytes_per_pixel())
212 .sum::<u32>()
213 + self.depth.bytes_per_pixel()
214 }
215
216 pub fn find(&self, sem: ChannelSemantic) -> Option<(usize, usize)> {
218 self.targets
219 .iter()
220 .enumerate()
221 .find_map(|(t, tgt)| tgt.channels.iter().position(|c| *c == sem).map(|c| (t, c)))
222 }
223
224 pub fn validate(&self) -> Result<(), String> {
228 let mut seen: Vec<ChannelSemantic> = Vec::new();
229 for (t, tgt) in self.targets.iter().enumerate() {
230 for (c, sem) in tgt.channels.iter().enumerate() {
231 if *sem == ChannelSemantic::Unused {
232 continue;
233 }
234 if c >= tgt.format.channel_count() {
235 return Err(format!(
236 "Target {t}: Kanal {c} über Formatbreite {}",
237 tgt.format.channel_count()
238 ));
239 }
240 if seen.contains(sem) {
241 return Err(format!("doppelte Semantik {sem:?}"));
242 }
243 seen.push(*sem);
244 }
245 }
246 let has = |s| seen.contains(&s);
247 let albedo_count = [
248 ChannelSemantic::AlbedoR,
249 ChannelSemantic::AlbedoG,
250 ChannelSemantic::AlbedoB,
251 ]
252 .iter()
253 .filter(|s| has(**s))
254 .count();
255 if !(albedo_count == 0 || albedo_count == 3) {
256 return Err(format!("Albedo unvollständig ({albedo_count}/3 Kanälen)"));
257 }
258 if has(ChannelSemantic::NormalOctX) != has(ChannelSemantic::NormalOctY) {
259 return Err("Normal-Oktaeder nur halb vorhanden".into());
260 }
261 if has(ChannelSemantic::VelocityX) != has(ChannelSemantic::VelocityY) {
262 return Err("Velocity nur halb vorhanden".into());
263 }
264 Ok(())
265 }
266
267 pub fn pack(&self, s: &Surface) -> Vec<[f32; 4]> {
271 let oct = octahedral_encode(s.normal);
272 let mut out = vec![[0.0f32; 4]; self.targets.len()];
273 for (t, tgt) in self.targets.iter().enumerate() {
274 for (c, sem) in tgt.channels.iter().enumerate() {
275 let v = match sem {
276 ChannelSemantic::AlbedoR => s.albedo[0],
277 ChannelSemantic::AlbedoG => s.albedo[1],
278 ChannelSemantic::AlbedoB => s.albedo[2],
279 ChannelSemantic::Metallic => s.metallic,
280 ChannelSemantic::NormalOctX => oct[0],
281 ChannelSemantic::NormalOctY => oct[1],
282 ChannelSemantic::Roughness => s.roughness,
283 ChannelSemantic::MaterialId => s.material_id as f32 / 255.0,
284 ChannelSemantic::VelocityX => s.velocity[0],
285 ChannelSemantic::VelocityY => s.velocity[1],
286 _ => 0.0,
287 };
288 out[t][c] = if tgt.format.is_quantized8() { q8(v) } else { v };
289 }
290 }
291 out
292 }
293
294 pub fn unpack(&self, targets: &[[f32; 4]]) -> Surface {
297 let get = |sem: ChannelSemantic| -> f32 {
298 self.find(sem)
299 .and_then(|(t, c)| targets.get(t).map(|row| row[c]))
300 .unwrap_or(0.0)
301 };
302 Surface {
303 albedo: [
304 get(ChannelSemantic::AlbedoR),
305 get(ChannelSemantic::AlbedoG),
306 get(ChannelSemantic::AlbedoB),
307 ],
308 metallic: get(ChannelSemantic::Metallic),
309 roughness: get(ChannelSemantic::Roughness),
310 normal: octahedral_decode([
311 get(ChannelSemantic::NormalOctX),
312 get(ChannelSemantic::NormalOctY),
313 ]),
314 material_id: (get(ChannelSemantic::MaterialId) * 255.0).round() as u8,
315 velocity: [
316 get(ChannelSemantic::VelocityX),
317 get(ChannelSemantic::VelocityY),
318 ],
319 }
320 }
321}
322
323fn q8(v: f32) -> f32 {
325 (v.clamp(0.0, 1.0) * 255.0).round() / 255.0
326}
327
328#[derive(Clone, Copy, Debug, PartialEq)]
331pub struct Surface {
332 pub albedo: [f32; 3],
334 pub metallic: f32,
335 pub roughness: f32,
336 pub normal: Vec3,
338 pub material_id: u8,
339 pub velocity: [f32; 2],
341}
342
343impl Default for Surface {
344 fn default() -> Self {
345 Self {
346 albedo: [0.5, 0.5, 0.5],
347 metallic: 0.0,
348 roughness: 0.5,
349 normal: Vec3::Z,
350 material_id: 0,
351 velocity: [0.0, 0.0],
352 }
353 }
354}
355
356pub fn pack_visibility_id(instance: u16, primitive: u16) -> u32 {
358 ((instance as u32) << 16) | primitive as u32
359}
360
361pub fn unpack_visibility_id(id: u32) -> (u16, u16) {
363 ((id >> 16) as u16, id as u16)
364}
365
366#[cfg(test)]
367mod tests {
368 use super::*;
369
370 fn angle_deg(a: Vec3, b: Vec3) -> f32 {
371 a.normalize()
372 .dot(b.normalize())
373 .clamp(-1.0, 1.0)
374 .acos()
375 .to_degrees()
376 }
377
378 #[test]
379 fn achsen_runden_exakt() {
380 let achsen = [Vec3::X, -Vec3::X, Vec3::Y, -Vec3::Y, Vec3::Z, -Vec3::Z];
381 for a in achsen {
382 let back = octahedral_decode(octahedral_encode(a));
383 assert!(angle_deg(a, back) < 1e-3, "{a:?} -> {back:?}");
384 }
385 }
386
387 #[test]
388 fn diagonale_runden_dicht() {
389 let richtungen = [
390 Vec3::new(1.0, 1.0, 1.0),
391 Vec3::new(-1.0, 0.2, -0.7),
392 Vec3::new(0.0, -1.0, -1.0),
393 Vec3::new(0.3, 0.3, -0.05),
394 Vec3::new(-0.9, 0.1, 0.42),
395 ];
396 for r in richtungen {
397 let back = octahedral_decode(octahedral_encode(r));
398 assert!(angle_deg(r, back) < 1e-3, "{r:?} -> {back:?}");
399 }
400 }
401
402 #[test]
403 fn kodierte_uv_in_null_eins() {
404 for i in 0..64u32 {
405 let f = i as f32 / 64.0;
406 let n = Vec3::new((f * 7.0).sin(), (f * 11.0).cos(), (f * 3.0).sin() - 0.3);
407 let uv = octahedral_encode(n);
408 assert!(
409 uv[0] >= 0.0 && uv[0] <= 1.0 && uv[1] >= 0.0 && uv[1] <= 1.0,
410 "{n:?} -> {uv:?}"
411 );
412 }
413 }
414
415 #[test]
416 fn nullvektor_ist_plus_z() {
417 assert_eq!(octahedral_encode(Vec3::ZERO), [0.5, 0.5]);
418 assert_eq!(octahedral_decode([0.5, 0.5]), Vec3::Z);
419 }
420
421 #[test]
422 fn encode_decode_encode_idempotent() {
423 let n = Vec3::new(0.4, -0.8, 0.35);
424 let uv1 = octahedral_encode(n);
425 let uv2 = octahedral_encode(octahedral_decode(uv1));
426 assert!((uv1[0] - uv2[0]).abs() < 1e-5 && (uv1[1] - uv2[1]).abs() < 1e-5);
427 }
428
429 #[test]
430 fn quantisierung_8bit_haelt_winkel_klein() {
431 let mut worst = 0.0f32;
433 for i in 0..64u32 {
434 let f = i as f32 / 64.0;
435 let n = Vec3::new((f * 13.0).sin(), (f * 5.0).cos(), (f * 9.0).sin());
436 let q = quantize_uv(octahedral_encode(n), 8);
437 worst = worst.max(angle_deg(n, octahedral_decode(q)));
438 }
439 assert!(worst < 3.0, "8-Bit-Quantisierung: max {worst}°");
440 }
441
442 #[test]
443 fn decode_klemmt_ausserhalb() {
444 let v = octahedral_decode([1.02, -0.01]);
447 assert!(v.is_finite());
448 assert!((v.length() - 1.0).abs() < 1e-5);
449 }
450
451 #[test]
452 fn deferred_layout_struktur_und_bandbreite() {
453 let l = GBufferLayout::deferred_v1();
454 assert_eq!(l.targets.len(), 3);
455 assert!(l.validate().is_ok());
456 assert_eq!(l.bytes_per_pixel(), 16);
458 assert_eq!(l.find(ChannelSemantic::AlbedoR), Some((0, 0)));
460 assert_eq!(l.find(ChannelSemantic::Metallic), Some((0, 3)));
461 assert_eq!(l.find(ChannelSemantic::NormalOctX), Some((1, 0)));
462 assert_eq!(l.find(ChannelSemantic::Roughness), Some((1, 2)));
463 assert_eq!(l.find(ChannelSemantic::MaterialId), Some((1, 3)));
464 assert_eq!(l.find(ChannelSemantic::VelocityX), Some((2, 0)));
465 assert_eq!(l.find(ChannelSemantic::VisibilityId), None);
466 }
467
468 #[test]
469 fn visibility_layout_halbe_bandbreite() {
470 let v = GBufferLayout::visibility_v1();
471 assert!(v.validate().is_ok());
472 assert_eq!(v.bytes_per_pixel(), 8);
474 assert_eq!(v.find(ChannelSemantic::VisibilityId), Some((0, 0)));
475 }
476
477 #[test]
478 fn validierung_findet_fehler() {
479 let mut l = GBufferLayout::deferred_v1();
481 l.targets[1].channels[3] = ChannelSemantic::Roughness;
482 assert!(l.validate().is_err(), "doppeltes Roughness muss fehln");
483 let mut l2 = GBufferLayout::deferred_v1();
485 l2.targets[2].channels[2] = ChannelSemantic::Metallic;
486 assert!(l2.validate().is_err(), "Kanal 2 in RG-Format muss fehln");
487 let mut l3 = GBufferLayout::deferred_v1();
489 l3.targets[0].channels[1] = ChannelSemantic::Unused;
490 assert!(l3.validate().is_err(), "2/3 Albedo muss fehln");
491 let mut l4 = GBufferLayout::deferred_v1();
493 l4.targets[1].channels[1] = ChannelSemantic::Unused;
494 assert!(l4.validate().is_err(), "Normal-X ohne Y muss fehln");
495 let mut l5 = GBufferLayout::deferred_v1();
497 l5.targets[2].channels[1] = ChannelSemantic::Unused;
498 assert!(l5.validate().is_err(), "Velocity-X ohne Y muss fehln");
499 }
500
501 #[test]
502 fn pack_unpack_roundtrip_haelt_praezisionsbudget() {
503 let l = GBufferLayout::deferred_v1();
504 let s = Surface {
505 albedo: [0.8, 0.25, 0.5],
506 metallic: 1.0,
507 roughness: 0.37,
508 normal: Vec3::new(0.4, -0.8, 0.35).normalize(),
509 material_id: 173,
510 velocity: [-12.75, 3.5],
511 };
512 let back = l.unpack(&l.pack(&s));
513 for i in 0..3 {
515 assert!(
516 (back.albedo[i] - s.albedo[i]).abs() <= 1.0 / 255.0 + 1e-6,
517 "albedo {i}"
518 );
519 }
520 assert!((back.metallic - s.metallic).abs() <= 1.0 / 255.0 + 1e-6);
521 assert!((back.roughness - s.roughness).abs() <= 1.0 / 255.0 + 1e-6);
522 let dot = back.normal.dot(s.normal).clamp(-1.0, 1.0);
524 let winkel = dot.acos().to_degrees();
525 assert!(winkel < 3.0, "Normalenwinkel {winkel}°");
526 assert_eq!(back.material_id, s.material_id);
528 assert_eq!(back.velocity, s.velocity);
529 }
530
531 #[test]
532 fn quantisierung_entspricht_dem_format() {
533 let l = GBufferLayout::deferred_v1();
534 let s = Surface {
535 albedo: [0.5001, 0.0, 0.0], velocity: [123.456, -0.001], ..Default::default()
538 };
539 let packed = l.pack(&s);
540 assert_eq!(packed[0][0], 128.0 / 255.0, "Albedo muss auf 8 Bit rastern");
541 assert_eq!(
542 packed[2][0], 123.456,
543 "Velocity (RG16F-Spec) darf nicht rastern"
544 );
545 }
546
547 #[test]
548 fn visibility_id_rundlauf() {
549 for (inst, prim) in [(0u16, 0u16), (1, 2), (65535, 65535), (4096, 1234)] {
550 let id = pack_visibility_id(inst, prim);
551 assert_eq!(unpack_visibility_id(id), (inst, prim));
552 }
553 assert_eq!(pack_visibility_id(1, 0), 1 << 16);
555 assert_eq!(pack_visibility_id(0, 1), 1);
556 }
557}