-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhostCode.cpp
More file actions
1445 lines (1175 loc) · 54.4 KB
/
hostCode.cpp
File metadata and controls
1445 lines (1175 loc) · 54.4 KB
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
// ======================================================================== //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
// This program reads a MagicaVoxel file and ray traces it. Different types of
// acceleration structures can be built with command line options.
// public owl node-graph API
#include "owl/owl.h"
// our device-side data structures
#include "deviceCode.h"
// viewer base class, for window and user interaction
#include "owlViewer/OWLViewer.h"
#include "owl/common/math/AffineSpace.h"
#include "constants.h"
#include "ogt_vox.h"
#include "readVox.h"
#include <cassert>
#include <cstdint>
#include <map>
#include <tuple>
#include <vector>
#define LOG(message) \
std::cout << OWL_TERMINAL_BLUE; \
std::cout << "#owl.sample(main): " << message << std::endl; \
std::cout << OWL_TERMINAL_DEFAULT;
#define LOG_OK(message) \
std::cout << OWL_TERMINAL_LIGHT_BLUE; \
std::cout << "#owl.sample(main): " << message << std::endl; \
std::cout << OWL_TERMINAL_DEFAULT;
extern "C" char deviceCode_ptx[];
// Small default vox file as byte buffer
extern "C" const uint8_t voxBuffer[];
extern "C" const size_t voxBufferLen;
enum SceneType {
SCENE_TYPE_FLAT=1,
SCENE_TYPE_USER,
SCENE_TYPE_USERBLOCKS,
SCENE_TYPE_INSTANCED,
SCENE_TYPE_INVALID
};
struct Viewer : public owl::viewer::OWLViewer
{
struct GlobalOptions {
bool enableGround = true;
bool enableClipping = true;
bool enableToonOutline = true;
};
Viewer(const ogt_vox_scene *scene, SceneType sceneType, const GlobalOptions &options);
/*! gets called whenever the viewer needs us to re-render out widget */
void render() override;
/*! window notifies us that we got resized. We HAVE to override
this to know our actual render dimensions, and get pointer
to the device frame buffer that the viewer cated for us */
void resize(const vec2i &newSize) override;
/*! this function gets called whenever any camera manipulator
updates the camera. gets called AFTER all values have been updated */
void cameraChanged() override;
void key(char key, const vec2i &/*where*/) override;
/// Geometry creation functions
OWLGroup createFlatTriangleGeometryScene(OWLModule module,
const ogt_vox_scene *scene,
owl::box3f &sceneBox);
OWLGroup createInstancedTriangleGeometryScene(OWLModule module,
const ogt_vox_scene *scene,
owl::box3f &sceneBox);
OWLGroup createUserGeometryScene(OWLModule module,
const ogt_vox_scene *scene,
owl::box3f &sceneBox);
OWLGroup createUserBlocksGeometryScene(OWLModule module,
const ogt_vox_scene *scene,
owl::box3f &sceneBox) ;
bool sbtDirty = true;
OWLRayGen rayGen { 0 };
OWLLaunchParams launchParams { 0 };
OWLContext context { 0 };
int frameID = 0;
OWLBuffer fbAccum = nullptr;
owl::box3f sceneBox; // in units of bricks
int clipHeight = 1000;
bool clipDirty = false;
float sunPhi = 0.785398f; // rotation about up axis
float sunTheta = 0.785398f; // elevation angle, 0 at horizon
bool sunDirty = true;
bool enableGround = true;
bool enableClipping = true; // enable clipping plane in shader
bool enableToonOutline = true;
};
/*! window notifies us that we got resized */
void Viewer::resize(const vec2i &newSize)
{
OWLViewer::resize(newSize);
if (fbAccum) {
owlBufferDestroy(fbAccum);
}
fbAccum = owlDeviceBufferCreate(context, OWL_FLOAT4, newSize.x*newSize.y, nullptr);
owlParamsSetBuffer(launchParams, "fbAccumBuffer", fbAccum);
cameraChanged();
}
/*! window notifies us that the camera has changed */
void Viewer::cameraChanged()
{
frameID = 0; // reset accum
const vec3f lookFrom = camera.getFrom();
const vec3f lookAt = camera.getAt();
const vec3f lookUp = camera.getUp();
const float tanHalfAngle = tanf(owl::viewer::toRadian(0.5f*camera.getFovyInDegrees()));
// ----------- compute variable values ------------------
vec3f camera_pos = lookFrom;
vec3f camera_d00
= normalize(lookAt-lookFrom);
float aspect = fbSize.x / float(fbSize.y);
vec3f camera_ddu
= tanHalfAngle * aspect * normalize(cross(camera_d00,lookUp));
vec3f camera_ddv
= tanHalfAngle * normalize(cross(camera_ddu,camera_d00));
camera_d00 -= 0.5f * camera_ddu;
camera_d00 -= 0.5f * camera_ddv;
// ----------- set variables ----------------------------
owlParamsSet1ul(launchParams, "fbPtr", (uint64_t)fbPointer);
owlParamsSet2i (launchParams, "fbSize", (const owl2i&)fbSize);
owlRayGenSet3f (rayGen,"camera.pos", (const owl3f&)camera_pos);
owlRayGenSet3f (rayGen,"camera.dir_00",(const owl3f&)camera_d00);
owlRayGenSet3f (rayGen,"camera.dir_du",(const owl3f&)camera_ddu);
owlRayGenSet3f (rayGen,"camera.dir_dv",(const owl3f&)camera_ddv);
sbtDirty = true;
}
void Viewer::key(char key, const vec2i &where)
{
switch (key) {
case '1':
sunTheta += 0.1f;
sunTheta = owl::clamp(sunTheta, 0.f, M_PIf/2);
sunDirty = true;
return;
case '2':
sunTheta -= 0.1f;
sunTheta = owl::clamp(sunTheta, 0.f, M_PIf/2);
sunDirty = true;
return;
case '3':
sunPhi += 0.1f;
if (sunPhi >= 2.0f*M_PIf) sunPhi -= 2.0f*M_PIf;
sunDirty = true;
return;
case '4':
sunPhi -= 0.1f;
if (sunPhi <= 0.0f) sunPhi += 2.0f*M_PIf;
sunDirty = true;
return;
case '[':
clipHeight -= 1;
if (clipHeight < 0) clipHeight = 0;
clipDirty = true;
return;
case ']':
clipHeight += 1;
if (clipHeight > int(sceneBox.span().z)+1) {
clipHeight = int(sceneBox.span().z)+1;
}
clipDirty = true;
return;
case 'p':
const std::string filename = "screenshot.png";
LOG("Saving screenshot to: " << filename);
screenShot(filename);
break;
}
OWLViewer::key(key, where);
}
// Adapted from ogt demo code.
// The OGT format stores voxels as solid grids; we only need to store the nonempty entries on device.
std::vector<uchar4> extractSolidVoxelsFromModel(const ogt_vox_model* model)
{
// is the voxel at the given index opaque?
auto isOpaque = [model](int x, int y, int z) -> bool {
if (x < 0 || x >= (int)model->size_x) return false;
if (y < 0 || y >= (int)model->size_y) return false;
if (z < 0 || z >= (int)model->size_z) return false;
int index = z*model->size_x*model->size_y + y*model->size_x + x;
uint8_t ci = model->voxel_data[index];
return ci != 0;
};
uint32_t voxel_index = 0;
std::vector<uchar4> solid_voxels;
solid_voxels.reserve(model->size_z * model->size_y * model->size_x);
for (int z = 0; z < (int)model->size_z; z++) {
for (int y = 0; y < (int)model->size_y; y++) {
for (int x = 0; x < (int)model->size_x; x++, voxel_index++) {
uint8_t ci = model->voxel_data[voxel_index];
if (ci) {
solid_voxels.push_back(
// Switch to Y-up
make_uchar4(uint8_t(x), uint8_t(y), uint8_t(z), ci));
}
}
}
}
LOG("solid voxel count: " << solid_voxels.size());
return solid_voxels;
}
// Similar to above, but extract small dense grids ("blocks") of voxels.
void extractBlocksFromModel(const ogt_vox_model* model, int blockLen,
std::vector<uchar3> &blockOriginsOut, std::vector<unsigned char> &colorIndicesOut)
{
const vec3i blockDim(blockLen);
const int bricksPerBlock = blockDim.x * blockDim.y * blockDim.z;
// Use CUDA notation to keep this straight:
// block: an NxNxN cube of bricks (original voxels)
// grid: a cube of blocks, however many needed to hold all voxels
vec3i gridDim(
(model->size_x + blockDim.x - 1)/blockDim.x, // ceil(size_x/blockDim.x); using integer math
(model->size_y + blockDim.y - 1)/blockDim.y,
(model->size_z + blockDim.z - 1)/blockDim.z);
std::vector<uchar3> blockOrigins(gridDim.x * gridDim.y * gridDim.z);
// Fill in block origins
{
int blockIdx = 0;
for (int gridZ = 0; gridZ < gridDim.z; ++gridZ) {
for (int gridY = 0; gridY < gridDim.y; ++gridY) {
for (int gridX = 0; gridX < gridDim.x; ++gridX) {
blockOrigins[blockIdx] = make_uchar3(gridX*blockDim.x, gridY*blockDim.y, gridZ*blockDim.z);
blockIdx++;
}
}
}
}
// iterate over the voxels and scatter color indices into block order
std::vector<unsigned char> colorIndices(blockOrigins.size()*bricksPerBlock, 0);
int voxel_index = 0;
for (int z = 0; z < (int)model->size_z; z++) {
for (int y = 0; y < (int)model->size_y; y++) {
for (int x = 0; x < (int)model->size_x; x++, voxel_index++) {
uint8_t ci = model->voxel_data[voxel_index];
// Note: some of this could be moved out of the innermost loop
vec3i blockIdx (x/blockDim.x, y/blockDim.y, z/blockDim.z);
int blockOffsetInGrid = blockIdx.x + blockIdx.y*gridDim.x + blockIdx.z*gridDim.x*gridDim.y;
int blockOffset = blockOffsetInGrid*bricksPerBlock;
// local brick coords inside a block
int bx = x - blockIdx.x*blockDim.x;
int by = y - blockIdx.y*blockDim.y;
int bz = z - blockIdx.z*blockDim.z;
int brickOffsetInBlock = bx + by*blockDim.x + bz*blockDim.x*blockDim.y;
int brickOffset = blockOffset + brickOffsetInBlock;
assert(brickOffset < colorIndices.size());
colorIndices[brickOffset] = ci;
}
}
}
// Compact by removing empty blocks
blockOriginsOut.reserve(blockOrigins.size());
colorIndicesOut.reserve(colorIndices.size());
for (int blockIdx = 0; blockIdx < int(blockOrigins.size()); ++blockIdx) {
bool visible = false;
for (int i = blockIdx*bricksPerBlock, k = 0; k < bricksPerBlock; ++i, ++k) {
if (colorIndices[i] > 0) {
visible = true;
break;
}
}
if (visible) {
blockOriginsOut.push_back(blockOrigins[blockIdx]);
for (int i = blockIdx*bricksPerBlock, k = 0; k < bricksPerBlock; ++i, ++k) {
colorIndicesOut.push_back(colorIndices[i]);
}
}
}
}
// Simple memory tracker
struct BufferAllocator {
inline OWLBuffer deviceBufferCreate(OWLContext context,
OWLDataType type,
size_t count,
const void *init)
{
OWLBuffer buf = owlDeviceBufferCreate(context, type, count, init);
bytesAllocated += owlBufferSizeInBytes(buf);
return buf;
}
size_t bytesAllocated = 0u;
};
void logSceneMemory(size_t bottomLevelBvhSizeInBytes,
size_t topLevelBvhSizeInBytes,
const BufferAllocator &allocator)
{
LOG("Scene GAS memory: " << owl::common::prettyNumber(bottomLevelBvhSizeInBytes));
LOG("Scene IAS memory: " << owl::common::prettyNumber(topLevelBvhSizeInBytes));
LOG("Scene buffer memory: " << owl::common::prettyNumber(allocator.bytesAllocated));
size_t total = bottomLevelBvhSizeInBytes + topLevelBvhSizeInBytes + allocator.bytesAllocated;
LOG("Scene total memory: " << total << " (" << owl::common::prettyNumber(total) << ")");
}
size_t getAccelSizeInBytes(OWLGroup group)
{
size_t finalSize = 0u;
owlGroupGetAccelSize(group, &finalSize, nullptr);
return finalSize;
}
// Helper function to extract vox instance transforms
void appendInstanceTransforms(const ogt_vox_scene *scene, const ogt_vox_model *vox_model, const std::vector<uint32_t> &instances,
std::vector<owl::affine3f> &instanceTransforms, box3f &sceneBox)
{
for (uint32_t instanceIndex : instances) {
const ogt_vox_instance &vox_instance = scene->instances[instanceIndex];
const ogt_vox_transform &vox_transform = vox_instance.transform;
const owl::affine3f instanceTransform(
vec3f( vox_transform.m00, vox_transform.m01, vox_transform.m02 ), // column 0
vec3f( vox_transform.m10, vox_transform.m11, vox_transform.m12 ), // 1
vec3f( vox_transform.m20, vox_transform.m21, vox_transform.m22 ), // 2
vec3f( vox_transform.m30, vox_transform.m31, vox_transform.m32 )); // 3
// This matrix translates model to its center (in integer coords!) and applies instance transform
const affine3f instanceMoveToCenterAndTransform =
affine3f(instanceTransform) *
affine3f::translate(-vec3f(float(vox_model->size_x/2), // Note: snapping to int to match MV
float(vox_model->size_y/2),
float(vox_model->size_z/2)));
sceneBox.extend(xfmPoint(instanceMoveToCenterAndTransform, vec3f(0.0f)));
sceneBox.extend(xfmPoint(instanceMoveToCenterAndTransform,
vec3f(float(vox_model->size_x), float(vox_model->size_y), float(vox_model->size_z))));
instanceTransforms.push_back(instanceMoveToCenterAndTransform);
}
}
// User scene type:
// * each brick is a user (custom) prim
// * each vox model is an OWL geom group
// * vox instances are an OWL instance group
OWLGroup Viewer::createUserGeometryScene(OWLModule module, const ogt_vox_scene *scene,
box3f &sceneBox)
{
BufferAllocator allocator;
// -------------------------------------------------------
// declare user vox geometry type
// -------------------------------------------------------
OWLVarDecl voxGeomVars[] = {
{ "prims", OWL_BUFPTR, OWL_OFFSETOF(VoxGeomData,prims)},
{ "colorPalette", OWL_BUFPTR, OWL_OFFSETOF(VoxGeomData,colorPalette)},
{ "enableToonOutline", OWL_BOOL, OWL_OFFSETOF(VoxGeomData, enableToonOutline)},
{ /* sentinel to mark end of list */ }
};
OWLGeomType voxGeomType
= owlGeomTypeCreate(context,
OWL_GEOMETRY_USER,
sizeof(VoxGeomData),
voxGeomVars, -1);
owlGeomTypeSetClosestHit(voxGeomType, 0, module, "VoxGeom");
owlGeomTypeSetIntersectProg(voxGeomType, 0, module, "VoxGeomMajercik");
owlGeomTypeSetIntersectProg(voxGeomType, 1, module, "VoxGeomShadow"); // for shadow rays
if (this->enableToonOutline) {
owlGeomTypeSetIntersectProg(voxGeomType, 2, module, "VoxGeomOutlineShadow");
}
owlGeomTypeSetBoundsProg(voxGeomType, module, "VoxGeom");
// Do this before setting up user geometry, to compile bounds program
owlBuildPrograms(context);
assert(scene->num_instances > 0);
assert(scene->num_models > 0);
// Palette buffer is global to scene
OWLBuffer paletteBuffer
= allocator.deviceBufferCreate(context, OWL_UCHAR4, 256, scene->palette.color);
// Cluster instances together that use the same model
std::map<uint32_t, std::vector<uint32_t>> modelToInstances;
for (uint32_t instanceIndex = 0; instanceIndex < scene->num_instances; instanceIndex++) {
const ogt_vox_instance &vox_instance = scene->instances[instanceIndex];
if (!vox_instance.hidden) {
modelToInstances[vox_instance.model_index].push_back(instanceIndex);
}
}
std::vector<OWLGroup> geomGroups;
geomGroups.reserve(scene->num_models);
std::vector<owl::affine3f> instanceTransforms;
instanceTransforms.reserve(scene->num_instances);
size_t totalSolidVoxelCount = 0;
size_t bottomLevelBvhSizeInBytes = 0;
// Make instance transforms
for (auto it : modelToInstances) {
const ogt_vox_model *vox_model = scene->models[it.first];
assert(vox_model);
std::vector<uchar4> voxdata = extractSolidVoxelsFromModel(vox_model);
LOG("building user geometry for model ...");
// ------------------------------------------------------------------
// set up user primitives for single vox model
// ------------------------------------------------------------------
OWLBuffer primBuffer
= allocator.deviceBufferCreate(context, OWL_UCHAR4, voxdata.size(), voxdata.data());
OWLGeom voxGeom = owlGeomCreate(context, voxGeomType);
owlGeomSetPrimCount(voxGeom, voxdata.size());
owlGeomSetBuffer(voxGeom, "prims", primBuffer);
owlGeomSetBuffer(voxGeom, "colorPalette", paletteBuffer);
owlGeomSet1b(voxGeom, "enableToonOutline", this->enableToonOutline);
// ------------------------------------------------------------------
// bottom level group/accel
// ------------------------------------------------------------------
OWLGroup userGeomGroup = owlUserGeomGroupCreate(context,1,&voxGeom);
owlGroupBuildAccel(userGeomGroup);
bottomLevelBvhSizeInBytes += getAccelSizeInBytes(userGeomGroup);
totalSolidVoxelCount += voxdata.size() * it.second.size();
LOG("adding (" << it.second.size() << ") instance transforms for model ...");
appendInstanceTransforms(scene, vox_model, it.second, instanceTransforms, sceneBox);
for (uint32_t instanceIndex : it.second) {
geomGroups.push_back(userGeomGroup);
}
}
LOG("Total solid voxels in all instanced models: " << totalSolidVoxelCount);
const vec3f sceneCenter = sceneBox.center();
const vec3f sceneSpan = sceneBox.span();
if (this->enableGround) {
// ------------------------------------------------------------------
// set up vox data and accels for ground (single stretched brick)
// ------------------------------------------------------------------
std::vector<uchar4> voxdata {make_uchar4(0,0,0, 249)}; // using color index of grey in default palette
OWLBuffer primBuffer
= allocator.deviceBufferCreate(context, OWL_UCHAR4, voxdata.size(), voxdata.data());
OWLGeom voxGeom = owlGeomCreate(context, voxGeomType);
owlGeomSetPrimCount(voxGeom, voxdata.size());
owlGeomSetBuffer(voxGeom, "prims", primBuffer);
owlGeomSetBuffer(voxGeom, "colorPalette", paletteBuffer);
owlGeomSet1b(voxGeom, "enableToonOutline", false); // no outline for ground because it's scaled
OWLGroup userGeomGroup = owlUserGeomGroupCreate(context,1,&voxGeom);
owlGroupBuildAccel(userGeomGroup);
bottomLevelBvhSizeInBytes += getAccelSizeInBytes(userGeomGroup);
geomGroups.push_back(userGeomGroup);
instanceTransforms.push_back(
owl::affine3f::translate(vec3f(sceneCenter.x, sceneCenter.y, sceneCenter.z - 1 - 0.5f*sceneSpan.z)) *
owl::affine3f::scale(vec3f(2*sceneSpan.x, 2*sceneSpan.y, 1.0f))* // assume Z up
owl::affine3f::translate(vec3f(-0.5f, -0.5f, 0.0f))
);
}
// Apply final scene transform so we can use the same camera for every scene
const float maxSpan = owl::reduce_max(sceneBox.span());
owl::affine3f worldTransform =
owl::affine3f::scale(2.0f/maxSpan) * // normalize
owl::affine3f::translate(vec3f(-sceneCenter.x, -sceneCenter.y, -sceneBox.lower.z)); // center about (x,y) origin ,with Z up to match MV
for (size_t i = 0; i < instanceTransforms.size(); ++i) {
instanceTransforms[i] = worldTransform * instanceTransforms[i];
}
OWLGroup world = owlInstanceGroupCreate(context, instanceTransforms.size(),
geomGroups.data(), nullptr, (const float*)instanceTransforms.data(), OWL_MATRIX_FORMAT_OWL);
owlGroupBuildAccel(world);
uint64_t topLevelBvhSizeInBytes = getAccelSizeInBytes(world);
logSceneMemory(bottomLevelBvhSizeInBytes, topLevelBvhSizeInBytes, allocator);
return world;
}
// User block scene type:
// * each small block of NxNxN bricks is a user prim.
// * otherwise the same as user scene type above.
OWLGroup Viewer::createUserBlocksGeometryScene(OWLModule module, const ogt_vox_scene *scene,
box3f &sceneBox)
{
BufferAllocator allocator;
// -------------------------------------------------------
// declare user vox geometry type
// -------------------------------------------------------
OWLVarDecl voxGeomVars[] = {
{ "prims", OWL_BUFPTR, OWL_OFFSETOF(VoxBlockGeomData,prims)},
{ "colorIndices", OWL_BUFPTR, OWL_OFFSETOF(VoxBlockGeomData,colorIndices)},
{ "colorPalette", OWL_BUFPTR, OWL_OFFSETOF(VoxBlockGeomData,colorPalette)},
{ /* sentinel to mark end of list */ }
};
OWLGeomType voxGeomType
= owlGeomTypeCreate(context,
OWL_GEOMETRY_USER,
sizeof(VoxBlockGeomData),
voxGeomVars, -1);
owlGeomTypeSetClosestHit(voxGeomType, 0, module, "VoxBlockGeom");
owlGeomTypeSetIntersectProg(voxGeomType, 0, module, "VoxBlockGeom");
owlGeomTypeSetIntersectProg(voxGeomType, 1, module, "VoxBlockGeomShadow");
owlGeomTypeSetBoundsProg(voxGeomType, module, "VoxBlockGeom");
// Do this before setting up user geometry, to compile bounds program
owlBuildPrograms(context);
assert(scene->num_instances > 0);
assert(scene->num_models > 0);
// Palette buffer is global to scene
OWLBuffer paletteBuffer
= allocator.deviceBufferCreate(context, OWL_UCHAR4, 256, scene->palette.color);
// Cluster instances together that use the same model
std::map<uint32_t, std::vector<uint32_t>> modelToInstances;
for (uint32_t instanceIndex = 0; instanceIndex < scene->num_instances; instanceIndex++) {
const ogt_vox_instance &vox_instance = scene->instances[instanceIndex];
if (!vox_instance.hidden) {
modelToInstances[vox_instance.model_index].push_back(instanceIndex);
}
}
std::vector<OWLGroup> geomGroups;
geomGroups.reserve(scene->num_models);
std::vector<owl::affine3f> instanceTransforms;
instanceTransforms.reserve(scene->num_instances);
size_t totalPrimCount = 0;
size_t bottomLevelBvhSizeInBytes = 0;
// Make instance transforms
for (auto it : modelToInstances) {
const ogt_vox_model *vox_model = scene->models[it.first];
assert(vox_model);
std::vector<uchar3> blockOrigins;
std::vector<unsigned char> colorIndices;
extractBlocksFromModel(vox_model, BLOCKLEN, blockOrigins, colorIndices);
LOG("building user blocks (dda " << BLOCKLEN << "x" << BLOCKLEN << "x" << BLOCKLEN << ") geometry for model ...");
// ------------------------------------------------------------------
// set up user primitives for single vox model
// ------------------------------------------------------------------
OWLBuffer primBuffer
= allocator.deviceBufferCreate(context, OWL_UCHAR3, blockOrigins.size(), blockOrigins.data());
OWLBuffer colorIndexBuffer
= allocator.deviceBufferCreate(context, OWL_UCHAR, colorIndices.size(), colorIndices.data());
OWLGeom voxGeom = owlGeomCreate(context, voxGeomType);
owlGeomSetPrimCount(voxGeom, blockOrigins.size());
owlGeomSetBuffer(voxGeom, "prims", primBuffer);
owlGeomSetBuffer(voxGeom, "colorIndices", colorIndexBuffer);
owlGeomSetBuffer(voxGeom, "colorPalette", paletteBuffer);
// ------------------------------------------------------------------
// bottom level group/accel
// ------------------------------------------------------------------
OWLGroup userGeomGroup = owlUserGeomGroupCreate(context,1,&voxGeom);
owlGroupBuildAccel(userGeomGroup);
bottomLevelBvhSizeInBytes += getAccelSizeInBytes(userGeomGroup);
totalPrimCount += blockOrigins.size() * it.second.size();
LOG("adding (" << it.second.size() << ") instance transforms for model ...");
appendInstanceTransforms(scene, vox_model, it.second, instanceTransforms, sceneBox);
for (uint32_t instanceIndex : it.second) {
geomGroups.push_back(userGeomGroup);
}
}
LOG("Total user prims in all instanced models: " << totalPrimCount);
const vec3f sceneCenter = sceneBox.center();
const vec3f sceneSpan = sceneBox.span();
if (this->enableGround) {
// ------------------------------------------------------------------
// set up block vox data and accels for ground (single stretched block)
// ------------------------------------------------------------------
std::vector<uchar3> blockOrigins {make_uchar3(0,0,0)};
std::vector<unsigned char> colorIndices(BLOCKLEN*BLOCKLEN*BLOCKLEN, 249);
OWLBuffer primBuffer
= allocator.deviceBufferCreate(context, OWL_UCHAR3, blockOrigins.size(), blockOrigins.data());
OWLBuffer colorIndexBuffer
= allocator.deviceBufferCreate(context, OWL_UCHAR, colorIndices.size(), colorIndices.data());
OWLGeom voxGeom = owlGeomCreate(context, voxGeomType);
owlGeomSetPrimCount(voxGeom, blockOrigins.size());
owlGeomSetBuffer(voxGeom, "prims", primBuffer);
owlGeomSetBuffer(voxGeom, "colorIndices", colorIndexBuffer);
owlGeomSetBuffer(voxGeom, "colorPalette", paletteBuffer);
OWLGroup userGeomGroup = owlUserGeomGroupCreate(context,1,&voxGeom);
owlGroupBuildAccel(userGeomGroup);
bottomLevelBvhSizeInBytes += getAccelSizeInBytes(userGeomGroup);
geomGroups.push_back(userGeomGroup);
instanceTransforms.push_back(
owl::affine3f::translate(vec3f(sceneCenter.x, sceneCenter.y, sceneCenter.z - 1 - 0.5f*sceneSpan.z)) *
owl::affine3f::scale(vec3f(2*sceneSpan.x/BLOCKLEN, 2*sceneSpan.y/BLOCKLEN, 1.0f/BLOCKLEN))* // assume Z up
owl::affine3f::translate(vec3f(-0.5f*BLOCKLEN, -0.5f*BLOCKLEN, 0.0f))
);
}
// Apply final scene transform so we can use the same camera for every scene
const float maxSpan = owl::reduce_max(sceneBox.span());
owl::affine3f worldTransform =
owl::affine3f::scale(2.0f/maxSpan) * // normalize
owl::affine3f::translate(vec3f(-sceneCenter.x, -sceneCenter.y, -sceneBox.lower.z)); // center about (x,y) origin ,with Z up to match MV
for (size_t i = 0; i < instanceTransforms.size(); ++i) {
instanceTransforms[i] = worldTransform * instanceTransforms[i];
}
OWLGroup world = owlInstanceGroupCreate(context, instanceTransforms.size(),
geomGroups.data(), nullptr, (const float*)instanceTransforms.data(), OWL_MATRIX_FORMAT_OWL);
owlGroupBuildAccel(world);
uint64_t topLevelBvhSizeInBytes = getAccelSizeInBytes(world);
logSceneMemory(bottomLevelBvhSizeInBytes, topLevelBvhSizeInBytes, allocator);
return world;
}
// Flat triangle scene type:
// * each vox model is a single flat triangle mesh.
// * vox instances are an OWL instance group
OWLGroup Viewer::createFlatTriangleGeometryScene(OWLModule module, const ogt_vox_scene *scene,
box3f &sceneBox )
{
BufferAllocator allocator;
// -------------------------------------------------------
// declare triangle-based box geometry type
// -------------------------------------------------------
OWLVarDecl trianglesGeomVars[] = {
{ "index", OWL_BUFPTR, OWL_OFFSETOF(TrianglesGeomData,index)},
{ "vertex", OWL_BUFPTR, OWL_OFFSETOF(TrianglesGeomData,vertex)},
{ "colorIndexPerBrick", OWL_BUFPTR, OWL_OFFSETOF(TrianglesGeomData,colorIndexPerBrick)},
{ "colorPalette", OWL_BUFPTR, OWL_OFFSETOF(TrianglesGeomData,colorPalette)},
{ "primCountPerBrick", OWL_INT, OWL_OFFSETOF(TrianglesGeomData,primCountPerBrick)},
{ /* sentinel to mark end of list */ }
};
OWLGeomType trianglesGeomType
= owlGeomTypeCreate(context,
OWL_TRIANGLES,
sizeof(TrianglesGeomData),
trianglesGeomVars,-1);
owlGeomTypeSetClosestHit(trianglesGeomType,0,
module,"TriangleMesh");
assert(scene->num_instances > 0);
assert(scene->num_models > 0);
// Palette buffer is global to scene
OWLBuffer paletteBuffer
= allocator.deviceBufferCreate(context, OWL_UCHAR4, 256, scene->palette.color);
// Cluster instances together that use the same model
std::map<uint32_t, std::vector<uint32_t>> modelToInstances;
for (uint32_t instanceIndex = 0; instanceIndex < scene->num_instances; instanceIndex++) {
const ogt_vox_instance &vox_instance = scene->instances[instanceIndex];
if (!vox_instance.hidden) {
modelToInstances[vox_instance.model_index].push_back(instanceIndex);
}
}
std::vector<OWLGroup> geomGroups;
geomGroups.reserve(scene->num_models);
std::vector<owl::affine3f> instanceTransforms;
instanceTransforms.reserve(scene->num_instances);
size_t totalSolidVoxelCount = 0;
size_t bottomLevelBvhSizeInBytes = 0;
// Make instance transforms
for (auto it : modelToInstances) {
const ogt_vox_model *vox_model = scene->models[it.first];
assert(vox_model);
std::vector<uchar4> voxdata = extractSolidVoxelsFromModel(vox_model);
LOG("building flat triangle geometry for model ...");
std::vector<vec3f> meshVertices;
meshVertices.reserve(voxdata.size() * NUM_BRICK_VERTICES); // worst case
std::vector<vec3i> meshIndices;
meshIndices.reserve(voxdata.size() * NUM_BRICK_FACES);
std::vector<unsigned char> colorIndicesPerBrick;
colorIndicesPerBrick.reserve(voxdata.size());
// Share vertices between voxels to save a little memory. Only works for simple brick.
constexpr bool SHARE_BRICK_VERTICES = (NUM_BRICK_VERTICES == 8 && NUM_BRICK_FACES == 12);
std::map<std::tuple<int, int, int>, int> brickVertexToMeshVertexIndex;
// Build mesh in object space where each brick is 1x1x1
std::vector<int> indexRemap(NUM_BRICK_VERTICES); // local brick vertex --> flat mesh vertex
for (uchar4 voxel : voxdata) {
const vec3i brickTranslation(voxel.x, voxel.y, voxel.z);
for (int i = 0; i < NUM_BRICK_VERTICES; ++i) {
const vec3f &v = brickVertices[i];
std::tuple<int,int,int> brickVertex = std::make_tuple(
brickTranslation.x + int(v.x),
brickTranslation.y + int(v.y),
brickTranslation.z + int(v.z));
int vertexIndexInMesh = -1;
if (SHARE_BRICK_VERTICES) {
const auto it = brickVertexToMeshVertexIndex.find(brickVertex);
if (it != brickVertexToMeshVertexIndex.end()) {
vertexIndexInMesh = it->second;
} else {
meshVertices.push_back(vec3f(brickTranslation) + v);
vertexIndexInMesh = int(meshVertices.size())-1;
brickVertexToMeshVertexIndex[brickVertex] = vertexIndexInMesh;
}
} else {
// do not share vertices
meshVertices.push_back(vec3f(brickTranslation) + v);
vertexIndexInMesh = int(meshVertices.size())-1;
}
indexRemap[i] = vertexIndexInMesh; // brick vertex -> flat mesh vertex
}
for (const vec3i &index : brickIndices) {
vec3i face(indexRemap[index.x], indexRemap[index.y], indexRemap[index.z]);
meshIndices.push_back(face);
}
colorIndicesPerBrick.push_back(voxel.w);
}
LOG("Mesh vertex count: " << meshVertices.size());
LOG("Mesh face count: " << meshIndices.size());
OWLBuffer vertexBuffer
= allocator.deviceBufferCreate(context, OWL_FLOAT3, meshVertices.size(), meshVertices.data());
OWLBuffer indexBuffer
= allocator.deviceBufferCreate(context, OWL_INT3, meshIndices.size(), meshIndices.data());
OWLGeom trianglesGeom = owlGeomCreate(context, trianglesGeomType);
owlTrianglesSetVertices(trianglesGeom, vertexBuffer, meshVertices.size(), sizeof(vec3f), 0);
owlTrianglesSetIndices(trianglesGeom, indexBuffer, meshIndices.size(), sizeof(vec3i), 0);
owlGeomSetBuffer(trianglesGeom, "vertex", vertexBuffer);
owlGeomSetBuffer(trianglesGeom, "index", indexBuffer);
owlGeomSetBuffer(trianglesGeom, "colorPalette", paletteBuffer);
owlGeomSet1i(trianglesGeom, "primCountPerBrick", NUM_BRICK_FACES);
OWLBuffer colorIndexBuffer
= allocator.deviceBufferCreate(context, OWL_UCHAR, colorIndicesPerBrick.size(), colorIndicesPerBrick.data());
owlGeomSetBuffer(trianglesGeom, "colorIndexPerBrick", colorIndexBuffer);
// ------------------------------------------------------------------
// the group/accel for the model
// ------------------------------------------------------------------
OWLGroup trianglesGroup = owlTrianglesGeomGroupCreate(context, 1, &trianglesGeom);
owlGroupBuildAccel(trianglesGroup);
bottomLevelBvhSizeInBytes += getAccelSizeInBytes(trianglesGroup);
totalSolidVoxelCount += voxdata.size() * it.second.size();
LOG("adding (" << it.second.size() << ") instance transforms for model ...");
appendInstanceTransforms(scene, vox_model, it.second, instanceTransforms, sceneBox);
for (uint32_t instanceIndex : it.second) {
geomGroups.push_back(trianglesGroup);
}
}
LOG("Total solid voxels in all instanced models: " << totalSolidVoxelCount);
const vec3f sceneCenter = sceneBox.center();
const vec3f sceneSpan = sceneBox.span();
if (this->enableGround) {
// Extra scaled brick for ground plane
OWLBuffer vertexBuffer
= allocator.deviceBufferCreate(context,OWL_FLOAT3,NUM_BRICK_VERTICES,brickVertices);
OWLBuffer indexBuffer
= allocator.deviceBufferCreate(context,OWL_INT3,NUM_BRICK_FACES,brickIndices);
OWLGeom trianglesGeom
= owlGeomCreate(context,trianglesGeomType);
owlTrianglesSetVertices(trianglesGeom,vertexBuffer,
NUM_BRICK_VERTICES,sizeof(vec3f),0);
owlTrianglesSetIndices(trianglesGeom,indexBuffer,
NUM_BRICK_FACES,sizeof(vec3i),0);
owlGeomSetBuffer(trianglesGeom,"vertex",vertexBuffer);
owlGeomSetBuffer(trianglesGeom,"index",indexBuffer);
owlGeomSetBuffer(trianglesGeom, "colorPalette", paletteBuffer);
owlGeomSet1i(trianglesGeom, "primCountPerBrick", NUM_BRICK_FACES);
std::vector<unsigned char> colorIndicesPerBrick = {249}; // grey in default palette
OWLBuffer colorIndexBuffer
= allocator.deviceBufferCreate(context, OWL_UCHAR, colorIndicesPerBrick.size(), colorIndicesPerBrick.data());
owlGeomSetBuffer(trianglesGeom, "colorIndexPerBrick", colorIndexBuffer);
OWLGroup trianglesGroup
= owlTrianglesGeomGroupCreate(context,1,&trianglesGeom);
owlGroupBuildAccel(trianglesGroup);
bottomLevelBvhSizeInBytes += getAccelSizeInBytes(trianglesGroup);
geomGroups.push_back(trianglesGroup);
instanceTransforms.push_back(
owl::affine3f::translate(vec3f(sceneCenter.x, sceneCenter.y, sceneCenter.z - 1 - 0.5f*sceneSpan.z)) *
owl::affine3f::scale(vec3f(2*sceneSpan.x, 2*sceneSpan.y, 1.0f))* // assume Z up
owl::affine3f::translate(vec3f(-0.5f, -0.5f, 0.0f))
);
}
// Apply final scene transform so we can use the same camera for every scene
const float maxSpan = owl::reduce_max(sceneBox.span());
owl::affine3f worldTransform =
owl::affine3f::scale(2.0f/maxSpan) * // normalize
owl::affine3f::translate(vec3f(-sceneCenter.x, -sceneCenter.y, -sceneBox.lower.z)); // center about (x,y) origin ,with Z up to match MV
for (size_t i = 0; i < instanceTransforms.size(); ++i) {
instanceTransforms[i] = worldTransform * instanceTransforms[i];
}
OWLGroup world = owlInstanceGroupCreate(context,
instanceTransforms.size(),
geomGroups.data(),
/*instanceIds*/ nullptr,
(const float*)instanceTransforms.data(), OWL_MATRIX_FORMAT_OWL);
owlGroupBuildAccel(world);
uint64_t topLevelBvhSizeInBytes = getAccelSizeInBytes(world);
logSceneMemory(bottomLevelBvhSizeInBytes, topLevelBvhSizeInBytes, allocator);
return world;
}
// Instanced triangle scene type:
// * there is only 1 brick geom group for the entire scene. That brick is made of triangles.
// * vox models and instances are flattened into a single OWL instance group with many transforms
// (i.e., in a simple vox file, the OWL scene would have a transform per opaque voxel)
OWLGroup Viewer::createInstancedTriangleGeometryScene(OWLModule module, const ogt_vox_scene *scene,
owl::box3f &sceneBox)
{
BufferAllocator allocator;
// -------------------------------------------------------
// declare triangle-based box geometry type
// -------------------------------------------------------
OWLVarDecl trianglesGeomVars[] = {
{ "index", OWL_BUFPTR, OWL_OFFSETOF(TrianglesGeomData,index)},
{ "vertex", OWL_BUFPTR, OWL_OFFSETOF(TrianglesGeomData,vertex)},
{ "colorIndexPerBrick", OWL_BUFPTR, OWL_OFFSETOF(TrianglesGeomData,colorIndexPerBrick)},
{ "colorPalette", OWL_BUFPTR, OWL_OFFSETOF(TrianglesGeomData,colorPalette)},
{ /* sentinel to mark end of list */ }
};
OWLGeomType trianglesGeomType
= owlGeomTypeCreate(context,
OWL_TRIANGLES,
sizeof(TrianglesGeomData),
trianglesGeomVars,-1);
owlGeomTypeSetClosestHit(trianglesGeomType,0,
module,"InstancedTriangleMesh");
LOG("building triangle geometry for single brick ...");
// ------------------------------------------------------------------
// triangle mesh for single unit brick
// ------------------------------------------------------------------
OWLBuffer vertexBuffer
= allocator.deviceBufferCreate(context,OWL_FLOAT3,NUM_BRICK_VERTICES,brickVertices);
OWLBuffer indexBuffer
= allocator.deviceBufferCreate(context,OWL_INT3,NUM_BRICK_FACES,brickIndices);
OWLGeom trianglesGeom
= owlGeomCreate(context,trianglesGeomType);
owlTrianglesSetVertices(trianglesGeom,vertexBuffer,
NUM_BRICK_VERTICES,sizeof(vec3f),0);
owlTrianglesSetIndices(trianglesGeom,indexBuffer,
NUM_BRICK_FACES,sizeof(vec3i),0);
owlGeomSetBuffer(trianglesGeom,"vertex",vertexBuffer);
owlGeomSetBuffer(trianglesGeom,"index",indexBuffer);
OWLBuffer paletteBuffer
= allocator.deviceBufferCreate(context, OWL_UCHAR4, 256, scene->palette.color);
owlGeomSetBuffer(trianglesGeom, "colorPalette", paletteBuffer);
// ------------------------------------------------------------------
// the group/accel for the one brick
// ------------------------------------------------------------------
OWLGroup trianglesGroup
= owlTrianglesGeomGroupCreate(context,1,&trianglesGeom);
owlGroupBuildAccel(trianglesGroup);
uint64_t bottomLevelBvhSizeInBytes = getAccelSizeInBytes(trianglesGroup);
// ------------------------------------------------------------------
// instance the brick for each Vox model in the scene, flattening all Vox instance transforms
// ------------------------------------------------------------------
LOG("building instances ...");