This repository was archived by the owner on Feb 13, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathpy_operations.hpp
1233 lines (1014 loc) · 50.1 KB
/
py_operations.hpp
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
#pragma once
#include "py_types.hpp"
#include <meshops_internal/heightmap.hpp>
#include <meshops_internal/meshops_vertexattribs.h>
#include <tool_meshops_objects.hpp>
#include "imageio/imageio.hpp"
void bake(meshops::Context context, PyBakerInput& bakerInput, PyMicromeshData& bakeOutput)
{
if (!context)
{
throw std::runtime_error("no context available");
}
meshops::MeshData baseMesh;
meshops::ResizableMeshView baseMeshView(baseMesh, makeResizableMeshViewCallback(baseMesh));
micromesh::Matrix_float_4x4 baseMeshTransform;
meshops::MeshTopologyData baseMeshTopology;
meshops::MeshData referenceMesh;
meshops::ResizableMeshView referenceMeshView(referenceMesh, makeResizableMeshViewCallback(referenceMesh));
micromesh::Matrix_float_4x4 referenceMeshTransform;
meshops::MeshTopologyData referenceMeshTopology;
std::vector<meshops::OpBake_resamplerInput> resamplerInput;
std::vector<meshops::Texture> resamplerOutput;
if (bakerInput.baseMesh)
{
bakerInput.baseMesh->toMeshView(baseMeshView);
numpyArrayToMatrix(bakerInput.baseMeshTransform, baseMeshTransform);
meshops::OpBuildTopology_input buildTopologyInput;
buildTopologyInput.meshView = baseMeshView;
meshops::OpBuildTopology_output buildTopologyOutput;
buildTopologyOutput.meshTopology = &baseMeshTopology;
if (meshops::meshopsOpBuildTopology(context, 1, &buildTopologyInput, &buildTopologyOutput) != micromesh::Result::eSuccess)
{
throw std::runtime_error("unable to create base mesh topology");
}
}
bool baseMeshIncludesTexCoords = baseMeshView.vertexTexcoords0.size() > 0;
if (bakerInput.referenceMesh)
{
bakerInput.referenceMesh->toMeshView(referenceMeshView);
numpyArrayToMatrix(bakerInput.referenceMeshTransform, referenceMeshTransform);
meshops::OpBuildTopology_input buildTopologyInput;
buildTopologyInput.meshView = referenceMeshView;
meshops::OpBuildTopology_output buildTopologyOutput;
buildTopologyOutput.meshTopology = &referenceMeshTopology;
if (meshops::meshopsOpBuildTopology(context, 1, &buildTopologyInput, &buildTopologyOutput) != micromesh::Result::eSuccess)
{
throw std::runtime_error("unable to create reference mesh topology");
}
}
std::vector<std::unique_ptr<micromesh_tool::MeshopsTexture>> meshopsTextures;
// Reference mesh heightmap config
meshops::OpBake_heightmap heightmapDesc;
meshops::TextureConfig heightmapConfig{};
heightmapDesc.normalizeDirections = true;
heightmapDesc.usesVertexNormalsAsDirections = false; // Smooth direction vectors give better results at hard edges
heightmapDesc.scale = bakerInput.heightmap.scale;
heightmapDesc.bias = bakerInput.heightmap.bias;
if(!referenceMeshView.triangleSubdivisionLevels.empty())
{
heightmapDesc.maxSubdivLevel = *std::max_element(referenceMeshView.triangleSubdivisionLevels.begin(),
referenceMeshView.triangleSubdivisionLevels.end());
}
// Load the heightmap, if there is one
if (!bakerInput.heightmap.filepath.empty() || bakerInput.heightmap.data.size() > 0)
{
size_t w = 0, h = 0, comp = 0;
imageio::ImageIOData data = nullptr;
if(bakerInput.heightmap.filepath.empty())
{
if (bakerInput.heightmap.format == PyTextureFormat::eR16Unorm ||
bakerInput.heightmap.format == PyTextureFormat::eRGBA16Unorm ||
bakerInput.heightmap.format == PyTextureFormat::eRGBA8Unorm)
{
std::vector<uint8_t> rawData;
numpyArrayToVector<1, uint8_t, uint8_t>(bakerInput.heightmap.data, rawData);
if (rawData.size() > 0)
{
w = bakerInput.heightmap.width;
h = bakerInput.heightmap.height;
int bitDepth = 1;
switch (bakerInput.heightmap.format)
{
case PyTextureFormat::eRGBA8Unorm:
bitDepth = 8;
comp = 4;
break;
case PyTextureFormat::eRGBA16Unorm:
bitDepth = 16;
comp = 4;
break;
case PyTextureFormat::eR16Unorm:
bitDepth = 16;
comp = 1;
break;
};
size_t sizeCheck = w * h * comp * (bitDepth / CHAR_BIT);
if (sizeCheck != rawData.size())
{
imageio::freeData(&data);
std::stringstream s; s << "Error: heightmap texture image data inconsistent with width '" << bakerInput.heightmap.width << "', height '" << bakerInput.heightmap.height << "', and format '" << bakerInput.heightmap.format << "' provided";
throw std::runtime_error(s.str());
}
data = imageio::allocateData(rawData.size());
memcpy(data, rawData.data(), rawData.size());
// Convert from 8-16 bit if necessary
if (bakerInput.heightmap.format == PyTextureFormat::eRGBA8Unorm)
{
if(!imageio::convertFormat(&data, w, h, 4, 8, 1, 32))
{
imageio::freeData(&data);
throw std::runtime_error("Error: failed to convert heightmap texture image data from RGBA8Unorm to R32");
}
}
else if (bakerInput.heightmap.format == PyTextureFormat::eRGBA16Unorm)
{
if(!imageio::convertFormat(&data, w, h, 4, 16, 1, 32))
{
imageio::freeData(&data);
throw std::runtime_error("Error: failed to convert heightmap texture image data from RGBA16Unorm to R32");
}
}
else if (bakerInput.heightmap.format == PyTextureFormat::eR16Unorm)
{
if(!imageio::convertFormat(&data, w, h, 1, 16, 1, 32))
{
imageio::freeData(&data);
throw std::runtime_error("Error: failed to convert heightmap texture image data from R16Unorm to R32");
}
}
}
else
{
throw std::runtime_error("Error: heightmap texture image data is empty");
}
}
else
{
throw std::runtime_error("Error: heightmap texture image data format is not compatible (8 or 16-bit RGBAUnorm only)");
}
}
else
{
if (!imageio::info(bakerInput.heightmap.filepath.c_str(), &w, &h, &comp))
{
std::stringstream s; s << "Error: heightmap texture image data in wrong format or could not read file at path '" << bakerInput.heightmap.filepath << "'";
throw std::runtime_error(s.str());
}
data = imageio::loadF(bakerInput.heightmap.filepath.c_str(), &w, &h, &comp, 1);
}
size_t dataSize = w * h * sizeof(float);
heightmapConfig.baseFormat = micromesh::Format::eR32_sfloat;
heightmapConfig.width = static_cast<uint32_t>(w);
heightmapConfig.height = static_cast<uint32_t>(h);
heightmapConfig.mips = 1;
heightmapConfig.internalFormatVk = VK_FORMAT_R32_SFLOAT;
meshopsTextures.push_back(std::make_unique<micromesh_tool::MeshopsTexture>(context, meshops::eTextureUsageBakerHeightmapSource, heightmapConfig, dataSize, data));
imageio::freeData(&data);
if(!meshopsTextures.back()->valid())
{
throw std::runtime_error("Error: meshopsTextureCreate() failed to create heightmap texture\n");
}
heightmapDesc.texture = *meshopsTextures.back();
}
// Set up resampled textures
if(bakerInput.resamplerInput.size() > 0)
{
if (baseMeshIncludesTexCoords)
{
for (py::handle handle: bakerInput.resamplerInput)
{
meshops::OpBake_resamplerInput input;
PyResamplerInput pyResamplerInput = py::cast<PyResamplerInput>(handle);
size_t w = 0, h = 0, comp = 0;
imageio::ImageIOData data = nullptr;
if(pyResamplerInput.input.filepath.empty())
{
if (pyResamplerInput.input.format == PyTextureFormat::eRGBA16Unorm ||
pyResamplerInput.input.format == PyTextureFormat::eRGBA8Unorm)
{
std::vector<uint8_t> rawData;
numpyArrayToVector<1, uint8_t, uint8_t>(pyResamplerInput.input.data, rawData);
if (rawData.size() > 0)
{
w = pyResamplerInput.input.width;
h = pyResamplerInput.input.height;
int bitDepth = 1;
switch (pyResamplerInput.input.format)
{
case PyTextureFormat::eRGBA8Unorm:
bitDepth = 8;
comp = 4;
break;
case PyTextureFormat::eRGBA16Unorm:
bitDepth = 16;
comp = 4;
break;
};
size_t sizeCheck = w * h * comp * (bitDepth / CHAR_BIT);
if (sizeCheck != rawData.size())
{
imageio::freeData(&data);
std::stringstream s; s << "Error: resampler input texture image data inconsistent with width '" << pyResamplerInput.input.width << "', height '" << pyResamplerInput.input.height << "', and format '" << pyResamplerInput.input.format << "' provided";
throw std::runtime_error(s.str());
}
data = imageio::allocateData(rawData.size());
memcpy(data, rawData.data(), rawData.size());
// Convert from 8-16 bit if necessary
if (pyResamplerInput.input.format == PyTextureFormat::eRGBA8Unorm)
{
if(!imageio::convertFormat(&data, w, h, 4, 8, 4, 16))
{
imageio::freeData(&data);
throw std::runtime_error("Error: failed to convert resampler input texture image data");
}
}
}
else
{
throw std::runtime_error("Error: resampler input texture image data is empty");
}
}
else
{
throw std::runtime_error("Error: resampler input texture image data format is not compatible (8 or 16-bit RGBAUnorm only)");
}
}
else
{
if (!imageio::info(pyResamplerInput.input.filepath.c_str(), &w, &h, &comp))
{
std::stringstream s; s << "Error: resampler input texture image data in wrong format or could not read file at path '" << pyResamplerInput.input.filepath << "'";
throw std::runtime_error(s.str());
}
data = imageio::load16(pyResamplerInput.input.filepath.c_str(), &w, &h, &comp, 4);
}
size_t dataSize = w * h * 4 * 2 * sizeof(char);
meshops::TextureConfig config;
config.baseFormat = micromesh::Format::eRGBA16_unorm;
config.width = static_cast<uint32_t>(w);
config.height = static_cast<uint32_t>(h);
config.mips = 1;
config.internalFormatVk = VK_FORMAT_R16G16B16A16_UNORM;
meshopsTextures.push_back(std::make_unique<micromesh_tool::MeshopsTexture>(context, meshops::eTextureUsageBakerResamplingSource, config, dataSize, data));
imageio::freeData(&data);
if(!meshopsTextures.back()->valid())
{
throw std::runtime_error("Error: meshopsTextureCreate() failed to create resampled input texture\n");
}
if (pyResamplerInput.input.type != meshops::TextureType::eNormalMap)
{
input.textureType = meshops::TextureType::eGeneric;
}
else
{
input.textureType = meshops::TextureType::eNormalMap;
}
input.texture = *meshopsTextures.back();
micromesh::MicromapValue fillInitDist{};
fillInitDist.value_float[0] = std::numeric_limits<float>::max();
meshops::TextureConfig distanceConfig;
distanceConfig.baseFormat = micromesh::Format::eR32_sfloat;
distanceConfig.internalFormatVk = VK_FORMAT_R32_SFLOAT;
distanceConfig.width = uint32_t(pyResamplerInput.output.width);
distanceConfig.height = uint32_t(pyResamplerInput.output.height);
distanceConfig.mips = static_cast<uint32_t>(std::floor(std::log2(std::min(pyResamplerInput.output.width, pyResamplerInput.output.height)))) + 1;
meshopsTextures.push_back(std::make_unique<micromesh_tool::MeshopsTexture>(context, meshops::eTextureUsageBakerResamplingDistance, distanceConfig, &fillInitDist));
if(!meshopsTextures.back()->valid())
{
throw std::runtime_error("Error: meshopsTextureCreate() failed to create reampled distance texture");
}
input.distance = *meshopsTextures.back();
meshops::TextureConfig outputConfig;
outputConfig.baseFormat = micromesh::Format::eRGBA16_unorm;
outputConfig.width = static_cast<uint32_t>(pyResamplerInput.output.width);
outputConfig.height = static_cast<uint32_t>(pyResamplerInput.output.height);
outputConfig.mips = 1;
outputConfig.internalFormatVk = VK_FORMAT_R16G16B16A16_UNORM;
size_t outputImageDataSize = outputConfig.width * outputConfig.height * 4 * 2 * sizeof(char);
std::vector<uint8_t> outputImageData;
outputImageData.resize(outputImageDataSize);
meshopsTextures.push_back(std::make_unique<micromesh_tool::MeshopsTexture>(context, meshops::eTextureUsageBakerResamplingDestination, outputConfig, outputImageDataSize, outputImageData.data()));
if(!meshopsTextures.back()->valid())
{
throw std::runtime_error("Error: meshopsTextureCreate() failed to create resampled input texture");
}
resamplerOutput.push_back(*meshopsTextures.back());
resamplerInput.emplace_back(input);
}
}
else
{
LOGI("There are textures to be resampled but base mesh does not contain texture coordinates; ignoring\n");
}
}
// Create normal map texture
int outputQuaternionMapOutputIndex = -1;
if(!bakerInput.quaternionMapFilepath.empty() && baseMeshIncludesTexCoords)
{
meshops::OpBake_resamplerInput input;
micromesh::MicromapValue fillValue;
fillValue.value_int32[0] = fillValue.value_int32[1] = fillValue.value_int32[2] = fillValue.value_int32[3] = 0;
meshops::TextureConfig inputConfig;
inputConfig.baseFormat = micromesh::Format::eR32_sfloat;
inputConfig.internalFormatVk = VK_FORMAT_R32_SFLOAT;
inputConfig.width = uint32_t(bakerInput.quaternionMapResolution);
inputConfig.height = uint32_t(bakerInput.quaternionMapResolution);
inputConfig.mips = static_cast<uint32_t>(std::floor(std::log2(bakerInput.quaternionMapResolution))) + 1;
meshopsTextures.push_back(std::make_unique<micromesh_tool::MeshopsTexture>(context, meshops::eTextureUsageBakerResamplingSource, inputConfig, &fillValue));
if(!meshopsTextures.back()->valid())
{
throw std::runtime_error("Error: meshopsTextureCreate() failed to create quaternion input texture");
}
input.textureType = meshops::TextureType::eQuaternionMap;
input.texture = *meshopsTextures.back();
micromesh::MicromapValue fillInitDist{};
fillInitDist.value_float[0] = std::numeric_limits<float>::max();
meshops::TextureConfig distanceConfig;
distanceConfig.baseFormat = micromesh::Format::eR32_sfloat;
distanceConfig.internalFormatVk = VK_FORMAT_R32_SFLOAT;
distanceConfig.width = uint32_t(bakerInput.quaternionMapResolution);
distanceConfig.height = uint32_t(bakerInput.quaternionMapResolution);
distanceConfig.mips = static_cast<uint32_t>(std::floor(std::log2(bakerInput.quaternionMapResolution))) + 1;
meshopsTextures.push_back(std::make_unique<micromesh_tool::MeshopsTexture>(context, meshops::eTextureUsageBakerResamplingDistance, distanceConfig, &fillInitDist));
if(!meshopsTextures.back()->valid())
{
throw std::runtime_error("Error: meshopsTextureCreate() failed to create quaternion distance texture\n");
}
input.distance = *meshopsTextures.back();
resamplerInput.push_back(input);
meshops::TextureConfig quaternionMapConfig;
quaternionMapConfig.baseFormat = micromesh::Format::eRGBA8_unorm;
quaternionMapConfig.internalFormatVk = VK_FORMAT_R8G8B8A8_UNORM;
quaternionMapConfig.width = uint32_t(bakerInput.quaternionMapResolution);
quaternionMapConfig.height = uint32_t(bakerInput.quaternionMapResolution);
quaternionMapConfig.mips = static_cast<uint32_t>(std::floor(std::log2(bakerInput.quaternionMapResolution))) + 1;
meshopsTextures.push_back(std::make_unique<micromesh_tool::MeshopsTexture>(context, meshops::eTextureUsageBakerResamplingDestination, quaternionMapConfig, &fillValue));
if(!meshopsTextures.back()->valid())
{
throw std::runtime_error("Error: meshopsTextureCreate() failed to create quaternion output texture\n");
}
outputQuaternionMapOutputIndex = (int)resamplerOutput.size();
resamplerOutput.push_back(*meshopsTextures.back());
}
// Create uv remap texture
int outputOffsetMapOutputIndex = -1;
if(!bakerInput.offsetMapFilepath.empty() && baseMeshIncludesTexCoords)
{
meshops::OpBake_resamplerInput input;
micromesh::MicromapValue fillValue;
fillValue.value_int32[0] = fillValue.value_int32[1] = fillValue.value_int32[2] = fillValue.value_int32[3] = 0;
meshops::TextureConfig inputConfig;
inputConfig.baseFormat = micromesh::Format::eR32_sfloat;
inputConfig.internalFormatVk = VK_FORMAT_R32_SFLOAT;
inputConfig.width = uint32_t(bakerInput.offsetMapResolution);
inputConfig.height = uint32_t(bakerInput.offsetMapResolution);
inputConfig.mips = static_cast<uint32_t>(std::floor(std::log2(bakerInput.offsetMapResolution))) + 1;
meshopsTextures.push_back(std::make_unique<micromesh_tool::MeshopsTexture>(context, meshops::eTextureUsageBakerResamplingSource,
inputConfig, &fillValue));
if(!meshopsTextures.back()->valid())
{
throw std::runtime_error("Error: meshopsTextureCreate() failed to create offset input texture\n");
}
input.textureType = meshops::TextureType::eOffsetMap;
input.texture = *meshopsTextures.back();
micromesh::MicromapValue fillInitDist{};
fillInitDist.value_float[0] = std::numeric_limits<float>::max();
meshops::TextureConfig distanceConfig;
distanceConfig.baseFormat = micromesh::Format::eR32_sfloat;
distanceConfig.internalFormatVk = VK_FORMAT_R32_SFLOAT;
distanceConfig.width = uint32_t(bakerInput.offsetMapResolution);
distanceConfig.height = uint32_t(bakerInput.offsetMapResolution);
distanceConfig.mips = static_cast<uint32_t>(std::floor(std::log2(bakerInput.offsetMapResolution))) + 1;
meshopsTextures.push_back(std::make_unique<micromesh_tool::MeshopsTexture>(context, meshops::eTextureUsageBakerResamplingDistance,
distanceConfig, &fillInitDist));
if(!meshopsTextures.back()->valid())
{
throw std::runtime_error("Error: meshopsTextureCreate() failed to create offset distance texture\n");
}
input.distance = *meshopsTextures.back();
resamplerInput.push_back(input);
meshops::TextureConfig offsetMapConfig;
offsetMapConfig.baseFormat = micromesh::Format::eRGBA16_unorm;
offsetMapConfig.internalFormatVk = VK_FORMAT_R16G16B16A16_UNORM;
offsetMapConfig.width = uint32_t(bakerInput.offsetMapResolution);
offsetMapConfig.height = uint32_t(bakerInput.offsetMapResolution);
offsetMapConfig.mips = static_cast<uint32_t>(std::floor(std::log2(bakerInput.offsetMapResolution))) + 1;
meshopsTextures.push_back(std::make_unique<micromesh_tool::MeshopsTexture>(context, meshops::eTextureUsageBakerResamplingDestination, offsetMapConfig, &fillValue));
if(!meshopsTextures.back()->valid())
{
throw std::runtime_error("Error: meshopsTextureCreate() failed to create offset output texture\n");
}
outputOffsetMapOutputIndex = (int)resamplerOutput.size();
resamplerOutput.push_back(*meshopsTextures.back());
}
OpBake_settings settings;
bakerInput.settings.toSettings(settings);
micromesh_tool::BakeOperator bakeOperator(context);
meshops::OpBake_properties bakeProperties;
meshops::meshopsBakeGetProperties(context, bakeOperator, bakeProperties);
// Make sure subdivision levels get generated unless explicitly requesting uniform values
bool uniformSubdivLevels = bakerInput.settings.subdivMethod == PySubdivMethod::eUniform;
// Query the mesh attributes needed to bake
meshops::OpBake_requirements meshRequirements;
meshops::meshopsBakeGetRequirements(context, bakeOperator, settings, resamplerInput,
uniformSubdivLevels, heightmapDesc.texture != nullptr,
heightmapDesc.usesVertexNormalsAsDirections, meshRequirements);
if(!uniformSubdivLevels)
{
// while the baker doesn't need the basemesh with triangle primitive flags, the resulting
// mesh must be consistent for further processing / saving etc.
meshRequirements.baseMeshAttribFlags |= meshops::MeshAttributeFlagBits::eMeshAttributeTrianglePrimitiveFlagsBit;
}
// If we want uniform subdiv levels, we should not pass in a per-triangle array.
// If we want generated subdiv levels we need to clear and re-generate existing ones.
bool generateSubdivLevels = bakerInput.settings.subdivMethod == PySubdivMethod::eAdaptive3D
|| bakerInput.settings.subdivMethod == PySubdivMethod::eAdaptiveUV;
if(bakerInput.settings.subdivMethod == PySubdivMethod::eUniform || generateSubdivLevels)
{
if(!baseMeshView.triangleSubdivisionLevels.empty())
{
LOGW("Warning: clearing base mesh's subdivision levels due to --subdivmode.\n");
}
baseMeshView.triangleSubdivisionLevels = {};
if(!baseMeshView.trianglePrimitiveFlags.empty())
{
LOGW("Warning: clearing base mesh's primitive flags due to --subdivmode.\n");
}
baseMeshView.trianglePrimitiveFlags = {};
}
// Warn if the input subdiv level is all ones or zeroes
if(!baseMeshView.triangleSubdivisionLevels.empty())
{
int maxSubdivLevel = *std::max_element(baseMeshView.triangleSubdivisionLevels.begin(),
baseMeshView.triangleSubdivisionLevels.end());
if(maxSubdivLevel < 2)
{
LOGW("Warning: max input subdivision level in the base mesh is only %i\n", maxSubdivLevel);
}
}
// Base mesh
{
meshops::OpGenerateSubdivisionLevel_input baseSubdivSettings;
baseSubdivSettings.maxSubdivLevel = settings.level;
baseSubdivSettings.subdivLevelBias = bakerInput.settings.lowTessBias;
baseSubdivSettings.relativeWeight = bakerInput.settings.adaptiveFactor;
baseSubdivSettings.useTextureArea = bakerInput.settings.subdivMethod == PySubdivMethod::eAdaptiveUV;
if(baseSubdivSettings.useTextureArea)
{
if(heightmapDesc.texture == nullptr)
{
throw std::runtime_error("Error: adaptiveUV given but the reference mesh has no heightmap");
}
baseSubdivSettings.textureWidth = heightmapConfig.width;
baseSubdivSettings.textureHeight = heightmapConfig.height;
}
uint32_t maxGeneratedSubdivLevel;
// Scoped here to ensure Python global interpreter lock is
// released while this function does all its heavy lifting
{
py::gil_scoped_release release;
micromesh::Result result =
generateMeshAttributes(context, meshRequirements.baseMeshAttribFlags, &baseSubdivSettings,
baseMeshTopology, baseMeshView, maxGeneratedSubdivLevel,
bakerInput.settings.normalReduceOp, bakerInput.settings.tangentAlgorithm);
if(result != micromesh::Result::eSuccess)
{
LOGE("Error: generating attributes for base mesh failed\n");
throw std::runtime_error("unable to generate attributes for base mesh");
}
}
}
// Reference mesh
// Updates heightmapDesc.maxSubdivLevel if subdiv levels are generated (it is unlikely to already have them)
{
meshops::OpGenerateSubdivisionLevel_input referenceSubdivSettings;
referenceSubdivSettings.maxSubdivLevel = bakeProperties.maxHeightmapTessellateLevel;
referenceSubdivSettings.subdivLevelBias = bakerInput.settings.highTessBias;
referenceSubdivSettings.textureWidth = heightmapConfig.width;
referenceSubdivSettings.textureHeight = heightmapConfig.height;
referenceSubdivSettings.useTextureArea = true;
// Scoped here to ensure Python global interpreter lock is
// released while this function does all its heavy lifting
{
py::gil_scoped_release release;
micromesh::Result result =
generateMeshAttributes(context, meshRequirements.referenceMeshAttribFlags, &referenceSubdivSettings,
referenceMeshTopology, referenceMeshView, heightmapDesc.maxSubdivLevel,
bakerInput.settings.normalReduceOp, bakerInput.settings.tangentAlgorithm);
if(result != micromesh::Result::eSuccess)
{
LOGE("Error: generating attributes for reference mesh failed\n");
throw std::runtime_error("unable to generate attributes for reference mesh");
}
}
}
baryutils::BaryBasicData baryUncompressedTemp;
meshops::OpBake_input input;
input.settings = settings;
input.baseMeshView = baseMeshView;
input.baseMeshTopology = baseMeshTopology;
input.referenceMeshView = referenceMeshView;
input.referenceMeshTopology = referenceMeshTopology;
input.referenceMeshHeightmap = heightmapDesc;
input.resamplerInput = meshops::ArrayView(resamplerInput);
input.baseMeshTransform = baseMeshTransform;
input.referenceMeshTransform = referenceMeshTransform;
std::vector<baryutils::BaryContentData> baryContents;
baryContents.emplace_back();
OpBake_output output;
output.resamplerTextures = meshops::ArrayView(resamplerOutput);
output.uncompressedDisplacement = bakerInput.settings.enableCompression ? &baryUncompressedTemp : &baryContents.back().basic;
std::vector<nvmath::vec2f> vertexDirectionBounds;
vertexDirectionBounds.resize(input.baseMeshView.vertexDirectionBounds.size());
std::copy(input.baseMeshView.vertexDirectionBounds.begin(), input.baseMeshView.vertexDirectionBounds.end(), vertexDirectionBounds.begin());
output.vertexDirectionBounds = vertexDirectionBounds;
// Scoped here to ensure Python global interpreter lock is
// released while this function does all its heavy lifting
{
py::gil_scoped_release release;
micromesh::Result result = meshops::meshopsOpBake(context, bakeOperator, input, output);
if(result != micromesh::Result::eSuccess)
{
throw std::runtime_error("baking mesh failed");
}
}
baryutils::BaryBasicData* outputData = nullptr;
if(bakerInput.settings.enableCompression)
{
bary::BasicView uncompressedView = output.uncompressedDisplacement->getView();
meshops::OpCompressDisplacementMicromap_input compressedInput;
compressedInput.meshTopology = baseMeshTopology;
compressedInput.meshView = baseMeshView;
compressedInput.settings.minimumPSNR = bakerInput.settings.minPSNR;
compressedInput.settings.validateInputs = true;
compressedInput.settings.validateOutputs = true;
compressedInput.uncompressedDisplacement = &uncompressedView;
compressedInput.uncompressedDisplacementGroupIndex = 0;
meshops::OpCompressDisplacementMicromap_output compressedOutput;
compressedOutput.compressedDisplacement = &baryContents.back().basic;
compressedOutput.compressedDisplacementRasterMips = bakerInput.settings.compressedRasterData ? &baryContents.back().misc : nullptr;
micromesh::Result result = meshops::meshopsOpCompressDisplacementMicromaps(context, 1, &compressedInput, &compressedOutput);
if(result != micromesh::Result::eSuccess)
{
throw std::runtime_error("compressing mesh failed");
}
outputData = compressedOutput.compressedDisplacement;
}
else
{
outputData = output.uncompressedDisplacement;
}
//
// Save textures to disk (these could be condensed into one loop like in baker with a little bit of refactoring)
//
// Write out resampled textures
size_t resampledTextureIndex = 0;
for (py::handle handle: bakerInput.resamplerInput)
{
if (resampledTextureIndex >= resamplerOutput.size())
{
break;
}
PyResamplerInput pyResamplerInput = py::cast<PyResamplerInput>(handle);
meshops::Texture tex = resamplerOutput[resampledTextureIndex];
size_t rawDataSize = meshops::meshopsTextureGetMipDataSize(tex, 0);
std::vector<uint8_t> rawData;
rawData.resize(rawDataSize);
meshops::meshopsTextureToData(context, tex, rawDataSize, &rawData[0]);
imageio::ImageIOData data = imageio::allocateData(rawData.size());
memcpy(data, rawData.data(), rawData.size());
int outputDataSize = 0;
int w = pyResamplerInput.output.width;
int h = pyResamplerInput.output.height;
// Convert from internal format to output format if necessary
if (pyResamplerInput.output.format == PyTextureFormat::eRGBA8Unorm)
{
if(!imageio::convertFormat(&data, w, h, 4, 16, 4, 8))
{
imageio::freeData(&data);
throw std::runtime_error("Error: failed to convert resampler output texture image data");
}
outputDataSize = w * h * 4;
}
else if (pyResamplerInput.output.format == PyTextureFormat::eRGBA16Unorm)
{
//if(!imageio::convertFormat(&data, w, h, 4, 16, 4, 8))
//{
// imageio::freeData(&data);
// throw std::runtime_error("Error: failed to convert resampler output texture image data");
//}
outputDataSize = w * h * 4 * 2;
}
else if (pyResamplerInput.output.format == PyTextureFormat::eR16Unorm)
{
if(!imageio::convertFormat(&data, w, h, 4, 16, 1, 16))
{
imageio::freeData(&data);
throw std::runtime_error("Error: failed to convert resampler output texture image data");
}
outputDataSize = w * h * 2;
}
if (!pyResamplerInput.output.filepath.empty())
{
if (!imageio::writePNG(pyResamplerInput.output.filepath.c_str(), pyResamplerInput.output.width,
pyResamplerInput.output.height, data, (VkFormat)pyResamplerInput.output.format))
{
std::stringstream s; s << "Error: failed to write resampled output texture (" << pyResamplerInput.output.filepath << ")";
throw std::runtime_error(s.str());
}
}
else
{
rawData.assign((uint8_t *)data, (uint8_t *)data + outputDataSize);
vectorToNumpyArray<1, uint8_t, uint8_t>(rawData, pyResamplerInput.output.data);
}
resampledTextureIndex++;
}
// Write out quat map
if(!bakerInput.quaternionMapFilepath.empty() && outputQuaternionMapOutputIndex >= 0
&& static_cast<size_t>(outputQuaternionMapOutputIndex) < resamplerOutput.size())
{
meshops::Texture tex = resamplerOutput[outputQuaternionMapOutputIndex];
size_t dataSize = meshops::meshopsTextureGetMipDataSize(tex, 0);
std::vector<uint8_t> data;
data.resize(dataSize);
meshops::meshopsTextureToData(context, tex, dataSize, &data[0]);
if(!imageio::writePNG(bakerInput.quaternionMapFilepath.c_str(), bakerInput.quaternionMapResolution,
bakerInput.quaternionMapResolution, &data[0], VK_FORMAT_R8G8B8A8_UNORM))
{
std::stringstream s;
s << "Error: failed to write normal map (" << bakerInput.quaternionMapFilepath << ")";
throw std::runtime_error(s.str());
}
}
// Write out undistort map
if(!bakerInput.offsetMapFilepath.empty() && outputOffsetMapOutputIndex >= 0
&& static_cast<size_t>(outputOffsetMapOutputIndex) < resamplerOutput.size())
{
meshops::Texture tex = resamplerOutput[outputOffsetMapOutputIndex];
size_t dataSize = meshops::meshopsTextureGetMipDataSize(tex, 0);
std::vector<uint8_t> data;
data.resize(dataSize);
meshops::meshopsTextureToData(context, tex, dataSize, &data[0]);
if(!imageio::writePNG(bakerInput.offsetMapFilepath.c_str(), bakerInput.offsetMapResolution,
bakerInput.offsetMapResolution, &data[0], VK_FORMAT_R16G16B16A16_UNORM))
{
std::stringstream s;
s << "Error: failed to write UV remap/undistort/offset texture (" << bakerInput.offsetMapFilepath << ")";
throw std::runtime_error(s.str());
}
}
// Copy to output
bakeOutput.fromBaryData(outputData, &input.baseMeshView.vertexDirections,
reinterpret_cast<meshops::ArrayView<const nvmath::vec2f>*>(&output.vertexDirectionBounds),
&baseMeshView);
}
void displace(meshops::Context context, PyMesh& inputMesh, PyMicromeshData& inputMicromesh, PyMesh& outputMesh)
{
if(!context)
{
throw std::runtime_error("no context available");
}
meshops::MeshData mesh;
meshops::ResizableMeshView meshView(mesh, makeResizableMeshViewCallback(mesh));
inputMesh.toMeshView(meshView);
baryutils::BaryBasicData baryBasicData;
baryBasicData.groups.resize(1);
meshops::ArrayView<nvmath::vec3f> vertexDirections;
meshops::ArrayView<nvmath::vec2f> vertexDirectionBounds;
inputMicromesh.toBaryData(&baryBasicData, &vertexDirections, &vertexDirectionBounds, &meshView);
meshView.vertexDirections = vertexDirections;
meshView.vertexDirectionBounds = vertexDirectionBounds;
const bary::BasicView baryBasicView = baryBasicData.getView();
meshops::OpDisplacedTessellate_input input{};
input.meshView = meshView;
input.baryDisplacement = &baryBasicView;
input.baryDisplacementGroupIndex = 0;
input.baryDisplacementMapOffset = 0;
if(!meshView.hasMeshAttributeFlags(meshops::eMeshAttributeVertexDirectionBit))
{
LOGW("Warning: missing direction vectors. Using normals instead; there may be cracks.\n");
input.meshView.vertexDirections = meshView.vertexNormals;
}
meshops::MeshData tessellatedMesh;
meshops::OpDisplacedTessellate_output output{};
meshops::ResizableMeshView tessellatedMeshView(tessellatedMesh, makeResizableMeshViewCallback(tessellatedMesh));
output.meshView = &tessellatedMeshView;
micromesh::Result result = meshops::meshopsOpDisplacedTessellate(context, 1, &input, &output);
if(result != micromesh::Result::eSuccess)
{
throw std::runtime_error("displacing mesh failed");
}
outputMesh.fromMeshView(*output.meshView);
fflush(stdout);
}
void remesh(meshops::Context context, PyMesh& inputMesh, PyRemesherSettings& settings, PyMesh& outputMesh)
{
if (!context)
{
throw std::runtime_error("no context available");
}
meshops::MeshData mesh;
meshops::ResizableMeshView meshView(mesh, makeResizableMeshViewCallback(mesh));
inputMesh.toMeshView(meshView);
micromesh_tool::GenerateImportanceOperator generateImportanceOperator(context);
micromesh_tool::RemeshingOperator remeshingOperator(context);
if(!generateImportanceOperator.valid())
{
throw std::runtime_error("Error: failed to create vertex importance operator\n");
}
meshops::MeshAttributeFlags requiredMeshAttributes =
meshops::eMeshAttributeTriangleVerticesBit | meshops::eMeshAttributeTriangleSubdivLevelsBit
| meshops::eMeshAttributeTrianglePrimitiveFlagsBit | meshops::eMeshAttributeVertexPositionBit
| meshops::eMeshAttributeVertexNormalBit | meshops::eMeshAttributeVertexTangentBit
| meshops::eMeshAttributeVertexDirectionBit | meshops::eMeshAttributeVertexDirectionBoundsBit
| meshops::eMeshAttributeVertexImportanceBit | meshops::eMeshAttributeVertexTexcoordBit;
// Allocate storage for output attributes, if missing
const meshops::MeshAttributeFlags combinedMeshAttributes = (~meshView.getMeshAttributeFlags()) & requiredMeshAttributes;
meshView.resize(combinedMeshAttributes, meshView.triangleCount(), meshView.vertexCount());
{
// Scoped here to ensure Python global interpreter lock is
// released while this function does all its heavy lifting
py::gil_scoped_release release;
if(meshopsGenerateVertexDirections(context, meshView) != micromesh::Result::eSuccess)
{
throw std::runtime_error("Error: could not generate valid per-vertex directions\n");
}
}
uint64_t originalTriangleCount = meshView.triangleCount();
meshops::DeviceMeshSettings deviceMeshSettings;
deviceMeshSettings.usageFlags = meshops::DeviceMeshUsageBlasBit;
deviceMeshSettings.attribFlags = requiredMeshAttributes;
meshops::DeviceMesh deviceMesh;
micromesh::Result result = micromesh::Result::eSuccess;
{
// Scoped here to ensure Python global interpreter lock is
// released while this function does all its heavy lifting
py::gil_scoped_release release;
result = meshopsDeviceMeshCreate(context, meshView, deviceMeshSettings, &deviceMesh);
if(result != micromesh::Result::eSuccess)
{
std::stringstream s; s << "Error: cannot create device mesh (" << micromesh::micromeshResultGetName(result) << ")";
throw std::runtime_error(s.str());
}
}
meshops::OpGenerateImportance_modified importanceParameters{};
importanceParameters.deviceMesh = deviceMesh;
importanceParameters.meshView = meshView;
importanceParameters.importanceTextureCoord = ~0u;
importanceParameters.importancePower = settings.curvaturePower;
meshops::Texture importanceMap;
if(!settings.importanceMap.empty())
{
size_t width = 0, height = 0, components = 0;
size_t requiredComponents = 1;
imageio::ImageIOData importanceData =
imageio::loadGeneral(settings.importanceMap.c_str(), &width, &height, &components, requiredComponents, 8);
if(width == 0 || height == 0 || components == 0)
{
std::stringstream s; s << "Error: cannot load importance map '" << settings.importanceMap << "'";
throw std::runtime_error(s.str());
}
meshops::TextureConfig config{};
config.width = static_cast<uint32_t>(width);
config.height = static_cast<uint32_t>(height);
config.baseFormat = micromesh::Format::eR8_unorm;
config.internalFormatVk = VK_FORMAT_R8_UNORM;
result = meshops::meshopsTextureCreateFromData(context,
meshops::TextureUsageFlagBit::eTextureUsageRemesherImportanceSource,
config, width * height, importanceData, &importanceMap);
if(result != micromesh::Result::eSuccess)
{
std::stringstream s; s << "Error: cannot create meshops importance map texture '" << micromesh::micromeshResultGetName(result) << "'";
throw std::runtime_error(s.str());
}
importanceParameters.importanceTexture = importanceMap;
importanceParameters.importanceTextureCoord = ((settings.importanceTexcoord == ~0u) ? 0 : settings.importanceTexcoord);
}
if(settings.curvatureMaxDistMode == PyRemesherCurvatureMaxDistanceMode::eWorldSpace)
{
importanceParameters.rayTracingDistance = settings.curvatureMaxDist;
}
if(settings.curvatureMaxDistMode == PyRemesherCurvatureMaxDistanceMode::eSceneFraction)
{
// Scoped here to ensure Python global interpreter lock is
// released while this function does all its heavy lifting
py::gil_scoped_release release;
meshops::ContextConfig contextConfig;
result = meshops::meshopsContextGetConfig(context, &contextConfig);
if(result != micromesh::Result::eSuccess)
{
std::stringstream s; s << "Error: cannot get meshops config '" << micromesh::micromeshResultGetName(result) << "'";
throw std::runtime_error(s.str());
}
float scale = meshopsComputeMeshViewExtent(context, meshView);
importanceParameters.rayTracingDistance = settings.curvatureMaxDist * scale;
}
{
// Scoped here to ensure Python global interpreter lock is
// released while this function does all its heavy lifting
py::gil_scoped_release release;
result = meshops::meshopsOpGenerateImportance(context, generateImportanceOperator, 1, &importanceParameters);
if(result != micromesh::Result::eSuccess)
{
std::stringstream s; s << "Error: cannot generate vertex importance '" << micromesh::micromeshResultGetName(result) << "'";
throw std::runtime_error(s.str());
}
}
if(!settings.importanceMap.empty())
{
meshops::meshopsTextureDestroy(context, importanceMap);
}
meshops::OpRemesh_input input{};
input.errorThreshold = settings.errorThreshold;
input.maxOutputTriangleCount = settings.maxOutputTriangleCount;
input.generateMicromeshInfo = !settings.disableMicromeshData;
if(settings.heightmapWidth > 0 && settings.heightmapHeight > 0)
{
input.heightmapTextureCoord = (settings.heightmapTexcoord != ~0u) ? settings.heightmapTexcoord : 0;
}
else
{
input.heightmapTextureCoord = 0;
}
input.heightmapTextureWidth = settings.heightmapWidth;
input.heightmapTextureHeight = settings.heightmapHeight;