oxigaf-render 0.1.2

Differentiable 3D Gaussian Splatting rasterizer (wgpu)
Documentation
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
//! # oxigaf-render
//!
//! Differentiable 3D Gaussian Splatting rasterizer using wgpu compute shaders.
//!
//! The rasterizer implements the full 3DGS pipeline:
//! - **Forward**: project → sort → rasterize (per-tile alpha-blending)
//! - **Backward**: reverse-order gradient computation through the rasterizer
//!
//! FLAME mesh binding allows Gaussians to be anchored to a parametric head model.
//!
//! ## Cargo Features
//!
//! This crate supports the following feature flags:
//!
//! - **`default`** = `[]`:
//!   Minimal configuration with no extra features
//!
//! - **`gpu_debug`**:
//!   Enables GPU debug mode with validation layers:
//!   - Vulkan validation layers on Linux/Windows
//!   - Metal API validation on macOS
//!   - DirectX debug layer on Windows
//!   - Enhanced error messages and warnings
//!   - **Warning**: Adds significant runtime overhead (10-100× slower)
//!
//! The `gpu_debug` feature is useful for:
//! - Debugging shader errors
//! - Validating buffer usage
//! - Catching GPU API misuse
//! - Performance profiling with detailed traces
//!
//! Example usage:
//! ```toml
//! # In Cargo.toml
//! # For production use (fast, minimal validation)
//! oxigaf-render = { version = "0.1" }
//!
//! # For development/debugging (slow, extensive validation)
//! oxigaf-render = { version = "0.1", features = ["gpu_debug"] }
//! ```
//!
//! ## Examples
//!
//! These mirror the examples in this crate's `README.md`, but as real
//! doctests so `cargo test --doc` catches API drift instead of letting the
//! README quietly rot. The GPU-touching ones are `no_run`: they are compiled
//! and type-checked on every test run, but not executed (creating a wgpu
//! device and writing PNGs is not something a doctest should do).
//!
//! The examples use [`pollster`](https://docs.rs/pollster) to block on the
//! async GPU setup from a plain `fn main`; add `pollster = "1"` to your own
//! `[dependencies]` to run them as-is (any other async executor works too).
//!
//! ### Basic Gaussian rendering
//!
//! ```no_run
//! use oxigaf_render::{
//!     keyframe_to_render_camera, CameraKeyframe, GaussianAttributes, GaussianModel,
//!     RasterConfig, Rasterizer, RenderError,
//! };
//!
//! // `Rasterizer::new` is async because wgpu device creation is async.
//! fn main() -> Result<(), RenderError> {
//!     pollster::block_on(run())
//! }
//!
//! async fn run() -> Result<(), RenderError> {
//!     // A single Gaussian at the origin, SH degree 0.
//!     let gaussians = vec![GaussianAttributes {
//!         position: [0.0, 0.0, 0.0],
//!         _pad0: 0.0,
//!         rotation: [0.0, 0.0, 0.0, 1.0], // identity quaternion (x, y, z, w)
//!         scale: [-4.0, -4.0, -4.0],      // log-scale: exp(-4) ≈ 0.018
//!         opacity: 2.0,                   // inverse-sigmoid: sigmoid(2.0) ≈ 0.88
//!     }];
//!
//!     // DC-only SH colour. The DC term is scaled by the Y_0^0 basis constant
//!     // (≈ 0.2821) when evaluated, so pre-dividing by it gives ≈ [1.0, 0.5, 0.5].
//!     let sh_coeffs = vec![3.545, 1.772, 1.772];
//!
//!     let model = GaussianModel {
//!         gaussians,
//!         sh_coeffs,
//!         sh_degree: 0,
//!         // Only meaningful for FLAME-bound avatars; unused here.
//!         face_indices: vec![0],
//!         barycentric: vec![[1.0, 0.0, 0.0]],
//!         local_offsets: vec![[0.0, 0.0, 0.0]],
//!         is_rigid: vec![true],
//!     };
//!
//!     let config = RasterConfig::new().with_resolution(512, 512).with_sh_degree(0);
//!     let mut rasterizer = Rasterizer::new(config.clone()).await?;
//!
//!     let camera = keyframe_to_render_camera(
//!         &CameraKeyframe::look_from_to(0.0, [0.0, 0.0, 2.0], [0.0, 0.0, 0.0]),
//!         config.image_width as usize,
//!         config.image_height as usize,
//!     );
//!
//!     rasterizer.upload_gaussians(&model);
//!     let output = rasterizer.forward(&model, &camera)?;
//!
//!     let image = rasterizer.download_image(&output);
//!     image
//!         .save("output.png")
//!         .map_err(|e| RenderError::ImageSaveFailed(e.to_string()))?;
//!
//!     println!("Rendered {} Gaussians", model.len());
//!     Ok(())
//! }
//! ```
//!
//! ### Differentiable rendering with gradients
//!
//! ```no_run
//! use oxigaf_render::{
//!     keyframe_to_render_camera, CameraKeyframe, GaussianGradients, GaussianModel,
//!     RasterConfig, RenderCamera, Rasterizer, RenderError,
//! };
//! # use oxigaf_render::GaussianAttributes;
//! # fn demo_model() -> GaussianModel {
//! #     GaussianModel {
//! #         gaussians: vec![GaussianAttributes {
//! #             position: [0.0, 0.0, 0.0],
//! #             _pad0: 0.0,
//! #             rotation: [0.0, 0.0, 0.0, 1.0],
//! #             scale: [-4.0, -4.0, -4.0],
//! #             opacity: 2.0,
//! #         }],
//! #         sh_coeffs: vec![3.545, 1.772, 1.772],
//! #         sh_degree: 0,
//! #         face_indices: vec![0],
//! #         barycentric: vec![[1.0, 0.0, 0.0]],
//! #         local_offsets: vec![[0.0, 0.0, 0.0]],
//! #         is_rigid: vec![true],
//! #     }
//! # }
//!
//! fn main() -> Result<(), RenderError> {
//!     pollster::block_on(run())
//! }
//!
//! async fn run() -> Result<(), RenderError> {
//!     let config = RasterConfig::default();
//!     let mut rasterizer = Rasterizer::new(config.clone()).await?;
//!     let mut model = demo_model(); // swap in your own model
//!     let camera = create_camera(config.image_width, config.image_height);
//!
//!     // Forward pass.
//!     rasterizer.upload_gaussians(&model);
//!     let output = rasterizer.forward(&model, &camera)?;
//!
//!     // Per-pixel loss gradient against a target (e.g. L1).
//!     let target = vec![0.0_f32; output.color_data.len()];
//!     let grad_image = l1_gradient(&output.color_data, &target);
//!
//!     // Backward pass: chains the image-space gradient back to per-Gaussian gradients.
//!     let gradients = rasterizer.backward(&model, &grad_image)?;
//!
//!     println!("Position gradients: {} values", gradients.grad_positions.len());
//!     println!("Rotation gradients: {} values", gradients.grad_rotations.len());
//!     println!("Scale gradients:    {} values", gradients.grad_scales.len());
//!     println!("Opacity gradients:  {} values", gradients.grad_opacities.len());
//!     println!("SH gradients:       {} values", gradients.grad_sh_coeffs.len());
//!
//!     // Apply gradients with a plain SGD step (swap in Adam etc. for real training).
//!     apply_gradients(&mut model, &gradients, 0.001);
//!     Ok(())
//! }
//!
//! fn create_camera(width: u32, height: u32) -> RenderCamera {
//!     keyframe_to_render_camera(
//!         &CameraKeyframe::look_from_to(0.0, [0.0, 0.0, 2.0], [0.0, 0.0, 0.0]),
//!         width as usize,
//!         height as usize,
//!     )
//! }
//!
//! /// L1 loss gradient: sign(rendered - target).
//! fn l1_gradient(rendered: &[f32], target: &[f32]) -> Vec<f32> {
//!     rendered.iter().zip(target).map(|(r, t)| (r - t).signum()).collect()
//! }
//!
//! fn apply_gradients(model: &mut GaussianModel, gradients: &GaussianGradients, lr: f32) {
//!     for (g, grad) in model.gaussians.iter_mut().zip(gradients.grad_positions.iter()) {
//!         g.position[0] -= lr * grad[0];
//!         g.position[1] -= lr * grad[1];
//!         g.position[2] -= lr * grad[2];
//!     }
//! }
//! ```
//!
//! ### Custom camera trajectories
//!
//! ```no_run
//! use oxigaf_render::{turntable_path, GaussianModel, RasterConfig, Rasterizer, RenderError};
//! use std::f32::consts::FRAC_PI_4;
//! # use oxigaf_render::GaussianAttributes;
//! # fn load_avatar_model() -> GaussianModel {
//! #     GaussianModel {
//! #         gaussians: vec![GaussianAttributes {
//! #             position: [0.0, 0.0, 0.0],
//! #             _pad0: 0.0,
//! #             rotation: [0.0, 0.0, 0.0, 1.0],
//! #             scale: [-4.0, -4.0, -4.0],
//! #             opacity: 2.0,
//! #         }],
//! #         sh_coeffs: vec![3.545, 1.772, 1.772],
//! #         sh_degree: 0,
//! #         face_indices: vec![0],
//! #         barycentric: vec![[1.0, 0.0, 0.0]],
//! #         local_offsets: vec![[0.0, 0.0, 0.0]],
//! #         is_rigid: vec![true],
//! #     }
//! # }
//!
//! fn main() -> Result<(), RenderError> {
//!     pollster::block_on(run())
//! }
//!
//! async fn run() -> Result<(), RenderError> {
//!     let config = RasterConfig::new().with_resolution(512, 512);
//!     let mut rasterizer = Rasterizer::new(config.clone()).await?;
//!     let model = load_avatar_model(); // e.g. GaussianModel::load_ply(...)
//!
//!     // A 360-frame turntable orbit around the origin.
//!     let num_frames: usize = 360;
//!     let path = turntable_path(
//!         [0.0, 0.0, 0.0], // center
//!         2.0,             // radius
//!         0.0,             // elevation
//!         num_frames,      // keyframes
//!         FRAC_PI_4,       // vertical FOV
//!     );
//!     let cameras = path.to_render_cameras(
//!         num_frames,
//!         config.image_width as usize,
//!         config.image_height as usize,
//!     );
//!
//!     rasterizer.upload_gaussians(&model);
//!     for (frame, camera) in cameras.iter().enumerate() {
//!         let output = rasterizer.forward(&model, camera)?;
//!         let image = rasterizer.download_image(&output);
//!         image.save(format!("frame_{frame:04}.png")).map_err(|e| {
//!             RenderError::ImageSaveFailed(format!("Failed to save frame {frame}: {e}"))
//!         })?;
//!     }
//!
//!     println!("Rendered {} frames", cameras.len());
//!     Ok(())
//! }
//! ```
//!
//! ### High-quality rendering configuration
//!
//! ```no_run
//! use oxigaf_render::{RasterConfig, Rasterizer, RenderError};
//!
//! fn main() -> Result<(), RenderError> {
//!     let config = RasterConfig::new()
//!         .with_resolution(1920, 1080) // Full HD
//!         .with_sh_degree(3)           // maximum spherical harmonics degree
//!         .with_depth_output(true);    // enable depth buffer output
//!
//!     println!("Resolution: {}x{}", config.image_width, config.image_height);
//!     println!("Tile size:  {}x{}", config.tile_size, config.tile_size);
//!     println!("Max SH degree: {}", config.sh_degree);
//!
//!     // `Rasterizer::new` is async because wgpu device creation is async.
//!     let _rasterizer = pollster::block_on(Rasterizer::new(config))?;
//!     Ok(())
//! }
//! ```
//!
//! ### Buffer pool for memory efficiency
//!
//! This one touches no GPU state, so it really runs:
//!
//! ```
//! use oxigaf_render::BufferPool;
//!
//! // A buffer pool for efficient GPU memory reuse (10 MB budget).
//! let pool = BufferPool::new(10 * 1024 * 1024);
//!
//! let stats = pool.stats();
//! assert_eq!(stats.total_allocations, 0);
//! assert_eq!(stats.total_acquisitions, 0);
//! assert_eq!(stats.in_use_count, 0);
//! assert_eq!(stats.available_count, 0);
//! assert_eq!(stats.total_allocated_bytes, 0);
//! println!("Hit rate: {:.1}%", stats.hit_rate * 100.0);
//!
//! // Buffers are automatically returned to the pool when dropped.
//! ```

#![cfg_attr(not(test), deny(clippy::unwrap_used))]
#![cfg_attr(not(test), deny(clippy::expect_used))]

pub mod ambient_occlusion;
pub mod antialiasing;
pub mod background;
pub mod binding;
pub mod bloom;
pub mod bloom_simple;
pub mod buffers;
pub mod bvh;
pub mod camera_path;
pub mod chrom_post_effect;
pub mod chromatic_aberration;
pub mod color_calibration;
pub mod color_grading;
pub mod colorspace;
pub mod compression;
pub mod config;
pub mod cov2d_backward;
pub mod cpu_reference;
pub mod debug_readback;
pub mod deform;
pub mod denoising;
pub mod density;
pub mod depth_map;
pub mod depth_of_field;
pub mod dof;
pub mod edge_detection;
pub mod environment;
pub mod exposure;
pub mod film_grain;
pub mod gaussian;
pub mod gaussian_culling;
pub mod gaussian_stats;
pub mod gltf;
pub mod hdr_tone_mapping;
pub mod image_compositor;
pub mod image_resize;
pub mod init;
pub mod lens_distortion;
pub mod lens_effects;
pub mod light_probe;
pub mod lod;
pub mod mb_pipeline;
pub mod mip_splatting;
pub mod model_pruning;
pub mod motion_blur;
pub mod motion_blur_image;
pub mod multi_view;
pub mod normal_estimation;
pub mod panoramic;
pub mod picking;
pub mod pipeline;
pub mod pool;
pub mod post_processing;
pub mod profiler;
pub mod rasterizer;
pub mod render_graph;
pub mod render_metrics;
pub mod scene_compositor;
pub mod sharpening;
pub mod silhouette;
pub mod sort;
pub mod spherical_harmonics;
pub mod ssao;
pub mod stereo;
pub mod temporal;
pub mod temporal_aa;
pub mod tile_stats;
pub mod tone_curve;
pub mod validation;
pub mod vignetting;
pub mod workgroup;

pub use background::{
    generate_background, standard_augmentor, BackgroundAugmentor, BackgroundColor,
    BackgroundEnvMap, BackgroundError, BackgroundImage, BackgroundType,
};
pub use color_grading::{
    hsv_to_rgb_grading, luminance, rgb_to_hsv_grading, ColorGradingError, ColorGradingPipeline,
    ContrastAdjust, ExposureAdjust, GradingStep, Lut3D, RgbHistogram, SaturationAdjust, ToneCurve,
};
pub use hdr_tone_mapping::{
    aces_filmic,
    apply_exposure,
    apply_gamma,
    apply_gamma_image,
    // New per-pixel helpers
    apply_operator,
    auto_exposure,
    compute_hdr_stats,
    estimate_scene_key,
    filmic,
    format_tone_config,
    gamma_correct,
    // Generalised Reinhard curve (previously mislabelled `lottes_approx`)
    generalized_reinhard,
    hable,
    hdr_image_stats,
    // New linear↔sRGB (prefixed to avoid conflict with colorspace::*)
    hdr_linear_to_srgb,
    // New white balance (prefixed to avoid conflict)
    hdr_white_balance,
    image_hdr_linear_to_srgb,
    inverse_srgb_gamma,
    // Real Lottes (GDC 2016) tone mapper
    lottes,
    // New analysis
    luminance_histogram,
    preset_aces,
    preset_filmic,
    preset_photography,
    preset_reinhard,
    recommend_exposure,
    reinhard,
    reinhard_extended,
    srgb_gamma,
    srgb_to_linear_hdr,
    tone_luminance,
    // New image-level pipeline
    tone_map,
    tone_map_image,
    tone_map_inplace,
    tone_map_rgba_image,
    HdrImageStats,
    HdrStats,
    LottesParams,
    ToneMapConfig,
    // New types and operators
    ToneMapOperator,
    ToneMappingConfig,
    ToneMappingError,
    ToneMappingOperator,
};
pub use image_compositor::{
    apply_blend_mode, blend_pixel, composite_image_layers, composite_over, composite_psnr,
    compute_image_composite_stats, extract_alpha, flatten_to_rgb, premultiply_alpha, replace_alpha,
    scale_alpha, solid_color, transparency_checkerboard, unpremultiply_alpha, BlendMode,
    CompositingLayer, CompositorConfig, ImageCompositeStats, ImageCompositorError,
};
pub use image_resize::{
    center_crop, crop, fit_dimensions, flip_horizontal, flip_vertical, image_pyramid, pad_image,
    pad_to_square, resize, resize_bicubic, resize_bilinear, resize_box, resize_nearest, rotate_180,
    rotate_90_ccw, rotate_90_cw, scale_by_factor, thumbnail,
    validate_buffer as validate_image_buffer, ResizeError, ResizeFilter,
};

// `AoProjParams` / `AoSamplingBuffers` are the argument types of the
// flat-re-exported `ao_compute` and `apply_ssao`: without them a
// crate-root-only caller cannot even build their parameters.
pub use ambient_occlusion::{
    ao_apply_to_image, ao_bilateral_blur, ao_compute, ao_compute_stats, ao_cross, ao_dot,
    ao_noise_texture, ao_normalize, ao_sample_depth, ao_sample_kernel, ao_smoothstep, apply_ssao,
    format_ao_config, format_ao_stats, AoConfig, AoError, AoProjParams, AoSamplingBuffers, AoStats,
    SsaoResult,
};
pub use antialiasing::{
    aa_bilinear_sample,
    aa_edge_count,
    aa_edge_map,
    aa_luminance,
    aa_luminance_map,
    aa_quality_estimate,
    aa_sample_pixel,
    aa_sample_pixel_edge,
    apply_antialiasing,
    apply_fxaa,
    apply_image_aa,
    // Callers wanting *real* temporal AA must use this history-aware entry
    // point; `apply_image_aa` has no history buffer to accumulate into.
    apply_image_aa_with_history,
    apply_smaa_lite,
    apply_supersampling_aa,
    apply_temporal_aa,
    compute_scale_compensation,
    compute_screen_radius_px,
    format_aa_config,
    format_aa_stats,
    opacity_scale_from_screen_radius,
    try_apply_antialiasing,
    AaConfig,
    // Post-processing AA
    AaError,
    AaMethod,
    AaStats,
    AliasingStats,
    MipSplatConfig,
};
pub use bvh::{extract_frustum_planes, Aabb, BvhNode, GaussianBvh};
pub use camera_path::{
    dolly_path, keyframe_to_render_camera, spiral_path, turntable_path, CameraKeyframe, CameraPath,
    PathInterpolation,
};
pub use color_calibration::{
    apply_calibration,
    apply_color_correction_matrix,
    apply_gamma_correction_image,
    apply_gamma_f32,
    apply_saturation_image,
    apply_srgb_decoding,
    apply_srgb_encoding,
    apply_white_balance_image,
    compute_color_stats,
    compute_correction_matrix,
    d65_white_balance,
    gray_world_white_balance,
    histogram_stretch_matrix,
    kelvin_to_rgb_multipliers,
    // Renamed to avoid clash with colorspace::{linear_to_srgb, srgb_to_linear}
    linear_to_srgb_calib,
    rgb_to_luminance,
    saturation_matrix,
    srgb_to_linear_calib,
    white_balance_matrix,
    CalibrationError,
    ColorCalibrationConfig,
    ColorMatrix,
    ColorStats,
    WhiteBalance,
};
pub use colorspace::{
    apply_tone_mapping_image,
    // Channel-generic (RGB *and* RGBA) variants added alongside the
    // `UnsupportedChannelCount` fix; the 3-channel-only functions above stay
    // for source compatibility.
    apply_tone_mapping_image_channels,
    apply_white_balance,
    color_linear_to_srgb,
    color_srgb_to_linear,
    convert_color,
    convert_image_colorspace,
    convert_image_colorspace_channels,
    hsl_to_linear_rgb,
    hsv_to_linear_rgb,
    lab_to_xyz,
    linear_rgb_to_hsl,
    linear_rgb_to_hsv,
    linear_rgb_to_xyz,
    linear_to_srgb,
    srgb_to_linear,
    white_balance_from_temperature,
    xyz_to_lab,
    xyz_to_linear_rgb,
    Color,
    ColorError,
    ColorSpace,
    ToneMapping,
};
pub use compression::{
    compress_gaussians, decompress_gaussians, CompressedGaussianModel, CompressedOpacities,
    CompressedPositions, CompressedRotations, CompressedScales, CompressionConfig,
    CompressionError, CompressionStats, DecompressedArrays, SceneBounds, ShCodebook, ShCompressed,
};
pub use config::RasterConfig;
pub use cov2d_backward::{cov2d_backward, Cov2dBwdInput, Cov2dGrads};
pub use cpu_reference::{CpuCamera, CpuRasterizer, CpuRenderOutput};
pub use debug_readback::{DebugReadbackBuilder, RasterizationSnapshot, RasterizationStats};
pub use deform::{deform_cpu, DeformPipeline, MeshBuffers};
pub use denoising::{
    bilateral_filter, denoise_adaptive, estimate_noise, gaussian_denoise, joint_bilateral_filter,
    median_filter, non_local_means, BilateralConfig, DenoisingError, DenoisingMethod,
    DenoisingPipeline, GaussianDenoiseConfig, MedianConfig, NlmConfig, NoiseStats,
};
pub use density::{DensityConfig, DensityController, GradientAccumulator};
pub use depth_map::{
    depth_map_to_pointcloud, depth_to_disparity, render_depth_map, render_depth_maps, DepthCamera,
    DepthMap, DepthMapError, DepthMapStats, DepthMode, DepthSample, GaussianDepthData,
};
pub use depth_of_field::{
    // Full pipeline (renamed to avoid collision with dof::apply_dof)
    apply_depth_of_field as apply_bokeh_depth_of_field,
    dof_bilinear_sample,
    dof_circular_kernel,
    dof_composite_layers,
    // dof_-prefixed functions (no collision risk)
    dof_compute_coc,
    dof_compute_stats,
    dof_format_config,
    dof_format_stats,
    dof_gather,
    dof_hexagonal_kernel,
    dof_make_kernel,
    dof_pentagonal_kernel,
    dof_separate_layers,
    dof_square_kernel,
    // Non-conflicting types
    BokehShape,
    DofCocBuffer,
    // Rename conflicting types to avoid collision with dof::{DofConfig, DofError, DofStats}
    DofConfig as BokehDofConfig,
    DofError as BokehDofError,
    DofResult,
    DofStats as BokehDofStats,
};
pub use dof::{
    apply_dof, compute_coc, generate_dof_kernel, DofConfig, DofError, DofKernelShape, DofStats,
};
pub use edge_detection::{
    build_edge_gaussian_kernel, canny_edges, compute_edge_stats, detect_edges_log,
    detect_edges_sobel, edge_convolve, edge_gaussian_blur, hysteresis_threshold, log_edges,
    non_max_suppress, prewitt_edges, rgba_to_luminance, sobel_edges, CannyConfig,
    EdgeDetectionError, EdgeMap, EdgeStats, SobelResult,
};
pub use environment::{
    evaluate_gaussian_sh, project_environment_to_sh, sh_basis_up_to_l2, EnvironmentMap,
    SphericalHarmonicsLight,
};
pub use exposure::{
    apply_ev, apply_exposure as apply_exposure_u8, apply_gamma_correction, apply_lift_gain_offset,
    auto_expose, clahe, compute_histogram, compute_luminance_map, exposure_bracket,
    histogram_equalize, hsl_to_rgb, meter_exposure, rgb_to_hsl, scene_key, ExposureConfig,
    ExposureError, ExposureMetering, LuminanceHistogram,
};
pub use film_grain::{
    apply_film_grain, apply_film_grain_frame, apply_film_grain_rgba, apply_film_grain_sequence,
    compute_grain_stats, film_luminance, generate_grain_map, grain_scale_fn, FilmGrainConfig,
    FilmGrainError, GrainStats,
};
pub use gaussian::{GaussianAttributes, GaussianModel};
pub use gaussian_culling::{
    compute_cull_stats, compute_screen_bounds, cull_gaussians, project_radius_ndc, transform_point,
    CullStats, CullingConfig, CullingError, CullingResult, FrustumPlane, GaussianCullData,
    ScreenSpaceBounds, ViewFrustum,
};
pub use gaussian_stats::{
    compute_scalar_stats, detect_anomalies, format_gaussian_report, GaussianHistograms,
    GaussianStats, Histogram, ScalarStats,
};
pub use gltf::{write_gltf, GltfError, EXTENSION_NAME};
pub use init::{GaussianInitConfig, GaussianInitializer};
pub use light_probe::{
    lp_apply_ibl_to_gaussians, lp_blend_irradiance_sh, lp_compute_stats, lp_cubemap_to_sh,
    lp_cubemap_to_sh_with_config, lp_dir_to_cubemap_uv, lp_evaluate_diffuse_ibl, lp_format_config,
    lp_format_stats, lp_generate_sphere_samples, lp_normalize_dir, lp_project_latitude_longitude,
    lp_project_latitude_longitude_with_config, lp_project_samples_to_sh, lp_sh_basis,
    lp_sh_basis_l0, lp_sh_basis_l1, lp_sh_basis_l2, CubemapFace, CubemapProbe, IrradianceSH,
    LightProbe, LightProbeBlend, LightProbeConfig, LightProbeError, LightProbeStats,
    ProbeBlendMode,
};
pub use lod::{
    opacity_scale_from_radius, AdaptiveLodConfig, GaussianLodInfo, LodCamera, LodConfig, LodError,
    LodFilter, LodLevel, LodManager, LodSelector, LodStats, LodTransition,
};
pub use mb_pipeline::{
    // apply_motion_blur renamed to avoid conflict with motion_blur_image::apply_motion_blur
    apply_motion_blur as mb_apply_full_pipeline,
    mb_apply,
    mb_bilinear_sample,
    mb_compute_stats,
    mb_depth_weight,
    mb_dilate_velocity,
    mb_format_config,
    mb_format_stats,
    mb_jitter_samples,
    mb_smooth_velocity,
    mb_triangle_weight,
    mb_velocity_from_camera_motion,
    mb_velocity_from_depth,
    mb_velocity_rotational,
    MbConfig,
    MbStats,
    MotionBlurResult,
    VelocityBuffer,
};
pub use mip_splatting::{
    adjust_scales_for_mip, compute_ewa_filter, compute_filter_variance, compute_mip_level,
    compute_mip_levels_batch, compute_mip_stats, FilterMode as MipFilterMode, MipCamera, MipConfig,
    MipSplattingError, MipSplattingStats,
};
pub use model_pruning::{
    apply_pruning_mask, compute_pruning_mask, prune_gaussian_arrays, ImportanceScorer,
    PrunedArrays, PruningConfig, PruningCriteria, PruningError, PruningResult, BYTES_PER_GAUSSIAN,
};
pub use motion_blur::{
    accumulate_frames, apply_velocity_blur, compute_motion_stats, lerp_position, lerp_quaternion,
    normalize_quaternion, subframe_t, AccumulatedBlur, AccumulationConfig, CameraMotion,
    MotionBlurError, MotionBlurStats, VelocityBlurConfig, VelocityField,
};
pub use motion_blur_image::{
    accumulate_motion_blur, apply_linear_motion_blur, apply_motion_blur,
    apply_per_pixel_motion_blur, apply_radial_blur, apply_rotational_blur,
    compute_image_motion_stats, compute_motion_from_frames, format_motion_stats, BlurType,
    ImageMotionField, MotionBlurConfig, MotionStats,
};
pub use multi_view::{MultiViewConfig, MultiViewRenderer};
pub use normal_estimation::{
    compute_normal_stats, estimate_curvature, estimate_normals_cross_product,
    estimate_normals_sobel, normal_consistency_loss, smooth_normals, NormalError, NormalMap,
    NormalStats,
};
pub use panoramic::{
    camera_from_angles, compute_panoramic_stats, direction_to_equirect, equirect_to_cube_face,
    equirect_to_cubemap, equirect_to_direction, fibonacci_sphere_views, perspective_to_equirect,
    stitch_to_equirect, CubeFace, PanoramicCamera, PanoramicError, PanoramicStats, PerspectiveView,
};
pub use picking::{
    compute_pick_stats, pick_all, pick_closest_approach, pick_nearest, pick_region,
    ray_point_distance, ray_sphere_intersect, GaussianPickData, PickCamera, PickConfig, PickHit,
    PickStats, PickingError, Ray, RegionPickResult,
};
pub use pool::{BufferPool, PoolStats, PooledBuffer};
pub use post_processing::{
    // apply_bloom renamed to avoid collision with bloom::apply_bloom
    apply_bloom as post_apply_bloom,
    apply_chromatic_aberration,
    apply_sharpening,
    apply_vignette,
    // BloomConfig renamed to avoid collision with bloom::BloomConfig
    BloomConfig as PostBloomConfig,
    ChromaticAberrationConfig,
    PostEffect,
    PostImage,
    PostProcessError,
    PostProcessingPipeline,
    SharpenConfig,
    VignetteConfig,
};
pub use profiler::{PassProfiler, PassRecord, PassStats, ProfileScope};
pub use rasterizer::{GaussianGradients, Rasterizer, RenderCamera, RenderOutput};
pub use render_graph::{
    build_standard_3dgs_graph, CompiledRenderGraph, PassDesc, PassType, RenderGraph,
    RenderGraphError, ResourceDesc, ResourceFormat, ResourceId, ResourceLifetime,
};
pub use render_metrics::{
    compare_renders, compute_ms_ssim, compute_psnr, compute_ssim, MetricThresholds,
    RenderQualityMetrics,
};
pub use scene_compositor::{
    apply_trimap_matting, blend_pixels, composite_layers, compute_composite_stats, dilate_mask,
    erode_mask, feather_mask, mask_and, mask_not, mask_or, BlendMode as CompositorBlendMode,
    CompositeStats, CompositorError, Layer, RgbaImage,
};
pub use sharpening::{
    adaptive_sharpen,
    apply_sharpening as apply_sharpen_filter,
    compute_sharpening_stats,
    gaussian_blur_rgb as sharpen_blur_rgb,
    gaussian_kernel_1d as sharpen_kernel_1d,
    high_boost_filter,
    high_pass_sharpen,
    laplacian_sharpen,
    laplacian_variance,
    local_contrast_enhance,
    richardson_lucy_sharpen,
    sobel_magnitude_map,
    unsharp_mask,
    // Renamed to avoid collision with post_processing::{SharpenConfig, apply_sharpening}
    // and bloom::{gaussian_kernel_1d, gaussian_blur_rgb}.
    SharpenConfig as SharpenFilterConfig,
    SharpenMethod,
    SharpenStats,
    SharpeningError,
};
pub use silhouette::{
    render_silhouette, render_silhouette_antialiased, render_silhouettes, silhouette_bce_loss,
    silhouette_iou, GaussianSilData, SilhouetteCamera, SilhouetteError, SilhouetteMask,
    SilhouetteMode, SilhouetteStats,
};
pub use spherical_harmonics::{
    color_to_sh_dc, rotate_sh_coeffs_z, sh_band_energy, sh_dc_to_color, sh_downsample, sh_eval,
    sh_eval_degree0, sh_eval_degree1, sh_eval_degree2, sh_eval_degree3, sh_num_coeffs,
    sh_project_monte_carlo, sh_to_color, sh_upsample, ShBasis, ShError, SH_C0, SH_C1, SH_C2, SH_C3,
};
pub use ssao::{
    apply_ao_to_image, blur_ssao, compute_ssao, generate_noise_texture, SsaoConfig, SsaoError,
    SsaoKernel, SsaoStats,
};
pub use stereo::{
    compose_anaglyph, compose_side_by_side, compose_top_bottom, compute_disparity_sad,
    compute_stereo_stats, disparity_to_depth, disparity_to_image, split_side_by_side, AnaglyphMode,
    EyeOffsetMode, StereoConfig, StereoError, StereoImage, StereoStats,
};
pub use temporal::{
    MotionVector, MotionVectorField, TaaConfig, TaaError, TemporalAccumulator, TemporalStats,
};
pub use temporal_aa::{
    accumulate_taa, clip_to_variance, compute_taa_stats, halton, jitter_offset, local_color_stats,
    sharpen_image, TaaAccumulator, TaaHistory, TaaStats,
};
pub use tile_stats::{
    compute_tile_stats, HeatmapMode, TileAnalysisReport, TileHeatmap, TileStats, TileStatsError,
    TileStatsGrid,
};
pub use tone_curve::{
    analyze_curve,
    apply_bezier_curve,
    apply_channel_curves,
    apply_lut_256,
    apply_tone_curve,
    blend_curves,
    compose_curves,
    compute_tangents,
    curve_contrast,
    histogram_tone_curve,
    invert_curve,
    monotone_cubic_interp,
    BezierCurve,
    ChannelCurves,
    CurveStats,
    // ToneCurve renamed to avoid collision with color_grading::ToneCurve
    ToneCurve as ParametricToneCurve,
    ToneCurveError,
};
pub use validation::*;
pub use workgroup::{
    WorkgroupBenchResult, WorkgroupBenchmarker, WorkgroupConfig, WorkgroupProfile, WorkgroupSize,
};
pub mod subsurface_scatter;
pub use subsurface_scatter::{
    sss_apply_profile, sss_apply_transmittance, sss_blur_2d, sss_blur_depth_aware,
    sss_blur_horizontal, sss_blur_vertical, sss_compute_stats, sss_format_config,
    sss_format_material, sss_format_stats, sss_gaussian_kernel_1d, sss_integrate_irradiance,
    sss_monte_carlo_integral, sss_radial_irradiance, sss_transmittance, DiffusionProfile,
    SssConfig, SssError, SssMaterial, SssResult, SssStats,
};
pub mod volumetric_render;
pub use volumetric_render::{
    vr_build_occupancy_grid, vr_can_skip, vr_compute_stats, vr_format_config, vr_format_stats,
    vr_gaussians_to_volume, vr_march_ray, vr_ray_aabb_intersect, vr_render_image,
    vr_render_image_u8, RayMarchResult, TransferFunction, TransferPoint, VolumeGrid,
    VolumetricCamera, VolumetricIntegration, VolumetricRay, VolumetricRenderConfig,
    VolumetricRenderError, VolumetricStats,
};

pub use bloom::{
    apply_bloom,
    apply_hdr_bloom,
    apply_hdr_bloom_and_tonemap,
    apply_hdr_bloom_rgba,
    bloom_accumulate_mip_chain,
    bloom_build_mip_chain,
    bloom_composite,
    bloom_convolve_horizontal,
    bloom_convolve_vertical,
    bloom_coverage,
    bloom_downsample,
    bloom_extract_bright,
    bloom_gaussian_blur,
    bloom_luminance_map,
    bloom_make_kernel,
    bloom_upsample,
    build_mip_pyramid,
    compute_hdr_bloom_stats,
    downsample_2x,
    extract_bright,
    format_bloom_config,
    gaussian_blur_rgb,
    gaussian_kernel_1d,
    soft_knee_weight,
    upsample_2x,
    BloomConfig,
    // New simplified bloom API
    BloomError,
    HdrBloomConfig,
    HdrBloomError,
    HdrBloomStats,
};
pub use chromatic_aberration::{
    aberration_map,
    apply_barrel_distortion,
    apply_barrel_distortion_rgba,
    apply_chrom_aberration,
    apply_chromatic_aberration as apply_full_chromatic_aberration,
    apply_chromatic_aberration_rgba,
    apply_lateral_ca,
    apply_lens_effects,
    apply_longitudinal_ca,
    apply_radial_chromatic_aberration,
    apply_vignette_effect,
    apply_vignetting_f32,
    bilinear_sample_channel as chrom_bilinear_sample,
    compute_chromatic_stats,
    compute_lens_effect_stats,
    compute_radial_distances,
    compute_vignette_mask,
    estimate_aberration_strength,
    format_chrom_config,
    fringe_visualization,
    nearest_sample_channel as chrom_nearest_sample,
    radial_factor,
    shift_channel,
    undistort_pixel,
    ChromAberrationConfig,
    // f32 RGB post-processing API
    ChromAberrationError,
    ChromInterpolation,
    ChromaticError,
    ChromaticStats,
    DistortionConfig,
    LateralChromaticConfig,
    // RGBA u8 lens-effects API (re-exported via chromatic_aberration with renamed aliases)
    LensEffectError,
    LensEffectStats,
    LensEffectsConfig,
    LensVignetteConfig,
    LongitudinalChromaticConfig,
    RgbaChromAberrationConfig,
};
pub use lens_distortion::{
    barrel_distort_image, compute_distortion_map, compute_distortion_stats, distort_image,
    distort_point, estimate_radial_coefficients, remap_image, undistort_image,
    undistort_point_iterative, CameraIntrinsics, DistortionModel, DistortionStats,
    LensDistortionError,
};
pub use vignetting::{
    animated_vignetting_strength, apply_vignetting, apply_vignetting_rgba,
    apply_vignetting_sequence, compute_vignetting_stats, generate_vignetting_mask, pixel_radius,
    VignettingConfig, VignettingError, VignettingModel, VignettingStats,
};

use thiserror::Error;

/// Reason for GPU device being lost.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeviceLostReason {
    /// Device was explicitly destroyed.
    Destroyed,
    /// Unknown reason.
    Unknown,
    /// Device was disconnected (e.g., GPU unplugged).
    DeviceDisconnected,
    /// Driver was updated while rendering.
    DriverUpdate,
    /// Out of GPU memory.
    OutOfMemory,
}

impl std::fmt::Display for DeviceLostReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Destroyed => write!(f, "device destroyed"),
            Self::Unknown => write!(f, "unknown reason"),
            Self::DeviceDisconnected => write!(f, "device disconnected"),
            Self::DriverUpdate => write!(f, "driver update"),
            Self::OutOfMemory => write!(f, "out of memory"),
        }
    }
}

/// Errors that can occur during rendering operations.
#[derive(Debug, Error)]
pub enum RenderError {
    // --- GPU initialization ---
    /// General GPU initialization error.
    #[error("GPU initialization error: {0}")]
    GpuInit(String),

    /// No suitable GPU adapter found.
    #[error("No suitable GPU adapter found")]
    AdapterNotFound,

    /// Failed to create GPU device.
    #[error("Failed to create GPU device: {0}")]
    DeviceCreationFailed(String),

    /// GPU device was lost during operation.
    #[error("GPU device lost ({reason}): {message}")]
    DeviceLost {
        /// Reason for device loss.
        reason: DeviceLostReason,
        /// Additional message.
        message: String,
    },

    // --- Shader compilation ---
    /// Shader compilation failed.
    #[error("Shader compilation failed for '{shader_name}': {error}")]
    ShaderCompilation {
        /// Name of the shader that failed to compile.
        shader_name: String,
        /// Compilation error message.
        error: String,
    },

    /// Shader validation failed.
    #[error("Shader validation failed for '{shader_name}': {error}")]
    ShaderValidation {
        /// Name of the shader that failed validation.
        shader_name: String,
        /// Validation error message.
        error: String,
    },

    // --- Buffer operations ---
    /// Buffer allocation failed.
    #[error("Buffer allocation failed for '{buffer_name}' (requested {requested_size} bytes)")]
    BufferAllocation {
        /// Name of the buffer.
        buffer_name: String,
        /// Requested size in bytes.
        requested_size: u64,
    },

    /// Buffer overflow.
    #[error("Buffer overflow for '{buffer_name}' (max: {max_size}, requested: {requested})")]
    BufferOverflow {
        /// Name of the buffer.
        buffer_name: String,
        /// Maximum size in bytes.
        max_size: u64,
        /// Requested size in bytes.
        requested: u64,
    },

    /// Buffer mapping failed.
    #[error("Buffer map failed for '{buffer_name}': {error}")]
    BufferMapFailed {
        /// Name of the buffer.
        buffer_name: String,
        /// Error message.
        error: String,
    },

    // --- Rasterization ---
    /// General rasterization error.
    #[error("Rasterization error: {0}")]
    Rasterize(String),

    /// Compute dispatch limit exceeded.
    #[error("Dispatch limit exceeded for {dimension}: requested {requested}, max {max}")]
    DispatchLimitExceeded {
        /// Which dimension (x, y, or z).
        dimension: String,
        /// Requested workgroup count.
        requested: u32,
        /// Maximum allowed.
        max: u32,
    },

    /// Too many Gaussians for allocated buffers.
    #[error("Too many Gaussians: {count} exceeds maximum {max}")]
    TooManyGaussians {
        /// Actual count.
        count: u32,
        /// Maximum allowed.
        max: u32,
    },

    /// Too many tile-Gaussian pairs.
    #[error("Too many tile pairs: {count} exceeds allocated {allocated}")]
    TooManyTilePairs {
        /// Actual count.
        count: u32,
        /// Allocated capacity.
        allocated: u32,
    },

    // --- Validation ---
    /// Invalid Gaussian data.
    #[error("Invalid Gaussian at index {index}: {reason}")]
    InvalidGaussian {
        /// Index of the invalid Gaussian.
        index: usize,
        /// Reason for invalidity.
        reason: String,
    },

    /// Invalid quaternion (not normalized or zero).
    #[error("Invalid quaternion at index {index}: norm = {norm}")]
    InvalidQuaternion {
        /// Index of the Gaussian with invalid quaternion.
        index: usize,
        /// Norm of the quaternion.
        norm: f32,
    },

    /// Invalid scale values.
    #[error("Invalid scale at index {index}: values = {values:?}")]
    InvalidScale {
        /// Index of the Gaussian with invalid scale.
        index: usize,
        /// Scale values.
        values: [f32; 3],
    },

    /// Mismatched buffer sizes.
    #[error("Mismatched buffer sizes: expected {expected}, got {actual}")]
    MismatchedBufferSizes {
        /// Expected size.
        expected: usize,
        /// Actual size.
        actual: usize,
    },

    // --- I/O ---
    /// PLY I/O error.
    #[error("PLY I/O error: {0}")]
    PlyIo(String),

    /// SafeTensors I/O error.
    #[error("SafeTensors I/O error: {0}")]
    SafetensorsIo(String),

    /// Image save failed.
    #[error("Image save failed: {0}")]
    ImageSaveFailed(String),

    /// Gradient readback failed.
    #[error("Gradient readback failed: {0}")]
    GradientReadbackFailed(String),

    /// Channel receive error.
    #[error("Channel receive error: {0}")]
    ChannelRecvError(String),

    /// Camera path error.
    #[error("Camera path error: {0}")]
    CameraPath(String),

    /// General validation error (NaN/Inf checks, count mismatches, etc.)
    #[error("Validation error: {0}")]
    ValidationError(String),
}

impl From<wgpu::RequestDeviceError> for RenderError {
    fn from(err: wgpu::RequestDeviceError) -> Self {
        RenderError::DeviceCreationFailed(err.to_string())
    }
}

impl From<std::sync::mpsc::RecvError> for RenderError {
    fn from(err: std::sync::mpsc::RecvError) -> Self {
        RenderError::ChannelRecvError(err.to_string())
    }
}

impl From<image::ImageError> for RenderError {
    fn from(err: image::ImageError) -> Self {
        RenderError::ImageSaveFailed(err.to_string())
    }
}

#[cfg(test)]
mod crate_root_api {
    //! Regression guards for the crate-root re-export surface.
    //!
    //! Every path below was, at some point, reachable only through its
    //! defining module — so a downstream caller writing `use oxigaf_render::*`
    //! could not name it, and in the `ambient_occlusion` case could not even
    //! construct the arguments for the functions that *were* re-exported.
    //! Naming them through `crate::` here turns a dropped `pub use` into a
    //! compile error instead of a silent API regression.

    #[test]
    fn antialiasing_entry_points_are_re_exported() {
        // `apply_image_aa_with_history` is the entry point callers must use
        // for real temporal AA; `apply_image_aa` has no history to accumulate.
        let _ = crate::try_apply_antialiasing;
        let _ = crate::apply_image_aa_with_history;
        let _ = crate::aa_sample_pixel_edge;
    }

    #[test]
    fn ambient_occlusion_argument_types_are_re_exported() {
        // `ao_compute` / `apply_ssao` take these by reference, so without the
        // type re-exports a crate-root-only caller cannot build their args.
        let _: Option<crate::AoProjParams> = None;
        let _: Option<crate::AoSamplingBuffers<'_>> = None;
        let _ = crate::ao_compute;
        let _ = crate::apply_ssao;
    }

    #[test]
    fn colorspace_channel_generic_api_is_re_exported() {
        // The RGBA/channel-generic pair added with the `UnsupportedChannelCount`
        // fix; the 3-channel-only originals stay re-exported alongside them.
        let _ = crate::apply_tone_mapping_image_channels;
        let _ = crate::convert_image_colorspace_channels;
        let _ = crate::apply_tone_mapping_image;
        let _ = crate::convert_image_colorspace;
    }

    #[test]
    fn deform_api_is_re_exported() {
        let _: Option<crate::MeshBuffers> = None;
        let _: Option<crate::DeformPipeline> = None;
        let _ = crate::deform_cpu;
    }

    #[test]
    fn cov2d_backward_api_is_re_exported() {
        let _: Option<crate::Cov2dBwdInput> = None;
        let _: Option<crate::Cov2dGrads> = None;
        let _ = crate::cov2d_backward;
    }

    #[test]
    fn light_probe_api_is_re_exported() {
        let sh = crate::IrradianceSH::new();
        let probe = crate::LightProbe::new([0.0, 0.0, 0.0], sh, 0.0);
        let blend = crate::LightProbeBlend::new(vec![probe], crate::ProbeBlendMode::Nearest)
            .expect("a single-probe blend is valid");
        let irradiance = blend
            .evaluate([0.0, 0.0, 0.0], [0.0, 0.0, 1.0])
            .expect("a unit normal is a valid direction");
        assert_eq!(irradiance, [0.0, 0.0, 0.0], "a zeroed probe emits nothing");

        let _: Option<crate::CubemapProbe> = None;
        let _: Option<crate::CubemapFace> = None;
        let _: Option<crate::LightProbeConfig> = None;
        let _: Option<crate::LightProbeStats> = None;
        let _: Option<crate::LightProbeError> = None;
        let _ = crate::lp_sh_basis;
        let _ = crate::lp_project_latitude_longitude;
        let _ = crate::lp_cubemap_to_sh;
        let _ = crate::lp_evaluate_diffuse_ibl;
        let _ = crate::lp_apply_ibl_to_gaussians;
        let _ = crate::lp_compute_stats;
    }
}