forked from LWJGL/lwjgl3-demos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SdfBricks.java
1767 lines (1649 loc) · 89 KB
/
SdfBricks.java
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
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.demo.vulkan.raytracing;
import static java.lang.ClassLoader.getSystemResourceAsStream;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;
import static org.joml.Math.*;
import static org.lwjgl.demo.vulkan.VKUtil.*;
import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.glfw.GLFWVulkan.*;
import static org.lwjgl.system.MemoryStack.stackPush;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.util.vma.Vma.*;
import static org.lwjgl.vulkan.EXTDebugUtils.*;
import static org.lwjgl.vulkan.EXTDescriptorIndexing.*;
import static org.lwjgl.vulkan.EXTScalarBlockLayout.*;
import static org.lwjgl.vulkan.KHRAccelerationStructure.*;
import static org.lwjgl.vulkan.KHRBufferDeviceAddress.*;
import static org.lwjgl.vulkan.KHRDeferredHostOperations.VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME;
import static org.lwjgl.vulkan.KHRRayTracingPipeline.*;
import static org.lwjgl.vulkan.KHRShaderFloatControls.VK_KHR_SHADER_FLOAT_CONTROLS_EXTENSION_NAME;
import static org.lwjgl.vulkan.KHRSpirv14.VK_KHR_SPIRV_1_4_EXTENSION_NAME;
import static org.lwjgl.vulkan.KHRSurface.*;
import static org.lwjgl.vulkan.KHRSwapchain.*;
import static org.lwjgl.vulkan.VK11.*;
import java.io.*;
import java.nio.*;
import java.util.*;
import java.util.function.Consumer;
import org.joml.*;
import org.lwjgl.PointerBuffer;
import org.lwjgl.demo.util.*;
import org.lwjgl.demo.util.MagicaVoxelLoader.Material;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.system.*;
import org.lwjgl.util.vma.*;
import org.lwjgl.vulkan.*;
/**
* Renders brick models using signed distance functions together with ray tracing / spatial acceleration structure.
* <p>
* The bricks are procedural AABB geometries in a Vulkan ray tracing acceleration structure and the SDF of
* a possibly repeated cube is evaluated in an intersection shader.
* <p>
* One AABB geometry can represent multiple bricks.
*
* @author Kai Burjack
*/
public class SdfBricks {
private static final boolean DEBUG = Boolean.parseBoolean(System.getProperty("debug", "true"));
static {
if (DEBUG) {
// When we are in debug mode, enable all LWJGL debug flags
Configuration.DEBUG.set(true);
Configuration.DEBUG_FUNCTIONS.set(true);
Configuration.DEBUG_LOADER.set(true);
Configuration.DEBUG_MEMORY_ALLOCATOR.set(true);
Configuration.DEBUG_MEMORY_ALLOCATOR_FAST.set(true);
Configuration.DEBUG_STACK.set(true);
} else {
Configuration.DISABLE_CHECKS.set(true);
}
}
private static WindowAndCallbacks windowAndCallbacks;
private static VkInstance instance;
private static long surface;
private static DebugCallbackAndHandle debugCallbackHandle;
private static DeviceAndQueueFamilies deviceAndQueueFamilies;
private static int queueFamily;
private static VkDevice device;
private static long vmaAllocator;
private static VkQueue queue;
private static Swapchain swapchain;
private static long commandPool, commandPoolTransient;
private static VkCommandBuffer[] commandBuffers;
private static long[] imageAcquireSemaphores;
private static long[] renderCompleteSemaphores;
private static long[] renderFences;
private static final Map<Long, Runnable> waitingFenceActions = new HashMap<>();
private static Geometry geometry;
private static AccelerationStructure blas, tlas;
private static RayTracingPipeline rayTracingPipeline;
private static AllocationAndBuffer[] rayTracingUbos;
private static AllocationAndBuffer sbt;
private static DescriptorSets rayTracingDescriptorSets;
private static final Matrix4f projMatrix = new Matrix4f();
private static final Matrix4x3f viewMatrix = new Matrix4x3f().setLookAt(-40, 50, 140, 90, -10, 40, 0, 1, 0);
private static final Matrix4f invProjMatrix = new Matrix4f();
private static final Matrix4x3f invViewMatrix = new Matrix4x3f();
private static final Vector3f tmpv3 = new Vector3f();
private static final boolean[] keydown = new boolean[GLFW_KEY_LAST + 1];
private static boolean mouseDown;
private static int mouseX, mouseY;
private static void onCursorPos(long window, double x, double y) {
if (mouseDown) {
float deltaX = (float) x - mouseX;
float deltaY = (float) y - mouseY;
viewMatrix.rotateLocalY(deltaX * 0.004f);
viewMatrix.rotateLocalX(deltaY * 0.004f);
}
mouseX = (int) x;
mouseY = (int) y;
}
private static void onKey(long window, int key, int scancode, int action, int mods) {
if (key == GLFW_KEY_ESCAPE)
glfwSetWindowShouldClose(window, true);
if (key >= 0)
keydown[key] = action == GLFW_PRESS || action == GLFW_REPEAT;
}
private static void onMouseButton(long window, int button, int action, int mods) {
mouseDown = action == GLFW_PRESS;
}
private static void registerWindowCallbacks(long window) {
glfwSetKeyCallback(window, SdfBricks::onKey);
glfwSetCursorPosCallback(window, SdfBricks::onCursorPos);
glfwSetMouseButtonCallback(window, SdfBricks::onMouseButton);
}
private static class WindowAndCallbacks {
private final long window;
private int width;
private int height;
private WindowAndCallbacks(long window, int width, int height) {
this.window = window;
this.width = width;
this.height = height;
}
private void free() {
glfwFreeCallbacks(window);
glfwDestroyWindow(window);
}
}
private static class DebugCallbackAndHandle {
private final long messengerHandle;
private final VkDebugUtilsMessengerCallbackEXT callback;
private DebugCallbackAndHandle(long handle, VkDebugUtilsMessengerCallbackEXT callback) {
this.messengerHandle = handle;
this.callback = callback;
}
private void free() {
vkDestroyDebugUtilsMessengerEXT(instance, messengerHandle, null);
callback.free();
}
}
private static class QueueFamilies {
private final List<Integer> computeFamilies = new ArrayList<>();
private final List<Integer> presentFamilies = new ArrayList<>();
private int findSingleSuitableQueue() {
return computeFamilies
.stream()
.filter(presentFamilies::contains)
.findAny()
.orElseThrow(() -> new AssertionError("No suitable queue found"));
}
}
private static class DeviceAndQueueFamilies {
private final VkPhysicalDevice physicalDevice;
private final QueueFamilies queuesFamilies;
private final int shaderGroupBaseAlignment;
private final int minAccelerationStructureScratchOffsetAlignment;
private DeviceAndQueueFamilies(VkPhysicalDevice physicalDevice, QueueFamilies queuesFamilies,
int shaderGroupBaseAlignment,
int minAccelerationStructureScratchOffsetAlignment) {
this.physicalDevice = physicalDevice;
this.queuesFamilies = queuesFamilies;
this.shaderGroupBaseAlignment = shaderGroupBaseAlignment;
this.minAccelerationStructureScratchOffsetAlignment = minAccelerationStructureScratchOffsetAlignment;
}
}
private static class ColorFormatAndSpace {
private final int colorFormat;
private final int colorSpace;
private ColorFormatAndSpace(int colorFormat, int colorSpace) {
this.colorFormat = colorFormat;
this.colorSpace = colorSpace;
}
}
private static class Swapchain {
private final long swapchain;
private final long[] images;
private final long[] imageViews;
private final int width, height;
private Swapchain(long swapchain, long[] images, long[] imageViews, int width, int height) {
this.swapchain = swapchain;
this.images = images;
this.imageViews = imageViews;
this.width = width;
this.height = height;
}
private void free() {
vkDestroySwapchainKHR(device, swapchain, null);
for (long imageView : imageViews)
vkDestroyImageView(device, imageView, null);
}
}
private static class RayTracingPipeline {
private final long pipelineLayout;
private final long descriptorSetLayout;
private final long pipeline;
private RayTracingPipeline(long pipelineLayout, long descriptorSetLayout, long pipeline) {
this.pipelineLayout = pipelineLayout;
this.descriptorSetLayout = descriptorSetLayout;
this.pipeline = pipeline;
}
private void free() {
vkDestroyPipelineLayout(device, pipelineLayout, null);
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, null);
vkDestroyPipeline(device, pipeline, null);
}
}
private static class DescriptorSets {
private final long descriptorPool;
private final long[] sets;
private DescriptorSets(long descriptorPool, long[] sets) {
this.descriptorPool = descriptorPool;
this.sets = sets;
}
private void free() {
vkDestroyDescriptorPool(device, descriptorPool, null);
}
}
private static PointerBuffer pointers(MemoryStack stack, PointerBuffer pts, ByteBuffer... pointers) {
PointerBuffer res = stack.mallocPointer(pts.remaining() + pointers.length);
res.put(pts);
for (ByteBuffer pointer : pointers) {
res.put(pointer);
}
res.flip();
return res;
}
private static List<String> enumerateSupportedInstanceExtensions() {
try (MemoryStack stack = stackPush()) {
IntBuffer pPropertyCount = stack.mallocInt(1);
_CHECK_(vkEnumerateInstanceExtensionProperties((ByteBuffer) null, pPropertyCount, null),
"Could not enumerate number of instance extensions");
int propertyCount = pPropertyCount.get(0);
VkExtensionProperties.Buffer pProperties = VkExtensionProperties.malloc(propertyCount, stack);
_CHECK_(vkEnumerateInstanceExtensionProperties((ByteBuffer) null, pPropertyCount, pProperties),
"Could not enumerate instance extensions");
return pProperties.stream().map(VkExtensionProperties::extensionNameString).collect(toList());
}
}
private static VkInstance createInstance(PointerBuffer requiredExtensions) {
List<String> supportedInstanceExtensions = enumerateSupportedInstanceExtensions();
try (MemoryStack stack = stackPush()) {
PointerBuffer ppEnabledExtensionNames = requiredExtensions;
if (DEBUG) {
if (!supportedInstanceExtensions.contains(VK_EXT_DEBUG_UTILS_EXTENSION_NAME)) {
throw new AssertionError(VK_EXT_DEBUG_UTILS_EXTENSION_NAME + " is not supported on the instance");
}
ppEnabledExtensionNames = pointers(stack, requiredExtensions, stack.UTF8(VK_EXT_DEBUG_UTILS_EXTENSION_NAME));
}
PointerBuffer ppEnabledLayerNames = null;
if (DEBUG) {
List<String> supportedLayers = enumerateSupportedInstanceLayers();
if (!supportedLayers.contains("VK_LAYER_KHRONOS_validation")) {
System.err.println("DEBUG requested but layer VK_LAYER_KHRONOS_validation is unavailable. Install the Vulkan SDK for your platform. Vulkan debug layer will not be used.");
} else {
ppEnabledLayerNames = stack.pointers(stack.UTF8("VK_LAYER_KHRONOS_validation"));
}
}
VkInstanceCreateInfo pCreateInfo = VkInstanceCreateInfo
.calloc(stack)
.sType$Default()
.pApplicationInfo(VkApplicationInfo
.calloc(stack)
.sType$Default()
.apiVersion(VK_API_VERSION_1_1))
.ppEnabledLayerNames(ppEnabledLayerNames)
.ppEnabledExtensionNames(ppEnabledExtensionNames);
PointerBuffer pInstance = stack.mallocPointer(1);
_CHECK_(vkCreateInstance(pCreateInfo, null, pInstance), "Failed to create VkInstance");
return new VkInstance(pInstance.get(0), pCreateInfo);
}
}
private static PointerBuffer initGlfwAndReturnRequiredExtensions() {
if (!glfwInit())
throw new AssertionError("Failed to initialize GLFW");
if (!glfwVulkanSupported())
throw new AssertionError("GLFW failed to find the Vulkan loader");
PointerBuffer requiredExtensions = glfwGetRequiredInstanceExtensions();
if (requiredExtensions == null)
throw new AssertionError("Failed to find list of required Vulkan extensions");
return requiredExtensions;
}
private static WindowAndCallbacks createWindow() {
glfwDefaultWindowHints();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
GLFWVidMode mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
long window = glfwCreateWindow(mode.width(), mode.height(), "Hello, SDF bricks!", NULL, NULL);
registerWindowCallbacks(window);
int w, h;
try (MemoryStack stack = stackPush()) {
IntBuffer addr = stack.mallocInt(2);
nglfwGetFramebufferSize(window, memAddress(addr), memAddress(addr) + Integer.BYTES);
w = addr.get(0);
h = addr.get(1);
}
return new WindowAndCallbacks(window, w, h);
}
private static long createSurface() {
try (MemoryStack stack = stackPush()) {
LongBuffer surface = stack.mallocLong(1);
_CHECK_(glfwCreateWindowSurface(instance, windowAndCallbacks.window, null, surface), "Failed to create surface");
return surface.get(0);
}
}
private static DebugCallbackAndHandle setupDebugging() {
if (!DEBUG) {
return null;
}
VkDebugUtilsMessengerCallbackEXT callback = new VkDebugUtilsMessengerCallbackEXT() {
public int invoke(int messageSeverity, int messageTypes, long pCallbackData, long pUserData) {
VkDebugUtilsMessengerCallbackDataEXT message = VkDebugUtilsMessengerCallbackDataEXT.create(pCallbackData);
System.err.println(message.pMessageString());
return 0;
}
};
try (MemoryStack stack = stackPush()) {
LongBuffer pMessenger = stack.mallocLong(1);
_CHECK_(vkCreateDebugUtilsMessengerEXT(instance,
VkDebugUtilsMessengerCreateInfoEXT
.calloc(stack)
.sType$Default()
.messageSeverity(VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT)
.messageType(VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT)
.pfnUserCallback(callback),
null, pMessenger),
"Failed to create debug messenger");
return new DebugCallbackAndHandle(pMessenger.get(0), callback);
}
}
private static boolean familySupports(VkQueueFamilyProperties prop, int bit) {
return (prop.queueFlags() & bit) != 0;
}
private static QueueFamilies obtainQueueFamilies(VkPhysicalDevice physicalDevice) {
QueueFamilies ret = new QueueFamilies();
try (MemoryStack stack = stackPush()) {
IntBuffer pQueueFamilyPropertyCount = stack.mallocInt(1);
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount, null);
int numQueueFamilies = pQueueFamilyPropertyCount.get(0);
if (numQueueFamilies == 0)
throw new AssertionError("No queue families found");
VkQueueFamilyProperties.Buffer familyProperties = VkQueueFamilyProperties.malloc(numQueueFamilies, stack);
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount, familyProperties);
int queueFamilyIndex = 0;
IntBuffer pSupported = stack.mallocInt(1);
for (VkQueueFamilyProperties queueFamilyProps : familyProperties) {
if (queueFamilyProps.queueCount() < 1) {
continue;
}
vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, queueFamilyIndex, surface, pSupported);
// we need compute for acceleration structure build and ray tracing commands.
// we will also use this for vkCmdCopyBuffer
if (familySupports(queueFamilyProps, VK_QUEUE_COMPUTE_BIT))
ret.computeFamilies.add(queueFamilyIndex);
// we also need present
if (pSupported.get(0) != 0)
ret.presentFamilies.add(queueFamilyIndex);
queueFamilyIndex++;
}
return ret;
}
}
private static boolean isDeviceSuitable(QueueFamilies queuesFamilies) {
return !queuesFamilies.computeFamilies.isEmpty() && !queuesFamilies.presentFamilies.isEmpty();
}
private static DeviceAndQueueFamilies selectPhysicalDevice() {
try (MemoryStack stack = stackPush()) {
// Retrieve number of available physical devices
IntBuffer pPhysicalDeviceCount = stack.mallocInt(1);
_CHECK_(vkEnumeratePhysicalDevices(instance, pPhysicalDeviceCount, null),
"Failed to get number of physical devices");
int physicalDeviceCount = pPhysicalDeviceCount.get(0);
if (physicalDeviceCount == 0)
throw new AssertionError("No physical devices available");
// Retrieve pointers to all available physical devices
PointerBuffer pPhysicalDevices = stack.mallocPointer(physicalDeviceCount);
_CHECK_(vkEnumeratePhysicalDevices(instance, pPhysicalDeviceCount, pPhysicalDevices),
"Failed to get physical devices");
// and enumerate them to see which one we will use...
for (int i = 0; i < physicalDeviceCount; i++) {
VkPhysicalDevice dev = new VkPhysicalDevice(pPhysicalDevices.get(i), instance);
// Check if the device supports all needed features
VkPhysicalDeviceScalarBlockLayoutFeaturesEXT scalarBlockLayoutFeatures = VkPhysicalDeviceScalarBlockLayoutFeaturesEXT
.malloc(stack)
.sType$Default();
VkPhysicalDeviceAccelerationStructureFeaturesKHR accelerationStructureFeatures = VkPhysicalDeviceAccelerationStructureFeaturesKHR
.malloc(stack)
.sType$Default();
VkPhysicalDeviceRayTracingPipelineFeaturesKHR rayTracingPipelineFeatures = VkPhysicalDeviceRayTracingPipelineFeaturesKHR
.malloc(stack)
.sType$Default();
VkPhysicalDeviceBufferDeviceAddressFeaturesKHR bufferDeviceAddressFeatures = VkPhysicalDeviceBufferDeviceAddressFeaturesKHR
.malloc(stack)
.sType$Default();
vkGetPhysicalDeviceFeatures2(dev, VkPhysicalDeviceFeatures2
.calloc(stack)
.sType$Default()
.pNext(bufferDeviceAddressFeatures)
.pNext(rayTracingPipelineFeatures)
.pNext(accelerationStructureFeatures)
.pNext(scalarBlockLayoutFeatures));
// If any of the above is not supported, we continue with the next physical device
if (!bufferDeviceAddressFeatures.bufferDeviceAddress() ||
!rayTracingPipelineFeatures.rayTracingPipeline() ||
!accelerationStructureFeatures.accelerationStructure() ||
!scalarBlockLayoutFeatures.scalarBlockLayout())
continue;
// Check if the physical device supports the VK_FORMAT_R32G32B32_SFLOAT vertexFormat for acceleration structure geometry
VkFormatProperties formatProperties = VkFormatProperties.malloc(stack);
vkGetPhysicalDeviceFormatProperties(dev, VK_FORMAT_R32G32B32_SFLOAT, formatProperties);
if ((formatProperties.bufferFeatures() & VK_FORMAT_FEATURE_ACCELERATION_STRUCTURE_VERTEX_BUFFER_BIT_KHR) == 0)
continue;
// Retrieve physical device properties (limits, offsets, alignments, ...)
VkPhysicalDeviceAccelerationStructurePropertiesKHR accelerationStructureProperties = VkPhysicalDeviceAccelerationStructurePropertiesKHR
.malloc(stack)
.sType$Default();
VkPhysicalDeviceRayTracingPipelinePropertiesKHR rayTracingProperties = VkPhysicalDeviceRayTracingPipelinePropertiesKHR
.malloc(stack)
.sType$Default();
vkGetPhysicalDeviceProperties2(dev, VkPhysicalDeviceProperties2
.calloc(stack)
.sType$Default()
.pNext(rayTracingProperties)
.pNext(accelerationStructureProperties));
// Check queue families
QueueFamilies queuesFamilies = obtainQueueFamilies(dev);
if (isDeviceSuitable(queuesFamilies)) {
return new DeviceAndQueueFamilies(dev, queuesFamilies,
rayTracingProperties.shaderGroupBaseAlignment(),
accelerationStructureProperties.minAccelerationStructureScratchOffsetAlignment());
}
}
throw new AssertionError("No suitable physical device found");
}
}
private static List<String> enumerateSupportedInstanceLayers() {
try (MemoryStack stack = stackPush()) {
IntBuffer pPropertyCount = stack.mallocInt(1);
vkEnumerateInstanceLayerProperties(pPropertyCount, null);
int count = pPropertyCount.get(0);
if (count > 0) {
VkLayerProperties.Buffer pProperties = VkLayerProperties.malloc(count, stack);
vkEnumerateInstanceLayerProperties(pPropertyCount, pProperties);
return pProperties.stream().map(VkLayerProperties::layerNameString).collect(toList());
}
}
return emptyList();
}
private static VkDevice createDevice(List<String> requiredExtensions) {
List<String> supportedDeviceExtensions = enumerateSupportedDeviceExtensions();
for (String requiredExtension : requiredExtensions) {
if (!supportedDeviceExtensions.contains(requiredExtension))
throw new AssertionError(requiredExtension + " device extension is not supported");
}
try (MemoryStack stack = stackPush()) {
PointerBuffer extensions = stack.mallocPointer(requiredExtensions.size());
for (String requiredExtension : requiredExtensions)
extensions.put(stack.UTF8(requiredExtension));
extensions.flip();
PointerBuffer ppEnabledLayerNames = null;
if (DEBUG) {
ppEnabledLayerNames = stack.pointers(stack.UTF8("VK_LAYER_KHRONOS_validation"));
}
VkDeviceCreateInfo pCreateInfo = VkDeviceCreateInfo
.calloc(stack)
.sType$Default()
.pNext(VkPhysicalDeviceRayTracingPipelineFeaturesKHR
.calloc(stack)
.sType$Default()
.rayTracingPipeline(true))
.pNext(VkPhysicalDeviceAccelerationStructureFeaturesKHR
.calloc(stack)
.sType$Default()
.accelerationStructure(true))
.pNext(VkPhysicalDeviceBufferDeviceAddressFeaturesKHR
.calloc(stack)
.sType$Default()
.bufferDeviceAddress(true))
.pNext(VkPhysicalDeviceScalarBlockLayoutFeaturesEXT
.calloc(stack)
.sType$Default()
.scalarBlockLayout(true))
.pQueueCreateInfos(VkDeviceQueueCreateInfo
.calloc(1, stack)
.sType$Default()
.queueFamilyIndex(queueFamily)
.pQueuePriorities(stack.floats(1.0f)))
.ppEnabledLayerNames(ppEnabledLayerNames)
.ppEnabledExtensionNames(extensions);
PointerBuffer pDevice = stack.mallocPointer(1);
_CHECK_(vkCreateDevice(deviceAndQueueFamilies.physicalDevice, pCreateInfo, null, pDevice),
"Failed to create device");
return new VkDevice(pDevice.get(0), deviceAndQueueFamilies.physicalDevice, pCreateInfo, VK_API_VERSION_1_1);
}
}
private static List<String> enumerateSupportedDeviceExtensions() {
try (MemoryStack stack = stackPush()) {
IntBuffer pPropertyCount = stack.mallocInt(1);
_CHECK_(vkEnumerateDeviceExtensionProperties(deviceAndQueueFamilies.physicalDevice, (ByteBuffer) null, pPropertyCount, null),
"Failed to get number of device extensions");
int propertyCount = pPropertyCount.get(0);
VkExtensionProperties.Buffer pProperties = VkExtensionProperties.malloc(propertyCount, stack);
_CHECK_(vkEnumerateDeviceExtensionProperties(deviceAndQueueFamilies.physicalDevice, (ByteBuffer) null, pPropertyCount, pProperties),
"Failed to enumerate the device extensions");
return pProperties.stream().map(VkExtensionProperties::extensionNameString).collect(toList());
}
}
private static long createVmaAllocator() {
try (MemoryStack stack = stackPush()) {
PointerBuffer pAllocator = stack.mallocPointer(1);
_CHECK_(vmaCreateAllocator(VmaAllocatorCreateInfo
.calloc(stack)
.flags(VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT)
.physicalDevice(deviceAndQueueFamilies.physicalDevice)
.device(device)
.pVulkanFunctions(VmaVulkanFunctions
.calloc(stack)
.set(instance, device))
.instance(instance)
.vulkanApiVersion(VK_API_VERSION_1_1), pAllocator),
"Failed to create VMA allocator");
return pAllocator.get(0);
}
}
private static VkQueue retrieveQueue() {
try (MemoryStack stack = stackPush()) {
PointerBuffer pQueue = stack.mallocPointer(1);
vkGetDeviceQueue(device, queueFamily, 0, pQueue);
return new VkQueue(pQueue.get(0), device);
}
}
private static ColorFormatAndSpace determineSurfaceFormat(VkPhysicalDevice physicalDevice, long surface) {
try (MemoryStack stack = stackPush()) {
IntBuffer pSurfaceFormatCount = stack.mallocInt(1);
_CHECK_(vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, pSurfaceFormatCount, null),
"Failed to get number of device surface formats");
VkSurfaceFormatKHR.Buffer pSurfaceFormats = VkSurfaceFormatKHR
.malloc(pSurfaceFormatCount.get(0), stack);
_CHECK_(vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, pSurfaceFormatCount, pSurfaceFormats),
"Failed to get device surface formats");
for (VkSurfaceFormatKHR surfaceFormat : pSurfaceFormats) {
if (surfaceFormat.format() == VK_FORMAT_B8G8R8A8_UNORM) {
return new ColorFormatAndSpace(surfaceFormat.format(), surfaceFormat.colorSpace());
}
}
return new ColorFormatAndSpace(pSurfaceFormats.get(0).format(), pSurfaceFormats.get(0).colorSpace());
}
}
private static Vector2i determineSwapchainExtents(VkSurfaceCapabilitiesKHR surfCaps) {
VkExtent2D extent = surfCaps.currentExtent();
Vector2i ret = new Vector2i(extent.width(), extent.height());
if (extent.width() == -1) {
ret.set(max(min(1280, surfCaps.maxImageExtent().width()), surfCaps.minImageExtent().width()),
max(min(720, surfCaps.maxImageExtent().height()), surfCaps.minImageExtent().height()));
}
return ret;
}
private static Swapchain createSwapchain() {
try (MemoryStack stack = stackPush()) {
VkSurfaceCapabilitiesKHR pSurfaceCapabilities = VkSurfaceCapabilitiesKHR
.malloc(stack);
_CHECK_(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(deviceAndQueueFamilies.physicalDevice, surface, pSurfaceCapabilities),
"Failed to get physical device surface capabilities");
IntBuffer pPresentModeCount = stack.mallocInt(1);
_CHECK_(vkGetPhysicalDeviceSurfacePresentModesKHR(deviceAndQueueFamilies.physicalDevice, surface, pPresentModeCount, null),
"Failed to get presentation modes count");
int presentModeCount = pPresentModeCount.get(0);
IntBuffer pPresentModes = stack.mallocInt(presentModeCount);
_CHECK_(vkGetPhysicalDeviceSurfacePresentModesKHR(deviceAndQueueFamilies.physicalDevice, surface, pPresentModeCount, pPresentModes),
"Failed to get presentation modes");
int imageCount = min(max(pSurfaceCapabilities.minImageCount(), 2), pSurfaceCapabilities.maxImageCount());
ColorFormatAndSpace surfaceFormat = determineSurfaceFormat(deviceAndQueueFamilies.physicalDevice, surface);
Vector2i swapchainExtents = determineSwapchainExtents(pSurfaceCapabilities);
LongBuffer pSwapchain = stack.mallocLong(1);
_CHECK_(vkCreateSwapchainKHR(device, VkSwapchainCreateInfoKHR
.calloc(stack)
.sType$Default()
.surface(surface)
.minImageCount(imageCount)
.imageFormat(surfaceFormat.colorFormat)
.imageColorSpace(surfaceFormat.colorSpace)
.imageExtent(e -> e.width(swapchainExtents.x).height(swapchainExtents.y))
.imageArrayLayers(1)
.imageUsage(VK_IMAGE_USAGE_STORAGE_BIT) // <- for writing to in the raygen shader
.imageSharingMode(VK_SHARING_MODE_EXCLUSIVE)
.preTransform(pSurfaceCapabilities.currentTransform())
.compositeAlpha(VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR)
.presentMode(VK_PRESENT_MODE_FIFO_KHR)
.clipped(true)
.oldSwapchain(swapchain != null ? swapchain.swapchain : VK_NULL_HANDLE), null, pSwapchain),
"Failed to create swap chain");
if (swapchain != null) {
swapchain.free();
}
long swapchain = pSwapchain.get(0);
IntBuffer pSwapchainImageCount = stack.mallocInt(1);
_CHECK_(vkGetSwapchainImagesKHR(device, swapchain, pSwapchainImageCount, null),
"Failed to get swapchain images count");
int actualImageCount = pSwapchainImageCount.get(0);
LongBuffer pSwapchainImages = stack.mallocLong(actualImageCount);
_CHECK_(vkGetSwapchainImagesKHR(device, swapchain, pSwapchainImageCount, pSwapchainImages),
"Failed to get swapchain images");
long[] images = new long[actualImageCount];
pSwapchainImages.get(images, 0, images.length);
long[] imageViews = new long[actualImageCount];
LongBuffer pImageView = stack.mallocLong(1);
for (int i = 0; i < actualImageCount; i++) {
_CHECK_(vkCreateImageView(device,
VkImageViewCreateInfo
.calloc(stack)
.sType$Default()
.image(pSwapchainImages.get(i))
.viewType(VK_IMAGE_TYPE_2D)
.format(surfaceFormat.colorFormat)
.subresourceRange(r -> r
.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
.layerCount(1)
.levelCount(1)),
null, pImageView),
"Failed to create image view");
imageViews[i] = pImageView.get(0);
}
return new Swapchain(swapchain, images, imageViews, swapchainExtents.x, swapchainExtents.y);
}
}
private static long createCommandPool(int flags) {
try (MemoryStack stack = stackPush()) {
LongBuffer pCmdPool = stack.mallocLong(1);
_CHECK_(vkCreateCommandPool(device, VkCommandPoolCreateInfo
.calloc(stack)
.sType$Default()
.flags(flags)
.queueFamilyIndex(queueFamily), null, pCmdPool),
"Failed to create command pool");
return pCmdPool.get(0);
}
}
private static VkCommandBuffer createCommandBuffer(long pool, int beginFlags) {
try (MemoryStack stack = stackPush()) {
PointerBuffer pCommandBuffer = stack.mallocPointer(1);
_CHECK_(vkAllocateCommandBuffers(device,
VkCommandBufferAllocateInfo
.calloc(stack)
.sType$Default()
.commandPool(pool)
.level(VK_COMMAND_BUFFER_LEVEL_PRIMARY)
.commandBufferCount(1), pCommandBuffer),
"Failed to create command buffer");
VkCommandBuffer cmdBuffer = new VkCommandBuffer(pCommandBuffer.get(0), device);
_CHECK_(vkBeginCommandBuffer(cmdBuffer, VkCommandBufferBeginInfo
.calloc(stack)
.sType$Default()
.flags(beginFlags)),
"Failed to begin command buffer");
return cmdBuffer;
}
}
private static void createSyncObjects() {
imageAcquireSemaphores = new long[swapchain.imageViews.length];
renderCompleteSemaphores = new long[swapchain.imageViews.length];
renderFences = new long[swapchain.imageViews.length];
for (int i = 0; i < swapchain.imageViews.length; i++) {
try (MemoryStack stack = stackPush()) {
LongBuffer pSemaphore = stack.mallocLong(1);
VkSemaphoreCreateInfo pCreateInfo = VkSemaphoreCreateInfo
.calloc(stack)
.sType$Default();
_CHECK_(vkCreateSemaphore(device, pCreateInfo, null, pSemaphore),
"Failed to create image acquire semaphore");
imageAcquireSemaphores[i] = pSemaphore.get(0);
_CHECK_(vkCreateSemaphore(device, pCreateInfo, null, pSemaphore),
"Failed to create render complete semaphore");
renderCompleteSemaphores[i] = pSemaphore.get(0);
LongBuffer pFence = stack.mallocLong(1);
_CHECK_(vkCreateFence(device, VkFenceCreateInfo
.calloc(stack)
.sType$Default()
.flags(VK_FENCE_CREATE_SIGNALED_BIT), null, pFence),
"Failed to create fence");
renderFences[i] = pFence.get(0);
}
}
}
private static void updateFramebufferSize() {
try (MemoryStack stack = stackPush()) {
long mem = stack.nmalloc(2 * Integer.BYTES);
nglfwGetFramebufferSize(windowAndCallbacks.window, mem, mem + Integer.BYTES);
windowAndCallbacks.width = memGetInt(mem);
windowAndCallbacks.height = memGetInt(mem + Integer.BYTES);
}
}
private static boolean isWindowRenderable() {
return windowAndCallbacks.width > 0 && windowAndCallbacks.height > 0;
}
private static boolean windowSizeChanged() {
return windowAndCallbacks.width != swapchain.width || windowAndCallbacks.height != swapchain.height;
}
private static void recreateSwapchainAndDependentResources() {
swapchain = createSwapchain();
rayTracingDescriptorSets = createRayTracingDescriptorSets();
commandBuffers = createRayTracingCommandBuffers();
}
private static void processFinishedFences() {
Iterator<Map.Entry<Long, Runnable>> it = waitingFenceActions.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Long, Runnable> e = it.next();
if (vkGetFenceStatus(device, e.getKey()) == VK_SUCCESS) {
it.remove();
vkDestroyFence(device, e.getKey(), null);
e.getValue().run();
}
}
}
private static boolean submitAndPresent(int imageIndex, int idx) {
try (MemoryStack stack = stackPush()) {
_CHECK_(vkQueueSubmit(queue, VkSubmitInfo
.calloc(stack)
.sType$Default()
.pWaitSemaphores(stack.longs(imageAcquireSemaphores[idx]))
.pWaitDstStageMask(stack.ints(VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR))
.pCommandBuffers(stack.pointers(commandBuffers[idx]))
.waitSemaphoreCount(1)
.pSignalSemaphores(stack.longs(renderCompleteSemaphores[idx])),
renderFences[idx]),
"Failed to submit command buffer");
int result = vkQueuePresentKHR(queue, VkPresentInfoKHR
.calloc(stack)
.sType$Default()
.pWaitSemaphores(stack.longs(renderCompleteSemaphores[idx]))
.swapchainCount(1)
.pSwapchains(stack.longs(swapchain.swapchain))
.pImageIndices(stack.ints(imageIndex)));
return result != VK_ERROR_OUT_OF_DATE_KHR && result != VK_SUBOPTIMAL_KHR;
}
}
private static boolean acquireSwapchainImage(IntBuffer pImageIndex, int idx) {
int res = vkAcquireNextImageKHR(device, swapchain.swapchain, -1L, imageAcquireSemaphores[idx], VK_NULL_HANDLE, pImageIndex);
return res != VK_ERROR_OUT_OF_DATE_KHR;
}
private static void runWndProcLoop() {
glfwShowWindow(windowAndCallbacks.window);
while (!glfwWindowShouldClose(windowAndCallbacks.window)) {
glfwWaitEvents();
}
}
private static class AllocationAndBuffer {
private final long allocation;
private final long buffer;
private final boolean hostCoherent;
private ByteBuffer mapped;
private AllocationAndBuffer(long allocation, long buffer, boolean hostCoerent) {
this.allocation = allocation;
this.buffer = buffer;
this.hostCoherent = hostCoerent;
}
private void free() {
if (mapped != null) {
vmaUnmapMemory(vmaAllocator, allocation);
mapped = null;
}
vmaDestroyBuffer(vmaAllocator, buffer, allocation);
}
private void map(int size) {
if (mapped != null)
return;
try (MemoryStack stack = stackPush()) {
PointerBuffer pb = stack.mallocPointer(1);
_CHECK_(vmaMapMemory(vmaAllocator, allocation, pb), "Failed to map allocation");
mapped = memByteBuffer(pb.get(0), size);
}
}
private void flushMapped(long offset, long size) {
if (!hostCoherent)
vmaFlushAllocation(vmaAllocator, allocation, offset, size);
}
}
private static class Geometry {
private final AllocationAndBuffer aabbs;
private final int numAabbs;
private Geometry(AllocationAndBuffer aabbs, int numAabbs) {
this.aabbs = aabbs;
this.numAabbs = numAabbs;
}
private void free() {
aabbs.free();
}
}
private static long submitCommandBuffer(VkCommandBuffer commandBuffer, boolean endCommandBuffer, Runnable afterComplete) {
if (endCommandBuffer)
_CHECK_(vkEndCommandBuffer(commandBuffer),
"Failed to end command buffer");
try (MemoryStack stack = stackPush()) {
LongBuffer pFence = stack.mallocLong(1);
_CHECK_(vkCreateFence(device, VkFenceCreateInfo
.calloc(stack)
.sType$Default(), null, pFence),
"Failed to create fence");
_CHECK_(vkQueueSubmit(queue, VkSubmitInfo
.calloc(stack)
.sType$Default()
.pCommandBuffers(stack.pointers(commandBuffer)), pFence.get(0)),
"Failed to submit command buffer");
long fence = pFence.get(0);
if (afterComplete != null)
waitingFenceActions.put(fence, afterComplete);
return fence;
}
}
private static AllocationAndBuffer createBuffer(int usageFlags, long size, ByteBuffer data, long alignment, Consumer<VkCommandBuffer> beforeSubmit) {
try (MemoryStack stack = stackPush()) {
// create the final destination buffer
LongBuffer pBuffer = stack.mallocLong(1);
PointerBuffer pAllocation = stack.mallocPointer(1);
VmaAllocationInfo pAllocationInfo = VmaAllocationInfo.malloc(stack);
_CHECK_(vmaCreateBuffer(vmaAllocator,
VkBufferCreateInfo
.calloc(stack)
.sType$Default()
.size(size)
.usage(usageFlags | (data != null ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : 0)),
VmaAllocationCreateInfo
.calloc(stack)
.usage(VMA_MEMORY_USAGE_AUTO), pBuffer, pAllocation, pAllocationInfo),
"Failed to allocate buffer");
validateAlignment(pAllocationInfo, alignment);
// if we have data to upload, use a staging buffer
if (data != null) {
// create the staging buffer
LongBuffer pBufferStage = stack.mallocLong(1);
PointerBuffer pAllocationStage = stack.mallocPointer(1);
_CHECK_(vmaCreateBuffer(vmaAllocator, VkBufferCreateInfo
.calloc(stack)
.sType$Default()
.size(data.remaining())
.usage(VK_BUFFER_USAGE_TRANSFER_SRC_BIT),
VmaAllocationCreateInfo
.calloc(stack)
.usage(VMA_MEMORY_USAGE_AUTO)
.flags(VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT), pBufferStage, pAllocationStage, null),
"Failed to allocate stage buffer");
// map the memory and memcpy into it
PointerBuffer pData = stack.mallocPointer(1);
_CHECK_(vmaMapMemory(vmaAllocator, pAllocationStage.get(0), pData), "Failed to map memory");
memCopy(memAddress(data), pData.get(0), data.remaining());
// no need to vkFlushMappedMemoryRanges(), because VMA guarantees VMA_MEMORY_USAGE_CPU_ONLY to be host coherent.
vmaUnmapMemory(vmaAllocator, pAllocationStage.get(0));
// issue copy buffer command
VkCommandBuffer cmdBuffer = createCommandBuffer(commandPoolTransient, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT);
vkCmdCopyBuffer(cmdBuffer, pBufferStage.get(0), pBuffer.get(0), VkBufferCopy
.calloc(1, stack)
.size(data.remaining()));
long bufferStage = pBufferStage.get(0);
long allocationStage = pAllocationStage.get(0);
if (beforeSubmit != null)
beforeSubmit.accept(cmdBuffer);
// and submit that, with a callback to destroy the staging buffer once copying is complete
submitCommandBuffer(cmdBuffer, true, () -> {
vkFreeCommandBuffers(device, commandPoolTransient, cmdBuffer);
vmaDestroyBuffer(vmaAllocator, bufferStage, allocationStage);
});
}
return new AllocationAndBuffer(pAllocation.get(0), pBuffer.get(0), false);
}
}
private static AllocationAndBuffer createBuffer(int usageFlags, ByteBuffer data, long alignment, Consumer<VkCommandBuffer> beforeSubmit) {
return createBuffer(usageFlags, data.remaining(), data, alignment, beforeSubmit);
}
private static AllocationAndBuffer[] createUniformBufferObjects(int size) {
AllocationAndBuffer[] ret = new AllocationAndBuffer[swapchain.imageViews.length];
for (int i = 0; i < ret.length; i++) {
try (MemoryStack stack = stackPush()) {
LongBuffer pBuffer = stack.mallocLong(1);
PointerBuffer pAllocation = stack.mallocPointer(1);
VmaAllocationInfo pAllocationInfo = VmaAllocationInfo.malloc(stack);
_CHECK_(vmaCreateBuffer(vmaAllocator, VkBufferCreateInfo
.calloc(stack)
.sType$Default()
.size(size)
.usage(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT),
VmaAllocationCreateInfo
.calloc(stack)
.usage(VMA_MEMORY_USAGE_AUTO)
.flags(VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT), pBuffer, pAllocation, pAllocationInfo),
"Failed to allocate buffer");
// check whether the allocation is host-coherent
IntBuffer memTypeProperties = stack.mallocInt(1);
vmaGetMemoryTypeProperties(vmaAllocator, pAllocationInfo.memoryType(), memTypeProperties);
boolean isHostCoherent = (memTypeProperties.get(0) & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) != 0;
AllocationAndBuffer a = new AllocationAndBuffer(pAllocation.get(0), pBuffer.get(0), isHostCoherent);
a.map(size);
ret[i] = a;
}
}
return ret;
}
private static int idx(int x, int y, int z, int width, int depth) {
return (x + 1) + (width + 2) * ((z + 1) + (y + 1) * (depth + 2));
}
private static class VoxelField {
int ny, py, w, d;
byte[] field;
}
private static VoxelField buildVoxelField() throws IOException {
Vector3i dims = new Vector3i();
Vector3i min = new Vector3i(Integer.MAX_VALUE);
Vector3i max = new Vector3i(Integer.MIN_VALUE);
byte[] field = new byte[(256 + 2) * (256 + 2) * (256 + 2)];
try (InputStream is = getSystemResourceAsStream("org/lwjgl/demo/models/mikelovesrobots_mmmm/scene_house5.vox");
BufferedInputStream bis = new BufferedInputStream(is)) {
new MagicaVoxelLoader().read(bis, new MagicaVoxelLoader.Callback() {
public void voxel(int x, int y, int z, byte c) {
y = dims.z - y - 1;
field[idx(x, z, y, dims.x, dims.z)] = 1;
min.set(min(min.x, x), min(min.y, z), min(min.z, y));
max.set(max(max.x, x), max(max.y, z), max(max.z, y));
}
public void size(int x, int y, int z) {
dims.x = x;
dims.y = z;
dims.z = y;
}
public void paletteMaterial(int i, Material mat) {