-
Notifications
You must be signed in to change notification settings - Fork 5
/
PopGeometry.cs
1474 lines (1272 loc) · 42.8 KB
/
PopGeometry.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
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.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
[System.Serializable]
public class UnityEvent_ListOfLine3 : UnityEngine.Events.UnityEvent<List<PopX.Line3>> { }
// rename namespace to Pop in later refactor
namespace PopX
{
public class MeshContents
{
public List<Vector3> NewPositons;
public List<Vector3> NewNormals;
public List<Vector2> NewUv1s;
public List<Vector2> NewUv2s;
public List<Vector2> NewUv3s;
public List<Color> NewColourfs;
public List<Color32> NewColour32s;
public List<int> TriangleIndexes;
public Bounds? OldBounds = null;
public int TriangleCount { get { return (TriangleIndexes == null) ? 0 : TriangleIndexes.Count / 3; } }
void Append<T>(List<T> SourceArray, int[] SourceIndexes, ref List<T> DestArray)
{
if (SourceArray == null)
return;
if (DestArray == null)
DestArray = new List<T>();
DestArray.Add(SourceArray[SourceIndexes[0]]);
DestArray.Add(SourceArray[SourceIndexes[1]]);
DestArray.Add(SourceArray[SourceIndexes[2]]);
}
public void AddTriangle(Vector3 a, Vector3 b, Vector3 c)
{
Pop.AllocIfNull(ref NewPositons);
NewPositons.Add(a);
NewPositons.Add(b);
NewPositons.Add(c);
}
public void AddTriangle(Vector3 Pos0, Vector3 Pos1, Vector3 Pos2, Vector3 Normal0, Vector3 Normal1, Vector3 Normal2)
{
Pop.AllocIfNull(ref NewPositons);
NewPositons.Add(Pos0);
NewPositons.Add(Pos1);
NewPositons.Add(Pos2);
Pop.AllocIfNull(ref NewNormals);
NewNormals.Add(Normal0);
NewNormals.Add(Normal1);
NewNormals.Add(Normal2);
}
public void AddTriangle(MeshContents SourceMesh, int[] Triangle)
{
Append(SourceMesh.NewPositons, Triangle, ref this.NewPositons);
Append(SourceMesh.NewNormals, Triangle, ref this.NewNormals);
Append(SourceMesh.NewUv1s, Triangle, ref this.NewUv1s);
Append(SourceMesh.NewUv2s, Triangle, ref this.NewUv2s);
Append(SourceMesh.NewUv3s, Triangle, ref this.NewUv3s);
Append(SourceMesh.NewColourfs, Triangle, ref this.NewColourfs);
Append(SourceMesh.NewColour32s, Triangle, ref this.NewColour32s);
}
public void AutoFillTriangleIndexes()
{
if (this.TriangleIndexes != null)
throw new System.Exception("Expected null triangle indexes");
this.TriangleIndexes = new List<int>();
Pop.AllocIfNull(ref this.NewPositons);
for (var i = 0; i < this.NewPositons.Count; i++)
this.TriangleIndexes.Add(i);
}
void Remove<T>(List<T> AttributeArray, int[] Indexes)
{
try
{
AttributeArray.RemoveAt(Indexes[0]);
AttributeArray.RemoveAt(Indexes[1]);
AttributeArray.RemoveAt(Indexes[2]);
}
catch
{ }
}
public void RemoveTriangles(List<int> RemoveTriangles)
{
RemoveTriangles.Sort();
for (int i = RemoveTriangles.Count - 1; i >= 0; i--)
{
var ta = (RemoveTriangles[i] * 3) + 0;
var tb = (RemoveTriangles[i] * 3) + 1;
var tc = (RemoveTriangles[i] * 3) + 2;
TriangleIndexes.RemoveAt(tc);
TriangleIndexes.RemoveAt(tb);
TriangleIndexes.RemoveAt(ta);
}
/*
Remove(NewPositons, Triangle);
Remove(NewNormals, Triangle);
Remove(NewUv1s, Triangle);
Remove(NewUv2s, Triangle);
Remove(NewUv3s, Triangle);
Remove(NewColourfs, Triangle);
Remove(NewColour32s, Triangle);
*/
}
public Mesh CreateMesh(string MeshName)
{
var m = new Mesh();
AutoFillTriangleIndexes();
m.SetVertices(this.NewPositons);
// fill optional mesh attribs
if (this.NewNormals != null) m.SetNormals(NewNormals);
if (this.NewUv1s != null) m.SetUVs(0, NewUv1s);
if (this.NewUv2s != null) m.SetUVs(1, NewUv2s);
if (this.NewUv3s != null) m.SetUVs(2, NewUv3s);
if (this.NewColourfs != null) m.SetColors(NewColourfs);
if (this.NewColour32s != null) m.SetColors(NewColour32s);
m.SetIndices(this.TriangleIndexes.ToArray(), MeshTopology.Triangles, 0);
if (OldBounds.HasValue)
m.bounds = this.OldBounds.Value;
else
m.RecalculateBounds();
return m;
}
bool IsMatchingVertex<T>(List<T> AttributeArray, int IndexA, int IndexB, float MaxDistance, System.Func<T, T, float> GetDistance)
{
if (AttributeArray == null)
return true;
var AttribA = AttributeArray[IndexA];
var AttribB = AttributeArray[IndexB];
var Distance = GetDistance(AttribA, AttribB);
if (Distance >= MaxDistance)
return false;
return true;
}
/*
*
static void WeldMeshVertexes(List<Vector3> Positions,List<int> TriangleIndexes)
{
System.Func<int,int,bool> IsMatchingVertex = (First, Second) => {
//var Distance = PopMath.Vector3_DistanceSquared (Positions [First], Positions [Second]);
var Distance = Vector3.Distance(Positions [First], Positions [Second]);
if (Distance < Mathf.Epsilon)
return true;
return false;
};
// make a new list of "unique" verts
var UniqueVerts = new List<Vector3>();
// make a table of the "lower matching index"
var NewVertexIndex = new int[Positions.Count];
for (int i = 0; i < NewVertexIndex.Length; i++)
NewVertexIndex [i] = -1;
for (int i = 0; i < Positions.Count; i++) {
for (int low = 0; low < i; low++) {
// find a match
if ( IsMatchingVertex( i, low ) )
{
NewVertexIndex [i] = NewVertexIndex[low];
break;
}
}
// im a unique vertex!
if (NewVertexIndex [i] == -1) {
NewVertexIndex [i] = UniqueVerts.Count;
UniqueVerts.Add (Positions [i]);
}
}
// re-index triangles
for (int ti = 0; ti < TriangleIndexes.Count; ti++) {
if (NewVertexIndex [ti] == -1)
throw new System.Exception ("Unexpected un-matched vertex index");
TriangleIndexes [ti] = NewVertexIndex [ti];
}
Positions.Clear ();
Positions.AddRange (UniqueVerts);
}
*/
public void WeldVertexes()
{
/*
System.Func<int, int, bool> CompareVertex = (IndexA, IndexB) =>
{
if (!IsMatchingVertex(this.NewPositons, IndexA, IndexB, Mathf.Epsilon, Vector3.Distance))
return false;
if (!IsMatchingVertex(this.NewUv1s, IndexA, IndexB, Mathf.Epsilon, Vector2.Distance))
return false;
if (!IsMatchingVertex(this.NewUv2s, IndexA, IndexB, Mathf.Epsilon, Vector2.Distance))
return false;
if (!IsMatchingVertex(this.NewUv3s, IndexA, IndexB, Mathf.Epsilon, Vector2.Distance))
return false;
return true;
};
*/
throw new System.Exception("todo: WeldVertexes");
}
public void AddMesh(Mesh Mesh,Matrix4x4 Transform)
{
// add each triangle
var Triangles = Mesh.GetTriangles(0);
var Positions = Mesh.vertices;
var Normals = Mesh.normals;
for (var t = 0; t < Triangles.Length; t+=3)
{
var pa = Positions[Triangles[t + 0]];
var pb = Positions[Triangles[t + 1]];
var pc = Positions[Triangles[t + 2]];
pa = Transform.MultiplyPoint(pa);
pb = Transform.MultiplyPoint(pb);
pc = Transform.MultiplyPoint(pc);
var na = Normals[Triangles[t + 0]];
var nb = Normals[Triangles[t + 1]];
var nc = Normals[Triangles[t + 2]];
/*
na = Transform.MultiplyVector(na);
nb = Transform.MultiplyVector(nb);
nc = Transform.MultiplyVector(nc);
*/
AddTriangle(pa, pb, pc, na, nb, nc);
}
}
};
// gr: should this be in Pop.Geometry.Line3 ?
[System.Serializable]
public struct Line3
{
public Vector3 Start;
public Vector3 End;
public Line3(Vector3 _Start, Vector3 _End)
{
Start = _Start;
End = _End;
}
};
// gr: should this be in Pop.Geometry.Sphere3 ?
[System.Serializable]
public struct Sphere3
{
public Vector3 center;
public float radius;
public Vector3 radius3 { get { return new Vector3(radius, radius, radius); } }
public Sphere3(Vector3 _Center, float _Radius)
{
center = _Center;
radius = _Radius;
}
// negative - inside sphere, positive, distance from sphere.
public float Distance(Ray ray)
{
Vector3 Temp;
return Distance(ray, out Temp);
}
// negative - inside sphere, positive, distance from sphere.
public float Distance(Ray ray, out Vector3 NearestPoint)
{
NearestPoint = PopMath.NearestToRay3(this.center, ray);
var dist = Vector3.Distance(NearestPoint, this.center);
dist -= this.radius;
return dist;
}
public bool IsPointInside(Vector3 Position)
{
return Distance(Position) <= 0;
}
public float Distance(Vector3 Position)
{
var Dist = Vector3.Distance(Position, this.center);
Dist -= this.radius;
return Dist;
}
public void Transform(Matrix4x4 Transform)
{
var EdgePos = center + new Vector3(0, 0, radius);
// transform
center = Transform.MultiplyPoint(center);
// find new edge
var WorldEdgePos = Transform.MultiplyPoint(EdgePos);
radius = Vector3.Distance(WorldEdgePos, center);
}
};
public static class Geometry
{
// gr: this value is NOT uInt16.MaxValue/65535 as we'd expect. I can't remember why, but it's something deep inside unity. maybe it uses some magic numbers for other things
// so just impose a vaguely similar limit
const int Max16BitTriangleIndexes = 65000;
#if UNITY_EDITOR
[MenuItem("CONTEXT/MeshFilter/Unshare triangle indexes of mesh")]
public static void UnshareTrianglesOfMesh(MenuCommand menuCommand)
{
var mf = menuCommand.context as MeshFilter;
var mesh = mf.sharedMesh;
Undo.RecordObject(mesh, "Unshare Triangles Of Mesh " + mesh.name);
UnshareTrianglesOfMesh(ref mesh);
Undo.FlushUndoRecordObjects();
}
#endif
#if UNITY_EDITOR
[MenuItem("CONTEXT/MeshFilter/Unshare triangle indexes to new mesh...")]
public static void UnshareTrianglesToMesh(MenuCommand menuCommand)
{
var mf = menuCommand.context as MeshFilter;
var m = CopyMesh(mf.sharedMesh);
m.name = mf.sharedMesh.name + " unshared";
UnshareTrianglesOfMesh(ref m);
SaveMesh(m, m.name, true);
}
#endif
#if UNITY_EDITOR
[MenuItem("CONTEXT/MeshFilter/Weld vertexes of mesh")]
public static void _WeldVertexesOfMesh(MenuCommand menuCommand)
{
var mf = menuCommand.context as MeshFilter;
var mesh = mf.sharedMesh;
Undo.RecordObject(mesh, "Unshare Triangles Of Mesh " + mesh.name);
WeldVertexesOfMesh(ref mesh);
Undo.FlushUndoRecordObjects();
}
#endif
#if UNITY_EDITOR
[MenuItem("CONTEXT/MeshFilter/Weld vertexes to new mesh...")]
public static void _WeldVertexesOfNewMesh(MenuCommand menuCommand)
{
var mf = menuCommand.context as MeshFilter;
var m = CopyMesh(mf.sharedMesh);
m.name = mf.sharedMesh.name + " welded";
WeldVertexesOfMesh(ref m);
SaveMesh(m, m.name, true);
}
#endif
#if UNITY_EDITOR
[MenuItem("CONTEXT/MeshFilter/Randomise triangle order")]
public static void _RandomiseTriangleOrder(MenuCommand menuCommand)
{
var mf = menuCommand.context as MeshFilter;
var mesh = mf.sharedMesh;
Undo.RecordObject(mesh, "Randomised triangle order of " + mesh.name);
RandomiseTriangleOrder(mesh);
Undo.FlushUndoRecordObjects();
}
#endif
#if UNITY_EDITOR
[MenuItem("CONTEXT/MeshFilter/Set mesh UV[3] to vertex index")]
public static void _SetMeshUV5ToVertexIndex(MenuCommand menuCommand)
{
var mf = menuCommand.context as MeshFilter;
var mesh = mf.sharedMesh;
Undo.RecordObject(mesh, "Set mesh UV3 to vertex index of " + mesh.name);
SetMeshUVToVertexIndex(mesh, 3);
Undo.FlushUndoRecordObjects();
}
#endif
#if UNITY_EDITOR
[MenuItem("CONTEXT/MeshFilter/Set mesh UV[0] to triangle index")]
public static void _SetMeshUV0ToTriangleIndex(MenuCommand menuCommand)
{
var mf = menuCommand.context as MeshFilter;
var mesh = mf.sharedMesh;
Undo.RecordObject(mesh, "Set mesh UV0 to triangle index of " + mesh.name);
SetMeshUVToTriangleIndex(mesh, 0);
Undo.FlushUndoRecordObjects();
}
#endif
#if UNITY_EDITOR
[MenuItem("CONTEXT/MeshFilter/Set mesh UV1 to triangle barycentric coords")]
public static void SetMeshUV1ToTriangleBarycentricCoords(MenuCommand menuCommand)
{
var mf = menuCommand.context as MeshFilter;
var m = mf.sharedMesh;
var TriangleIndexes = m.triangles;
if (TriangleIndexes.Length != m.vertexCount)
{
var DialogResult = EditorUtility.DisplayDialog("Error", "Assigning triangle indexes to attributes probably won't work as expected for meshes sharing vertexes.", "Continue", "Cancel");
if (!DialogResult)
throw new System.Exception("Aborted assignment of UV triangle indexes");
}
using (var Progress = new ScopedProgressBar("Setting UVs"))
{
var Uvs = new Vector3[m.vertexCount];
{
var barya = new Vector3(1, 0, 0);
var baryb = new Vector3(0, 1, 0);
var baryc = new Vector3(0, 0, 1);
for (int t = 0; t < TriangleIndexes.Length; t += 3)
{
Progress.SetProgress("Setting UV of triangle", t / 3, TriangleIndexes.Length / 3, 100);
Uvs[TriangleIndexes[t + 0]] = barya;
Uvs[TriangleIndexes[t + 1]] = baryb;
Uvs[TriangleIndexes[t + 2]] = baryc;
}
}
m.SetUVs(1, new List<Vector3>(Uvs));
m.UploadMeshData(true);
AssetDatabase.SaveAssets();
}
}
#endif
#if UNITY_EDITOR
[MenuItem("CONTEXT/MeshFilter/Set mesh UV2 to random per-triangle")]
public static void SetMeshUV2ToRandomPerTriangle(MenuCommand menuCommand)
{
var mf = menuCommand.context as MeshFilter;
var m = mf.sharedMesh;
var TriangleIndexes = m.triangles;
if (TriangleIndexes.Length != m.vertexCount)
{
var DialogResult = EditorUtility.DisplayDialog("Error", "Assigning triangle indexes to attributes probably won't work as expected for meshes sharing vertexes.", "Continue", "Cancel");
if (!DialogResult)
throw new System.Exception("Aborted assignment of UV triangle indexes");
}
using (var Progress = new ScopedProgressBar("Setting UVs"))
{
var Uvs = new Vector3[m.vertexCount];
{
var random3 = new Vector3(0, 0, 0);
for (int t = 0; t < TriangleIndexes.Length; t += 3)
{
Progress.SetProgress("Setting UV of triangle", t / 3, TriangleIndexes.Length / 3, 100);
float tTime = t / (float)TriangleIndexes.Length;
random3.x = Mathf.PerlinNoise(tTime, 0.0f);
random3.y = Mathf.PerlinNoise(0.0f, tTime);
random3.z = Random.Range(0.0f, 1.0f);
Uvs[TriangleIndexes[t + 0]] = random3;
Uvs[TriangleIndexes[t + 1]] = random3;
Uvs[TriangleIndexes[t + 2]] = random3;
}
}
m.SetUVs(2, new List<Vector3>(Uvs));
m.UploadMeshData(true);
AssetDatabase.SaveAssets();
}
}
#endif
#if UNITY_EDITOR
[MenuItem("CONTEXT/MeshFilter/Set mesh bounds to Box Collider")]
public static void SetMeshBoundsToBoxCollider(MenuCommand menuCommand)
{
var mf = menuCommand.context as MeshFilter;
var m = mf.sharedMesh;
var bc = mf.GetComponent<BoxCollider>();
m.bounds = bc.bounds;
// save the asset, if this is not asset-backed, it will prompt to create a new asset and return that
m = AssetWriter.SaveAsset(m);
mf.sharedMesh = m;
}
#endif
#if UNITY_EDITOR
[MenuItem("CONTEXT/MeshFilter/Set Box Collider to Mesh Bounds", true)]
public static bool SetBoxColliderToMeshBounds_Verify(MenuCommand menuCommand)
{
var mf = menuCommand.context as MeshFilter;
var bc = mf.GetComponent<BoxCollider>();
return bc != null;
}
[MenuItem("CONTEXT/MeshFilter/Set Box Collider to Mesh Bounds")]
public static void SetBoxColliderToMeshBounds(MenuCommand menuCommand)
{
var mf = menuCommand.context as MeshFilter;
var m = mf.sharedMesh;
var bc = mf.GetComponent<BoxCollider>();
bc.size = m.bounds.size;
bc.center = m.bounds.center;
}
#endif
#if UNITY_EDITOR
[MenuItem("CONTEXT/BoxCollider/Set Box Collider to Mesh Bounds", true)]
public static bool SetBoxColliderToMeshBounds2_Verify(MenuCommand menuCommand)
{
var bc = menuCommand.context as BoxCollider;
var mf = bc.GetComponent<MeshFilter>();
return mf != null;
}
[MenuItem("CONTEXT/BoxCollider/Set Box Collider to Mesh Bounds")]
public static void SetBoxColliderToMeshBounds2(MenuCommand menuCommand)
{
var bc = menuCommand.context as BoxCollider;
var mf = bc.GetComponent<MeshFilter>();
var m = mf.sharedMesh;
bc.size = m.bounds.size;
bc.center = m.bounds.center;
}
#endif
#if UNITY_EDITOR
[MenuItem("Assets/Mesh/Save as new asset...", true)]
public static bool MeshSaveAsNewAsset_Verify()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
return Meshes.Length > 0;
}
[MenuItem("Assets/Mesh/Save as new asset...")]
public static void MeshSaveAsNewAsset()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
foreach (var Mesh in Meshes)
{
AssetWriter.SaveAsNewAsset(Mesh);
}
}
[MenuItem("CONTEXT/MeshFilter/Save as new asset...")]
public static void MeshSaveAsNewAsset(MenuCommand menuCommand)
{
var mf = menuCommand.context as MeshFilter;
var m = mf.sharedMesh;
AssetWriter.SaveAsNewAsset(m);
}
#endif
#if UNITY_EDITOR
[MenuItem("Assets/Mesh/Center mesh on bounds", true)]
public static bool MeshCenterPivotViaBounds_Verify()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
return Meshes.Length > 0;
}
[MenuItem("Assets/Mesh/Center pivot via bounds")]
public static void MeshCenterPivotViaBounds()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
foreach (var Mesh in Meshes)
{
Mesh.CenterOnBounds();
AssetWriter.SaveAsset(Mesh);
}
}
[MenuItem("CONTEXT/MeshFilter/Center mesh pivot via bounds")]
public static void MeshCenterPivotViaBounds(MenuCommand menuCommand)
{
var mf = menuCommand.context as MeshFilter;
var m = mf.sharedMesh;
m.CenterOnBounds();
AssetWriter.SaveAsset(m);
}
#endif
#if UNITY_EDITOR
[MenuItem("Assets/Mesh/Recalculate bounds", true)]
public static bool MeshRecalculateBounds_Verify()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
return Meshes.Length > 0;
}
[MenuItem("Assets/Mesh/Recalculate bounds")]
public static void MeshRecalculateBounds()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
foreach (var Mesh in Meshes)
{
Mesh.RecalculateBounds();
AssetWriter.SaveAsset(Mesh);
}
}
[MenuItem("CONTEXT/MeshFilter/Recalculate mesh bounds")]
public static void MeshRecalculateBounds(MenuCommand menuCommand)
{
var mf = menuCommand.context as MeshFilter;
var m = mf.sharedMesh;
m.RecalculateBounds();
AssetWriter.SaveAsset(m);
}
#endif
#if UNITY_EDITOR
const string MergeSubmeshMenuLabel = "Merge Submeshes, uv[1].x=index";
[MenuItem("Assets/Mesh/" + MergeSubmeshMenuLabel, true)]
public static bool MergeSubmeshMenu_Verify()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
return Meshes.Length > 0;
}
[MenuItem("Assets/Mesh/" + MergeSubmeshMenuLabel)]
public static void MergeSubmeshMenu()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
foreach (var mesh in Meshes)
{
// gr: undo is nice, but SOOO slow on meshes
//Undo.RecordObject(mesh, MergeSubmeshMenuLabel + " of " + mesh.name);
MergeSubmeshes(mesh, 1);
//Undo.FlushUndoRecordObjects();
AssetWriter.SaveAsset(mesh);
}
}
[MenuItem("CONTEXT/MeshFilter/" + MergeSubmeshMenuLabel)]
public static void MergeSubmeshMenu(MenuCommand menuCommand)
{
var mf = menuCommand.context as MeshFilter;
var mesh = mf.sharedMesh;
// gr: undo is nice, but SOOO slow on meshes
//Undo.RecordObject(mesh, MergeSubmeshMenuLabel + " of " + mesh.name);
MergeSubmeshes(mesh, 1);
//Undo.FlushUndoRecordObjects();
AssetWriter.SaveAsset(mesh);
}
[MenuItem("Assets/Mesh/Merge Submeshes 0,1,2,3,4,5,12", true)]
public static bool MergeSubmesh_0_1_2_3_4_5_12_Menu_Verify()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
return Meshes.Length > 0;
}
[MenuItem("Assets/Mesh/Merge Submeshes 0,1,2,3,4,5,12")]
public static void MergeSubmesh_0_1_2_3_4_5_12_Menu()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
foreach (var mesh in Meshes)
{
var NewMesh = ExtractSubmeshesAsMesh(mesh, new int[] { 0, 1, 2, 3, 4, 5, 12 });
AssetWriter.SaveAsset(NewMesh);
}
}
[MenuItem("Assets/Mesh/Merge Submeshes 6,7,8,9,10,11", true)]
public static bool MergeSubmesh_6_7_8_9_10_11_Menu_Verify()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
return Meshes.Length > 0;
}
[MenuItem("Assets/Mesh/Merge Submeshes 6,7,8,9,10,11")]
public static void MergeSubmesh_6_7_8_9_10_11_Menu()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
foreach (var mesh in Meshes)
{
var NewMesh = ExtractSubmeshesAsMesh(mesh, new int[] { 6, 7, 8, 9, 10, 11 });
AssetWriter.SaveAsset(NewMesh);
}
}
[MenuItem("Assets/Mesh/Merge Submeshes 2,12,10,5,7,11,4", true)]
public static bool MergeSubmesh_2_12_10_5_7_11_4_Menu_Verify()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
return Meshes.Length > 0;
}
[MenuItem("Assets/Mesh/Merge Submeshes 2,12,10,5,7,11,4")]
public static void MergeSubmesh_2_12_10_5_7_11_4_Menu()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
foreach (var mesh in Meshes)
{
var NewMesh = ExtractSubmeshesAsMesh(mesh, new int[] { 2, 12, 10, 5, 7, 11, 4 });
AssetWriter.SaveAsset(NewMesh);
}
}
[MenuItem("Assets/Mesh/Merge Submeshes 8,6,9,3,0,1", true)]
public static bool MergeSubmesh_8_6_9_3_0_1_Menu_Verify()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
return Meshes.Length > 0;
}
[MenuItem("Assets/Mesh/Merge Submeshes 8,6,9,3,0,1")]
public static void MergeSubmesh_8_6_9_3_0_1_Menu()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
foreach (var mesh in Meshes)
{
var NewMesh = ExtractSubmeshesAsMesh(mesh, new int[] { 8, 6, 9, 3, 0, 1 });
AssetWriter.SaveAsset(NewMesh);
}
}
[MenuItem("Assets/Mesh/Merge Submeshes 0,3,4,7,10,11,12", true)]
public static bool MergeSubmesh_0_3_4_7_10_11_12_Menu_Verify()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
return Meshes.Length > 0;
}
[MenuItem("Assets/Mesh/Merge Submeshes 0,3,4,7,10,11,12")]
public static void MergeSubmesh_0_3_4_7_10_11_12_Menu()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
foreach (var mesh in Meshes)
{
var NewMesh = ExtractSubmeshesAsMesh(mesh, new int[] { 0, 3, 4, 7, 10, 11, 12 });
AssetWriter.SaveAsset(NewMesh);
}
}
[MenuItem("Assets/Mesh/Merge Submeshes 1,2,5,6,8,9", true)]
public static bool MergeSubmesh_1_2_5_6_8_9_Menu_Verify()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
return Meshes.Length > 0;
}
[MenuItem("Assets/Mesh/Merge Submeshes 1,2,5,6,8,9")]
public static void MergeSubmesh_1_2_5_6_8_9_Menu()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
foreach (var mesh in Meshes)
{
var NewMesh = ExtractSubmeshesAsMesh(mesh, new int[] { 1, 2, 5, 6, 8, 9 });
AssetWriter.SaveAsset(NewMesh);
}
}
[MenuItem("Assets/Mesh/Split Submeshes...", true)]
public static bool SplitSubmeshes_Verify()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
return Meshes.Length > 0;
}
[MenuItem("Assets/Mesh/Split Submeshes...")]
public static void SplitSubmeshes()
{
var Meshes = Selection.GetFiltered<Mesh>(SelectionMode.Assets);
foreach (var mesh in Meshes)
{
for (int s = 0; s < mesh.subMeshCount; s++)
{
var NewMesh = ExtractSubmeshesAsMesh(mesh, new int[] { s });
AssetWriter.SaveAsset(NewMesh);
}
}
}
#endif
#if UNITY_EDITOR
//[MenuItem("CONTEXT/Transform/Merge GameObject Tree into one mesh...")]
[MenuItem("GameObject/Merge GameObject Tree into one mesh...",false,49)]
static void Menu_GameObjectTreeToNewMesh(MenuCommand menuCommand)
{
//var t = menuCommand.context as Transform;
var go = UnityEditor.Selection.activeGameObject;
if (!go)
throw new System.Exception("No object selected");
var t = go.transform;
var MergedMesh = MergeTransformTreeToNewMesh(t);
MergedMesh.name = t.name + " merged";
AssetWriter.SaveAsNewAsset(MergedMesh);
}
#endif
public static Mesh MergeTransformTreeToNewMesh(Transform RootObject)
{
var Meshes = new List<Mesh>();
var Transforms = new List<Matrix4x4>();
// Apply this transform to make
//var GlobalTransform = RootObject.worldToLocalMatrix;
var GlobalTransform = Matrix4x4.identity;
System.Action<MeshFilter> AppendMesh = (MeshFilter Child) =>
{
var Object = Child.GetComponent<Transform>();
var mf = Object.GetComponent<MeshFilter>();
if (mf == null)
return;
var mesh = mf.sharedMesh;
var trans = GlobalTransform * Object.localToWorldMatrix;
Meshes.Add(mesh);
Transforms.Add(trans);
};
// recurse the tree
var MeshFilterChildren = RootObject.GetComponentsInChildren<MeshFilter>();
foreach (var Child in MeshFilterChildren)
AppendMesh(Child);
// make a new mesh
var MeshContents = new MeshContents();
for (var i = 0; i < Meshes.Count; i++)
{
var Mesh = Meshes[i];
var Transform = Transforms[i];
MeshContents.AddMesh(Mesh, Transform);
}
var MergedMesh = MeshContents.CreateMesh(RootObject.name + " Merged");
return MergedMesh;
}
public static void MergeSubmeshes(Mesh mesh, int IndexesUvChannel)
{
// get a merged triangle list
var NewTriangles = new List<int>();
var SubmeshIndexes = new Vector2[mesh.vertexCount];
for (int sm = 0; sm < mesh.subMeshCount; sm++)
{
var OldTriangleCount = NewTriangles.Count;
#if UNITY_2018_0_OR_NEWER
var smtris = mesh.GetTriangles(sm, true);
#else
var smtris = mesh.GetTriangles(sm);
#endif
NewTriangles.AddRange(smtris);
// set the submesh index of the new batch
for (int t = OldTriangleCount; t < NewTriangles.Count; t++)
{
var vi = NewTriangles[t];
SubmeshIndexes[vi].x = sm;
}
}
// remove old triangles
mesh.subMeshCount = 1;
mesh.SetUVs(IndexesUvChannel, new List<Vector2>(SubmeshIndexes));
mesh.SetTriangles(NewTriangles, 0);
mesh.UploadMeshData(false);
}
public static Mesh ExtractSubmeshesAsMesh(Mesh mesh, int[] SubmeshesToMerge)
{
// copy verts, uvs etc, but not triangle sets
var MergedMesh = CopyMesh(mesh, false);
#if UNITY_2018_OR_NEWER
// just in case we overflow, always set to 32bit format
MergedMesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
#endif
/*
MergedMesh.subMeshCount = SubmeshesToMerge.Length;
for (int i = 0; i < SubmeshesToMerge.Length; i++)
{
var sm = SubmeshesToMerge[i];
var smtriangles = mesh.GetTriangles(sm, true);
MergedMesh.name += "_" + sm;
MergedMesh.SetTriangles(smtriangles, i);
}
*/
var MergedTriangles = new List<int>();
foreach (var sm in SubmeshesToMerge)
{
#if UNITY_2018_OR_NEWER
var smtriangles = mesh.GetTriangles(sm,true);
#else
var smtriangles = mesh.GetTriangles(sm);
#endif
MergedTriangles.AddRange(smtriangles);
MergedMesh.name += "_" + sm;
}
MergedMesh.subMeshCount = 1;
MergedMesh.SetTriangles(MergedTriangles, 0);
return MergedMesh;
}
class Vertex
{
public Vector3 position;
public Vector3 normal;
public Vector2 uv1;
public Vector2 uv2;
public Vector2 uv3;
public Color colourf;
public Color32 colour32;
};
static void SafeSet<T>(ref T Value, T[] Array, int ArrayIndex)
{
if (Array == null)
return;
if (Array.Length == 0)
return;
Value = Array[ArrayIndex];
}
static T[] NullIfEmpty<T>(T[] Array)
{
if (Array == null)
return null;
if (Array.Length == 0)
return null;
return Array;
}
// center the mesh so the center of the bounds is 0,0,0 (for when your mesh bounds may be specifically offset!)
public static void CenterOnBounds(this Mesh mesh)
{
// get delta to center it
var MeshBounds = mesh.bounds;
var Delta = -MeshBounds.center;
var Positions = mesh.vertices;
for (int i = 0; i < Positions.Length; i++)
Positions[i] += Delta;
mesh.vertices = Positions;
// this should be 000 now
MeshBounds.center += Delta;
mesh.bounds = MeshBounds;
}
public static Mesh CopyMesh(Mesh OldMesh, bool CopyTriangles = true)
{
var NewMesh = new Mesh();
NewMesh.name = OldMesh.name;
NewMesh.vertices = NullIfEmpty(OldMesh.vertices);
NewMesh.uv = NullIfEmpty(OldMesh.uv);
NewMesh.uv2 = NullIfEmpty(OldMesh.uv2);
NewMesh.uv3 = NullIfEmpty(OldMesh.uv3);
NewMesh.normals = NullIfEmpty(OldMesh.normals);
NewMesh.colors = NullIfEmpty(OldMesh.colors);
NewMesh.tangents = NullIfEmpty(OldMesh.tangents);
NewMesh.bounds = OldMesh.bounds;
// gr: VERY important. submeshes with > 65k triangles causes my mac to reboot if the mesh gets uploaded without 32bit indexes set.
// probably should set this in the right conditions irregardless of old mesh settings
#if UNITY_2018_OR_NEWER
NewMesh.indexFormat = OldMesh.indexFormat;
#endif
if (CopyTriangles)
{
NewMesh.subMeshCount = OldMesh.subMeshCount;
for (int sm = 0; sm < OldMesh.subMeshCount; sm++)
{
#if UNITY_2018_OR_NEWER
var smtriangles = OldMesh.GetTriangles(sm,true);
#else
var smtriangles = OldMesh.GetTriangles(sm);
#endif