@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.
- package/dist/cli.js +8 -5
- package/dist/convert.d.ts +41 -0
- package/dist/convert.js +326 -38
- package/dist/export.d.ts +22 -3
- package/dist/export.js +243 -33
- package/dist/page.d.ts +2 -0
- package/dist/page.js +30 -12
- package/dist/stub.d.ts +7 -2
- package/dist/stub.js +66 -25
- package/dist/twin.d.ts +52 -0
- package/dist/twin.js +1076 -0
- package/package.json +2 -2
- package/unity/KeepAcrossScenes.cs +9 -2
- package/unity/PORTING.md +100 -52
- package/unity/SceNoCoImporter.cs +334 -883
- package/unity/SceNoCoValidate.cs +96 -0
- package/unity/SplineKnotNodes.cs +66 -0
- package/unity/SplineMesh.cs +255 -0
- package/unity/Driver/SceNoCo.Driver.asmdef +0 -32
- package/unity/Driver/SceNoCoDriver.cs +0 -697
package/dist/convert.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
1
2
|
import { outsideClasses, readClass, stubClass } from './stub.js';
|
|
2
3
|
/** SceNoCo's layers are 0 to 15, Unity's own 0 to 5: layer n, past 0, is Unity's user layer n + 7. */
|
|
3
4
|
export const unityLayer = (n) => (n === 0 ? 0 : n + 7);
|
|
@@ -17,12 +18,17 @@ const UNITY_NAMES = new Set(('Transform RectTransform Camera Light Animator Anim
|
|
|
17
18
|
.split(' '));
|
|
18
19
|
/** A game behaviour's C# class name. */
|
|
19
20
|
export const csName = (type) => (UNITY_NAMES.has(type) ? `${type}Behaviour` : type);
|
|
21
|
+
/** Where each kind of loaded file goes in the Unity project. */
|
|
22
|
+
const FILE_FOLDERS = { Model: 'Assets/Models', AudioClip: 'Assets/Audio', Texture2D: 'Assets/Textures' };
|
|
20
23
|
const flipV = ([x, y, z]) => [x, y, z === 0 ? 0 : -z];
|
|
21
24
|
const flipQ = ([x, y, z, w]) => [x === 0 ? 0 : -x, y === 0 ? 0 : -y, z, w];
|
|
25
|
+
/** A rate about each axis — degrees a second about x, y and z — mirrors as a rotation does: x and y turn the other way. */
|
|
26
|
+
const flipAxes = ([x, y, z]) => [x === 0 ? 0 : -x, y === 0 ? 0 : -y, z];
|
|
22
27
|
export function convert(snap, options = {}) {
|
|
23
28
|
const warnings = [...snap.warnings];
|
|
24
29
|
const paths = new Paths();
|
|
25
30
|
const copies = new Map();
|
|
31
|
+
const read = readSources(snap, options);
|
|
26
32
|
// three draws a geometry's groups only for a mesh given a list of materials; with one material it
|
|
27
33
|
// draws everything with it. A BoxGeometry has six groups, so this decides whether it is one submesh or six.
|
|
28
34
|
const multi = new Set();
|
|
@@ -42,17 +48,29 @@ export function convert(snap, options = {}) {
|
|
|
42
48
|
const materials = Object.entries(snap.materials).map(([id, m]) => {
|
|
43
49
|
const path = paths.take('Assets/Materials', m.name, '.mat');
|
|
44
50
|
materialPath.set(id, path);
|
|
45
|
-
return material(m, path, options.textures, copies, warnings);
|
|
51
|
+
return material(m, path, options.textures, copies, warnings, read.emits);
|
|
46
52
|
});
|
|
47
53
|
const terrains = [];
|
|
48
54
|
const terrainPath = new Map();
|
|
55
|
+
// The world scale of the node being converted: what a terrain on it is drawn at.
|
|
56
|
+
let worldScale = 1;
|
|
49
57
|
const terrainOf = (fields) => {
|
|
50
|
-
const key = JSON.stringify(fields)
|
|
58
|
+
const key = `${worldScale} ${JSON.stringify(fields)}`;
|
|
51
59
|
let path = terrainPath.get(key);
|
|
52
60
|
if (!path) {
|
|
53
|
-
path = paths.take('Assets/Terrains', 'Terrain', '.asset');
|
|
61
|
+
path = paths.take('Assets/Terrains', typeof fields.name === 'string' && fields.name ? fields.name : 'Terrain', '.asset');
|
|
54
62
|
terrainPath.set(key, path);
|
|
55
|
-
|
|
63
|
+
// A layer's texture files, copied in once each, under the terrain's own folder.
|
|
64
|
+
const copy = (url) => {
|
|
65
|
+
const found = options.textures?.(url);
|
|
66
|
+
if (!found)
|
|
67
|
+
return undefined;
|
|
68
|
+
// Each terrain's own folder: levels name their layers alike (every map's `grass.jpg`), and one file each.
|
|
69
|
+
const to = `Assets/Textures/Terrain/${path.replace(/^.*\/|\.asset$/g, '')}/${found.name}`;
|
|
70
|
+
copies.set(found.file, to);
|
|
71
|
+
return to;
|
|
72
|
+
};
|
|
73
|
+
const t = terrain(fields, path, copy, worldScale);
|
|
56
74
|
terrains.push(t.terrain);
|
|
57
75
|
warnings.push(...t.warnings);
|
|
58
76
|
}
|
|
@@ -66,9 +84,53 @@ export function convert(snap, options = {}) {
|
|
|
66
84
|
else
|
|
67
85
|
prefabPath.set(p.id, paths.take('Assets/Prefabs', p.name, '.prefab'));
|
|
68
86
|
}
|
|
87
|
+
/** A behaviour's field: a rate about each axis mirrors as a rotation, every other value as itself. */
|
|
88
|
+
const field = (type, name, v) => {
|
|
89
|
+
if (read.axes.has(`${type}.${name}`) && v && typeof v === 'object' && 'v3' in v)
|
|
90
|
+
return { v3: flipAxes(v.v3) };
|
|
91
|
+
// A list of [x, y, z] — a path's points written as tuples — is a list of points: Vector3[], mirrored.
|
|
92
|
+
if (v && typeof v === 'object' && 'array' in v && v.array.length && v.array.every((p) => p && typeof p === 'object' && 'array' in p && p.array.length === 3 && p.array.every((x) => typeof x === 'number')))
|
|
93
|
+
return { array: v.array.map((p) => ({ v3: flipV(p.array) })) };
|
|
94
|
+
return value(v);
|
|
95
|
+
};
|
|
96
|
+
// A file the game loads — a model, a sound — copied in once, by its URL: Unity imports it (a .glb with glTFast).
|
|
97
|
+
const filePath = new Map();
|
|
98
|
+
const modelVariants = [];
|
|
99
|
+
const dataTextures = [];
|
|
100
|
+
const fileOf = (url, type) => {
|
|
101
|
+
if (!filePath.has(url)) {
|
|
102
|
+
const found = options.textures?.(url);
|
|
103
|
+
if (!found) {
|
|
104
|
+
warnings.push(`${url}: the ${type} was not found in the project — its fields are left empty.`);
|
|
105
|
+
filePath.set(url, null);
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
const ext = found.name.slice(found.name.lastIndexOf('.'));
|
|
109
|
+
const path = paths.take(FILE_FOLDERS[type] ?? 'Assets/Files', found.name.slice(0, -ext.length), ext);
|
|
110
|
+
copies.set(found.file, path);
|
|
111
|
+
filePath.set(url, path);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
const path = filePath.get(url);
|
|
115
|
+
if (!path)
|
|
116
|
+
return null;
|
|
117
|
+
if (type === 'Texture2D' && !dataTextures.includes(path))
|
|
118
|
+
dataTextures.push(path);
|
|
119
|
+
const settings = type === 'Model' ? snap.modelSettings?.[url] : undefined;
|
|
120
|
+
if (!settings)
|
|
121
|
+
return { asset: path };
|
|
122
|
+
let variant = modelVariants.find((v) => v.model === path);
|
|
123
|
+
if (!variant) {
|
|
124
|
+
variant = { path: paths.take('Assets/Models', path.replace(/^.*\/|\.[^.]*$/g, ''), '.prefab'), model: path, ...settings };
|
|
125
|
+
modelVariants.push(variant);
|
|
126
|
+
}
|
|
127
|
+
return { asset: variant.path };
|
|
128
|
+
};
|
|
69
129
|
const value = (v) => {
|
|
70
130
|
if (v === null || typeof v !== 'object')
|
|
71
131
|
return v;
|
|
132
|
+
if ('file' in v)
|
|
133
|
+
return fileOf(v.file, v.type);
|
|
72
134
|
if ('v3' in v)
|
|
73
135
|
return { v3: flipV(v.v3) };
|
|
74
136
|
if ('quat' in v)
|
|
@@ -77,8 +139,9 @@ export function convert(snap, options = {}) {
|
|
|
77
139
|
return { array: v.array.map(value) };
|
|
78
140
|
if ('prefab' in v)
|
|
79
141
|
return sceneName.get(v.prefab) ?? (prefabPath.has(v.prefab) ? { asset: prefabPath.get(v.prefab) } : null);
|
|
142
|
+
// A game behaviour named as Unity's own is renamed; a package's component is Unity's, by its name.
|
|
80
143
|
if ('component' in v)
|
|
81
|
-
return { component: csName(v.component), node: v.node };
|
|
144
|
+
return { component: snap.classes[v.component] ? csName(v.component) : v.component, node: v.node };
|
|
82
145
|
if ('material' in v)
|
|
83
146
|
return { asset: materialPath.get(v.material) };
|
|
84
147
|
if ('geometry' in v)
|
|
@@ -89,8 +152,23 @@ export function convert(snap, options = {}) {
|
|
|
89
152
|
return { object: { type: v.object.type, fields: Object.fromEntries(Object.entries(v.object.fields).map(([k, f]) => [k, value(f)])) } };
|
|
90
153
|
return v;
|
|
91
154
|
};
|
|
155
|
+
for (const f of options.files ?? [])
|
|
156
|
+
fileOf(f.url, f.type);
|
|
92
157
|
let ambient;
|
|
93
158
|
const node = (n) => {
|
|
159
|
+
const outer = worldScale;
|
|
160
|
+
const [sx, sy, sz] = n.scale;
|
|
161
|
+
worldScale *= sx;
|
|
162
|
+
if (n.components.some((c) => c.type === 'Terrain') && (Math.abs(sx - sy) > 1e-6 || Math.abs(sx - sz) > 1e-6))
|
|
163
|
+
warnings.push(`${n.source ?? n.name}: a terrain under a scale that differs by axis — Unity sizes it by x.`);
|
|
164
|
+
try {
|
|
165
|
+
return convertNode(n);
|
|
166
|
+
}
|
|
167
|
+
finally {
|
|
168
|
+
worldScale = outer;
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
const convertNode = (n) => {
|
|
94
172
|
const out = {
|
|
95
173
|
name: n.name,
|
|
96
174
|
position: flipV(n.position),
|
|
@@ -101,13 +179,20 @@ export function convert(snap, options = {}) {
|
|
|
101
179
|
components: n.components.map((c) => {
|
|
102
180
|
const fields = {};
|
|
103
181
|
for (const [k, v] of Object.entries(c.fields))
|
|
104
|
-
fields[k] = value(v);
|
|
182
|
+
fields[k] = c.game ? field(c.type, k, v) : value(v);
|
|
183
|
+
// A template the class clones is a field Unity wires: its UXML.
|
|
184
|
+
if (c.game)
|
|
185
|
+
for (const [k, path] of read.templates.get(c.type) ?? [])
|
|
186
|
+
fields[k] ??= { asset: path };
|
|
187
|
+
if (c.game)
|
|
188
|
+
for (const [k, ref] of read.prefabs.get(c.type) ?? [])
|
|
189
|
+
fields[k] ??= value(ref);
|
|
105
190
|
const component = { type: c.game ? csName(c.type) : c.type, game: c.game, fields };
|
|
106
191
|
if (c.source)
|
|
107
192
|
component.source = c.source;
|
|
108
193
|
return component;
|
|
109
194
|
}),
|
|
110
|
-
children: n.children.map(node),
|
|
195
|
+
children: siblings(n.children.map(node)),
|
|
111
196
|
};
|
|
112
197
|
if (n.source)
|
|
113
198
|
out.source = n.source;
|
|
@@ -122,18 +207,38 @@ export function convert(snap, options = {}) {
|
|
|
122
207
|
else
|
|
123
208
|
out.active = false;
|
|
124
209
|
}
|
|
210
|
+
if (n.added)
|
|
211
|
+
out.added = true;
|
|
125
212
|
if (n.prefab) {
|
|
126
213
|
const path = prefabPath.get(n.prefab);
|
|
127
|
-
if (path)
|
|
214
|
+
if (path) {
|
|
128
215
|
out.prefab = path;
|
|
129
|
-
|
|
216
|
+
if (n.given)
|
|
217
|
+
out.given = true;
|
|
218
|
+
}
|
|
219
|
+
// Given attributes, it holds what it is built as: copied in.
|
|
220
|
+
else if (!n.given)
|
|
130
221
|
warnings.push(`${n.source ?? n.name}: nested ${n.prefab} is not a prefab of its own — left empty.`);
|
|
131
222
|
}
|
|
223
|
+
if (n.model) {
|
|
224
|
+
// A placed model is the model file, placed as a prefab is. glTFast mirrors a model in x where this
|
|
225
|
+
// export mirrors the world in z: half a turn about its own up puts it back as three draws it.
|
|
226
|
+
const file = fileOf(n.model, 'Model');
|
|
227
|
+
if (file && typeof file === 'object' && 'asset' in file) {
|
|
228
|
+
out.prefab = file.asset;
|
|
229
|
+
const found = options.textures?.(n.model);
|
|
230
|
+
if (found && /\.glb$/i.test(found.file))
|
|
231
|
+
out.meshNodes = glbMeshNodes(found.file);
|
|
232
|
+
const [x, y, z, w] = out.rotation;
|
|
233
|
+
out.rotation = [-z, w, x, -y].map((c) => (c === 0 ? 0 : c));
|
|
234
|
+
}
|
|
235
|
+
}
|
|
132
236
|
if (n.geometry)
|
|
133
237
|
out.mesh = meshPath.get(n.geometry);
|
|
134
|
-
|
|
238
|
+
// A mesh whose geometry its code builds (a river's ribbon) still has its renderer and material.
|
|
239
|
+
if (n.materials)
|
|
135
240
|
out.materials = n.materials.map((id) => materialPath.get(id));
|
|
136
|
-
if (n.geometry) {
|
|
241
|
+
if (n.geometry || n.materials) {
|
|
137
242
|
out.castShadows = n.castShadow;
|
|
138
243
|
out.receiveShadows = n.receiveShadow;
|
|
139
244
|
}
|
|
@@ -177,10 +282,11 @@ export function convert(snap, options = {}) {
|
|
|
177
282
|
}
|
|
178
283
|
ambient = undefined;
|
|
179
284
|
const root = node(p.root);
|
|
180
|
-
// The scene's own components, if any, need an object to live on: the
|
|
181
|
-
//
|
|
285
|
+
// The scene's own components, if any, need an object to live on: one that holds the whole scene, as
|
|
286
|
+
// three's Scene does — so DontDestroyOnLoad on it keeps the scene, and GetComponentInParent finds it.
|
|
287
|
+
// A reference into the scene, a path of child indices, starts one level down.
|
|
182
288
|
const roots = root.components.length
|
|
183
|
-
?
|
|
289
|
+
? nestNodes([{ ...root, name: p.name, position: [0, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1] }])
|
|
184
290
|
: root.children;
|
|
185
291
|
const scene = { path: `Assets/Scenes/${sceneName.get(p.id)}.unity`, roots };
|
|
186
292
|
if (p.background)
|
|
@@ -203,19 +309,83 @@ export function convert(snap, options = {}) {
|
|
|
203
309
|
ignore2D: given.ignore2D.map(([a, b]) => [unityLayer(a), unityLayer(b)]),
|
|
204
310
|
ignore3D: given.ignore3D.map(([a, b]) => [unityLayer(a), unityLayer(b)]),
|
|
205
311
|
};
|
|
206
|
-
return { data: { meshes, terrains, materials, prefabs, scenes, layers, warnings }, scripts: scripts(snap,
|
|
312
|
+
return { data: { meshes, terrains, materials, prefabs, scenes, layers, modelVariants, dataTextures, warnings }, scripts: scripts(snap, field, read, options, warnings), copies };
|
|
313
|
+
}
|
|
314
|
+
function readSources(snap, options) {
|
|
315
|
+
const out = { classes: new Map(), axes: new Set(), templates: new Map(), emits: false, prefabs: new Map() };
|
|
316
|
+
const prefabNames = [
|
|
317
|
+
...snap.prefabs.filter((p) => !p.scene).map((p) => [p.name, { prefab: p.id }]),
|
|
318
|
+
// A model's prefab is the model file, as Unity's model prefab is.
|
|
319
|
+
...Object.entries(snap.models ?? {}).map(([id, url]) => [id.split('#')[1], { file: url, type: 'Model' }]),
|
|
320
|
+
];
|
|
321
|
+
const templates = options.templates ?? {};
|
|
322
|
+
for (const [type, info] of Object.entries(snap.classes)) {
|
|
323
|
+
const code = options.source?.(info.file);
|
|
324
|
+
if (!code)
|
|
325
|
+
continue;
|
|
326
|
+
if (/\.emissive(Intensity)?\b/.test(code))
|
|
327
|
+
out.emits = true;
|
|
328
|
+
const cls = readClass(code, info.file, type);
|
|
329
|
+
if (!cls)
|
|
330
|
+
continue;
|
|
331
|
+
out.classes.set(type, cls);
|
|
332
|
+
const fields = new Set(cls.members.filter((m) => m.kind === 'field').map((m) => m.name));
|
|
333
|
+
for (const m of cls.members) {
|
|
334
|
+
for (const line of m.body ?? []) {
|
|
335
|
+
// `rotation.x += this.speed.x * k`: the field is a rate about the axes.
|
|
336
|
+
const set = /(?:\.rotation|\.eulerAngles|\.rotate\w*\()(?:[.\w]*\s*[-+*/]?=)?(.*)$/.exec(line);
|
|
337
|
+
if (set)
|
|
338
|
+
for (const [, name] of set[1].matchAll(/this\.(\w+)/g))
|
|
339
|
+
if (fields.has(name))
|
|
340
|
+
out.axes.add(`${type}.${name}`);
|
|
341
|
+
// `this.chip = element('chip')`, where `chip` is a template's id.
|
|
342
|
+
const clone = /this\.(\w+)\s*=\s*[^;]*?\(\s*['"`]#?([\w-]+)['"`]/.exec(line);
|
|
343
|
+
if (clone && fields.has(clone[1]) && templates[clone[2]]) {
|
|
344
|
+
const own = out.templates.get(type) ?? new Map();
|
|
345
|
+
own.set(clone[1], templates[clone[2]]);
|
|
346
|
+
out.templates.set(type, own);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
// A template named anywhere else in the class — `clone('who')` through a helper — is a field of its
|
|
351
|
+
// own: the id's name, or `<id>Template` where the class has a member called that already.
|
|
352
|
+
const own = out.templates.get(type) ?? new Map();
|
|
353
|
+
const taken = new Set(cls.members.map((m) => m.name));
|
|
354
|
+
const wired = new Set(own.values());
|
|
355
|
+
const text = cls.members.map((m) => m.text).join('\n');
|
|
356
|
+
for (const [id, path] of Object.entries(templates)) {
|
|
357
|
+
if (wired.has(path) || !new RegExp(`['"\`]#?${id}['"\`]`).test(text))
|
|
358
|
+
continue;
|
|
359
|
+
const name = id.replace(/-(\w)/g, (_, c) => c.toUpperCase());
|
|
360
|
+
own.set(taken.has(name) ? `${name}Template` : name, path);
|
|
361
|
+
}
|
|
362
|
+
if (own.size)
|
|
363
|
+
out.templates.set(type, own);
|
|
364
|
+
// A prefab the class names in its code — it imports and instantiates it — is a field Unity wires: the
|
|
365
|
+
// prefab's name in camelCase (`Goblin` → `goblin`), or `<name>Prefab` where that name is a member already.
|
|
366
|
+
const spawns = new Map();
|
|
367
|
+
const written = new Set(Object.keys(info.defaults ?? {}));
|
|
368
|
+
for (const [name, ref] of prefabNames) {
|
|
369
|
+
if (!new RegExp(`\\b${name}\\b`).test(text))
|
|
370
|
+
continue;
|
|
371
|
+
const camel = name.charAt(0).toLowerCase() + name.slice(1);
|
|
372
|
+
const field = taken.has(camel) || written.has(camel) ? `${camel}Prefab` : camel;
|
|
373
|
+
spawns.set(field, ref);
|
|
374
|
+
}
|
|
375
|
+
if (spawns.size)
|
|
376
|
+
out.prefabs.set(type, spawns);
|
|
377
|
+
}
|
|
378
|
+
return out;
|
|
207
379
|
}
|
|
208
|
-
/** Every node reference in `roots` one root
|
|
209
|
-
function
|
|
380
|
+
/** Every node reference in `roots` under the one root that now holds them; the scene itself (`''`) is that root. */
|
|
381
|
+
function nestNodes(roots) {
|
|
210
382
|
const shift = (v) => {
|
|
211
383
|
if (!v || typeof v !== 'object')
|
|
212
384
|
return v;
|
|
213
385
|
if ('array' in v)
|
|
214
386
|
return { array: v.array.map(shift) };
|
|
215
|
-
if ('node' in v)
|
|
216
|
-
|
|
217
|
-
return { ...v, node: [String(Number(first) + 1), ...rest].join('/') };
|
|
218
|
-
}
|
|
387
|
+
if ('node' in v)
|
|
388
|
+
return { ...v, node: v.node === '' ? '0' : `0/${v.node}` };
|
|
219
389
|
return v;
|
|
220
390
|
};
|
|
221
391
|
const visit = (n) => ({
|
|
@@ -225,6 +395,20 @@ function shiftNodes(roots) {
|
|
|
225
395
|
});
|
|
226
396
|
return roots.map(visit);
|
|
227
397
|
}
|
|
398
|
+
/**
|
|
399
|
+
* Siblings of one name made apart as Unity's Duplicate names them — `Mesh`, `Mesh (1)` — so a placed
|
|
400
|
+
* prefab's override can say which child it changes (three names an unnamed mesh after its type).
|
|
401
|
+
*/
|
|
402
|
+
function siblings(children) {
|
|
403
|
+
const seen = new Map();
|
|
404
|
+
for (const c of children) {
|
|
405
|
+
const k = seen.get(c.name) ?? 0;
|
|
406
|
+
seen.set(c.name, k + 1);
|
|
407
|
+
if (k > 0)
|
|
408
|
+
c.name = `${c.name} (${k})`;
|
|
409
|
+
}
|
|
410
|
+
return children;
|
|
411
|
+
}
|
|
228
412
|
function hasComponents(n) {
|
|
229
413
|
return n.components.length > 0 || n.children.some(hasComponents);
|
|
230
414
|
}
|
|
@@ -242,7 +426,11 @@ class Paths {
|
|
|
242
426
|
}
|
|
243
427
|
const numbers = (v) => v && typeof v === 'object' && 'array' in v ? v.array.map((x) => (typeof x === 'number' ? x : 0)) : [];
|
|
244
428
|
/** A terrain's metres as Unity's TerrainData: mirrored in z, anchored at its corner, heights 0..1 of their span. */
|
|
245
|
-
|
|
429
|
+
/**
|
|
430
|
+
* `scale` is the node's own scale in the world: Unity draws a Terrain at its data's size whatever its
|
|
431
|
+
* transform's scale, so a terrain under a scaled node takes the scale into its size and its tiling.
|
|
432
|
+
*/
|
|
433
|
+
function terrain(f, path, copy = () => undefined, scale = 1) {
|
|
246
434
|
const warnings = [];
|
|
247
435
|
const width = f.width;
|
|
248
436
|
const depth = f.depth;
|
|
@@ -267,9 +455,11 @@ function terrain(f, path) {
|
|
|
267
455
|
const layers = layerValues.map((l) => {
|
|
268
456
|
const fields = l && typeof l === 'object' && 'object' in l ? l.object.fields : {};
|
|
269
457
|
const color = fields.color && typeof fields.color === 'object' && 'color' in fields.color ? fields.color.color : '#808080';
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
458
|
+
const texture = typeof fields.texture === 'string' ? copy(fields.texture) : undefined;
|
|
459
|
+
const normalMap = typeof fields.normalMap === 'string' ? copy(fields.normalMap) : undefined;
|
|
460
|
+
if (fields.textured && !texture)
|
|
461
|
+
warnings.push(`${path}: layer "${fields.name || 'unnamed'}" has a texture made in code, which is not exported — it is its colour in Unity.`);
|
|
462
|
+
return { name: String(fields.name ?? ''), tileSize: Number(fields.tileSize ?? 10) * scale, color, ...(texture ? { texture } : {}), ...(normalMap ? { normalMap } : {}) };
|
|
273
463
|
});
|
|
274
464
|
const a = f.alphamapResolution;
|
|
275
465
|
const bytes = numbers(f.alphamaps);
|
|
@@ -290,7 +480,7 @@ function terrain(f, path) {
|
|
|
290
480
|
return {
|
|
291
481
|
terrain: {
|
|
292
482
|
path,
|
|
293
|
-
size: [width, span, depth],
|
|
483
|
+
size: [width * scale, span * scale, depth * scale],
|
|
294
484
|
offset: [-width / 2, low, -depth / 2],
|
|
295
485
|
heightmapResolution: n,
|
|
296
486
|
heights,
|
|
@@ -308,6 +498,8 @@ function mesh(g, path) {
|
|
|
308
498
|
out.normals = g.normal.map((v, i) => (i % 3 === 2 && v !== 0 ? -v : v));
|
|
309
499
|
if (g.uv)
|
|
310
500
|
out.uv = g.uv;
|
|
501
|
+
if (g.color)
|
|
502
|
+
out.colors = g.colorSize === 4 ? g.color : g.color.flatMap((v, i) => (i % 3 === 2 ? [v, 1] : [v]));
|
|
311
503
|
// Mirrored with its camera, a triangle still winds counter-clockwise on screen — three's front, Unity's back.
|
|
312
504
|
const wind = (from, count) => {
|
|
313
505
|
const out = [];
|
|
@@ -325,7 +517,7 @@ function mesh(g, path) {
|
|
|
325
517
|
}
|
|
326
518
|
return out;
|
|
327
519
|
}
|
|
328
|
-
function material(m, path, textures, copies, warnings) {
|
|
520
|
+
function material(m, path, textures, copies, warnings, emits = false) {
|
|
329
521
|
const lit = !/Basic/.test(m.type);
|
|
330
522
|
const out = {
|
|
331
523
|
path,
|
|
@@ -342,8 +534,10 @@ function material(m, path, textures, copies, warnings) {
|
|
|
342
534
|
out.smoothness = m.roughness !== undefined ? 1 - m.roughness : m.shininess !== undefined ? Math.min(1, m.shininess / 100) : 0.5;
|
|
343
535
|
out.metallic = m.metalness ?? 0;
|
|
344
536
|
}
|
|
345
|
-
|
|
346
|
-
|
|
537
|
+
// URP draws emission only with its keyword on: a material whose code may light it later — black now,
|
|
538
|
+
// a colour set from a behaviour — keeps it on, or setting _EmissionColor at runtime draws nothing.
|
|
539
|
+
if ((m.emissiveIntensity ?? 1) > 0 && ((m.emissive && m.emissive !== '#000000') || (emits && lit))) {
|
|
540
|
+
out.emission = m.emissive ?? '#000000';
|
|
347
541
|
out.emissionIntensity = m.emissiveIntensity ?? 1;
|
|
348
542
|
}
|
|
349
543
|
for (const [slot, key] of [['map', 'texture'], ['emissiveMap', 'emissionTexture']]) {
|
|
@@ -361,7 +555,7 @@ function material(m, path, textures, copies, warnings) {
|
|
|
361
555
|
if (m.repeat)
|
|
362
556
|
out.tiling = m.repeat;
|
|
363
557
|
if (m.vertexColors)
|
|
364
|
-
|
|
558
|
+
out.vertexColors = true;
|
|
365
559
|
if (m.flatShading)
|
|
366
560
|
warnings.push(`${m.source ?? m.name}: flat shading is not exported — the mesh keeps its normals.`);
|
|
367
561
|
return out;
|
|
@@ -446,7 +640,8 @@ function mix(a, b) {
|
|
|
446
640
|
* written, started from the defaults a fresh instance holds — and, from its TypeScript, every other
|
|
447
641
|
* member with that member's code inside it as comments, for a port to write in place.
|
|
448
642
|
*/
|
|
449
|
-
function scripts(snap, value,
|
|
643
|
+
function scripts(snap, value, read, options, warnings) {
|
|
644
|
+
const source = options.source;
|
|
450
645
|
const seen = new Map();
|
|
451
646
|
const visit = (n) => {
|
|
452
647
|
for (const c of n.components) {
|
|
@@ -455,7 +650,13 @@ function scripts(snap, value, source) {
|
|
|
455
650
|
const fields = seen.get(c.type) ?? new Map();
|
|
456
651
|
seen.set(c.type, fields);
|
|
457
652
|
for (const [k, v] of Object.entries(c.fields))
|
|
458
|
-
fields.set(k, [...(fields.get(k) ?? []), value(v)]);
|
|
653
|
+
fields.set(k, [...(fields.get(k) ?? []), value(c.type, k, v)]);
|
|
654
|
+
for (const [k, path] of read.templates.get(c.type) ?? [])
|
|
655
|
+
if (!(k in c.fields))
|
|
656
|
+
fields.set(k, [...(fields.get(k) ?? []), { asset: path }]);
|
|
657
|
+
for (const [k, ref] of read.prefabs.get(c.type) ?? [])
|
|
658
|
+
if (!(k in c.fields))
|
|
659
|
+
fields.set(k, [...(fields.get(k) ?? []), value(c.type, k, ref)]);
|
|
459
660
|
}
|
|
460
661
|
n.children.forEach(visit);
|
|
461
662
|
};
|
|
@@ -467,23 +668,38 @@ function scripts(snap, value, source) {
|
|
|
467
668
|
for (const type of new Set([...seen.keys(), ...Object.keys(snap.classes)])) {
|
|
468
669
|
const info = snap.classes[type];
|
|
469
670
|
const wired = new Map();
|
|
671
|
+
const usings = new Set();
|
|
470
672
|
for (const [name, values] of seen.get(type) ?? []) {
|
|
471
673
|
const cs = csType(values);
|
|
674
|
+
// A stub that does not compile stops the Editor at Safe Mode before anything can be ported: a type
|
|
675
|
+
// only goes into C# when it is known to be there — the game's own, or Unity's with its namespace.
|
|
676
|
+
const known = cs === undefined ? undefined : knownType(cs, classes);
|
|
677
|
+
if (cs && known === undefined) {
|
|
678
|
+
warnings.push(`${type}.${name} holds a ${cs}, which has no C# type here — the stub leaves it as a comment: declare it when porting.`);
|
|
679
|
+
wired.set(name, ` // ${name}: a ${cs} in TypeScript, which has no C# type here — declare it when porting`);
|
|
680
|
+
continue;
|
|
681
|
+
}
|
|
682
|
+
if (known)
|
|
683
|
+
usings.add(known);
|
|
472
684
|
const fallback = info?.defaults[name];
|
|
473
|
-
const init = fallback === undefined ? '' : csValue(value(fallback), cs);
|
|
685
|
+
const init = fallback === undefined ? '' : csValue(value(type, name, fallback), cs);
|
|
474
686
|
wired.set(name, cs ? ` public ${cs} ${name}${init ? ` = ${init}` : ''};` : ` // ${name}: always empty where it is written, so its type is unknown`);
|
|
475
687
|
}
|
|
688
|
+
const using = (text) => {
|
|
689
|
+
const missing = [...usings].filter((u) => !text.includes(`using ${u};`)).map((u) => `using ${u};\n`).join('');
|
|
690
|
+
return missing + text;
|
|
691
|
+
};
|
|
476
692
|
const name = csName(type);
|
|
477
693
|
const code = info && source?.(info.file);
|
|
478
|
-
const cls =
|
|
694
|
+
const cls = read.classes.get(type);
|
|
479
695
|
if (cls) {
|
|
480
696
|
const file = info.file;
|
|
481
697
|
const outside = outsideGiven.has(file) ? [] : outsideClasses(code, file, Object.keys(snap.classes).filter((t) => snap.classes[t].file === file));
|
|
482
698
|
outsideGiven.add(file);
|
|
483
|
-
out.set(name, stubClass(name, file, cls, wired, classes, outside).replace(/^(public class)/m, `${name !== type ? `// Named ${name}: Unity has its own ${type}.\n` : ''}$1`));
|
|
699
|
+
out.set(name, using(stubClass(name, file, cls, wired, classes, outside, options.aliases).replace(/^(public class)/m, `${name !== type ? `// Named ${name}: Unity has its own ${type}.\n` : ''}$1`)));
|
|
484
700
|
continue;
|
|
485
701
|
}
|
|
486
|
-
out.set(name, [
|
|
702
|
+
out.set(name, using([
|
|
487
703
|
'using UnityEngine;',
|
|
488
704
|
'',
|
|
489
705
|
`// The fields ${info?.file ?? 'the game'} sets on ${type} in its scenes and prefabs. Port its logic here;`,
|
|
@@ -494,10 +710,36 @@ function scripts(snap, value, source) {
|
|
|
494
710
|
...wired.values(),
|
|
495
711
|
'}',
|
|
496
712
|
'',
|
|
497
|
-
].join('\n'));
|
|
713
|
+
].join('\n')));
|
|
498
714
|
}
|
|
499
715
|
return out;
|
|
500
716
|
}
|
|
717
|
+
/**
|
|
718
|
+
* The C# types a stub may name, by the namespace each needs: Unity's own that a SceNoCo package's
|
|
719
|
+
* component or an asset becomes. Anything else stays a comment, so a stub always compiles.
|
|
720
|
+
*/
|
|
721
|
+
const NAMESPACES = {
|
|
722
|
+
...Object.fromEntries(('float int bool string Vector2 Vector3 Vector4 Quaternion Color GameObject Transform Material Mesh Texture Texture2D AudioClip ' +
|
|
723
|
+
'AudioSource AudioListener Camera Light Rigidbody Rigidbody2D Collider Collider2D BoxCollider SphereCollider CapsuleCollider ' +
|
|
724
|
+
'MeshCollider BoxCollider2D CircleCollider2D CapsuleCollider2D PolygonCollider2D EdgeCollider2D Joint2D HingeJoint2D ' +
|
|
725
|
+
'FixedJoint2D SpringJoint2D DistanceJoint2D WheelJoint2D SliderJoint2D HingeJoint FixedJoint SpringJoint ConfigurableJoint ' +
|
|
726
|
+
'CharacterJoint Terrain TerrainData TerrainCollider TerrainLayer ParticleSystem Animator MeshFilter MeshRenderer Renderer ' +
|
|
727
|
+
'PhysicsMaterial PhysicsMaterial2D MonoBehaviour Behaviour Component Sprite')
|
|
728
|
+
.split(' ')
|
|
729
|
+
.map((t) => [t, 'UnityEngine'])),
|
|
730
|
+
...Object.fromEntries('SplineContainer SplineAnimate SplineInstantiate SplineExtrude'.split(' ').map((t) => [t, 'UnityEngine.Splines'])),
|
|
731
|
+
...Object.fromEntries('UIDocument VisualTreeAsset VisualElement PanelSettings'.split(' ').map((t) => [t, 'UnityEngine.UIElements'])),
|
|
732
|
+
Volume: 'UnityEngine.Rendering',
|
|
733
|
+
VolumeProfile: 'UnityEngine.Rendering',
|
|
734
|
+
SplineMesh: 'SceNoCo',
|
|
735
|
+
};
|
|
736
|
+
/** The namespace a stub needs for `cs` (an array of it too); '' for a class of the game; undefined when unknown. */
|
|
737
|
+
function knownType(cs, classes) {
|
|
738
|
+
const base = cs.replace(/(\[\])+$/, '');
|
|
739
|
+
if ([...classes.values()].includes(base))
|
|
740
|
+
return '';
|
|
741
|
+
return NAMESPACES[base];
|
|
742
|
+
}
|
|
501
743
|
function csType(values) {
|
|
502
744
|
const known = values.find((v) => v !== null && !(typeof v === 'object' && 'array' in v && v.array.length === 0)) ?? values[0];
|
|
503
745
|
if (known === undefined || known === null)
|
|
@@ -523,13 +765,31 @@ function csType(values) {
|
|
|
523
765
|
if ('node' in known)
|
|
524
766
|
return 'Transform';
|
|
525
767
|
if ('asset' in known)
|
|
526
|
-
return
|
|
768
|
+
return assetType(known.asset);
|
|
527
769
|
if ('array' in known) {
|
|
528
770
|
const inner = csType(values.flatMap((v) => (v && typeof v === 'object' && 'array' in v ? v.array : [])));
|
|
529
771
|
return inner ? `${inner}[]` : undefined;
|
|
530
772
|
}
|
|
531
773
|
return undefined;
|
|
532
774
|
}
|
|
775
|
+
/** The C# type of an asset, by its file: a model imports as a GameObject, as a prefab does. */
|
|
776
|
+
export function assetType(path) {
|
|
777
|
+
if (/\.(prefab|glb|gltf)$/i.test(path))
|
|
778
|
+
return 'GameObject';
|
|
779
|
+
if (path.endsWith('.mat'))
|
|
780
|
+
return 'Material';
|
|
781
|
+
if (path.endsWith('.uxml'))
|
|
782
|
+
return 'VisualTreeAsset';
|
|
783
|
+
if (/\.(wav|mp3|ogg|m4a|aiff?|flac)$/i.test(path))
|
|
784
|
+
return 'AudioClip';
|
|
785
|
+
if (/\.(png|jpe?g|webp|tga)$/i.test(path))
|
|
786
|
+
return 'Texture2D';
|
|
787
|
+
if (path.startsWith('Assets/Terrains/'))
|
|
788
|
+
return 'TerrainData';
|
|
789
|
+
if (path.startsWith('Assets/Materials/Physics/'))
|
|
790
|
+
return 'PhysicsMaterial';
|
|
791
|
+
return 'Mesh';
|
|
792
|
+
}
|
|
533
793
|
function csValue(v, type) {
|
|
534
794
|
const f = (n) => `${Number.isInteger(n) ? n : n}f`;
|
|
535
795
|
if (v === null || type === undefined)
|
|
@@ -555,3 +815,31 @@ function csValue(v, type) {
|
|
|
555
815
|
}
|
|
556
816
|
return '';
|
|
557
817
|
}
|
|
818
|
+
/**
|
|
819
|
+
* The objects of a .glb that hold a mesh, as glTFast builds them under the model's root: one per node
|
|
820
|
+
* of its scene, named as the node is, or `Node-<index>` when it has no name.
|
|
821
|
+
*/
|
|
822
|
+
export function glbMeshNodes(file) {
|
|
823
|
+
if (!existsSync(file))
|
|
824
|
+
return [];
|
|
825
|
+
const bytes = readFileSync(file);
|
|
826
|
+
if (bytes.readUInt32LE(0) !== 0x46546c67)
|
|
827
|
+
return [];
|
|
828
|
+
const length = bytes.readUInt32LE(12);
|
|
829
|
+
const json = JSON.parse(bytes.subarray(20, 20 + length).toString('utf8'));
|
|
830
|
+
const nodes = json.nodes ?? [];
|
|
831
|
+
const out = [];
|
|
832
|
+
const walk = (index, path) => {
|
|
833
|
+
const node = nodes[index];
|
|
834
|
+
if (!node)
|
|
835
|
+
return;
|
|
836
|
+
const here = [...path, node.name || `Node-${index}`];
|
|
837
|
+
if (node.mesh !== undefined)
|
|
838
|
+
out.push(here);
|
|
839
|
+
for (const child of node.children ?? [])
|
|
840
|
+
walk(child, here);
|
|
841
|
+
};
|
|
842
|
+
for (const root of json.scenes?.[json.scene ?? 0]?.nodes ?? [])
|
|
843
|
+
walk(root, []);
|
|
844
|
+
return out;
|
|
845
|
+
}
|
package/dist/export.d.ts
CHANGED
|
@@ -11,6 +11,10 @@ export declare function snapshotProject(root: string, options?: {
|
|
|
11
11
|
}): Promise<ExportSnapshot>;
|
|
12
12
|
export interface Written {
|
|
13
13
|
converted: Converted;
|
|
14
|
+
/** The scenes' and prefabs' text, by the path Scenoco builds each from. */
|
|
15
|
+
twins: string[];
|
|
16
|
+
/** Packages added to the project's manifest: Scenoco, which builds the text, and Diceload, which checks the port. */
|
|
17
|
+
packages: string[];
|
|
14
18
|
/** Stubs written; the rest already had a class of that name in the project. */
|
|
15
19
|
scripts: string[];
|
|
16
20
|
/** Module stubs written: the game's code outside its behaviours. */
|
|
@@ -35,10 +39,25 @@ export interface ExportSnapshot extends Snapshot {
|
|
|
35
39
|
ignore3D?: [number, number][];
|
|
36
40
|
/** A layer's name, from an exported constant such as `Layer = { ball: 1 }`. */
|
|
37
41
|
layerNames?: Record<number, string>;
|
|
42
|
+
/** Every file the game's modules load, by URL and the class that loads it: copied in whether or not a field names it. */
|
|
43
|
+
files?: {
|
|
44
|
+
url: string;
|
|
45
|
+
type: string;
|
|
46
|
+
}[];
|
|
38
47
|
}
|
|
39
48
|
/**
|
|
40
|
-
* Convert a snapshot and write it into the Unity project:
|
|
41
|
-
*
|
|
42
|
-
*
|
|
49
|
+
* Convert a snapshot and write it into the Unity project: the scenes and prefabs as Scenoco's text, data
|
|
50
|
+
* for the importer that makes the assets they name, the importer, C# stubs, textures, the page as UXML
|
|
51
|
+
* and USS with its images and fonts, the input actions — and the porting rules, with Scenoco and Diceload
|
|
52
|
+
* in the project's manifest for the agent that ports and checks it.
|
|
43
53
|
*/
|
|
44
54
|
export declare function writeUnity(snap: ExportSnapshot, project: string, root: string): Promise<Written>;
|
|
55
|
+
/** Whether a module tweens with core's API — `Tween.sequence()`, `node.doMove(…)` — which a port writes with DOTween. */
|
|
56
|
+
export declare function usesTweens(code: string): boolean;
|
|
57
|
+
/**
|
|
58
|
+
* The fields a C# file declares that Unity serializes, as a scene sets them: public ones, and
|
|
59
|
+
* `[SerializeField]` ones — not static, const or readonly, not a property or a method.
|
|
60
|
+
*/
|
|
61
|
+
export declare function serializedFields(code: string): Set<string>;
|
|
62
|
+
/** The decoder packages `files` (.glb or .gltf) need: read from each file's JSON, its `extensionsUsed`. */
|
|
63
|
+
export declare function gltfDecoders(files: string[]): Set<string>;
|