-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathshape_splat_pt.rs
2310 lines (2225 loc) · 92.4 KB
/
shape_splat_pt.rs
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
use std::cell::RefCell;
use std::collections::HashSet;
use std::env;
use std::f32::consts::PI;
use std::fs::File;
use std::io::BufWriter;
use std::sync::Arc;
use std::time::Instant;
use akari_render::luisa::runtime::KernelBuildOptions;
use akari_render::rand::Rng;
use akari_render::serde::de;
use akari_render::svm::surface::{BsdfEvalContext, Surface};
use akari_render::util::distribution::{AliasTableEntry, BindlessAliasTableVar};
// use akari_render::luisa::lang::debug::is_cpu_backend;
// use akari_render::shared::Shared;
use serde::{Deserialize, Serialize};
use super::pt::PathTracerBase;
use super::{Integrator, RenderSession};
use crate::geometry::Ray;
use crate::pt::{
DenoisingFeatures, ReconnectionShiftMapping, ReconnectionVertex, SurfaceHit, VertexType,
};
use crate::util::distribution::AliasTable;
use crate::util::{is_power_of_four, morton2d};
use crate::{color::*, sampler::*, *};
#[derive(Clone)]
pub struct ShapeSplattingPathTracer {
pub device: Device,
pub spp: u32,
pub max_depth: u32,
pub spp_per_pass: u32,
pub use_nee: bool,
pub rr_depth: u32,
pub indirect_only: bool,
pub pixel_offset: Int2,
pub force_diffuse: bool,
pub n_shift_pixels: u32,
config: Config,
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
#[serde(crate = "serde")]
pub enum BaseShape {
#[serde(rename = "square")]
Square,
#[serde(rename = "circle")]
Circle,
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
#[serde(crate = "serde")]
pub enum SpatialCurve {
#[serde(rename = "morton")]
Morton,
#[serde(rename = "hilbert")]
Hilbert,
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq)]
#[serde(crate = "serde")]
pub enum SplatMethod {
#[serde(rename = "lerp")]
Lerp,
#[serde(rename = "subspace")]
Subspace,
#[serde(rename = "voronoi")]
Voronoi,
#[serde(rename = "inv_dist")]
InverseDistance,
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq)]
#[serde(crate = "serde")]
pub enum MixingMethod {
#[serde(rename = "none")]
None,
#[serde(rename = "min")]
Min,
#[serde(rename = "inv_var")]
InverseVariance,
#[serde(rename = "inv_var2")]
InverseVarianceNoPt,
#[serde(rename = "uniform")]
Uniform,
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
#[serde(default, crate = "serde")]
pub struct Config {
pub spp: u32,
pub max_depth: u32,
pub spp_per_pass: u32,
pub use_nee: bool,
pub rr_depth: u32,
pub indirect_only: bool,
pub force_diffuse: bool,
pub pixel_offset: [i32; 2],
pub shape_width: u32,
pub curve: SpatialCurve,
pub shape: BaseShape,
pub mix: MixingMethod,
pub max_sampled_length: Option<u32>,
pub stride: f32,
pub reconnect: bool,
pub min_dist: f32,
pub min_roughness: f32,
pub pmf_power: f32,
pub denoiser_kernel: bool,
///
pub async_compile: bool,
pub sample_all: bool,
pub randomize: bool,
}
impl Default for Config {
fn default() -> Self {
Self {
spp: 256,
max_depth: 7,
rr_depth: 5,
spp_per_pass: 64,
use_nee: true,
indirect_only: false,
force_diffuse: false,
pixel_offset: [0, 0],
shape_width: 6,
max_sampled_length: None,
curve: SpatialCurve::Hilbert,
shape: BaseShape::Square,
mix: MixingMethod::InverseVariance,
stride: 1.0,
reconnect: false,
min_dist: 0.0,
min_roughness: 0.0,
pmf_power: -2.0,
denoiser_kernel: true,
sample_all: false,
randomize: true,
async_compile: false,
}
}
}
impl ShapeSplattingPathTracer {
pub fn new(device: Device, config: Config) -> Self {
assert!(config.pmf_power <= 0.0);
// center square numbers
let n_shift_pixels = match config.shape {
BaseShape::Square => config.shape_width.pow(2) + (config.shape_width - 1).pow(2) - 1,
_ => todo!(),
};
Self {
device,
spp: config.spp,
max_depth: config.max_depth,
spp_per_pass: config.spp_per_pass,
use_nee: config.use_nee,
rr_depth: config.rr_depth,
indirect_only: config.indirect_only,
force_diffuse: config.force_diffuse,
pixel_offset: Int2::new(config.pixel_offset[0], config.pixel_offset[1]),
n_shift_pixels,
config,
}
}
}
#[derive(Copy, Clone)]
struct RenderState<'a> {
t_lo: i32,
t_hi: i32,
base_shape_center: u32,
pmf_ats: &'a BindlessArray,
tele_film: &'a Film,
pt_film: &'a Film,
pt_sqr_film: &'a Film,
mc_film: &'a Film,
mc_replay_film: &'a Film,
mc_sqr_film: &'a Film,
mc_replay_sqr_film: &'a Film,
debug_film: &'a Film,
albedo_buf: &'a Tex2d<Float4>,
normal_buf: &'a Tex2d<Float4>,
first_hit: &'a Buffer<pt::SurfaceHit>,
reconnect_vertex_buf: &'a Buffer<ReconnectionVertex>,
path_states: &'a Buffer<PathState>,
path_counter_buf: &'a Buffer<u32>,
path_sm_replay: &'a ColorBuffer,
path_sm_reconnect: &'a ColorBuffer,
path_jacobians: &'a Buffer<f32>,
sampled_indices: &'a Buffer<i8>,
shifted_path_states: &'a Buffer<ShiftedPathState>,
sort_tmp: &'a Buffer<i8>,
rotation: &'a Buffer<f32>,
shapes: &'a Buffer<Shape>,
shape_indices: &'a Buffer<i8>,
curve: &'a Buffer<Int2>,
rng_buf: &'a Buffer<Pcg32>,
avg_per_pixel: &'a Buffer<f32>,
}
#[derive(Copy, Clone, Value)]
#[luisa(crate = "luisa")]
#[repr(C)]
pub struct Shape {
// offset: u32,
pub center: u8,
pub n_pixels: u8,
}
#[derive(Copy, Clone, Value)]
#[luisa(crate = "luisa")]
#[repr(C, align(16))]
struct PathState {
k: u32,
pmf_k: f32,
offset: u32,
center: u32,
}
#[derive(Copy, Clone, Value)]
#[luisa(crate = "luisa")]
#[repr(C)]
struct ShiftedPathState {
ps_idx: u32,
sampled_index: i32,
color_index: u32,
}
impl ShapeSplattingPathTracer {
#[tracked(crate = "luisa")]
fn radiance(
&self,
scene: &Arc<Scene>,
color_pipeline: ColorPipeline,
ray: Expr<Ray>,
swl: Var<SampledWavelengths>,
sampler: &dyn Sampler,
sm: Option<&ReconnectionShiftMapping>,
) -> (Color, Color, DenoisingFeatures, Expr<u32>) {
let mut pt = PathTracerBase::new(
scene,
color_pipeline,
self.max_depth.expr(),
self.rr_depth.expr(),
self.use_nee,
self.indirect_only,
swl,
);
pt.need_shift_mapping = self.config.reconnect;
pt.force_diffuse = self.force_diffuse;
pt.denoising = Some(DenoisingFeatures {
first_hit_albedo: ColorVar::zero(color_pipeline.color_repr),
first_hit_normal: Float3::var_zeroed(),
first_hit_roughness: 0.0f32.var(),
first_hit: {
let v = SurfaceHit::var_zeroed();
*v.inst_id = u32::MAX;
v
},
});
pt.run_pt_hybrid_shift_mapping(ray, sampler, sm, None);
let replay = if self.config.reconnect {
pt.base_replay_throughput.load()
} else {
pt.radiance.load()
};
(
replay,
pt.radiance.load() - replay,
pt.denoising.unwrap(),
**pt.depth,
)
}
#[tracked(crate = "luisa")]
fn kernel_compute_auxillary(
&self,
scene: Arc<Scene>,
color_pipeline: ColorPipeline,
_sampler_creator: &dyn SamplerCreator,
state: RenderState,
spp: Expr<u32>,
) {
let resolution = scene.camera.resolution();
set_block_size([256, 1, 1]);
let px_idx = dispatch_id().x;
let p = {
let p = Uint2::expr(px_idx % resolution.x, px_idx / resolution.x);
p
};
let rng = IndependentSampler::from_pcg32(state.rng_buf.read(px_idx).var());
let acc_normal = Float3::var_zeroed();
let acc_albedo = ColorVar::zero(color_pipeline.color_repr);
for _ in 0u32.expr()..spp {
let swl = sample_wavelengths(color_pipeline.color_repr, &rng);
let (ray, _) = scene.camera.generate_ray(
&scene,
state.mc_film.filter(),
p,
&rng,
color_pipeline.color_repr,
swl,
);
let si = scene.intersect(ray);
if si.valid {
let n = si.ng;
let albedo =
scene
.svm
.dispatch_surface(si.surface, color_pipeline, si, swl, |closure| {
closure.albedo(
-ray.d,
swl,
&BsdfEvalContext {
color_repr: color_pipeline.color_repr,
ad_mode: ADMode::None,
},
)
});
*acc_normal += n;
acc_albedo.store(acc_albedo.load() + albedo);
}
}
state.normal_buf.write(
p,
(acc_normal / spp.as_f32()).normalize().extend(0.0) * 0.5 + 0.5,
);
state
.albedo_buf
.write(p, (acc_albedo.load() / spp.as_f32()).as_rgb().extend(0.0));
state.rng_buf.write(px_idx, rng.state);
}
#[tracked(crate = "luisa")]
fn default_shape(&self, state: RenderState) -> Expr<Shape> {
let n = self.n_shift_pixels.expr() + 1;
Shape::from_comps_expr(ShapeComps {
center: state.base_shape_center.expr().as_u8(),
n_pixels: n.as_u8(),
})
}
#[tracked(crate = "luisa")]
fn sample_indices(
&self,
state: RenderState,
rng: &IndependentSampler,
px_idx: Expr<u32>,
shape: Expr<Shape>,
tmp_buf_offset: Expr<u32>,
sort_buf_offset: Expr<u32>,
shifted_buf_offset: Expr<u32>,
k: Expr<u32>,
n: Expr<u32>,
) -> Expr<u32> {
let path_states = state.path_states;
/*
* Sample indices
*/
let center = u32::MAX.var();
let sampled_indices = state.sampled_indices;
let sort_tmp = state.sort_tmp;
if k > 0 {
let use_reservoir = true;
if use_reservoir {
// sample k integrers from [0, n)
// initialize the resevoir
for i in 0u32.expr()..k {
sampled_indices.write(tmp_buf_offset + i, i.as_i8());
}
let w = (rng.next_1d().ln() / k.as_f32()).exp().var();
// for i in k..n {
// let j = rng.state.gen_u32() % (i + 1);
// if j < k {
// sampled_indices.write(tmp_buf_offset + j, i.as_i32());
// }
// }
let i = k.var();
while i < n {
*i += (rng.next_1d().ln() / (1.0 - w).ln()).floor().as_u32() + 1;
if i < n {
let j = rng.state.gen_u32() % k;
sampled_indices.write(tmp_buf_offset + j, i.as_i8());
*w *= (rng.next_1d().ln() / k.as_f32()).exp();
}
}
} else {
// shuffle n times
for i in 0u32.expr()..n {
sampled_indices.write(tmp_buf_offset + i, i.as_i8());
}
for _ in 0u32.expr()..n {
let p = rng.state.gen_u32() % n;
let q = 1 + rng.state.gen_u32() % (n - 1);
let q = (p + q) % n;
lc_assert!(p.ne(q));
let tmp = sampled_indices.read(tmp_buf_offset + p);
sampled_indices
.write(tmp_buf_offset + p, sampled_indices.read(tmp_buf_offset + q));
sampled_indices.write(tmp_buf_offset + q, tmp);
}
}
// sort the indices using counting sort
for i in 0u32.expr()..n {
sort_tmp.write(sort_buf_offset + i, 0);
}
for i in 0u32.expr()..k {
let idx = sampled_indices.read(tmp_buf_offset + i);
sort_tmp.write(sort_buf_offset + idx.as_u32(), 1);
}
let cnt = 0u32.var();
for i in 0u32.expr()..n {
let contained = sort_tmp.read(sort_buf_offset + i) != 0;
let j = i.as_i32().var();
if contained {
if j.as_u32() < shape.center.as_u32() {
*j = j - shape.center.as_i32();
} else {
*j = j - shape.center.as_i32() + 1;
}
if center == u32::MAX {
if j > 0 {
*center = cnt;
}
}
if center != u32::MAX {
if cnt < center {
lc_assert!(j.lt(0));
} else {
lc_assert!(j.gt(0));
}
}
// lc_assert!(j.ne(0));
let idx = ((center == u32::MAX) | (cnt < center)).select(**cnt, cnt + 1);
// lc_assert!(j.ge(t_lo));
// lc_assert!(j.lt(t_hi));
sampled_indices.write(tmp_buf_offset + idx, j.as_i8());
let shifted = ShiftedPathState::var_zeroed();
*shifted.ps_idx = px_idx;
*shifted.sampled_index = j;
*shifted.color_index = tmp_buf_offset + idx;
state
.shifted_path_states
.write(shifted_buf_offset + cnt, shifted);
*cnt += 1;
}
}
// lc_assert!(cnt.eq(k));
if center == u32::MAX {
*center = k;
}
} else {
*center = 0;
}
{
let ps = path_states.read(px_idx).var();
*ps.center = center;
*ps.offset = tmp_buf_offset;
path_states.write(px_idx, ps);
}
if k > 0 {
sampled_indices.write(tmp_buf_offset + center, 0);
}
**center
}
#[tracked(crate = "luisa")]
fn is_shape_full(&self, s: Expr<Shape>) -> Expr<bool> {
s.n_pixels.as_u32() == (self.n_shift_pixels + 1u32)
}
#[tracked(crate = "luisa")]
fn kernel_compute_denoiser_kernel(&self, scene: Arc<Scene>, state: RenderState) {
let resolution = scene.camera.resolution();
set_block_size([64, 1, 1]);
let px_idx = dispatch_id().x;
let p = {
let p = Uint2::expr(px_idx % resolution.x, px_idx / resolution.x);
p
};
let p_from_t = self.get_p_from_t_raw(p, resolution.expr(), state, false);
let cnt = 0u32.var();
let t_lo = state.t_lo.expr();
let t_hi = state.t_hi.expr();
let center_normal = state.normal_buf.read(p).xyz() * 2.0 - 1.0;
let center_albedo = state.albedo_buf.read(p).xyz();
let offset = px_idx;
let shape = state.shapes.read(offset).var();
for t in t_lo..t_hi {
let write = false.var();
if t == 0 {
*shape.center = cnt.as_u8();
*write = true;
} else {
let p = p_from_t(t);
if (p < Int2::expr(0, 0)).any()
| (p >= scene.camera.resolution().expr().cast_i32()).any()
{
continue;
}
let p = p.cast_u32();
let normal = state.normal_buf.read(p).xyz() * 2.0 - 1.0;
let albedo = state.albedo_buf.read(p).xyz();
let group_normal = normal.dot(center_normal) >= 0.707;
let group_albedo = (center_albedo - albedo).abs().reduce_max() < 0.1;
if (!self.config.denoiser_kernel) | (group_normal & group_albedo) {
*write = true;
}
}
if write {
state
.shape_indices
.write(offset * (1 + self.n_shift_pixels) + cnt, t.cast_i8());
*cnt += 1;
}
}
*shape.n_pixels = cnt.as_u8();
state.shapes.write(offset, shape);
}
#[tracked(crate = "luisa")]
fn trace(
&self,
scene: &Scene,
state: &RenderState,
color_pipeline: ColorPipeline,
sampler: &dyn Sampler,
pixel: Expr<Uint2>,
is_primary: bool,
shift_mapping: &ReconnectionShiftMapping,
) -> (Expr<SampledWavelengths>, Color) {
let swl_v = SampledWavelengths::var_zeroed();
let indirect = ColorVar::zero(color_pipeline.color_repr);
outline(|| {
sampler.forget();
let swl = sample_wavelengths(color_pipeline.color_repr, sampler).var();
let (ray, _ray_w) = scene.camera.generate_ray(
&scene,
state.pt_film.filter(),
pixel,
sampler,
color_pipeline.color_repr,
**swl,
);
let swl = swl.var();
let mut pt = PathTracerBase::new(
scene,
color_pipeline,
self.config.max_depth.expr(),
self.config.rr_depth.expr(),
self.config.use_nee,
true,
swl,
);
pt.need_shift_mapping = true;
*shift_mapping.is_base_path = is_primary;
pt.run_pt_hybrid_shift_mapping(
ray,
sampler,
if self.config.reconnect {
Some(shift_mapping)
} else {
None
},
None,
);
let direct = pt.base_replay_throughput.load();
indirect.store(pt.radiance.load() - direct);
*swl_v = swl;
});
// let indirect = Color::one(state.color_pipeline.color_repr);//# - direct;
(**swl_v, indirect.load())
}
/**
* Sample a primary path, store the reconnection vertex
* Store the albedo
* Sample telescoping path indices
*/
#[tracked(crate = "luisa")]
fn kernel_sample_primary(
&self,
scene: Arc<Scene>,
color_pipeline: ColorPipeline,
sampler_creator: &dyn SamplerCreator,
state: RenderState,
) {
let resolution = scene.camera.resolution();
set_block_size([256, 1, 1]);
let px_idx = dispatch_id().x;
let p = {
let p = Uint2::expr(px_idx % resolution.x, px_idx / resolution.x);
p
};
let rng = IndependentSampler::from_pcg32(state.rng_buf.read(px_idx).var());
// let pmf_at = state.pmf_at;
let path_states = state.path_states;
/*
* Sample shape config
*/
let shape = {
if self.config.denoiser_kernel {
state.shapes.read(px_idx)
} else {
self.default_shape(state)
}
};
let n = shape.n_pixels.as_u32() - 1;
let k = if n > 0 {
let entries = state.pmf_ats.buffer::<AliasTableEntry>(n * 2);
let pmf = state.pmf_ats.buffer::<f32>(n * 2 + 1);
let pmf_at = BindlessAliasTableVar(entries, pmf);
let (k, pmf_k, _) = pmf_at.sample_and_remap(rng.next_1d());
lc_assert!(k.lt(n));
let k = k + 1;
let ps = path_states.read(px_idx).var();
*ps.k = k;
*ps.pmf_k = pmf_k;
path_states.write(px_idx, ps);
k
} else {
let ps = path_states.read(px_idx).var();
*ps.pmf_k = 1.0f32.expr();
*ps.k = 0;
path_states.write(px_idx, ps);
0u32.expr()
};
// Perform atomic increment on path counter
let tmp_buf_offset = state.path_counter_buf.atomic_fetch_add(0, 1 + k);
let shifted_buf_offset = state.path_counter_buf.atomic_fetch_add(1, k);
let sort_buf_offset = px_idx * (1 + self.n_shift_pixels);
let center = self.sample_indices(
state,
&rng,
px_idx,
shape,
tmp_buf_offset,
sort_buf_offset,
shifted_buf_offset,
k,
n,
);
state
.reconnect_vertex_buf
.write(px_idx, ReconnectionVertex::var_zeroed());
// trace primary path
let shift_mapping = if self.config.reconnect {
Some(ReconnectionShiftMapping {
min_dist: self.config.min_dist.expr(),
min_roughness: self.config.min_roughness.expr(),
is_base_path: true.var(),
read_vertex: Box::new(|| state.reconnect_vertex_buf.read(px_idx)),
write_vertex: Box::new(|v| state.reconnect_vertex_buf.write(px_idx, v)),
jacobian: 0.0f32.var(),
success: false.var(),
})
} else {
None
};
let sampler = sampler_creator.create(p);
sampler.forget();
sampler.start();
let (primary_l, primary_reconnect, swl, _primay_ray_w, _, _, first_hit) = self.trace_path(
scene.clone(),
&sampler,
color_pipeline,
state,
sampler_creator,
p,
true.expr(),
0i32.expr(),
shift_mapping.as_ref(),
);
{
state.first_hit.write(px_idx, first_hit);
let avg_per_pixel = state.avg_per_pixel.read(shape.n_pixels.as_u32() - 1);
state
.path_sm_replay
.write(tmp_buf_offset + center, primary_l, swl);
state
.path_jacobians
.write(tmp_buf_offset + center, 1.0f32.expr());
state
.path_sm_reconnect
.write(tmp_buf_offset + center, primary_reconnect, swl);
state.mc_film.add_splat(
p.cast_f32(),
&(primary_l + primary_reconnect),
swl,
1.0 / avg_per_pixel,
);
{
let l = primary_l + primary_reconnect;
state
.pt_film
.add_sample(p.cast_f32(), &l, swl, 1.0f32.expr());
state
.pt_sqr_film
.add_sample(p.cast_f32(), &(l * l), swl, 1.0f32.expr());
}
state.debug_film.add_sample(
p.cast_f32(),
&(Color::one(color_pipeline.color_repr)
* (shape.n_pixels.as_f32() / (1.0f32 + self.n_shift_pixels as f32))),
swl,
1.0f32.expr(),
);
}
state.rng_buf.write(px_idx, rng.state);
}
#[tracked(crate = "luisa")]
fn kernel_sample_shifted(
&self,
scene: Arc<Scene>,
color_pipeline: ColorPipeline,
sampler_creator: &dyn SamplerCreator,
state: RenderState,
) {
let resolution = scene.camera.resolution();
set_block_size([256, 1, 1]);
let tid = dispatch_id().x;
if tid >= state.path_counter_buf.read(1) {
return;
}
let shifted = state.shifted_path_states.read(tid);
let px_idx = shifted.ps_idx;
// device_log!("{} {}", px_idx, tid);
let p = {
let p = Uint2::expr(px_idx % resolution.x, px_idx / resolution.x);
p
};
let sm = if self.config.reconnect {
Some(ReconnectionShiftMapping {
min_dist: self.config.min_dist.expr(),
min_roughness: self.config.min_roughness.expr(),
is_base_path: false.var(),
read_vertex: Box::new(|| state.reconnect_vertex_buf.read(px_idx)),
write_vertex: Box::new(|_| {}),
jacobian: 0.0f32.var(),
success: false.var(),
})
} else {
None
};
let sampler = sampler_creator.create(p);
sampler.start();
sampler.forget();
let t = shifted.sampled_index;
let p_from_t: Box<dyn Fn(Expr<i32>) -> Expr<Vector<i32, 2>>> =
self.get_p_from_t(p, resolution.expr(), state, self.config.denoiser_kernel);
let proposal_p = p_from_t(t).cast_f32();
let proposal_p_idx = proposal_p.x.as_u32() + proposal_p.y.as_u32() * resolution.x;
let (l, reconnect, swl, _ray_w, jacobian, _, _) = self.trace_path(
scene.clone(),
&sampler,
color_pipeline,
state,
sampler_creator,
p,
false.expr(),
t,
sm.as_ref(),
);
// let jacobian = 1.0f32.expr();//(jacobian > 0.0).select(1.0f32.expr(), 0.0f32.expr());
let ps = state.path_states.read(px_idx);
let buf_offset = ps.offset;
// let shape = state.shapes.read(px_idx);
let (primary_l, primary_swl) = state.path_sm_replay.read(buf_offset + ps.center);
let (primary_reconnect, _) = state.path_sm_reconnect.read(buf_offset + ps.center);
let cur_p = p;
let shape = if self.config.denoiser_kernel {
state.shapes.read(px_idx)
} else {
self.default_shape(state)
};
let avg_per_pixel = state.avg_per_pixel.read(shape.n_pixels.as_u32() - 1);
let proposal_shape = if self.config.denoiser_kernel {
state.shapes.read(proposal_p_idx)
} else {
self.default_shape(state)
};
{
let scale = 1.0 / avg_per_pixel;
let acc_proposal_replay = ColorVar::zero(primary_l.repr());
let acc_proposal_replay_w = 0.0f32.var();
let acc_proposal_reconnect = ColorVar::zero(primary_l.repr());
let acc_proposal_reconnect_w = 0.0f32.var();
let acc_primary_replay = ColorVar::zero(primary_l.repr());
let acc_primary_replay_w = 0.0f32.var();
let acc_primary_reconnect = ColorVar::zero(primary_l.repr());
let acc_primary_reconnect_w = 0.0f32.var();
let acc_sqr_proposal_replay = ColorVar::zero(primary_l.repr());
let acc_sqr_proposal_replay_w = 0.0f32.var();
let acc_sqr_proposal_reconnect = ColorVar::zero(primary_l.repr());
let acc_sqr_proposal_reconnect_w = 0.0f32.var();
let acc_sqr_primary_replay = ColorVar::zero(primary_l.repr());
let acc_sqr_primary_replay_w = 0.0f32.var();
let acc_sqr_primary_reconnect = ColorVar::zero(primary_l.repr());
let acc_sqr_primary_reconnect_w = 0.0f32.var();
self.splat_mcmc_contribution(
shape,
proposal_shape,
primary_l,
primary_reconnect,
l,
reconnect,
jacobian,
|v, w| {
acc_primary_replay.store(acc_primary_replay.load() + v * w);
*acc_primary_replay_w += w;
acc_sqr_primary_replay.store(acc_sqr_primary_replay.load() + v * v * w);
*acc_sqr_primary_replay_w += w;
},
|v, w| {
acc_primary_reconnect.store(acc_primary_reconnect.load() + v * w);
*acc_primary_reconnect_w += w;
acc_sqr_primary_reconnect.store(acc_sqr_primary_reconnect.load() + v * v * w);
*acc_sqr_primary_reconnect_w += w;
},
|v, w| {
acc_proposal_replay.store(acc_proposal_replay.load() + v * w);
*acc_proposal_replay_w += w;
acc_sqr_proposal_replay.store(acc_sqr_proposal_replay.load() + v * v * w);
*acc_sqr_proposal_replay_w += w;
},
|v, w| {
acc_proposal_reconnect.store(acc_proposal_reconnect.load() + v * w);
*acc_proposal_reconnect_w += w;
acc_sqr_proposal_reconnect.store(acc_sqr_proposal_reconnect.load() + v * v * w);
*acc_sqr_proposal_reconnect_w += w;
},
);
state.mc_film.add_splat(
proposal_p,
&(acc_proposal_replay.load() + acc_proposal_reconnect.load()),
swl,
scale,
);
state.mc_film.add_splat(
cur_p.cast_f32(),
&(acc_primary_replay.load() + acc_primary_reconnect.load()),
primary_swl,
scale,
);
}
let shifted = state.shifted_path_states.read(tid);
state.path_sm_replay.write(shifted.color_index, l, swl);
state
.path_sm_reconnect
.write(shifted.color_index, reconnect, swl);
state.path_jacobians.write(shifted.color_index, jacobian);
}
#[tracked(crate = "luisa")]
fn kernel_telelscoping_sum(
&self,
scene: Arc<Scene>,
color_pipeline: ColorPipeline,
_sampler_creator: &dyn SamplerCreator,
state: RenderState,
) {
let resolution = scene.camera.resolution();
set_block_size([256, 1, 1]);
let px_idx = dispatch_id().x;
let p = {
let p = Uint2::expr(px_idx % resolution.x, px_idx / resolution.x);
p
};
let ps = state.path_states.read(px_idx);
let k = ps.k;
let pmf_k = ps.pmf_k;
let tmp_buf_offset = ps.offset;
let center = ps.center;
let shape = if self.config.denoiser_kernel {
state.shapes.read(px_idx)
} else {
self.default_shape(state)
};
let p_from_t = self.get_p_from_t(p, resolution.expr(), state, self.config.denoiser_kernel);
let (primary_l, swl) = state.path_sm_replay.read(tmp_buf_offset + ps.center);
let p_from_t = &p_from_t;
let (primary_reconnect, _) = state.path_sm_reconnect.read(tmp_buf_offset + ps.center);
let n = shape.n_pixels - 1;
let t_lo = -(shape.center.cast_i32());
let t_hi = (1 + n - shape.center).cast_i32();
// device_log!(
// "{} {} {}",
// shape,
// primary_l.as_rgb(),
// primary_reconnect.as_rgb()
// );
if !self.config.sample_all {
if shape.n_pixels == 1 {
state.tele_film.add_splat(
p.cast_f32(),
&(primary_l + primary_reconnect),
swl,
1.0f32.expr(),
);
} else {
self.telescoping_lerp(
state,
scene.camera.resolution().expr(),
state.shapes.var(),
state.path_states.var(),
p.cast_f32(),
primary_l,
primary_reconnect,
swl,
&state.path_sm_replay,
&state.path_sm_reconnect,
&state.path_jacobians,
&state.sampled_indices,
tmp_buf_offset,
tmp_buf_offset + k + 1,
tmp_buf_offset + center,
p_from_t,
t_lo,
t_hi,
1.0 / shape.n_pixels.as_f32(),
1.0f32 / pmf_k,
k.as_f32(),
|p, l, swl, scale| {
state.tele_film.add_splat(p, &l, swl, scale);
},
);
}
}
}
#[tracked(crate = "luisa")]
fn get_p_from_t_raw<'a>(
&'a self,
p: Expr<Uint2>,
resolution: Expr<Uint2>,
state: RenderState<'a>,
use_shape_indices: bool,
) -> Box<dyn Fn(Expr<i32>) -> Expr<Int2> + 'a> {
let n = self.n_shift_pixels.expr();
let p_idx = p.x + p.y * resolution.x;
let shape = if use_shape_indices {
Some(state.shapes.read(p_idx))
} else {
None
};
let offset = (p_idx) * (1 + n);
let map_i = move |i: Expr<i32>| -> Expr<i32> {
if use_shape_indices {
let shape = shape.unwrap();
if self.is_shape_full(shape) {
i
} else {
let center = shape.center;
let t = i + center.as_i32();
let shape_indices = state.shape_indices;
shape_indices.read(offset + t.as_u32()).cast_i32()
}
} else {
i
}
};
let curve: BufferVar<Vector<i32, 2>> = state.curve.var();
let p_from_t = move |i: Expr<i32>| -> Expr<Int2> {
let i = map_i(i);
let i = i + state.base_shape_center as i32;
// lc_assert!(i.ge(0));
// if i.as_u32() >= curve.len_expr_u32() {
// device_log!("i = {}, curve.len = {}", i, curve.len_expr_u32());
// }
let morton_p = curve.read(i.as_u32());
let ip = p.cast_i32() + morton_p;
ip
};
Box::new(p_from_t) as Box<dyn Fn(Expr<i32>) -> Expr<Int2>>
}
#[tracked(crate = "luisa")]
fn get_p_from_t<'a>(
&'a self,
p: Expr<Uint2>,
resolution: Expr<Uint2>,
state: RenderState<'a>,
use_shape_indices: bool,