Repository navigation
Expand file tree
/
Copy pathAndroidARGenerators.ts
More file actions
453 lines (409 loc) · 18.2 KB
/
Copy pathAndroidARGenerators.ts
File metadata and controls
453 lines (409 loc) · 18.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
import type { HoloComposition, HoloObjectDecl, HoloValue } from '../parser/HoloCompositionTypes';
import type { AndroidCompiler } from './AndroidCompiler';
import { toKotlinColor } from './AndroidKotlinHelpers';
import {
hasGeoTraits,
hasGeospatialVPSTraits,
hasHandTrackingTraits,
} from './AndroidSceneViewFeatureGenerators';
// =============================================================================
// compile_to_android — SceneView (Apache 2.0) Compose-native AR target.
//
// Retargeted OFF the EOL Sceneform fork (com.gorisse.thomas.sceneform, archived)
// ONTO SceneView 4.18.0 (io.github.sceneview, Apache 2.0, actively maintained).
// The proven-green device reference lives at apps/android-reference/ (built with
// the local ad-hoc toolchain and run on a Galaxy S23 — live ARCore session +
// Filament renderer). These generators reproduce that reference: regenerate via
// apps/android-reference/generate-native.mts, gated by
// scripts/holo-ci/check-android-emit-matches-reference.mts (byte-diff) and
// scripts/holo-ci/check-android-build-verify.mts (real gradle build).
//
// SceneView's declarative `ARScene { }` model means there is NO ArFragment, NO
// R.layout, NO imperative NodeFactory and NO SceneState ViewModel — nodes are
// composables (CubeNode / SphereNode / CylinderNode) placed inside the scene
// lambda. generateStateFile / generateNodeFactoryFile therefore emit nothing.
//
// Wave 1 (this code) is the BASE render path. Wave 2 feature traits now emit
// optional SceneView sidecar files (geo-anchor, geospatial VPS, depth scan,
// portal AR, hand tracking, authoring, haptic, ...), so the base activity stays
// declarative and the trait managers remain independently gated.
// =============================================================================
/**
* The SceneView node composable emitted for each geometry kind — the emitter's whole repertoire
* (listed in import order). The node call and its import are both read from here, and the golden
* test (__tests__/AndroidCompiler.golden.test.ts) requires apps/android-reference/scene.holo to
* exercise every entry and checks each named argument against the pinned SceneView signature.
* A kind the reference never compiles is a kind the real gradle build never checks: that is how
* CylinderNode shipped a `length` argument SceneView does not have (its parameter is `height`).
*/
export const SCENEVIEW_NODE_COMPOSABLES = {
cube: 'CubeNode',
cylinder: 'CylinderNode',
sphere: 'SphereNode',
} as const;
type Geometry = keyof typeof SCENEVIEW_NODE_COMPOSABLES;
/** Render a number as a Kotlin Float literal (e.g. 0.2 → "0.2f", -1 → "-1f"). */
function toKotlinFloatLiteral(value: unknown, fallback: number): string {
const numeric = typeof value === 'number' ? value : Number(value);
const resolved = Number.isFinite(numeric) ? numeric : fallback;
return `${resolved}f`;
}
/** Classify an object's mesh/geometry into a SceneView node kind (default cube). */
function geometryOf(compiler: AndroidCompiler, obj: HoloObjectDecl): Geometry {
const raw =
compiler.findObjProp(obj, 'geometry') ??
compiler.findObjProp(obj, 'mesh') ??
compiler.findObjProp(obj, 'type') ??
'cube';
const g = String(raw).toLowerCase();
// box / cube / anything unrecognised → cube (the safe renderable default). Own keys only, so
// an inherited name like "constructor" can never pass as a node kind.
return Object.prototype.hasOwnProperty.call(SCENEVIEW_NODE_COMPOSABLES, g)
? (g as Geometry)
: 'cube';
}
const NAMED_COMPOSE_COLORS: Record<string, string> = {
red: 'Color(0xFFFF0000)',
green: 'Color(0xFF00FF00)',
blue: 'Color(0xFF2196F3)',
white: 'Color(0xFFFFFFFF)',
black: 'Color(0xFF000000)',
yellow: 'Color(0xFFFFEB3B)',
cyan: 'Color(0xFF00BCD4)',
magenta: 'Color(0xFFE91E63)',
orange: 'Color(0xFFFF9800)',
};
/** Neutral default when an object declares no color. */
const DEFAULT_COMPOSE_COLOR = 'Color(0xFF4488FF)';
/**
* Convert a HoloValue colour to a Jetpack-Compose `Color(0x........)` literal for
* SceneView's `materialLoader.createColorInstance(...)`.
*/
function toComposeColor(value: HoloValue | undefined): string {
if (typeof value === 'string') {
if (value.startsWith('#')) return toKotlinColor(value);
return NAMED_COMPOSE_COLORS[value.toLowerCase()] ?? DEFAULT_COMPOSE_COLOR;
}
if (Array.isArray(value) && value.length >= 3) {
const nums = value as number[];
const [r, g, b, a = 1] = nums;
const ch = (n: number) =>
Math.max(0, Math.min(255, Math.round(n * 255)))
.toString(16)
.padStart(2, '0')
.toUpperCase();
return `Color(0x${ch(a)}${ch(r)}${ch(g)}${ch(b)})`;
}
return DEFAULT_COMPOSE_COLOR;
}
/** `Position(x = …f, y = …f, z = …f)` from a [x,y,z] position prop. */
function toPosition(value: HoloValue | undefined): string {
const c = Array.isArray(value) && value.length >= 3 ? (value as number[]) : [0, 0, 0];
return `Position(x = ${toKotlinFloatLiteral(c[0], 0)}, y = ${toKotlinFloatLiteral(
c[1],
0
)}, z = ${toKotlinFloatLiteral(c[2], 0)})`;
}
/** Size in meters of a shape with no scale prop: every kind is this wide. */
const DEFAULT_SIZE = 0.1;
/** One axis of a scale prop: the number itself, or that component of an [x,y,z] vector. */
function scaleAxis(value: HoloValue | undefined, axis: 0 | 1 | 2, fallback: number): number {
if (typeof value === 'number') return value;
if (Array.isArray(value) && typeof value[axis] === 'number') {
return value[axis] as number;
}
return fallback;
}
/** Cube `size = Size(…)` from a scalar or [x,y,z] scale (Size(v) is uniform). */
function toCubeSize(value: HoloValue | undefined): string {
if (Array.isArray(value) && value.length >= 3) {
const n = value as number[];
return `Size(${toKotlinFloatLiteral(n[0], 0.1)}, ${toKotlinFloatLiteral(
n[1],
0.1
)}, ${toKotlinFloatLiteral(n[2], 0.1)})`;
}
return `Size(${toKotlinFloatLiteral(scaleAxis(value, 0, DEFAULT_SIZE), DEFAULT_SIZE)})`;
}
/** Emit one SceneView node composable for a HoloScript object inside ARScene { }. */
function emitObjectNode(compiler: AndroidCompiler, obj: HoloObjectDecl): void {
const geom = geometryOf(compiler, obj);
const colorExpr = toComposeColor(compiler.findObjProp(obj, 'color'));
const position = toPosition(compiler.findObjProp(obj, 'position'));
const scale = compiler.findObjProp(obj, 'scale');
// Escape the name even inside a // comment: an unescaped newline or quote-sequence in a
// hostile object name would otherwise break out of the comment (CWE-94, FlowLevel hardening).
const safeName = compiler.escapeStringValue(obj.name as string, 'Kotlin');
// Shape arguments per kind. Every name must be a real parameter of the SceneView composable
// (the golden test checks them against the pinned signature): a cylinder is radius + height.
// Scale is the shape's size, the rule Quest (quest-world-emit.ts: Sphere(0.5 * sx), boxes
// sx wide) and the web (SphereGeometry(0.5) / CylinderGeometry(0.5, 0.5, 1) scaled) follow.
// A sphere of scale s is s across, a cylinder s across and s tall (y of an [x,y,z] scale),
// a cube s on each side. SceneView takes radii, so round shapes get half the size; passing
// the size itself drew them twice as wide as every other target.
const shapeArgs: Record<Geometry, string[]> = {
cube: [`size = ${toCubeSize(scale)}`],
cylinder: [
`radius = ${toKotlinFloatLiteral(scaleAxis(scale, 0, DEFAULT_SIZE) / 2, DEFAULT_SIZE / 2)}`,
`height = ${toKotlinFloatLiteral(scaleAxis(scale, 1, DEFAULT_SIZE), DEFAULT_SIZE)}`,
],
sphere: [
`radius = ${toKotlinFloatLiteral(scaleAxis(scale, 0, DEFAULT_SIZE) / 2, DEFAULT_SIZE / 2)}`,
],
};
compiler.emit(`// ${safeName} — geometry: ${geom}`);
compiler.emit(`${SCENEVIEW_NODE_COMPOSABLES[geom]}(`);
compiler.indentLevel++;
for (const arg of [
...shapeArgs[geom],
`materialInstance = materialLoader.createColorInstance(${colorExpr})`,
`position = ${position}`,
]) {
compiler.emit(`${arg},`);
}
compiler.indentLevel--;
compiler.emit(')');
}
export function generateActivityFile(
compiler: AndroidCompiler,
composition: HoloComposition
): string {
compiler.lines = [];
compiler.indentLevel = 0;
const pkg = compiler.options.packageName;
const cls = compiler.options.className;
const objects = composition.objects ?? [];
// Which node kinds appear → conditional imports (empty scene → a default cube).
const geoms = new Set<Geometry>(objects.map((o) => geometryOf(compiler, o)));
if (objects.length === 0) geoms.add('cube');
compiler.emit('// Auto-generated by HoloScript AndroidCompiler');
compiler.emit(
`// Source: composition "${compiler.escapeStringValue(composition.name as string, 'Kotlin')}"`
);
compiler.emit(
'// Do not edit manually — regenerate from .holo (apps/android-reference/generate-native.mts)'
);
compiler.emit('//');
compiler.emit(
'// SceneView (Apache 2.0) Compose-native AR. Declarative ARScene { } with one node per'
);
compiler.emit('// HoloScript object — no ArFragment, no R.layout, no NodeFactory/ViewModel.');
compiler.emit('');
compiler.emit(`package ${pkg}`);
compiler.emit('');
compiler.emit('import android.os.Bundle');
compiler.emit('import androidx.activity.ComponentActivity');
compiler.emit('import androidx.activity.compose.setContent');
compiler.emit('import androidx.compose.foundation.layout.fillMaxSize');
compiler.emit('import androidx.compose.ui.Modifier');
compiler.emit('import androidx.compose.ui.graphics.Color');
compiler.emit('import io.github.sceneview.ar.ARScene');
compiler.emit('import io.github.sceneview.ar.rememberARCameraNode');
compiler.emit('import io.github.sceneview.math.Position');
if (geoms.has('cube')) compiler.emit('import io.github.sceneview.math.Size');
for (const [geom, node] of Object.entries(SCENEVIEW_NODE_COMPOSABLES)) {
if (geoms.has(geom as Geometry)) compiler.emit(`import io.github.sceneview.node.${node}`);
}
compiler.emit('import io.github.sceneview.rememberEngine');
compiler.emit('import io.github.sceneview.rememberMaterialLoader');
compiler.emit('');
compiler.emit(`class ${cls}Activity : ComponentActivity() {`);
compiler.indentLevel++;
compiler.emit('override fun onCreate(savedInstanceState: Bundle?) {');
compiler.indentLevel++;
compiler.emit('super.onCreate(savedInstanceState)');
compiler.emit('setContent {');
compiler.indentLevel++;
compiler.emit('val engine = rememberEngine()');
compiler.emit('val materialLoader = rememberMaterialLoader(engine)');
compiler.emit('val cameraNode = rememberARCameraNode(engine)');
compiler.emit('');
compiler.emit('ARScene(');
compiler.indentLevel++;
compiler.emit('modifier = Modifier.fillMaxSize(),');
compiler.emit('engine = engine,');
compiler.emit('cameraNode = cameraNode,');
compiler.emit('materialLoader = materialLoader,');
compiler.emit('planeRenderer = true,');
compiler.indentLevel--;
compiler.emit(') {');
compiler.indentLevel++;
if (objects.length) {
objects.forEach((obj, i) => {
if (i > 0) compiler.emit('');
emitObjectNode(compiler, obj);
});
} else {
compiler.emit('// No objects in composition — default placeholder cube at 1m.');
compiler.emit('CubeNode(');
compiler.indentLevel++;
compiler.emit('size = Size(0.1f),');
compiler.emit(
`materialInstance = materialLoader.createColorInstance(${DEFAULT_COMPOSE_COLOR}),`
);
compiler.emit('position = Position(x = 0f, y = 0f, z = -1f),');
compiler.indentLevel--;
compiler.emit(')');
}
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--; // setContent
compiler.emit('}');
compiler.indentLevel--; // onCreate
compiler.emit('}');
compiler.indentLevel--; // class
compiler.emit('}');
return compiler.lines.join('\n') + '\n';
}
/**
* SceneView's declarative `ARScene { }` keeps node state in the composable tree,
* so the Sceneform `SceneState : ViewModel` is dissolved. Emit nothing.
*/
export function generateStateFile(
_compiler: AndroidCompiler,
_composition: HoloComposition
): string {
return '';
}
/**
* SceneView builds nodes declaratively (CubeNode / SphereNode / …) inside the
* scene lambda, so the Sceneform `NodeFactory` (MaterialFactory/ShapeFactory
* futures) is dissolved. Emit nothing.
*/
export function generateNodeFactoryFile(
_compiler: AndroidCompiler,
_composition: HoloComposition
): string {
return '';
}
export function generateManifestFile(
compiler: AndroidCompiler,
composition: HoloComposition
): string {
const cls = compiler.options.className;
const hasGeo = hasGeoTraits(composition);
const hasGeospatialVPS = hasGeospatialVPSTraits(composition);
const geoPermissions =
hasGeo || hasGeospatialVPS
? `
<!-- Geo-Anchor: Location permissions -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />`
: '';
const geospatialApiKeyMeta = hasGeospatialVPS
? `
<!-- ARCore Geospatial API key (replace with your key from Google Cloud Console) -->
<meta-data android:name="com.google.android.ar.API_KEY" android:value="\${GEOSPATIAL_API_KEY}" />`
: '';
return `<?xml version="1.0" encoding="utf-8"?>
<!-- Auto-generated by HoloScript AndroidCompiler -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<!-- AR Required -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera.ar" android:required="true" />
<!-- ARCore Required -->
<uses-feature android:glEsVersion="0x00030000" android:required="true" />${geoPermissions}
<application
android:allowBackup="true"
android:label="${compiler.escapeStringValue(composition.name as string, 'XML')}"
android:supportsRtl="true"
android:theme="@android:style/Theme.Material.Light.NoActionBar">
<!-- ARCore metadata. SceneView's arsceneview AAR declares com.google.ar.core as
"optional"; this app requires AR, so override the merged value. -->
<meta-data android:name="com.google.ar.core" android:value="required"
tools:replace="android:value" />${geospatialApiKeyMeta}
<activity
android:name=".${cls}Activity"
android:exported="true"
android:configChanges="orientation|screenSize"
android:screenOrientation="locked">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>`;
}
export function generateBuildGradle(
compiler: AndroidCompiler,
composition: HoloComposition
): string {
const pkg = compiler.options.packageName;
const minSdk = compiler.options.minSdk;
// SceneView 4.18.0 pulls androidx.core 1.18.0, which refuses to compile below API 36, so 36 is
// the floor for both compile and target SDK. A higher requested targetSdk flows through.
const sdk = Math.max(36, compiler.options.targetSdk);
const optionalDependencies = new Set<string>();
if (hasGeoTraits(composition) || hasGeospatialVPSTraits(composition)) {
optionalDependencies.add(
'implementation("com.google.android.gms:play-services-location:21.3.0")'
);
}
if (hasHandTrackingTraits(composition)) {
optionalDependencies.add('implementation("androidx.camera:camera-core:1.4.1")');
optionalDependencies.add('implementation("androidx.camera:camera-camera2:1.4.1")');
optionalDependencies.add('implementation("androidx.camera:camera-lifecycle:1.4.1")');
optionalDependencies.add('implementation("com.google.mediapipe:tasks-vision:0.10.20")');
}
const optionalDependencyBlock =
optionalDependencies.size > 0
? `\n\n // Optional SceneView feature-trait sidecars\n ${[...optionalDependencies].join('\n ')}`
: '';
return `// Auto-generated by HoloScript AndroidCompiler
// Source: ${compiler.escapeStringValue(composition.name as string, 'Kotlin')}
//
// SceneView (Apache 2.0) Compose-native AR target — replaces the EOL Sceneform fork.
// compileSdk/targetSdk floor at 36: SceneView 4.18.0 pulls androidx.core 1.18.0, which refuses
// to compile below API 36 and requires Android Gradle Plugin 8.9.1+ and Kotlin 2.3.21 (both
// declared in the hand-maintained root build.gradle.kts scaffold).
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("org.jetbrains.kotlin.plugin.compose")
}
android {
namespace = "${pkg}"
compileSdk = ${sdk}
defaultConfig {
applicationId = "${pkg}"
minSdk = ${minSdk}
targetSdk = ${sdk}
versionCode = ${compiler.options.versionCode}
versionName = "${compiler.escapeStringValue(compiler.options.versionName, 'Kotlin')}"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
buildFeatures {
compose = true
}
}
// Kotlin 2.3 removed the kotlinOptions { jvmTarget = "17" } DSL (now a hard error);
// the JVM target moves to the top-level compilerOptions DSL.
kotlin {
compilerOptions {
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
}
}
dependencies {
implementation("androidx.core:core-ktx:1.13.1")
implementation("androidx.activity:activity-compose:1.9.3")
// Jetpack Compose (BOM matches SceneView 4.18.0's compose surface)
implementation(platform("androidx.compose:compose-bom:2024.09.03"))
implementation("androidx.compose.ui:ui")
implementation("androidx.compose.foundation:foundation")
implementation("androidx.compose.material3:material3")
// SceneView (Apache 2.0) — Compose-native AR; pulls io.github.sceneview:sceneview + ARCore 1.54.0
// transitively. Replaces the EOL Sceneform fork. No ArFragment / no R.layout (Compose-native).
implementation("io.github.sceneview:arsceneview:4.18.0")${optionalDependencyBlock}
}`;
}