-
Notifications
You must be signed in to change notification settings - Fork 174
/
AlembicMaterial.cs
481 lines (386 loc) · 16 KB
/
AlembicMaterial.cs
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
using System;
using System.Xml;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UTJ.Alembic
{
[ExecuteInEditMode]
public class AlembicMaterial : MonoBehaviour
{
public class Assignment
{
public Material material;
public List<int> faces;
}
[Serializable]
public class Facesets
{
public int[] faceCounts;
public int[] faceIndices;
}
bool dirty = false;
List<Material> materials = new List<Material>();
// Need to keep thess around when scene is serialized
[HideInInspector]
public Facesets facesetsCache = new Facesets { faceCounts = new int[0], faceIndices = new int[0] };
void Start()
{
}
void Update()
{
var player = gameObject.transform.root.GetComponent<AlembicStreamPlayer>();
var stream = player.Stream;
if (materials.Count > 0)
{
var alembicTreeNode = stream.AlembicTreeRoot.FindNodeRecursive(gameObject);
var abcmesh = alembicTreeNode.GetAlembicObj<AlembicMesh>();
if (abcmesh != null)
{
int splitIndex = 0;
int submeshIndex = 0;
if (abcmesh.m_submeshes.Count < materials.Count)
{
// should have at least materials.Count submeshes
Debug.Log("\"" + alembicTreeNode.linkedGameObj.name + "\": Not enough submeshes for all assigned materials. (" + materials.Count + " material(s) for " + abcmesh.m_submeshes.Count + " submesh(es))");
return;
}
var renderer = gameObject.GetComponent<MeshRenderer>();
foreach (AlembicMesh.Submesh submesh in abcmesh.m_submeshes)
{
if (submesh.splitIndex != splitIndex)
{
submeshIndex = 0;
}
MeshRenderer splitRenderer = null;
Transform split = gameObject.transform.Find(gameObject.name + "_split_" + submesh.splitIndex);
if (split == null)
{
if (submesh.splitIndex > 0)
{
Debug.Log("Invalid split index");
return;
}
splitRenderer = renderer;
}
else
{
if (submesh.splitIndex == 0 && !split.gameObject.activeSelf)
{
// First split sub object not active means the mesh is hold be the current object
splitRenderer = renderer;
}
else
{
splitRenderer = split.gameObject.GetComponent<MeshRenderer>();
}
}
if (splitRenderer == null)
{
Debug.Log("No renderer on \"" + gameObject.name + "\" to assign materials to");
return;
}
Material[] assignedMaterials = splitRenderer.sharedMaterials;
if (submesh.facesetIndex != -1)
{
if (submesh.facesetIndex < 0 || submesh.facesetIndex >= materials.Count)
{
// invalid facesetIndex, do no update material assignments at all
Debug.Log("Invalid faceset index");
return;
}
if (submeshIndex >= assignedMaterials.Length)
{
Debug.Log("No material for submesh");
return;
}
if (assignedMaterials[submeshIndex] != materials[submesh.facesetIndex])
{
assignedMaterials[submeshIndex] = materials[submesh.facesetIndex];
splitRenderer.sharedMaterials = assignedMaterials;
// propagate first split single material assignment to parent renderer if it exists
if (submesh.splitIndex == 0 && splitRenderer != renderer && renderer != null && assignedMaterials.Length == 1)
{
renderer.sharedMaterials = assignedMaterials;
}
}
}
else
{
// should I reset to default material or leave it as it is
}
splitIndex = submesh.splitIndex;
++submeshIndex;
}
}
materials.Clear();
}
}
public int GetFacesetsCount()
{
return facesetsCache.faceCounts.Length;
}
public void GetFacesets(ref AbcAPI.aiFacesets facesets)
{
facesets.count = facesetsCache.faceCounts.Length;
facesets.faceCounts = Marshal.UnsafeAddrOfPinnedArrayElement(facesetsCache.faceCounts, 0);
facesets.faceIndices = Marshal.UnsafeAddrOfPinnedArrayElement(facesetsCache.faceIndices, 0);
}
public bool HasFacesetsChanged()
{
return dirty;
}
public void AknowledgeFacesetsChanges()
{
dirty = false;
}
public void UpdateAssignments(List<Assignment> assignments)
{
int count = 0;
int indicesCount = 0;
// keep list of materials for next update
materials.Clear();
if (facesetsCache.faceCounts.Length < assignments.Count)
{
Array.Resize(ref facesetsCache.faceCounts, assignments.Count);
dirty = true;
}
for (int i = 0; i < assignments.Count; ++i)
{
materials.Add(assignments[i].material);
int face_count = assignments[i].faces.Count;
dirty = dirty || (facesetsCache.faceCounts[count] != face_count);
facesetsCache.faceCounts[count++] = face_count;
if (facesetsCache.faceIndices.Length < (indicesCount + face_count))
{
Array.Resize(ref facesetsCache.faceIndices, indicesCount + face_count);
dirty = true;
}
for (int j = 0; j < face_count; ++j, ++indicesCount)
{
int face_index = assignments[i].faces[j];
dirty = dirty || (facesetsCache.faceIndices[indicesCount] != face_index);
facesetsCache.faceIndices[indicesCount] = face_index;
}
}
}
#if UNITY_EDITOR
static char[] PathSep = new char[1] { '/' };
static char[] FaceSep = new char[1] { ',' };
static char[] RangeSep = new char[1] { '-' };
static GameObject SearchNodeInstance(Transform parent, string name, int instNum, ref int curInst)
{
Transform node = parent.Find(name);
if (node != null)
{
if (curInst == instNum)
{
return node.gameObject;
}
else
{
++curInst;
}
}
for (int i = 0; i < parent.childCount; ++i)
{
GameObject rv = SearchNodeInstance(parent.GetChild(i), name, instNum, ref curInst);
if (rv != null)
{
return rv;
}
}
return null;
}
static GameObject FindNode(GameObject root, string path, int instNum)
{
if (root == null)
{
return null;
}
string[] paths = path.Split(PathSep, StringSplitOptions.RemoveEmptyEntries);
if (paths.Length == 0)
{
return null;
}
bool isFullPath = path.StartsWith("/");
if (isFullPath)
{
int curPath = 0;
Transform curNode = root.transform;
while (curNode != null && curPath < paths.Length)
{
Transform child = curNode.Find(paths[curPath]);
if (child == null)
{
Debug.Log("Object \"" + curNode.name + "\" has no child named \"" + paths[curPath] + "\"");
curNode = null;
break;
}
else
{
curNode = child;
++curPath;
}
}
if (curNode == null)
{
Debug.Log("Failed to find object \"" + path + "\"");
return null;
}
else
{
return curNode.gameObject;
}
}
else
{
string name = path;
int curInst = 0;
int idx = name.LastIndexOf("/");
if (idx >= 0 && idx < path.Length)
{
name = name.Substring(idx + 1);
}
if (instNum < 0)
{
instNum = 0;
}
return SearchNodeInstance(root.transform, name, instNum, ref curInst);
}
}
static Material GetMaterial(string name, string matfolder)
{
// FindAssets will return all shaders that contains name in a case insensitive way
string[] guids = AssetDatabase.FindAssets(name + " t:material", new string[1] { matfolder });
foreach (string guid in guids)
{
string path = AssetDatabase.GUIDToAssetPath(guid);
Material mat = AssetDatabase.LoadAssetAtPath(path, typeof(Material)) as Material;
if (mat.name == name)
{
return mat;
}
}
return null;
}
public static void Import(string xmlPath, GameObject root, string materialFolder)
{
XmlDocument doc = new XmlDocument();
doc.Load(xmlPath);
XmlNode xmlRoot = doc.DocumentElement;
XmlNodeList nodes = xmlRoot.SelectNodes("/assignments/node");
Dictionary<GameObject, List<Assignment>> allAssignments = new Dictionary<GameObject, List<Assignment>>();
foreach (XmlNode node in nodes)
{
string path = node.Attributes["path"].Value;
XmlNodeList shaders = node.SelectNodes("shader");
foreach (XmlNode shader in shaders)
{
XmlAttribute name = shader.Attributes["name"];
XmlAttribute inst = shader.Attributes["instance"];
if (name == null)
{
continue;
}
int instNum = (inst == null ? 0 : Convert.ToInt32(inst.Value));
GameObject target = FindNode(root, path, instNum);
if (target == null)
{
// Debug.Log("Could not find node: " + path);
continue;
}
List<Assignment> assignments;
if (!allAssignments.ContainsKey(target))
{
assignments = new List<Assignment>();
allAssignments.Add(target, assignments);
}
else
{
assignments = allAssignments[target];
}
Material material = GetMaterial(name.Value, materialFolder);
if (material == null)
{
material = new Material(Shader.Find("Standard"));
material.color = new Color(UnityEngine.Random.value,
UnityEngine.Random.value,
UnityEngine.Random.value);
AssetDatabase.CreateAsset(material, materialFolder + "/" + name.Value + ".mat");
}
// Get or create material assignment
bool newlyAssigned = false;
var a = new Assignment
{
material = material,
faces = new List<int>()
};
assignments.Add(a);
newlyAssigned = true;
string faceset = shader.InnerText;
faceset.Trim();
if (faceset.Length > 0 && (newlyAssigned || a.faces.Count > 0))
{
string[] items = faceset.Split(FaceSep, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < items.Length; ++i)
{
string[] rng = items[i].Split(RangeSep, StringSplitOptions.RemoveEmptyEntries);
if (rng.Length == 1)
{
a.faces.Add(Convert.ToInt32(rng[0]));
}
else if (rng.Length == 2)
{
int j0 = Convert.ToInt32(rng[0]);
int j1 = Convert.ToInt32(rng[1]);
for (int j = j0; j <= j1; ++j)
{
a.faces.Add(j);
}
}
}
if (!newlyAssigned)
{
a.faces = new List<int>(new HashSet<int>(a.faces));
}
}
else if (faceset.Length == 0 && a.faces.Count > 0)
{
// Shader assgined to whole object, remove any face level assignments
a.faces.Clear();
}
}
}
// Update AlembicMaterial components
foreach (KeyValuePair<GameObject, List<Assignment>> pair in allAssignments)
{
AlembicMaterial abcmaterial = pair.Key.GetComponent<AlembicMaterial>();
if (abcmaterial == null)
{
abcmaterial = pair.Key.AddComponent<AlembicMaterial>();
}
abcmaterial.UpdateAssignments(pair.Value);
}
// Force refresh
var player = root.GetComponent<AlembicStreamPlayer>();
if (player != null && player.Stream != null )
{
player.SendMessage("ForceRefresh", null, SendMessageOptions.DontRequireReceiver);
}
else
{
// todo: do figure something else...
}
}
public static void Export(string xmlPath, GameObject root)
{
// Not Yet Implemented
Debug.Log("Material assignment export not yet implemented");
}
#endif
}
}