-
Notifications
You must be signed in to change notification settings - Fork 178
Expand file tree
/
Copy pathBaseMeshSync.cs
More file actions
3136 lines (2578 loc) · 116 KB
/
BaseMeshSync.cs
File metadata and controls
3136 lines (2578 loc) · 116 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
using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Animations;
using Unity.Collections;
using UnityEngine.Assertions;
using System.IO;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using Unity.FilmInternalUtilities;
using UnityEngine.Rendering; //Volume, IndexFormat
#if AT_USE_SPLINES
using Unity.Mathematics;
#endif
#if AT_USE_HDRP
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.Experimental.Rendering;
#endif
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.SceneManagement;
using Unity.FilmInternalUtilities.Editor;
#endif
[assembly: InternalsVisibleTo("Unity.Utilities.VariantExport")]
namespace Unity.MeshSync {
/// <summary>
/// A delegate to handle scene updates
/// </summary>
internal delegate void SceneHandler();
/// <summary>
/// A delegate to handle audio updates
/// </summary>
internal delegate void UpdateAudioHandler(AudioClip audio, AudioData data);
/// <summary>
/// A delegate to handle texture updates
/// </summary>
internal delegate void UpdateTextureHandler(Texture2D tex, TextureData data);
/// <summary>
/// A delegate to handle material updates
/// </summary>
internal delegate void UpdateMaterialHandler(Material mat, MaterialData data);
/// <summary>
/// A delegate to handle entity updates
/// </summary>
internal delegate void UpdateEntityHandler(GameObject obj, TransformData data);
/// <summary>
/// A delegate to handle animation updates
/// </summary>
internal delegate void UpdateAnimationHandler(AnimationClip anim, AnimationClipData data);
/// <summary>
/// A delegate to handle entity deletions
/// </summary>
internal delegate void DeleteEntityHandler(GameObject obj);
/// <summary>
/// A delegate to handle instance info updates
/// </summary>
/// <param name="data"></param>
internal delegate void UpdateInstanceInfoHandler(string path, GameObject go, Matrix4x4[] transforms);
/// <summary>
/// A delegate to handle instance meshes.
/// </summary>
internal delegate void UpdateInstancedEntityHandler(string path, GameObject go);
/// <summary>
/// A delegate to handle instance deletions
/// </summary>
internal delegate void DeleteInstanceHandler(string path);
/// <summary>
/// Internal analytics observer data
/// </summary>
public struct MeshSyncAnalyticsData {
internal MeshSyncSessionStartAnalyticsData? sessionStartData;
internal MeshSyncSyncAnalyticsData? syncData;
}
/// <summary>
/// Data about sync.
/// </summary>
public struct MeshSyncSyncAnalyticsData {
internal AssetType assetType;
internal EntityType entityType;
internal string syncMode;
}
/// <summary>
/// Information about the DCC tool used with MeshSync.
/// </summary>
public struct MeshSyncSessionStartAnalyticsData {
public string DCCToolName;
}
//----------------------------------------------------------------------------------------------------------------------
/// <summary>
/// The base class of main MeshSync components (MeshSyncServer, SceneCachePlayer),
/// which encapsulates common functionalities
/// </summary>
[ExecuteInEditMode]
public abstract partial class BaseMeshSync : MonoBehaviour, IObservable<MeshSyncAnalyticsData>, ISerializationCallbackReceiver {
#region EventHandler Declarations
/// <summary>
/// An event that is executed when the scene update is started
/// </summary>
internal event SceneHandler onSceneUpdateBegin;
/// <summary>
/// An event that is executed when an audio is updated
/// </summary>
internal event UpdateAudioHandler onUpdateAudio;
/// <summary>
/// An event that is executed when a texture is updated
/// </summary>
internal event UpdateTextureHandler onUpdateTexture;
/// <summary>
/// An event that is executed when an material is updated
/// </summary>
internal event UpdateMaterialHandler onUpdateMaterial;
/// <summary>
/// An event that is executed when an entity is updated
/// </summary>
internal event UpdateEntityHandler onUpdateEntity;
/// <summary>
/// An event that is executed when an animation is updated
/// </summary>
internal event UpdateAnimationHandler onUpdateAnimation;
/// <summary>
/// An event that is executed when an entity is deleted
/// </summary>
internal event DeleteEntityHandler onDeleteEntity;
/// <summary>
/// An event that is executed when the scene update is finished
/// </summary>
internal event SceneHandler onSceneUpdateEnd;
internal event UpdateInstanceInfoHandler onUpdateInstanceInfo;
internal event UpdateInstancedEntityHandler onUpdateInstancedEntity;
internal event DeleteInstanceHandler onDeleteInstanceInfo;
internal event DeleteInstanceHandler onDeleteInstancedEntity;
#endregion EventHandler Declarations
//----------------------------------------------------------------------------------------------------------------------
internal void Init(string assetsFolder) {
Assert.IsTrue(assetsFolder.StartsWith("Assets"));
m_assetsFolder = assetsFolder.Replace('\\', '/');
m_rootObject = gameObject.transform;
m_materialList.Clear();
m_textureList.Clear();
m_audioList.Clear();
m_clientObjects.Clear();
m_hostObjects.Clear();
m_objIDTable.Clear();
m_clientInstances.Clear();
m_clientInstancedEntities.Clear();
m_prefabDict.Clear();
InitInternalV();
}
private protected abstract void InitInternalV();
//----------------------------------------------------------------------------------------------------------------------
#region Getter/Setter
internal string GetAssetsFolder() {
return m_assetsFolder;
}
public void SetAssetsFolder(string folder) {
m_assetsFolder = folder;
}
internal Transform GetRootObject() {
return m_rootObject;
}
internal void SetRootObject(Transform t) {
m_rootObject = t;
}
internal IDictionary<string, EntityRecord> GetClientObjects() {
return m_clientObjects;
}
#endregion Simple Getter/Setter
#region Properties
[SerializeField] private int currentSessionId = -1;
private bool forceDeleteChildrenInNextSession = false;
private protected string GetServerDocRootPath() {
return Application.streamingAssetsPath + "/MeshSyncServerRoot";
}
private protected void SetSaveAssetsInScene(bool saveAssetsInScene) {
m_saveAssetsInScene = saveAssetsInScene;
}
private protected void MarkMeshesDynamic(bool markMeshesDynamic) {
m_markMeshesDynamic = markMeshesDynamic;
}
internal void EnableKeyValuesSerialization(bool kvEnabled) {
m_keyValuesSerializationEnabled = kvEnabled;
}
internal abstract MeshSyncPlayerConfig GetConfigV();
internal bool useCustomCameraMatrices {
get { return m_useCustomCameraMatrices; }
set { m_useCustomCameraMatrices = value; }
}
internal List<MaterialHolder> materialList {
get { return m_materialList; }
}
internal List<TextureHolder> textureList {
get { return m_textureList; }
}
internal PrefabDictionary prefabDict {
get { return m_prefabDict; }
}
#if UNITY_EDITOR
protected void SetSortEntities(bool sortEntities) {
m_sortEntities = sortEntities;
}
internal bool foldSyncSettings {
get { return m_foldSyncSettings; }
set { m_foldSyncSettings = value; }
}
internal bool foldImportSettings {
get { return m_foldImportSettings; }
set { m_foldImportSettings = value; }
}
internal bool foldMisc {
get { return m_foldMisc; }
set { m_foldMisc = value; }
}
internal bool foldMaterialList {
get { return m_foldMaterialList; }
set { m_foldMaterialList = value; }
}
internal bool foldAnimationTweak {
get { return m_foldAnimationTweak; }
set { m_foldAnimationTweak = value; }
}
internal bool foldExportAssets {
get { return m_foldExportAssets; }
set { m_foldExportAssets = value; }
}
#endif
#endregion
//----------------------------------------------------------------------------------------------------------------------
#region Impl
private void SerializeDictionary<K, V>(Dictionary<K, V> dic, ref K[] keys, ref V[] values) {
keys = dic.Keys.ToArray();
values = dic.Values.ToArray();
}
private void DeserializeDictionary<K, V>(Dictionary<K, V> dic, ref K[] keys, ref V[] values) {
try {
if (keys != null && values != null && keys.Length == values.Length) {
int n = keys.Length;
for (int i = 0; i < n; ++i)
dic[keys[i]] = values[i];
}
}
catch (Exception e) {
Debug.LogError(e);
}
keys = null;
values = null;
}
//----------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Called during serialization as an implementation of ISerializationCallbackReceiver
/// </summary>
public void OnBeforeSerialize() {
OnBeforeSerializeMeshSyncPlayerV();
#if UNITY_EDITOR
SaveMaterialRenderTexturesToAssetDatabase();
#endif
if (!m_keyValuesSerializationEnabled)
return;
SerializeDictionary(m_clientObjects, ref m_clientObjects_keys, ref m_clientObjects_values);
SerializeDictionary(m_hostObjects, ref m_hostObjects_keys, ref m_hostObjects_values);
SerializeDictionary(m_objIDTable, ref m_objIDTable_keys, ref m_objIDTable_values);
m_baseMeshSyncVersion = CUR_BASE_MESHSYNC_VERSION;
}
/// <summary>
/// Called during serialization as an implementation of ISerializationCallbackReceiver
/// </summary>
public void OnAfterDeserialize() {
DeserializeDictionary(m_clientObjects, ref m_clientObjects_keys, ref m_clientObjects_values);
DeserializeDictionary(m_hostObjects, ref m_hostObjects_keys, ref m_hostObjects_values);
DeserializeDictionary(m_objIDTable, ref m_objIDTable_keys, ref m_objIDTable_values);
OnAfterDeserializeMeshSyncPlayerV();
if (CUR_BASE_MESHSYNC_VERSION == m_baseMeshSyncVersion)
return;
if (m_baseMeshSyncVersion < (int)BaseMeshSyncVersion.INITIAL_0_10_0) {
#pragma warning disable 612
MeshSyncPlayerConfig config = GetConfigV();
config?.UsePhysicalCameraParams(m_usePhysicalCameraParams);
#pragma warning restore 612
}
m_baseMeshSyncVersion = CUR_BASE_MESHSYNC_VERSION;
}
private protected abstract void OnBeforeSerializeMeshSyncPlayerV();
private protected abstract void OnAfterDeserializeMeshSyncPlayerV();
//----------------------------------------------------------------------------------------------------------------------
#endregion
#region Misc
//[MethodImpl(MethodImplOptions.AggressiveInlining)]
private protected bool Try(Action act) {
try {
act.Invoke();
return true;
}
catch (Exception e) {
if (GetConfigV().Logging)
Debug.LogError(e);
return false;
}
}
//----------------------------------------------------------------------------------------------------------------------
private void MakeSureAssetDirectoryExists() {
#if UNITY_EDITOR
if (Directory.Exists(m_assetsFolder))
return;
Directory.CreateDirectory(m_assetsFolder);
AssetDatabase.Refresh();
#endif
}
//----------------------------------------------------------------------------------------------------------------------
private bool IsAsset(UnityEngine.Object obj) {
#if UNITY_EDITOR
return AssetDatabase.Contains(obj);
#else
return false;
#endif
}
private bool DestroyIfNotAsset(UnityEngine.Object obj) {
if (obj != null && IsAsset(obj)) {
DestroyImmediate(obj, false);
return true;
}
return false;
}
internal string BuildPath(Transform t) {
Transform parent = t.parent;
if (parent != null && parent != m_rootObject)
return BuildPath(parent) + "/" + t.name;
else
return "/" + t.name;
}
internal static Texture2D FindTexture(int id, List<TextureHolder> textureHolders) {
if (id == Lib.invalidID)
return null;
TextureHolder rec = textureHolders.Find(a => a.id == id);
return rec != null ? rec.texture : null;
}
internal Material FindMaterial(int id) {
if (id == Lib.invalidID)
return null;
MaterialHolder rec = m_materialList.Find(a => a.id == id);
return rec != null ? rec.material : null;
}
internal bool EraseMaterialRecord(int id) {
return m_materialList.RemoveAll(v => v.id == id) != 0;
}
private protected int GetMaterialIndex(Material mat) {
if (mat == null)
return Lib.invalidID;
for (int i = 0; i < m_materialList.Count; ++i)
if (m_materialList[i].material == mat)
return i;
int ret = m_materialList.Count;
MaterialHolder tmp = new MaterialHolder();
tmp.name = mat.name;
tmp.material = mat;
tmp.id = ret + 1;
m_materialList.Add(tmp);
return ret;
}
internal AudioClip FindAudio(int id) {
if (id == Lib.invalidID)
return null;
AudioHolder rec = m_audioList.Find(a => a.id == id);
return rec != null ? rec.audio : null;
}
internal int GetObjectlID(GameObject go) {
if (go == null)
return Lib.invalidID;
if (m_objIDTable.TryGetValue(go, out int ret))
return ret;
ret = ++m_objIDSeed;
m_objIDTable[go] = ret;
return ret;
}
//----------------------------------------------------------------------------------------------------------------------
private static Material CreateDefaultMaterial(string shaderName = null) {
Material mat = new Material(GetShader(shaderName, out _));
UpdateShader(mat, shaderName);
return mat;
}
internal void ForceRepaint() {
#if UNITY_EDITOR
if (!EditorApplication.isPlaying && !EditorApplication.isPaused) {
SceneView.RepaintAll();
UnityEditorInternal.InternalEditorUtility.RepaintAllViews();
}
#endif
}
#endregion
#region ReceiveScene
internal void BeforeUpdateScene(FenceMessage? mes = null) {
onSceneUpdateBegin?.Invoke();
CheckForNewSession(mes);
numberOfPropertiesReceived = 0;
}
public void ForceDeleteChildrenInNextSession() {
forceDeleteChildrenInNextSession = true;
}
private void CheckForNewSession(FenceMessage? mes) {
#if UNITY_EDITOR
if (!mes.HasValue || currentSessionId == mes.Value.SessionId) return;
currentSessionId = mes.Value.SessionId;
SendEventData(new MeshSyncAnalyticsData()
{ sessionStartData = new MeshSyncSessionStartAnalyticsData() { DCCToolName = mes.Value.DCCToolName } });
if (transform.childCount <= 0) return;
int choice;
if (forceDeleteChildrenInNextSession) {
choice = 2;
forceDeleteChildrenInNextSession = false;
}
else {
choice = EditorUtility.DisplayDialogComplex("A new session started.",
"MeshSync detected that the DCC tool session has changed. To ensure that the sync state is correct you can delete previously synced objects, stash them and move them to another game object or ignore this and keep all children.",
"Ignore and keep all children",
"Stash",
"Delete all children of the server");
}
switch (choice) {
case 1:
// Stash
Transform stash = new GameObject($"{name}_stash").transform;
for (int i = transform.childCount - 1; i >= 0; i--) {
Transform child = transform.GetChild(i);
child.SetParent(stash, true);
}
Init(GetAssetsFolder());
break;
case 2:
// Destroy
transform.DestroyChildrenImmediate();
Init(GetAssetsFolder());
break;
}
#endif
}
private protected void UpdateScene(SceneData scene, bool updateNonMaterialAssets, bool logAnalytics = true) {
MeshSyncPlayerConfig config = GetConfigV();
// handle assets
Try(() => {
int numAssets = scene.numAssets;
if (numAssets > 0) {
bool save = false;
for (int i = 0; i < numAssets; ++i) {
AssetData asset = scene.GetAsset(i);
//Only update non-MaterialAsset if specified
if (!updateNonMaterialAssets && asset.type != AssetType.Material)
continue;
switch (asset.type) {
case AssetType.File:
UpdateFileAsset((FileAssetData)asset);
break;
case AssetType.Audio:
UpdateAudioAsset((AudioData)asset);
break;
case AssetType.Texture:
UpdateTextureAsset((TextureData)asset);
break;
case AssetType.Material:
UpdateMaterialAssetV((MaterialData)asset);
break;
case AssetType.Animation:
UpdateAnimationAsset((AnimationClipData)asset, config);
save = true;
break;
default:
if (config.Logging)
Debug.Log("unknown asset: " + asset.name);
break;
}
if (logAnalytics) {
string syncMode = "None";
if (asset.type == AssetType.Material) {
syncMode = scene.GetMaterialSyncMode();
// TODO: Don't do this when GetMaterialSyncMode() works
if (textureList.Count > 0) syncMode = "Basic";
}
SendEventData(
new MeshSyncAnalyticsData() { syncData = new MeshSyncSyncAnalyticsData() { assetType = asset.type, syncMode = syncMode } });
}
}
#if UNITY_EDITOR
if (save)
AssetDatabase.SaveAssets();
#endif
}
});
// handle entities
Try(() => {
int numObjects = scene.numEntities;
for (int i = 0; i < numObjects; ++i) {
EntityRecord dst = null;
TransformData src = scene.GetEntity(i);
switch (src.entityType) {
case EntityType.Transform:
dst = UpdateTransformEntity(src, config);
break;
case EntityType.Camera:
dst = UpdateCameraEntity((CameraData)src, config);
break;
case EntityType.Light:
dst = UpdateLightEntity((LightData)src, config);
break;
case EntityType.Mesh:
dst = UpdateMeshEntity((MeshData)src, config);
break;
case EntityType.Points:
dst = UpdatePointsEntity((PointsData)src, config);
break;
case EntityType.Curve:
dst = UpdateCurveEntity((CurvesData)src, config);
break;
default:
Debug.LogError($"Unhandled entity type: {src.entityType}");
break;
}
SendEventData(new MeshSyncAnalyticsData() { syncData = new MeshSyncSyncAnalyticsData() { entityType = src.entityType } });
if (dst != null && onUpdateEntity != null)
onUpdateEntity.Invoke(dst.go, src);
}
});
// handle constraints
Try(() => {
int numConstraints = scene.numConstraints;
for (int i = 0; i < numConstraints; ++i)
UpdateConstraint(scene.GetConstraint(i));
});
// handle instance meshes
Try(() => {
int numMeshes = scene.numInstancedEntities;
for (int i = 0; i < numMeshes; ++i) {
TransformData src = scene.GetInstancedEntity(i);
// If an instance entity is not part of the scene, it can only be supported if it is a Mesh
//[TODO] Refactor code to support more types
if (src.entityType != EntityType.Mesh)
continue;
EntityRecord dst = UpdateInstancedEntity(src);
if (dst == null) return;
if (onUpdateInstancedEntity != null)
onUpdateInstancedEntity(src.path, dst.go);
}
});
// handle instances
Try(() => {
int numInstances = scene.numInstanceInfos;
for (int i = 0; i < numInstances; ++i) {
InstanceInfoData src = scene.GetInstanceInfo(i);
InstanceInfoRecord dst = UpdateInstanceInfo(src);
if (onUpdateInstanceInfo != null)
onUpdateInstanceInfo.Invoke(src.path, dst.go, src.transforms);
}
});
UpdateProperties(scene);
#if UNITY_EDITOR
if (config.ProgressiveDisplay)
ForceRepaint();
#endif
#if AT_USE_HDRP && UNITY_2021_2_OR_NEWER
if (m_needToResetPathTracing) {
HDRPUtility.ResetPathTracing();
m_needToResetPathTracing = false;
}
#endif
}
internal virtual void AfterUpdateScene() {
// If none of the set messages had properties, we need to remove all properties:
if (numberOfPropertiesReceived == 0) propertyInfos.Clear();
List<string> deadKeys = null;
// resolve bones
foreach (KeyValuePair<string, EntityRecord> kvp in m_clientObjects) {
EntityRecord rec = kvp.Value;
if (rec.go == null) {
if (deadKeys == null)
deadKeys = new List<string>();
deadKeys.Add(kvp.Key);
continue;
}
if (rec.smrUpdated) {
rec.smrUpdated = false;
SkinnedMeshRenderer smr = rec.skinnedMeshRenderer;
if (rec.bonePaths != null && rec.bonePaths.Length > 0) {
int boneCount = rec.bonePaths.Length;
Transform[] bones = new Transform[boneCount];
for (int bi = 0; bi < boneCount; ++bi)
bones[bi] = FilmInternalUtilities.GameObjectUtility.FindByPath(m_rootObject, rec.bonePaths[bi]);
Transform root = null;
if (!string.IsNullOrEmpty(rec.rootBonePath))
root = FilmInternalUtilities.GameObjectUtility.FindByPath(m_rootObject, rec.rootBonePath);
if (root == null && boneCount > 0) {
// find root bone
root = bones[0];
for (;;) {
Transform parent = root.parent;
if (parent == null || parent == m_rootObject)
break;
root = parent;
}
}
smr.rootBone = root;
smr.bones = bones;
smr.updateWhenOffscreen = true; // todo: this should be turned off at some point
rec.bonePaths = null;
rec.rootBonePath = null;
}
smr.enabled = rec.smrEnabled;
}
}
if (deadKeys != null)
foreach (string key in deadKeys)
m_clientObjects.Remove(key);
// resolve references
// this must be another pass because resolving bones can affect references
foreach (KeyValuePair<string, EntityRecord> kvp in m_clientObjects) {
EntityRecord rec = kvp.Value;
if (!string.IsNullOrEmpty(rec.reference)) {
EntityRecord srcrec = null;
if (m_clientObjects.TryGetValue(rec.reference, out srcrec) && srcrec.go != null) {
rec.materialIDs = srcrec.materialIDs;
UpdateReference(rec, srcrec, GetConfigV());
}
}
}
// reassign materials
if (m_needReassignMaterials) {
m_materialList = m_materialList.OrderBy(v => v.index).ToList();
ReassignMaterials(false);
m_needReassignMaterials = false;
}
#if UNITY_EDITOR
// sort objects by index
if (m_sortEntities) {
IOrderedEnumerable<EntityRecord> rec = m_clientObjects.Values.OrderBy(v => v.index);
foreach (EntityRecord r in rec)
if (r.go != null)
r.go.GetComponent<Transform>().SetSiblingIndex(r.index + 1000);
}
if (!EditorApplication.isPlaying || !EditorApplication.isPaused)
// force recalculate skinning
foreach (KeyValuePair<string, EntityRecord> kvp in m_clientObjects) {
EntityRecord rec = kvp.Value;
SkinnedMeshRenderer smr = rec.skinnedMeshRenderer;
if (smr != null && rec.smrEnabled && rec.go.activeInHierarchy) {
smr.enabled = false; //
smr.enabled = true; // force recalculate skinned mesh on editor. I couldn't find better way...
}
}
if (!EditorApplication.isPlaying)
// mark scene dirty
EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene());
#endif
MeshSyncLogger.VerboseLog($"Scene updated.");
if (onSceneUpdateEnd != null)
onSceneUpdateEnd.Invoke();
}
//----------------------------------------------------------------------------------------------------------------------
private void UpdateFileAsset(FileAssetData src) {
MakeSureAssetDirectoryExists();
#if UNITY_EDITOR
src.WriteToFile(m_assetsFolder + "/" + src.name);
#endif
}
private void UpdateAudioAsset(AudioData src) {
MakeSureAssetDirectoryExists();
AudioClip ac = null;
AudioFormat format = src.format;
if (format == AudioFormat.RawFile) {
#if UNITY_EDITOR
// create file and import it
string dstPath = m_assetsFolder + "/" + src.name;
src.WriteToFile(dstPath);
AssetDatabase.ImportAsset(dstPath);
ac = AssetDatabase.LoadAssetAtPath<AudioClip>(dstPath);
if (ac != null) {
AudioImporter importer = (AudioImporter)AssetImporter.GetAtPath(dstPath);
if (importer != null) {
// nothing todo for now
}
}
#endif
}
else {
#if UNITY_EDITOR
// export as .wav and import it
string dstPath = m_assetsFolder + "/" + src.name + ".wav";
if (src.ExportAsWave(dstPath)) {
AssetDatabase.ImportAsset(dstPath);
ac = AssetDatabase.LoadAssetAtPath<AudioClip>(dstPath);
if (ac != null) {
AudioImporter importer = (AudioImporter)AssetImporter.GetAtPath(dstPath);
if (importer != null) {
// nothing todo for now
}
}
}
#endif
if (ac == null) {
ac = AudioClip.Create(src.name, src.sampleLength, src.channels, src.frequency, false);
ac.SetData(src.samples, 0);
}
}
if (ac != null) {
int id = src.id;
AudioHolder dst = m_audioList.Find(a => a.id == id);
if (dst == null) {
dst = new AudioHolder();
dst.id = id;
m_audioList.Add(dst);
}
dst.audio = ac;
if (onUpdateAudio != null)
onUpdateAudio.Invoke(ac, src);
}
}
//----------------------------------------------------------------------------------------------------------------------
private void UpdateTextureAsset(TextureData src) {
MakeSureAssetDirectoryExists();
Texture2D texture = null;
#if UNITY_EDITOR
Action<string> doImport = (path) => {
bool assetExisted = AssetDatabase.LoadAssetAtPath<Texture2D>(path) != null;
AssetDatabase.ImportAsset(path);
texture = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
if (texture != null) {
TextureImporter importer = (TextureImporter)AssetImporter.GetAtPath(path);
bool needReimport = false;
// Make sure the full texture is used unless the user changed this setting before:
if (!assetExisted) {
importer.npotScale = TextureImporterNPOTScale.None;
needReimport = true;
}
if (importer != null)
switch (src.type) {
case TextureType.NormalMap:
importer.textureType = TextureImporterType.NormalMap;
needReimport = true;
break;
case TextureType.NonColor:
importer.sRGBTexture = false;
needReimport = true;
break;
}
if (needReimport) {
importer.SaveAndReimport();
AssetDatabase.Refresh();
}
}
};
#endif
TextureFormat format = src.format;
if (format == TextureFormat.RawFile) {
#if UNITY_EDITOR
// write data to file and import
string path = m_assetsFolder + "/" + src.name;
if (src.WriteToFile(path))
doImport(path);
#endif
}
else {
texture = new Texture2D(src.width, src.height, Misc.ToUnityTextureFormat(src.format), false);
texture.name = src.name;
texture.LoadRawTextureData(src.dataPtr, src.sizeInByte);
texture.Apply();
#if UNITY_EDITOR
// encode and write data to file and import
// (script-generated texture works but can't set texture type such as normal map)
bool exported = false;
string path = null;
switch (src.format) {
case TextureFormat.Ru8:
case TextureFormat.RGu8:
case TextureFormat.RGBu8:
case TextureFormat.RGBAu8: {
path = m_assetsFolder + "/" + src.name + ".png";
exported = TextureData.WriteToFile(path, EncodeToPNG(texture));
break;
}
case TextureFormat.Rf16:
case TextureFormat.RGf16:
case TextureFormat.RGBf16:
case TextureFormat.RGBAf16: {
path = m_assetsFolder + "/" + src.name + ".exr";
exported = TextureData.WriteToFile(path, EncodeToEXR(texture, Texture2D.EXRFlags.CompressZIP));
break;
}
case TextureFormat.Rf32:
case TextureFormat.RGf32:
case TextureFormat.RGBf32:
case TextureFormat.RGBAf32: {
path = m_assetsFolder + "/" + src.name + ".exr";
exported = TextureData.WriteToFile(path, EncodeToEXR(texture, Texture2D.EXRFlags.OutputAsFloat | Texture2D.EXRFlags.CompressZIP));
break;
}
}
if (exported) {
texture = null;
doImport(path);
}
#endif
}
if (texture != null) {
int id = src.id;
TextureHolder dst = m_textureList.Find(a => a.id == id);
if (dst == null) {
dst = new TextureHolder();
dst.id = id;
m_textureList.Add(dst);
}
dst.texture = texture;
if (onUpdateTexture != null)
onUpdateTexture.Invoke(texture, src);
}
}