-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrasterizer.rs
2208 lines (1929 loc) · 91.5 KB
/
rasterizer.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 na::{Vector3, Vector4, Point3, Point4, Matrix3, Matrix4, Isometry3};
use na::{Norm, Diagonal, Inverse, Transpose};
use na;
use std::path;
use std::fs::File;
use std::error::Error;
use std::io::prelude::*;
use std::f32;
use std::i64;
use std::f32::consts;
use stb_image::image;
use time::{PreciseTime};
use std::cmp;
use ansi_term;
use scoped_threadpool;
use std::cell::UnsafeCell;
use num_cpus;
//
// ------------------------------------------
// General Utilities & Linear Algebra Helpers
// ------------------------------------------
//
type V3F = Vector3<f32>;
type P3F = Point3<f32>;
fn deg_to_rad(deg: f32) -> f32 {
// std::f32::to_radians() is still unstable
deg * 0.0174532925
}
fn max3<T: PartialOrd>(a: T, b: T, c: T) -> T {
if a > b {
if a > c { a } else { c }
} else {
if b > c { b } else { c }
}
}
fn min3<T: PartialOrd>(a: T, b: T, c: T) -> T {
if a < b {
if a < c { a } else { c }
} else {
if b < c { b } else { c }
}
}
fn face_normal(v0: &P3F, v1: &P3F, v2: &P3F) -> V3F {
na::normalize(&na::cross(&(*v1 - *v0), &(*v2 - *v0)))
}
fn fast_normalize(n: &V3F) -> V3F {
// nalgbera doesn't use a reciprocal
let l = 1.0 / (n.x * n.x + n.y * n.y + n.z * n.z).sqrt();
Vector3::new(n.x * l, n.y * l, n.z * l)
}
fn reflect(i: &V3F, n: &V3F) -> V3F {
// GLSL style reflection vector function
*i - (*n * na::dot(n, i) * 2.0)
}
//
// -------------------------
// Mesh Loading & Processing
// -------------------------
//
struct Vertex {
p: P3F,
n: V3F,
col: V3F
}
impl Vertex {
fn new(px: f32, py: f32, pz: f32,
nx: f32, ny: f32, nz: f32,
r: f32, g: f32, b: f32) -> Vertex {
Vertex {
p: Point3 ::new(px, py, pz),
n: Vector3::new(nx, ny, nz),
col: Vector3::new(r , g , b)
}
}
}
// Indexed triangle representation
struct Triangle {
v0: u32,
v1: u32,
v2: u32
}
impl Triangle {
fn new(v0: u32, v1: u32, v2: u32) -> Triangle {
Triangle { v0: v0, v1: v1, v2: v2 }
}
}
struct Mesh {
tri: Vec<Triangle>,
vtx: Vec<Vertex>,
aabb_min: V3F,
aabb_max: V3F
}
impl Mesh {
fn new(tri: Vec<Triangle>, vtx: Vec<Vertex>) -> Mesh {
// Compute AABB
let mut mesh = Mesh { tri: tri, vtx: vtx, aabb_min: na::zero(), aabb_max: na::zero() };
mesh.update_aabb();
mesh
}
fn update_aabb(&mut self) {
self.aabb_min = Vector3::new(f32::MAX, f32::MAX, f32::MAX);
self.aabb_max = Vector3::new(f32::MIN, f32::MIN, f32::MIN);
for v in &self.vtx {
self.aabb_min.x = if self.aabb_min.x < v.p.x { self.aabb_min.x } else { v.p.x };
self.aabb_min.y = if self.aabb_min.y < v.p.y { self.aabb_min.y } else { v.p.y };
self.aabb_min.z = if self.aabb_min.z < v.p.z { self.aabb_min.z } else { v.p.z };
self.aabb_max.x = if self.aabb_max.x > v.p.x { self.aabb_max.x } else { v.p.x };
self.aabb_max.y = if self.aabb_max.y > v.p.y { self.aabb_max.y } else { v.p.y };
self.aabb_max.z = if self.aabb_max.z > v.p.z { self.aabb_max.z } else { v.p.z };
}
}
fn normalize_dimensions(&self) -> Matrix4<f32> {
// Build a matrix to transform the mesh to a unit cube with the origin as its center
// Translate to center
let center = (self.aabb_min + self.aabb_max) / 2.0;
let transf = Isometry3::new(-center, na::zero());
// Scale to unit cube
let extends = self.aabb_max - self.aabb_min;
let extends_max = max3(extends.x, extends.y, extends.z);
let extends_scale = 1.0 / extends_max;
let scale: Matrix4<f32> =
Diagonal::from_diagonal(&Vector4::new(extends_scale, extends_scale, extends_scale, 1.0));
scale * na::to_homogeneous(&transf)
}
}
// We have a few different combinations of vertex attributes in the mesh file format
#[derive(PartialEq, Debug)]
enum MeshFileType { XyzNxNyNz, XyzNxNyNzRGB, XyzRGB }
fn load_mesh(file_name: &str, mesh_file_type: MeshFileType) -> Mesh {
// Load a text format mesh from disk
let file_name = &file_name.to_string();
let path = path::Path::new(file_name);
let display = path.display();
// Open mesh file
let mut file = match File::open(&path) {
Err(why) => panic!("load_mesh(): Couldn't open {}: {}",
display,
Error::description(&why)),
Ok(file) => file
};
// Read entire mesh file into memory
let mut data_str = String::new();
match file.read_to_string(&mut data_str) {
Err(why) => panic!("load_mesh(): Couldn't read {}: {}",
display,
Error::description(&why)),
Ok(_) => ()
};
// Parse mesh format line-by-line
let mut lines = data_str.lines();
// Comment header / vertex count
let vtx_cnt;
loop {
match lines.next() {
Some("") => (), // Skip empty lines
Some(ln) => {
let words: Vec<&str> = ln.split(" ").collect();
if words[0] == "#" { continue } // Skip comments
// First non-empty, non-comment line should contain the vertex count
vtx_cnt = match words[0].parse::<u32>() {
Err(why) => panic!("load_mesh(): Can't parse vertex count: {}: {}",
Error::description(&why),
display),
Ok(n) => n
};
break;
}
None => panic!("load_mesh(): EOF while parsing vertex count: {}", display)
}
}
// Vertices
let mut vtx: Vec<Vertex> = Vec::new();
loop {
match lines.next() {
Some("") => (), // Skip empty lines
Some(ln) => {
let mut words = ln.split(" ");
let words_collect: Vec<&str> = words.clone().collect();
let num_components = match mesh_file_type {
MeshFileType::XyzNxNyNzRGB => 9,
MeshFileType::XyzNxNyNz | MeshFileType::XyzRGB => 6
};
if words_collect.len() != num_components {
panic!("load_mesh(): Expected {} component vertices: {}",
num_components, display);
}
let mut components: Vec<f32> = Vec::new();
for _ in 0..num_components {
components.push(words.next().unwrap().parse::<f32>().unwrap());
}
match mesh_file_type {
MeshFileType::XyzRGB =>
vtx.push(Vertex::new(components[0],
components[1],
components[2],
// Compute the normal later
0.0, 0.0, 0.0,
components[3],
components[4],
components[5]
)),
MeshFileType::XyzNxNyNzRGB =>
vtx.push(Vertex::new(components[0],
components[1],
components[2],
components[3],
components[4],
components[5],
components[6],
components[7],
components[8]
)),
MeshFileType::XyzNxNyNz =>
vtx.push(Vertex::new(components[0],
components[1],
components[2],
components[3],
components[4],
components[5],
// White as default color
1.0, 1.0, 1.0
))
}
// Done?
if vtx.len() == vtx_cnt as usize { break }
}
None => panic!("load_mesh(): EOF while parsing vertices: {}", display)
}
}
if vtx_cnt < 3 {
panic!("load_mesh(): Bogus vertex count: {}: {}", vtx_cnt, display)
}
// Index count
let idx_cnt;
loop {
match lines.next() {
Some("") => (), // Skip empty lines
Some(ln) => {
// First non-empty, non-comment line should contain the index count
idx_cnt = match ln.parse::<u32>() {
Err(why) => panic!("load_mesh(): Can't parse index count: {}: {}",
Error::description(&why),
display),
Ok(n) => n
};
break;
}
None => panic!("load_mesh(): EOF while parsing index count: {}", display)
}
}
if idx_cnt % 3 != 0 {
panic!("load_mesh(): Bogus index count: {}: {}", idx_cnt, display)
}
// Indices
let mut idx: Vec<(u32, u32, u32)> = Vec::new();
loop {
match lines.next() {
Some("") => (), // Skip empty lines
Some(ln) => {
let mut words = ln.split(" ");
let words_collect: Vec<&str> = words.clone().collect();
if words_collect.len() != 3 {
panic!("load_mesh(): Expected 3 component indexed triangles: {}", display);
}
let mut components: Vec<u32> = Vec::new();
for _ in 0..3 {
let idx = words.next().unwrap().parse::<u32>().unwrap();
if idx >= vtx_cnt {
panic!("load_mesh(): Out-of-bounds index: {}: {}", idx, display)
}
components.push(idx);
}
idx.push((components[0], components[1], components[2]));
// Done?
if idx.len() * 3 == idx_cnt as usize { break }
}
None => panic!("load_mesh(): EOF while parsing indices: {}", display)
}
}
// Assemble triangle vector and mesh
let mut tri = Vec::new();
for tri_idx in idx {
let ntri = Triangle::new(tri_idx.0, tri_idx.1, tri_idx.2);
if mesh_file_type == MeshFileType::XyzRGB {
// Set vertex normals from face normal
// TODO: This obviously does not take sharing into account at all, but it's
// OK for now as we're only using it with very simple meshes
let v0p = Point3::new(vtx[tri_idx.0 as usize].p.x,
vtx[tri_idx.0 as usize].p.y,
vtx[tri_idx.0 as usize].p.z);
let v1p = Point3::new(vtx[tri_idx.1 as usize].p.x,
vtx[tri_idx.1 as usize].p.y,
vtx[tri_idx.1 as usize].p.z);
let v2p = Point3::new(vtx[tri_idx.2 as usize].p.x,
vtx[tri_idx.2 as usize].p.y,
vtx[tri_idx.2 as usize].p.z);
let n = face_normal(&v0p, &v1p, &v2p);
vtx[tri_idx.0 as usize].n = n;
vtx[tri_idx.1 as usize].n = n;
vtx[tri_idx.2 as usize].n = n;
}
tri.push(ntri);
}
let mesh = Mesh::new(tri, vtx);
// Print some mesh information
println!("load_mesh(): Loaded {} Tri and {} Vtx (format: {:?}) from '{}', \
AABB ({}, {}, {}) - ({}, {}, {})",
mesh.tri.len(), mesh.vtx.len(), mesh_file_type, display,
mesh.aabb_min.x, mesh.aabb_min.y, mesh.aabb_min.z,
mesh.aabb_max.x, mesh.aabb_max.y, mesh.aabb_max.z);
mesh
}
#[no_mangle]
pub extern fn rast_get_num_meshes() -> i32 { 12 }
#[no_mangle]
pub extern fn rast_get_mesh_name(idx: i32) -> *const u8 { mesh_by_idx(idx).0.as_ptr() }
#[no_mangle]
pub extern fn rast_get_mesh_tri_cnt(idx: i32) -> i32 { mesh_by_idx(idx).2.tri.len() as i32 }
fn mesh_by_idx<'a>(idx: i32) -> (&'a str, CameraFromTime, &'a Mesh) {
// Retrieve mesh name, camera and geometry by its index. We do this in such an awkward
// way so we can take advantage of the on-demand loading of the meshes through
// lazy_static
// Mesh geometry
lazy_static! {
static ref MESH_KILLEROO: Mesh =
load_mesh("meshes/killeroo_ao.dat" , MeshFileType::XyzNxNyNzRGB);
static ref MESH_HEAD: Mesh =
load_mesh("meshes/head_ao.dat" , MeshFileType::XyzNxNyNzRGB);
static ref MESH_MITSUBA: Mesh =
load_mesh("meshes/mitsuba_ao.dat" , MeshFileType::XyzNxNyNzRGB);
static ref MESH_CAT: Mesh =
load_mesh("meshes/cat_ao.dat" , MeshFileType::XyzNxNyNzRGB);
static ref MESH_HAND: Mesh =
load_mesh("meshes/hand_ao.dat" , MeshFileType::XyzNxNyNzRGB);
static ref MESH_TEAPOT: Mesh =
load_mesh("meshes/teapot.dat" , MeshFileType::XyzNxNyNz );
static ref MESH_TORUS_KNOT: Mesh =
load_mesh("meshes/torus_knot.dat" , MeshFileType::XyzNxNyNz );
static ref MESH_DWARF: Mesh =
load_mesh("meshes/dwarf.dat" , MeshFileType::XyzNxNyNzRGB);
static ref MESH_BLOB: Mesh =
load_mesh("meshes/blob.dat" , MeshFileType::XyzNxNyNz );
static ref MESH_CUBE: Mesh =
load_mesh("meshes/cube.dat" , MeshFileType::XyzNxNyNzRGB);
static ref MESH_SPHERE: Mesh =
load_mesh("meshes/sphere.dat" , MeshFileType::XyzNxNyNz );
static ref MESH_CORNELL: Mesh =
load_mesh("meshes/cornell_radiosity.dat", MeshFileType::XyzRGB );
}
// Name, camera and geometry tuple
match idx {
// Null terminated names so we can easily pass them as C strings
0 => ("Killeroo\0" , cam_orbit_front, &MESH_KILLEROO ),
1 => ("Head\0" , cam_orbit_closer, &MESH_HEAD ),
2 => ("Mitsuba\0" , cam_pan_front, &MESH_MITSUBA ),
3 => ("Cat\0" , cam_orbit_closer, &MESH_CAT ),
4 => ("Hand\0" , cam_orbit_closer, &MESH_HAND ),
5 => ("Teapot\0" , cam_orbit_closer, &MESH_TEAPOT ),
6 => ("TorusKnot\0" , cam_orbit, &MESH_TORUS_KNOT),
7 => ("Dwarf\0" , cam_orbit_front, &MESH_DWARF ),
8 => ("Blob\0" , cam_orbit, &MESH_BLOB ),
9 => ("Cube\0" , cam_orbit, &MESH_CUBE ),
10 => ("Sphere\0" , cam_orbit, &MESH_SPHERE ),
11 => ("CornellBox\0", cam_pan_back , &MESH_CORNELL ),
_ => panic!("mesh_by_idx: Invalid index: {}", idx)
}
}
//
// -----------------
// Camera Animations
// -----------------
//
// Eye position at the given time
type CameraFromTime = fn(f64) -> P3F;
fn cam_orbit(tick: f64) -> P3F {
// Orbit around object
Point3::new(((tick / 1.25).cos() * 1.8) as f32,
0.0,
((tick / 1.25).sin() * 1.8) as f32)
}
fn cam_orbit_closer(tick: f64) -> P3F {
// Orbit closer around object
Point3::new(((tick / 1.25).cos() * 1.6) as f32,
0.0,
((tick / 1.25).sin() * 1.6) as f32)
}
fn cam_orbit_front(tick: f64) -> P3F {
// Slow, dampened orbit around the front of the object, some slow vertical bobbing as well
let tick_slow = tick / 3.5;
let reverse = tick_slow as i64 % 2 == 1;
let tick_f = if reverse {
1.0 - tick_slow.fract()
} else {
tick_slow.fract()
} as f32;
let smooth = smootherstep(0.0, 1.0, tick_f);
let a_weight = 1.0 - smooth;
let b_weight = smooth;
let tick_seg = -consts::PI / 2.0 -
(-(consts::PI / 6.0) * a_weight + (consts::PI / 6.0) * b_weight);
Point3::new(tick_seg.cos() as f32,
((tick / 2.0).sin() * 0.25 + 0.2) as f32,
tick_seg.sin() as f32)
}
fn cam_pan_front(tick: f64) -> P3F {
// Camera makes circular motion looking at the mesh
Point3::new((tick.cos() * 0.3) as f32,
(tick.sin() * 0.3) as f32 + 0.4,
1.7)
}
fn cam_pan_back(tick: f64) -> P3F {
// Camera makes circular motion looking at the box (which is open at the back)
Point3::new((tick.cos() * 0.3) as f32,
(tick.sin() * 0.3) as f32,
-2.0)
}
fn smootherstep(edge0: f32, edge1: f32, x: f32) -> f32
{
// Scale and clamp x to 0..1 range
let x = na::clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);
// Evaluate polynomial
x * x * x * (x * (x * 6.0 - 15.0) + 10.0)
}
//
// -----------------------------
// Cube Map Loading & Processing
// -----------------------------
//
// All our irradiance cube map faces have the same fixed dimensions
static CM_FACE_WDH: i32 = 64;
#[derive(PartialEq, Debug, Copy, Clone)]
enum CMFaceName { XPos, XNeg, YPos, YNeg, ZPos, ZNeg }
// TODO: We could store the different convolution cube maps interleaved,
// increasing cache usage for lookups using multiple powers
type CMFace = Vec<V3F>;
type CM = [CMFace; 6];
struct IrradianceCMSet {
cos_0: CM, // Reflection map
cos_1: CM, // Diffuse
cos_8: CM, // Specular pow^x
cos_64: CM, // ..
cos_512: CM, // ..
cross: Vec<u32>, // Image of unfolded LDR cube map cross
cross_wdh: i32, // Width of cross
cross_hgt: i32 // Height of cross
}
impl IrradianceCMSet {
fn from_path(path: &str) -> IrradianceCMSet {
// Build a full irradiance cube map set with preview from the files found in 'path'
let path = &path.to_string();
println!("IrradianceCMSet::from_path(): Loading 5x6x{}x{} cube map faces of \
cos^[0|1|8|64|512] convolved irradiance from '{}'",
CM_FACE_WDH, CM_FACE_WDH, path);
// Low-res reflection map and LDR unfolded image
let cos_0 = load_cm(0, path);
let (cross, cross_wdh, cross_hgt) = draw_cm_cross_buffer(&cos_0);
IrradianceCMSet {
cos_0: cos_0,
cos_1: load_cm(1, path),
cos_8: load_cm(8, path),
cos_64: load_cm(64, path),
cos_512: load_cm(512, path),
cross: cross,
cross_wdh: cross_wdh,
cross_hgt: cross_hgt
}
}
fn draw_cross(&self, xorg: i32, yorg: i32, w: i32, h: i32, fb: *mut u32) {
// Draw the cross image into the given framebuffer
let x1 = na::clamp(xorg, 0, w);
let y1 = na::clamp(yorg, 0, h);
let x2 = cmp::min(x1 + self.cross_wdh, w);
let y2 = cmp::min(y1 + self.cross_hgt, h);
let cross_ptr = self.cross.as_ptr();
for y in y1..y2 {
let cy = y - y1;
let fb_row = y * w;
let cross_row = cy * self.cross_wdh - x1;
for x in x1..x2 {
let c = unsafe { * cross_ptr.offset((cross_row + x) as isize) };
// Skip pixels not on the cross (alpha == 0)
if c & 0xFF000000 == 0 { continue }
unsafe { * fb.offset((fb_row + x) as isize) = c }
}
}
}
}
fn load_hdr(file_name: &String) -> image::Image<f32> {
// Load a Radiance HDR image using the stb_image library
let path = path::Path::new(file_name);
if !path.exists() {
panic!("load_hdr(): File not found: {}", file_name)
}
match image::load(path) {
image::LoadResult::ImageF32(img) => img,
image::LoadResult::ImageU8(_) => panic!("load_hdr(): Not HDR: {}", file_name),
image::LoadResult::Error(err) => panic!("load_hdr(): {}: {}", err, file_name)
}
}
fn cm_fn_from_param(path: &String, power: i32, face: CMFaceName) -> String {
// Construct a file name like 'data/env_cos_64_x+.hdr' from the given parameters
let face_name = match face {
CMFaceName::XPos => "x+",
CMFaceName::XNeg => "x-",
CMFaceName::YPos => "y+",
CMFaceName::YNeg => "y-",
CMFaceName::ZPos => "z+",
CMFaceName::ZNeg => "z-"
}.to_string();
format!("{}/env_cos_{}_{}.hdr", path, power, face_name)
}
fn load_cm_face(file_name: &String, flip_x: bool, flip_y: bool) -> CMFace {
// Load HDR
let img = load_hdr(&file_name);
if img.width != CM_FACE_WDH as usize ||
img.height != CM_FACE_WDH as usize {
panic!("load_cm_face(): HDR image has wrong cube map face dimensions: {}: {} x {}",
file_name, img.width, img.height);
}
// Convert to our format, flip axis as requested
let mut face = Vec::new();
face.resize((CM_FACE_WDH * CM_FACE_WDH) as usize, na::zero());
for y in 0..CM_FACE_WDH {
for x in 0..CM_FACE_WDH {
face[(if flip_x { CM_FACE_WDH - 1 - x } else { x } +
if flip_y { CM_FACE_WDH - 1 - y } else { y } * CM_FACE_WDH) as usize] =
Vector3::new(img.data[(x * 3 + y * CM_FACE_WDH * 3 + 0) as usize],
img.data[(x * 3 + y * CM_FACE_WDH * 3 + 1) as usize],
img.data[(x * 3 + y * CM_FACE_WDH * 3 + 2) as usize]);
}
}
face
}
fn load_cm(power: i32, path: &String) -> CM {
// Load all six cube map faces of the given power from the given path
// The cube maps we load are oriented like OpenGL expects them, which is actually
// rather strange. Flip and mirror so it's convenient for the way we do lookups
[ load_cm_face(&cm_fn_from_param(path, power, CMFaceName::XPos), true , true ),
load_cm_face(&cm_fn_from_param(path, power, CMFaceName::XNeg), false, true ),
load_cm_face(&cm_fn_from_param(path, power, CMFaceName::YPos), false, false),
load_cm_face(&cm_fn_from_param(path, power, CMFaceName::YNeg), false, true ),
load_cm_face(&cm_fn_from_param(path, power, CMFaceName::ZPos), false, true ),
load_cm_face(&cm_fn_from_param(path, power, CMFaceName::ZNeg), true , true )
]
}
fn draw_cm_cross_buffer(cm: &CM) -> (Vec<u32>, i32, i32) {
// Draw a flattened out cube map into a buffer, faces are half size
//
// _ _ (cross_wdh, cross_hgt)
// | Y+ |
// X- Z- X+ Z+
// |_ Y- _|
// (0,0)
//
let faces = [
CMFaceName::XPos, CMFaceName::XNeg,
CMFaceName::YPos, CMFaceName::YNeg,
CMFaceName::ZPos, CMFaceName::ZNeg
];
let cross_wdh = 4 * (CM_FACE_WDH / 2);
let cross_hgt = 3 * (CM_FACE_WDH / 2);
let mut cross = Vec::new();
cross.resize((cross_wdh * cross_hgt) as usize, 0);
for face_idx in faces.iter() {
let face = &cm[*face_idx as usize];
// Our faces are oriented so we can most efficiently do vector lookups, not
// necessarily in the right format for display, so we have to mirror and flip
let (xoff, yoff, flip_x, flip_y) = match face_idx {
&CMFaceName::XPos => (2, 1, false, false),
&CMFaceName::XNeg => (0, 1, true , false),
&CMFaceName::YPos => (1, 2, false, false),
&CMFaceName::YNeg => (1, 0, false, true ),
&CMFaceName::ZPos => (3, 1, true , false),
&CMFaceName::ZNeg => (1, 1, false, false)
};
let wdh_half = CM_FACE_WDH / 2;
for yf in 0..wdh_half {
for xf in 0..wdh_half {
let x = xf + xoff * wdh_half;
let y = yf + yoff * wdh_half;
let col = face[(
if flip_x { wdh_half - 1 - xf } else { xf } * 2 +
if flip_y { wdh_half - 1 - yf } else { yf } * 2 * CM_FACE_WDH) as usize];
let idx = (x + y * cross_wdh) as usize;
// We later use the alpha channel to skip pixels outside the cross
cross[idx] = rgbf_to_abgr32_gamma(col.x, col.y, col.z) | 0xFF000000;
}
}
}
(cross, cross_wdh, cross_hgt)
}
fn cm_texel_from_dir(dir: &V3F) -> (CMFaceName, i32) {
// Find the closest cube map texel pointed at by 'dir'
let face;
let mut u;
let mut v;
let dir_abs = Vector3::new(dir.x.abs(), dir.y.abs(), dir.z.abs());
// Find major axis
if dir_abs.x > dir_abs.y && dir_abs.x > dir_abs.z {
face = if dir.x > 0.0 { CMFaceName::XPos } else { CMFaceName::XNeg };
let inv_dir_abs = 1.0 / dir_abs.x;
u = dir.z * inv_dir_abs;
v = dir.y * inv_dir_abs;
} else if dir_abs.y > dir_abs.x && dir_abs.y > dir_abs.z {
face = if dir.y > 0.0 { CMFaceName::YPos } else { CMFaceName::YNeg };
let inv_dir_abs = 1.0 / dir_abs.y;
u = dir.x * inv_dir_abs;
v = dir.z * inv_dir_abs;
} else {
face = if dir.z > 0.0 { CMFaceName::ZPos } else { CMFaceName::ZNeg };
let inv_dir_abs = 1.0 / dir_abs.z;
u = dir.x * inv_dir_abs;
v = dir.y * inv_dir_abs;
}
// Face texel coordinates
u = (u + 1.0) * 0.5;
v = (v + 1.0) * 0.5;
let tx = na::clamp((u * CM_FACE_WDH as f32) as i32, 0, CM_FACE_WDH - 1);
let ty = na::clamp((v * CM_FACE_WDH as f32) as i32, 0, CM_FACE_WDH - 1);
(face, tx + ty * CM_FACE_WDH)
}
fn lookup_texel_cm(cm: &CM, texel: (CMFaceName, i32)) -> V3F {
let (face, idx) = texel;
unsafe { *cm.get_unchecked(face as usize).get_unchecked(idx as usize) }
}
fn lookup_dir_cm(cm: &CM, dir: &V3F) -> V3F {
lookup_texel_cm(cm, cm_texel_from_dir(dir))
}
#[allow(dead_code)]
fn cm_texel_to_dir(face: CMFaceName, x: i32, y: i32) -> V3F {
// Convert a texel position on a cube map face into a direction
let vw = (x as f32 + 0.5) / CM_FACE_WDH as f32 * 2.0 - 1.0;
let vh = (y as f32 + 0.5) / CM_FACE_WDH as f32 * 2.0 - 1.0;
na::normalize(&match face {
CMFaceName::XPos => V3F::new( 1.0, vh, vw),
CMFaceName::XNeg => V3F::new(-1.0, vh, vw),
CMFaceName::YPos => V3F::new( vw, 1.0, vh),
CMFaceName::YNeg => V3F::new( vw, -1.0, vh),
CMFaceName::ZPos => V3F::new( vw, vh, 1.0),
CMFaceName::ZNeg => V3F::new( vw, vh, -1.0)
})
}
// Normalization cube map, used as a lookup table for vector normalization
lazy_static! {
static ref _CM_NORMALIZE:[Vec<V3F>; 6] = {
let build_face = |face: CMFaceName| -> Vec<V3F> {
let mut v: Vec<V3F> = Vec::new();
v.resize((CM_FACE_WDH * CM_FACE_WDH) as usize, V3F::new(0.0, 0.0, 0.0));
for y in 0..CM_FACE_WDH {
for x in 0..CM_FACE_WDH {
v[(x + y * CM_FACE_WDH) as usize] = cm_texel_to_dir(face, x, y);
}
}
v
};
[ build_face(CMFaceName::XPos), build_face(CMFaceName::XNeg),
build_face(CMFaceName::YPos), build_face(CMFaceName::YNeg),
build_face(CMFaceName::ZPos), build_face(CMFaceName::ZNeg)
]
};
}
#[no_mangle]
pub extern fn rast_get_num_cm_sets() -> i32 { 9 }
#[no_mangle]
pub extern fn rast_get_cm_set_name(idx: i32) -> *const u8 { cm_set_by_idx(idx).0.as_ptr() }
fn cm_set_by_idx<'a>(idx: i32) -> (&'a str, &'a IrradianceCMSet) {
// Retrieve irradiance cube map set name and images by its index. We do this in such
// an awkward way so we can take advantage of the on-demand loading of the cube maps
// through lazy_static
// Sets of pre-filtered irradiance cube maps
lazy_static! {
static ref CM_GRACE: IrradianceCMSet =
IrradianceCMSet::from_path("envmaps/grace" );
static ref CM_PARKING_LOT: IrradianceCMSet =
IrradianceCMSet::from_path("envmaps/parking_lot");
static ref CM_ENIS: IrradianceCMSet =
IrradianceCMSet::from_path("envmaps/enis" );
static ref CM_GLACIER: IrradianceCMSet =
IrradianceCMSet::from_path("envmaps/glacier" );
static ref CM_PISA: IrradianceCMSet =
IrradianceCMSet::from_path("envmaps/pisa" );
static ref CM_PINE_TREE: IrradianceCMSet =
IrradianceCMSet::from_path("envmaps/pine_tree" );
static ref CM_UFFIZI: IrradianceCMSet =
IrradianceCMSet::from_path("envmaps/uffizi" );
static ref CM_DOGE: IrradianceCMSet =
IrradianceCMSet::from_path("envmaps/doge" );
static ref CM_COLTEST: IrradianceCMSet =
IrradianceCMSet::from_path("envmaps/coltest/" );
}
match idx {
// Null terminated names so we can easily pass them as C strings
0 => ("Grace\0" , &CM_GRACE ),
1 => ("ParkingLot\0", &CM_PARKING_LOT),
2 => ("Enis\0" , &CM_ENIS ),
3 => ("Glacier\0" , &CM_GLACIER ),
4 => ("Pisa\0" , &CM_PISA ),
5 => ("PineTree\0" , &CM_PINE_TREE ),
6 => ("Uffizi\0" , &CM_UFFIZI ),
7 => ("Doge\0" , &CM_DOGE ),
8 => ("ColTest\0" , &CM_COLTEST ),
_ => panic!("cm_set_by_idx: Invalid index: {}", idx)
}
}
//
// -------
// Shaders
// -------
//
// All shaders have this signature
type Shader = fn(&V3F, // World space position
&V3F, // World space normal
&V3F, // Color (usually baked AO / radiosity)
&P3F, // World space camera position
f64, // Current time (tick)
&IrradianceCMSet) -> // Current environment cube map set
V3F; // Output color
fn shader_color(_: &V3F, _: &V3F, col: &V3F, _: &P3F, _: f64, _: &IrradianceCMSet) -> V3F {
*col
}
fn shader_n_to_color(_: &V3F, n: &V3F, _: &V3F, _: &P3F, _: f64, _: &IrradianceCMSet) -> V3F {
// Convert the normal to a color
(n.normalize() + 1.0) * 0.5
}
fn shader_headlight(p: &V3F, n: &V3F, col: &V3F, eye: &P3F, _: f64, _: &IrradianceCMSet) -> V3F {
let n = fast_normalize(n);
let l = fast_normalize(&(*eye.as_vector() - *p));
let ldotn = na::clamp(na::dot(&l, &n), 0.0, 1.0);
let occlusion = *col * *col;
occlusion * ldotn
}
fn shader_dir_light(p: &V3F, n: &V3F, col: &V3F, eye: &P3F, _tick: f64,
_cm: &IrradianceCMSet) -> V3F {
// Specular material lit by two light sources
let n = fast_normalize(n);
let eye = *p - *eye.as_vector();
let r = fast_normalize(&reflect(&eye, &n));
let l = Vector3::new(0.577350269, 0.577350269, 0.577350269); // Normalized (1, 1, 1)
let light_1 = {
let ldotn = na::clamp(na::dot(&l, &n), 0.0, 1.0);
let ldotr = fast_unit_pow16(na::clamp(na::dot(&l, &r), 0.0, 1.0));
ldotn * 0.25 + ldotr * 0.75
};
let light_2 = {
let ldotn = na::clamp(na::dot(&-l, &n), 0.0, 1.0);
let ldotr = fast_unit_pow16(na::clamp(na::dot(&-l, &r), 0.0, 1.0));
ldotn * 0.25 + ldotr * 0.75
};
let ambient = Vector3::new(0.05, 0.05, 0.05);
let light = Vector3::new(1.0, 0.5, 0.5) * light_1 +
Vector3::new(0.5, 0.5, 1.0) * light_2 +
ambient;
let occlusion = *col * *col;
light * occlusion
}
fn normalize_phong_lobe(power: f32) -> f32
{
(power + 2.0) * 0.5
}
fn shader_cm_diffuse(_p: &V3F, n: &V3F, col: &V3F, _eye: &P3F, _tick: f64,
cm: &IrradianceCMSet) -> V3F {
let n = fast_normalize(n);
lookup_dir_cm(&cm.cos_1, &n) * (*col * *col)
}
fn shader_cm_refl(p: &V3F, n: &V3F, col: &V3F, eye: &P3F, _tick: f64,
cm: &IrradianceCMSet) -> V3F {
let n = fast_normalize(n);
let eye = *p - *eye.as_vector();
let r = reflect(&eye, &n);
let r_tex = cm_texel_from_dir(&r);
( lookup_dir_cm (&cm.cos_1 , &n)
+ lookup_texel_cm(&cm.cos_8 , r_tex) * normalize_phong_lobe(8.0 )
+ lookup_texel_cm(&cm.cos_64, r_tex) * normalize_phong_lobe(64.0)
)
* (*col * *col)
}
fn shader_cm_coated(p: &V3F, n: &V3F, col: &V3F, eye: &P3F, _tick: f64,
cm: &IrradianceCMSet) -> V3F {
let n = fast_normalize(n);
let eye = *p - *eye.as_vector();
let r = reflect(&eye, &n);
let r_tex = cm_texel_from_dir(&r);
let fresnel = fresnel_conductor(na::dot(&-eye, &n), 1.0, 1.1);
( lookup_dir_cm (&cm.cos_1 , &n) * 0.85
+ lookup_texel_cm(&cm.cos_8 , r_tex) * normalize_phong_lobe(8.0 ) * fresnel
+ lookup_texel_cm(&cm.cos_512, r_tex) * normalize_phong_lobe(512.0) * fresnel * 1.5
)
* (*col * *col)
}
fn shader_cm_diff_rim(p: &V3F, n: &V3F, col: &V3F, eye: &P3F, _: f64,
cm: &IrradianceCMSet) -> V3F {
let n = fast_normalize(n);
let eye = *p - *eye.as_vector();
let fresnel = fresnel_conductor(na::dot(&-eye, &n), 1.0, 1.1);
(lookup_dir_cm(&cm.cos_1, &n) + fresnel * 0.75) * *col
}
fn shader_cm_glossy(p: &V3F, n: &V3F, col: &V3F, eye: &P3F, _tick: f64,
cm: &IrradianceCMSet) -> V3F {
let n = fast_normalize(n);
let eye = *p - *eye.as_vector();
let r = reflect(&eye, &n);
( lookup_dir_cm(&cm.cos_1, &n)
+ lookup_dir_cm(&cm.cos_8, &r) * normalize_phong_lobe(8.0)
)
* (*col * *col)
}
fn shader_cm_green_highlight(p: &V3F, n: &V3F, col: &V3F, eye: &P3F, _tick: f64,
cm: &IrradianceCMSet) -> V3F {
let n = fast_normalize(n);
let eye = *p - *eye.as_vector();
let r = reflect(&eye, &n);
( lookup_dir_cm(&cm.cos_1 , &n)
+ lookup_dir_cm(&cm.cos_64, &r) * normalize_phong_lobe(64.0) * Vector3::new(0.2, 0.8, 0.2)
)
* (*col * *col)
}
fn shader_cm_red_material(p: &V3F, n: &V3F, col: &V3F, eye: &P3F, _tick: f64,
cm: &IrradianceCMSet) -> V3F {
let n = fast_normalize(n);
let eye = *p - *eye.as_vector();
let r = reflect(&eye, &n);
( lookup_dir_cm(&cm.cos_1 , &n) * Vector3::new(0.8, 0.2, 0.2)
+ lookup_dir_cm(&cm.cos_512, &r) * normalize_phong_lobe(512.0)
)
* (*col * *col)
}
fn shader_cm_metallic(p: &V3F, n: &V3F, col: &V3F, eye: &P3F, _tick: f64,
cm: &IrradianceCMSet) -> V3F {
let n = fast_normalize(n);
let eye = *p - *eye.as_vector();
let r = reflect(&eye, &n);
let r_tex = cm_texel_from_dir(&r);
( lookup_texel_cm(&cm.cos_8 , r_tex) * normalize_phong_lobe(8.0 )
+ lookup_texel_cm(&cm.cos_64, r_tex) * normalize_phong_lobe(64.0)
)
* (*col)
}
fn shader_cm_super_shiny(p: &V3F, n: &V3F, col: &V3F, eye: &P3F, _tick: f64,
cm: &IrradianceCMSet) -> V3F {
let n = fast_normalize(n);
let eye = *p - *eye.as_vector();
let r = reflect(&eye, &n);
let r_tex = cm_texel_from_dir(&r);
( lookup_texel_cm(&cm.cos_64 , r_tex) * normalize_phong_lobe(64.0 )
+ lookup_texel_cm(&cm.cos_512, r_tex) * normalize_phong_lobe(512.0)
+ lookup_texel_cm(&cm.cos_0 , r_tex)
)
* (*col)
}
fn shader_cm_gold(p: &V3F, n: &V3F, col: &V3F, eye: &P3F, _tick: f64,
cm: &IrradianceCMSet) -> V3F {
let n = fast_normalize(n);
let l = fast_normalize(&(*eye.as_vector() - *p));
let ldotn = na::clamp(na::dot(&l, &n), 0.0, 1.0);
let eye = *p - *eye.as_vector();
let r = reflect(&eye, &n);
let albedo = Vector3::new(1.0, 0.76, 0.33);
let r_tex = cm_texel_from_dir(&r);
( lookup_dir_cm (&cm.cos_1 , &n) * ldotn
+ lookup_texel_cm(&cm.cos_8 , r_tex) * normalize_phong_lobe(8.0 )
+ lookup_texel_cm(&cm.cos_512, r_tex) * normalize_phong_lobe(512.0) * (1.0 - ldotn)
)
* albedo * (*col * *col)
}