@scenoco-three/unity 1.4.0 → 1.6.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.
@@ -1,8 +1,12 @@
1
1
  // Written by scenoco-unity on every export — edits here are overwritten.
2
2
  //
3
- // Builds what Assets/SceNoCo/export.json describes with Unity's own API: mesh and material assets,
4
- // prefabs (nested ones as nested prefabs), and scenes. It runs by itself after the export's scripts
5
- // compile, or from SceNoCo ▸ Import. Re-importing updates assets in place, so references to them hold.
3
+ // Makes what Assets/SceNoCo/export.json describes and the game's scenes and prefabs name: meshes,
4
+ // materials, terrains, physics and particle materials, post-processing profiles, UI panels, and the
5
+ // project's settings — with Unity's own API, updating each asset in place so references to it hold.
6
+ // Then the scenes and prefabs themselves: their text (.uscene, .uprefab) goes beside where they
7
+ // belong, and Scenoco (com.roro.scenoco) builds each .unity and .prefab from it — on a later export,
8
+ // changes only what changed. What the text has no place for, a scene's lighting, is set on the scene
9
+ // after. It runs by itself after the export's scripts compile, or from SceNoCo ▸ Import.
6
10
  using System;
7
11
  using System.Collections.Generic;
8
12
  using System.Globalization;
@@ -23,7 +27,13 @@ namespace SceNoCo
23
27
  public static class Importer
24
28
  {
25
29
  const string DataPath = "Assets/SceNoCo/export.json";
30
+ /// <summary>Written once the recommended rendering settings are set: later imports leave them to the port.</summary>
31
+ const string RecommendedPath = "ProjectSettings/SceNoCoRecommended.txt";
26
32
  const string PendingPath = "Assets/SceNoCo/.pending";
33
+ /// <summary>Where the export leaves the scenes' and prefabs' text: Unity imports nothing in a folder ending in ~.</summary>
34
+ const string Staged = "Assets/SceNoCo/Twins~";
35
+ // Each twin as the last import left it, after Scenoco wrote it: what tells a port's edit from an export.
36
+ const string Placed = "Assets/SceNoCo/Placed~";
27
37
 
28
38
  static Importer()
29
39
  {
@@ -31,17 +41,29 @@ namespace SceNoCo
31
41
  EditorApplication.update += WhenSettled;
32
42
  }
33
43
 
44
+ static double nextLook;
45
+
46
+ // Watched for as long as the Editor runs, not once after a reload: an export that changes no code
47
+ // reloads nothing, and its .pending would wait unread. A look a second costs one file check.
34
48
  static void WhenSettled()
35
49
  {
50
+ if (EditorApplication.timeSinceStartup < nextLook) return;
51
+ nextLook = EditorApplication.timeSinceStartup + 1;
36
52
  if (EditorApplication.isCompiling || EditorApplication.isUpdating || EditorApplication.isPlayingOrWillChangePlaymode) return;
37
- EditorApplication.update -= WhenSettled;
38
- if (File.Exists(PendingPath)) Import();
53
+ if (!File.Exists(PendingPath)) return;
54
+ try { Import(); }
55
+ catch (Exception error)
56
+ {
57
+ // Once, not every second: the export stays where it is for SceNoCo ▸ Import.
58
+ File.Delete(PendingPath);
59
+ Debug.LogException(error);
60
+ Debug.LogError("SceNoCo: the import stopped (above). Fix it, then SceNoCo ▸ Import.");
61
+ }
39
62
  }
40
63
 
41
64
  static readonly List<string> warnings = new List<string>();
42
65
  /// <summary>What the last import could not carry across, each with where it was written.</summary>
43
66
  public static IReadOnlyList<string> Warnings => warnings;
44
- static Dictionary<string, object> ui;
45
67
 
46
68
  [MenuItem("SceNoCo/Import")]
47
69
  public static void Import()
@@ -49,50 +71,162 @@ namespace SceNoCo
49
71
  if (!File.Exists(DataPath))
50
72
  {
51
73
  Debug.LogError($"SceNoCo: no {DataPath} — run scenoco-unity first.");
74
+ if (File.Exists(PendingPath)) File.Delete(PendingPath);
52
75
  return;
53
76
  }
54
77
  warnings.Clear();
55
78
  AssetDatabase.Refresh();
56
79
  var data = (Dictionary<string, object>)Json.Parse(File.ReadAllText(DataPath));
57
80
  foreach (var w in List(data["warnings"])) warnings.Add((string)w);
58
- ui = data.TryGetValue("ui", out var u) ? Obj(u) : null;
59
- Try(Project.Recommended, "rendering settings");
81
+ // The rendering settings are a starting point, set by the first import only: a port that changes
82
+ // one — a game lit in gamma — keeps its choice through every export after.
83
+ if (!File.Exists(RecommendedPath))
84
+ {
85
+ Try(Project.Recommended, "rendering settings");
86
+ File.WriteAllText(RecommendedPath, "SceNoCo set this project's rendering settings once. Delete this file to set them again on the next import.\n");
87
+ }
60
88
  if (data.TryGetValue("layers", out var layers)) Try(() => Project.Layers(Obj(layers)), "layers");
61
89
  if (data.TryGetValue("input", out var input)) Try(() => Project.Input((string)input), "input actions");
62
90
 
91
+ // The assets the text names, before the text is built.
92
+ var rerooted = false;
93
+ Try(() => rerooted = ModelRoots(), "the models' import settings");
94
+ if (data.TryGetValue("dataTextures", out var stamps))
95
+ foreach (var t in List(stamps)) Try(() => DataTexture((string)t), (string)t);
96
+ if (data.TryGetValue("modelVariants", out var variants))
97
+ foreach (var v in List(variants)) Try(() => ModelVariant(Obj(v)), Str(Obj(v), "path"));
63
98
  foreach (var m in List(data["meshes"])) Try(() => MakeMesh(Obj(m)), Str(Obj(m), "path"));
64
- Terrains.Offsets.Clear();
65
- if (data.TryGetValue("terrains", out var ts)) foreach (var t in List(ts)) Try(() => Terrains.Make(Obj(t)), Str(Obj(t), "path"));
99
+ foreach (var t in List(data["terrains"])) Try(() => MakeTerrain(Obj(t)), Str(Obj(t), "path"));
100
+ if (data.TryGetValue("terrainMaterial", out var tm)) Try(() => TerrainMaterial((string)tm), (string)tm);
66
101
  foreach (var m in List(data["materials"])) Try(() => MakeMaterial(Obj(m)), Str(Obj(m), "path"));
102
+ foreach (var m in List(data["physicsMaterials"])) Try(() => PhysicsMaterial(Obj(m)), Str(Obj(m), "path"));
103
+ foreach (var b in List(data["particleMaterials"])) Try(() => ParticleMaterial((string)b), $"Particles-{b}");
104
+ foreach (var v in List(data["volumes"])) Try(() => Volumes.Make(Obj(v)), Str(Obj(v), "path"));
105
+ var theme = data.TryGetValue("theme", out var th) ? (string)th : null;
106
+ foreach (var p in List(data["panels"])) Try(() => MakePanel(Obj(p), theme), Str(Obj(p), "path"));
67
107
  AssetDatabase.SaveAssets();
68
108
 
69
- var prefabs = List(data["prefabs"]).Select(Obj).ToList();
70
- // First every prefab's objects and components, then their fields: a field may name a prefab saved later.
71
- foreach (var p in prefabs) Try(() => SavePrefab(p), Str(p, "path"));
72
- foreach (var p in prefabs) Try(() => WirePrefab(p), Str(p, "path"));
109
+ // The scenes and prefabs: their text in place, built by Scenoco.
110
+ // A twin the port edited since the last import is the port's: kept, with the export beside it to merge.
111
+ var twins = List(data["twins"]).Select(t => (string)t).ToList();
112
+ var kept = new HashSet<string>();
113
+ foreach (var twin in twins)
114
+ Try(() =>
115
+ {
116
+ var rel = twin.Substring("Assets/".Length);
117
+ var placed = Path.Combine(Placed, rel);
118
+ if (File.Exists(twin) && File.Exists(placed) && Text(twin) != Text(placed))
119
+ {
120
+ kept.Add(twin);
121
+ warnings.Add($"{twin}: edited since the last export — kept. This export's is {Path.Combine(Staged, rel)}: merge what it changes by hand, or delete {placed} and import again to take it whole.");
122
+ return;
123
+ }
124
+ Directory.CreateDirectory(Path.GetDirectoryName(twin));
125
+ File.Copy(Path.Combine(Staged, rel), twin, true);
126
+ }, twin);
127
+ AssetDatabase.Refresh();
128
+ var status = Scenoco.Files.Sync();
129
+ foreach (var line in status.Split('\n'))
130
+ if (twins.Any(t => line.StartsWith(t + ":")) && !line.Contains(": Synced")) warnings.Add(line);
131
+ foreach (var twin in twins.Where(t => !kept.Contains(t) && File.Exists(t)))
132
+ Try(() =>
133
+ {
134
+ var placed = Path.Combine(Placed, twin.Substring("Assets/".Length));
135
+ Directory.CreateDirectory(Path.GetDirectoryName(placed));
136
+ File.Copy(twin, placed, true);
137
+ }, twin);
73
138
 
74
139
  var scenes = List(data["scenes"]).Select(Obj).ToList();
75
- reopen = null;
76
- for (var i = 0; i < scenes.Count; i++)
77
- {
78
- var s = scenes[i];
79
- var first = i == 0;
80
- Try(() => SaveScene(s, first), Str(s, "path"));
81
- }
82
- var paths = scenes.Select(s => Str(s, "path")).ToList();
83
- // An empty untitled scene stood in for the first exported one, or an open scene was rebuilt: open it again.
84
- if (reopen != null && paths.Count > 0) EditorSceneManager.OpenScene(reopen == "" ? paths[0] : reopen, OpenSceneMode.Single);
140
+ foreach (var s in scenes) Try(() => Lighting(s), Str(s, "path"));
141
+ var paths = scenes.Select(s => Str(s, "path")).Where(File.Exists).ToList();
85
142
  EditorBuildSettings.scenes = paths.Select(p => new EditorBuildSettingsScene(p, true))
86
143
  .Concat(EditorBuildSettings.scenes.Where(s => !paths.Contains(s.path))).ToArray();
144
+ Try(Skill, "the unity-game skill");
87
145
 
88
146
  File.Delete(PendingPath);
147
+ // A model given its root just now: the prefabs placing it re-import after this pass, losing their
148
+ // overrides on the old root. Once they have, a second pass builds the text into them again.
149
+ if (rerooted) File.WriteAllText(PendingPath, "models re-rooted");
89
150
  AssetDatabase.SaveAssets();
90
151
  AssetDatabase.Refresh();
91
152
  foreach (var w in warnings) Debug.LogWarning($"SceNoCo: {w}");
92
- Debug.Log($"SceNoCo: imported {prefabs.Count} prefabs, {scenes.Count} scenes, {List(data["meshes"]).Count} meshes, {List(data["materials"]).Count} materials"
153
+ Debug.Log($"SceNoCo: imported {twins.Count(t => t.EndsWith(".uprefab"))} prefabs, {scenes.Count} scenes, {List(data["meshes"]).Count} meshes, {List(data["materials"]).Count} materials"
93
154
  + (warnings.Count > 0 ? $" — {warnings.Count} warnings above." : "."));
94
155
  }
95
156
 
157
+ /// <summary>
158
+ /// Every model glTFast imports gets a root of its own, as three.js's loader gives it a scene: by
159
+ /// default glTFast makes a lone node the root, and a placement's Transform then replaces that
160
+ /// node's own (a quantized model's decoding scale) where three keeps both.
161
+ /// </summary>
162
+ static bool ModelRoots()
163
+ {
164
+ var changed = false;
165
+ if (!AssetDatabase.IsValidFolder("Assets/Models")) return false;
166
+ foreach (var guid in AssetDatabase.FindAssets("", new[] { "Assets/Models" }))
167
+ {
168
+ var path = AssetDatabase.GUIDToAssetPath(guid);
169
+ if (!path.EndsWith(".glb") && !path.EndsWith(".gltf")) continue;
170
+ var importer = AssetImporter.GetAtPath(path);
171
+ if (importer == null) continue;
172
+ var settings = new SerializedObject(importer);
173
+ // glTFast's SceneObjectCreation: Never 0, Always 1, WhenMultipleRootNodes 2.
174
+ var creation = settings.FindProperty("instantiationSettings.sceneObjectCreation");
175
+ if (creation == null || creation.intValue == 1) continue;
176
+ creation.intValue = 1;
177
+ settings.ApplyModifiedPropertiesWithoutUndo();
178
+ importer.SaveAndReimport();
179
+ changed = true;
180
+ }
181
+ return changed;
182
+ }
183
+
184
+ /// <summary>
185
+ /// An image a behaviour reads as data — a height stamp, a map — imported pixel for pixel, as the
186
+ /// browser decodes it: readable, uncompressed, no mipmaps, and never resized to a power of two.
187
+ /// </summary>
188
+ static void DataTexture(string path)
189
+ {
190
+ if (!(AssetImporter.GetAtPath(path) is TextureImporter importer)) return;
191
+ if (importer.isReadable && importer.npotScale == TextureImporterNPOTScale.None && !importer.mipmapEnabled
192
+ && importer.textureCompression == TextureImporterCompression.Uncompressed) return;
193
+ importer.isReadable = true;
194
+ importer.npotScale = TextureImporterNPOTScale.None;
195
+ importer.mipmapEnabled = false;
196
+ importer.textureCompression = TextureImporterCompression.Uncompressed;
197
+ importer.SaveAndReimport();
198
+ }
199
+
200
+ /// <summary>
201
+ /// A model whose every copy draws otherwise than Unity's defaults — <c>sharedModel(url, { castShadow: false })</c> —
202
+ /// as a prefab variant of its file with its renderers set. Placements and fields name the variant.
203
+ /// </summary>
204
+ static void ModelVariant(Dictionary<string, object> v)
205
+ {
206
+ var path = Str(v, "path");
207
+ var model = AssetDatabase.LoadAssetAtPath<GameObject>(Str(v, "model"));
208
+ if (model == null)
209
+ {
210
+ warnings.Add($"{path}: its model {Str(v, "model")} did not import — placements of it are empty.");
211
+ return;
212
+ }
213
+ var copy = (GameObject)PrefabUtility.InstantiatePrefab(model);
214
+ try
215
+ {
216
+ foreach (var r in copy.GetComponentsInChildren<Renderer>(true))
217
+ {
218
+ r.shadowCastingMode = (bool)v["castShadow"] ? ShadowCastingMode.On : ShadowCastingMode.Off;
219
+ r.receiveShadows = (bool)v["receiveShadow"];
220
+ }
221
+ // Over an existing variant, in place: its GUID, and so every reference to it, stays.
222
+ PrefabUtility.SaveAsPrefabAsset(copy, path);
223
+ }
224
+ finally { Object.DestroyImmediate(copy); }
225
+ }
226
+
227
+ // A file's text with its line endings made one: a checkout may have changed them, not the port.
228
+ static string Text(string path) => File.ReadAllText(path).Replace("\r\n", "\n");
229
+
96
230
  static void Try(Action action, string what)
97
231
  {
98
232
  try { action(); }
@@ -127,6 +261,11 @@ namespace SceNoCo
127
261
  var f = Floats(u);
128
262
  mesh.uv = Enumerable.Range(0, f.Length / 2).Select(i => new Vector2(f[i * 2], f[i * 2 + 1])).ToArray();
129
263
  }
264
+ if (m.TryGetValue("colors", out var c))
265
+ {
266
+ var f = Floats(c);
267
+ mesh.colors = Enumerable.Range(0, f.Length / 4).Select(i => new Color(f[i * 4], f[i * 4 + 1], f[i * 4 + 2], f[i * 4 + 3])).ToArray();
268
+ }
130
269
  var subs = List(m["submeshes"]);
131
270
  mesh.subMeshCount = subs.Count;
132
271
  for (var i = 0; i < subs.Count; i++) mesh.SetTriangles(Floats(subs[i]).Select(x => (int)x).ToArray(), i);
@@ -139,7 +278,11 @@ namespace SceNoCo
139
278
  static void MakeMaterial(Dictionary<string, object> m)
140
279
  {
141
280
  var lit = Str(m, "shader") == "lit";
142
- var shader = Shader.Find(lit ? "Universal Render Pipeline/Lit" : "Universal Render Pipeline/Unlit")
281
+ // Vertex colours: URP's Particles shaders multiply by them (Color Mode Multiply), lit or not; Lit and Unlit ignore them.
282
+ var colours = m.TryGetValue("vertexColors", out var vc) && (bool)vc;
283
+ var shader = Shader.Find(colours
284
+ ? (lit ? "Universal Render Pipeline/Particles/Lit" : "Universal Render Pipeline/Particles/Unlit")
285
+ : (lit ? "Universal Render Pipeline/Lit" : "Universal Render Pipeline/Unlit"))
143
286
  ?? Shader.Find(lit ? "Standard" : "Unlit/Color");
144
287
  var path = Str(m, "path");
145
288
  var mat = AssetDatabase.LoadAssetAtPath<Material>(path);
@@ -223,76 +366,153 @@ namespace SceNoCo
223
366
  AssetDatabase.CreateFolder(parent, Path.GetFileName(path));
224
367
  }
225
368
 
226
- // --- prefabs and scenes ------------------------------------------------------------------
227
369
 
228
- static void SavePrefab(Dictionary<string, object> p)
370
+ /// <summary>A terrain's heights and colour layers, in place: the layers live inside the data's asset, each with a one-pixel texture of its colour.</summary>
371
+ static void MakeTerrain(Dictionary<string, object> t)
229
372
  {
230
- var path = Str(p, "path");
231
- Folder(Path.GetDirectoryName(path));
232
- var go = Build(Obj(p["root"]), null);
233
- PrefabUtility.SaveAsPrefabAsset(go, path);
234
- Object.DestroyImmediate(go);
373
+ var path = Str(t, "path");
374
+ var data = AssetDatabase.LoadAssetAtPath<TerrainData>(path);
375
+ var created = data == null;
376
+ if (created) data = new TerrainData();
377
+ var n = (int)Num(t, "heightmapResolution", 33);
378
+ data.heightmapResolution = n;
379
+ data.size = V3(t["size"]);
380
+ var flat = Floats(t["heights"]);
381
+ var heights = new float[n, n];
382
+ for (var y = 0; y < n; y++) for (var x = 0; x < n; x++) heights[y, x] = flat[y * n + x];
383
+ data.SetHeights(0, 0, heights);
384
+ if (created) SaveAsset(data, path);
385
+ // Only what an earlier import added: Unity keeps the splat maps in this asset too, and
386
+ // SetAlphamaps fails ("splatdatabase alphamap 0 is null") once they are gone.
387
+ foreach (var old in AssetDatabase.LoadAllAssetRepresentationsAtPath(path))
388
+ if (old is TerrainLayer || (old is Texture2D added && added.name.EndsWith(" colour"))) Object.DestroyImmediate(old, true);
389
+ var layers = List(t["layers"]).Select(Obj).Select(spec =>
390
+ {
391
+ // The layer's own texture, copied in by the export; else its colour, as a one-pixel texture.
392
+ var texture = spec.ContainsKey("texture") ? AssetDatabase.LoadAssetAtPath<Texture2D>(Str(spec, "texture")) : null;
393
+ if (texture == null)
394
+ {
395
+ if (spec.ContainsKey("texture")) warnings.Add($"{path}: layer texture {Str(spec, "texture")} did not import — the layer is its colour.");
396
+ texture = new Texture2D(1, 1) { name = Str(spec, "name") + " colour" };
397
+ texture.SetPixel(0, 0, Hex(Str(spec, "color")));
398
+ texture.Apply();
399
+ AssetDatabase.AddObjectToAsset(texture, data);
400
+ }
401
+ var tile = Num(spec, "tileSize", 10);
402
+ var layer = new TerrainLayer { name = Str(spec, "name"), diffuseTexture = texture, tileSize = new Vector2(tile, tile) };
403
+ if (spec.ContainsKey("normalMap")) layer.normalMapTexture = NormalMap(Str(spec, "normalMap"));
404
+ AssetDatabase.AddObjectToAsset(layer, data);
405
+ return layer;
406
+ }).ToArray();
407
+ data.terrainLayers = layers;
408
+ if (layers.Length > 0)
409
+ {
410
+ var a = (int)Num(t, "alphamapResolution", 16);
411
+ data.alphamapResolution = a;
412
+ var w = Floats(t["alphamaps"]);
413
+ var maps = new float[a, a, layers.Length];
414
+ for (var y = 0; y < a; y++) for (var x = 0; x < a; x++) for (var l = 0; l < layers.Length; l++) maps[y, x, l] = w[(y * a + x) * layers.Length + l];
415
+ data.SetAlphamaps(0, 0, maps);
416
+ }
417
+ EditorUtility.SetDirty(data);
235
418
  }
236
419
 
237
- static void WirePrefab(Dictionary<string, object> p)
420
+ /// <summary>A texture imported as a normal map: Unity reads one only when its importer says so.</summary>
421
+ static Texture2D NormalMap(string path)
238
422
  {
239
- var path = Str(p, "path");
240
- var root = PrefabUtility.LoadPrefabContents(path);
241
- try
423
+ if (AssetImporter.GetAtPath(path) is TextureImporter importer && importer.textureType != TextureImporterType.NormalMap)
242
424
  {
243
- Wire(Obj(p["root"]), root, root);
244
- PrefabUtility.SaveAsPrefabAsset(root, path);
425
+ importer.textureType = TextureImporterType.NormalMap;
426
+ importer.SaveAndReimport();
245
427
  }
246
- finally { PrefabUtility.UnloadPrefabContents(root); }
428
+ var texture = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
429
+ if (texture == null) warnings.Add($"{path}: the normal map did not import.");
430
+ return texture;
247
431
  }
248
432
 
249
- /// <summary>The scene to open once the import is done: "" for the first exported one.</summary>
250
- static string reopen;
433
+ /// <summary>URP's terrain material, one for the project: a terrain with none draws pink there.</summary>
434
+ static void TerrainMaterial(string path)
435
+ {
436
+ if (AssetDatabase.LoadAssetAtPath<Material>(path) != null) return;
437
+ var shader = Shader.Find("Universal Render Pipeline/Terrain/Lit") ?? Shader.Find("Nature/Terrain/Standard");
438
+ SaveAsset(new Material(shader), path);
439
+ }
440
+
441
+ /// <summary>A collider's friction and bounciness: one PhysicsMaterial (or 2D) per pair.</summary>
442
+ static void PhysicsMaterial(Dictionary<string, object> m)
443
+ {
444
+ var path = Str(m, "path");
445
+ float friction = Num(m, "friction", 0.5f), bounce = Num(m, "bounciness", 0);
446
+ if (Num(m, "dimensions", 3) == 2)
447
+ {
448
+ var two = AssetDatabase.LoadAssetAtPath<PhysicsMaterial2D>(path);
449
+ if (two == null) SaveAsset(two = new PhysicsMaterial2D(), path);
450
+ two.friction = friction;
451
+ two.bounciness = bounce;
452
+ EditorUtility.SetDirty(two);
453
+ return;
454
+ }
455
+ var three = AssetDatabase.LoadAssetAtPath<PhysicsMaterial>(path);
456
+ if (three == null) SaveAsset(three = new PhysicsMaterial(), path);
457
+ three.dynamicFriction = three.staticFriction = friction;
458
+ three.bounciness = bounce;
459
+ EditorUtility.SetDirty(three);
460
+ }
461
+
462
+ /// <summary>One particle material per blending, shared by every system: URP's particle shader, Unity's soft round sprite.</summary>
463
+ static void ParticleMaterial(string blending)
464
+ {
465
+ var path = $"Assets/Materials/Particles-{blending}.mat";
466
+ if (AssetDatabase.LoadAssetAtPath<Material>(path) != null) return;
467
+ var shader = Shader.Find("Universal Render Pipeline/Particles/Unlit") ?? Shader.Find("Particles/Standard Unlit");
468
+ var mat = new Material(shader);
469
+ mat.SetTexture("_BaseMap", AssetDatabase.GetBuiltinExtraResource<Texture2D>("Default-Particle.psd"));
470
+ mat.SetFloat("_Surface", 1);
471
+ mat.SetFloat("_Blend", blending == "Additive" ? 2 : 0);
472
+ mat.SetFloat("_SrcBlend", (float)BlendMode.SrcAlpha);
473
+ mat.SetFloat("_DstBlend", (float)(blending == "Additive" ? BlendMode.One : BlendMode.OneMinusSrcAlpha));
474
+ mat.SetFloat("_ZWrite", 0);
475
+ mat.SetOverrideTag("RenderType", "Transparent");
476
+ mat.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
477
+ mat.renderQueue = (int)RenderQueue.Transparent;
478
+ SaveAsset(mat, path);
479
+ }
251
480
 
252
- static void SaveScene(Dictionary<string, object> s, bool first)
481
+ /// <summary>Panel Settings for a UIDocument's element, scaling as core's UIDocument does.</summary>
482
+ static void MakePanel(Dictionary<string, object> p, string theme)
483
+ {
484
+ var path = Str(p, "path");
485
+ var panel = AssetDatabase.LoadAssetAtPath<PanelSettings>(path);
486
+ if (panel == null) SaveAsset(panel = ScriptableObject.CreateInstance<PanelSettings>(), path);
487
+ if (theme != null) panel.themeStyleSheet = AssetDatabase.LoadAssetAtPath<ThemeStyleSheet>(theme);
488
+ panel.scaleMode = PanelScaleMode.ScaleWithScreenSize;
489
+ panel.screenMatchMode = PanelScreenMatchMode.MatchWidthOrHeight;
490
+ var size = Floats(p["referenceResolution"]);
491
+ panel.referenceResolution = new Vector2Int(Mathf.RoundToInt(size[0]), Mathf.RoundToInt(size[1]));
492
+ panel.match = Num(p, "match", 0.5f);
493
+ panel.sortingOrder = Num(p, "sortingOrder", 0);
494
+ EditorUtility.SetDirty(panel);
495
+ }
496
+
497
+ // --- scenes: what their text has no place for ------------------------------------------------
498
+
499
+ /// <summary>
500
+ /// A scene's fog, ambient light and reflections, which a scene keeps outside its objects: set on the scene
501
+ /// Scenoco built, opened beside whatever is open, saved and closed again.
502
+ /// </summary>
503
+ static void Lighting(Dictionary<string, object> s)
253
504
  {
254
505
  var path = Str(s, "path");
255
- Folder(Path.GetDirectoryName(path));
256
- // A scene of its own, beside whatever is open: nothing the user has open is touched. Unity
257
- // cannot add one beside an untitled scene, nor save over an open one, so an untouched untitled
258
- // scene or this very scene open is replaced instead, and opened again at the end.
259
- var open = SceneManager.GetSceneByPath(path);
260
- if (open.IsValid() && open.isDirty) throw new Exception("it is open with unsaved changes — save or discard them, then import again");
261
- var beside = open.IsValid() && SceneManager.sceneCount > 1;
262
- if (beside) EditorSceneManager.CloseScene(open, true);
263
- var previous = SceneManager.GetActiveScene();
264
- var untitled = SceneManager.sceneCount == 1 && string.IsNullOrEmpty(previous.path);
265
- if (untitled && previous.isDirty) throw new Exception("the open scene is untitled and has unsaved changes — save or discard it, then import again");
266
- var single = untitled || previous.path == path;
267
- var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, single ? NewSceneMode.Single : NewSceneMode.Additive);
268
- if (single) { reopen ??= untitled ? "" : path; previous = default; }
506
+ if (!File.Exists(path)) return; // Scenoco's status says why
507
+ var scene = SceneManager.GetSceneByPath(path);
508
+ var open = scene.IsValid() && scene.isLoaded;
509
+ if (open && scene.isDirty) throw new Exception("its lighting was not set: it is open with unsaved changes — save or discard them, then import again");
510
+ if (!open) scene = EditorSceneManager.OpenScene(path, OpenSceneMode.Additive);
511
+ var active = SceneManager.GetActiveScene();
269
512
  SceneManager.SetActiveScene(scene);
270
513
  try
271
514
  {
272
- var roots = List(s["roots"]).Select(Obj).ToList();
273
- var built = roots.Select(r => Build(r, null)).ToList();
274
- // References between a scene's roots go through a holder that lists them as its children.
275
- var holder = new GameObject("__scenoco");
276
- foreach (var go in built) go.transform.SetParent(holder.transform, false);
277
- for (var i = 0; i < roots.Count; i++) Wire(roots[i], built[i], holder);
278
- foreach (var go in built) go.transform.SetParent(null, false);
279
- Object.DestroyImmediate(holder);
280
- if (first) MakeInput();
281
-
282
515
  RenderSettings.skybox = null;
283
- Color background = Color.black;
284
- var hasBackground = s.TryGetValue("background", out var bg);
285
- if (hasBackground) background = Hex((string)bg);
286
- var cameras = built.SelectMany(go => go.GetComponentsInChildren<Camera>(true)).ToList();
287
- foreach (var cam in cameras)
288
- {
289
- cam.clearFlags = hasBackground ? CameraClearFlags.SolidColor : cam.clearFlags;
290
- cam.backgroundColor = background;
291
- Volumes.Enable(cam);
292
- }
293
- if (cameras.Count > 0) cameras[0].gameObject.tag = "MainCamera";
294
- else warnings.Add($"{path}: no camera in the scene.");
295
-
296
516
  if (s.TryGetValue("fog", out var f))
297
517
  {
298
518
  var fog = Obj(f);
@@ -329,100 +549,58 @@ namespace SceNoCo
329
549
  // three lights a surface with no environment by nothing but its lights: no skybox reflections either.
330
550
  RenderSettings.defaultReflectionMode = DefaultReflectionMode.Custom;
331
551
  RenderSettings.customReflectionTexture = null;
332
- RenderSettings.reflectionIntensity = s.ContainsKey("environment") ? 1 : 0;
333
- EditorSceneManager.SaveScene(scene, path);
552
+ RenderSettings.reflectionIntensity = 0;
553
+ EditorSceneManager.SaveScene(scene);
334
554
  }
335
555
  finally
336
556
  {
337
- if (previous.IsValid())
338
- {
339
- SceneManager.SetActiveScene(previous);
340
- EditorSceneManager.CloseScene(scene, true);
341
- if (beside) EditorSceneManager.OpenScene(path, OpenSceneMode.Additive);
342
- }
557
+ if (active.IsValid() && active != scene) SceneManager.SetActiveScene(active);
558
+ if (!open && SceneManager.sceneCount > 1) EditorSceneManager.CloseScene(scene, true);
343
559
  }
344
560
  }
345
561
 
346
- /** A node and everything under it, with its components added and not yet set. */
347
- static GameObject Build(Dictionary<string, object> n, Transform parent)
562
+ /// <summary>Diceload's skill, for the agent porting the game: copied into the project's .claude/skills once.</summary>
563
+ static void Skill()
348
564
  {
349
- GameObject go;
350
- if (n.TryGetValue("prefab", out var prefab))
351
- {
352
- var asset = AssetDatabase.LoadAssetAtPath<GameObject>((string)prefab);
353
- if (asset == null) throw new Exception($"nested prefab {prefab} is missing");
354
- go = (GameObject)PrefabUtility.InstantiatePrefab(asset);
355
- }
356
- else go = new GameObject();
357
- go.name = Str(n, "name");
358
- go.transform.SetParent(parent, false);
359
- go.transform.localPosition = V3(n["position"]);
360
- var r = Floats(n["rotation"]);
361
- go.transform.localRotation = new Quaternion(r[0], r[1], r[2], r[3]);
362
- go.transform.localScale = V3(n["scale"]);
363
- if (n.TryGetValue("layer", out var layer)) go.layer = Convert.ToInt32(layer, CultureInfo.InvariantCulture);
364
-
365
- if (n.TryGetValue("mesh", out var mesh))
366
- {
367
- go.AddComponent<MeshFilter>().sharedMesh = AssetDatabase.LoadAssetAtPath<Mesh>((string)mesh);
368
- var renderer = go.AddComponent<MeshRenderer>();
369
- var mats = n.TryGetValue("materials", out var ms) ? List(ms).Select(x => AssetDatabase.LoadAssetAtPath<Material>((string)x)).ToArray() : new Material[0];
370
- renderer.sharedMaterials = mats;
371
- renderer.shadowCastingMode = n.TryGetValue("castShadows", out var cs) && (bool)cs ? ShadowCastingMode.On : ShadowCastingMode.Off;
372
- renderer.receiveShadows = n.TryGetValue("receiveShadows", out var rs) && (bool)rs;
373
- }
374
- if (n.TryGetValue("light", out var l)) MakeLight(go, Obj(l));
375
- if (n.TryGetValue("camera", out var c)) MakeCamera(go, Obj(c));
376
-
377
- foreach (var comp in List(n["components"]).Select(Obj))
378
- {
379
- var type = Str(comp, "type");
380
- if ((bool)comp["game"])
381
- {
382
- var t = GameType(type);
383
- if (t == null) warnings.Add($"{Where(comp, n)}: no MonoBehaviour named {type} — it has a stub in Assets/Scripts unless a class of that name exists elsewhere.");
384
- else go.AddComponent(t);
385
- }
386
- else if (type == "ParticleSystem") Particles.Add(go, Obj(comp["fields"]), w => warnings.Add($"{Where(comp, n)}: {w}"));
387
- else if (type == "UIDocument") MakeDocument(go, Obj(comp["fields"]), Where(comp, n));
388
- else if (Volumes.Add(go, type, Obj(comp["fields"]))) { }
389
- else if (Terrains.Add(go, type, Obj(comp["fields"]), w => warnings.Add($"{Where(comp, n)}: {w}"))) { }
390
- else if (!Physics.Add(go, type, Obj(comp["fields"]))) warnings.Add($"{Where(comp, n)}: {type} has no Unity counterpart here — left off.");
391
- }
392
-
393
- foreach (var child in List(n["children"]).Select(Obj)) Build(child, go.transform);
394
- if (n.TryGetValue("renderersEnabled", out var re) && !(bool)re)
395
- foreach (var rr in go.GetComponentsInChildren<Renderer>(true)) rr.enabled = false;
396
- if (n.TryGetValue("active", out var act) && !(bool)act) go.SetActive(false);
397
- return go;
565
+ const string to = ".claude/skills/unity-game";
566
+ if (Directory.Exists(to)) return;
567
+ var package = UnityEditor.PackageManager.PackageInfo.FindForPackageName("com.roro.diceload");
568
+ var from = package == null ? null : Path.Combine(package.resolvedPath, "Skills~/unity-game");
569
+ if (from == null || !Directory.Exists(from)) throw new Exception("com.roro.diceload is not in the project — add it to Packages/manifest.json");
570
+ Directory.CreateDirectory(to);
571
+ foreach (var file in Directory.GetFiles(from)) File.Copy(file, Path.Combine(to, Path.GetFileName(file)));
398
572
  }
399
573
 
400
- /// <summary>
401
- /// A game's post effects as a URP Volume and its profile, one per node that has them. By type name and
402
- /// serialized field, as the project's settings are, so a project without URP still compiles this.
403
- /// </summary>
574
+ /// <summary>A game's post effects as a URP Volume profile. By type name and serialized field, so a project without URP still compiles this.</summary>
404
575
  static class Volumes
405
576
  {
406
577
  const string Rendering = "UnityEngine.Rendering.{0}, Unity.RenderPipelines.Core.Runtime";
407
578
  const string Universal = "UnityEngine.Rendering.Universal.{0}, Unity.RenderPipelines.Universal.Runtime";
408
- static readonly Dictionary<GameObject, ScriptableObject> Profiles = new Dictionary<GameObject, ScriptableObject>();
409
- static readonly HashSet<string> Written = new HashSet<string>();
410
- static readonly string[] Effects = { "Bloom", "Tonemapping", "ColorAdjustments", "Vignette", "DepthOfField", "ChromaticAberration", "FilmGrain" };
411
579
 
412
- public static bool Add(GameObject go, string type, Dictionary<string, object> f)
580
+ public static void Make(Dictionary<string, object> v)
413
581
  {
414
- if (type == "Volume")
582
+ var path = Str(v, "path");
583
+ var profileType = Type.GetType(string.Format(Rendering, "VolumeProfile")) ?? throw new Exception("URP is not in this project");
584
+ // Made anew each time: its effects are objects of their own in the profile's file.
585
+ var existing = AssetDatabase.LoadMainAssetAtPath(path);
586
+ ScriptableObject profile;
587
+ if (existing != null && existing.GetType() == profileType)
415
588
  {
416
- Profile(go);
417
- var volume = new SerializedObject(go.GetComponent(Type.GetType(string.Format(Rendering, "Volume"))));
418
- volume.FindProperty("priority").floatValue = Num(f, "priority", 0);
419
- volume.ApplyModifiedPropertiesWithoutUndo();
420
- return true;
589
+ profile = (ScriptableObject)existing;
590
+ foreach (var old in AssetDatabase.LoadAllAssetRepresentationsAtPath(path)) Object.DestroyImmediate(old, true);
591
+ var list = new SerializedObject(profile);
592
+ list.FindProperty("components").ClearArray();
593
+ list.ApplyModifiedPropertiesWithoutUndo();
421
594
  }
422
- if (!Effects.Contains(type)) return false;
595
+ else SaveAsset(profile = ScriptableObject.CreateInstance(profileType), path);
596
+ foreach (var e in List(v["effects"]).Select(Obj)) Effect(profile, Str(e, "type"), Obj(e["fields"]));
597
+ EditorUtility.SetDirty(profile);
598
+ }
599
+
600
+ static void Effect(ScriptableObject profile, string type, Dictionary<string, object> f)
601
+ {
423
602
  var effect = Type.GetType(string.Format(Universal, type));
424
- if (effect == null) return false;
425
- var profile = Profile(go);
603
+ if (effect == null) { warnings.Add($"{type}: not a URP effect here — left out of the Volume."); return; }
426
604
  var added = (ScriptableObject)profile.GetType().GetMethod("Add", new[] { typeof(Type), typeof(bool) }).Invoke(profile, new object[] { effect, false });
427
605
  var o = new SerializedObject(added);
428
606
  void Float(string name, float value) => Set(o, name, p => p.floatValue = value);
@@ -470,39 +648,6 @@ namespace SceNoCo
470
648
  // Each is an object of its own in the profile's file, and its list is lost at save unless marked.
471
649
  AssetDatabase.AddObjectToAsset(added, profile);
472
650
  EditorUtility.SetDirty(added);
473
- EditorUtility.SetDirty(profile);
474
- return true;
475
- }
476
-
477
- /// <summary>Post Processing on for a camera, in a game with a Volume in any scene: one kept across loads shapes every level's camera.</summary>
478
- public static void Enable(Camera camera)
479
- {
480
- if (Profiles.Count == 0 && !File.ReadAllText(DataPath).Contains("\"Volume\"")) return;
481
- var data = Type.GetType(string.Format(Universal, "UniversalAdditionalCameraData"));
482
- if (data == null) return;
483
- var extra = camera.GetComponent(data) ?? camera.gameObject.AddComponent(data);
484
- var o = new SerializedObject(extra);
485
- o.FindProperty("m_RenderPostProcessing").boolValue = true;
486
- o.ApplyModifiedPropertiesWithoutUndo();
487
- }
488
-
489
- static ScriptableObject Profile(GameObject go)
490
- {
491
- if (Profiles.TryGetValue(go, out var made)) return made;
492
- var profileType = Type.GetType(string.Format(Rendering, "VolumeProfile"));
493
- var path = $"Assets/Materials/Volume-{go.name}.asset";
494
- for (var i = 2; !Written.Add(path); i++) path = $"Assets/Materials/Volume-{go.name}-{i}.asset";
495
- Directory.CreateDirectory("Assets/Materials");
496
- AssetDatabase.DeleteAsset(path);
497
- var profile = ScriptableObject.CreateInstance(profileType);
498
- AssetDatabase.CreateAsset(profile, path);
499
- var volume = go.GetComponent(Type.GetType(string.Format(Rendering, "Volume"))) ?? go.AddComponent(Type.GetType(string.Format(Rendering, "Volume")));
500
- var o = new SerializedObject(volume);
501
- o.FindProperty("sharedProfile").objectReferenceValue = profile;
502
- o.FindProperty("m_IsGlobal").boolValue = true;
503
- o.ApplyModifiedPropertiesWithoutUndo();
504
- Profiles[go] = profile;
505
- return profile;
506
651
  }
507
652
 
508
653
  static void Set(SerializedObject o, string name, Action<SerializedProperty> value)
@@ -513,188 +658,6 @@ namespace SceNoCo
513
658
  }
514
659
  }
515
660
 
516
- /** Set the fields of a node's game components, walking the data and the built objects together. */
517
- static void Wire(Dictionary<string, object> n, GameObject go, GameObject root)
518
- {
519
- var games = List(n["components"]).Select(Obj).Where(c => (bool)c["game"]).ToList();
520
- foreach (var comp in games)
521
- {
522
- var t = GameType(Str(comp, "type"));
523
- var behaviour = t == null ? null : go.GetComponent(t);
524
- if (behaviour == null) continue;
525
- var so = new SerializedObject(behaviour);
526
- foreach (var field in Obj(comp["fields"]))
527
- {
528
- var prop = so.FindProperty(field.Key);
529
- if (prop == null)
530
- {
531
- warnings.Add($"{Where(comp, n)}: {t.Name} has no serialized field {field.Key} — add a public one to wire it.");
532
- continue;
533
- }
534
- try { Set(prop, field.Value, root); }
535
- catch (Exception e) { warnings.Add($"{Where(comp, n)}: {t.Name}.{field.Key}: {e.Message}"); }
536
- }
537
- so.ApplyModifiedPropertiesWithoutUndo();
538
- }
539
- Physics.WireJoints(n, go, root, warnings.Add);
540
- if (n.ContainsKey("prefab")) return; // a nested prefab is wired in its own asset
541
- var children = List(n["children"]).Select(Obj).ToList();
542
- for (var i = 0; i < children.Count && i < go.transform.childCount; i++) Wire(children[i], go.transform.GetChild(i).gameObject, root);
543
- }
544
-
545
- static void Set(SerializedProperty p, object v, GameObject root)
546
- {
547
- if (p.isArray && p.propertyType != SerializedPropertyType.String)
548
- {
549
- var items = v is Dictionary<string, object> d && d.TryGetValue("array", out var a) ? List(a) : new List<object>();
550
- p.arraySize = items.Count;
551
- for (var i = 0; i < items.Count; i++) Set(p.GetArrayElementAtIndex(i), items[i], root);
552
- return;
553
- }
554
- var o = v as Dictionary<string, object>;
555
- switch (p.propertyType)
556
- {
557
- case SerializedPropertyType.Float: p.floatValue = Convert.ToSingle(v, CultureInfo.InvariantCulture); return;
558
- case SerializedPropertyType.Integer: p.intValue = (int)Math.Round(Convert.ToDouble(v, CultureInfo.InvariantCulture)); return;
559
- case SerializedPropertyType.Boolean: p.boolValue = (bool)v; return;
560
- case SerializedPropertyType.String: p.stringValue = Convert.ToString(v, CultureInfo.InvariantCulture); return;
561
- case SerializedPropertyType.Enum:
562
- if (v is string name)
563
- {
564
- var plain = new Func<string, string>(x => x.Replace("_", "").Replace("-", "").ToLowerInvariant());
565
- var index = Array.FindIndex(p.enumNames, e => plain(e) == plain(name));
566
- if (index < 0) throw new Exception($"'{name}' is none of {string.Join(", ", p.enumNames)}");
567
- p.enumValueIndex = index;
568
- }
569
- else p.enumValueIndex = (int)Convert.ToDouble(v, CultureInfo.InvariantCulture);
570
- return;
571
- case SerializedPropertyType.Vector2: { var f = Floats(o["v2"]); p.vector2Value = new Vector2(f[0], f[1]); return; }
572
- case SerializedPropertyType.Vector3: p.vector3Value = V3(o["v3"]); return;
573
- case SerializedPropertyType.Vector4: { var f = Floats(o["v4"]); p.vector4Value = new Vector4(f[0], f[1], f[2], f[3]); return; }
574
- case SerializedPropertyType.Quaternion: { var f = Floats(o["quat"]); p.quaternionValue = new Quaternion(f[0], f[1], f[2], f[3]); return; }
575
- case SerializedPropertyType.Color: p.colorValue = Hex(Str(o, "color")); return;
576
- case SerializedPropertyType.ObjectReference: p.objectReferenceValue = Reference(p, o, root); return;
577
- }
578
- throw new Exception($"a {p.propertyType} field is not set by the importer");
579
- }
580
-
581
- static Object Reference(SerializedProperty p, Dictionary<string, object> o, GameObject root)
582
- {
583
- if (o == null) return null;
584
- // "PPtr<$Transform>": what the field holds.
585
- var wanted = p.type.StartsWith("PPtr<$") ? p.type.Substring(6, p.type.Length - 7) : p.type;
586
- GameObject go = null;
587
- if (o.TryGetValue("asset", out var asset))
588
- {
589
- var loaded = AssetDatabase.LoadMainAssetAtPath((string)asset);
590
- if (!(loaded is GameObject prefab)) return loaded;
591
- go = prefab;
592
- }
593
- else if (o.TryGetValue("node", out var node)) go = Find(root, (string)node);
594
- if (go == null) throw new Exception("its target was not found");
595
- if (wanted == "GameObject") return go;
596
- if (wanted == "Transform") return go.transform;
597
- var component = o.TryGetValue("component", out var c) ? (string)c : wanted;
598
- var t = GameType(component) ?? GameType(wanted);
599
- return t != null ? go.GetComponent(t) : go.GetComponent(wanted);
600
- }
601
-
602
- // --- the page and input ------------------------------------------------------------------
603
-
604
- /// <summary>A UIDocument for the page's element: its UXML, and Panel Settings that scale as core's UIDocument does.</summary>
605
- static void MakeDocument(GameObject go, Dictionary<string, object> f, string where)
606
- {
607
- var element = f.TryGetValue("element", out var e) ? (string)e : "ui";
608
- var documents = ui != null && ui.TryGetValue("documents", out var d) ? Obj(d) : new Dictionary<string, object>();
609
- if (!documents.TryGetValue(element, out var uxml))
610
- {
611
- warnings.Add($"{where}: no UXML for the element \"{element}\" — the page has no element with that id.");
612
- return;
613
- }
614
- var path = $"Assets/UI/{element}.panel.asset";
615
- var panel = AssetDatabase.LoadAssetAtPath<PanelSettings>(path);
616
- if (panel == null)
617
- {
618
- panel = ScriptableObject.CreateInstance<PanelSettings>();
619
- SaveAsset(panel, path);
620
- }
621
- panel.themeStyleSheet = AssetDatabase.LoadAssetAtPath<ThemeStyleSheet>(Str(ui, "theme"));
622
- panel.scaleMode = PanelScaleMode.ScaleWithScreenSize;
623
- panel.screenMatchMode = PanelScreenMatchMode.MatchWidthOrHeight;
624
- var size = f.TryGetValue("referenceResolution", out var r) ? Floats(Obj(r)["v2"]) : new[] { 1280f, 720f };
625
- panel.referenceResolution = new Vector2Int(Mathf.RoundToInt(size[0]), Mathf.RoundToInt(size[1]));
626
- panel.match = Num(f, "match", 0.5f);
627
- // In the page's order: an element written later draws over an earlier one.
628
- panel.sortingOrder = documents.Keys.ToList().IndexOf(element);
629
- EditorUtility.SetDirty(panel);
630
- var doc = go.AddComponent<UIDocument>();
631
- doc.panelSettings = panel;
632
- doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>((string)uxml);
633
- }
634
-
635
- /// <summary>The first scene's Input object: the UI's EventSystem and its Input System module, kept for the whole game.</summary>
636
- static void MakeInput()
637
- {
638
- var go = new GameObject("Input");
639
- foreach (var name in new[] { "UnityEngine.EventSystems.EventSystem, UnityEngine.UI", "UnityEngine.InputSystem.UI.InputSystemUIInputModule, Unity.InputSystem", "SceNoCo.KeepAcrossScenes, Assembly-CSharp" })
640
- {
641
- var t = Type.GetType(name);
642
- if (t != null) go.AddComponent(t);
643
- else warnings.Add($"Input: {name.Split(',')[0]} is not in this project — add the Input System and UI packages.");
644
- }
645
- }
646
-
647
- static GameObject Find(GameObject root, string path)
648
- {
649
- var t = root.transform;
650
- if (path.Length == 0) return root;
651
- foreach (var step in path.Split('/'))
652
- {
653
- var i = int.Parse(step, CultureInfo.InvariantCulture);
654
- if (i >= t.childCount) return null;
655
- t = t.GetChild(i);
656
- }
657
- return t.gameObject;
658
- }
659
-
660
- static void MakeLight(GameObject go, Dictionary<string, object> l)
661
- {
662
- var light = go.AddComponent<Light>();
663
- var type = Str(l, "type");
664
- light.type = type == "Directional" ? LightType.Directional : type == "Spot" ? LightType.Spot : LightType.Point;
665
- light.color = Hex(Str(l, "color"));
666
- light.intensity = Num(l, "intensity", 1);
667
- light.shadows = l.TryGetValue("shadows", out var s) && (bool)s ? LightShadows.Soft : LightShadows.None;
668
- if (l.ContainsKey("range")) light.range = Num(l, "range", 10);
669
- if (l.ContainsKey("spotAngle")) light.spotAngle = Num(l, "spotAngle", 30);
670
- if (l.ContainsKey("innerSpotAngle")) light.innerSpotAngle = Num(l, "innerSpotAngle", 21);
671
- }
672
-
673
- static void MakeCamera(GameObject go, Dictionary<string, object> c)
674
- {
675
- var cam = go.AddComponent<Camera>();
676
- cam.orthographic = (bool)c["orthographic"];
677
- cam.nearClipPlane = Num(c, "near", 0.1f);
678
- cam.farClipPlane = Num(c, "far", 1000);
679
- if (cam.orthographic) cam.orthographicSize = Num(c, "size", 5);
680
- else cam.fieldOfView = Num(c, "fov", 60);
681
- }
682
-
683
- static readonly Dictionary<string, Type> types = new Dictionary<string, Type>();
684
- static Type GameType(string name)
685
- {
686
- if (types.TryGetValue(name, out var known)) return known;
687
- var found = TypeCache.GetTypesDerivedFrom<MonoBehaviour>()
688
- .FirstOrDefault(t => t.Name == name && !t.Assembly.FullName.StartsWith("Unity"));
689
- types[name] = found;
690
- return found;
691
- }
692
-
693
- static string Where(Dictionary<string, object> comp, Dictionary<string, object> node) =>
694
- comp.TryGetValue("source", out var s) ? (string)s : node.TryGetValue("source", out var ns) ? (string)ns : Str(node, "name");
695
-
696
- // --- physics: SceNoCo's rapier and box2d components are Unity's own --------------------
697
-
698
661
  /// <summary>The project's own settings: what a three.js game draws and reads like, in Unity 6.</summary>
699
662
  static class Project
700
663
  {
@@ -783,518 +746,6 @@ namespace SceNoCo
783
746
  }
784
747
  }
785
748
 
786
- /// <summary>
787
- /// A SceNoCo ParticleSystem's effect — Shuriken's modules under Shuriken's names — as Unity's own
788
- /// ParticleSystem. three.quarks emits along +Z like Unity; the mirror on Z turns a cone or a hemisphere round.
789
- /// </summary>
790
- static class Particles
791
- {
792
- public static void Add(GameObject go, Dictionary<string, object> f, Action<string> warn)
793
- {
794
- if (!f.TryGetValue("effect", out var e) || !(e is Dictionary<string, object> eo) || !eo.ContainsKey("object"))
795
- {
796
- warn("ParticleSystem has no effect it could read — left off.");
797
- return;
798
- }
799
- var c = Fields(eo);
800
- var ps = go.AddComponent<ParticleSystem>();
801
- ps.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
802
- var main = ps.main;
803
- main.duration = Num(c, "duration", 5);
804
- main.loop = Bool(c, "looping", true);
805
- main.prewarm = Bool(c, "prewarm", false);
806
- main.startLifetime = Num(c, "startLifetime", 5);
807
- main.startSpeed = Num(c, "startSpeed", 5);
808
- main.startSize = Num(c, "startSize", 1);
809
- main.startRotation = Num(c, "startRotation", 0) * Mathf.Deg2Rad;
810
- main.startColor = ColorOf(c, "startColor", Color.white);
811
- main.gravityModifier = Num(c, "gravityModifier", 0);
812
- main.simulationSpace = Str(c, "simulationSpace") == "World" ? ParticleSystemSimulationSpace.World : ParticleSystemSimulationSpace.Local;
813
- main.playOnAwake = !f.TryGetValue("playOnAwake", out var awake) || (bool)awake;
814
- main.scalingMode = ParticleSystemScalingMode.Hierarchy;
815
-
816
- var emission = ps.emission;
817
- var em = Sub(c, "emission");
818
- emission.rateOverTime = Num(em, "rateOverTime", 10);
819
- if (em.TryGetValue("bursts", out var bursts))
820
- emission.SetBursts(List(Obj(bursts)["array"]).Select(b => Fields(Obj(b))).Select(b => new ParticleSystem.Burst(Num(b, "time", 0), (short)Num(b, "count", 0))).ToArray());
821
-
822
- var shape = ps.shape;
823
- var sh = Sub(c, "shape");
824
- var type = sh.ContainsKey("type") ? Str(sh, "type") : "Cone";
825
- shape.radius = Num(sh, "radius", 1);
826
- shape.angle = Num(sh, "angle", 25);
827
- shape.arc = Num(sh, "arc", 360);
828
- switch (type)
829
- {
830
- case "Sphere": shape.shapeType = ParticleSystemShapeType.Sphere; break;
831
- case "Hemisphere": shape.shapeType = ParticleSystemShapeType.Hemisphere; shape.rotation = new Vector3(0, 180, 0); break;
832
- case "Circle": shape.shapeType = ParticleSystemShapeType.Circle; break;
833
- case "Donut": shape.shapeType = ParticleSystemShapeType.Donut; break;
834
- case "Rectangle": shape.shapeType = ParticleSystemShapeType.Rectangle; shape.scale = new Vector3(shape.radius * 2, shape.radius * 2, 1); break;
835
- case "Point": shape.shapeType = ParticleSystemShapeType.Sphere; shape.radius = 0.0001f; break;
836
- default: shape.shapeType = ParticleSystemShapeType.Cone; shape.rotation = new Vector3(0, 180, 0); break;
837
- }
838
-
839
- if (c.TryGetValue("noise", out _))
840
- {
841
- var n = Sub(c, "noise");
842
- var noise = ps.noise;
843
- noise.enabled = true;
844
- noise.strength = Num(n, "strength", 1);
845
- noise.frequency = Num(n, "frequency", 2);
846
- }
847
- if (c.TryGetValue("colorOverLifetime", out _))
848
- {
849
- var colors = List(Obj(Sub(c, "colorOverLifetime")["colors"])["array"]).Select(x => Hex(Str(Obj(x), "color"))).ToArray();
850
- if (colors.Length > 0)
851
- {
852
- // Evenly spaced, as the effect writes them; full alpha, fading out over the last third, as three.quarks does.
853
- var keys = colors.Select((col, i) => new GradientColorKey(col, colors.Length == 1 ? 0 : i / (float)(colors.Length - 1))).Take(8).ToArray();
854
- var gradient = new Gradient();
855
- gradient.SetKeys(keys, new[] { new GradientAlphaKey(1, 0), new GradientAlphaKey(1, 0.7f), new GradientAlphaKey(0, 1) });
856
- var col = ps.colorOverLifetime;
857
- col.enabled = true;
858
- col.color = gradient;
859
- }
860
- }
861
- if (c.TryGetValue("sizeOverLifetime", out _))
862
- {
863
- var values = Floats(Obj(Sub(c, "sizeOverLifetime")["curve"])["array"]);
864
- if (values.Length > 0)
865
- {
866
- var curve = new AnimationCurve(values.Select((v, i) => new Keyframe(values.Length == 1 ? 0 : i / (float)(values.Length - 1), v)).ToArray());
867
- for (var i = 0; i < curve.length; i++) AnimationUtility.SetKeyLeftTangentMode(curve, i, AnimationUtility.TangentMode.Linear);
868
- for (var i = 0; i < curve.length; i++) AnimationUtility.SetKeyRightTangentMode(curve, i, AnimationUtility.TangentMode.Linear);
869
- var size = ps.sizeOverLifetime;
870
- size.enabled = true;
871
- size.size = new ParticleSystem.MinMaxCurve(1, curve);
872
- }
873
- }
874
- if (c.TryGetValue("rotationOverLifetime", out _))
875
- {
876
- var rot = ps.rotationOverLifetime;
877
- rot.enabled = true;
878
- rot.z = Num(Sub(c, "rotationOverLifetime"), "angularVelocity", 0) * Mathf.Deg2Rad;
879
- }
880
-
881
- var r = Sub(c, "renderer");
882
- var renderer = go.GetComponent<ParticleSystemRenderer>();
883
- renderer.renderMode = Str(r, "renderMode") switch
884
- {
885
- "StretchedBillboard" => ParticleSystemRenderMode.Stretch,
886
- "HorizontalBillboard" => ParticleSystemRenderMode.HorizontalBillboard,
887
- "VerticalBillboard" => ParticleSystemRenderMode.VerticalBillboard,
888
- "Mesh" => ParticleSystemRenderMode.Mesh,
889
- _ => ParticleSystemRenderMode.Billboard,
890
- };
891
- renderer.sharedMaterial = SharedMaterial(Str(r, "blending") == "Alpha" ? "Alpha" : "Additive");
892
- }
893
-
894
- /// <summary>One material per blending, shared by every system: URP's particle shader, Unity's soft round sprite.</summary>
895
- static Material SharedMaterial(string blending)
896
- {
897
- var path = $"Assets/Materials/Particles-{blending}.mat";
898
- var mat = AssetDatabase.LoadAssetAtPath<Material>(path);
899
- if (mat != null) return mat;
900
- var shader = Shader.Find("Universal Render Pipeline/Particles/Unlit") ?? Shader.Find("Particles/Standard Unlit");
901
- mat = new Material(shader);
902
- mat.SetTexture("_BaseMap", AssetDatabase.GetBuiltinExtraResource<Texture2D>("Default-Particle.psd"));
903
- mat.SetFloat("_Surface", 1);
904
- mat.SetFloat("_Blend", blending == "Additive" ? 2 : 0);
905
- mat.SetFloat("_SrcBlend", (float)BlendMode.SrcAlpha);
906
- mat.SetFloat("_DstBlend", (float)(blending == "Additive" ? BlendMode.One : BlendMode.OneMinusSrcAlpha));
907
- mat.SetFloat("_ZWrite", 0);
908
- mat.SetOverrideTag("RenderType", "Transparent");
909
- mat.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
910
- mat.renderQueue = (int)RenderQueue.Transparent;
911
- SaveAsset(mat, path);
912
- return mat;
913
- }
914
-
915
- static Dictionary<string, object> Fields(Dictionary<string, object> o) => Obj(Obj(o["object"])["fields"]);
916
- static Dictionary<string, object> Sub(Dictionary<string, object> c, string key) =>
917
- c.TryGetValue(key, out var v) && v is Dictionary<string, object> d && d.ContainsKey("object") ? Fields(d) : new Dictionary<string, object>();
918
- static bool Bool(Dictionary<string, object> d, string key, bool fallback) => d.TryGetValue(key, out var v) && v is bool b ? b : fallback;
919
- static Color ColorOf(Dictionary<string, object> d, string key, Color fallback) =>
920
- d.TryGetValue(key, out var v) && v is Dictionary<string, object> o && o.TryGetValue("color", out var hex) ? Hex((string)hex) : fallback;
921
- }
922
-
923
- /// <summary>
924
- /// A game's terrain as Unity's own: a TerrainData asset holding its heights (0..1 of size.y, as the
925
- /// exporter wrote them) and a layer per colour, and the Terrain and TerrainCollider on a child at the
926
- /// data's corner — Unity's terrain starts at its object, SceNoCo's is centred on its node.
927
- /// </summary>
928
- static class Terrains
929
- {
930
- public static readonly Dictionary<string, Vector3> Offsets = new Dictionary<string, Vector3>();
931
-
932
- public static void Make(Dictionary<string, object> t)
933
- {
934
- var path = Str(t, "path");
935
- var data = AssetDatabase.LoadAssetAtPath<TerrainData>(path);
936
- var created = data == null;
937
- if (created) data = new TerrainData();
938
- var n = (int)Num(t, "heightmapResolution", 33);
939
- data.heightmapResolution = n;
940
- data.size = V3(t["size"]);
941
- var flat = Floats(t["heights"]);
942
- var heights = new float[n, n];
943
- for (var y = 0; y < n; y++) for (var x = 0; x < n; x++) heights[y, x] = flat[y * n + x];
944
- data.SetHeights(0, 0, heights);
945
- if (created) SaveAsset(data, path);
946
- // The layers live inside the data's asset, each with a one-pixel texture of its colour.
947
- foreach (var old in AssetDatabase.LoadAllAssetRepresentationsAtPath(path)) Object.DestroyImmediate(old, true);
948
- var specs = List(t["layers"]).Select(Obj).ToList();
949
- var layers = specs.Select(spec =>
950
- {
951
- var texture = new Texture2D(1, 1) { name = Str(spec, "name") + " colour" };
952
- texture.SetPixel(0, 0, Hex(Str(spec, "color")));
953
- texture.Apply();
954
- AssetDatabase.AddObjectToAsset(texture, data);
955
- var tile = Num(spec, "tileSize", 10);
956
- var layer = new TerrainLayer { name = Str(spec, "name"), diffuseTexture = texture, tileSize = new Vector2(tile, tile) };
957
- AssetDatabase.AddObjectToAsset(layer, data);
958
- return layer;
959
- }).ToArray();
960
- data.terrainLayers = layers;
961
- if (layers.Length > 0)
962
- {
963
- var a = (int)Num(t, "alphamapResolution", 16);
964
- data.alphamapResolution = a;
965
- var w = Floats(t["alphamaps"]);
966
- var maps = new float[a, a, layers.Length];
967
- for (var y = 0; y < a; y++) for (var x = 0; x < a; x++) for (var l = 0; l < layers.Length; l++) maps[y, x, l] = w[(y * a + x) * layers.Length + l];
968
- data.SetAlphamaps(0, 0, maps);
969
- }
970
- EditorUtility.SetDirty(data);
971
- Offsets[path] = V3(t["offset"]);
972
- }
973
-
974
- public static bool Add(GameObject go, string type, Dictionary<string, object> f, Action<string> warn)
975
- {
976
- if (type != "Terrain" && type != "TerrainCollider") return false;
977
- var path = f.TryGetValue("terrainData", out var v) && v is Dictionary<string, object> d && d.TryGetValue("asset", out var p) ? (string)p : null;
978
- var data = path != null ? AssetDatabase.LoadAssetAtPath<TerrainData>(path) : null;
979
- if (data == null)
980
- {
981
- warn($"{type} has no exported terrainData — left off.");
982
- return true;
983
- }
984
- var child = go.transform.Find("Terrain")?.gameObject;
985
- if (child == null)
986
- {
987
- child = new GameObject("Terrain");
988
- child.transform.SetParent(go.transform, false);
989
- child.transform.localPosition = Offsets.TryGetValue(path, out var at) ? at : Vector3.zero;
990
- if ((go.transform.lossyScale - Vector3.one).sqrMagnitude > 1e-6f) warn("a Unity terrain ignores its object's scale — size the TerrainData instead.");
991
- }
992
- if (type == "Terrain")
993
- {
994
- var terrain = child.AddComponent<Terrain>();
995
- terrain.terrainData = data;
996
- terrain.heightmapPixelError = Num(f, "heightmapPixelError", 5);
997
- terrain.shadowCastingMode = Bool(f, "castShadows", true) ? ShadowCastingMode.On : ShadowCastingMode.Off;
998
- var lit = Shader.Find("Universal Render Pipeline/Terrain/Lit");
999
- if (lit != null) terrain.materialTemplate = TerrainMaterial(lit);
1000
- }
1001
- else child.AddComponent<TerrainCollider>().terrainData = data;
1002
- return true;
1003
- }
1004
-
1005
- /** URP's terrain material, one for the project: a terrain with none draws pink there. */
1006
- static Material TerrainMaterial(Shader lit)
1007
- {
1008
- const string path = "Assets/Terrains/TerrainLit.mat";
1009
- var mat = AssetDatabase.LoadAssetAtPath<Material>(path);
1010
- if (mat == null) SaveAsset(mat = new Material(lit), path);
1011
- return mat;
1012
- }
1013
- }
1014
-
1015
- static class Physics
1016
- {
1017
- public static bool Add(GameObject go, string type, Dictionary<string, object> f)
1018
- {
1019
- switch (type)
1020
- {
1021
- case "Rigidbody":
1022
- {
1023
- var rb = go.AddComponent<Rigidbody>();
1024
- rb.isKinematic = Bool(f, "isKinematic", false);
1025
- rb.useGravity = Bool(f, "useGravity", true);
1026
- rb.linearDamping = Num(f, "linearDamping", 0);
1027
- rb.angularDamping = Num(f, "angularDamping", 0.05f);
1028
- rb.freezeRotation = Bool(f, "freezeRotation", false);
1029
- return true;
1030
- }
1031
- case "BoxCollider":
1032
- {
1033
- var c = go.AddComponent<BoxCollider>();
1034
- if (f.ContainsKey("size")) { var s = V3(Obj(f["size"])["v3"]); c.size = new Vector3(Mathf.Abs(s.x), Mathf.Abs(s.y), Mathf.Abs(s.z)); }
1035
- if (f.ContainsKey("center")) c.center = V3(Obj(f["center"])["v3"]);
1036
- SetCollider3D(c, f);
1037
- return true;
1038
- }
1039
- case "SphereCollider":
1040
- {
1041
- var c = go.AddComponent<SphereCollider>();
1042
- c.radius = Num(f, "radius", 0.5f);
1043
- if (f.ContainsKey("center")) c.center = V3(Obj(f["center"])["v3"]);
1044
- SetCollider3D(c, f);
1045
- return true;
1046
- }
1047
- case "CapsuleCollider":
1048
- {
1049
- var c = go.AddComponent<CapsuleCollider>();
1050
- c.radius = Num(f, "radius", 0.5f);
1051
- c.height = Num(f, "height", 2);
1052
- if (f.ContainsKey("center")) c.center = V3(Obj(f["center"])["v3"]);
1053
- SetCollider3D(c, f);
1054
- return true;
1055
- }
1056
- case "Rigidbody2D":
1057
- {
1058
- // SceNoCo's enums carry Unity's own values.
1059
- var rb = go.AddComponent<Rigidbody2D>();
1060
- rb.bodyType = (RigidbodyType2D)(int)Num(f, "bodyType", 0);
1061
- rb.useAutoMass = Bool(f, "useAutoMass", false);
1062
- if (!rb.useAutoMass) rb.mass = Num(f, "mass", 1);
1063
- rb.gravityScale = Num(f, "gravityScale", 1);
1064
- rb.linearDamping = Num(f, "linearDamping", 0);
1065
- rb.angularDamping = Num(f, "angularDamping", 0.05f);
1066
- rb.constraints = (RigidbodyConstraints2D)(int)Num(f, "constraints", 0);
1067
- if (Bool(f, "freezeRotation", false)) rb.freezeRotation = true;
1068
- rb.collisionDetectionMode = (CollisionDetectionMode2D)(int)Num(f, "collisionDetectionMode", 0);
1069
- return true;
1070
- }
1071
- case "BoxCollider2D":
1072
- {
1073
- var c = go.AddComponent<BoxCollider2D>();
1074
- if (f.ContainsKey("size")) c.size = V2(f["size"]);
1075
- SetCollider2D(c, f);
1076
- return true;
1077
- }
1078
- case "CircleCollider2D":
1079
- {
1080
- var c = go.AddComponent<CircleCollider2D>();
1081
- c.radius = Num(f, "radius", 0.5f);
1082
- SetCollider2D(c, f);
1083
- return true;
1084
- }
1085
- case "CapsuleCollider2D":
1086
- {
1087
- var c = go.AddComponent<CapsuleCollider2D>();
1088
- if (f.ContainsKey("size")) c.size = V2(f["size"]);
1089
- c.direction = (CapsuleDirection2D)(int)Num(f, "direction", 0);
1090
- SetCollider2D(c, f);
1091
- return true;
1092
- }
1093
- case "PolygonCollider2D":
1094
- {
1095
- var c = go.AddComponent<PolygonCollider2D>();
1096
- if (f.ContainsKey("points")) c.SetPath(0, Points(f["points"]));
1097
- SetCollider2D(c, f);
1098
- return true;
1099
- }
1100
- case "EdgeCollider2D":
1101
- {
1102
- var c = go.AddComponent<EdgeCollider2D>();
1103
- if (f.ContainsKey("points")) c.points = Points(f["points"]);
1104
- SetCollider2D(c, f);
1105
- return true;
1106
- }
1107
- // Joints: `connectedBody` is another node's, set by `WireJoints` once every node is built.
1108
- case "FixedJoint2D":
1109
- {
1110
- var j = go.AddComponent<FixedJoint2D>();
1111
- SetAnchored(j, f, true);
1112
- j.frequency = Num(f, "frequency", 0);
1113
- j.dampingRatio = Num(f, "dampingRatio", 0);
1114
- return true;
1115
- }
1116
- case "HingeJoint2D":
1117
- {
1118
- var j = go.AddComponent<HingeJoint2D>();
1119
- SetAnchored(j, f, true);
1120
- j.useLimits = Bool(f, "useLimits", false);
1121
- if (f.ContainsKey("limits")) { var l = Fields(f["limits"]); j.limits = new JointAngleLimits2D { min = Num(l, "min", 0), max = Num(l, "max", 359) }; }
1122
- j.useMotor = Bool(f, "useMotor", false);
1123
- if (f.ContainsKey("motor")) j.motor = Motor(f["motor"]);
1124
- return true;
1125
- }
1126
- case "DistanceJoint2D":
1127
- {
1128
- var j = go.AddComponent<DistanceJoint2D>();
1129
- SetAnchored(j, f, false);
1130
- j.autoConfigureDistance = Bool(f, "autoConfigureDistance", true);
1131
- if (f.ContainsKey("distance")) j.distance = Num(f, "distance", 1);
1132
- j.maxDistanceOnly = Bool(f, "maxDistanceOnly", false);
1133
- return true;
1134
- }
1135
- case "SpringJoint2D":
1136
- {
1137
- var j = go.AddComponent<SpringJoint2D>();
1138
- SetAnchored(j, f, false);
1139
- j.autoConfigureDistance = Bool(f, "autoConfigureDistance", true);
1140
- if (f.ContainsKey("distance")) j.distance = Num(f, "distance", 1);
1141
- j.dampingRatio = Num(f, "dampingRatio", 0);
1142
- j.frequency = Num(f, "frequency", 1);
1143
- return true;
1144
- }
1145
- case "SliderJoint2D":
1146
- {
1147
- var j = go.AddComponent<SliderJoint2D>();
1148
- SetAnchored(j, f, true);
1149
- j.autoConfigureAngle = Bool(f, "autoConfigureAngle", false);
1150
- j.angle = Num(f, "angle", 0);
1151
- j.useLimits = Bool(f, "useLimits", false);
1152
- if (f.ContainsKey("limits")) { var l = Fields(f["limits"]); j.limits = new JointTranslationLimits2D { min = Num(l, "min", 0), max = Num(l, "max", 0) }; }
1153
- j.useMotor = Bool(f, "useMotor", false);
1154
- if (f.ContainsKey("motor")) j.motor = Motor(f["motor"]);
1155
- return true;
1156
- }
1157
- case "WheelJoint2D":
1158
- {
1159
- var j = go.AddComponent<WheelJoint2D>();
1160
- SetAnchored(j, f, true);
1161
- if (f.ContainsKey("suspension"))
1162
- {
1163
- var s = Fields(f["suspension"]);
1164
- j.suspension = new JointSuspension2D { dampingRatio = Num(s, "dampingRatio", 0.7f), frequency = Num(s, "frequency", 2), angle = Num(s, "angle", 90) };
1165
- }
1166
- j.useMotor = Bool(f, "useMotor", false);
1167
- if (f.ContainsKey("motor")) j.motor = Motor(f["motor"]);
1168
- return true;
1169
- }
1170
- case "FrictionJoint2D":
1171
- {
1172
- var j = go.AddComponent<FrictionJoint2D>();
1173
- SetAnchored(j, f, true);
1174
- j.maxForce = Num(f, "maxForce", 1);
1175
- j.maxTorque = Num(f, "maxTorque", 1);
1176
- return true;
1177
- }
1178
- case "RelativeJoint2D":
1179
- {
1180
- var j = go.AddComponent<RelativeJoint2D>();
1181
- SetJoint(j, f);
1182
- j.maxForce = Num(f, "maxForce", 10000);
1183
- j.maxTorque = Num(f, "maxTorque", 10000);
1184
- j.correctionScale = Num(f, "correctionScale", 0.3f);
1185
- j.autoConfigureOffset = Bool(f, "autoConfigureOffset", true);
1186
- if (f.ContainsKey("linearOffset")) j.linearOffset = V2(f["linearOffset"]);
1187
- if (f.ContainsKey("angularOffset")) j.angularOffset = Num(f, "angularOffset", 0);
1188
- return true;
1189
- }
1190
- case "TargetJoint2D":
1191
- {
1192
- var j = go.AddComponent<TargetJoint2D>();
1193
- SetJoint(j, f);
1194
- if (f.ContainsKey("anchor")) j.anchor = V2(f["anchor"]);
1195
- j.autoConfigureTarget = Bool(f, "autoConfigureTarget", true);
1196
- if (f.ContainsKey("target")) j.target = V2(f["target"]);
1197
- j.maxForce = Num(f, "maxForce", 1000);
1198
- j.dampingRatio = Num(f, "dampingRatio", 1);
1199
- j.frequency = Num(f, "frequency", 5);
1200
- return true;
1201
- }
1202
- }
1203
- return false;
1204
- }
1205
-
1206
- static void SetJoint(Joint2D j, Dictionary<string, object> f)
1207
- {
1208
- j.enableCollision = Bool(f, "enableCollision", false);
1209
- if (f.ContainsKey("breakForce")) j.breakForce = Num(f, "breakForce", float.PositiveInfinity);
1210
- if (f.ContainsKey("breakTorque")) j.breakTorque = Num(f, "breakTorque", float.PositiveInfinity);
1211
- }
1212
-
1213
- /** `autoConfigureConnectedAnchor` before `connectedAnchor`: Unity overwrites the anchor while it is on. */
1214
- static void SetAnchored(AnchoredJoint2D j, Dictionary<string, object> f, bool autoByDefault)
1215
- {
1216
- SetJoint(j, f);
1217
- if (f.ContainsKey("anchor")) j.anchor = V2(f["anchor"]);
1218
- j.autoConfigureConnectedAnchor = Bool(f, "autoConfigureConnectedAnchor", autoByDefault);
1219
- if (f.ContainsKey("connectedAnchor")) j.connectedAnchor = V2(f["connectedAnchor"]);
1220
- }
1221
-
1222
- /** A settings object's fields: `{ object: { fields } }`. */
1223
- static Dictionary<string, object> Fields(object v) => Obj(Obj(Obj(v)["object"])["fields"]);
1224
-
1225
- static JointMotor2D Motor(object v)
1226
- {
1227
- var m = Fields(v);
1228
- return new JointMotor2D { motorSpeed = Num(m, "motorSpeed", 0), maxMotorTorque = Num(m, "maxMotorTorque", 10000) };
1229
- }
1230
-
1231
- /** Each joint's `connectedBody`: the Rigidbody2D on the node it names, joints matched by type in order. */
1232
- public static void WireJoints(Dictionary<string, object> n, GameObject go, GameObject root, Action<string> warn)
1233
- {
1234
- var seen = new Dictionary<string, int>();
1235
- foreach (var comp in List(n["components"]).Select(Obj).Where(c => !(bool)c["game"]))
1236
- {
1237
- var type = Str(comp, "type");
1238
- var t = typeof(Joint2D).Assembly.GetType("UnityEngine." + type);
1239
- if (t == null || !typeof(Joint2D).IsAssignableFrom(t)) continue;
1240
- seen[type] = seen.TryGetValue(type, out var i) ? i + 1 : 0;
1241
- if (!Obj(comp["fields"]).TryGetValue("connectedBody", out var link) || !(link is Dictionary<string, object> l) || !l.TryGetValue("node", out var path)) continue;
1242
- var joint = (Joint2D)go.GetComponents(t)[seen[type]];
1243
- var target = Find(root, (string)path);
1244
- joint.connectedBody = target != null ? target.GetComponent<Rigidbody2D>() : null;
1245
- if (joint.connectedBody == null) warn($"{type} on {go.name}: its connectedBody was not found");
1246
- }
1247
- }
1248
-
1249
- static void SetCollider3D(Collider c, Dictionary<string, object> f)
1250
- {
1251
- c.isTrigger = Bool(f, "isTrigger", false);
1252
- if (!f.ContainsKey("friction") && !f.ContainsKey("bounciness")) return;
1253
- var friction = Num(f, "friction", 0.5f);
1254
- var bounce = Num(f, "bounciness", 0);
1255
- var path = $"Assets/Materials/Physics/Friction{friction:0.##}_Bounce{bounce:0.##}.asset".Replace(',', '.');
1256
- var m = AssetDatabase.LoadAssetAtPath<PhysicsMaterial>(path);
1257
- if (m == null)
1258
- {
1259
- m = new PhysicsMaterial { dynamicFriction = friction, staticFriction = friction, bounciness = bounce };
1260
- Folder(Path.GetDirectoryName(path));
1261
- AssetDatabase.CreateAsset(m, path);
1262
- }
1263
- c.sharedMaterial = m;
1264
- }
1265
-
1266
- static void SetCollider2D(Collider2D c, Dictionary<string, object> f)
1267
- {
1268
- c.isTrigger = Bool(f, "isTrigger", false);
1269
- if (f.ContainsKey("offset")) c.offset = V2(f["offset"]);
1270
- if (f.ContainsKey("density")) c.density = Num(f, "density", 1);
1271
- // A shared PhysicsMaterial2D, or the collider's own friction and bounciness: one asset per pair.
1272
- var surface = f.TryGetValue("material", out var mv) && mv is Dictionary<string, object> mo && mo.TryGetValue("object", out var ov)
1273
- ? Obj(Obj(ov)["fields"])
1274
- : f;
1275
- if (!surface.ContainsKey("friction") && !surface.ContainsKey("bounciness")) return;
1276
- var friction = Num(surface, "friction", 0.4f);
1277
- var bounce = Num(surface, "bounciness", 0);
1278
- var path = $"Assets/Materials/Physics/Friction{friction:0.##}_Bounce{bounce:0.##}_2D.asset".Replace(',', '.');
1279
- var m = AssetDatabase.LoadAssetAtPath<PhysicsMaterial2D>(path);
1280
- if (m == null)
1281
- {
1282
- m = new PhysicsMaterial2D { friction = friction, bounciness = bounce };
1283
- Folder(Path.GetDirectoryName(path));
1284
- AssetDatabase.CreateAsset(m, path);
1285
- }
1286
- c.sharedMaterial = m;
1287
- }
1288
-
1289
- static Vector2 V2(object v)
1290
- {
1291
- var p = Floats(Obj(v)["v2"]);
1292
- return new Vector2(p[0], p[1]);
1293
- }
1294
-
1295
- static Vector2[] Points(object v) =>
1296
- List(Obj(v)["array"]).Select(p => Floats(Obj(p)["v2"])).Select(p => new Vector2(p[0], p[1])).ToArray();
1297
- }
1298
749
 
1299
750
  // --- data ----------------------------------------------------------------------------------
1300
751