forked from GafferHQ/gaffer
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathInstancer.cpp
More file actions
3476 lines (2980 loc) · 114 KB
/
Copy pathInstancer.cpp
File metadata and controls
3476 lines (2980 loc) · 114 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
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012, John Haddon. All rights reserved.
// Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "GafferScene/Instancer.h"
#include "GafferScene/Capsule.h"
#include "GafferScene/Orientation.h"
#include "GafferScene/SceneAlgo.h"
#include "GafferScene/Private/ChildNamesMap.h"
#include "GafferScene/Private/RendererAlgo.h"
#include "GafferScene/Private/IECoreScenePreview/Renderer.h"
#include "Gaffer/Context.h"
#include "Gaffer/StringPlug.h"
#include "Gaffer/Private/IECorePreview/LRUCache.h"
#include "IECoreScene/Primitive.h"
#include "IECore/DataAlgo.h"
#include "IECore/MessageHandler.h"
#include "IECore/ObjectVector.h"
#include "IECore/NullObject.h"
#include "IECore/VectorTypedData.h"
#include "boost/lexical_cast.hpp"
#include "boost/unordered_set.hpp"
#include "tbb/blocked_range.h"
#include "tbb/parallel_for.h"
#include "tbb/parallel_reduce.h"
#include "tbb/spin_mutex.h"
#include "fmt/format.h"
#include <functional>
#include <unordered_map>
using namespace std;
using namespace std::placeholders;
using namespace tbb;
using namespace Imath;
using namespace IECore;
using namespace IECoreScene;
using namespace Gaffer;
using namespace GafferScene;
namespace
{
const PrimitiveVariable *findVertexVariable( const IECoreScene::Primitive* primitive, const InternedString &name )
{
PrimitiveVariableMap::const_iterator it = primitive->variables.find( name );
if( it == primitive->variables.end() )
{
return nullptr;
}
if(
it->second.interpolation == IECoreScene::PrimitiveVariable::Vertex ||
(
it->second.interpolation == IECoreScene::PrimitiveVariable::Varying &&
primitive->variableSize( PrimitiveVariable::Vertex ) == primitive->variableSize( PrimitiveVariable::Varying )
)
)
{
return &it->second;
}
return nullptr;
}
// We need to able to quantize all our basic numeric values, so we have a set of templates for this, with
// a special exception if you try to use a non-zero quantize on a type that can't be quantize ( ie. a string ).
//
// We quantize by forcing a value to the closest value that is a multiple of quantize. For vector types,
// this is done independently for each axis.
class QuantizeException {};
template <class T>
inline T quantize( const T &v, float q )
{
if( q != 0.0f )
{
throw QuantizeException();
}
return v;
}
template <>
inline float quantize( const float &v, float q )
{
if( q == 0.0f )
{
return v;
}
// \todo : Higher performance round
float r = q * round( v / q );
// Letting negative zeros slip through is confusing because they hash to different values
if( r == 0 )
{
r = 0;
}
return r;
}
template <>
inline int quantize( const int &v, float q )
{
if( q == 0.0f )
{
return v;
}
int intQuantize = round( q );
if( intQuantize == 0 )
{
return v;
}
int halfQuantize = intQuantize / 2;
return intQuantize * ( ( v + halfQuantize ) / intQuantize );
}
template <class T>
inline Vec2<T> quantize( const Vec2<T> &v, float q )
{
return Vec2<T>( quantize( v[0], q ), quantize( v[1], q ) );
}
template <class T>
inline Vec3<T> quantize( const Vec3<T> &v, float q )
{
return Vec3<T>( quantize( v[0], q ), quantize( v[1], q ), quantize( v[2], q ) );
}
template <>
inline Color3f quantize( const Color3f &v, float q )
{
return Color3f( quantize( v[0], q ), quantize( v[1], q ), quantize( v[2], q ) );
}
template <>
inline Color4f quantize( const Color4f &v, float q )
{
return Color4f( quantize( v[0], q ), quantize( v[1], q ), quantize( v[2], q ), quantize( v[3], q ) );
}
// An internal struct for storing everything we need to know about a context modification we're making
// when accessing the prototypes scene
struct PrototypeContextVariable
{
InternedString name; // Name of context variable
const PrimitiveVariable *primVar; // Primitive variable that drives it
float quantize; // The interval we quantize to
bool offsetMode; // Special mode for adding to existing variable instead of replacing
bool seedMode; // Special mode for seed context which is driven from the id
int numSeeds; // When in seedMode, the number of distinct seeds to output
int seedScramble; // A random seed that affects how seeds are generated
};
// A functor for use with IECore::dispatch that sets a variable in a context, based on a PrototypeContextVariable
// struct
struct AccessPrototypeContextVariable
{
template< class T>
void operator()( const TypedData<vector<T>> *data, const PrototypeContextVariable &v, size_t index, Context::EditableScope &scope )
{
T raw = PrimitiveVariable::IndexedView<T>( *v.primVar )[index];
T value = quantize( raw, v.quantize );
scope.setAllocated( v.name, value );
}
void operator()( const TypedData<vector<float>> *data, const PrototypeContextVariable &v, size_t index, Context::EditableScope &scope )
{
float raw = PrimitiveVariable::IndexedView<float>( *v.primVar )[index];
float value = quantize( raw, v.quantize );
if( v.offsetMode )
{
scope.setAllocated( v.name, value + scope.context()->get<float>( v.name ) );
}
else
{
scope.setAllocated( v.name, value );
}
}
void operator()( const TypedData<vector<int>> *data, const PrototypeContextVariable &v, size_t index, Context::EditableScope &scope )
{
int raw = PrimitiveVariable::IndexedView<int>( *v.primVar )[index];
int value = quantize( raw, v.quantize );
if( v.offsetMode )
{
scope.setAllocated( v.name, float(value) + scope.context()->get<float>( v.name ) );
}
else
{
scope.setAllocated( v.name, value );
}
}
void operator()( const Data *data, const PrototypeContextVariable &v, size_t index, Context::EditableScope &scope )
{
throw IECore::Exception( "Context variable prim vars must contain vector data" );
}
};
// A functor for use with IECore::dispatch that adds to a hash, based on a PrototypeContextVariable
// struct. This is only used to count the number of unique hashes, so we can take some shortcuts, for
// example, we ignore the offsetMode, because adding the offsets to a different global time doesn't change
// the number of unique offsets. We also ignore the name of the context variable, since we always process
// the same PrototypeContextVariables in the same order
struct UniqueHashPrototypeContextVariable
{
template< class T>
void operator()( const TypedData<vector<T>> *data, const PrototypeContextVariable &v, size_t index, MurmurHash &contextHash )
{
T raw = PrimitiveVariable::IndexedView<T>( *v.primVar )[index];
T value = quantize( raw, v.quantize );
contextHash.append( value );
}
void operator()( const Data *data, const PrototypeContextVariable &v, int index, MurmurHash &contextHash )
{
throw IECore::Exception( "Context variable prim vars must contain vector data" );
}
};
InternedString g_prototypeRootName( "root" );
ConstInternedStringVectorDataPtr g_emptyNames = new InternedStringVectorData();
struct IdData
{
IdData() :
intElements( nullptr ), int64Elements( nullptr )
{
}
void initialize( const Primitive *primitive, const std::string &name )
{
if( const IntVectorData *intData = primitive->variableData<IntVectorData>( name ) )
{
intElements = &intData->readable();
}
else if( const Int64VectorData *int64Data = primitive->variableData<Int64VectorData>( name ) )
{
int64Elements = &int64Data->readable();
}
}
size_t size() const
{
if( intElements )
{
return intElements->size();
}
else if( int64Elements )
{
return int64Elements->size();
}
else
{
return 0;
}
}
int64_t element( size_t i ) const
{
if( intElements )
{
return (*intElements)[i];
}
else
{
return (*int64Elements)[i];
}
}
const std::vector<int> *intElements;
const std::vector<int64_t> *int64Elements;
};
// We create a seed integer that corresponds to the id by hashing the id and then modulo'ing to
// numSeeds, to create seeds in the range 0 .. numSeeds-1 that persistently correspond to the ids,
// with a grouping pattern that can be changed with seedScramble
int seedForPoint( size_t index, const IdData &idData, int numSeeds, int seedScramble )
{
int64_t id = index;
if( idData.size() )
{
id = idData.element( index );
}
// numSeeds is set to 0 when we're just passing through the id
if( numSeeds != 0 )
{
// The method used for random generation of seeds is actually rather important.
// We need a random access RNG which allows evaluating any input id independently,
// and should not create lattice artifacts if interpreted as a spacial attribute
// such as size. This is actually a somewhat demanding set of criteria - many
// easy to seed RNGs with a small state space could create lattice artifacts.
//
// Using MurmurHash doesn't seem conceptually perfect, but it uses code we already
// have around, should perform fairly well ( might help if the constructor was inlined ),
// and I've tested for lattice artifacts by generating 200 000 points with Y set to
// seedId, and X set to point index. These points looked good, with even distribution
// and no latticing, so this is probably a reasonable approach to stick with
IECore::MurmurHash seedHash;
seedHash.append( seedScramble );
if( id <= INT32_MAX && id >= INT_MIN )
{
// This branch shouldn't be needed, we'd like to just treat ids as 64 bit now ...
// but if we just took the branch below, that would changing the seeding of existing
// scenes.
seedHash.append( (int)id );
}
else
{
seedHash.append( id );
}
id = int( ( double( seedHash.h1() ) / double( UINT64_MAX ) ) * double( numSeeds ) );
id = id % numSeeds; // For the rare case h1 / max == 1.0, make sure we stay in range
}
return id;
}
std::atomic<int> g_instancerCount( 0 );
bool checkEnvFlag( const char *envVar, bool def )
{
const char *value = getenv( envVar );
if( value )
{
return std::string( value ) != "0";
}
else
{
return def;
}
}
}
//////////////////////////////////////////////////////////////////////////
// EngineData
//////////////////////////////////////////////////////////////////////////
// Custom Data derived class used to encapsulate the data and
// logic needed to generate instances. We are deliberately omitting
// a custom TypeId etc because this is just a private class.
class Instancer::EngineData : public Data
{
public :
EngineData(
ConstPrimitivePtr primitive,
PrototypeMode mode,
const std::string &prototypeIndexName,
const std::string &rootsVariable,
const StringVectorData *rootsList,
const std::string &idName,
bool omitDuplicateIds,
const std::string &position,
const std::string &orientation,
const std::string &scale,
const std::string &inactiveIds,
const std::string &attributes,
const std::string &attributePrefix,
const std::vector< PrototypeContextVariable > &prototypeContextVariables
)
: m_primitive( primitive ),
m_numPrototypes( 0 ),
m_numValidPrototypes( 0 ),
m_prototypeIndices( nullptr ),
m_positions( nullptr ),
m_orientations( nullptr ),
m_scales( nullptr ),
m_uniformScales( nullptr ),
m_prototypeContextVariables( prototypeContextVariables )
{
if( !m_primitive )
{
return;
}
initPrototypes( mode, prototypeIndexName, rootsVariable, rootsList );
m_ids.initialize( m_primitive.get(), idName );
if( m_ids.size() && m_ids.size() != numPoints() )
{
throw IECore::Exception( fmt::format( "Id primitive variable \"{}\" has incorrect size", idName ) );
}
if( const V3fVectorData *p = m_primitive->variableData<V3fVectorData>( position ) )
{
m_positions = &p->readable();
if( m_positions->size() != numPoints() )
{
throw IECore::Exception( fmt::format( "Position primitive variable \"{}\" has incorrect size", position ) );
}
}
if( const QuatfVectorData *o = m_primitive->variableData<QuatfVectorData>( orientation ) )
{
m_orientations = &o->readable();
if( m_orientations->size() != numPoints() )
{
throw IECore::Exception( fmt::format( "Orientation primitive variable \"{}\" has incorrect size", orientation ) );
}
}
if( const V3fVectorData *s = m_primitive->variableData<V3fVectorData>( scale ) )
{
m_scales = &s->readable();
if( m_scales->size() != numPoints() )
{
throw IECore::Exception( fmt::format( "Scale primitive variable \"{}\" has incorrect size", scale ) );
}
}
else if( const FloatVectorData *s = m_primitive->variableData<FloatVectorData>( scale ) )
{
m_uniformScales = &s->readable();
if( m_uniformScales->size() != numPoints() )
{
throw IECore::Exception( fmt::format( "Uniform scale primitive variable \"{}\" has incorrect size", scale ) );
}
}
if( m_ids.size() )
{
for( size_t i = 0, e = numPoints(); i < e; ++i )
{
int64_t id = m_ids.element(i);
auto ins = m_idsToPointIndices.try_emplace( id, i );
if( !ins.second )
{
// We have multiple indices trying to use this id.
if( !omitDuplicateIds )
{
throw IECore::Exception( fmt::format( "Instance id \"{}\" is duplicated at index {} and {}. This probably indicates invalid source data, if you want to hack around it, you can set \"omitDuplicateIds\".", id, m_idsToPointIndices[id], i ) );
}
if( !m_indicesInactive.size() )
{
m_indicesInactive.resize( numPoints(), false );
}
// If we're omitting duplicate ids, then we need to omit both the current index, and
// the index that first tried to use this id.
m_indicesInactive[ i ] = true;
m_indicesInactive[ ins.first->second ] = true;
}
}
}
std::vector<std::string> inactiveIdVarNames;
IECore::StringAlgo::tokenize( inactiveIds, ' ', inactiveIdVarNames );
for( std::string &inactiveIdVarName : inactiveIdVarNames )
{
if( m_primitive->variables.find( inactiveIdVarName ) == m_primitive->variables.end() )
{
continue;
}
const PrimitiveVariable *vertexInactiveVar = findVertexVariable( m_primitive.get(), inactiveIdVarName );
if( vertexInactiveVar )
{
if( IECore::size( vertexInactiveVar->data.get() ) != numPoints() )
{
throw IECore::Exception( fmt::format( "Inactive primitive variable \"{}\" has incorrect size", inactiveIdVarName ) );
}
if( const auto *vertexInactiveData = IECore::runTimeCast<BoolVectorData>( vertexInactiveVar->data.get() ) )
{
const std::vector<bool> &vertexInactive = vertexInactiveData->readable();
if( !m_indicesInactive.size() )
{
// If we don't already have an inactive array set up, we can just directly copy the data
// from a vertex primitive variable. Technically, we might not even need to do this copy,
// if there aren't any other inactive vars we're merging with, we could just have a
// separate way of storing a const pointer for this case, but given that this data is
// 32X smaller than any of our other per-vertex data anyway, it's probably fine to pay
// the cost of copying it in exchange for slightly simpler code.
m_indicesInactive = vertexInactive;
}
else
{
for( size_t i = 0; i < vertexInactive.size(); i++ )
{
if( vertexInactive[i] )
{
m_indicesInactive[ i ] = true;
}
}
}
}
else if( const auto *vertexInactiveIntData = IECore::runTimeCast<IntVectorData>( vertexInactiveVar->data.get() ) )
{
const std::vector<int> &vertexInactiveInt = vertexInactiveIntData->readable();
if( !m_indicesInactive.size() )
{
m_indicesInactive.resize( numPoints(), false );
}
for( size_t i = 0; i < vertexInactiveInt.size(); i++ )
{
if( vertexInactiveInt[i] )
{
m_indicesInactive[ i ] = true;
}
}
}
continue;
}
IdData idData;
idData.initialize( m_primitive.get(), inactiveIdVarName );
size_t idSize = idData.size();
if( !idSize )
{
continue;
}
if( !m_indicesInactive.size() )
{
m_indicesInactive.resize( numPoints(), false );
}
if( m_idsToPointIndices.size() )
{
for( size_t i = 0; i < idSize; i++ )
{
auto it = m_idsToPointIndices.find( idData.element(i) );
if( it == m_idsToPointIndices.end() )
{
// I wish I could throw here ... it would be a really helpful clue to get an error
// if you've accidentally chosen a bad id. But ids might be changing over time, so
// we probably need to allow someone to deactivate an id even if it doesn't exist
// on all frames.
continue;
}
m_indicesInactive[ it->second ] = true;
}
}
else
{
for( size_t i = 0; i < idSize; i++ )
{
int64_t id = idData.element(i);
if( id < 0 || id >= (int64_t)m_indicesInactive.size() )
{
continue;
}
m_indicesInactive[ id ] = true;
}
}
}
initAttributes( attributes, attributePrefix );
for( const auto &v : m_prototypeContextVariables )
{
// We need to check if the primVars driving the context are the right size.
// There's not an easy way to do this on PrimitiveVariable without knowing the type,
// but we can check that it is valid for the primitive, and that the primitive size for that
// variable is correct
if( v.primVar && !(
m_primitive->isPrimitiveVariableValid( *v.primVar ) &&
m_primitive->variableSize( v.primVar->interpolation ) == numPoints()
) )
{
throw IECore::Exception( fmt::format( "Context primitive variable for \"{}\" is not a correctly sized Vertex primitive variable", v.name.string() ) );
}
}
}
size_t numPoints() const
{
return m_primitive ? m_primitive->variableSize( PrimitiveVariable::Vertex ) : 0;
}
int64_t instanceId( size_t pointIndex ) const
{
return m_ids.size() ? m_ids.element( pointIndex ) : pointIndex;
}
size_t pointIndex( int64_t i ) const
{
if( !m_ids.size() )
{
if( i >= (int64_t)numPoints() || i < 0 )
{
throw IECore::Exception( fmt::format( "Instance id \"{}\" is invalid, instancer produces only {} children. Topology may have changed during shutter.", i, numPoints() ) );
}
return i;
}
IdsToPointIndices::const_iterator it = m_idsToPointIndices.find( i );
if( it == m_idsToPointIndices.end() )
{
throw IECore::Exception( fmt::format( "Instance id \"{}\" is invalid. Topology may have changed during shutter.", i ) );
}
return it->second;
}
size_t pointIndex( const InternedString &name ) const
{
return pointIndex( boost::lexical_cast<size_t>( name ) );
}
size_t numValidPrototypes() const
{
return m_numValidPrototypes;
}
int prototypeIndex( size_t pointIndex ) const
{
if( m_numPrototypes == 0 )
{
return -1;
}
if( m_indicesInactive.size() )
{
// If this point is tagged as inactive ( could be due to a user specified inactiveIds,
// or due to an id collision when omitDuplicateIds is set ), then we return -1 for
// the prototype, which means to omit this point.
if( m_indicesInactive[pointIndex] )
{
return -1;
}
}
if( m_prototypeIndices )
{
return m_prototypeIndexRemap[ (*m_prototypeIndices)[pointIndex] % m_numPrototypes ];
}
else
{
return m_prototypeIndexRemap[ 0 ];
}
}
// Return a pointer since this is for internal use only, and it helps communicate that we
// are responsible for holding the storage for this scene path when it gets put in the context
const ScenePlug::ScenePath *prototypeRoot( const InternedString &name, const ScenePlug::ScenePath &enginePath, ScenePlug::ScenePath &storage ) const
{
return prototypeRoot( m_names->input( name ).index, enginePath, storage );
}
const ScenePlug::ScenePath *prototypeRoot( int prototypeId, const ScenePlug::ScenePath &enginePath, ScenePlug::ScenePath &storage ) const
{
if( m_roots[prototypeId].relative )
{
const ScenePlug::ScenePath &prototypePath = m_roots[prototypeId].path->readable();
storage.resize( 0 );
storage.reserve( enginePath.size() + prototypePath.size() );
storage.insert( storage.end(), enginePath.begin(), enginePath.end() );
storage.insert( storage.end(), prototypePath.begin(), prototypePath.end() );
return &storage;
}
else
{
return &( m_roots[prototypeId].path->readable() );
}
}
const InternedStringVectorData *prototypeNames() const
{
return m_names ? m_names->outputChildNames() : g_emptyNames.get();
}
M44f instanceTransform( size_t pointIndex ) const
{
M44f result;
if( m_positions )
{
result.translate( (*m_positions)[pointIndex] );
}
if( m_orientations )
{
// Using Orientation::normalizedIfNeeded avoids modifying quaternions that are already
// normalized. It's better for consistency to not be pointlessly changing the values
// slightly at the limits of floating point precision, when they're already as close to
// normalized as they can get, and this saves 4% runtime on InstancerTest.testBoundPerformance.
result = Orientation::normalizedIfNeeded((*m_orientations)[pointIndex]).toMatrix44() * result;
}
if( m_scales )
{
result.scale( (*m_scales)[pointIndex] );
}
if( m_uniformScales )
{
result.scale( V3f( (*m_uniformScales)[pointIndex] ) );
}
return result;
}
size_t numInstanceAttributes() const
{
return m_attributeCreators.size();
}
void instanceAttributesHash( size_t pointIndex, MurmurHash &h ) const
{
h.append( m_attributesHash );
h.append( (uint64_t)pointIndex );
}
void instanceAttributes( size_t pointIndex, CompoundObject &result ) const
{
CompoundObject::ObjectMap &writableResult = result.members();
for( const auto &attributeCreator : m_attributeCreators )
{
writableResult[attributeCreator.first] = attributeCreator.second( pointIndex );
}
}
using PrototypeHashes = std::map<InternedString, boost::unordered_set<IECore::MurmurHash>>;
// In order to compute the number of variations, we compute a unique hash for every context we use
// for evaluating prototypes. So that we can track which sources are responsible for variations,
// we return a map of hash sets, with a set of hashes for each variable name in
// m_prototypeContextVariables, plus an extra entry for "" for the combined result of all variation
// sources
std::unique_ptr<PrototypeHashes> uniquePrototypeHashes() const
{
std::vector< boost::unordered_set< IECore::MurmurHash > > variableHashAccumulate( m_prototypeContextVariables.size() );
boost::unordered_set< IECore::MurmurHash > totalHashAccumulate;
size_t n = numPoints();
for( size_t i = 0; i < n; i++ )
{
int protoIndex = prototypeIndex( i );
if( protoIndex == -1 )
{
continue;
}
IECore::MurmurHash totalHash;
const auto &rootPath = m_roots[ protoIndex ];
// Note that we are rehashing the root path for every point, even though they are heavily
// reused. This seems suboptimal, but is simpler, and the more complex version doesn't
// appear to make any performance difference in practice
totalHash.append( &(rootPath.path->readable())[0], rootPath.path->readable().size() );
totalHash.append( rootPath.relative );
for( unsigned int j = 0; j < m_prototypeContextVariables.size(); j++ )
{
IECore::MurmurHash r; // TODO - if we're using this in inner loops, the constructor should probably be inlined?
hashPrototypeContextVariable( i, m_prototypeContextVariables[j], r );
variableHashAccumulate[j].insert( r );
totalHash.append( r );
}
totalHashAccumulate.insert( totalHash );
}
auto result = std::make_unique<PrototypeHashes>();
for( unsigned int j = 0; j < m_prototypeContextVariables.size(); j++ )
{
(*result)[ m_prototypeContextVariables[j].name ] = variableHashAccumulate[j];
}
(*result)[ "" ] = totalHashAccumulate;
return result;
}
bool hasContextVariables() const
{
return m_prototypeContextVariables.size() != 0;
}
// Set the context variables in the context for this point index, based on the m_prototypeContextVariables
// set up for this EngineData
void setPrototypeContextVariables( size_t pointIndex, Context::EditableScope &scope ) const
{
for( unsigned int i = 0; i < m_prototypeContextVariables.size(); i++ )
{
const PrototypeContextVariable &v = m_prototypeContextVariables[i];
if( v.seedMode )
{
scope.setAllocated( v.name, seedForPoint( pointIndex, m_ids, v.numSeeds, v.seedScramble ) );
continue;
}
if( !v.primVar )
{
continue;
}
try
{
IECore::dispatch( v.primVar->data.get(), AccessPrototypeContextVariable(), v, pointIndex, scope );
}
catch( QuantizeException & )
{
throw IECore::Exception( fmt::format( "Context variable \"{}\" : cannot quantize variable of type {}", v.name.string(), v.primVar->data->typeName() ) );
}
}
}
protected :
// Needs to match setPrototypeContextVariables above, except that it operates on one
// PrototypeContextVariable at a time instead of iterating through them
void hashPrototypeContextVariable( size_t pointIndex, const PrototypeContextVariable &v, IECore::MurmurHash &result ) const
{
if( v.seedMode )
{
result.append( seedForPoint( pointIndex, m_ids, v.numSeeds, v.seedScramble ) );
return;
}
if( !v.primVar )
{
return;
}
try
{
IECore::dispatch( v.primVar->data.get(), UniqueHashPrototypeContextVariable(), v, pointIndex, result );
}
catch( QuantizeException & )
{
throw IECore::Exception( fmt::format( "Context variable \"{}\" : cannot quantize variable of type {}", v.name.string(), v.primVar->data->typeName() ) );
}
}
void copyFrom( const Object *other, CopyContext *context ) override
{
Data::copyFrom( other, context );
msg( Msg::Warning, "EngineData::copyFrom", "Not implemented" );
}
void save( SaveContext *context ) const override
{
Data::save( context );
msg( Msg::Warning, "EngineData::save", "Not implemented" );
}
void load( LoadContextPtr context ) override
{
Data::load( context );
msg( Msg::Warning, "EngineData::load", "Not implemented" );
}
private :
using AttributeCreator = std::function<DataPtr ( size_t )>;
struct MakeAttributeCreator
{
template<typename T>
AttributeCreator operator()( const TypedData<vector<T>> *data )
{
return std::bind( &createAttribute<T>, data->readable(), std::placeholders::_1 );
}
template<typename T>
AttributeCreator operator()( const GeometricTypedData<vector<T>> *data )
{
return std::bind( &createGeometricAttribute<T>, data->readable(), data->getInterpretation(), std::placeholders::_1 );
}
AttributeCreator operator()( const Data *data )
{
throw IECore::InvalidArgumentException( "Expected VectorTypedData" );
}
private :
template<typename T>
static DataPtr createAttribute( const vector<T> &values, size_t index )
{
return new TypedData<T>( values[index] );
}
template<typename T>
static DataPtr createGeometricAttribute( const vector<T> &values, GeometricData::Interpretation interpretation, size_t index )
{
return new GeometricTypedData<T>( values[index], interpretation );
}
};
void initAttributes( const std::string &attributes, const std::string &attributePrefix )
{
m_attributesHash.append( attributePrefix );
for( auto &primVar : m_primitive->variables )
{
if( !(
primVar.second.interpolation == PrimitiveVariable::Vertex ||
(
primVar.second.interpolation == PrimitiveVariable::Varying &&
m_primitive->variableSize( PrimitiveVariable::Vertex ) == m_primitive->variableSize( PrimitiveVariable::Varying )
)
) )
{
continue;
}
if( !StringAlgo::matchMultiple( primVar.first, attributes ) )
{
continue;
}
DataPtr d = primVar.second.expandedData();
AttributeCreator attributeCreator = dispatch( d.get(), MakeAttributeCreator() );
m_attributeCreators[attributePrefix + primVar.first] = attributeCreator;
m_attributesHash.append( primVar.first );
d->hash( m_attributesHash );
}
}
void initPrototypes( PrototypeMode mode, const std::string &prototypeIndex, const std::string &rootsVariable, const StringVectorData *rootsList )
{
const std::vector<std::string> *rootStrings = nullptr;
std::vector<std::string> rootStringsAlloc;
switch( mode )
{
case PrototypeMode::IndexedRootsList :
{
if( const auto *prototypeIndices = m_primitive->variableData<IntVectorData>( prototypeIndex ) )
{
m_prototypeIndices = &prototypeIndices->readable();
if( m_prototypeIndices->size() != numPoints() )
{
throw IECore::Exception( fmt::format( "prototypeIndex primitive variable \"{}\" has incorrect size", prototypeIndex ) );
}
}
rootStrings = &rootsList->readable();
break;
}
case PrototypeMode::IndexedRootsVariable :
{
if( const auto *prototypeIndices = m_primitive->variableData<IntVectorData>( prototypeIndex ) )
{
m_prototypeIndices = &prototypeIndices->readable();
if( m_prototypeIndices->size() != numPoints() )
{
throw IECore::Exception( fmt::format( "prototypeIndex primitive variable \"{}\" has incorrect size", prototypeIndex ) );
}
}
const auto *roots = m_primitive->variableData<StringVectorData>( rootsVariable, PrimitiveVariable::Constant );
if( !roots )