@scenoco-three/unity 1.4.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +8 -5
- package/dist/convert.d.ts +39 -0
- package/dist/convert.js +324 -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 +1074 -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;
|
|
@@ -124,16 +209,34 @@ export function convert(snap, options = {}) {
|
|
|
124
209
|
}
|
|
125
210
|
if (n.prefab) {
|
|
126
211
|
const path = prefabPath.get(n.prefab);
|
|
127
|
-
if (path)
|
|
212
|
+
if (path) {
|
|
128
213
|
out.prefab = path;
|
|
129
|
-
|
|
214
|
+
if (n.given)
|
|
215
|
+
out.given = true;
|
|
216
|
+
}
|
|
217
|
+
// Given attributes, it holds what it is built as: copied in.
|
|
218
|
+
else if (!n.given)
|
|
130
219
|
warnings.push(`${n.source ?? n.name}: nested ${n.prefab} is not a prefab of its own — left empty.`);
|
|
131
220
|
}
|
|
221
|
+
if (n.model) {
|
|
222
|
+
// A placed model is the model file, placed as a prefab is. glTFast mirrors a model in x where this
|
|
223
|
+
// export mirrors the world in z: half a turn about its own up puts it back as three draws it.
|
|
224
|
+
const file = fileOf(n.model, 'Model');
|
|
225
|
+
if (file && typeof file === 'object' && 'asset' in file) {
|
|
226
|
+
out.prefab = file.asset;
|
|
227
|
+
const found = options.textures?.(n.model);
|
|
228
|
+
if (found && /\.glb$/i.test(found.file))
|
|
229
|
+
out.meshNodes = glbMeshNodes(found.file);
|
|
230
|
+
const [x, y, z, w] = out.rotation;
|
|
231
|
+
out.rotation = [-z, w, x, -y].map((c) => (c === 0 ? 0 : c));
|
|
232
|
+
}
|
|
233
|
+
}
|
|
132
234
|
if (n.geometry)
|
|
133
235
|
out.mesh = meshPath.get(n.geometry);
|
|
134
|
-
|
|
236
|
+
// A mesh whose geometry its code builds (a river's ribbon) still has its renderer and material.
|
|
237
|
+
if (n.materials)
|
|
135
238
|
out.materials = n.materials.map((id) => materialPath.get(id));
|
|
136
|
-
if (n.geometry) {
|
|
239
|
+
if (n.geometry || n.materials) {
|
|
137
240
|
out.castShadows = n.castShadow;
|
|
138
241
|
out.receiveShadows = n.receiveShadow;
|
|
139
242
|
}
|
|
@@ -177,10 +280,11 @@ export function convert(snap, options = {}) {
|
|
|
177
280
|
}
|
|
178
281
|
ambient = undefined;
|
|
179
282
|
const root = node(p.root);
|
|
180
|
-
// The scene's own components, if any, need an object to live on: the
|
|
181
|
-
//
|
|
283
|
+
// The scene's own components, if any, need an object to live on: one that holds the whole scene, as
|
|
284
|
+
// three's Scene does — so DontDestroyOnLoad on it keeps the scene, and GetComponentInParent finds it.
|
|
285
|
+
// A reference into the scene, a path of child indices, starts one level down.
|
|
182
286
|
const roots = root.components.length
|
|
183
|
-
?
|
|
287
|
+
? nestNodes([{ ...root, name: p.name, position: [0, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1] }])
|
|
184
288
|
: root.children;
|
|
185
289
|
const scene = { path: `Assets/Scenes/${sceneName.get(p.id)}.unity`, roots };
|
|
186
290
|
if (p.background)
|
|
@@ -203,19 +307,83 @@ export function convert(snap, options = {}) {
|
|
|
203
307
|
ignore2D: given.ignore2D.map(([a, b]) => [unityLayer(a), unityLayer(b)]),
|
|
204
308
|
ignore3D: given.ignore3D.map(([a, b]) => [unityLayer(a), unityLayer(b)]),
|
|
205
309
|
};
|
|
206
|
-
return { data: { meshes, terrains, materials, prefabs, scenes, layers, warnings }, scripts: scripts(snap,
|
|
310
|
+
return { data: { meshes, terrains, materials, prefabs, scenes, layers, modelVariants, dataTextures, warnings }, scripts: scripts(snap, field, read, options, warnings), copies };
|
|
311
|
+
}
|
|
312
|
+
function readSources(snap, options) {
|
|
313
|
+
const out = { classes: new Map(), axes: new Set(), templates: new Map(), emits: false, prefabs: new Map() };
|
|
314
|
+
const prefabNames = [
|
|
315
|
+
...snap.prefabs.filter((p) => !p.scene).map((p) => [p.name, { prefab: p.id }]),
|
|
316
|
+
// A model's prefab is the model file, as Unity's model prefab is.
|
|
317
|
+
...Object.entries(snap.models ?? {}).map(([id, url]) => [id.split('#')[1], { file: url, type: 'Model' }]),
|
|
318
|
+
];
|
|
319
|
+
const templates = options.templates ?? {};
|
|
320
|
+
for (const [type, info] of Object.entries(snap.classes)) {
|
|
321
|
+
const code = options.source?.(info.file);
|
|
322
|
+
if (!code)
|
|
323
|
+
continue;
|
|
324
|
+
if (/\.emissive(Intensity)?\b/.test(code))
|
|
325
|
+
out.emits = true;
|
|
326
|
+
const cls = readClass(code, info.file, type);
|
|
327
|
+
if (!cls)
|
|
328
|
+
continue;
|
|
329
|
+
out.classes.set(type, cls);
|
|
330
|
+
const fields = new Set(cls.members.filter((m) => m.kind === 'field').map((m) => m.name));
|
|
331
|
+
for (const m of cls.members) {
|
|
332
|
+
for (const line of m.body ?? []) {
|
|
333
|
+
// `rotation.x += this.speed.x * k`: the field is a rate about the axes.
|
|
334
|
+
const set = /(?:\.rotation|\.eulerAngles|\.rotate\w*\()(?:[.\w]*\s*[-+*/]?=)?(.*)$/.exec(line);
|
|
335
|
+
if (set)
|
|
336
|
+
for (const [, name] of set[1].matchAll(/this\.(\w+)/g))
|
|
337
|
+
if (fields.has(name))
|
|
338
|
+
out.axes.add(`${type}.${name}`);
|
|
339
|
+
// `this.chip = element('chip')`, where `chip` is a template's id.
|
|
340
|
+
const clone = /this\.(\w+)\s*=\s*[^;]*?\(\s*['"`]#?([\w-]+)['"`]/.exec(line);
|
|
341
|
+
if (clone && fields.has(clone[1]) && templates[clone[2]]) {
|
|
342
|
+
const own = out.templates.get(type) ?? new Map();
|
|
343
|
+
own.set(clone[1], templates[clone[2]]);
|
|
344
|
+
out.templates.set(type, own);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
// A template named anywhere else in the class — `clone('who')` through a helper — is a field of its
|
|
349
|
+
// own: the id's name, or `<id>Template` where the class has a member called that already.
|
|
350
|
+
const own = out.templates.get(type) ?? new Map();
|
|
351
|
+
const taken = new Set(cls.members.map((m) => m.name));
|
|
352
|
+
const wired = new Set(own.values());
|
|
353
|
+
const text = cls.members.map((m) => m.text).join('\n');
|
|
354
|
+
for (const [id, path] of Object.entries(templates)) {
|
|
355
|
+
if (wired.has(path) || !new RegExp(`['"\`]#?${id}['"\`]`).test(text))
|
|
356
|
+
continue;
|
|
357
|
+
const name = id.replace(/-(\w)/g, (_, c) => c.toUpperCase());
|
|
358
|
+
own.set(taken.has(name) ? `${name}Template` : name, path);
|
|
359
|
+
}
|
|
360
|
+
if (own.size)
|
|
361
|
+
out.templates.set(type, own);
|
|
362
|
+
// A prefab the class names in its code — it imports and instantiates it — is a field Unity wires: the
|
|
363
|
+
// prefab's name in camelCase (`Goblin` → `goblin`), or `<name>Prefab` where that name is a member already.
|
|
364
|
+
const spawns = new Map();
|
|
365
|
+
const written = new Set(Object.keys(info.defaults ?? {}));
|
|
366
|
+
for (const [name, ref] of prefabNames) {
|
|
367
|
+
if (!new RegExp(`\\b${name}\\b`).test(text))
|
|
368
|
+
continue;
|
|
369
|
+
const camel = name.charAt(0).toLowerCase() + name.slice(1);
|
|
370
|
+
const field = taken.has(camel) || written.has(camel) ? `${camel}Prefab` : camel;
|
|
371
|
+
spawns.set(field, ref);
|
|
372
|
+
}
|
|
373
|
+
if (spawns.size)
|
|
374
|
+
out.prefabs.set(type, spawns);
|
|
375
|
+
}
|
|
376
|
+
return out;
|
|
207
377
|
}
|
|
208
|
-
/** Every node reference in `roots` one root
|
|
209
|
-
function
|
|
378
|
+
/** Every node reference in `roots` under the one root that now holds them; the scene itself (`''`) is that root. */
|
|
379
|
+
function nestNodes(roots) {
|
|
210
380
|
const shift = (v) => {
|
|
211
381
|
if (!v || typeof v !== 'object')
|
|
212
382
|
return v;
|
|
213
383
|
if ('array' in v)
|
|
214
384
|
return { array: v.array.map(shift) };
|
|
215
|
-
if ('node' in v)
|
|
216
|
-
|
|
217
|
-
return { ...v, node: [String(Number(first) + 1), ...rest].join('/') };
|
|
218
|
-
}
|
|
385
|
+
if ('node' in v)
|
|
386
|
+
return { ...v, node: v.node === '' ? '0' : `0/${v.node}` };
|
|
219
387
|
return v;
|
|
220
388
|
};
|
|
221
389
|
const visit = (n) => ({
|
|
@@ -225,6 +393,20 @@ function shiftNodes(roots) {
|
|
|
225
393
|
});
|
|
226
394
|
return roots.map(visit);
|
|
227
395
|
}
|
|
396
|
+
/**
|
|
397
|
+
* Siblings of one name made apart as Unity's Duplicate names them — `Mesh`, `Mesh (1)` — so a placed
|
|
398
|
+
* prefab's override can say which child it changes (three names an unnamed mesh after its type).
|
|
399
|
+
*/
|
|
400
|
+
function siblings(children) {
|
|
401
|
+
const seen = new Map();
|
|
402
|
+
for (const c of children) {
|
|
403
|
+
const k = seen.get(c.name) ?? 0;
|
|
404
|
+
seen.set(c.name, k + 1);
|
|
405
|
+
if (k > 0)
|
|
406
|
+
c.name = `${c.name} (${k})`;
|
|
407
|
+
}
|
|
408
|
+
return children;
|
|
409
|
+
}
|
|
228
410
|
function hasComponents(n) {
|
|
229
411
|
return n.components.length > 0 || n.children.some(hasComponents);
|
|
230
412
|
}
|
|
@@ -242,7 +424,11 @@ class Paths {
|
|
|
242
424
|
}
|
|
243
425
|
const numbers = (v) => v && typeof v === 'object' && 'array' in v ? v.array.map((x) => (typeof x === 'number' ? x : 0)) : [];
|
|
244
426
|
/** A terrain's metres as Unity's TerrainData: mirrored in z, anchored at its corner, heights 0..1 of their span. */
|
|
245
|
-
|
|
427
|
+
/**
|
|
428
|
+
* `scale` is the node's own scale in the world: Unity draws a Terrain at its data's size whatever its
|
|
429
|
+
* transform's scale, so a terrain under a scaled node takes the scale into its size and its tiling.
|
|
430
|
+
*/
|
|
431
|
+
function terrain(f, path, copy = () => undefined, scale = 1) {
|
|
246
432
|
const warnings = [];
|
|
247
433
|
const width = f.width;
|
|
248
434
|
const depth = f.depth;
|
|
@@ -267,9 +453,11 @@ function terrain(f, path) {
|
|
|
267
453
|
const layers = layerValues.map((l) => {
|
|
268
454
|
const fields = l && typeof l === 'object' && 'object' in l ? l.object.fields : {};
|
|
269
455
|
const color = fields.color && typeof fields.color === 'object' && 'color' in fields.color ? fields.color.color : '#808080';
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
456
|
+
const texture = typeof fields.texture === 'string' ? copy(fields.texture) : undefined;
|
|
457
|
+
const normalMap = typeof fields.normalMap === 'string' ? copy(fields.normalMap) : undefined;
|
|
458
|
+
if (fields.textured && !texture)
|
|
459
|
+
warnings.push(`${path}: layer "${fields.name || 'unnamed'}" has a texture made in code, which is not exported — it is its colour in Unity.`);
|
|
460
|
+
return { name: String(fields.name ?? ''), tileSize: Number(fields.tileSize ?? 10) * scale, color, ...(texture ? { texture } : {}), ...(normalMap ? { normalMap } : {}) };
|
|
273
461
|
});
|
|
274
462
|
const a = f.alphamapResolution;
|
|
275
463
|
const bytes = numbers(f.alphamaps);
|
|
@@ -290,7 +478,7 @@ function terrain(f, path) {
|
|
|
290
478
|
return {
|
|
291
479
|
terrain: {
|
|
292
480
|
path,
|
|
293
|
-
size: [width, span, depth],
|
|
481
|
+
size: [width * scale, span * scale, depth * scale],
|
|
294
482
|
offset: [-width / 2, low, -depth / 2],
|
|
295
483
|
heightmapResolution: n,
|
|
296
484
|
heights,
|
|
@@ -308,6 +496,8 @@ function mesh(g, path) {
|
|
|
308
496
|
out.normals = g.normal.map((v, i) => (i % 3 === 2 && v !== 0 ? -v : v));
|
|
309
497
|
if (g.uv)
|
|
310
498
|
out.uv = g.uv;
|
|
499
|
+
if (g.color)
|
|
500
|
+
out.colors = g.colorSize === 4 ? g.color : g.color.flatMap((v, i) => (i % 3 === 2 ? [v, 1] : [v]));
|
|
311
501
|
// Mirrored with its camera, a triangle still winds counter-clockwise on screen — three's front, Unity's back.
|
|
312
502
|
const wind = (from, count) => {
|
|
313
503
|
const out = [];
|
|
@@ -325,7 +515,7 @@ function mesh(g, path) {
|
|
|
325
515
|
}
|
|
326
516
|
return out;
|
|
327
517
|
}
|
|
328
|
-
function material(m, path, textures, copies, warnings) {
|
|
518
|
+
function material(m, path, textures, copies, warnings, emits = false) {
|
|
329
519
|
const lit = !/Basic/.test(m.type);
|
|
330
520
|
const out = {
|
|
331
521
|
path,
|
|
@@ -342,8 +532,10 @@ function material(m, path, textures, copies, warnings) {
|
|
|
342
532
|
out.smoothness = m.roughness !== undefined ? 1 - m.roughness : m.shininess !== undefined ? Math.min(1, m.shininess / 100) : 0.5;
|
|
343
533
|
out.metallic = m.metalness ?? 0;
|
|
344
534
|
}
|
|
345
|
-
|
|
346
|
-
|
|
535
|
+
// URP draws emission only with its keyword on: a material whose code may light it later — black now,
|
|
536
|
+
// a colour set from a behaviour — keeps it on, or setting _EmissionColor at runtime draws nothing.
|
|
537
|
+
if ((m.emissiveIntensity ?? 1) > 0 && ((m.emissive && m.emissive !== '#000000') || (emits && lit))) {
|
|
538
|
+
out.emission = m.emissive ?? '#000000';
|
|
347
539
|
out.emissionIntensity = m.emissiveIntensity ?? 1;
|
|
348
540
|
}
|
|
349
541
|
for (const [slot, key] of [['map', 'texture'], ['emissiveMap', 'emissionTexture']]) {
|
|
@@ -361,7 +553,7 @@ function material(m, path, textures, copies, warnings) {
|
|
|
361
553
|
if (m.repeat)
|
|
362
554
|
out.tiling = m.repeat;
|
|
363
555
|
if (m.vertexColors)
|
|
364
|
-
|
|
556
|
+
out.vertexColors = true;
|
|
365
557
|
if (m.flatShading)
|
|
366
558
|
warnings.push(`${m.source ?? m.name}: flat shading is not exported — the mesh keeps its normals.`);
|
|
367
559
|
return out;
|
|
@@ -446,7 +638,8 @@ function mix(a, b) {
|
|
|
446
638
|
* written, started from the defaults a fresh instance holds — and, from its TypeScript, every other
|
|
447
639
|
* member with that member's code inside it as comments, for a port to write in place.
|
|
448
640
|
*/
|
|
449
|
-
function scripts(snap, value,
|
|
641
|
+
function scripts(snap, value, read, options, warnings) {
|
|
642
|
+
const source = options.source;
|
|
450
643
|
const seen = new Map();
|
|
451
644
|
const visit = (n) => {
|
|
452
645
|
for (const c of n.components) {
|
|
@@ -455,7 +648,13 @@ function scripts(snap, value, source) {
|
|
|
455
648
|
const fields = seen.get(c.type) ?? new Map();
|
|
456
649
|
seen.set(c.type, fields);
|
|
457
650
|
for (const [k, v] of Object.entries(c.fields))
|
|
458
|
-
fields.set(k, [...(fields.get(k) ?? []), value(v)]);
|
|
651
|
+
fields.set(k, [...(fields.get(k) ?? []), value(c.type, k, v)]);
|
|
652
|
+
for (const [k, path] of read.templates.get(c.type) ?? [])
|
|
653
|
+
if (!(k in c.fields))
|
|
654
|
+
fields.set(k, [...(fields.get(k) ?? []), { asset: path }]);
|
|
655
|
+
for (const [k, ref] of read.prefabs.get(c.type) ?? [])
|
|
656
|
+
if (!(k in c.fields))
|
|
657
|
+
fields.set(k, [...(fields.get(k) ?? []), value(c.type, k, ref)]);
|
|
459
658
|
}
|
|
460
659
|
n.children.forEach(visit);
|
|
461
660
|
};
|
|
@@ -467,23 +666,38 @@ function scripts(snap, value, source) {
|
|
|
467
666
|
for (const type of new Set([...seen.keys(), ...Object.keys(snap.classes)])) {
|
|
468
667
|
const info = snap.classes[type];
|
|
469
668
|
const wired = new Map();
|
|
669
|
+
const usings = new Set();
|
|
470
670
|
for (const [name, values] of seen.get(type) ?? []) {
|
|
471
671
|
const cs = csType(values);
|
|
672
|
+
// A stub that does not compile stops the Editor at Safe Mode before anything can be ported: a type
|
|
673
|
+
// only goes into C# when it is known to be there — the game's own, or Unity's with its namespace.
|
|
674
|
+
const known = cs === undefined ? undefined : knownType(cs, classes);
|
|
675
|
+
if (cs && known === undefined) {
|
|
676
|
+
warnings.push(`${type}.${name} holds a ${cs}, which has no C# type here — the stub leaves it as a comment: declare it when porting.`);
|
|
677
|
+
wired.set(name, ` // ${name}: a ${cs} in TypeScript, which has no C# type here — declare it when porting`);
|
|
678
|
+
continue;
|
|
679
|
+
}
|
|
680
|
+
if (known)
|
|
681
|
+
usings.add(known);
|
|
472
682
|
const fallback = info?.defaults[name];
|
|
473
|
-
const init = fallback === undefined ? '' : csValue(value(fallback), cs);
|
|
683
|
+
const init = fallback === undefined ? '' : csValue(value(type, name, fallback), cs);
|
|
474
684
|
wired.set(name, cs ? ` public ${cs} ${name}${init ? ` = ${init}` : ''};` : ` // ${name}: always empty where it is written, so its type is unknown`);
|
|
475
685
|
}
|
|
686
|
+
const using = (text) => {
|
|
687
|
+
const missing = [...usings].filter((u) => !text.includes(`using ${u};`)).map((u) => `using ${u};\n`).join('');
|
|
688
|
+
return missing + text;
|
|
689
|
+
};
|
|
476
690
|
const name = csName(type);
|
|
477
691
|
const code = info && source?.(info.file);
|
|
478
|
-
const cls =
|
|
692
|
+
const cls = read.classes.get(type);
|
|
479
693
|
if (cls) {
|
|
480
694
|
const file = info.file;
|
|
481
695
|
const outside = outsideGiven.has(file) ? [] : outsideClasses(code, file, Object.keys(snap.classes).filter((t) => snap.classes[t].file === file));
|
|
482
696
|
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`));
|
|
697
|
+
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
698
|
continue;
|
|
485
699
|
}
|
|
486
|
-
out.set(name, [
|
|
700
|
+
out.set(name, using([
|
|
487
701
|
'using UnityEngine;',
|
|
488
702
|
'',
|
|
489
703
|
`// The fields ${info?.file ?? 'the game'} sets on ${type} in its scenes and prefabs. Port its logic here;`,
|
|
@@ -494,10 +708,36 @@ function scripts(snap, value, source) {
|
|
|
494
708
|
...wired.values(),
|
|
495
709
|
'}',
|
|
496
710
|
'',
|
|
497
|
-
].join('\n'));
|
|
711
|
+
].join('\n')));
|
|
498
712
|
}
|
|
499
713
|
return out;
|
|
500
714
|
}
|
|
715
|
+
/**
|
|
716
|
+
* The C# types a stub may name, by the namespace each needs: Unity's own that a SceNoCo package's
|
|
717
|
+
* component or an asset becomes. Anything else stays a comment, so a stub always compiles.
|
|
718
|
+
*/
|
|
719
|
+
const NAMESPACES = {
|
|
720
|
+
...Object.fromEntries(('float int bool string Vector2 Vector3 Vector4 Quaternion Color GameObject Transform Material Mesh Texture Texture2D AudioClip ' +
|
|
721
|
+
'AudioSource AudioListener Camera Light Rigidbody Rigidbody2D Collider Collider2D BoxCollider SphereCollider CapsuleCollider ' +
|
|
722
|
+
'MeshCollider BoxCollider2D CircleCollider2D CapsuleCollider2D PolygonCollider2D EdgeCollider2D Joint2D HingeJoint2D ' +
|
|
723
|
+
'FixedJoint2D SpringJoint2D DistanceJoint2D WheelJoint2D SliderJoint2D HingeJoint FixedJoint SpringJoint ConfigurableJoint ' +
|
|
724
|
+
'CharacterJoint Terrain TerrainData TerrainCollider TerrainLayer ParticleSystem Animator MeshFilter MeshRenderer Renderer ' +
|
|
725
|
+
'PhysicsMaterial PhysicsMaterial2D MonoBehaviour Behaviour Component Sprite')
|
|
726
|
+
.split(' ')
|
|
727
|
+
.map((t) => [t, 'UnityEngine'])),
|
|
728
|
+
...Object.fromEntries('SplineContainer SplineAnimate SplineInstantiate SplineExtrude'.split(' ').map((t) => [t, 'UnityEngine.Splines'])),
|
|
729
|
+
...Object.fromEntries('UIDocument VisualTreeAsset VisualElement PanelSettings'.split(' ').map((t) => [t, 'UnityEngine.UIElements'])),
|
|
730
|
+
Volume: 'UnityEngine.Rendering',
|
|
731
|
+
VolumeProfile: 'UnityEngine.Rendering',
|
|
732
|
+
SplineMesh: 'SceNoCo',
|
|
733
|
+
};
|
|
734
|
+
/** The namespace a stub needs for `cs` (an array of it too); '' for a class of the game; undefined when unknown. */
|
|
735
|
+
function knownType(cs, classes) {
|
|
736
|
+
const base = cs.replace(/(\[\])+$/, '');
|
|
737
|
+
if ([...classes.values()].includes(base))
|
|
738
|
+
return '';
|
|
739
|
+
return NAMESPACES[base];
|
|
740
|
+
}
|
|
501
741
|
function csType(values) {
|
|
502
742
|
const known = values.find((v) => v !== null && !(typeof v === 'object' && 'array' in v && v.array.length === 0)) ?? values[0];
|
|
503
743
|
if (known === undefined || known === null)
|
|
@@ -523,13 +763,31 @@ function csType(values) {
|
|
|
523
763
|
if ('node' in known)
|
|
524
764
|
return 'Transform';
|
|
525
765
|
if ('asset' in known)
|
|
526
|
-
return
|
|
766
|
+
return assetType(known.asset);
|
|
527
767
|
if ('array' in known) {
|
|
528
768
|
const inner = csType(values.flatMap((v) => (v && typeof v === 'object' && 'array' in v ? v.array : [])));
|
|
529
769
|
return inner ? `${inner}[]` : undefined;
|
|
530
770
|
}
|
|
531
771
|
return undefined;
|
|
532
772
|
}
|
|
773
|
+
/** The C# type of an asset, by its file: a model imports as a GameObject, as a prefab does. */
|
|
774
|
+
export function assetType(path) {
|
|
775
|
+
if (/\.(prefab|glb|gltf)$/i.test(path))
|
|
776
|
+
return 'GameObject';
|
|
777
|
+
if (path.endsWith('.mat'))
|
|
778
|
+
return 'Material';
|
|
779
|
+
if (path.endsWith('.uxml'))
|
|
780
|
+
return 'VisualTreeAsset';
|
|
781
|
+
if (/\.(wav|mp3|ogg|m4a|aiff?|flac)$/i.test(path))
|
|
782
|
+
return 'AudioClip';
|
|
783
|
+
if (/\.(png|jpe?g|webp|tga)$/i.test(path))
|
|
784
|
+
return 'Texture2D';
|
|
785
|
+
if (path.startsWith('Assets/Terrains/'))
|
|
786
|
+
return 'TerrainData';
|
|
787
|
+
if (path.startsWith('Assets/Materials/Physics/'))
|
|
788
|
+
return 'PhysicsMaterial';
|
|
789
|
+
return 'Mesh';
|
|
790
|
+
}
|
|
533
791
|
function csValue(v, type) {
|
|
534
792
|
const f = (n) => `${Number.isInteger(n) ? n : n}f`;
|
|
535
793
|
if (v === null || type === undefined)
|
|
@@ -555,3 +813,31 @@ function csValue(v, type) {
|
|
|
555
813
|
}
|
|
556
814
|
return '';
|
|
557
815
|
}
|
|
816
|
+
/**
|
|
817
|
+
* The objects of a .glb that hold a mesh, as glTFast builds them under the model's root: one per node
|
|
818
|
+
* of its scene, named as the node is, or `Node-<index>` when it has no name.
|
|
819
|
+
*/
|
|
820
|
+
export function glbMeshNodes(file) {
|
|
821
|
+
if (!existsSync(file))
|
|
822
|
+
return [];
|
|
823
|
+
const bytes = readFileSync(file);
|
|
824
|
+
if (bytes.readUInt32LE(0) !== 0x46546c67)
|
|
825
|
+
return [];
|
|
826
|
+
const length = bytes.readUInt32LE(12);
|
|
827
|
+
const json = JSON.parse(bytes.subarray(20, 20 + length).toString('utf8'));
|
|
828
|
+
const nodes = json.nodes ?? [];
|
|
829
|
+
const out = [];
|
|
830
|
+
const walk = (index, path) => {
|
|
831
|
+
const node = nodes[index];
|
|
832
|
+
if (!node)
|
|
833
|
+
return;
|
|
834
|
+
const here = [...path, node.name || `Node-${index}`];
|
|
835
|
+
if (node.mesh !== undefined)
|
|
836
|
+
out.push(here);
|
|
837
|
+
for (const child of node.children ?? [])
|
|
838
|
+
walk(child, here);
|
|
839
|
+
};
|
|
840
|
+
for (const root of json.scenes?.[json.scene ?? 0]?.nodes ?? [])
|
|
841
|
+
walk(root, []);
|
|
842
|
+
return out;
|
|
843
|
+
}
|
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>;
|