@scenoco-three/unity 1.3.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,96 @@
1
+ // Written by scenoco-unity on every export — edits here are overwritten.
2
+ using System;
3
+ using System.Collections.Generic;
4
+ using System.Reflection;
5
+ using UnityEditor;
6
+ using UnityEditor.SceneManagement;
7
+ using UnityEngine;
8
+
9
+ namespace SceNoCo
10
+ {
11
+ /// <summary>
12
+ /// SceNoCo's <c>onValidate</c> also runs when the editor moves a behaviour's object, or an object the
13
+ /// behaviour was given (a knot under a spline's <c>knots</c>); Unity's runs only for a changed field.
14
+ /// This calls <c>OnValidate</c> for a move too: on the moved object's behaviours, and on every behaviour
15
+ /// in its scene whose fields hold that object or one above it. Edit mode only.
16
+ /// </summary>
17
+ [InitializeOnLoad]
18
+ static class Validate
19
+ {
20
+ static readonly Dictionary<Type, MethodInfo> hooks = new();
21
+
22
+ static Validate() => ObjectChangeEvents.changesPublished += Changed;
23
+
24
+ static void Changed(ref ObjectChangeEventStream stream)
25
+ {
26
+ if (EditorApplication.isPlayingOrWillChangePlaymode) return;
27
+ var moved = new HashSet<Transform>();
28
+ for (var i = 0; i < stream.length; i++)
29
+ {
30
+ if (stream.GetEventType(i) != ObjectChangeKind.ChangeGameObjectOrComponentProperties) continue;
31
+ stream.GetChangeGameObjectOrComponentPropertiesEvent(i, out var e);
32
+ // A field changed on a behaviour is Unity's own OnValidate already; a move is its Transform.
33
+ #if UNITY_6000_6_OR_NEWER
34
+ var changed = EditorUtility.EntityIdToObject(e.entityId);
35
+ #else
36
+ var changed = EditorUtility.InstanceIDToObject(e.instanceId);
37
+ #endif
38
+ if (changed is Transform t) moved.Add(t);
39
+ else if (changed is GameObject go) moved.Add(go.transform);
40
+ }
41
+ if (moved.Count == 0) return;
42
+
43
+ var called = new HashSet<MonoBehaviour>();
44
+ foreach (var scene in Scenes(moved))
45
+ foreach (var root in scene.GetRootGameObjects())
46
+ foreach (var b in root.GetComponentsInChildren<MonoBehaviour>(true))
47
+ if (b != null && IsGame(b.GetType()) && Hook(b.GetType()) != null && Concerns(b, moved)) called.Add(b);
48
+ foreach (var b in called)
49
+ {
50
+ try { Hook(b.GetType()).Invoke(b, null); }
51
+ catch (TargetInvocationException error) { Debug.LogException(error.InnerException ?? error, b); }
52
+ if (b.gameObject.scene.IsValid()) EditorSceneManager.MarkSceneDirty(b.gameObject.scene);
53
+ }
54
+ }
55
+
56
+ static IEnumerable<UnityEngine.SceneManagement.Scene> Scenes(HashSet<Transform> moved)
57
+ {
58
+ var seen = new HashSet<UnityEngine.SceneManagement.Scene>();
59
+ foreach (var t in moved) if (t != null && t.gameObject.scene.IsValid() && seen.Add(t.gameObject.scene)) yield return t.gameObject.scene;
60
+ }
61
+
62
+ /// <summary>The behaviour is on a moved object, or a field of it holds one or an object above one.</summary>
63
+ static bool Concerns(MonoBehaviour b, HashSet<Transform> moved)
64
+ {
65
+ foreach (var t in moved) if (t != null && t == b.transform) return true;
66
+ var field = new SerializedObject(b).GetIterator();
67
+ while (field.Next(true))
68
+ {
69
+ if (field.propertyType != SerializedPropertyType.ObjectReference || field.name == "m_Script") continue;
70
+ var held = field.objectReferenceValue switch
71
+ {
72
+ GameObject go => go.transform,
73
+ Component c => c.transform,
74
+ _ => null,
75
+ };
76
+ if (held == null) continue;
77
+ foreach (var t in moved) if (t != null && t.IsChildOf(held)) return true;
78
+ }
79
+ return false;
80
+ }
81
+
82
+ /// <summary>The game's own behaviour: Unity's components (a SplineInstantiate) follow their own changes.</summary>
83
+ static bool IsGame(Type type)
84
+ {
85
+ var assembly = type.Assembly.GetName().Name;
86
+ return !assembly.StartsWith("Unity") && !assembly.StartsWith("UnityEngine");
87
+ }
88
+
89
+ static MethodInfo Hook(Type type)
90
+ {
91
+ if (!hooks.TryGetValue(type, out var hook))
92
+ hooks[type] = hook = type.GetMethod("OnValidate", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
93
+ return hook;
94
+ }
95
+ }
96
+ }
@@ -0,0 +1,66 @@
1
+ // Written by scenoco-unity on every export — edits here are overwritten.
2
+ using System.Collections.Generic;
3
+ using Unity.Mathematics;
4
+ using UnityEngine;
5
+ using UnityEngine.Splines;
6
+
7
+ namespace SceNoCo
8
+ {
9
+ /// <summary>
10
+ /// The knots of this object's spline are the children of <see cref="knots"/>, in order, as SceNoCo's
11
+ /// <c>&lt;SplineContainer knots={node} /&gt;</c> reads them: move one, add one or take one away, in the
12
+ /// Scene view or from code, and the spline follows. Each knot's tangents are made smooth from its
13
+ /// neighbours, a third of the way to each (SceNoCo's AutoSmooth), so both engines draw the same curve.
14
+ /// </summary>
15
+ [ExecuteAlways, DisallowMultipleComponent, RequireComponent(typeof(SplineContainer))]
16
+ public sealed class SplineKnotNodes : MonoBehaviour
17
+ {
18
+ /// <summary>The object whose children are the knots.</summary>
19
+ public Transform knots;
20
+
21
+ readonly List<Vector3> seen = new();
22
+
23
+ void OnEnable()
24
+ {
25
+ seen.Clear();
26
+ Rebuild();
27
+ }
28
+
29
+ // Once a frame, as SceNoCo's SplineContainer looks: a rebuild only when a knot moved.
30
+ void Update() => Rebuild();
31
+
32
+ void Rebuild()
33
+ {
34
+ if (knots == null) return;
35
+ var points = new List<Vector3>(knots.childCount);
36
+ foreach (Transform child in knots) points.Add(transform.InverseTransformPoint(child.position));
37
+ if (Same(points, seen)) return;
38
+ seen.Clear();
39
+ seen.AddRange(points);
40
+
41
+ var spline = GetComponent<SplineContainer>().Spline;
42
+ var closed = spline.Closed;
43
+ var count = points.Count;
44
+ Vector3 At(int i) => points[closed ? (i % count + count) % count : Mathf.Clamp(i, 0, count - 1)];
45
+ // Along the line from the knot before to the one after, a third of the way to each neighbour.
46
+ Vector3 Smooth(int i, bool outward)
47
+ {
48
+ if (!closed && (outward ? i == count - 1 : i == 0)) return Vector3.zero;
49
+ var along = (At(i + 1) - At(i - 1)).normalized;
50
+ return outward ? along * (At(i + 1) - At(i)).magnitude / 3 : -along * (At(i) - At(i - 1)).magnitude / 3;
51
+ }
52
+
53
+ spline.Clear();
54
+ for (var i = 0; i < count; i++)
55
+ spline.Add(new BezierKnot(points[i], Smooth(i, false), Smooth(i, true), quaternion.identity), TangentMode.Broken);
56
+ spline.Closed = closed;
57
+ }
58
+
59
+ static bool Same(List<Vector3> a, List<Vector3> b)
60
+ {
61
+ if (a.Count != b.Count) return false;
62
+ for (var i = 0; i < a.Count; i++) if (a[i] != b[i]) return false;
63
+ return true;
64
+ }
65
+ }
66
+ }
@@ -0,0 +1,255 @@
1
+ // Written by scenoco-unity on every export — edits here are overwritten.
2
+ using System.Collections.Generic;
3
+ using System.Linq;
4
+ using Unity.Mathematics;
5
+ using UnityEngine;
6
+ using UnityEngine.Rendering;
7
+ using UnityEngine.Splines;
8
+
9
+ namespace SceNoCo
10
+ {
11
+ /// <summary>
12
+ /// SceNoCo's SplineMesh: bends a modelled piece along a spline, repeated end to end to cover it, into
13
+ /// this object's mesh — a road section with its kerbs and markings, a rail, a fence. Unity has no
14
+ /// built-in for it (its SplineExtrude sweeps a shape instead).
15
+ ///
16
+ /// <see cref="mesh"/> is a model — each of its meshes bent, each keeping its material — or a bare
17
+ /// Mesh drawn with this renderer's own material. The piece runs along its +Z with +Y up; its +X
18
+ /// goes to the spline's right. It bends only where it has vertices, so a piece needs edge loops
19
+ /// along its length. Copies are stretched a little so a whole number of them fills the length.
20
+ /// Bent when enabled and whenever the spline, the piece or the count changes. In the editor, into one
21
+ /// mesh asset per object beside the scene (<c>&lt;Scene&gt;/SplineMesh_&lt;path&gt;.asset</c>), as Unity's
22
+ /// SplineExtrude keeps its own, written again rather than made anew: opening the scene changes
23
+ /// nothing in it. Playing, into a mesh of its own; a player build reads the piece's vertices, so its
24
+ /// model needs Read/Write on.
25
+ /// </summary>
26
+ [ExecuteAlways, DisallowMultipleComponent, RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
27
+ public sealed class SplineMesh : MonoBehaviour
28
+ {
29
+ /// <summary>The spline. Left empty, the one on this object.</summary>
30
+ public SplineContainer container;
31
+ /// <summary>The piece to repeat: a model (its prefab) or a Mesh.</summary>
32
+ public Object mesh;
33
+ /// <summary>How many copies; 0 fits as many as the piece's own length allows.</summary>
34
+ public int count;
35
+
36
+ Mesh built;
37
+ /// <summary>What <see cref="built"/> was bent from: rebuilt only when this changes.</summary>
38
+ int builtFrom;
39
+ bool dirty;
40
+
41
+ /// <summary>One part of the piece: a submesh's vertices in the piece's own space, and its material.</summary>
42
+ struct Part
43
+ {
44
+ public Vector3[] positions, normals;
45
+ public Vector2[] uvs;
46
+ public int[] triangles;
47
+ public Material material;
48
+ }
49
+
50
+ void OnEnable()
51
+ {
52
+ Spline.Changed += OnSplineChanged;
53
+ Rebuild();
54
+ }
55
+
56
+ void OnDisable() => Spline.Changed -= OnSplineChanged;
57
+
58
+ void OnValidate() => dirty = true;
59
+
60
+ void OnSplineChanged(Spline spline, int knot, SplineModification change)
61
+ {
62
+ var c = Container;
63
+ if (c != null && c.Splines.Contains(spline)) dirty = true;
64
+ }
65
+
66
+ void Update()
67
+ {
68
+ if (dirty) Rebuild();
69
+ }
70
+
71
+ SplineContainer Container => container != null ? container : GetComponent<SplineContainer>();
72
+
73
+ /// <summary>The inputs, as one number: the knots, the spline's place against this object, the piece and the count.</summary>
74
+ int Inputs(SplineContainer spline)
75
+ {
76
+ var hash = new System.HashCode();
77
+ hash.Add(spline.Spline.Closed);
78
+ foreach (var knot in spline.Spline.Knots) { hash.Add(knot.Position); hash.Add(knot.TangentIn); hash.Add(knot.TangentOut); hash.Add(knot.Rotation); }
79
+ var relative = transform.worldToLocalMatrix * spline.transform.localToWorldMatrix;
80
+ for (var i = 0; i < 16; i++) hash.Add(Mathf.Round(relative[i] * 1e4f));
81
+ hash.Add(mesh.name);
82
+ hash.Add(count);
83
+ return hash.ToHashCode();
84
+ }
85
+
86
+ /// <summary>Bend again, if the spline or the piece changed since the last time.</summary>
87
+ public void Rebuild()
88
+ {
89
+ dirty = false;
90
+ var spline = Container;
91
+ if (mesh == null || spline == null || spline.Spline == null || spline.Spline.Count < 2) return;
92
+ var inputs = Inputs(spline);
93
+ var filter = GetComponent<MeshFilter>();
94
+ if (built != null && inputs == builtFrom)
95
+ {
96
+ if (filter.sharedMesh != built) filter.sharedMesh = built;
97
+ return;
98
+ }
99
+ var parts = PartsOf(mesh);
100
+ if (parts.Count == 0) return;
101
+
102
+ // One length for the whole piece, so its parts stay in step.
103
+ float minZ = float.MaxValue, maxZ = float.MinValue;
104
+ foreach (var part in parts)
105
+ foreach (var p in part.positions) { minZ = Mathf.Min(minZ, p.z); maxZ = Mathf.Max(maxZ, p.z); }
106
+ var pieceLength = Mathf.Max(1e-6f, maxZ - minZ);
107
+ var length = spline.CalculateLength();
108
+ var copies = count > 0 ? count : Mathf.Max(1, Mathf.RoundToInt(length / pieceLength));
109
+
110
+ // A piece's vertices share edge loops: one frame per place along the spline.
111
+ var frames = new Dictionary<float, (Vector3 position, Vector3 right, Vector3 up, Vector3 forward)>();
112
+ (Vector3, Vector3, Vector3, Vector3) FrameAt(float t)
113
+ {
114
+ if (frames.TryGetValue(t, out var f)) return f;
115
+ spline.Evaluate(Mathf.Clamp01(t), out float3 position, out float3 tangent, out float3 up);
116
+ var forward = transform.InverseTransformDirection((Vector3)math.normalizesafe(tangent)).normalized;
117
+ var upward = transform.InverseTransformDirection((Vector3)math.normalizesafe(up)).normalized;
118
+ var right = Vector3.Cross(upward, forward).normalized;
119
+ upward = Vector3.Cross(forward, right);
120
+ f = (transform.InverseTransformPoint(position), right, upward, forward);
121
+ frames[t] = f;
122
+ return f;
123
+ }
124
+
125
+ var positions = new List<Vector3>();
126
+ var normals = new List<Vector3>();
127
+ var uvs = new List<Vector2>();
128
+ var submeshes = new List<int[]>();
129
+ var materials = new List<Material>();
130
+ foreach (var part in parts)
131
+ {
132
+ var triangles = new List<int>(part.triangles.Length * copies);
133
+ for (var i = 0; i < copies; i++)
134
+ {
135
+ var start = positions.Count;
136
+ for (var v = 0; v < part.positions.Length; v++)
137
+ {
138
+ var p = part.positions[v];
139
+ var (o, r, u, f) = FrameAt((i + (p.z - minZ) / pieceLength) / copies);
140
+ positions.Add(o + r * p.x + u * p.y);
141
+ if (part.normals != null) { var n = part.normals[v]; normals.Add((r * n.x + u * n.y + f * n.z).normalized); }
142
+ if (part.uvs != null) uvs.Add(part.uvs[v]);
143
+ }
144
+ foreach (var index in part.triangles) triangles.Add(start + index);
145
+ }
146
+ submeshes.Add(triangles.ToArray());
147
+ materials.Add(part.material);
148
+ }
149
+
150
+ if (built == null) built = NewMesh();
151
+ built.Clear();
152
+ built.indexFormat = positions.Count > 65535 ? IndexFormat.UInt32 : IndexFormat.UInt16;
153
+ built.SetVertices(positions);
154
+ if (normals.Count == positions.Count) built.SetNormals(normals);
155
+ if (uvs.Count == positions.Count) built.SetUVs(0, uvs);
156
+ built.subMeshCount = submeshes.Count;
157
+ for (var s = 0; s < submeshes.Count; s++) built.SetTriangles(submeshes[s], s);
158
+ if (normals.Count != positions.Count) built.RecalculateNormals();
159
+ built.RecalculateBounds();
160
+ builtFrom = inputs;
161
+ filter.sharedMesh = built;
162
+ if (mesh is GameObject) GetComponent<MeshRenderer>().sharedMaterials = materials.ToArray();
163
+ #if UNITY_EDITOR
164
+ if (UnityEditor.EditorUtility.IsPersistent(built)) UnityEditor.EditorUtility.SetDirty(built);
165
+ #endif
166
+ }
167
+
168
+ /// <summary>The mesh to bend into: in the editor, this object's asset in the scene's own folder; playing, a mesh of its own.</summary>
169
+ Mesh NewMesh()
170
+ {
171
+ #if UNITY_EDITOR
172
+ var scene = gameObject.scene.path;
173
+ if (!Application.isPlaying && !string.IsNullOrEmpty(scene))
174
+ {
175
+ var folder = $"{System.IO.Path.GetDirectoryName(scene)}/{System.IO.Path.GetFileNameWithoutExtension(scene)}";
176
+ var named = transform;
177
+ var path = name;
178
+ while ((named = named.parent) != null) path = $"{named.name}_{path}";
179
+ var file = $"{folder}/SplineMesh_{path}.asset";
180
+ var existing = UnityEditor.AssetDatabase.LoadAssetAtPath<Mesh>(file);
181
+ if (existing != null) return existing;
182
+ System.IO.Directory.CreateDirectory(folder);
183
+ var asset = new Mesh { name = $"SplineMesh_{path}" };
184
+ UnityEditor.AssetDatabase.CreateAsset(asset, file);
185
+ return asset;
186
+ }
187
+ #endif
188
+ return new Mesh { name = $"SplineMesh_{name}", hideFlags = HideFlags.DontSave };
189
+ }
190
+
191
+ void OnDestroy()
192
+ {
193
+ // A mesh made playing is this object's alone; the editor's is an asset, kept.
194
+ if (built != null && Application.isPlaying) Destroy(built);
195
+ }
196
+
197
+ /// <summary>A model's submeshes, each in the model root's space, or a lone Mesh's.</summary>
198
+ static List<Part> PartsOf(Object source)
199
+ {
200
+ var parts = new List<Part>();
201
+ if (source is Mesh lone)
202
+ {
203
+ for (var s = 0; s < lone.subMeshCount; s++) parts.Add(PartOf(lone, s, Matrix4x4.identity, null));
204
+ return parts;
205
+ }
206
+ if (source is not GameObject root) return parts;
207
+ var toRoot = root.transform.worldToLocalMatrix;
208
+ foreach (var filter in root.GetComponentsInChildren<MeshFilter>(true))
209
+ {
210
+ var m = filter.sharedMesh;
211
+ if (m == null) continue;
212
+ var shared = filter.TryGetComponent<MeshRenderer>(out var renderer) ? renderer.sharedMaterials : new Material[0];
213
+ var matrix = toRoot * filter.transform.localToWorldMatrix;
214
+ for (var s = 0; s < m.subMeshCount; s++)
215
+ parts.Add(PartOf(m, s, matrix, shared.Length > 0 ? shared[Mathf.Min(s, shared.Length - 1)] : null));
216
+ }
217
+ return parts;
218
+ }
219
+
220
+ /// <summary>One submesh, its vertices renumbered from 0 and moved by <paramref name="matrix"/>.</summary>
221
+ static Part PartOf(Mesh m, int submesh, Matrix4x4 matrix, Material material)
222
+ {
223
+ var source = m.GetTriangles(submesh);
224
+ var vertices = m.vertices;
225
+ var sourceNormals = m.normals;
226
+ var sourceUvs = m.uv;
227
+ var remap = new Dictionary<int, int>();
228
+ var positions = new List<Vector3>();
229
+ var normals = new List<Vector3>();
230
+ var uvs = new List<Vector2>();
231
+ var triangles = new int[source.Length];
232
+ var normalMatrix = matrix.inverse.transpose;
233
+ for (var i = 0; i < source.Length; i++)
234
+ {
235
+ var v = source[i];
236
+ if (!remap.TryGetValue(v, out var index))
237
+ {
238
+ index = remap[v] = positions.Count;
239
+ positions.Add(matrix.MultiplyPoint3x4(vertices[v]));
240
+ if (sourceNormals.Length == vertices.Length) normals.Add(normalMatrix.MultiplyVector(sourceNormals[v]).normalized);
241
+ if (sourceUvs.Length == vertices.Length) uvs.Add(sourceUvs[v]);
242
+ }
243
+ triangles[i] = index;
244
+ }
245
+ return new Part
246
+ {
247
+ positions = positions.ToArray(),
248
+ normals = normals.Count == positions.Count ? normals.ToArray() : null,
249
+ uvs = uvs.Count == positions.Count ? uvs.ToArray() : null,
250
+ triangles = triangles,
251
+ material = material,
252
+ };
253
+ }
254
+ }
255
+ }
@@ -1,32 +0,0 @@
1
- {
2
- "name": "SceNoCo.Driver",
3
- "rootNamespace": "SceNoCo.Driver",
4
- "references": [
5
- "Unity.Pipeline.Attributes",
6
- "Unity.InputSystem"
7
- ],
8
- "includePlatforms": [
9
- "Editor"
10
- ],
11
- "excludePlatforms": [],
12
- "allowUnsafeCode": false,
13
- "overrideReferences": false,
14
- "precompiledReferences": [],
15
- "autoReferenced": false,
16
- "defineConstraints": [
17
- "SCENOCO_PIPELINE"
18
- ],
19
- "versionDefines": [
20
- {
21
- "name": "com.unity.pipeline",
22
- "expression": "0.0.0",
23
- "define": "SCENOCO_PIPELINE"
24
- },
25
- {
26
- "name": "com.unity.inputsystem",
27
- "expression": "1.0.0",
28
- "define": "SCENOCO_INPUT_SYSTEM"
29
- }
30
- ],
31
- "noEngineReferences": false
32
- }