@clarity-js/port 0.0.0-stage → 1.5.1
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/README.md +253 -2
- package/bin/clarity-port.js +68 -0
- package/package.json +21 -4
- package/src/fiber.js +277 -0
- package/src/index.js +153 -0
- package/src/react.js +999 -0
- package/src/three.js +614 -0
package/src/three.js
ADDED
|
@@ -0,0 +1,614 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @clarity-js/port — a three.js script, as a Clarity component.
|
|
3
|
+
*
|
|
4
|
+
* A three.js scene is usually built by a script: `new THREE.Mesh(geometry, material)`, a position
|
|
5
|
+
* set, `scene.add(mesh)`, and a function that runs every frame. @clarity-js/gl writes the same
|
|
6
|
+
* scene as markup. This reads the script, follows what it builds at its top level (objects made
|
|
7
|
+
* with `new`, their place, what is added to what), and writes that scene. What the script does
|
|
8
|
+
* every frame becomes `frame()`, with the same statements.
|
|
9
|
+
*
|
|
10
|
+
* What a rule cannot follow is not guessed at: an object made in a loop or by a function of the
|
|
11
|
+
* script, a texture, a raycaster. Those statements are kept in the component as a comment, each
|
|
12
|
+
* with the line it came from, and listed in the notes.
|
|
13
|
+
*
|
|
14
|
+
* It works in two steps: the script is first said as a React Three Fiber component (which is the
|
|
15
|
+
* same scene as JSX), and that goes through the React porter (fiber.js), so both ways into
|
|
16
|
+
* @clarity-js/gl share one set of rules.
|
|
17
|
+
*
|
|
18
|
+
* Author: Özdemir Şarman
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { portReact } from './react.js';
|
|
22
|
+
|
|
23
|
+
const LIGHTS = new Set(['AmbientLight', 'HemisphereLight', 'DirectionalLight', 'PointLight', 'SpotLight']);
|
|
24
|
+
const lower = (name) => name[0].toLowerCase() + name.slice(1);
|
|
25
|
+
/** What a three.js object can be told every frame, and a node of @clarity-js/gl too. */
|
|
26
|
+
const MOVES = new Set(['position', 'rotation', 'scale', 'visible']);
|
|
27
|
+
/** The components of @clarity-js/gl this may write: a component made from a script does not take one of their names. */
|
|
28
|
+
const GL_TAGS = new Set(['Scene', 'Mesh', 'Group', 'Orbit', 'Model', ...LIGHTS]);
|
|
29
|
+
const ORBIT = { minDistance: 'minDistance', maxDistance: 'maxDistance', rotateSpeed: 'rotateSpeed', zoomSpeed: 'zoomSpeed', enablePan: 'enablePan', minPolarAngle: 'minPolarAngle', maxPolarAngle: 'maxPolarAngle' };
|
|
30
|
+
|
|
31
|
+
/** Does this text look like a script that builds a three.js scene? (It imports three and makes a Scene.) */
|
|
32
|
+
export function isThreeScript(source) {
|
|
33
|
+
return /\bfrom\s+['"]three['"]/.test(source) && /\bnew\s+(?:\w+\.)?Scene\s*\(/.test(source) && !/\bfrom\s+['"]@react-three\//.test(source);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Ports a three.js script.
|
|
38
|
+
*
|
|
39
|
+
* @param {string} source
|
|
40
|
+
* @param {object} options
|
|
41
|
+
* @param {object} options.typescript the `typescript` module (the parser)
|
|
42
|
+
* @param {string} [options.filename] 'scene.js'
|
|
43
|
+
* @param {string} [options.name] the component's name (default: from the file's name, or 'World')
|
|
44
|
+
* @returns {import('./react.js').PortResult & { fiber: string }} `fiber`: the scene as a React Three Fiber component (the step in between)
|
|
45
|
+
*/
|
|
46
|
+
export function portThree(source, options = {}) {
|
|
47
|
+
const ts = options.typescript;
|
|
48
|
+
if (typeof ts?.createSourceFile !== 'function') throw new Error('portThree needs the `typescript` module with its JavaScript API (TypeScript 5 or 6; TypeScript 7.0 has none): portThree(source, { typescript })');
|
|
49
|
+
const filename = options.filename ?? 'scene.js';
|
|
50
|
+
const K = ts.SyntaxKind;
|
|
51
|
+
const sf = ts.createSourceFile(filename, source, ts.ScriptTarget.Latest, true, /\.ts$/.test(filename) ? ts.ScriptKind.TS : ts.ScriptKind.JS);
|
|
52
|
+
const raw = (n) => source.slice(n.getStart(sf), n.end);
|
|
53
|
+
/** A statement's text, with the lines after its first moved left by as much as the statement stood in. */
|
|
54
|
+
const dedent = (text, n) => { const col = sf.getLineAndCharacterOfPosition(n.getStart(sf)).character; return text.split('\n').map((l, i) => (i && col ? l.replace(new RegExp(`^[ \\t]{0,${col}}`), '') : l).replace(/\s+$/, '').replace(/\t/g, ' ')).join('\n'); };
|
|
55
|
+
const indent = (text, pad) => text.split('\n').map((l) => (l ? pad + l : l)).join('\n');
|
|
56
|
+
const lineOf = (n) => sf.getLineAndCharacterOfPosition(n.getStart(sf)).line + 1;
|
|
57
|
+
const base = filename.replace(/^.*[\\/]/, '').replace(/\.m?[jt]s$/, '');
|
|
58
|
+
let name = options.name ?? (/^[A-Za-z]/.test(base) && !/^(main|index|scene|app|script)$/i.test(base) ? base.split(/[^A-Za-z0-9]+/).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join('') : 'World');
|
|
59
|
+
if (GL_TAGS.has(name)) name += 'World';
|
|
60
|
+
const notes = [];
|
|
61
|
+
const todo = (n, text) => notes.push({ line: lineOf(n), level: 'todo', text });
|
|
62
|
+
const done = (n, text) => notes.push({ line: lineOf(n), level: 'done', text });
|
|
63
|
+
const isFunction = (n) => !!n && (n.kind === K.ArrowFunction || n.kind === K.FunctionExpression || n.kind === K.FunctionDeclaration);
|
|
64
|
+
|
|
65
|
+
// ── names from three ──
|
|
66
|
+
const fromThree = new Set(); // names imported from 'three' one by one
|
|
67
|
+
const addons = new Set(); // … and from three/addons/… (OrbitControls, GLTFLoader)
|
|
68
|
+
let star = 'THREE';
|
|
69
|
+
const otherImports = [];
|
|
70
|
+
for (const s of sf.statements) {
|
|
71
|
+
if (s.kind !== K.ImportDeclaration) continue;
|
|
72
|
+
const spec = s.moduleSpecifier.text, c = s.importClause;
|
|
73
|
+
if (spec === 'three') { for (const e of c?.namedBindings?.elements ?? []) fromThree.add(e.name.text); if (c?.namedBindings?.name) star = c.namedBindings.name.text; continue; }
|
|
74
|
+
if (/^three\//.test(spec)) { for (const e of c?.namedBindings?.elements ?? []) addons.add(e.name.text); if (c?.name) addons.add(c.name.text); continue; }
|
|
75
|
+
otherImports.push(s);
|
|
76
|
+
}
|
|
77
|
+
/** `new THREE.Mesh(…)` → 'Mesh' (also `new Mesh(…)` imported by name, and `new OrbitControls(…)`). */
|
|
78
|
+
const made = (e) => {
|
|
79
|
+
if (!e || e.kind !== K.NewExpression) return null;
|
|
80
|
+
const c = e.expression;
|
|
81
|
+
if (c.kind === K.PropertyAccessExpression && c.expression.kind === K.Identifier && c.expression.text === star) return c.name.text;
|
|
82
|
+
if (c.kind === K.Identifier && (fromThree.has(c.text) || addons.has(c.text))) return c.text;
|
|
83
|
+
return null;
|
|
84
|
+
};
|
|
85
|
+
/** A top-level function by its name: `function f() {}` or `const f = () => {}`. */
|
|
86
|
+
const functionNamed = (id) => {
|
|
87
|
+
for (const s of sf.statements) {
|
|
88
|
+
if (s.kind === K.FunctionDeclaration && s.name?.text === id && s.body) return { fn: s, statement: s };
|
|
89
|
+
if (s.kind === K.VariableStatement) for (const d of s.declarationList.declarations) if (d.name.kind === K.Identifier && d.name.text === id && (d.initializer?.kind === K.ArrowFunction || d.initializer?.kind === K.FunctionExpression)) return { fn: d.initializer, statement: s };
|
|
90
|
+
}
|
|
91
|
+
return null;
|
|
92
|
+
};
|
|
93
|
+
/** The names a piece of code reads or writes (not the names of properties). */
|
|
94
|
+
const namesIn = (node, out = new Set()) => {
|
|
95
|
+
(function walk(n) {
|
|
96
|
+
if (n.kind === K.Identifier) {
|
|
97
|
+
const p = n.parent;
|
|
98
|
+
if (!(p.kind === K.PropertyAccessExpression && p.name === n) && !(p.kind === K.PropertyAssignment && p.name === n) && !(p.kind === K.MethodDeclaration && p.name === n)) out.add(n.text);
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
ts.forEachChild(n, walk);
|
|
102
|
+
})(node);
|
|
103
|
+
return out;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
// ── the function that runs every frame ──
|
|
107
|
+
// `renderer.setAnimationLoop(f)`, or a function that asks for the next frame with itself.
|
|
108
|
+
let loop = null; // { fn, name, statement }
|
|
109
|
+
const handedToRenderer = /\.setAnimationLoop\(\s*([A-Za-z_$][\w$]*)\s*\)/.exec(source)?.[1] ?? null;
|
|
110
|
+
{ const found = handedToRenderer ? functionNamed(handedToRenderer) : null; if (found) loop = { fn: found.fn, name: handedToRenderer, statement: found.statement }; }
|
|
111
|
+
if (!loop) for (const s of sf.statements) {
|
|
112
|
+
const ids = s.kind === K.FunctionDeclaration && s.name ? [s.name.text] : s.kind === K.VariableStatement ? s.declarationList.declarations.map((d) => (d.name.kind === K.Identifier ? d.name.text : null)) : [];
|
|
113
|
+
for (const id of ids) {
|
|
114
|
+
const found = id ? functionNamed(id) : null;
|
|
115
|
+
if (found && found.statement === s && new RegExp(`requestAnimationFrame\\(\\s*${id}\\s*\\)`).test(raw(found.fn.body))) loop = { fn: found.fn, name: id, statement: s };
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// ── the script as one list of statements ──
|
|
120
|
+
// Many scripts declare their names at the top (`let camera, scene, renderer;`) and build the scene
|
|
121
|
+
// in a function they call once (`init()`). Its statements are read where it is called.
|
|
122
|
+
const built = new Set(); // the statements of the functions read this way
|
|
123
|
+
const flat = (function flatten(statements, depth) {
|
|
124
|
+
const out = [];
|
|
125
|
+
for (const s of statements) {
|
|
126
|
+
const e = s.kind === K.ExpressionStatement ? (s.expression.kind === K.AwaitExpression ? s.expression.expression : s.expression) : null;
|
|
127
|
+
const call = e?.kind === K.CallExpression && e.expression.kind === K.Identifier && !e.arguments.length ? e.expression.text : null;
|
|
128
|
+
const found = call && call !== loop?.name && depth < 3 ? functionNamed(call) : null;
|
|
129
|
+
if (found && found.fn.body?.kind === K.Block && !found.fn.parameters.length && !built.has(found.statement)) { built.add(found.statement); out.push(...flatten([...found.fn.body.statements], depth + 1)); continue; }
|
|
130
|
+
out.push(s);
|
|
131
|
+
}
|
|
132
|
+
return out;
|
|
133
|
+
})([...sf.statements], 0);
|
|
134
|
+
// a loop written where it is handed over: renderer.setAnimationLoop(() => { … })
|
|
135
|
+
if (!loop) for (const s of flat) {
|
|
136
|
+
const e = s.kind === K.ExpressionStatement && s.expression.kind === K.CallExpression ? s.expression : null;
|
|
137
|
+
if (e?.expression.kind === K.PropertyAccessExpression && e.expression.name.text === 'setAnimationLoop' && isFunction(e.arguments[0])) loop = { fn: e.arguments[0], name: null, statement: s };
|
|
138
|
+
}
|
|
139
|
+
const idle = new Set(loop?.name ? [loop.name] : []); // functions a call of which is housekeeping: the loop itself (a call of it draws again), and those that only do housekeeping
|
|
140
|
+
const orphaned = new Set(); // names given a value in statements that were left out (inside a loader's callback)
|
|
141
|
+
// the functions of the script that the loop calls with nothing (`update(); render();`) are read as part of it
|
|
142
|
+
const inLoop = new Map(); // a function's name → its statement
|
|
143
|
+
const loopStatements = [];
|
|
144
|
+
if (loop && loop.fn.body.kind === K.Block) {
|
|
145
|
+
(function gather(statements, depth) {
|
|
146
|
+
for (const s of statements) {
|
|
147
|
+
const call = s.kind === K.ExpressionStatement && s.expression.kind === K.CallExpression && s.expression.expression.kind === K.Identifier && !s.expression.arguments.length ? s.expression.expression.text : null;
|
|
148
|
+
const found = call && call !== loop.name && depth < 3 ? functionNamed(call) : null;
|
|
149
|
+
if (found && found.fn.body.kind === K.Block && !found.fn.parameters.length && !built.has(found.statement)) { inLoop.set(call, found.statement); gather(found.fn.body.statements, depth + 1); continue; }
|
|
150
|
+
loopStatements.push(s);
|
|
151
|
+
}
|
|
152
|
+
})(loop.fn.body.statements, 0);
|
|
153
|
+
}
|
|
154
|
+
const partOfLoop = new Set([loop?.statement, ...inLoop.values()].filter(Boolean));
|
|
155
|
+
for (const name of inLoop.keys()) idle.add(name);
|
|
156
|
+
|
|
157
|
+
// ── what the script builds ──
|
|
158
|
+
const things = new Map(); // a name → { tag, attrs: [text], inner: [text], kids: [thing], line }
|
|
159
|
+
const geometries = new Map(), materials = new Map(), loaders = new Map();
|
|
160
|
+
let sceneName = null, cameraName = null, rendererName = null, clockName = null, controlsName = null, meterName = null;
|
|
161
|
+
const pending = new Set(); // names declared with nothing (`let camera, scene;`): what they are is said later
|
|
162
|
+
const canvas = { attrs: [], camera: {}, background: null, fog: null };
|
|
163
|
+
const controls = { attrs: [], dropped: [] };
|
|
164
|
+
const top = []; // the scene's children, in order
|
|
165
|
+
const leftover = []; // statements with no rule
|
|
166
|
+
let boilerplate = 0, shadowSettings = 0, anonymous = 0;
|
|
167
|
+
const usesModel = () => [...things.values(), ...top].some((t) => t.tag === 'Model') || modelMade;
|
|
168
|
+
let modelMade = false;
|
|
169
|
+
|
|
170
|
+
const geometryTag = (type, e) => `<${lower(type)}${e.arguments?.length ? ` args={[${e.arguments.map(raw).join(', ')}]}` : ''} />`;
|
|
171
|
+
function materialTag(type, e) {
|
|
172
|
+
const o = e.arguments?.[0];
|
|
173
|
+
const attrs = [];
|
|
174
|
+
if (o?.kind === K.ObjectLiteralExpression) for (const p of o.properties) {
|
|
175
|
+
if (p.kind === K.PropertyAssignment) attrs.push(`${p.name.getText(sf)}={${raw(p.initializer)}}`);
|
|
176
|
+
else if (p.kind === K.ShorthandPropertyAssignment) attrs.push(`${p.name.text}={${p.name.text}}`);
|
|
177
|
+
} else if (o) todo(e, `the settings of this ${type} are not written out here (${raw(o)}): write them on the <Mesh>`);
|
|
178
|
+
return `<${lower(type)}${attrs.length ? ' ' + attrs.join(' ') : ''} />`;
|
|
179
|
+
}
|
|
180
|
+
/** A thing from `new THREE.X(…)`: a mesh, a group, a light. Null when X is not something that stands in a scene by a rule. */
|
|
181
|
+
function thing(type, e, at) {
|
|
182
|
+
if (type === 'Mesh') {
|
|
183
|
+
const [g, m] = e.arguments ?? [];
|
|
184
|
+
const inner = [];
|
|
185
|
+
for (const [arg, table, tag, what] of [[g, geometries, geometryTag, 'geometry'], [m, materials, materialTag, 'material']]) {
|
|
186
|
+
if (!arg) continue;
|
|
187
|
+
const t = made(arg);
|
|
188
|
+
if (t) inner.push(tag(t, arg));
|
|
189
|
+
else if (arg.kind === K.Identifier && table.has(arg.text)) inner.push(table.get(arg.text));
|
|
190
|
+
else todo(arg, `this mesh's ${what} (${raw(arg)}) is not made where the script can be followed: write it on the <Mesh>`);
|
|
191
|
+
}
|
|
192
|
+
return { tag: 'mesh', attrs: [], inner, kids: [], line: lineOf(at) };
|
|
193
|
+
}
|
|
194
|
+
if (type === 'Group' || type === 'Object3D') return { tag: 'group', attrs: [], inner: [], kids: [], line: lineOf(at) };
|
|
195
|
+
if (LIGHTS.has(type)) return { tag: lower(type), attrs: e.arguments?.length ? [`args={[${e.arguments.map(raw).join(', ')}]}`] : [], inner: [], kids: [], line: lineOf(at), light: true };
|
|
196
|
+
return null;
|
|
197
|
+
}
|
|
198
|
+
/** Housekeeping a <Scene> does by itself: the renderer's size and render calls, the camera's aspect, asking for the next frame. */
|
|
199
|
+
const isBoilerplate = (text) => /^[\w.]+\.appendChild\(\s*\w+\.domElement\s*\)/.test(text) || /^requestAnimationFrame\(/.test(text)
|
|
200
|
+
|| (!!clockName && new RegExp(`^${clockName}\\.(?:update|connect|start|reset)\\(`).test(text))
|
|
201
|
+
|| (/^([A-Za-z_$][\w$]*)\(\)$/.test(text) && idle.has(text.slice(0, -2)))
|
|
202
|
+
|| (!!meterName && (new RegExp(`^${meterName}\\.`).test(text) || new RegExp(`\\.appendChild\\(\\s*${meterName}\\.dom(Element)?\\s*\\)$`).test(text)))
|
|
203
|
+
|| (!!rendererName && new RegExp(`^${rendererName}\\.(?:(?:setSize|setPixelRatio|setAnimationLoop|render)\\(|(?:outputColorSpace|outputEncoding|toneMapping|toneMappingExposure|shadowMap\\.type)\\s*=)`).test(text))
|
|
204
|
+
|| (!!cameraName && new RegExp(`^${cameraName}\\.(?:updateProjectionMatrix\\(|aspect\\s*=)`).test(text))
|
|
205
|
+
|| (!!controlsName && new RegExp(`^${controlsName}\\.update\\(`).test(text));
|
|
206
|
+
const axis = (p) => 'xyz'.indexOf(p);
|
|
207
|
+
/** The object a chain starts at: `a.b.c(…)` → 'a'. */
|
|
208
|
+
const rootOf = (n) => { let o = n; while (o.kind === K.PropertyAccessExpression || o.kind === K.CallExpression) o = o.expression; return o.kind === K.Identifier ? o.text : null; };
|
|
209
|
+
|
|
210
|
+
/** Where a thing is and how it is shown: `x.position.set(a, b, c)`, `x.rotation.y = v`, `x.castShadow = true`. True when a rule took it. */
|
|
211
|
+
function place(e, who, put, isThing) {
|
|
212
|
+
const text = raw(e);
|
|
213
|
+
let m;
|
|
214
|
+
if (e.kind === K.CallExpression) {
|
|
215
|
+
if ((m = new RegExp(`^${who}\\.(position|rotation|scale)\\.set\\(`).exec(text)) && e.arguments.length === 3) { put(m[1], `[${e.arguments.map(raw).join(', ')}]`); return true; }
|
|
216
|
+
if (new RegExp(`^${who}\\.scale\\.setScalar\\(`).test(text) && e.arguments[0]) { put('scale', raw(e.arguments[0])); return true; }
|
|
217
|
+
return false;
|
|
218
|
+
}
|
|
219
|
+
if (e.kind !== K.BinaryExpression || e.operatorToken.kind !== K.EqualsToken) return false;
|
|
220
|
+
const left = raw(e.left), value = raw(e.right);
|
|
221
|
+
if ((m = new RegExp(`^${who}\\.(position|rotation|scale)\\.([xyz])$`).exec(left))) { put(`${m[1]}-${m[2]}`, value); return true; }
|
|
222
|
+
if (isThing && (m = new RegExp(`^${who}\\.(castShadow|receiveShadow|visible|name|renderOrder|intensity|distance|decay|angle|penumbra)$`).exec(left))) { put(m[1], value); return true; }
|
|
223
|
+
return false;
|
|
224
|
+
}
|
|
225
|
+
const putOn = (t) => (prop, value) => t.attrs.push(value === 'true' ? prop : `${prop}={${value}}`);
|
|
226
|
+
|
|
227
|
+
/** `loader.load('fox.glb', (gltf) => { scene.add(gltf.scene) })` → a <Model>. True when a rule took it. */
|
|
228
|
+
function model(e, s) {
|
|
229
|
+
if (e.kind !== K.CallExpression || e.expression.kind !== K.PropertyAccessExpression || e.expression.name.text !== 'load') return false;
|
|
230
|
+
const on = e.expression.expression;
|
|
231
|
+
const type = on.kind === K.Identifier ? loaders.get(on.text) : made(on);
|
|
232
|
+
if (type !== 'GLTFLoader') return false;
|
|
233
|
+
const [url, cb] = e.arguments;
|
|
234
|
+
const p = isFunction(cb) && cb.parameters[0]?.name.kind === K.Identifier ? cb.parameters[0].name.text : null;
|
|
235
|
+
if (!url || !p || cb.body.kind !== K.Block) return false;
|
|
236
|
+
const t = { tag: 'Model', attrs: [`src={${raw(url)}}`], inner: [], kids: [], line: lineOf(s), name: `__${anonymous++}` };
|
|
237
|
+
let alias = null, parent = null, rest = 0;
|
|
238
|
+
for (const st of cb.body.statements) {
|
|
239
|
+
// const model = gltf.scene
|
|
240
|
+
if (st.kind === K.VariableStatement && st.declarationList.declarations.length === 1 && st.declarationList.declarations[0].name.kind === K.Identifier && raw(st.declarationList.declarations[0].initializer ?? st) === `${p}.scene`) { alias = st.declarationList.declarations[0].name.text; continue; }
|
|
241
|
+
if (st.kind !== K.ExpressionStatement) { rest++; continue; }
|
|
242
|
+
const x = st.expression, text = raw(x);
|
|
243
|
+
const who = alias && new RegExp(`^${alias}\\b`).test(text) ? alias : `${p}.scene`;
|
|
244
|
+
const add = /^(\w+)\.add\(\s*([\w.]+)\s*\)$/.exec(text);
|
|
245
|
+
if (add && (add[2] === `${p}.scene` || add[2] === alias)) { parent = add[1] === sceneName ? top : things.get(add[1])?.kids ?? null; if (!parent) rest++; continue; }
|
|
246
|
+
if (text.startsWith(who + '.') && place(x, who.replace(/\./g, '\\.'), putOn(t), true)) continue;
|
|
247
|
+
rest++;
|
|
248
|
+
}
|
|
249
|
+
(function find(n) { if (n.kind === K.BinaryExpression && n.operatorToken.kind === K.EqualsToken && n.left.kind === K.Identifier) orphaned.add(n.left.text); ts.forEachChild(n, find); })(cb.body);
|
|
250
|
+
if (!parent) return false;
|
|
251
|
+
parent.push(t); t.placed = true; modelMade = true;
|
|
252
|
+
done(s, 'a model loaded with GLTFLoader is <Model src>: it is fetched, added and drawn by the scene');
|
|
253
|
+
if (rest) todo(cb, `what else the script does with the loaded model (${rest} statement${rest === 1 ? '' : 's'}) is left out: <Model onLoad={ (model, animator) => … }> hands the model over`);
|
|
254
|
+
return true;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** `id = new THREE.X(…)`, in a declaration or an assignment: what `id` is from here on. False when no rule knows X. */
|
|
258
|
+
function makes(id, type, e, s) {
|
|
259
|
+
if (type === 'Scene') sceneName = id;
|
|
260
|
+
else if (type === 'PerspectiveCamera') { cameraName = id; const [fov, , near, far] = e.arguments ?? []; if (fov) canvas.camera.fov = raw(fov); if (near) canvas.camera.near = raw(near); if (far) canvas.camera.far = raw(far); }
|
|
261
|
+
else if (type === 'OrthographicCamera') { cameraName = id; todo(s, 'an orthographic camera: use `orthographic()` from @clarity-js/gl'); }
|
|
262
|
+
else if (type === 'WebGLRenderer' || type === 'WebGPURenderer') rendererName = id;
|
|
263
|
+
else if (type === 'Clock' || type === 'Timer') clockName = id;
|
|
264
|
+
else if (type === 'OrbitControls') controlsName = id;
|
|
265
|
+
else if (type === 'GLTFLoader') loaders.set(id, type);
|
|
266
|
+
else if (type === 'Stats') meterName = id; // the frame-rate meter of three.js's examples: left out
|
|
267
|
+
else if (/Geometry$/.test(type)) geometries.set(id, geometryTag(type, e));
|
|
268
|
+
else if (/Material$/.test(type)) materials.set(id, materialTag(type, e));
|
|
269
|
+
else { const t = thing(type, e, s); if (!t) return false; t.name = id; things.set(id, t); }
|
|
270
|
+
return true;
|
|
271
|
+
}
|
|
272
|
+
/** One statement of the script (its top level, and the function that builds the scene). True when it was understood. */
|
|
273
|
+
function follow(s) {
|
|
274
|
+
if (s.kind === K.ImportDeclaration || partOfLoop.has(s) || built.has(s)) return true;
|
|
275
|
+
if (s.kind === K.VariableStatement) {
|
|
276
|
+
// a declaration is taken name by name: `let camera, scene;` says what they are later, `mesh = new …` is followed, the rest is left
|
|
277
|
+
const ds = s.declarationList.declarations, rest = [];
|
|
278
|
+
for (const d of ds) {
|
|
279
|
+
const id = d.name.kind === K.Identifier ? d.name.text : null;
|
|
280
|
+
if (id && !d.initializer) { pending.add(id); continue; }
|
|
281
|
+
const type = made(d.initializer);
|
|
282
|
+
if (!type || !id || !makes(id, type, d.initializer, s)) rest.push(d);
|
|
283
|
+
}
|
|
284
|
+
if (ds.length === 1) return !rest.length;
|
|
285
|
+
leftover.push(...rest); // (each name on its own: a VariableDeclaration)
|
|
286
|
+
return true;
|
|
287
|
+
}
|
|
288
|
+
if (s.kind !== K.ExpressionStatement) return false;
|
|
289
|
+
const e = s.expression, text = raw(e);
|
|
290
|
+
// camera = new THREE.PerspectiveCamera(…): a name declared before, made here
|
|
291
|
+
if (e.kind === K.BinaryExpression && e.operatorToken.kind === K.EqualsToken && e.left.kind === K.Identifier && made(e.right) && makes(e.left.text, made(e.right), e.right, s)) return true;
|
|
292
|
+
if (model(e, s)) return true;
|
|
293
|
+
// the first call of the loop, and of a function that is read as part of it
|
|
294
|
+
if (e.kind === K.CallExpression && e.expression.kind === K.Identifier && !e.arguments.length && (e.expression.text === loop?.name || inLoop.has(e.expression.text))) { boilerplate++; return true; }
|
|
295
|
+
if (rendererName && text === `${rendererName}.shadowMap.enabled = true`) { canvas.attrs.push('shadows'); return true; }
|
|
296
|
+
// the controls: what <Orbit> has too is carried over, the rest is said
|
|
297
|
+
if (controlsName && rootOf(e.kind === K.BinaryExpression ? e.left : e) === controlsName) {
|
|
298
|
+
let m;
|
|
299
|
+
if (e.kind === K.CallExpression && new RegExp(`^${controlsName}\\.target\\.set\\(`).test(text)) controls.attrs.push(`target={[${e.arguments.map(raw).join(', ')}]}`);
|
|
300
|
+
else if (e.kind === K.BinaryExpression && (m = new RegExp(`^${controlsName}\\.(\\w+)$`).exec(raw(e.left))) && ORBIT[m[1]]) controls.attrs.push(`${ORBIT[m[1]]}={${raw(e.right)}}`);
|
|
301
|
+
else if (e.kind === K.BinaryExpression && (m = new RegExp(`^${controlsName}\\.(\\w+)$`).exec(raw(e.left))) && !/^(enableDamping|dampingFactor)$/.test(m[1])) controls.dropped.push(m[1]);
|
|
302
|
+
else boilerplate++;
|
|
303
|
+
return true;
|
|
304
|
+
}
|
|
305
|
+
if (isBoilerplate(text) || /^window\.addEventListener\(\s*['"]resize['"]/.test(text)) { boilerplate++; return true; }
|
|
306
|
+
// renderer.setClearColor(c): the picture's background
|
|
307
|
+
if (rendererName && e.kind === K.CallExpression && text.startsWith(`${rendererName}.setClearColor(`) && e.arguments[0]) { canvas.background ??= made(e.arguments[0]) === 'Color' && e.arguments[0].arguments?.[0] ? raw(e.arguments[0].arguments[0]) : raw(e.arguments[0]); return true; }
|
|
308
|
+
|
|
309
|
+
// a.add(b, new THREE.X(…))
|
|
310
|
+
if (e.kind === K.CallExpression && e.expression.kind === K.PropertyAccessExpression && e.expression.name.text === 'add' && e.expression.expression.kind === K.Identifier) {
|
|
311
|
+
const into = e.expression.expression.text;
|
|
312
|
+
const parent = into === sceneName ? top : things.get(into)?.kids;
|
|
313
|
+
if (!parent) return false;
|
|
314
|
+
for (const a of e.arguments) {
|
|
315
|
+
let t = a.kind === K.Identifier ? things.get(a.text) : null;
|
|
316
|
+
if (!t) { const type = made(a); t = type ? thing(type, a, s) : null; if (t) t.name = `__${anonymous++}`; }
|
|
317
|
+
if (!t) { todo(a, `${raw(a)} is added to the scene, and the script does not make it where a rule can follow (an object made by a function or in a loop is a <list> over data here, or a component of its own)`); continue; }
|
|
318
|
+
if (t.placed) { todo(a, `${raw(a)} is added a second time: an object stands in one place`); continue; }
|
|
319
|
+
parent.push(t); t.placed = true;
|
|
320
|
+
}
|
|
321
|
+
return true;
|
|
322
|
+
}
|
|
323
|
+
// scene.background = new THREE.Color(c) | c ; scene.fog = new THREE.Fog(c, near, far)
|
|
324
|
+
if (e.kind === K.BinaryExpression && e.operatorToken.kind === K.EqualsToken && sceneName) {
|
|
325
|
+
const left = raw(e.left), right = e.right;
|
|
326
|
+
if (left === `${sceneName}.background`) {
|
|
327
|
+
if (made(right) === 'Color' && right.arguments?.[0]) { canvas.background = raw(right.arguments[0]); return true; }
|
|
328
|
+
if (right.kind === K.NumericLiteral || right.kind === K.StringLiteral) { canvas.background = raw(right); return true; }
|
|
329
|
+
return false;
|
|
330
|
+
}
|
|
331
|
+
if (left === `${sceneName}.fog` && made(right) === 'Fog' && right.arguments?.length) {
|
|
332
|
+
const [c, ...rest] = right.arguments;
|
|
333
|
+
const colour = c.kind === K.NumericLiteral || c.kind === K.StringLiteral ? raw(c) : made(c) === 'Color' && c.arguments?.[0] ? raw(c.arguments[0]) : raw(c) === `${sceneName}.background` && canvas.background ? canvas.background : null;
|
|
334
|
+
if (!colour) return false;
|
|
335
|
+
canvas.fog = [colour, ...rest.map(raw)]; return true;
|
|
336
|
+
}
|
|
337
|
+
if (left === `${sceneName}.fog` && made(right) === 'FogExp2' && right.arguments?.length && (right.arguments[0].kind === K.NumericLiteral || right.arguments[0].kind === K.StringLiteral)) { canvas.fogExp = right.arguments.map(raw); return true; }
|
|
338
|
+
}
|
|
339
|
+
// where a thing is: x.position.set(a, b, c), x.rotation.y = v, x.scale.setScalar(s), x.castShadow = true, camera.lookAt(…)
|
|
340
|
+
const who = rootOf(e.kind === K.BinaryExpression ? e.left : e);
|
|
341
|
+
const isCamera = !!who && who === cameraName, t = who ? things.get(who) : null;
|
|
342
|
+
if (!isCamera && !t) return false;
|
|
343
|
+
if (t) {
|
|
344
|
+
if (place(e, who, putOn(t), true)) return true;
|
|
345
|
+
if (e.kind === K.CallExpression && new RegExp(`^${who}\\.shadow\\.mapSize\\.set\\(`).test(text) && e.arguments[0]) { t.attrs.push(`shadow-mapSize={[${e.arguments.map(raw).join(', ')}]}`); return true; }
|
|
346
|
+
if (t.light && new RegExp(`^${who}\\.shadow\\.`).test(text)) { shadowSettings++; return true; }
|
|
347
|
+
return false;
|
|
348
|
+
}
|
|
349
|
+
if (place(e, who, (prop, value) => { const m = /^(\w+)-([xyz])$/.exec(prop); if (m) { const p = (canvas.cameraParts ??= {}); (p[m[1]] ??= ['0', '0', '0'])[axis(m[2])] = value; } else canvas.camera[prop] = value; }, false)) return true;
|
|
350
|
+
if (e.kind === K.CallExpression && new RegExp(`^${who}\\.lookAt\\(`).test(text)) {
|
|
351
|
+
if (e.arguments.length === 3) { canvas.camera.lookAt = `[${e.arguments.map(raw).join(', ')}]`; return true; }
|
|
352
|
+
if (e.arguments.length === 1 && raw(e.arguments[0]) === `${sceneName}.position`) { canvas.camera.lookAt = '[0, 0, 0]'; return true; }
|
|
353
|
+
}
|
|
354
|
+
return false;
|
|
355
|
+
}
|
|
356
|
+
for (const s of flat) if (!follow(s)) leftover.push(s);
|
|
357
|
+
|
|
358
|
+
if (!sceneName && !top.length) return { clarity: null, shared: null, components: [], notes: [{ line: 1, level: 'todo', text: 'no three.js scene is built at the top of this script (no `new THREE.Scene()`): there is nothing a rule can follow' }], fiber: '' };
|
|
359
|
+
|
|
360
|
+
// ── what runs after the scene is built ──
|
|
361
|
+
// The loop, the functions it calls, a listener: they name the script's objects. A thing that is
|
|
362
|
+
// in the ported scene is reached through a ref. What is not there (a raycaster, an object made
|
|
363
|
+
// in a loop) is not: a statement that uses it is kept as a comment, and said.
|
|
364
|
+
const placed = (id) => things.get(id)?.placed === true;
|
|
365
|
+
const lost = new Set([star, ...fromThree, ...addons, sceneName, cameraName, rendererName, clockName, controlsName, meterName, ...things.keys(), ...geometries.keys(), ...materials.keys(), ...loaders.keys(), ...[...orphaned].filter((n) => pending.has(n))].filter((n) => n && !placed(n)));
|
|
366
|
+
/** A statement of the script, or one name of a declaration of several (`let a = 1, b = 2;`). */
|
|
367
|
+
const isName = (s) => s.kind === K.VariableDeclaration;
|
|
368
|
+
const wordOf = (d) => (d.parent.flags & ts.NodeFlags.Const ? 'const' : d.parent.flags & ts.NodeFlags.Let ? 'let' : 'var');
|
|
369
|
+
const textOf = (s, text = dedent(raw(s), s)) => (isName(s) ? `${wordOf(s)} ${text};` : text);
|
|
370
|
+
const declared = (s) => (s.kind === K.VariableStatement ? s.declarationList.declarations.flatMap((d) => [...namesIn(d.name)])
|
|
371
|
+
: isName(s) ? [...namesIn(s.name)]
|
|
372
|
+
: s.kind === K.ExpressionStatement && s.expression.kind === K.BinaryExpression && s.expression.operatorToken.kind === K.EqualsToken && s.expression.left.kind === K.Identifier && pending.has(s.expression.left.text) ? [s.expression.left.text]
|
|
373
|
+
: s.name?.text ? [s.name.text] : []);
|
|
374
|
+
/** What a statement that does not run takes with it: the names it declares, and the names declared bare that it gives a value. */
|
|
375
|
+
const goneWith = (s) => { const out = new Set(declared(s)); (function find(n) { if (n.kind === K.BinaryExpression && n.operatorToken.kind === K.EqualsToken && n.left.kind === K.Identifier && pending.has(n.left.text)) out.add(n.left.text); ts.forEachChild(n, find); })(s); return out; };
|
|
376
|
+
const moved = new Set(); // the things that are touched after the scene is built: they get a ref
|
|
377
|
+
const short = (s) => { const t = textOf(s, raw(s)), line = t.split('\n')[0]; return `\`${line.slice(0, 56)}${line.length > 56 || t.includes('\n') ? '…' : ''}\``; };
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* A piece of the script with its names said as a React Three Fiber component says them: a thing
|
|
381
|
+
* → its ref; in the loop, the clock → the frame's own.
|
|
382
|
+
* `told`: what it tells a thing that a node here is not told (`hub.material`); `strangers`: what it uses that is not in the ported scene.
|
|
383
|
+
*/
|
|
384
|
+
function reworded(node, { frame = false, gone = lost, delta = 'delta', elapsedAlias = null } = {}) {
|
|
385
|
+
const edits = [], told = new Set(), strangers = new Set(), refs = new Set(), ofStar = [];
|
|
386
|
+
(function walk(n) {
|
|
387
|
+
if (frame && clockName && n.kind === K.CallExpression && n.expression.kind === K.PropertyAccessExpression && n.expression.expression.kind === K.Identifier && n.expression.expression.text === clockName) {
|
|
388
|
+
const m = n.expression.name.text;
|
|
389
|
+
if (m === 'getDelta') { edits.push([n, delta]); return; }
|
|
390
|
+
if (m === 'getElapsedTime' || m === 'getElapsed') { edits.push([n, 'state.clock.elapsedTime']); return; }
|
|
391
|
+
}
|
|
392
|
+
if (frame && clockName && n.kind === K.PropertyAccessExpression && n.expression.kind === K.Identifier && n.expression.text === clockName && n.name.text === 'elapsedTime') { edits.push([n, 'state.clock.elapsedTime']); return; }
|
|
393
|
+
if (n.kind === K.PropertyAccessExpression && n.expression.kind === K.Identifier && placed(n.expression.text) && !MOVES.has(n.name.text)) told.add(`${n.expression.text}.${n.name.text}`);
|
|
394
|
+
// a place is an array of three numbers here: `.x`, `.set(a, b, c)` and `.setScalar(s)` are said again; a vector's other methods are not
|
|
395
|
+
if (n.kind === K.PropertyAccessExpression && n.expression.kind === K.Identifier && placed(n.expression.text) && /^(position|rotation|scale)$/.test(n.name.text)) {
|
|
396
|
+
const p = n.parent, call = p.kind === K.PropertyAccessExpression && p.expression === n && p.parent.kind === K.CallExpression && p.parent.expression === p;
|
|
397
|
+
const ok = p.kind === K.PropertyAccessExpression && p.expression === n && (/^[xyz]$/.test(p.name.text) || (call && (p.name.text === 'set' ? p.parent.arguments.length === 3 : p.name.text === 'setScalar')));
|
|
398
|
+
if (!ok) told.add(`${n.expression.text}.${n.name.text}${p.kind === K.PropertyAccessExpression && p.expression === n ? '.' + p.name.text : ''}`);
|
|
399
|
+
}
|
|
400
|
+
if (n.kind === K.Identifier) {
|
|
401
|
+
const p = n.parent;
|
|
402
|
+
if ((p.kind === K.PropertyAccessExpression && p.name === n) || (p.kind === K.PropertyAssignment && p.name === n)) return;
|
|
403
|
+
if (placed(n.text)) { refs.add(n.text); edits.push([n, p.kind === K.ShorthandPropertyAssignment ? `${n.text}: ${n.text}.current` : `${n.text}.current`]); }
|
|
404
|
+
else if (elapsedAlias && n.text === elapsedAlias) edits.push([n, 'state.clock.elapsedTime']);
|
|
405
|
+
else if (gone.has(n.text)) { strangers.add(n.text); if (n.text === star && p.kind === K.PropertyAccessExpression) ofStar.push(`${star}.${p.name.text}`); }
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
ts.forEachChild(n, walk);
|
|
409
|
+
})(node);
|
|
410
|
+
let text = '', at = node.getStart(sf);
|
|
411
|
+
for (const [n, to] of edits.sort((a, b) => a[0].getStart(sf) - b[0].getStart(sf))) { text += source.slice(at, n.getStart(sf)) + to; at = n.end; }
|
|
412
|
+
return { text: dedent(text + source.slice(at, node.end), node), told, strangers, refs, ofStar };
|
|
413
|
+
}
|
|
414
|
+
/** Why a statement could not be carried over. */
|
|
415
|
+
function why(r) {
|
|
416
|
+
if (r.told.size && [...r.told].every((n) => /\.(position|rotation|scale)\b/.test(n))) return `it uses ${[...r.told].map((n) => `\`${n}\``).join(', ')}: a node's position, rotation and scale are arrays of three numbers here (\`.x\`, \`.set(a, b, c)\` and \`.setScalar(s)\` are carried over; a vector's other methods are not)`;
|
|
417
|
+
if (r.told.size) return `it uses ${[...r.told].map((n) => `\`${n}\``).join(', ')}: a node here is told its position, rotation, scale and whether it is seen. A colour or a material's setting is a prop of the <Mesh>, bound to a state`;
|
|
418
|
+
const names = [...r.strangers];
|
|
419
|
+
const classes = names.filter((n) => n === star || fromThree.has(n) || addons.has(n));
|
|
420
|
+
if (classes.length) return `it uses three.js's ${classes.map((n) => `\`${n === star ? r.ofStar?.[0] ?? star : n}\``).join(', ')}, for which there is no rule (the math and the helpers of @clarity-js/gl are in the clarity-gl skill)`;
|
|
421
|
+
if (cameraName && names.includes(cameraName)) return `it moves or reads the camera (\`${cameraName}\`): here the camera is the <Scene>'s \`camera\` prop (a state), or an <Orbit>`;
|
|
422
|
+
return `it uses ${names.map((n) => `\`${n}\``).join(', ')}, which ${names.length === 1 ? 'is' : 'are'} not in the ported scene (made by a statement that is kept as a comment, or not an object a rule could place)`;
|
|
423
|
+
}
|
|
424
|
+
/** Statements that run later (the loop's, a function's): each as it is said here, or as a comment when it uses what is not here. */
|
|
425
|
+
function later(list, options = {}) {
|
|
426
|
+
const gone = new Set(options.gone ?? lost), lines = [], said = [], refs = new Set();
|
|
427
|
+
let live = 0;
|
|
428
|
+
for (const s of list) {
|
|
429
|
+
if (isBoilerplate(raw(s).replace(/;\s*$/, ''))) continue;
|
|
430
|
+
const r = reworded(s, { ...options, gone });
|
|
431
|
+
if (r.strangers.size || r.told.size) {
|
|
432
|
+
for (const n of goneWith(s)) gone.add(n);
|
|
433
|
+
lines.push(...dedent(raw(s), s).split('\n').map((l) => `// TODO(port): ${l}`));
|
|
434
|
+
said.push([s, `${short(s)}: ${why(r)}. The statement is kept as a comment`]);
|
|
435
|
+
continue;
|
|
436
|
+
}
|
|
437
|
+
for (const id of r.refs) refs.add(id);
|
|
438
|
+
lines.push(r.text); live++;
|
|
439
|
+
}
|
|
440
|
+
return { lines, live, said, refs };
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
const REASONS = [
|
|
444
|
+
[(s, t) => !!sceneName && new RegExp(`^${sceneName}\\.(background|fog)\\s*=`).test(t), 'the scene\'s background or fog is worked out here in a way no rule reads (a colour a rule reads is written out: `0x101820`, `\'skyblue\'`): write it on the <Scene>'],
|
|
445
|
+
[(s, t) => /\bRaycaster\b/.test(t), 'picking with a Raycaster: here a <Mesh> hears `on:click` and the pointer events (the <Scene> already has `events={ pointerEvents }`)'],
|
|
446
|
+
[(s, t) => /\bTextureLoader\b|Loader\b[^\n]*\.load\(|\.load\(/.test(t), 'a picture or a file is loaded: a texture is `loadTexture(url)` with the `textured` material, a model is <Model src>'],
|
|
447
|
+
[(s, t) => /\bEffectComposer\b|\b\w+Pass\b/.test(t), 'post-processing: here it is the `effects` prop of <Scene> (the clarity-gl-polish skill)'],
|
|
448
|
+
[(s, t) => (s.kind === K.ForStatement || s.kind === K.ForOfStatement || s.kind === K.ForInStatement || s.kind === K.WhileStatement || /\.forEach\(|Array\.from\(/.test(t)) && /\bnew\s/.test(t), 'objects made in a loop: here that is a <list> over data (an array of places), with one <Mesh> per row'],
|
|
449
|
+
];
|
|
450
|
+
// Housekeeping first: a function that only keeps the renderer and the camera in step with the
|
|
451
|
+
// window (the resize listener's, a `render()` that only draws) is not needed, and neither is a call of it.
|
|
452
|
+
const housekeeping = new Set();
|
|
453
|
+
const functionOf = (s) => (s.kind === K.FunctionDeclaration ? s : s.kind === K.VariableStatement && s.declarationList.declarations.length === 1 && isFunction(s.declarationList.declarations[0].initializer) ? s.declarationList.declarations[0].initializer : isName(s) && isFunction(s.initializer) ? s.initializer : null);
|
|
454
|
+
{ const plainCheck = isBoilerplate; for (const s of leftover) { const fn = functionOf(s); if (fn?.body?.kind === K.Block && fn.body.statements.length && fn.body.statements.every((x) => plainCheck(raw(x).replace(/;\s*$/, '')))) { housekeeping.add(s); boilerplate += fn.body.statements.length; for (const n of declared(s)) { lost.add(n); idle.add(n); } } } }
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* Every statement no rule took, said as what it is here: `kept` (a declaration that runs as it
|
|
458
|
+
* did), `atMount` (a statement that runs once the scene is there), or `commented`. What a
|
|
459
|
+
* commented statement declared is lost to the others, so this is done again until nothing more is lost.
|
|
460
|
+
*/
|
|
461
|
+
function classify() {
|
|
462
|
+
const out = { kept: [], atMount: [], commented: [], todos: [], refs: new Set(), grew: false };
|
|
463
|
+
const lose = (s) => { for (const n of goneWith(s)) if (!lost.has(n)) { lost.add(n); out.grew = true; } };
|
|
464
|
+
const comment = (s, because, said) => { lose(s); out.commented.push({ s, why: because }); out.todos.push([s, said ?? `${short(s)}: ${because}. The statement is kept in the component as a comment`]); };
|
|
465
|
+
const take = (r) => { for (const id of r.refs) out.refs.add(id); for (const x of r.said ?? []) out.todos.push(x); };
|
|
466
|
+
for (const s of leftover) {
|
|
467
|
+
if (housekeeping.has(s)) continue;
|
|
468
|
+
const text = raw(s);
|
|
469
|
+
if (s.kind === K.ExpressionStatement && isBoilerplate(text.replace(/;\s*$/, ''))) continue;
|
|
470
|
+
const isDeclaration = s.kind === K.VariableStatement || isName(s) || s.kind === K.ClassDeclaration || s.kind === K.FunctionDeclaration;
|
|
471
|
+
// it names nothing of three.js: it runs as it is (a constant the loop reads, a key listener)
|
|
472
|
+
if (![...namesIn(s)].some((n) => lost.has(n) || placed(n))) { (isDeclaration ? out.kept : out.atMount).push({ s, text: textOf(s) }); continue; }
|
|
473
|
+
const fn = functionOf(s);
|
|
474
|
+
const reason = REASONS.find(([test]) => test(s, text))?.[1];
|
|
475
|
+
// a function of the script: its statements are taken one by one
|
|
476
|
+
if (!reason && fn?.body?.kind === K.Block) {
|
|
477
|
+
const r = later(fn.body.statements);
|
|
478
|
+
if (!r.lines.length) { lose(s); for (const n of declared(s)) idle.add(n); continue; } // only housekeeping in it
|
|
479
|
+
if (r.live) {
|
|
480
|
+
take(r);
|
|
481
|
+
out.kept.push({ s, text: `${isName(s) ? wordOf(s) + ' ' : ''}${source.slice(s.getStart(sf), fn.body.getStart(sf) + 1)}\n${indent(r.lines.join('\n'), ' ')}\n}${s.kind === K.FunctionDeclaration ? '' : ';'}` });
|
|
482
|
+
continue;
|
|
483
|
+
}
|
|
484
|
+
comment(s, 'a function of the script that makes or changes what is not in the ported scene: here it is a component of its own, or an action', `${short(s)}: nothing in this function could be carried over (${r.said[0]?.[1].replace(/^.*?: /, '').replace(/\. The statement is kept as a comment$/, '') ?? 'it uses three.js'}). It is kept in the component as a comment`);
|
|
485
|
+
continue;
|
|
486
|
+
}
|
|
487
|
+
if (!reason && !fn) {
|
|
488
|
+
const r = reworded(s);
|
|
489
|
+
if (!r.strangers.size && !r.told.size && !isDeclaration) { take(r); out.atMount.push({ s, text: r.text }); continue; }
|
|
490
|
+
comment(s, r.strangers.size || r.told.size ? why(r) : `it reads ${[...r.refs].map((n) => `\`${n}\``).join(', ')} while the script runs from top to bottom: here the scene exists once the component is mounted (read it in onMount)`);
|
|
491
|
+
continue;
|
|
492
|
+
}
|
|
493
|
+
comment(s, reason ?? 'no rule knows what this is in @clarity-js/gl');
|
|
494
|
+
}
|
|
495
|
+
return out;
|
|
496
|
+
}
|
|
497
|
+
let sorted = classify();
|
|
498
|
+
for (let i = 0; i < 8 && sorted.grew; i++) sorted = classify();
|
|
499
|
+
const { kept, atMount, commented } = sorted;
|
|
500
|
+
for (const id of sorted.refs) moved.add(id);
|
|
501
|
+
for (const [s, text] of sorted.todos) todo(s, text);
|
|
502
|
+
|
|
503
|
+
// a name declared with nothing at the top that is not one of three.js's objects is still declared (`let paused;`)
|
|
504
|
+
{ const plain = [...pending].filter((n) => !lost.has(n) && !things.has(n) && ![sceneName, cameraName, rendererName, clockName, controlsName].includes(n) && !geometries.has(n) && !materials.has(n) && !loaders.has(n)); if (plain.length) kept.unshift({ s: sf.statements[0], text: `let ${plain.join(', ')};` }); }
|
|
505
|
+
|
|
506
|
+
// ── every frame ──
|
|
507
|
+
let frameBody = '', deltaName = 'delta';
|
|
508
|
+
if (loop) {
|
|
509
|
+
const f = loop.fn, param = f.parameters?.[0]?.name.kind === K.Identifier ? f.parameters[0].name.text : null;
|
|
510
|
+
const locals = namesIn(f);
|
|
511
|
+
const list = [];
|
|
512
|
+
let elapsedAlias = null, deltaTaken = false;
|
|
513
|
+
for (const s of loopStatements) {
|
|
514
|
+
const text = raw(s).replace(/;\s*$/, '');
|
|
515
|
+
if (isBoilerplate(text)) continue;
|
|
516
|
+
// `const dt = clock.getDelta()`: the frame hands that over, under the same name
|
|
517
|
+
const d = s.kind === K.VariableStatement && s.declarationList.declarations.length === 1 ? s.declarationList.declarations[0] : null;
|
|
518
|
+
const init = d?.initializer ? raw(d.initializer) : '';
|
|
519
|
+
if (clockName && d?.name.kind === K.Identifier && init === `${clockName}.getDelta()` && !deltaTaken) { deltaName = d.name.text; deltaTaken = true; continue; }
|
|
520
|
+
if (clockName && d?.name.kind === K.Identifier && d.name.text === 'elapsed' && (init === `${clockName}.getElapsedTime()` || init === `${clockName}.elapsedTime`)) { elapsedAlias = 'elapsed'; continue; }
|
|
521
|
+
list.push(s);
|
|
522
|
+
}
|
|
523
|
+
if (!deltaTaken && locals.has('delta')) deltaName = locals.has('dt') ? 'frameDelta' : 'dt';
|
|
524
|
+
const gone = new Set(lost);
|
|
525
|
+
if (param) gone.delete(param);
|
|
526
|
+
const r = later(list, { frame: true, gone, delta: deltaName, elapsedAlias });
|
|
527
|
+
for (const id of r.refs) moved.add(id);
|
|
528
|
+
for (const [st, text] of r.said) todo(st, text);
|
|
529
|
+
const lines = [...r.lines];
|
|
530
|
+
// the time the browser hands a frame (milliseconds), under the name the script gave it
|
|
531
|
+
const usesParam = param && list.some((s) => namesIn(s).has(param));
|
|
532
|
+
if (usesParam) lines.unshift(`let ${param} = state.clock.elapsedTime * 1000;`);
|
|
533
|
+
frameBody = indent(lines.join('\n'), ' ').trimStart();
|
|
534
|
+
if (!lines.length) done(f, 'the function that ran every frame only drew the picture (and kept the controls going): it is not needed, a scene draws itself when something in it changes');
|
|
535
|
+
else done(f, `the function that ran every frame is \`frame()\`${inLoop.size ? ` (with ${[...inLoop.keys()].map((n) => `${n}()`).join(', ')} read into it)` : ''}; a scene draws itself while a frame() runs${usesParam ? `. \`${param}\` is the time since the scene started, in milliseconds as before` : ''}`);
|
|
536
|
+
}
|
|
537
|
+
if (meterName) notes.push({ line: 1, level: 'done', text: 'the frame-rate meter (Stats) is left out' });
|
|
538
|
+
if (controls.dropped.length) notes.push({ line: 1, level: 'done', text: `the controls' ${controls.dropped.join(', ')}: left out (<Orbit> has target, the distances, the polar limits, rotateSpeed, zoomSpeed, pan, keys, damping)` });
|
|
539
|
+
if (shadowSettings) notes.push({ line: 1, level: 'done', text: `${shadowSettings} setting${shadowSettings === 1 ? '' : 's'} of a light's shadow camera ${shadowSettings === 1 ? 'is' : 'are'} left out: a light here has shadowMapSize and shadowCameraSize` });
|
|
540
|
+
|
|
541
|
+
// ── the same scene as React Three Fiber ──
|
|
542
|
+
const lineMap = []; // a line of the text made here → the line of the script it came from
|
|
543
|
+
const out = [];
|
|
544
|
+
const emit = (text, line) => { for (const l of text.split('\n')) { out.push(l); lineMap[out.length] = line ?? 1; } };
|
|
545
|
+
const first = sf.statements[0] ? lineOf(sf.statements[0]) : 1;
|
|
546
|
+
emit(`import { useRef, useEffect } from 'react';`, first);
|
|
547
|
+
emit(`import { Canvas, useFrame } from '@react-three/fiber';`, first);
|
|
548
|
+
emit(`import { OrbitControls } from '@react-three/drei';`, first);
|
|
549
|
+
for (const i of otherImports) emit(raw(i), lineOf(i));
|
|
550
|
+
emit(`export default function ${name}() {`, first);
|
|
551
|
+
for (const id of moved) emit(` const ${id} = useRef();`, things.get(id).line);
|
|
552
|
+
for (const k of kept) emit(indent(k.text, ' '), lineOf(k.s));
|
|
553
|
+
if (loop && frameBody) { emit(` useFrame((state, ${deltaName}) => {`, lineOf(loop.fn)); emit(` ${frameBody}`, lineOf(loop.fn)); emit(` });`, lineOf(loop.fn)); }
|
|
554
|
+
if (atMount.length) {
|
|
555
|
+
emit(` useEffect(() => {`, lineOf(atMount[0].s));
|
|
556
|
+
for (const k of atMount) emit(indent(k.text, ' '), lineOf(k.s));
|
|
557
|
+
emit(` }, []);`, lineOf(atMount[0].s));
|
|
558
|
+
notes.push({ line: lineOf(atMount[0].s), level: 'done', text: `${atMount.length} statement${atMount.length === 1 ? '' : 's'} of the script that ${atMount.length === 1 ? 'is' : 'are'} not about the scene (a listener, a line for the page) run${atMount.length === 1 ? 's' : ''} in onMount` });
|
|
559
|
+
}
|
|
560
|
+
emit(` return (`, first);
|
|
561
|
+
const cam = { ...canvas.camera };
|
|
562
|
+
for (const [part, value] of Object.entries(canvas.cameraParts ?? {})) cam[part] ??= `[${value.join(', ')}]`;
|
|
563
|
+
const camText = Object.keys(cam).length ? ` camera={{ ${Object.entries(cam).map(([k, v]) => `${k}: ${v}`).join(', ')} }}` : '';
|
|
564
|
+
emit(` <div style={{ height: '100vh' }}>`, first);
|
|
565
|
+
emit(` <Canvas${canvas.attrs.length ? ' ' + [...new Set(canvas.attrs)].join(' ') : ''}${camText}>`, first);
|
|
566
|
+
if (canvas.background) emit(` <color attach="background" args={[${canvas.background}]} />`, first);
|
|
567
|
+
if (canvas.fog) emit(` <fog attach="fog" args={[${canvas.fog.join(', ')}]} />`, first);
|
|
568
|
+
if (canvas.fogExp) emit(` <fogExp2 attach="fog" args={[${canvas.fogExp.join(', ')}]} />`, first);
|
|
569
|
+
(function write(list, pad) {
|
|
570
|
+
for (const t of list) {
|
|
571
|
+
const attrs = [...(moved.has(t.name) ? [`ref={${t.name}}`] : []), ...t.attrs].join(' ');
|
|
572
|
+
const open = `<${t.tag}${attrs ? ' ' + attrs : ''}`;
|
|
573
|
+
if (!t.inner.length && !t.kids.length) { emit(`${pad}${open} />`, t.line); continue; }
|
|
574
|
+
emit(`${pad}${open}>`, t.line);
|
|
575
|
+
for (const i of t.inner) emit(`${pad} ${i}`, t.line);
|
|
576
|
+
write(t.kids, pad + ' ');
|
|
577
|
+
emit(`${pad}</${t.tag}>`, t.line);
|
|
578
|
+
}
|
|
579
|
+
})(top, ' ');
|
|
580
|
+
if (controlsName) emit(` <OrbitControls${controls.attrs.length ? ' ' + controls.attrs.join(' ') : ''} />`, first);
|
|
581
|
+
emit(` </Canvas>`, first);
|
|
582
|
+
emit(` </div>`, first);
|
|
583
|
+
emit(` );`, first);
|
|
584
|
+
emit(`}`, first);
|
|
585
|
+
for (const [id, t] of things) if (!t.placed) notes.push({ line: t.line, level: 'todo', text: `\`${id}\` is made and never added to the scene where a rule can follow: it is left out` });
|
|
586
|
+
const fiber = out.join('\n') + '\n';
|
|
587
|
+
|
|
588
|
+
// ── and that, through the React porter ──
|
|
589
|
+
const r = portReact(fiber, { typescript: ts, filename: `${name}.jsx`, gl: usesModel() ? ['Model'] : [] });
|
|
590
|
+
let clarity = r.clarity;
|
|
591
|
+
// the statements no rule took, as a comment at the top of the component
|
|
592
|
+
if (clarity && commented.length) {
|
|
593
|
+
// (the reason is folded at 100 columns; the statement's own lines stand further in)
|
|
594
|
+
const fold = (text) => { const out = []; let line = ' //'; for (const word of text.split(' ')) { if (line.length + word.length + 1 > 100 && line.length > 4) { out.push(line); line = ' //'; } line += ' ' + word; } out.push(line); return out; };
|
|
595
|
+
const block = commented.flatMap(({ s, why }) => [...fold(`TODO(port): ${filename.replace(/^.*[\\/]/, '')} line ${lineOf(s)}: ${why}.`), ...textOf(s).split('\n').map((l) => ` // ${l}`.trimEnd())]);
|
|
596
|
+
clarity = clarity.replace(new RegExp(`^(component ${name}\\([^\\n]*\\{)$`, 'm'), (all) => `${all}\n${block.join('\n')}\n`);
|
|
597
|
+
}
|
|
598
|
+
if (clarity) {
|
|
599
|
+
const code = clarity.replace(/^\s*\/\/.*$/gm, '').replace(/^import .*$/gm, '');
|
|
600
|
+
const still = [...lost].filter((n) => n !== star && !fromThree.has(n) && !addons.has(n) && new RegExp(`(?<![.\\w$'"\`<-])${n.replace(/\$/g, '\\$')}(?![\\w$'"\`]|\\s*[=:](?!=))`).test(code));
|
|
601
|
+
if (still.length) notes.push({ line: 1, level: 'todo', text: `${still.map((n) => `\`${n}\``).join(', ')} ${still.length === 1 ? 'is' : 'are'} still named in the ported scene, and what the script made ${still.length === 1 ? 'it' : 'them'} from is not in it (a texture, a value worked out with three.js): write ${still.length === 1 ? 'it' : 'them'} with @clarity-js/gl` });
|
|
602
|
+
}
|
|
603
|
+
if (clarity && new RegExp(`(?<![.\\w$])${star}\\.`).test(clarity.replace(/^\s*\/\/.*$/gm, ''))) notes.push({ line: 1, level: 'todo', text: `\`${star}.…\` is still used in the ported code: three.js is not imported here. Say it with @clarity-js/gl (its math is in the clarity-gl skill), or keep three for that one thing` });
|
|
604
|
+
// what the React Three Fiber rules said, in the script's own words (it wrote `new THREE.SphereGeometry`, not <sphereGeometry>)
|
|
605
|
+
const fromFiber = r.notes
|
|
606
|
+
.filter((n) => !/^useFrame: /.test(n.text))
|
|
607
|
+
.map((n) => ({ ...n, line: lineMap[n.line] ?? 1, text: /^<Canvas> is <Scene>/.test(n.text)
|
|
608
|
+
? 'the scene is in a <div> as tall as the window, as the script\'s canvas was: give it the size you want. Light strengths are not on the same scale in the two renderers: look at the picture and adjust'
|
|
609
|
+
: n.text.replace(/<([a-z]\w*)>/g, (all, tag) => tag[0].toUpperCase() + tag.slice(1)) }));
|
|
610
|
+
const seen = new Set();
|
|
611
|
+
const all = [...notes, ...fromFiber].sort((a, b) => a.line - b.line).filter((n) => { const k = `${n.line}\0${n.level}\0${n.text}`; if (seen.has(k)) return false; seen.add(k); return true; });
|
|
612
|
+
if (boilerplate) all.unshift({ line: first, level: 'done', text: `${boilerplate} line${boilerplate === 1 ? '' : 's'} of renderer and loop housekeeping (the size, the resize listener, appending the canvas, render calls) ${boilerplate === 1 ? 'is' : 'are'} not needed: <Scene> does that` });
|
|
613
|
+
return { clarity, shared: null, components: r.components, notes: all, fiber };
|
|
614
|
+
}
|