-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathrender_delegate.cpp
More file actions
2054 lines (1887 loc) · 84.7 KB
/
render_delegate.cpp
File metadata and controls
2054 lines (1887 loc) · 84.7 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
//
// SPDX-License-Identifier: Apache-2.0
//
// Copyright 2019 Luma Pictures
//
// 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.
//
// Modifications Copyright 2022 Autodesk, Inc.
//
// 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.
#include "render_delegate.h"
#include "reader.h"
#include <pxr/base/tf/getenv.h>
#include <pxr/base/tf/envSetting.h>
#include <pxr/imaging/hd/bprim.h>
#include <pxr/imaging/hd/camera.h>
#include <pxr/imaging/hd/extComputation.h>
#include <pxr/imaging/hd/instancer.h>
#include <pxr/imaging/hd/resourceRegistry.h>
#include <pxr/imaging/hd/rprim.h>
#include <pxr/imaging/hd/tokens.h>
#ifdef ENABLE_SCENE_INDEX
#include <pxr/imaging/hd/dirtyBitsTranslator.h>
#include <pxr/imaging/hd/retainedDataSource.h>
#endif
#include <common_utils.h>
#include <constant_strings.h>
#include <shape_utils.h>
#include "basis_curves.h"
#include "camera.h"
#include "config.h"
#include "gaussian_splat.h"
#include "instancer.h"
#include "light.h"
#include "mesh.h"
#include "native_rprim.h"
#include "node_graph.h"
#include "nodes/nodes.h"
#include "openvdb_asset.h"
#include "options.h"
#include "points.h"
#include "procedural_custom.h"
#include "render_buffer.h"
#include "render_pass.h"
#include "volume.h"
#include <cctype>
#ifdef ENABLE_HYDRA2_RENDERSETTINGS
#include "render_settings.h"
#endif
PXR_NAMESPACE_OPEN_SCOPE
// clang-format off
TF_DEFINE_PRIVATE_TOKENS(_tokens,
(arnold)
((aovDriverFormat, "driver:parameters:aov:format"))
((aovFormat, "arnold:format"))
(ArnoldOptions)
(openvdbAsset)
((arnoldGlobal, "arnold:global:"))
((arnoldDriver, "arnold:driver"))
((arnoldNamespace, "arnold:"))
((colorManagerNamespace, "color_manager:"))
(batchCommandLine)
(percentDone)
(totalClockTime)
(renderProgressAnnotation)
(delegateRenderProducts)
(orderedVars)
((aovSettings, "aovDescriptor.aovSettings"))
(productType)
(productName)
(pixelAspectRatio)
(driver_exr)
(sourceType)
(sourceName)
(dataType)
(huskErrorStatus)
((format, "aovDescriptor.format"))
((clearValue, "aovDescriptor.clearValue"))
((multiSampled, "aovDescriptor.multiSampled"))
((aovName, "driver:parameters:aov:name"))
(deep)
(raw)
(instantaneousShutter)
((aovShadersArray, "aov_shaders:i"))
(GeometryLight)
(dataWindowNDC)
(resolution)
// The following tokens are also defined in read_options.cpp, we need them
// here for the conversion from TfToken to HdFormat, while in read_options they
// are used for the conversion of HdFormat to TfToken.
((_float, "float"))
((_int, "int"))
(i8) (int8)
(ui8) (uint8)
(half) (float16)
(float2) (float3) (float4)
(half2) (half3) (half4)
(color2f) (color3f) (color4f)
(color2h) (color3h) (color4h)
(color2u8) (color3u8) (color4u8)
(color2i8) (color3i8) (color4i8)
(int2) (int3) (int4)
(uint2) (uint3) (uint4)
);
// clang-format on
#define PXR_VERSION_STR \
ARNOLD_XSTR(PXR_MAJOR_VERSION) "." ARNOLD_XSTR(PXR_MINOR_VERSION) "." ARNOLD_XSTR(PXR_PATCH_VERSION)
TF_DEFINE_ENV_SETTING(HDARNOLD_SHAPE_INSTANCING, "", "Set to 0 to disable inner shape instancing");
namespace {
const HdFormat _GetHdFormatFromToken(const TfToken& token)
{
if (token == _tokens->uint8) {
return HdFormatUNorm8;
} else if (token == _tokens->color2u8) {
return HdFormatUNorm8Vec2;
} else if (token == _tokens->color3u8) {
return HdFormatUNorm8Vec3;
} else if (token == _tokens->color4u8) {
return HdFormatUNorm8Vec4;
} else if (token == _tokens->int8) {
return HdFormatSNorm8;
} else if (token == _tokens->color2i8) {
return HdFormatSNorm8Vec2;
} else if (token == _tokens->color3i8) {
return HdFormatSNorm8Vec3;
} else if (token == _tokens->color4i8) {
return HdFormatSNorm8Vec4;
} else if (token == _tokens->half) {
return HdFormatFloat16;
} else if (token == _tokens->half2 || token == _tokens->color2h) {
return HdFormatFloat16Vec2;
} else if (token == _tokens->half3 || token == _tokens->color3h) {
return HdFormatFloat16Vec3;
} else if (token == _tokens->half4 || token == _tokens->color4h) {
return HdFormatFloat16Vec4;
} else if (token == _tokens->_float) {
return HdFormatFloat32;
} else if (token == _tokens->float2 || token == _tokens->color2f) {
return HdFormatFloat32Vec2;
} else if (token == _tokens->float3 || token == _tokens->color3f) {
return HdFormatFloat32Vec3;
} else if (token == _tokens->float4 || token == _tokens->color4f) {
return HdFormatFloat32Vec4;
} else if (token == _tokens->_int) {
return HdFormatInt32;
} else if (token == _tokens->int2) {
return HdFormatInt32Vec2;
} else if (token == _tokens->int3) {
return HdFormatInt32Vec3;
} else if (token == _tokens->int4) {
return HdFormatInt32Vec4;
} else {
return HdFormatInvalid;
}
}
VtValue _GetNodeParamValue(AtNode* node, const AtParamEntry* pentry)
{
if (Ai_unlikely(pentry == nullptr)) {
return {};
}
const auto ptype = AiParamGetType(pentry);
if (ptype == AI_TYPE_INT) {
return VtValue(AiNodeGetInt(node, AiParamGetName(pentry)));
} else if (ptype == AI_TYPE_FLOAT) {
return VtValue(AiNodeGetFlt(node, AiParamGetName(pentry)));
} else if (ptype == AI_TYPE_BOOLEAN) {
return VtValue(AiNodeGetBool(node, AiParamGetName(pentry)));
} else if (ptype == AI_TYPE_STRING || ptype == AI_TYPE_ENUM) {
return VtValue(std::string(AiNodeGetStr(node, AiParamGetName(pentry))));
}
return {};
}
void _SetNodeParam(AtNode* node, const TfToken& key, const VtValue& value)
{
// Some applications might send integers instead of booleans.
if (value.IsHolding<int>()) {
const auto* nodeEntry = AiNodeGetNodeEntry(node);
auto* paramEntry = AiNodeEntryLookUpParameter(nodeEntry, AtString(key.GetText()));
if (paramEntry != nullptr) {
const auto paramType = AiParamGetType(paramEntry);
if (paramType == AI_TYPE_INT) {
AiNodeSetInt(node, AtString(key.GetText()), value.UncheckedGet<int>());
} else if (paramType == AI_TYPE_BOOLEAN) {
AiNodeSetBool(node, AtString(key.GetText()), value.UncheckedGet<int>() != 0);
}
}
// Or longs.
} else if (value.IsHolding<long>()) {
const auto* nodeEntry = AiNodeGetNodeEntry(node);
auto* paramEntry = AiNodeEntryLookUpParameter(nodeEntry, AtString(key.GetText()));
if (paramEntry != nullptr) {
const auto paramType = AiParamGetType(paramEntry);
if (paramType == AI_TYPE_INT) {
AiNodeSetInt(node, AtString(key.GetText()), static_cast<int>(value.UncheckedGet<long>()));
} else if (paramType == AI_TYPE_BOOLEAN) {
AiNodeSetBool(node, AtString(key.GetText()), value.UncheckedGet<long>() != 0);
}
}
// Or long longs.
} else if (value.IsHolding<long long>()) {
const auto* nodeEntry = AiNodeGetNodeEntry(node);
auto* paramEntry = AiNodeEntryLookUpParameter(nodeEntry, AtString(key.GetText()));
if (paramEntry != nullptr) {
const auto paramType = AiParamGetType(paramEntry);
if (paramType == AI_TYPE_INT) {
AiNodeSetInt(node, AtString(key.GetText()), static_cast<int>(value.UncheckedGet<long long>()));
} else if (paramType == AI_TYPE_BOOLEAN) {
AiNodeSetBool(node, AtString(key.GetText()), value.UncheckedGet<long long>() != 0);
}
}
} else if (value.IsHolding<float>()) {
AiNodeSetFlt(node, AtString(key.GetText()), value.UncheckedGet<float>());
} else if (value.IsHolding<double>()) {
AiNodeSetFlt(node, AtString(key.GetText()), static_cast<float>(value.UncheckedGet<double>()));
} else if (value.IsHolding<bool>()) {
AiNodeSetBool(node, AtString(key.GetText()), value.UncheckedGet<bool>());
} else if (value.IsHolding<std::string>()) {
AiNodeSetStr(node, AtString(key.GetText()), AtString(value.UncheckedGet<std::string>().c_str()));
} else if (value.IsHolding<TfToken>()) {
AiNodeSetStr(node, AtString(key.GetText()), AtString(value.UncheckedGet<TfToken>().GetText()));
}
}
inline const TfTokenVector& _SupportedSprimTypes()
{
// Hd_PrimTypeIndex::SyncPrims walks types in this order; every prim of type N
// is fully synced before any prim of type N+1. Light shaders (and filters) can
// target ArnoldNodeGraph prims, which must therefore appear before light types.
// Scene-index dependency forwarding dirties lights when graphs change but does
// not reorder this pass.
static const TfTokenVector r{HdPrimTypeTokens->camera,
HdPrimTypeTokens->material,
str::t_ArnoldNodeGraph,
HdPrimTypeTokens->distantLight,
HdPrimTypeTokens->sphereLight,
HdPrimTypeTokens->diskLight,
HdPrimTypeTokens->rectLight,
HdPrimTypeTokens->cylinderLight,
HdPrimTypeTokens->domeLight,
#ifdef ENABLE_SCENE_INDEX
HdPrimTypeTokens->meshLight,
#endif
_tokens->GeometryLight,
_tokens->ArnoldOptions,
HdPrimTypeTokens->extComputation
/*HdPrimTypeTokens->simpleLight*/};
return r;
}
inline const TfTokenVector& _SupportedBprimTypes(bool ownsUniverse)
{
// For the hydra render delegate plugin, when we own the arnold universe, we don't want
// to support the render settings primitives as Bprims since it will be passed through SetRenderSettings
#if PXR_VERSION >= 2208
if (!ownsUniverse) {
static const TfTokenVector r{HdPrimTypeTokens->renderBuffer, _tokens->openvdbAsset, HdPrimTypeTokens->renderSettings};
return r;
} else
#endif
{
#ifdef ENABLE_HYDRA2_RENDERSETTINGS
static const TfTokenVector r{HdPrimTypeTokens->renderBuffer, _tokens->openvdbAsset, HdPrimTypeTokens->renderSettings};
#else
static const TfTokenVector r{HdPrimTypeTokens->renderBuffer, _tokens->openvdbAsset};
#endif
return r;
}
}
struct SupportedRenderSetting {
/// Constructor with no default value.
SupportedRenderSetting(const char* _label) : label(_label) {}
/// Constructor with a default value.
template <typename T>
SupportedRenderSetting(const char* _label, const T& _defaultValue) : label(_label), defaultValue(_defaultValue)
{
}
TfToken label;
VtValue defaultValue;
};
using SupportedRenderSettings = std::vector<std::pair<TfToken, SupportedRenderSetting>>;
using VtStringArray = VtArray<std::string>;
const SupportedRenderSettings& _GetSupportedRenderSettings()
{
static const auto& config = HdArnoldConfig::GetInstance();
static const SupportedRenderSettings data{
// Global settings to control rendering
{str::t_enable_progressive_render, {"Enable Progressive Render", config.enable_progressive_render}},
{str::t_progressive_min_AA_samples,
{"Progressive Render Minimum AA Samples", config.progressive_min_AA_samples}},
{str::t_enable_adaptive_sampling, {"Enable Adaptive Sampling", config.enable_adaptive_sampling}},
#ifndef __APPLE__
{str::t_enable_gpu_rendering, {"Enable GPU Rendering", config.enable_gpu_rendering}},
#endif
{str::t_interactive_target_fps, {"Target FPS for Interactive Rendering", config.interactive_target_fps}},
{str::t_interactive_target_fps_min,
{"Minimum Target FPS for Interactive Rendering", config.interactive_target_fps_min}},
{str::t_interactive_fps_min, {"Minimum FPS for Interactive Rendering", config.interactive_fps_min}},
// Threading settings
{str::t_threads, {"Number of Threads", config.threads}},
// Sampling settings
{str::t_AA_samples, {"AA Samples", config.AA_samples}},
{str::t_AA_samples_max, {"AA Samples Max"}},
{str::t_GI_diffuse_samples, {"Diffuse Samples", config.GI_diffuse_samples}},
{str::t_GI_specular_samples, {"Specular Samples", config.GI_specular_samples}},
{str::t_GI_transmission_samples, {"Transmission Samples", config.GI_transmission_samples}},
{str::t_GI_sss_samples, {"SubSurface Scattering Samples", config.GI_sss_samples}},
{str::t_GI_volume_samples, {"Volume Samples", config.GI_volume_samples}},
// Depth settings
{str::t_auto_transparency_depth, {"Auto Transparency Depth"}},
{str::t_GI_diffuse_depth, {"Diffuse Depth", config.GI_diffuse_depth}},
{str::t_GI_specular_depth, {"Specular Depth", config.GI_specular_depth}},
{str::t_GI_transmission_depth, {"Transmission Depth", config.GI_transmission_depth}},
{str::t_GI_volume_depth, {"Volume Depth"}},
{str::t_GI_total_depth, {"Total Depth"}},
// Ignore settings
{str::t_abort_on_error, {"Abort On Error", config.abort_on_error}},
{str::t_ignore_textures, {"Ignore Textures"}},
{str::t_ignore_shaders, {"Ignore Shaders"}},
{str::t_ignore_atmosphere, {"Ignore Atmosphere"}},
{str::t_ignore_lights, {"Ignore Lights"}},
{str::t_ignore_shadows, {"Ignore Shadows"}},
{str::t_ignore_subdivision, {"Ignore Subdivision"}},
{str::t_ignore_displacement, {"Ignore Displacement"}},
{str::t_ignore_bump, {"Ignore Bump"}},
{str::t_ignore_motion, {"Ignore Motion"}},
{str::t_ignore_motion_blur, {"Ignore Motion Blur"}},
{str::t_ignore_dof, {"Ignore Depth of Field"}},
{str::t_ignore_smoothing, {"Ignore Smoothing"}},
{str::t_ignore_sss, {"Ignore SubSurface Scattering"}},
{str::t_ignore_operators, {"Ignore Operators"}},
// HTML Report Settings
{str::t_report_file, {"HTML Report Path", config.report_file}},
// Log Settings
{str::t_log_verbosity, {"Log Verbosity (0-5)", config.log_verbosity}},
{str::t_log_file, {"Log File Path", config.log_file}},
// Profiling Settings
{str::t_profile_file, {"File Output for Profiling", config.profile_file}},
// Stats Settings
{str::t_stats_file, {"File Output for Stats", config.stats_file}},
// Search paths
{str::t_plugin_searchpath, {"Plugin search path.", config.plugin_searchpath}},
#if ARNOLD_VERSION_NUM <= 70403
{str::t_plugin_searchpath, {"Plugin search path.", config.plugin_searchpath}},
{str::t_procedural_searchpath, {"Procedural search path.", config.procedural_searchpath}},
#else
{str::t_asset_searchpath, {"Asset search path.", config.asset_searchpath}},
#endif
{str::t_osl_includepath, {"OSL include path.", config.osl_includepath}},
{str::t_subdiv_dicing_camera, {"Subdiv Dicing Camera", std::string{}}},
{str::t_subdiv_frustum_culling, {"Subdiv Frustum Culling"}},
{str::t_subdiv_frustum_padding, {"Subdiv Frustum Padding"}},
{str::t_shader_override, {"Path to the shader_override node graph", std::string{}}},
{str::t_background, {"Path to the background node graph.", std::string{}}},
{str::t_atmosphere, {"Path to the atmosphere node graph.", std::string{}}},
{str::t_aov_shaders, {"Path to the aov_shaders node graph.", std::string{}}},
{str::t_imager, {"Path to the imagers node graph.", std::string{}}},
{str::t_texture_auto_generate_tx, {"Auto-generate Textures to TX", config.auto_generate_tx}},
};
return data;
}
int _GetLogFlagsFromVerbosity(int verbosity)
{
if (verbosity <= 0) {
return 0;
}
if (verbosity >= 5) {
return AI_LOG_ALL & ~AI_LOG_COLOR;
}
int flags = AI_LOG_ERRORS | AI_LOG_TIMESTAMP | AI_LOG_MEMORY | AI_LOG_BACKTRACE;
if (verbosity >= 2) {
flags |= AI_LOG_WARNINGS;
if (verbosity >= 3) {
// Don't want progress without info, as otherwise it never prints a
// "render done" message!
flags |= AI_LOG_INFO | AI_LOG_PROGRESS;
if (verbosity >= 4) {
flags |= AI_LOG_STATS | AI_LOG_PLUGINS;
}
}
}
return flags;
}
template <typename F>
void _CheckForBoolValue(const VtValue& value, F&& f)
{
if (value.IsHolding<bool>()) {
f(value.UncheckedGet<bool>());
} else if (value.IsHolding<int>()) {
f(value.UncheckedGet<int>() != 0);
} else if (value.IsHolding<long>()) {
f(value.UncheckedGet<long>() != 0);
} else if (value.IsHolding<long long>()) {
f(value.UncheckedGet<long long>() != 0);
}
}
template <typename F>
void _CheckForIntValue(const VtValue& value, F&& f)
{
if (value.IsHolding<int>()) {
f(value.UncheckedGet<int>());
} else if (value.IsHolding<long>()) {
f(static_cast<int>(value.UncheckedGet<long>()));
} else if (value.IsHolding<long long>()) {
f(static_cast<int>(value.UncheckedGet<long long>()));
}
}
template <typename F>
void _CheckForFloatValue(const VtValue& value, F&& f)
{
if (value.IsHolding<float>()) {
f(value.UncheckedGet<float>());
} else if (value.IsHolding<double>()) {
f(static_cast<float>(value.UncheckedGet<double>()));
} else if (value.IsHolding<GfHalf>()) {
f(value.UncheckedGet<GfHalf>());
}
}
void _RemoveArnoldGlobalPrefix(const TfToken& key, TfToken& key_new)
{
if (TfStringStartsWith(key, _tokens->arnoldGlobal))
key_new = TfToken{key.GetText() + _tokens->arnoldGlobal.size()};
else if (TfStringStartsWith(key, _tokens->arnoldNamespace))
key_new = TfToken{key.GetText() + _tokens->arnoldNamespace.size()};
else
key_new = key;
}
} // namespace
std::mutex HdArnoldRenderDelegate::_mutexResourceRegistry;
std::atomic_int HdArnoldRenderDelegate::_counterResourceRegistry;
HdResourceRegistrySharedPtr HdArnoldRenderDelegate::_resourceRegistry;
AtNode* HydraArnoldAPI::CreateArnoldNode(const char* type, const char* name)
{
return _renderDelegate->CreateArnoldNode(AtString(type), AtString(name));
}
const AtNode* HydraArnoldAPI::GetProceduralParent() const
{
return _renderDelegate->GetProceduralParent();
}
void HydraArnoldAPI::AddNodeName(const std::string &name, AtNode *node)
{
_renderDelegate->AddNodeName(name, node);
}
AtNode* HydraArnoldAPI::LookupTargetNode(const char* targetName, const AtNode* source, ConnectionType c)
{
return _renderDelegate->LookupNode(targetName, true);
}
const AtString& HydraArnoldAPI::GetPxrMtlxPath()
{
return _renderDelegate->GetPxrMtlxPath();
}
HdArnoldRenderDelegate::HdArnoldRenderDelegate(bool isBatch, const TfToken &context, AtUniverse *universe, AtSessionMode renderSessionType, AtNode* procParent) :
_apiAdapter(this),
_universe(universe),
_procParent(procParent),
_renderSessionType(renderSessionType),
_context(context),
_isBatch(isBatch),
_renderDelegateOwnsUniverse(universe==nullptr)
{
_lightLinkingChanged.store(false, std::memory_order_release);
_meshLightsChanged.store(false, std::memory_order_release);
_id = SdfPath(TfToken(TfStringPrintf("/HdArnoldRenderDelegate_%p", this)));
// use the "render" tag by default
_renderTags.push_back(UsdGeomTokens->render);
// We first need to check if arnold has already been initialized.
// If not, we need to call AiBegin, and the destructor on we'll call AiEnd
bool isArnoldActive =
#if ARNOLD_VERSION_NUM >= 70100
AiArnoldIsActive();
#else
AiUniverseIsActive();
#endif
if (_isBatch && _renderDelegateOwnsUniverse) {
#if ARNOLD_VERSION_NUM >= 70104
// Ensure that the ADP dialog box will not pop up and hang the application
// We only want to do this when we own the universe (e.g. with husk),
// otherwise this would prevent CER from showing up when we're rendering it
// through a procedural, or scene format plugin
AiADPDisableDialogWindow();
AiErrorReportingSetEnabled(false);
#endif
}
if (!isArnoldActive) {
AiADPAddProductMetadata(AI_ADP_PLUGINNAME, AtString{"arnold-usd"});
AiADPAddProductMetadata(AI_ADP_PLUGINVERSION, AtString{AI_VERSION});
AiADPAddProductMetadata(AI_ADP_HOSTNAME, AtString{"Hydra"});
AiADPAddProductMetadata(AI_ADP_HOSTVERSION, AtString{PXR_VERSION_STR});
AiBegin(_renderSessionType);
}
_supportedRprimTypes = {HdPrimTypeTokens->mesh, HdPrimTypeTokens->volume, HdPrimTypeTokens->points,
HdPrimTypeTokens->basisCurves, str::t_procedural_custom};
#if PXR_VERSION >= 2603
_supportedRprimTypes.push_back(HdPrimTypeTokens->particleField);
#endif
if (_mask & AI_NODE_SHAPE) {
auto* shapeIter = AiUniverseGetNodeEntryIterator(AI_NODE_SHAPE);
while (!AiNodeEntryIteratorFinished(shapeIter)) {
const auto* nodeEntry = AiNodeEntryIteratorGetNext(shapeIter);
TfToken rprimType{ArnoldUsdMakeCamelCase(TfStringPrintf("Arnold_%s", AiNodeEntryGetName(nodeEntry)))};
_supportedRprimTypes.push_back(rprimType);
_nativeRprimTypes.insert({rprimType, AiNodeEntryGetNameAtString(nodeEntry)});
NativeRprimParamList paramList;
auto* paramIter = AiNodeEntryGetParamIterator(nodeEntry);
while (!AiParamIteratorFinished(paramIter)) {
const auto* param = AiParamIteratorGetNext(paramIter);
const auto paramName = AiParamGetName(param);
if (ArnoldUsdIgnoreParameter(paramName)) {
continue;
}
paramList.emplace(TfToken{TfStringPrintf("arnold:%s", paramName.c_str())}, param);
}
_nativeRprimParams.emplace(AiNodeEntryGetNameAtString(nodeEntry), std::move(paramList));
AiParamIteratorDestroy(paramIter);
}
AiNodeEntryIteratorDestroy(shapeIter);
}
std::lock_guard<std::mutex> guard(_mutexResourceRegistry);
if (_counterResourceRegistry.fetch_add(1) == 0) {
_resourceRegistry = std::make_shared<HdResourceRegistry>();
}
const auto& config = HdArnoldConfig::GetInstance();
if (_renderDelegateOwnsUniverse) {
// Msg & log settings should be skipped if we have a procedural parent.
// In this case, a procedural shouldn't affect the global scene settings
AiMsgSetConsoleFlags(
#if ARNOLD_VERSION_NUM < 70100
GetRenderSession(),
#else
_universe,
#endif
(config.log_flags_console >= 0) ?
config.log_flags_console : _verbosityLogFlags);
AiMsgSetLogFileFlags(
#if ARNOLD_VERSION_NUM < 70100
GetRenderSession(),
#else
_universe,
#endif
(config.log_flags_file >= 0) ?
config.log_flags_file : _verbosityLogFlags);
if (!config.log_file.empty())
{
AiMsgSetLogFileName(config.log_file.c_str());
}
if (!config.stats_file.empty())
{
AiStatsSetFileName(config.stats_file.c_str());
}
if (!config.profile_file.empty())
{
AiProfileSetFileName(config.profile_file.c_str());
}
}
hdArnoldInstallNodes();
// Check the USD environment variable for custom Materialx node definitions.
// We need to use this to pass it on to Arnold's MaterialX
const char *pxrMtlxPath = std::getenv("PXR_MTLX_STDLIB_SEARCH_PATHS");
if (pxrMtlxPath) {
_pxrMtlxPath = AtString(pxrMtlxPath);
}
if (_renderDelegateOwnsUniverse) {
_universe = AiUniverse();
_renderSession = AiRenderSession(_universe, _renderSessionType);
}
_renderParam = std::make_unique<HdArnoldRenderParam>(this);
// To set the default value.
_fps = _renderParam->GetFPS();
_options = AiUniverseGetOptions(_universe);
if (_renderDelegateOwnsUniverse) {
for (const auto& o : _GetSupportedRenderSettings()) {
_SetRenderSetting(o.first, o.second.defaultValue);
}
AiRenderSetHintStr(
GetRenderSession(), str::render_context, AtString(_context.GetText()));
// We need access to both beauty and P at the same time.
if (_isBatch) {
AiRenderSetHintBool(GetRenderSession(), str::progressive, false);
AiNodeSetBool(_options, str::enable_progressive_render, false);
} else {
AiRenderSetHintBool(GetRenderSession(), str::progressive_show_all_outputs, true);
}
}
// Check if shape instancing is supported
#if ARNOLD_VERSION_NUM >= 70405
std::string envShapeInstancing = TfGetEnvSetting(HDARNOLD_SHAPE_INSTANCING);
_supportShapeInstancing = envShapeInstancing != std::string("0");
#else
_supportShapeInstancing = false;
#endif
}
HdArnoldRenderDelegate::~HdArnoldRenderDelegate()
{
std::lock_guard<std::mutex> guard(_mutexResourceRegistry);
if (_counterResourceRegistry.fetch_sub(1) == 1) {
_resourceRegistry.reset();
}
_renderParam->Interrupt();
if (_renderDelegateOwnsUniverse) {
AiRenderSessionDestroy(GetRenderSession());
AiUniverseDestroy(_universe);
}
}
HdRenderParam* HdArnoldRenderDelegate::GetRenderParam() const { return _renderParam.get(); }
void HdArnoldRenderDelegate::CommitResources(HdChangeTracker* tracker) {}
const TfTokenVector& HdArnoldRenderDelegate::GetSupportedRprimTypes() const { return _supportedRprimTypes; }
const TfTokenVector& HdArnoldRenderDelegate::GetSupportedSprimTypes() const { return _SupportedSprimTypes(); }
const TfTokenVector& HdArnoldRenderDelegate::GetSupportedBprimTypes() const { return _SupportedBprimTypes(_renderDelegateOwnsUniverse); }
void HdArnoldRenderDelegate::_SetRenderSetting(const TfToken& _key, const VtValue& _value)
{
// function to get or create the color manager and set it on the options node
auto getOrCreateColorManager = [](HdArnoldRenderDelegate *renderDelegate, AtNode* options) -> AtNode* {
AtNode* colorManager = static_cast<AtNode*>(AiNodeGetPtr(options, str::color_manager));
if (colorManager == nullptr) {
const char *ocio_path = std::getenv("OCIO");
if (ocio_path) {
colorManager = renderDelegate->CreateArnoldNode(str::color_manager_ocio,
str::color_manager_ocio);
AiNodeSetPtr(options, str::color_manager, colorManager);
AiNodeSetStr(colorManager, str::config, AtString(ocio_path));
}
else
// use the default color manager
colorManager = renderDelegate->LookupNode("ai_default_color_manager_ocio");
}
return colorManager;
};
// When husk/houdini changes frame, they set the new frame number via the render settings.
if (_key == str::t_houdiniFrame) {
if (_value.IsHolding<double>()) {
const float frame = static_cast<float>(_value.UncheckedGet<double>());
AiNodeSetFlt(_options, str::frame, frame);
}
// We want to restart a new render in that case.
_renderParam->Restart();
}
// Special setting that describes custom output, like deep AOVs or other arnold drivers #1422.
if (_key == _tokens->delegateRenderProducts) {
_ParseDelegateRenderProducts(_value);
return;
}
TfToken key;
_RemoveArnoldGlobalPrefix(_key, key);
// Currently usdview can return double for floats, so until it's fixed
// we have to convert doubles to float.
auto value = _value.IsHolding<double>() ? VtValue(static_cast<float>(_value.UncheckedGet<double>())) : _value;
// Certain applications might pass boolean values via ints or longs.
if (key == str::t_enable_gpu_rendering) {
_CheckForBoolValue(value, [&](const bool b) {
AiNodeSetStr(_options, str::render_device, b ? str::GPU : str::CPU);
AiDeviceAutoSelect(GetRenderSession());
});
} else if (key == str::t_log_verbosity) {
if (value.IsHolding<int>()) {
_verbosityLogFlags = _GetLogFlagsFromVerbosity(value.UncheckedGet<int>());
static const auto& config = HdArnoldConfig::GetInstance();
// Do not set the console and file flags, if the corresponding
// environment variable was set in the config
if (config.log_flags_console < 0) {
AiMsgSetConsoleFlags(
#if ARNOLD_VERSION_NUM < 70100
GetRenderSession(),
#else
_universe,
#endif
_verbosityLogFlags);
}
if (config.log_flags_file < 0) {
AiMsgSetLogFileFlags(
#if ARNOLD_VERSION_NUM < 70100
GetRenderSession(),
#else
_universe,
#endif
_verbosityLogFlags);
}
}
} else if (key == str::t_log_file) {
if (value.IsHolding<std::string>()) {
_logFile = value.UncheckedGet<std::string>();
AiMsgSetLogFileName(_logFile.c_str());
}
#if ARNOLD_VERSION_NUM >= 70401
} else if (key == str::t_report_file) {
if (value.IsHolding<std::string>()) {
_reportFile = value.UncheckedGet<std::string>();
AiReportSetFileName(_reportFile.c_str());
}
#endif
} else if (key == str::t_stats_file) {
if (value.IsHolding<std::string>()) {
_statsFile = value.UncheckedGet<std::string>();
AiStatsSetFileName(_statsFile.c_str());
}
} else if (key == str::t_profile_file) {
if (value.IsHolding<std::string>()) {
_profileFile = value.UncheckedGet<std::string>();
AiProfileSetFileName(_profileFile.c_str());
}
} else if (key == str::t_enable_progressive_render) {
if (!_isBatch) {
_CheckForBoolValue(value, [&](const bool b) {
AiRenderSetHintBool(GetRenderSession(), str::progressive, b);
AiNodeSetBool(_options, str::enable_progressive_render, b);
});
}
} else if (key == str::t_progressive_min_AA_samples) {
if (!_isBatch) {
_CheckForIntValue(value, [&](const int i) {
AiRenderSetHintInt(GetRenderSession(), str::progressive_min_AA_samples, i);
});
}
} else if (key == str::t_interactive_target_fps) {
if (!_isBatch) {
if (value.IsHolding<float>()) {
AiRenderSetHintFlt(GetRenderSession(), str::interactive_target_fps, value.UncheckedGet<float>());
}
}
} else if (key == str::t_interactive_target_fps_min) {
if (!_isBatch) {
if (value.IsHolding<float>()) {
AiRenderSetHintFlt(GetRenderSession(), str::interactive_target_fps_min, value.UncheckedGet<float>());
}
}
} else if (key == str::t_interactive_fps_min) {
if (!_isBatch) {
if (value.IsHolding<float>()) {
AiRenderSetHintFlt(GetRenderSession(), str::interactive_fps_min, value.UncheckedGet<float>());
}
}
} else if (key == _tokens->instantaneousShutter) {
// If the arnold-specific attribute "ignore_motion_blur" is set, it should take
// precedence over the usd builtin instantaneousShutter
_CheckForBoolValue(value, [&](const bool b) {
if (!_forceIgnoreMotionBlur)
AiNodeSetBool(_options, str::ignore_motion_blur, b);
});
} else if (key == str::t_ignore_motion_blur) {
_CheckForBoolValue(value, [&](const bool b) {
AiNodeSetBool(_options, str::ignore_motion_blur, b);
_forceIgnoreMotionBlur = true;
});
} else if (key == str::t_houdiniFps) {
_CheckForFloatValue(value, [&](const float f) {
_fps = f;
AiNodeSetFlt(_options, str::fps, _fps);
});
} else if (key == str::t_background) {
ArnoldUsdCheckForSdfPathValue(value, [&](const SdfPath& p) { _background = p; });
} else if (key == str::t_atmosphere) {
ArnoldUsdCheckForSdfPathValue(value, [&](const SdfPath& p) { _atmosphere = p; });
} else if (key == str::t_aov_shaders) {
ArnoldUsdCheckForSdfPathVectorValue(value, [&](const SdfPathVector& p) { _aov_shaders = p; });
} else if (key == str::t_imager) {
ArnoldUsdCheckForSdfPathValue(value, [&](const SdfPath& p) { _imager = p; });
} else if (key == str::t_shader_override) {
ArnoldUsdCheckForSdfPathValue(value, [&](const SdfPath& p) { _shader_override = p; });
} else if (key == str::t_subdiv_dicing_camera) {
ArnoldUsdCheckForSdfPathValue(value, [&](const SdfPath& p) {
_subdiv_dicing_camera = p;
AiNodeSetPtr(_options, str::subdiv_dicing_camera, LookupNode(_subdiv_dicing_camera.GetText()));
});
} else if (key == str::color_space_linear) {
if (value.IsHolding<std::string>()) {
AtNode* colorManager = getOrCreateColorManager(this, _options);
AiNodeSetStr(colorManager, str::color_space_linear, AtString(value.UncheckedGet<std::string>().c_str()));
}
} else if (key == str::color_space_narrow) {
if (value.IsHolding<std::string>()) {
AtNode* colorManager = getOrCreateColorManager(this, _options);
AiNodeSetStr(colorManager, str::color_space_narrow, AtString(value.UncheckedGet<std::string>().c_str()));
}
} else if (key == _tokens->dataWindowNDC) {
if (value.IsHolding<GfVec4f>()) {
_windowNDC = value.UncheckedGet<GfVec4f>();
}
} else if (key == _tokens->pixelAspectRatio) {
if (value.IsHolding<float>()) {
_pixelAspectRatio = value.UncheckedGet<float>();
}
}
else if (key == _tokens->resolution) {
if (value.IsHolding<GfVec2i>()) {
_resolution = value.UncheckedGet<GfVec2i>();
}
} else if (key == _tokens->batchCommandLine) {
// Solaris-specific command line, it can have an argument "-o output.exr" to override
// the output image. We might end up using this for arnold drivers
if (value.IsHolding<VtStringArray>()) {
const VtStringArray &commandLine = value.UncheckedGet<VtArray<std::string>>();
for (unsigned int i = 0; i < commandLine.size(); ++i) {
// husk argument for output image
if (commandLine[i] == "-o" && i < commandLine.size() - 2) {
_outputOverride = commandLine[++i];
continue;
}
// husk argument for thread count (#1077)
if ((commandLine[i] == "-j" || commandLine[i] == "--threads")
&& i < commandLine.size() - 2) {
// if for some reason the argument value is not a number, atoi should return 0
// which is also the default arnold value.
AiNodeSetInt(_options, str::threads, std::atoi(commandLine[++i].c_str()));
}
}
}
} else if (TfStringStartsWith(key.GetString(), _tokens->colorManagerNamespace)) {
const char* cmParamCStr = key.GetText() + _tokens->colorManagerNamespace.GetString().size();
AtNode* colorManager = getOrCreateColorManager(this, _options);
AtString cmParamStr(cmParamCStr);
if (AiNodeEntryLookUpParameter(AiNodeGetNodeEntry(colorManager), cmParamStr) != nullptr) {
_SetNodeParam(colorManager, TfToken(cmParamCStr), value);
}
}
else {
auto* optionsEntry = AiNodeGetNodeEntry(_options);
// Sometimes the Render Delegate receives parameters that don't exist
// on the options node. For example, if the host application ignores the
// render setting descriptor list.
if (AiNodeEntryLookUpParameter(optionsEntry, AtString(key.GetText())) != nullptr) {
_SetNodeParam(_options, key, value);
}
}
}
void HdArnoldRenderDelegate::_ParseDelegateRenderProducts(const VtValue& value)
{
// Details about the data layout can be found here:
// https://www.sidefx.com/docs/hdk/_h_d_k__u_s_d_hydra.html#HDK_USDHydraHuskDRP
ClearDelegateRenderProducts();
using DataType = VtArray<HdAovSettingsMap>;
if (!value.IsHolding<DataType>()) {
return;
}
auto products = value.UncheckedGet<DataType>();
// For Render Delegate products, we want to eventually create arnold drivers
// during batch rendering #1422
for (auto& productIter : products) {
HdArnoldDelegateRenderProduct product;
const auto* productType = TfMapLookupPtr(productIter, _tokens->productType);
// check the product type, and see if we support it
if (productType == nullptr || !productType->IsHolding<TfToken>())
continue;
TfToken renderProductType = productType->UncheckedGet<TfToken>();
// We only consider render products with type set to "arnold",
// as well as "deep" for backwards compatibility #1422
if (renderProductType != str::t_arnold && renderProductType != _tokens->deep)
continue;
// default driver is exr
TfToken driverType = _tokens->driver_exr;
// Special case for "deep" for backwards compatibility, we want a deepexr driver
if (renderProductType == _tokens->deep)
driverType = str::t_driver_deepexr;
else {
const auto* arnoldDriver = TfMapLookupPtr(productIter, _tokens->arnoldDriver);
if (arnoldDriver != nullptr ) {
// arnold:driver is set in this render product, we use that for the driver type
if (arnoldDriver->IsHolding<TfToken>()) {
driverType = arnoldDriver->UncheckedGet<TfToken>();
} else if (arnoldDriver->IsHolding<std::string>()) {
driverType = TfToken(arnoldDriver->UncheckedGet<std::string>());
}
}
}
// Let's check if a driver type exists as this render product type #1422
if (AiNodeEntryLookUp(AtString(driverType.GetText())) == nullptr) {
// Arnold doesn't know how to render with this driver, let's skip it
AiMsgWarning("Unknown Arnold Driver Type %s", driverType.GetText());
continue;
}
// Ignoring cases where productName is not set.
const auto* productName = TfMapLookupPtr(productIter, _tokens->productName);
if (productName == nullptr || !productName->IsHolding<TfToken>()) {
continue;
}
product.productName = productName->UncheckedGet<TfToken>();
product.productType = driverType;
productIter.erase(_tokens->productType);
productIter.erase(_tokens->productName);
// Elements of the HdAovSettingsMap in the product are either a list of RenderVars or generic attributes
// of the render product.
for (const auto& productElem : productIter) {
// If the key is "aovDescriptor.aovSettings" then we got the list of RenderVars.
if (productElem.first == _tokens->orderedVars) {
if (!productElem.second.IsHolding<DataType>()) {
continue;
}
const auto& renderVars = productElem.second.UncheckedGet<DataType>();
for (const auto& renderVarIter : renderVars) {
HdArnoldRenderVar renderVar;
renderVar.sourceType = _tokens->raw;
// Each element either contains a setting, or "aovDescriptor.aovSettings" which will hold
// extra settings for the RenderVar including metadata.
for (const auto& renderVarElem : renderVarIter) {
if (renderVarElem.first == _tokens->aovSettings) {
if (!renderVarElem.second.IsHolding<HdAovSettingsMap>()) {
continue;
}
renderVar.settings = renderVarElem.second.UncheckedGet<HdAovSettingsMap>();
// name is not coming through as a top parameter.
const auto* aovName = TfMapLookupPtr(renderVar.settings, _tokens->aovName);
if (aovName != nullptr) {
if (aovName->IsHolding<std::string>()) {
renderVar.name = aovName->UncheckedGet<std::string>();
} else if (aovName->IsHolding<TfToken>()) {
renderVar.name = aovName->UncheckedGet<TfToken>().GetString();
}
}
} else if (
renderVarElem.first == _tokens->sourceName &&
renderVarElem.second.IsHolding<std::string>()) {
renderVar.sourceName = renderVarElem.second.UncheckedGet<std::string>();
} else if (
renderVarElem.first == _tokens->sourceType && renderVarElem.second.IsHolding<TfToken>()) {
renderVar.sourceType = renderVarElem.second.UncheckedGet<TfToken>();
} else if (