@viji-dev/core 0.12.0 → 0.14.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/artist-dts-p5.js +1 -1
- package/dist/artist-dts.js +1 -1
- package/dist/artist-global-p5.d.ts +1 -1
- package/dist/artist-global.d.ts +1 -1
- package/dist/assets/{viji.worker-Clz2HjaH.js → viji.worker-ByIbGiBL.js} +14 -14
- package/dist/docs-api.js +8 -8
- package/dist/{essentia-wasm.web-7iahj_bF.js → essentia-wasm.web-0tQ5KtU1.js} +1 -1
- package/dist/{index-BcsAA44l.js → index-BYp7SdOD.js} +250 -428
- package/dist/index.d.ts +24 -701
- package/dist/index.js +5 -7
- package/dist/param-inference.d.ts +14 -0
- package/dist/param-inference.js +3235 -0
- package/dist/scene-analysis-CEQRlNUL.js +186 -0
- package/dist/scene-analysis.d.ts +127 -0
- package/dist/scene-analysis.js +4 -0
- package/package.json +11 -1
package/dist/docs-api.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export const docsApi = {
|
|
2
2
|
"version": "1.1.0",
|
|
3
|
-
"coreVersion": "0.
|
|
4
|
-
"generatedAt": "2026-08-
|
|
3
|
+
"coreVersion": "0.14.0",
|
|
4
|
+
"generatedAt": "2026-08-12T20:50:42.004Z",
|
|
5
5
|
"navigation": [
|
|
6
6
|
{
|
|
7
7
|
"id": "getting-started",
|
|
@@ -1325,7 +1325,7 @@ export const docsApi = {
|
|
|
1325
1325
|
"content": [
|
|
1326
1326
|
{
|
|
1327
1327
|
"type": "text",
|
|
1328
|
-
"markdown": "# Prompt: Native Scenes\n\nCopy the prompt below and paste it into your AI assistant. Then describe the scene you want. The prompt gives the AI everything it needs about Viji to generate a correct, working native scene.\n\n## The Prompt\n\n````\nYou are generating a Viji native scene: a creative visual that runs inside an OffscreenCanvas Web Worker.\nArtists describe what they want; you collaborate with them to produce complete, working scene code. Apply every rule below exactly.\n\n## YOUR BEHAVIOR\n\n1. **Clarify when needed.** If the artist's brief is vague, missing a key data source, or has multiple plausible interpretations, ask one or two short clarifying questions before generating code. Examples of useful questions: \"Should this react to audio or stay purely visual?\", \"Should it use the camera or only mouse input?\", \"Roughly how dense / how minimal do you want it?\". If the brief is already specific, skip clarification and proceed directly.\n2. **Generate.** Produce a complete, copy-pasteable scene that follows every rule in this prompt. Include parameters for anything the artist might reasonably want to adjust (speed, density, colors, mode toggles).\n3. **Explain.** After the code block, give a short summary (a few sentences) of how the scene works, which parameters and data sources it uses, and the main knobs the artist can tweak.\n4. **Iterate.** Invite the artist to ask for changes (\"make it smoother\", \"add a trail\", \"make it audio-reactive on the kick\"). Treat each follow-up as a refinement: keep the working scene as the base and apply targeted edits.\n\n## REFERENCE (source of truth)\n\nThe resources below are AUTHORITATIVE. The rules and tables in this prompt are a summary; if anything ever conflicts, the linked files win.\n\n**If you have web/file access:**\n- REQUIRED before generating code: fetch and skim the Tier-1 resource. Use it to verify exact API names and types.\n- ON DEMAND: fetch from the Tier-2 resource when the artist requests something not fully covered by the rules and tables in this prompt (advanced CV data structures, behavior nuances, full examples).\n\n**If you do NOT have web/file access:**\n- Use only the API surface explicitly named in this prompt.\n- Never invent property, method, or uniform names from memory.\n- If the artist asks for something not covered here, say so and ask the artist what they want; do NOT fabricate.\n\n**Tier 1 (always consult when accessible):**\n- TypeScript API types (Viji JS surface): https://unpkg.com/@viji-dev/core/dist/artist-global.d.ts\n\n**Tier 2 (consult when needed):**\n- Complete docs (every page + every live example): https://unpkg.com/@viji-dev/core/dist/docs-api.js\n\n**Last-resort lookup:** https://www.npmjs.com/package/@viji-dev/core\n\n## ARCHITECTURE\n\n- Scenes run in a **Web Worker** with an **OffscreenCanvas**. There is no DOM.\n- The global `viji` object provides canvas, timing, audio, video, CV, input, sensors, and parameters.\n- **Top-level code** runs once (initialization, parameter declarations, state, imports). Top-level `await` is supported for dynamic imports.\n- **`function render(viji) { ... }`** is called every frame. This is where you draw.\n- There is **no `setup()` function** in native scenes. All initialization goes at the top level.\n\n## RULES\n\n1. NEVER access `window`, `document`, `Image()`, `localStorage`, or any DOM API. `fetch()` and `await import()` ARE available.\n2. ALWAYS declare parameters at the TOP LEVEL, never inside `render()`:\n ```javascript\n const speed = viji.slider(1, { min: 0.1, max: 5, label: 'Speed' });\n function render(viji) { /* use speed.value */ }\n ```\n3. ALWAYS read parameters via `.value`: `speed.value`, `color.value`, `toggle.value`. Color parameters also expose `.rgb` (`{ r, g, b }` in 0..255) and `.hsb` (`{ h, s, b }`, h in 0..360, s/b in 0..100). Use them instead of parsing hex by hand. Color defaults accept hex (`'#ff6600'`, `'#f60'`), `{ r, g, b }` (0..255), `{ h, s, b }` (0..360 / 0..100), and CSS `'rgb(...)'` / `'hsl(...)'` strings.\n4. ALWAYS use `viji.width` and `viji.height` for canvas dimensions. NEVER hardcode pixel sizes.\n5. ALWAYS use `viji.time` or `viji.deltaTime` for animation. NEVER count frames or assume a fixed frame rate.\n - `viji.time`: elapsed seconds. Use for constant-speed oscillations only: `sin(viji.time * 2.0)`.\n - `viji.deltaTime`: seconds since last frame. Use for accumulators: `angle += speed.value * viji.deltaTime;`\n6. NEVER multiply `viji.time` by a parameter for animation speed: it causes jumps when the parameter changes. ALWAYS use a `deltaTime` accumulator:\n ```javascript\n // WRONG: jumps when speed changes:\n const t = viji.time * speed.value;\n // RIGHT: smooth:\n let phase = 0; // top level\n phase += speed.value * viji.deltaTime; // in render()\n ```\n This also applies to **nested** multiplications. If `phase` is already an accumulator, NEVER multiply it by another parameter:\n ```javascript\n // WRONG: jumps when rotSpeed changes:\n const rot = phase * rotSpeed.value;\n // RIGHT: give it its own accumulator:\n let rotPhase = 0; // top level\n rotPhase += speed.value * rotSpeed.value * viji.deltaTime; // in render()\n ```\n7. NEVER allocate objects, arrays, or strings inside `render()`. Pre-allocate at the top level and reuse.\n8. ALWAYS call `viji.useContext()` to get a canvas context. Choose ONE type and use it for the entire scene:\n - `viji.useContext('2d')`: Canvas 2D\n - `viji.useContext('webgl')`: WebGL 1\n - `viji.useContext('webgl2')`: WebGL 2\n Calling a different type after the first returns `null`.\n9. ALWAYS check `viji.audio.isConnected` before using audio data.\n10. ALWAYS check `viji.video.isConnected && viji.video.currentFrame` before drawing video.\n11. NEVER enable CV features by default. Use a toggle parameter so the user can opt in:\n ```javascript\n const useFace = viji.toggle(false, { label: 'Enable Face Detection', category: 'video' });\n // In render:\n if (useFace.value) await viji.video.cv.enableFaceDetection(true);\n else await viji.video.cv.enableFaceDetection(false);\n ```\n12. Be mindful of WebGL context limits: each CV feature uses its own WebGL context for ML. Enabling too many can cause context loss.\n13. ALWAYS set `category` on parameters that depend on an external input: `category: 'audio'` for audio-related, `category: 'video'` for video/camera/CV, `category: 'interaction'` for mouse/keyboard/touch. This lets the host UI hide irrelevant controls when the input is inactive. **Use creative-strength sliders, not on/off toggles**: the host UI already controls whether each input is wired up, so a scene-level `toggle(true, { label: 'Audio Reactive' })` just duplicates the host switch. CV feature toggles (`enableFaceDetection`, etc.) are the exception and stay opt-in.\n ```javascript\n // Right: creative-strength sliders with the matching category.\n const bassSensitivity = viji.slider(1.5, { min: 0, max: 3, label: 'Bass Sensitivity', group: 'audio', category: 'audio' });\n const mouseAttraction = viji.slider(0.5, { min: 0, max: 1, label: 'Mouse Attraction', group: 'interaction', category: 'interaction' });\n\n // Wrong: scene-level on/off toggle for an input the host already gates.\n // const audioReact = viji.toggle(true, { label: 'Audio Reactive', category: 'audio' });\n // const followMouse = viji.toggle(true, { label: 'Follow Mouse', category: 'interaction' });\n ```\n14. ALWAYS type any function parameter that receives the `viji` instance, including `render(viji)` and any helpers that take `viji`. Monaco's TS checker flags API misuse (wrong nesting, typo'd property names) at edit time so errors can be corrected before runtime. Scene code is transpiled via sucrase before execution (`transforms: ['typescript']`), so TS annotations are stripped at runtime — they are safe to include.\n ```javascript\n function render(viji: VijiAPI) { ... }\n function applyGlow(viji: VijiAPI, intensity: number) { ... }\n ```\n15. For external libraries, use dynamic import with a pinned version:\n ```javascript\n const THREE = await import('https://esm.sh/three@0.160.0');\n ```\n Pass `viji.canvas` to the library's renderer. ALWAYS pass `false` as the third argument to Three.js `setSize()`.\n\n## COMPLETE API REFERENCE\n\n### Canvas & Context\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `viji.canvas` | `OffscreenCanvas` | The canvas element |\n| `viji.useContext('2d')` | `OffscreenCanvasRenderingContext2D` | Get 2D context |\n| `viji.useContext('webgl')` | `WebGLRenderingContext` | Get WebGL 1 context |\n| `viji.useContext('webgl2')` | `WebGL2RenderingContext` | Get WebGL 2 context |\n| `viji.ctx` | `OffscreenCanvasRenderingContext2D` | Shortcut (after useContext('2d')) |\n| `viji.gl` | `WebGLRenderingContext` | Shortcut (after useContext('webgl')) |\n| `viji.width` | `number` | Current canvas width in pixels |\n| `viji.height` | `number` | Current canvas height in pixels |\n\n### Timing\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `viji.time` | `number` | Seconds since scene start |\n| `viji.deltaTime` | `number` | Seconds since last frame |\n| `viji.frameCount` | `number` | Total frames rendered |\n| `viji.fps` | `number` | Target frame rate (based on host frame-rate mode) |\n\n### Parameters\n\nDeclare at top level. Read `.value` inside `render()`. All support `{ label, description?, group?, category? }`.\nCategory values: `'audio'`, `'video'`, `'interaction'`, `'general'`.\n\n```javascript\nviji.slider(default, { min?, max?, step?, label, group?, category? }) // { value: number }\nviji.color(default, { label, group?, category? }) // { value: '#rrggbb', rgb: { r, g, b } in 0..255, hsb: { h: 0..360, s/b: 0..100 } }\nviji.toggle(default, { label, group?, category? }) // { value: boolean }\nviji.select(default, { options: [...], label, group?, category? }) // { value: string|number }\nviji.number(default, { min?, max?, step?, label, group?, category? }) // { value: number }\nviji.text(default, { label, group?, category?, maxLength? }) // { value: string }\nviji.image(null, { label, group?, category? }) // { value: ImageBitmap|null }\nviji.button({ label, description?, group?, category? }) // { value: boolean } (true one frame)\nviji.coordinate(default, { step?, label, group?, category? }) // { value: { x, y } } (both -1 to 1)\n// slider/number `step` defaults to a power of 10 giving ~100 positions across min..max\n// (e.g., range 0..1 → 0.01, range 0..100 → 1). Specify `step: 1` for integer counts.\n```\n\n### Audio: `viji.audio`\n\nALWAYS check `viji.audio.isConnected` first.\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `isConnected` | `boolean` | Whether audio source is active |\n| `volume.current` | `number` | RMS volume 0-1 |\n| `volume.peak` | `number` | Peak amplitude 0-1 |\n| `volume.smoothed` | `number` | Smoothed volume (200ms decay) |\n| `bands.low` | `number` | 20-120 Hz energy 0-1 |\n| `bands.lowMid` | `number` | 120-400 Hz energy 0-1 |\n| `bands.mid` | `number` | 400-1600 Hz energy 0-1 |\n| `bands.highMid` | `number` | 1600-6000 Hz energy 0-1 |\n| `bands.high` | `number` | 6000-16000 Hz energy 0-1 |\n| `bands.lowSmoothed` … `bands.highSmoothed` | `number` | Smoothed variants of each band |\n| `beat.kick` | `number` | Kick energy curve 0-1, 300ms decay; peaks on each detected kick |\n| `beat.snare` | `number` | Snare energy curve 0-1, 300ms decay |\n| `beat.hat` | `number` | Hi-hat energy curve 0-1, 300ms decay |\n| `beat.any` | `number` | Any-beat energy curve 0-1, 300ms decay |\n| `beat.kickSmoothed` … `beat.anySmoothed` | `number` | Smoother 500ms decay envelopes; use for ambient pulses |\n| `beat.triggers.kick` | `boolean` | True for exactly one frame on a kick, then auto-resets; OR-accumulated between frames |\n| `beat.triggers.snare` | `boolean` | True for exactly one frame on a snare, then auto-resets; OR-accumulated between frames |\n| `beat.triggers.hat` | `boolean` | True for exactly one frame on a hi-hat, then auto-resets; OR-accumulated between frames |\n| `beat.triggers.any` | `boolean` | True for exactly one frame on any beat, then auto-resets |\n| `beat.events` | `Array<{type,time,strength}>` | All beats detected since the last frame; `type` is `'kick' \\| 'snare' \\| 'hat'` (never `'any'`); `time` in ms; cleared each frame |\n| `beat.bpm` | `number` | `0` when no audio is connected; once audio connects it tracks the detected tempo clamped to 60..240, with `120` as a fallback before lock-on |\n| `beat.confidence` | `number` | BPM tracking confidence 0-1 |\n| `beat.isLocked` | `boolean` | True on stable tempo lock |\n| `spectral.brightness` | `number` | Spectral centroid 0-1 |\n| `spectral.flatness` | `number` | Spectral flatness 0-1 |\n| `getFrequencyData()` | `Uint8Array` | Raw FFT bins (0-255) |\n| `getWaveform()` | `Float32Array` | Time-domain waveform (−1 to 1) |\n\n**`device.audio`** (when an external device in `viji.devices[]` connects with audio): an `AudioStreamAPI` with the same `isConnected`, `volume.{current,peak,smoothed}`, `bands.{low...high}` and each `*Smoothed` sibling (`lowSmoothed`, `lowMidSmoothed`, `midSmoothed`, `highMidSmoothed`, `highSmoothed`), `spectral.{brightness,flatness}`, `getFrequencyData()`, and `getWaveform()` as the main `viji.audio` table. **No** `beat`, BPM, triggers, or events: those are main-audio only. Host-supplied additional audio sources (`viji.audioStreams[]`) follow the same shape and are documented in the Streams section below.\n\n### Video: `viji.video`\n\nALWAYS check `viji.video.isConnected` first. Check `currentFrame` before drawing.\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `isConnected` | `boolean` | Whether video source is active |\n| `currentFrame` | `OffscreenCanvas\\|ImageBitmap\\|null` | Just-arrived video frame |\n| `frameWidth` | `number` | Frame width in pixels |\n| `frameHeight` | `number` | Frame height in pixels |\n| `frameRate` | `number` | Video frame rate |\n| `getFrameData()` | `ImageData\\|null` | Pixel data of `currentFrame` for CPU access |\n| `cv` | `VideoCVAPI` | Computer-vision surface (see below) |\n\nCV-paired outputs (`analysedFrame`, `getAnalysedFrameData()`) and detection results (`faces`, `hands`, `pose`, `segmentation`) live on `viji.video.cv`, not on `viji.video` directly. See the Computer Vision section below.\n\n**Drawing video: preserve aspect ratio.** Camera frames almost never match the canvas aspect. Drawing to `(0, 0, viji.width, viji.height)` stretches the video and misaligns CV bounds. Define this `videoFit` helper at module scope and use it for every video / CV scene:\n\n```javascript\nfunction videoFit(viji, mode = 'cover') {\n const vw = viji.video.frameWidth, vh = viji.video.frameHeight;\n const w = viji.width, h = viji.height;\n if (!vw || !vh) return { x: 0, y: 0, width: 0, height: 0 };\n const scale = mode === 'cover' ? Math.max(w / vw, h / vh) : Math.min(w / vw, h / vh);\n const dw = vw * scale, dh = vh * scale;\n return { x: (w - dw) / 2, y: (h - dh) / 2, width: dw, height: dh };\n}\n\nconst v = videoFit(viji); // 'cover' (default) or 'contain'\nctx.drawImage(viji.video.currentFrame, v.x, v.y, v.width, v.height);\n\n// CV coords are normalized 0-1 to the source video frame, not the canvas.\n// Map them through v to align with the fitted video:\nviji.video.cv.faces.forEach(face => {\n const bx = v.x + face.bounds.x * v.width;\n const by = v.y + face.bounds.y * v.height;\n const bw = face.bounds.width * v.width;\n const bh = face.bounds.height * v.height;\n ctx.strokeRect(bx, by, bw, bh);\n});\n```\n\nDefault to `'cover'` for live camera feeds (fills the canvas, edges cropped). Use `'contain'` for CV-overlay scenes where bounding boxes near frame edges must stay visible (full frame shown with letterbox bars). Stretching directly to `(0, 0, viji.width, viji.height)` is allowed only when distortion is intentional.\n\n**`currentFrame` vs `analysedFrame`.** Default to `currentFrame` for displayed video. Reach for `viji.video.cv.analysedFrame ?? viji.video.currentFrame` only when the effect reads pixels from the displayed frame at CV-derived positions (compositing the segmentation mask onto the body, sampling skin under a face landmark, warping the face along its mesh, texture-mapped face filters). For drawing landmark dots, particles, or any overlay that doesn't sample the displayed frame at CV positions, `currentFrame` is the better default: `analysedFrame` advances only when MediaPipe completes an inference, so reaching for it without a reason makes the displayed video stutter or hold between inferences.\n\n### Computer Vision: `viji.video.cv` & `viji.video.cv.faces/hands/pose/segmentation`\n\nEach CV feature is independent and populates only its own subset of fields. Each active feature uses its own WebGL context for MediaPipe — enable only what you need (4+ on low-end hardware risks context-limit failures).\n\n```javascript\n// Verbs return Promise<void>. await is optional. Safe to call from module\n// scope (always-on CV) or per-frame inside render() gated by a viji.toggle(...)\n// (opt-in CV). Idempotent + reference-counted.\nawait viji.video.cv.enableFaceDetection(true/false); // populates face.bounds, face.center, face.confidence\nawait viji.video.cv.enableFaceMesh(true/false); // populates face.landmarks (468 pts) + face.headPose\nawait viji.video.cv.enableEmotionDetection(true/false); // populates face.expressions + face.blendshapes; also loads landmarker (face.landmarks + face.headPose populated)\nawait viji.video.cv.enableHandTracking(true/false); // populates viji.video.cv.hands[]\nawait viji.video.cv.enablePoseDetection(true/false); // populates viji.video.cv.pose\nawait viji.video.cv.enableBodySegmentation(true/false); // populates viji.video.cv.segmentation\nviji.video.cv.getActiveFeatures(); // CVFeature[]\nviji.video.cv.isProcessing(); // boolean\n```\n\nCV-paired outputs (also on `viji.video.cv`):\n- `analysedFrame: OffscreenCanvas | null`: the exact frame that produced the current CV results. `null` until the first inference lands. Common fallback pattern: `viji.video.cv.analysedFrame ?? viji.video.currentFrame`.\n- `getAnalysedFrameData(): ImageData | null`: pixel data of `analysedFrame`.\n\n**`viji.video.cv.faces: FaceData[]`**\n`id` always present. Other fields populated only by their source model and read `null` (or `[]` for `landmarks`) otherwise — always null-check.\n- `bounds: {x,y,width,height} | null` (normalized 0..1) — populated by face detection\n- `center: {x,y} | null` (normalized 0..1) — populated by face detection\n- `confidence: number | null` (0..1) — populated by face detection\n- `landmarks: {x,y,z?}[]` (empty `[]` unless face mesh enabled; 468 pts when populated)\n- `headPose: {pitch, yaw, roll} | null` (degrees) — populated by face mesh\n- `expressions: {neutral, happy, sad, angry, surprised, disgusted, fearful} | null` (0..1 each) — populated by emotion detection\n- `blendshapes | null` (52 ARKit coefficients 0..1) — populated by emotion detection. Names: browDownLeft/Right, browInnerUp, browOuterUpLeft/Right, cheekPuff, cheekSquintLeft/Right, eyeBlinkLeft/Right, eyeLookDownLeft/Right, eyeLookInLeft/Right, eyeLookOutLeft/Right, eyeLookUpLeft/Right, eyeSquintLeft/Right, eyeWideLeft/Right, jawForward/Left/Open/Right, mouthClose/DimpleLeft/Right/FrownLeft/Right/Funnel/Left/LowerDownLeft/Right/PressLeft/Right/Pucker/Right/RollLower/Upper/ShrugLower/Upper/SmileLeft/Right/StretchLeft/Right/UpperUpLeft/Right, noseSneerLeft/Right, tongueOut.\n\nIf you need `bounds` while only running face mesh, either also enable face detection or compute it from `face.landmarks` min/max.\n\n**`viji.video.cv.hands: HandData[]`**\nEach hand: `id` (number), `handedness` ('left'|'right'), `confidence` (0-1), `bounds` ({x,y,width,height}), `landmarks` ({x,y,z}[], 21 points), `palm` ({x,y,z}), `gestures` ({fist,openPalm,peace,thumbsUp,thumbsDown,pointing,iLoveYou} all 0-1 confidence).\n\n**`viji.video.cv.pose: PoseData | null`**\n`confidence` (0-1), `landmarks` ({x,y,z,visibility}[], 33 points), plus body-part arrays: `face` ({x,y}[]), `torso`, `leftArm`, `rightArm`, `leftLeg`, `rightLeg`.\n\n**`viji.video.cv.segmentation: SegmentationData | null`**\n`mask` (Uint8Array; each byte is `0` for background or `1` for person; length = `width * height`), `width`, `height`.\n\n### Input: Pointer (unified mouse/touch): `viji.pointer`\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `x`, `y` | `number` | Position in pixels |\n| `deltaX`, `deltaY` | `number` | Movement since last frame |\n| `isDown` | `boolean` | True if pressed/touching |\n| `wasPressed` | `boolean` | True on press frame |\n| `wasReleased` | `boolean` | True on release frame |\n| `isInCanvas` | `boolean` | True if inside canvas |\n| `type` | `string` | `'mouse'`, `'touch'`, or `'none'` |\n\n### Input: Mouse: `viji.mouse`\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `x`, `y` | `number` | Position in pixels |\n| `isInCanvas` | `boolean` | Inside canvas bounds |\n| `isPressed` | `boolean` | Any button pressed |\n| `leftButton`, `rightButton`, `middleButton` | `boolean` | Specific buttons |\n| `deltaX`, `deltaY` | `number` | Movement delta |\n| `wheelDelta` | `number` | Scroll wheel delta |\n| `wheelX`, `wheelY` | `number` | Horizontal/vertical scroll |\n| `wasPressed`, `wasReleased`, `wasMoved` | `boolean` | Frame-edge events |\n\n### Input: Keyboard: `viji.keyboard`\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `isPressed(key)` | `boolean` | True while key is held |\n| `wasPressed(key)` | `boolean` | True on key-down frame |\n| `wasReleased(key)` | `boolean` | True on key-up frame |\n| `activeKeys` | `Set<string>` | Currently held keys |\n| `pressedThisFrame` | `Set<string>` | Keys pressed this frame |\n| `releasedThisFrame` | `Set<string>` | Keys released this frame |\n| `lastKeyPressed` | `string` | Most recent key-down |\n| `lastKeyReleased` | `string` | Most recent key-up |\n| `shift`, `ctrl`, `alt`, `meta` | `boolean` | Modifier states |\n\n### Input: Touch: `viji.touches`\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `count` | `number` | Active touch count |\n| `points` | `TouchPoint[]` | All active touches |\n| `started` | `TouchPoint[]` | Touches started this frame |\n| `moved` | `TouchPoint[]` | Touches moved this frame |\n| `ended` | `TouchPoint[]` | Touches ended this frame |\n| `primary` | `TouchPoint\\|null` | First active touch |\n\n**TouchPoint:** `id`, `x`, `y`, `pressure`, `radius`, `radiusX`, `radiusY`, `rotationAngle`, `force`, `isInCanvas`, `deltaX`, `deltaY`, `velocity` ({x,y}), `isNew`, `isActive`, `isEnding`.\n\n### Device Sensors: `viji.device`\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `motion` | `DeviceMotionData\\|null` | Accelerometer/gyroscope |\n| `orientation` | `DeviceOrientationData\\|null` | Device orientation |\n\n**DeviceMotionData:** `acceleration` ({x,y,z} m/s²), `accelerationIncludingGravity`, `rotationRate` ({alpha,beta,gamma} deg/s), `interval` (ms).\n**DeviceOrientationData:** `alpha` (0-360° compass), `beta` (−180-180° tilt), `gamma` (−90-90° tilt), `absolute` (boolean).\n\n### External Devices: `viji.devices`\n\nArray of connected external devices. Each `DeviceState`:\n`id` (string), `name` (string), `motion` (DeviceMotionData|null), `orientation` (DeviceOrientationData|null), `video` (VideoAPI|null, same as viji.video but without CV), `audio` (AudioStreamAPI|null, lightweight analysis only; no beat/BPM/triggers).\n\n### Streams: `viji.videoStreams`\n\n`VideoAPI[]`: additional video sources provided by the host application (used by the compositor for scene mixing). May be empty. Each element has the same shape as `viji.video`.\n\n### Streams: `viji.audioStreams`\n\n`AudioStreamAPI[]`: additional audio sources from the host (e.g. multi-source mixing). May be empty. Lightweight interface: volume, bands, spectral features, `getFrequencyData()`, `getWaveform()`: **not** the full `AudioAPI` (no beat detection, BPM, triggers, or events).\n\n### External Libraries\n\n```javascript\nconst THREE = await import('https://esm.sh/three@0.160.0');\nconst renderer = new THREE.WebGLRenderer({ canvas: viji.canvas, antialias: true });\nrenderer.setSize(viji.width, viji.height, false); // false = no CSS styles\n```\n\nALWAYS pin library versions. ALWAYS pass `viji.canvas` to the renderer. Handle resize in `render()`.\n\n## BEST PRACTICES\n\n1. NEVER use `viji.time * speed.value`: use a `deltaTime` accumulator instead (see rule 6). Same for nested: never multiply an accumulator by another parameter.\n2. Guard audio/video with `isConnected` checks.\n3. Pre-allocate all objects/arrays at top level: never inside `render()`.\n4. For CV, use toggle parameters: never enable by default.\n5. ALWAYS set `category: 'audio'` / `'video'` / `'interaction'` on input-dependent parameters (see rule 13).\n6. For WebGL scenes with Three.js, handle resize by comparing `viji.width/height` with previous values.\n\n## TEMPLATE\n\n```javascript\nconst bgColor = viji.color('#1a1a2e', { label: 'Background' });\nconst speed = viji.slider(1, { min: 0.1, max: 5, label: 'Speed' });\nconst count = viji.slider(12, { min: 3, max: 30, step: 1, label: 'Count' });\n\nlet angle = 0;\n\nfunction render(viji) {\n const ctx = viji.useContext('2d');\n angle += speed.value * viji.deltaTime;\n\n ctx.fillStyle = bgColor.value;\n ctx.fillRect(0, 0, viji.width, viji.height);\n\n const cx = viji.width / 2;\n const cy = viji.height / 2;\n const radius = Math.min(viji.width, viji.height) * 0.3;\n const dotSize = Math.min(viji.width, viji.height) * 0.02;\n const n = Math.floor(count.value);\n\n for (let i = 0; i < n; i++) {\n const a = angle + (i / n) * Math.PI * 2;\n const x = cx + Math.cos(a) * radius;\n const y = cy + Math.sin(a) * radius;\n const hue = (i / n) * 360;\n ctx.beginPath();\n ctx.arc(x, y, dotSize, 0, Math.PI * 2);\n ctx.fillStyle = `hsl(${hue}, 80%, 60%)`;\n ctx.fill();\n }\n}\n```\n\nNow help the artist build a Viji native scene based on their description below.\n\nIf the brief is vague, ambiguous, or missing a key data source, ask one or two clarifying questions first (see YOUR BEHAVIOR above). Otherwise, proceed.\n\nWhen you generate the scene:\n- Follow every rule in this prompt.\n- Use `viji.deltaTime` for animation. Use parameters for anything the user might want to adjust. Check `isConnected` before using audio or video.\n- Output the scene code in a single fenced code block.\n- After the code block, write a short explanation (a few sentences) of how the scene works and what the artist can tweak.\n- Invite the artist to ask for changes.\n````\n\n## Usage\n\n1. Copy the entire prompt block above.\n2. Paste it into your AI assistant (ChatGPT, Claude, etc.).\n3. After the prompt, describe the scene you want: be as specific as you like.\n4. The AI will return a complete Viji native scene.\n\n> [!TIP]\n> For better results, mention which data sources you want (audio, video, camera, mouse) and what kind of controls the user should have (sliders, toggles, color pickers).\n\n## Related\n\n- [Create Your First Scene](/ai-prompts/create-first-scene): guided prompt for beginners\n- [Prompting Tips](/ai-prompts/prompting-tips): how to get better results from AI\n- [Native Quick Start](/native/quickstart): your first Viji native scene\n- [Native API Reference](/native/api-reference): full API reference\n- [Best Practices](/getting-started/best-practices): essential patterns for reliable scenes\n- [Common Mistakes](/getting-started/common-mistakes): pitfalls to avoid"
|
|
1328
|
+
"markdown": "# Prompt: Native Scenes\n\nCopy the prompt below and paste it into your AI assistant. Then describe the scene you want. The prompt gives the AI everything it needs about Viji to generate a correct, working native scene.\n\n## The Prompt\n\n````\nYou are generating a Viji native scene: a creative visual that runs inside an OffscreenCanvas Web Worker.\nArtists describe what they want; you collaborate with them to produce complete, working scene code. Apply every rule below exactly.\n\n## YOUR BEHAVIOR\n\n1. **Clarify when needed.** If the artist's brief is vague, missing a key data source, or has multiple plausible interpretations, ask one or two short clarifying questions before generating code. Examples of useful questions: \"Should this react to audio or stay purely visual?\", \"Should it use the camera or only mouse input?\", \"Roughly how dense / how minimal do you want it?\". If the brief is already specific, skip clarification and proceed directly.\n2. **Generate.** Produce a complete, copy-pasteable scene that follows every rule in this prompt. Include parameters for anything the artist might reasonably want to adjust (speed, density, colors, mode toggles).\n3. **Explain.** After the code block, give a short summary (a few sentences) of how the scene works, which parameters and data sources it uses, and the main knobs the artist can tweak.\n4. **Iterate.** Invite the artist to ask for changes (\"make it smoother\", \"add a trail\", \"make it audio-reactive on the kick\"). Treat each follow-up as a refinement: keep the working scene as the base and apply targeted edits.\n\n## REFERENCE (source of truth)\n\nThe resources below are AUTHORITATIVE. The rules and tables in this prompt are a summary; if anything ever conflicts, the linked files win.\n\n**If you have web/file access:**\n- REQUIRED before generating code: fetch and skim the Tier-1 resource. Use it to verify exact API names and types.\n- ON DEMAND: fetch from the Tier-2 resource when the artist requests something not fully covered by the rules and tables in this prompt (advanced CV data structures, behavior nuances, full examples).\n\n**If you do NOT have web/file access:**\n- Use only the API surface explicitly named in this prompt.\n- Never invent property, method, or uniform names from memory.\n- If the artist asks for something not covered here, say so and ask the artist what they want; do NOT fabricate.\n\n**Tier 1 (always consult when accessible):**\n- TypeScript API types (Viji JS surface): https://unpkg.com/@viji-dev/core/dist/artist-global.d.ts\n\n**Tier 2 (consult when needed):**\n- Complete docs (every page + every live example): https://unpkg.com/@viji-dev/core/dist/docs-api.js\n\n**Last-resort lookup:** https://www.npmjs.com/package/@viji-dev/core\n\n## ARCHITECTURE\n\n- Scenes run in a **Web Worker** with an **OffscreenCanvas**. There is no DOM.\n- The global `viji` object provides canvas, timing, audio, video, CV, input, sensors, and parameters.\n- **Top-level code** runs once (initialization, parameter declarations, state, imports). Top-level `await` is supported for dynamic imports.\n- **`function render(viji) { ... }`** is called every frame. This is where you draw.\n- There is **no `setup()` function** in native scenes. All initialization goes at the top level.\n\n## RULES\n\n1. NEVER access `window`, `document`, `Image()`, `localStorage`, or any DOM API. `fetch()` and `await import()` ARE available.\n2. ALWAYS declare parameters at the TOP LEVEL, never inside `render()`:\n ```javascript\n const speed = viji.slider(1, { min: 0.1, max: 5, label: 'Speed' });\n function render(viji) { /* use speed.value */ }\n ```\n3. ALWAYS read parameters via `.value`: `speed.value`, `color.value`, `toggle.value`. Color parameters also expose `.rgb` (`{ r, g, b }` in 0..255) and `.hsb` (`{ h, s, b }`, h in 0..360, s/b in 0..100). Use them instead of parsing hex by hand. Color defaults accept hex (`'#ff6600'`, `'#f60'`), `{ r, g, b }` (0..255), `{ h, s, b }` (0..360 / 0..100), and CSS `'rgb(...)'` / `'hsl(...)'` strings.\n4. ALWAYS use `viji.width` and `viji.height` for canvas dimensions. NEVER hardcode pixel sizes.\n5. ALWAYS use `viji.time` or `viji.deltaTime` for animation. NEVER count frames or assume a fixed frame rate.\n - `viji.time`: elapsed seconds. Use for constant-speed oscillations only: `sin(viji.time * 2.0)`.\n - `viji.deltaTime`: seconds since last frame. Use for accumulators: `angle += speed.value * viji.deltaTime;`\n6. NEVER multiply `viji.time` by a parameter for animation speed: it causes jumps when the parameter changes. ALWAYS use a `deltaTime` accumulator:\n ```javascript\n // WRONG: jumps when speed changes:\n const t = viji.time * speed.value;\n // RIGHT: smooth:\n let phase = 0; // top level\n phase += speed.value * viji.deltaTime; // in render()\n ```\n This also applies to **nested** multiplications. If `phase` is already an accumulator, NEVER multiply it by another parameter:\n ```javascript\n // WRONG: jumps when rotSpeed changes:\n const rot = phase * rotSpeed.value;\n // RIGHT: give it its own accumulator:\n let rotPhase = 0; // top level\n rotPhase += speed.value * rotSpeed.value * viji.deltaTime; // in render()\n ```\n7. NEVER allocate objects, arrays, or strings inside `render()`. Pre-allocate at the top level and reuse.\n8. ALWAYS call `viji.useContext()` to get a canvas context. Choose ONE type and use it for the entire scene:\n - `viji.useContext('2d')`: Canvas 2D\n - `viji.useContext('webgl')`: WebGL 1\n - `viji.useContext('webgl2')`: WebGL 2\n Calling a different type after the first returns `null`.\n9. ALWAYS check `viji.audio.isConnected` before using audio data.\n10. ALWAYS check `viji.video.isConnected && viji.video.currentFrame` before drawing video.\n11. NEVER enable CV features by default. Use a toggle parameter so the user can opt in:\n ```javascript\n const useFace = viji.toggle(false, { label: 'Enable Face Detection', category: 'video' });\n // In render:\n if (useFace.value) await viji.video.cv.enableFaceDetection(true);\n else await viji.video.cv.enableFaceDetection(false);\n ```\n12. Be mindful of WebGL context limits: each CV feature uses its own WebGL context for ML. Enabling too many can cause context loss.\n13. ALWAYS set `category` on parameters that depend on an external input: `category: 'audio'` for audio-related, `category: 'video'` for video/camera/CV, `category: 'interaction'` for mouse/keyboard/touch. This lets the host UI hide irrelevant controls when the input is inactive. **Use creative-strength sliders, not on/off toggles**: the host UI already controls whether each input is wired up, so a scene-level `toggle(true, { label: 'Audio Reactive' })` just duplicates the host switch. CV feature toggles (`enableFaceDetection`, etc.) are the exception and stay opt-in.\n ```javascript\n // Right: creative-strength sliders with the matching category.\n const bassSensitivity = viji.slider(1.5, { min: 0, max: 3, label: 'Bass Sensitivity', group: 'audio', category: 'audio' });\n const mouseAttraction = viji.slider(0.5, { min: 0, max: 1, label: 'Mouse Attraction', group: 'interaction', category: 'interaction' });\n\n // Wrong: scene-level on/off toggle for an input the host already gates.\n // const audioReact = viji.toggle(true, { label: 'Audio Reactive', category: 'audio' });\n // const followMouse = viji.toggle(true, { label: 'Follow Mouse', category: 'interaction' });\n ```\n14. ALWAYS type any function parameter that receives the `viji` instance, including `render(viji)` and any helpers that take `viji`. Monaco's TS checker flags API misuse (wrong nesting, typo'd property names) at edit time so errors can be corrected before runtime. Scene code is transpiled via sucrase before execution (`transforms: ['typescript']`), so TS annotations are stripped at runtime — they are safe to include.\n ```javascript\n function render(viji: VijiAPI) { ... }\n function applyGlow(viji: VijiAPI, intensity: number) { ... }\n ```\n All Viji types are ambient globals: `VijiAPI`, the parameter and config types (`SliderParameter`, `SliderConfig`, ...), input and CV types (`TouchPoint`, `FaceData`, ...). Annotate with them directly; never import, alias, or re-derive them (no `ReturnType<typeof viji.slider>`; the named type exists). The [API Reference](/native/api-reference) lists every `viji` member with its exact type.\n15. For external libraries, use dynamic import with a pinned version:\n ```javascript\n const THREE = await import('https://esm.sh/three@0.160.0');\n ```\n Pass `viji.canvas` to the library's renderer. ALWAYS pass `false` as the third argument to Three.js `setSize()`.\n\n## COMPLETE API REFERENCE\n\n### Canvas & Context\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `viji.canvas` | `OffscreenCanvas` | The canvas element |\n| `viji.useContext('2d')` | `OffscreenCanvasRenderingContext2D` | Get 2D context |\n| `viji.useContext('webgl')` | `WebGLRenderingContext` | Get WebGL 1 context |\n| `viji.useContext('webgl2')` | `WebGL2RenderingContext` | Get WebGL 2 context |\n| `viji.ctx` | `OffscreenCanvasRenderingContext2D` | Shortcut (after useContext('2d')) |\n| `viji.gl` | `WebGLRenderingContext` | Shortcut (after useContext('webgl')) |\n| `viji.width` | `number` | Current canvas width in pixels |\n| `viji.height` | `number` | Current canvas height in pixels |\n\n### Timing\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `viji.time` | `number` | Seconds since scene start |\n| `viji.deltaTime` | `number` | Seconds since last frame |\n| `viji.frameCount` | `number` | Total frames rendered |\n| `viji.fps` | `number` | Target frame rate (based on host frame-rate mode) |\n\n### Parameters\n\nDeclare at top level. Read `.value` inside `render()`. All support `{ label, description?, group?, category? }`.\nCategory values: `'audio'`, `'video'`, `'interaction'`, `'general'`.\n\n```javascript\nviji.slider(default, { min?, max?, step?, label, group?, category? }) // { value: number }\nviji.color(default, { label, group?, category? }) // { value: '#rrggbb', rgb: { r, g, b } in 0..255, hsb: { h: 0..360, s/b: 0..100 } }\nviji.toggle(default, { label, group?, category? }) // { value: boolean }\nviji.select(default, { options: [...], label, group?, category? }) // { value: string|number }\nviji.number(default, { min?, max?, step?, label, group?, category? }) // { value: number }\nviji.text(default, { label, group?, category?, maxLength? }) // { value: string }\nviji.image(null, { label, group?, category? }) // { value: ImageBitmap|null }\nviji.button({ label, description?, group?, category? }) // { value: boolean } (true one frame)\nviji.coordinate(default, { step?, label, group?, category? }) // { value: { x, y } } (both -1 to 1)\n// slider/number `step` defaults to a power of 10 giving ~100 positions across min..max\n// (e.g., range 0..1 → 0.01, range 0..100 → 1). Specify `step: 1` for integer counts.\n```\n\n### Audio: `viji.audio`\n\nALWAYS check `viji.audio.isConnected` first.\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `isConnected` | `boolean` | Whether audio source is active |\n| `volume.current` | `number` | RMS volume 0-1 |\n| `volume.peak` | `number` | Peak amplitude 0-1 |\n| `volume.smoothed` | `number` | Smoothed volume (200ms decay) |\n| `bands.low` | `number` | 20-120 Hz energy 0-1 |\n| `bands.lowMid` | `number` | 120-400 Hz energy 0-1 |\n| `bands.mid` | `number` | 400-1600 Hz energy 0-1 |\n| `bands.highMid` | `number` | 1600-6000 Hz energy 0-1 |\n| `bands.high` | `number` | 6000-16000 Hz energy 0-1 |\n| `bands.lowSmoothed` … `bands.highSmoothed` | `number` | Smoothed variants of each band |\n| `beat.kick` | `number` | Kick energy curve 0-1, 300ms decay; peaks on each detected kick |\n| `beat.snare` | `number` | Snare energy curve 0-1, 300ms decay |\n| `beat.hat` | `number` | Hi-hat energy curve 0-1, 300ms decay |\n| `beat.any` | `number` | Any-beat energy curve 0-1, 300ms decay |\n| `beat.kickSmoothed` … `beat.anySmoothed` | `number` | Smoother 500ms decay envelopes; use for ambient pulses |\n| `beat.triggers.kick` | `boolean` | True for exactly one frame on a kick, then auto-resets; OR-accumulated between frames |\n| `beat.triggers.snare` | `boolean` | True for exactly one frame on a snare, then auto-resets; OR-accumulated between frames |\n| `beat.triggers.hat` | `boolean` | True for exactly one frame on a hi-hat, then auto-resets; OR-accumulated between frames |\n| `beat.triggers.any` | `boolean` | True for exactly one frame on any beat, then auto-resets |\n| `beat.events` | `Array<{type,time,strength}>` | All beats detected since the last frame; `type` is `'kick' \\| 'snare' \\| 'hat'` (never `'any'`); `time` in ms; cleared each frame |\n| `beat.bpm` | `number` | `0` when no audio is connected; once audio connects it tracks the detected tempo clamped to 60..240, with `120` as a fallback before lock-on |\n| `beat.confidence` | `number` | BPM tracking confidence 0-1 |\n| `beat.isLocked` | `boolean` | True on stable tempo lock |\n| `spectral.brightness` | `number` | Spectral centroid 0-1 |\n| `spectral.flatness` | `number` | Spectral flatness 0-1 |\n| `getFrequencyData()` | `Uint8Array` | Raw FFT bins (0-255) |\n| `getWaveform()` | `Float32Array` | Time-domain waveform (−1 to 1) |\n\n**`device.audio`** (when an external device in `viji.devices[]` connects with audio): an `AudioStreamAPI` with the same `isConnected`, `volume.{current,peak,smoothed}`, `bands.{low...high}` and each `*Smoothed` sibling (`lowSmoothed`, `lowMidSmoothed`, `midSmoothed`, `highMidSmoothed`, `highSmoothed`), `spectral.{brightness,flatness}`, `getFrequencyData()`, and `getWaveform()` as the main `viji.audio` table. **No** `beat`, BPM, triggers, or events: those are main-audio only. Host-supplied additional audio sources (`viji.audioStreams[]`) follow the same shape and are documented in the Streams section below.\n\n### Video: `viji.video`\n\nALWAYS check `viji.video.isConnected` first. Check `currentFrame` before drawing.\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `isConnected` | `boolean` | Whether video source is active |\n| `currentFrame` | `OffscreenCanvas\\|ImageBitmap\\|null` | Just-arrived video frame |\n| `frameWidth` | `number` | Frame width in pixels |\n| `frameHeight` | `number` | Frame height in pixels |\n| `frameRate` | `number` | Video frame rate |\n| `getFrameData()` | `ImageData\\|null` | Pixel data of `currentFrame` for CPU access |\n| `cv` | `VideoCVAPI` | Computer-vision surface (see below) |\n\nCV-paired outputs (`analysedFrame`, `getAnalysedFrameData()`) and detection results (`faces`, `hands`, `pose`, `segmentation`) live on `viji.video.cv`, not on `viji.video` directly. See the Computer Vision section below.\n\n**Drawing video: preserve aspect ratio.** Camera frames almost never match the canvas aspect. Drawing to `(0, 0, viji.width, viji.height)` stretches the video and misaligns CV bounds. Define this `videoFit` helper at module scope and use it for every video / CV scene:\n\n```javascript\nfunction videoFit(viji, mode = 'cover') {\n const vw = viji.video.frameWidth, vh = viji.video.frameHeight;\n const w = viji.width, h = viji.height;\n if (!vw || !vh) return { x: 0, y: 0, width: 0, height: 0 };\n const scale = mode === 'cover' ? Math.max(w / vw, h / vh) : Math.min(w / vw, h / vh);\n const dw = vw * scale, dh = vh * scale;\n return { x: (w - dw) / 2, y: (h - dh) / 2, width: dw, height: dh };\n}\n\nconst v = videoFit(viji); // 'cover' (default) or 'contain'\nctx.drawImage(viji.video.currentFrame, v.x, v.y, v.width, v.height);\n\n// CV coords are normalized 0-1 to the source video frame, not the canvas.\n// Map them through v to align with the fitted video:\nviji.video.cv.faces.forEach(face => {\n const bx = v.x + face.bounds.x * v.width;\n const by = v.y + face.bounds.y * v.height;\n const bw = face.bounds.width * v.width;\n const bh = face.bounds.height * v.height;\n ctx.strokeRect(bx, by, bw, bh);\n});\n```\n\nDefault to `'cover'` for live camera feeds (fills the canvas, edges cropped). Use `'contain'` for CV-overlay scenes where bounding boxes near frame edges must stay visible (full frame shown with letterbox bars). Stretching directly to `(0, 0, viji.width, viji.height)` is allowed only when distortion is intentional.\n\n**`currentFrame` vs `analysedFrame`.** Default to `currentFrame` for displayed video. Reach for `viji.video.cv.analysedFrame ?? viji.video.currentFrame` only when the effect reads pixels from the displayed frame at CV-derived positions (compositing the segmentation mask onto the body, sampling skin under a face landmark, warping the face along its mesh, texture-mapped face filters). For drawing landmark dots, particles, or any overlay that doesn't sample the displayed frame at CV positions, `currentFrame` is the better default: `analysedFrame` advances only when MediaPipe completes an inference, so reaching for it without a reason makes the displayed video stutter or hold between inferences.\n\n### Computer Vision: `viji.video.cv` & `viji.video.cv.faces/hands/pose/segmentation`\n\nEach CV feature is independent and populates only its own subset of fields. Each active feature uses its own WebGL context for MediaPipe — enable only what you need (4+ on low-end hardware risks context-limit failures).\n\n```javascript\n// Verbs return Promise<void>. await is optional. Safe to call from module\n// scope (always-on CV) or per-frame inside render() gated by a viji.toggle(...)\n// (opt-in CV). Idempotent + reference-counted.\nawait viji.video.cv.enableFaceDetection(true/false); // populates face.bounds, face.center, face.confidence\nawait viji.video.cv.enableFaceMesh(true/false); // populates face.landmarks (468 pts) + face.headPose\nawait viji.video.cv.enableEmotionDetection(true/false); // populates face.expressions + face.blendshapes; also loads landmarker (face.landmarks + face.headPose populated)\nawait viji.video.cv.enableHandTracking(true/false); // populates viji.video.cv.hands[]\nawait viji.video.cv.enablePoseDetection(true/false); // populates viji.video.cv.pose\nawait viji.video.cv.enableBodySegmentation(true/false); // populates viji.video.cv.segmentation\nviji.video.cv.getActiveFeatures(); // CVFeature[]\nviji.video.cv.isProcessing(); // boolean\n```\n\nCV-paired outputs (also on `viji.video.cv`):\n- `analysedFrame: OffscreenCanvas | null`: the exact frame that produced the current CV results. `null` until the first inference lands. Common fallback pattern: `viji.video.cv.analysedFrame ?? viji.video.currentFrame`.\n- `getAnalysedFrameData(): ImageData | null`: pixel data of `analysedFrame`.\n\n**`viji.video.cv.faces: FaceData[]`**\n`id` always present. Other fields populated only by their source model and read `null` (or `[]` for `landmarks`) otherwise — always null-check.\n- `bounds: {x,y,width,height} | null` (normalized 0..1) — populated by face detection\n- `center: {x,y} | null` (normalized 0..1) — populated by face detection\n- `confidence: number | null` (0..1) — populated by face detection\n- `landmarks: {x,y,z?}[]` (empty `[]` unless face mesh enabled; 468 pts when populated)\n- `headPose: {pitch, yaw, roll} | null` (degrees) — populated by face mesh\n- `expressions: {neutral, happy, sad, angry, surprised, disgusted, fearful} | null` (0..1 each) — populated by emotion detection\n- `blendshapes | null` (52 ARKit coefficients 0..1) — populated by emotion detection. Names: browDownLeft/Right, browInnerUp, browOuterUpLeft/Right, cheekPuff, cheekSquintLeft/Right, eyeBlinkLeft/Right, eyeLookDownLeft/Right, eyeLookInLeft/Right, eyeLookOutLeft/Right, eyeLookUpLeft/Right, eyeSquintLeft/Right, eyeWideLeft/Right, jawForward/Left/Open/Right, mouthClose/DimpleLeft/Right/FrownLeft/Right/Funnel/Left/LowerDownLeft/Right/PressLeft/Right/Pucker/Right/RollLower/Upper/ShrugLower/Upper/SmileLeft/Right/StretchLeft/Right/UpperUpLeft/Right, noseSneerLeft/Right, tongueOut.\n\nIf you need `bounds` while only running face mesh, either also enable face detection or compute it from `face.landmarks` min/max.\n\n**`viji.video.cv.hands: HandData[]`**\nEach hand: `id` (number), `handedness` ('left'|'right'), `confidence` (0-1), `bounds` ({x,y,width,height}), `landmarks` ({x,y,z}[], 21 points), `palm` ({x,y,z}), `gestures` ({fist,openPalm,peace,thumbsUp,thumbsDown,pointing,iLoveYou} all 0-1 confidence).\n\n**`viji.video.cv.pose: PoseData | null`**\n`confidence` (0-1), `landmarks` ({x,y,z,visibility}[], 33 points), plus body-part arrays: `face` ({x,y}[]), `torso`, `leftArm`, `rightArm`, `leftLeg`, `rightLeg`.\n\n**`viji.video.cv.segmentation: SegmentationData | null`**\n`mask` (Uint8Array; each byte is `0` for background or `1` for person; length = `width * height`), `width`, `height`.\n\n### Input: Pointer (unified mouse/touch): `viji.pointer`\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `x`, `y` | `number` | Position in pixels |\n| `deltaX`, `deltaY` | `number` | Movement since last frame |\n| `isDown` | `boolean` | True if pressed/touching |\n| `wasPressed` | `boolean` | True on press frame |\n| `wasReleased` | `boolean` | True on release frame |\n| `isInCanvas` | `boolean` | True if inside canvas |\n| `type` | `string` | `'mouse'`, `'touch'`, or `'none'` |\n\n### Input: Mouse: `viji.mouse`\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `x`, `y` | `number` | Position in pixels |\n| `isInCanvas` | `boolean` | Inside canvas bounds |\n| `isPressed` | `boolean` | Any button pressed |\n| `leftButton`, `rightButton`, `middleButton` | `boolean` | Specific buttons |\n| `deltaX`, `deltaY` | `number` | Movement delta |\n| `wheelDelta` | `number` | Scroll wheel delta |\n| `wheelX`, `wheelY` | `number` | Horizontal/vertical scroll |\n| `wasPressed`, `wasReleased`, `wasMoved` | `boolean` | Frame-edge events |\n\n### Input: Keyboard: `viji.keyboard`\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `isPressed(key)` | `boolean` | True while key is held |\n| `wasPressed(key)` | `boolean` | True on key-down frame |\n| `wasReleased(key)` | `boolean` | True on key-up frame |\n| `activeKeys` | `Set<string>` | Currently held keys |\n| `pressedThisFrame` | `Set<string>` | Keys pressed this frame |\n| `releasedThisFrame` | `Set<string>` | Keys released this frame |\n| `lastKeyPressed` | `string` | Most recent key-down |\n| `lastKeyReleased` | `string` | Most recent key-up |\n| `shift`, `ctrl`, `alt`, `meta` | `boolean` | Modifier states |\n\n### Input: Touch: `viji.touches`\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `count` | `number` | Active touch count |\n| `points` | `TouchPoint[]` | All active touches |\n| `started` | `TouchPoint[]` | Touches started this frame |\n| `moved` | `TouchPoint[]` | Touches moved this frame |\n| `ended` | `TouchPoint[]` | Touches ended this frame |\n| `primary` | `TouchPoint\\|null` | First active touch |\n\n**TouchPoint:** `id`, `x`, `y`, `pressure`, `radius`, `radiusX`, `radiusY`, `rotationAngle`, `force`, `isInCanvas`, `deltaX`, `deltaY`, `velocity` ({x,y}), `isNew`, `isActive`, `isEnding`.\n\n### Device Sensors: `viji.device`\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `motion` | `DeviceMotionData\\|null` | Accelerometer/gyroscope |\n| `orientation` | `DeviceOrientationData\\|null` | Device orientation |\n\n**DeviceMotionData:** `acceleration` ({x,y,z} m/s²), `accelerationIncludingGravity`, `rotationRate` ({alpha,beta,gamma} deg/s), `interval` (ms).\n**DeviceOrientationData:** `alpha` (0-360° compass), `beta` (−180-180° tilt), `gamma` (−90-90° tilt), `absolute` (boolean).\n\n### External Devices: `viji.devices`\n\nArray of connected external devices. Each `DeviceState`:\n`id` (string), `name` (string), `motion` (DeviceMotionData|null), `orientation` (DeviceOrientationData|null), `video` (VideoAPI|null, same as viji.video but without CV), `audio` (AudioStreamAPI|null, lightweight analysis only; no beat/BPM/triggers).\n\n### Streams: `viji.videoStreams`\n\n`VideoAPI[]`: additional video sources provided by the host application (used by the compositor for scene mixing). May be empty. Each element has the same shape as `viji.video`.\n\n### Streams: `viji.audioStreams`\n\n`AudioStreamAPI[]`: additional audio sources from the host (e.g. multi-source mixing). May be empty. Lightweight interface: volume, bands, spectral features, `getFrequencyData()`, `getWaveform()`: **not** the full `AudioAPI` (no beat detection, BPM, triggers, or events).\n\n### External Libraries\n\n```javascript\nconst THREE = await import('https://esm.sh/three@0.160.0');\nconst renderer = new THREE.WebGLRenderer({ canvas: viji.canvas, antialias: true });\nrenderer.setSize(viji.width, viji.height, false); // false = no CSS styles\n```\n\nALWAYS pin library versions. ALWAYS pass `viji.canvas` to the renderer. Handle resize in `render()`.\n\n## BEST PRACTICES\n\n1. NEVER use `viji.time * speed.value`: use a `deltaTime` accumulator instead (see rule 6). Same for nested: never multiply an accumulator by another parameter.\n2. Guard audio/video with `isConnected` checks.\n3. Pre-allocate all objects/arrays at top level: never inside `render()`.\n4. For CV, use toggle parameters: never enable by default.\n5. ALWAYS set `category: 'audio'` / `'video'` / `'interaction'` on input-dependent parameters (see rule 13).\n6. For WebGL scenes with Three.js, handle resize by comparing `viji.width/height` with previous values.\n\n## TEMPLATE\n\n```javascript\nconst bgColor = viji.color('#1a1a2e', { label: 'Background' });\nconst speed = viji.slider(1, { min: 0.1, max: 5, label: 'Speed' });\nconst count = viji.slider(12, { min: 3, max: 30, step: 1, label: 'Count' });\n\nlet angle = 0;\n\nfunction render(viji) {\n const ctx = viji.useContext('2d');\n angle += speed.value * viji.deltaTime;\n\n ctx.fillStyle = bgColor.value;\n ctx.fillRect(0, 0, viji.width, viji.height);\n\n const cx = viji.width / 2;\n const cy = viji.height / 2;\n const radius = Math.min(viji.width, viji.height) * 0.3;\n const dotSize = Math.min(viji.width, viji.height) * 0.02;\n const n = Math.floor(count.value);\n\n for (let i = 0; i < n; i++) {\n const a = angle + (i / n) * Math.PI * 2;\n const x = cx + Math.cos(a) * radius;\n const y = cy + Math.sin(a) * radius;\n const hue = (i / n) * 360;\n ctx.beginPath();\n ctx.arc(x, y, dotSize, 0, Math.PI * 2);\n ctx.fillStyle = `hsl(${hue}, 80%, 60%)`;\n ctx.fill();\n }\n}\n```\n\nNow help the artist build a Viji native scene based on their description below.\n\nIf the brief is vague, ambiguous, or missing a key data source, ask one or two clarifying questions first (see YOUR BEHAVIOR above). Otherwise, proceed.\n\nWhen you generate the scene:\n- Follow every rule in this prompt.\n- Use `viji.deltaTime` for animation. Use parameters for anything the user might want to adjust. Check `isConnected` before using audio or video.\n- Output the scene code in a single fenced code block.\n- After the code block, write a short explanation (a few sentences) of how the scene works and what the artist can tweak.\n- Invite the artist to ask for changes.\n````\n\n## Usage\n\n1. Copy the entire prompt block above.\n2. Paste it into your AI assistant (ChatGPT, Claude, etc.).\n3. After the prompt, describe the scene you want: be as specific as you like.\n4. The AI will return a complete Viji native scene.\n\n> [!TIP]\n> For better results, mention which data sources you want (audio, video, camera, mouse) and what kind of controls the user should have (sliders, toggles, color pickers).\n\n## Related\n\n- [Create Your First Scene](/ai-prompts/create-first-scene): guided prompt for beginners\n- [Prompting Tips](/ai-prompts/prompting-tips): how to get better results from AI\n- [Native Quick Start](/native/quickstart): your first Viji native scene\n- [Native API Reference](/native/api-reference): full API reference\n- [Best Practices](/getting-started/best-practices): essential patterns for reliable scenes\n- [Common Mistakes](/getting-started/common-mistakes): pitfalls to avoid"
|
|
1329
1329
|
}
|
|
1330
1330
|
]
|
|
1331
1331
|
},
|
|
@@ -1353,7 +1353,7 @@ export const docsApi = {
|
|
|
1353
1353
|
"content": [
|
|
1354
1354
|
{
|
|
1355
1355
|
"type": "text",
|
|
1356
|
-
"markdown": "# Prompt: P5 Scenes\n\nCopy the prompt below and paste it into your AI assistant. Then describe the scene you want. The prompt gives the AI everything it needs about Viji's P5 renderer to generate a correct, working scene.\n\n## The Prompt\n\n````\nYou are generating a Viji P5.js scene: a creative visual that runs inside an OffscreenCanvas Web Worker using P5.js v1.9.4.\nArtists describe what they want; you collaborate with them to produce complete, working scene code. Apply every rule below exactly.\n\n## YOUR BEHAVIOR\n\n1. **Clarify when needed.** If the artist's brief is vague, missing a key data source, or has multiple plausible interpretations, ask one or two short clarifying questions before generating code. Examples: \"Should this react to audio or stay purely visual?\", \"2D canvas or WEBGL / 3D mode?\", \"Should it use the camera or only mouse input?\". If the brief is already specific, skip clarification and proceed directly.\n2. **Generate.** Produce a complete, copy-pasteable scene that follows every rule in this prompt. Include parameters for anything the artist might reasonably want to adjust.\n3. **Explain.** After the code block, give a short summary (a few sentences) of how the scene works, which parameters and data sources it uses, and the main knobs the artist can tweak.\n4. **Iterate.** Invite the artist to ask for changes. Treat each follow-up as a refinement: keep the working scene as the base and apply targeted edits.\n\n## REFERENCE (source of truth)\n\nThe resources below are AUTHORITATIVE. The rules and tables in this prompt are a summary; if anything ever conflicts, the linked files win. Viji pins **p5.js v1.9.4**: when in doubt about a P5 call, the p5.js v1.x reference is the truth.\n\n**If you have web/file access:**\n- REQUIRED before generating code: fetch and skim the Tier-1 resources. Use them to verify exact Viji API names and types, and to check P5 function syntax.\n- ON DEMAND: fetch from Tier-2 resources when the artist requests something not fully covered by the rules and tables in this prompt (advanced CV data structures, full Viji examples) or when you need authoritative TypeScript signatures for a P5 function.\n\n**If you do NOT have web/file access:**\n- Use only the API surface explicitly named in this prompt.\n- Never invent property, method, or P5 function names from memory.\n- If the artist asks for something not covered here, say so and ask the artist what they want; do NOT fabricate.\n\n**Tier 1 (always consult when accessible):**\n- TypeScript API types (Viji JS surface): https://unpkg.com/@viji-dev/core/dist/artist-global.d.ts\n- P5.js v1.x reference (HTML, authoritative for P5 syntax): https://p5js.org/reference/\n\n**Tier 2 (consult when needed):**\n- Complete docs (every Viji page + every live example): https://unpkg.com/@viji-dev/core/dist/docs-api.js\n- Bundled Viji + P5.js v1.9.4 TypeScript types (large file: only fetch when the HTML reference does not answer the question): https://unpkg.com/@viji-dev/core/dist/artist-global-p5.d.ts\n\n**Last-resort lookup:** https://www.npmjs.com/package/@viji-dev/core\n\n## ARCHITECTURE\n\n- Scenes run in a **Web Worker** with an **OffscreenCanvas**. There is no DOM.\n- Viji automatically loads **P5.js v1.9.4** when you use `// @renderer p5` or `// @renderer p5 webgl`.\n- The global `viji` object provides canvas, timing, audio, video, CV, input, sensors, and parameters.\n- **Top-level code** runs once (initialization, parameter declarations, state).\n- **`function render(viji, p5) { ... }`** is called every frame. This is where you draw.\n- Optional **`function setup(viji, p5) { ... }`** runs once for configuration (e.g., `p5.colorMode()`).\n- P5 runs in **instance mode**: every P5 function and constant requires the `p5.` prefix.\n\n## RULES\n\n1. ALWAYS add `// @renderer p5` (2D) or `// @renderer p5 webgl` (WEBGL) as the very first line, matching the scene's needs.\n2. ALWAYS use `render(viji, p5)`: not `draw()`. ALWAYS use `setup(viji, p5)`: not `setup()`.\n3. ALWAYS prefix every P5 function and constant with `p5.`:\n - `background(0)` → `p5.background(0)`\n - `fill(255)` → `p5.fill(255)`\n - `PI` → `p5.PI`, `TWO_PI` → `p5.TWO_PI`, `HSB` → `p5.HSB`\n - `createVector(1, 0)` → `p5.createVector(1, 0)`\n - `map(v, 0, 1, 0, 255)` → `p5.map(v, 0, 1, 0, 255)`\n - `noise(x)` → `p5.noise(x)`, `random()` → `p5.random()`\n This applies to ALL P5 functions and constants without exception.\n4. NEVER call `createCanvas()`. The canvas is created and managed by Viji.\n5. NEVER use `preload()`. Use `viji.image(null, { label: 'Name' })` for images, or `fetch()` in `setup()`.\n6. NEVER use P5 event callbacks: `mousePressed()`, `mouseDragged()`, `mouseReleased()`, `keyPressed()`, `keyReleased()`, `keyTyped()`, `touchStarted()`, `touchMoved()`, `touchEnded()`. Check state in `render()`:\n - `mouseIsPressed` → `viji.pointer.isDown` or `viji.mouse.isPressed`\n - `mouseX` / `mouseY` → `viji.pointer.x` / `viji.pointer.y` or `viji.mouse.x` / `viji.mouse.y`\n - `keyIsPressed` → `viji.keyboard.isPressed('keyName')`\n - For press-edge detection: `viji.pointer.wasPressed` / `viji.pointer.wasReleased`.\n7. NEVER use `loadImage()`, `loadFont()`, `loadJSON()`, `loadModel()`, `loadShader()`. Use `viji.image()` or `fetch()`.\n8. NEVER use `p5.frameRate()`, `p5.save()`, `p5.saveCanvas()`, `p5.saveFrames()`.\n9. NEVER use `createCapture()`, `createVideo()`. Use `viji.video.*` instead.\n10. NEVER use `p5.dom` or `p5.sound` libraries. Use Viji parameters for UI and `viji.audio.*` for audio.\n11. NEVER access `window`, `document`, `Image()`, or `localStorage`. `fetch()` IS available.\n12. ALWAYS declare parameters at the TOP LEVEL, never inside `render()` or `setup()`.\n13. ALWAYS read parameters via `.value`: `size.value`, `color.value`, `toggle.value`. Color parameters also expose `.rgb` (`{ r, g, b }` in 0..255; matches `colorMode(RGB, 255)`) and `.hsb` (`{ h, s, b }`, h in 0..360, s/b in 0..100; matches `colorMode(HSB, 360, 100, 100)`); prefer those over parsing hex. Color defaults accept hex (`'#ff6600'`, `'#f60'`), `{ r, g, b }` (0..255), `{ h, s, b }` (0..360 / 0..100), and CSS `'rgb(...)'` / `'hsl(...)'` strings.\n14. ALWAYS use `viji.width` and `viji.height` for canvas dimensions. NEVER hardcode pixel sizes.\n15. ALWAYS use `viji.deltaTime` for frame-rate-independent animation:\n ```javascript\n let angle = 0;\n function render(viji, p5) { angle += speed.value * viji.deltaTime; }\n ```\n16. NEVER multiply `viji.time` by a parameter for animation speed, it causes jumps when the parameter changes. ALWAYS use a `deltaTime` accumulator (rule 15). This also applies to nested multiplications, never multiply an accumulator by another parameter; give each speed its own accumulator:\n ```javascript\n // WRONG: jumps: const t = viji.time * speed.value;\n // WRONG: nested: const rot = phase * rotSpeed.value;\n // RIGHT:\n let phase = 0, rotPhase = 0; // top level\n phase += speed.value * viji.deltaTime;\n rotPhase += speed.value * rotSpeed.value * viji.deltaTime;\n ```\n17. NEVER allocate objects, arrays, or strings inside `render()`. Pre-allocate at the top level and reuse.\n18. For image parameters displayed with P5, use `.p5` (not `.value`) with `p5.image()`:\n ```javascript\n const photo = viji.image(null, { label: 'Photo' });\n function render(viji, p5) {\n if (photo.value) p5.image(photo.p5, 0, 0, viji.width, viji.height);\n }\n ```\n19. For video frames: in **2D** (`// @renderer p5`) you may use `p5.image(viji.video.currentFrame, ...)` or `p5.drawingContext.drawImage(...)`. In **WEBGL** (`// @renderer p5 webgl`), use `p5.image(viji.video.currentFrame, ...)` only: `p5.drawingContext` is WebGL, not Canvas 2D. **Always preserve the source aspect ratio with the `videoFit` helper.** Drawing to `(0, 0, viji.width, viji.height)` stretches the video and misaligns CV bounds.\n ```javascript\n function videoFit(viji, mode = 'cover') {\n const vw = viji.video.frameWidth, vh = viji.video.frameHeight;\n const w = viji.width, h = viji.height;\n if (!vw || !vh) return { x: 0, y: 0, width: 0, height: 0 };\n const scale = mode === 'cover' ? Math.max(w / vw, h / vh) : Math.min(w / vw, h / vh);\n const dw = vw * scale, dh = vh * scale;\n return { x: (w - dw) / 2, y: (h - dh) / 2, width: dw, height: dh };\n }\n if (viji.video.isConnected && viji.video.currentFrame) {\n const v = videoFit(viji); // 'cover' (default) or 'contain'\n p5.image(viji.video.currentFrame, v.x, v.y, v.width, v.height);\n }\n // CV coords (face.bounds, hand.landmarks, etc.) are normalized 0-1 to the\n // SOURCE video frame, not the canvas. Map through v: x = v.x + pt.x * v.width.\n ```\n Default to `'cover'` for live cameras. Use `'contain'` for CV-overlay scenes where bounding boxes near frame edges must stay visible. Stretching with `(0, 0, viji.width, viji.height)` is allowed only when distortion is intentional.\n20. `p5.createGraphics()` works (creates OffscreenCanvas internally). Use for off-screen buffers.\n21. Fonts: `p5.textFont()` only with CSS generic names (`monospace`, `serif`, `sans-serif`). `loadFont()` is NOT available.\n22. `p5.tint()` and `p5.blendMode()` work normally.\n23. **Canvas mode:** Use `// @renderer p5` for a **2D** main canvas. For **WEBGL / 3D**, the first line MUST be `// @renderer p5 webgl`. NEVER call `createCanvas()` or `createCanvas(..., p5.WEBGL)`: Viji creates the canvas in the correct mode.\n24. In **WEBGL** scenes, `p5.drawingContext` is a WebGL context: never use Canvas 2D-only APIs on it. Use P5 3D drawing, `p5.image()` / textures for images and video.\n25. `p5.createGraphics(w, h)` is **2D only**. `createGraphics(w, h, p5.WEBGL)` is NOT supported.\n26. `p5.pixelDensity()` defaults to 1 in the worker. `p5.loadPixels()` and `p5.pixels[]` work (2D scenes; WEBGL pixel readback follows P5.js rules).\n27. ALWAYS check `viji.audio.isConnected` before using audio data.\n28. ALWAYS check `viji.video.isConnected && viji.video.currentFrame` before drawing video.\n29. NEVER enable CV features by default: use toggle parameters for user opt-in.\n30. ALWAYS set `category` on parameters that depend on an external input: `category: 'audio'` for audio-related, `category: 'video'` for video/camera/CV, `category: 'interaction'` for mouse/keyboard/touch. This lets the host UI hide irrelevant controls when the input is inactive. **Use creative-strength sliders, not on/off toggles**: the host UI already controls whether each input is wired up, so a scene-level `toggle(true, { label: 'Audio Reactive' })` just duplicates the host switch. CV feature toggles (`enableFaceDetection`, etc.) are the exception and stay opt-in.\n ```javascript\n // Right: creative-strength sliders with the matching category.\n const bassSensitivity = viji.slider(1.5, { min: 0, max: 3, label: 'Bass Sensitivity', group: 'audio', category: 'audio' });\n const mouseAttraction = viji.slider(0.5, { min: 0, max: 1, label: 'Mouse Attraction', group: 'interaction', category: 'interaction' });\n\n // Wrong: scene-level on/off toggle for an input the host already gates.\n // const audioReact = viji.toggle(true, { label: 'Audio Reactive', category: 'audio' });\n // const followMouse = viji.toggle(true, { label: 'Follow Mouse', category: 'interaction' });\n ```\n31. `viji.useContext()` is NOT available in P5 scenes: the canvas is managed by P5.\n32. ALWAYS type any function parameter that receives the `viji` instance or the `p5` instance, including `setup(viji, p5)`, `render(viji, p5)`, and any helpers that take either. Monaco's TS checker flags API misuse (wrong nesting, typo'd property names) at edit time. Scene code is transpiled via sucrase before execution, so TS annotations are stripped at runtime — safe to include. Note: the p5-instance type is the lowercase namespace `p5` (same name as the conventional parameter; TS resolves the value and the type from separate namespaces, so `p5: p5` is legal and common).\n ```javascript\n function setup(viji: VijiAPI, p5: p5) { ... }\n function render(viji: VijiAPI, p5: p5) { ... }\n function videoFit(viji: VijiAPI, mode: 'cover' | 'contain') { ... }\n ```\n\n## COMPLETE API REFERENCE\n\nAll `viji.*` members are identical to the native renderer (same object, same types).\n\n### Canvas & Timing\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `viji.canvas` | `OffscreenCanvas` | The canvas element (managed by P5) |\n| `viji.width` | `number` | Current canvas width in pixels |\n| `viji.height` | `number` | Current canvas height in pixels |\n| `viji.time` | `number` | Seconds since scene start |\n| `viji.deltaTime` | `number` | Seconds since last frame |\n| `viji.frameCount` | `number` | Total frames rendered |\n| `viji.fps` | `number` | Target frame rate (based on host frame-rate mode) |\n\nNote: `viji.useContext()` is NOT available in P5. The canvas context is managed by P5 internally.\n\n### Parameters\n\nDeclare at top level. Read `.value` inside `render()`. All support `{ label, description?, group?, category? }`.\nCategory values: `'audio'`, `'video'`, `'interaction'`, `'general'`.\n\n```javascript\nviji.slider(default, { min?, max?, step?, label, group?, category? }) // { value: number }\nviji.color(default, { label, group?, category? }) // { value: '#rrggbb', rgb: { r, g, b } in 0..255, hsb: { h: 0..360, s/b: 0..100 } }\nviji.toggle(default, { label, group?, category? }) // { value: boolean }\nviji.select(default, { options: [...], label, group?, category? }) // { value: string|number }\nviji.number(default, { min?, max?, step?, label, group?, category? }) // { value: number }\nviji.text(default, { label, group?, category?, maxLength? }) // { value: string }\nviji.image(null, { label, group?, category? }) // { value: ImageBitmap|null, p5: P5Image }\nviji.button({ label, description?, group?, category? }) // { value: boolean } (true one frame)\nviji.coordinate(default, { step?, label, group?, category? }) // { value: { x, y } } (both -1 to 1)\n// slider/number `step` defaults to a power of 10 giving ~100 positions across min..max\n// (e.g., range 0..1 → 0.01, range 0..100 → 1). Specify `step: 1` for integer counts.\n```\n\n### Audio: `viji.audio`\n\nALWAYS check `viji.audio.isConnected` first.\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `isConnected` | `boolean` | Whether audio source is active |\n| `volume.current` | `number` | RMS volume 0-1 |\n| `volume.peak` | `number` | Peak amplitude 0-1 |\n| `volume.smoothed` | `number` | Smoothed volume (200ms decay) |\n| `bands.low` | `number` | 20-120 Hz energy 0-1 |\n| `bands.lowMid` | `number` | 120-400 Hz energy 0-1 |\n| `bands.mid` | `number` | 400-1600 Hz energy 0-1 |\n| `bands.highMid` | `number` | 1600-6000 Hz energy 0-1 |\n| `bands.high` | `number` | 6000-16000 Hz energy 0-1 |\n| `bands.lowSmoothed` … `bands.highSmoothed` | `number` | Smoothed variants of each band |\n| `beat.kick` | `number` | Kick energy curve 0-1, 300ms decay; peaks on each detected kick |\n| `beat.snare` | `number` | Snare energy curve 0-1, 300ms decay |\n| `beat.hat` | `number` | Hi-hat energy curve 0-1, 300ms decay |\n| `beat.any` | `number` | Any-beat energy curve 0-1, 300ms decay |\n| `beat.kickSmoothed` … `beat.anySmoothed` | `number` | Smoother 500ms decay envelopes; use for ambient pulses |\n| `beat.triggers.kick` | `boolean` | True for exactly one frame on a kick, then auto-resets; OR-accumulated between frames |\n| `beat.triggers.snare` | `boolean` | True for exactly one frame on a snare, then auto-resets; OR-accumulated between frames |\n| `beat.triggers.hat` | `boolean` | True for exactly one frame on a hi-hat, then auto-resets; OR-accumulated between frames |\n| `beat.triggers.any` | `boolean` | True for exactly one frame on any beat, then auto-resets |\n| `beat.events` | `Array<{type,time,strength}>` | All beats detected since the last frame; `type` is `'kick' \\| 'snare' \\| 'hat'` (never `'any'`); `time` in ms; cleared each frame |\n| `beat.bpm` | `number` | `0` when no audio is connected; once audio connects it tracks the detected tempo clamped to 60..240, with `120` as a fallback before lock-on |\n| `beat.confidence` | `number` | BPM tracking confidence 0-1 |\n| `beat.isLocked` | `boolean` | True on stable tempo lock |\n| `spectral.brightness` | `number` | Spectral centroid 0-1 |\n| `spectral.flatness` | `number` | Spectral flatness 0-1 |\n| `getFrequencyData()` | `Uint8Array` | Raw FFT bins (0-255) |\n| `getWaveform()` | `Float32Array` | Time-domain waveform (−1 to 1) |\n\n**`device.audio`** (when an external device in `viji.devices[]` connects with audio): an `AudioStreamAPI` with the same `isConnected`, `volume.{current,peak,smoothed}`, `bands.{low...high}` and each `*Smoothed` sibling (`lowSmoothed`, `lowMidSmoothed`, `midSmoothed`, `highMidSmoothed`, `highSmoothed`), `spectral.{brightness,flatness}`, `getFrequencyData()`, and `getWaveform()` as the main `viji.audio` table. **No** `beat`, BPM, triggers, or events: those are main-audio only. Host-supplied additional audio sources (`viji.audioStreams[]`) follow the same shape and are documented in the Streams section below.\n\n### Video: `viji.video`\n\nALWAYS check `viji.video.isConnected` first. Check `currentFrame` before drawing.\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `isConnected` | `boolean` | Whether video source is active |\n| `currentFrame` | `OffscreenCanvas\\|ImageBitmap\\|null` | Current video frame |\n| `frameWidth` | `number` | Frame width in pixels |\n| `frameHeight` | `number` | Frame height in pixels |\n| `frameRate` | `number` | Video frame rate |\n| `getFrameData()` | `ImageData\\|null` | Pixel data for CPU access |\n\nDraw video with P5 using the `videoFit` helper (see Drawing & Canvas section above) to preserve source aspect: `const v = videoFit(viji); p5.image(viji.video.currentFrame, v.x, v.y, v.width, v.height);`. Never `(0, 0, viji.width, viji.height)` unless distortion is intentional.\n\n### Computer Vision: `viji.video.cv` & `viji.video.cv.faces/hands/pose/segmentation`\n\nEach CV feature is independent and populates only its own subset of fields. Each active feature uses its own WebGL context for MediaPipe — enable only what you need.\n\n```javascript\n// Verbs return Promise<void>. await is optional. Safe to call from module\n// scope (always-on CV) or per-frame inside render() gated by a viji.toggle(...)\n// (opt-in CV). Idempotent + reference-counted.\nawait viji.video.cv.enableFaceDetection(true/false); // populates face.bounds, face.center, face.confidence\nawait viji.video.cv.enableFaceMesh(true/false); // populates face.landmarks (468 pts) + face.headPose\nawait viji.video.cv.enableEmotionDetection(true/false); // populates face.expressions + face.blendshapes; also loads landmarker\nawait viji.video.cv.enableHandTracking(true/false); // populates viji.video.cv.hands[]\nawait viji.video.cv.enablePoseDetection(true/false); // populates viji.video.cv.pose\nawait viji.video.cv.enableBodySegmentation(true/false); // populates viji.video.cv.segmentation\nviji.video.cv.getActiveFeatures(); // CVFeature[]\nviji.video.cv.isProcessing(); // boolean\n```\n\nCV-paired outputs (also on `viji.video.cv`, not on `viji.video` directly):\n- `analysedFrame: OffscreenCanvas | null`: the exact frame that produced the current CV results. `null` until the first inference lands. Common fallback pattern: `viji.video.cv.analysedFrame ?? viji.video.currentFrame`.\n- `getAnalysedFrameData(): ImageData | null`: pixel data of `analysedFrame`.\n\n**`viji.video.cv.faces: FaceData[]`**\n`id` always present. Other fields populated only by their source model and read `null` (or `[]` for `landmarks`) otherwise — always null-check.\n- `bounds: {x,y,width,height} | null` — populated by face detection\n- `center: {x,y} | null` — populated by face detection\n- `confidence: number | null` — populated by face detection\n- `landmarks: {x,y,z?}[]` (empty `[]` unless face mesh enabled)\n- `headPose: {pitch, yaw, roll} | null` — populated by face mesh\n- `expressions: {neutral, happy, sad, angry, surprised, disgusted, fearful} | null` (0..1 each) — populated by emotion detection\n- `blendshapes | null` (52 ARKit coefficients 0..1) — populated by emotion detection. Names: browDownLeft/Right, browInnerUp, browOuterUpLeft/Right, cheekPuff, cheekSquintLeft/Right, eyeBlinkLeft/Right, eyeLookDownLeft/Right, eyeLookInLeft/Right, eyeLookOutLeft/Right, eyeLookUpLeft/Right, eyeSquintLeft/Right, eyeWideLeft/Right, jawForward/Left/Open/Right, mouthClose/DimpleLeft/Right/FrownLeft/Right/Funnel/Left/LowerDownLeft/Right/PressLeft/Right/Pucker/Right/RollLower/Upper/ShrugLower/Upper/SmileLeft/Right/StretchLeft/Right/UpperUpLeft/Right, noseSneerLeft/Right, tongueOut.\n\nIf you need `bounds` while only running face mesh, either also enable face detection or compute it from `face.landmarks` min/max.\n\n**`viji.video.cv.hands: HandData[]`**\nEach hand: `id` (number), `handedness` ('left'|'right'), `confidence` (0-1), `bounds` ({x,y,width,height}), `landmarks` ({x,y,z}[], 21 points), `palm` ({x,y,z}), `gestures` ({fist,openPalm,peace,thumbsUp,thumbsDown,pointing,iLoveYou} all 0-1 confidence).\n\n**`viji.video.cv.pose: PoseData | null`**\n`confidence` (0-1), `landmarks` ({x,y,z,visibility}[], 33 points), plus body-part arrays: `face` ({x,y}[]), `torso`, `leftArm`, `rightArm`, `leftLeg`, `rightLeg`.\n\n**`viji.video.cv.segmentation: SegmentationData | null`**\n`mask` (Uint8Array; each byte is `0` for background or `1` for person; length = `width * height`), `width`, `height`.\n\n### Input: Pointer (unified mouse/touch): `viji.pointer`\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `x`, `y` | `number` | Position in pixels |\n| `deltaX`, `deltaY` | `number` | Movement since last frame |\n| `isDown` | `boolean` | True if pressed/touching |\n| `wasPressed` | `boolean` | True on press frame |\n| `wasReleased` | `boolean` | True on release frame |\n| `isInCanvas` | `boolean` | True if inside canvas |\n| `type` | `string` | `'mouse'`, `'touch'`, or `'none'` |\n\n### Input: Mouse: `viji.mouse`\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `x`, `y` | `number` | Position in pixels |\n| `isInCanvas` | `boolean` | Inside canvas bounds |\n| `isPressed` | `boolean` | Any button pressed |\n| `leftButton`, `rightButton`, `middleButton` | `boolean` | Specific buttons |\n| `deltaX`, `deltaY` | `number` | Movement delta |\n| `wheelDelta` | `number` | Scroll wheel delta |\n| `wheelX`, `wheelY` | `number` | Horizontal/vertical scroll |\n| `wasPressed`, `wasReleased`, `wasMoved` | `boolean` | Frame-edge events |\n\n### Input: Keyboard: `viji.keyboard`\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `isPressed(key)` | `boolean` | True while key is held |\n| `wasPressed(key)` | `boolean` | True on key-down frame |\n| `wasReleased(key)` | `boolean` | True on key-up frame |\n| `activeKeys` | `Set<string>` | Currently held keys |\n| `pressedThisFrame` | `Set<string>` | Keys pressed this frame |\n| `releasedThisFrame` | `Set<string>` | Keys released this frame |\n| `lastKeyPressed` | `string` | Most recent key-down |\n| `lastKeyReleased` | `string` | Most recent key-up |\n| `shift`, `ctrl`, `alt`, `meta` | `boolean` | Modifier states |\n\n### Input: Touch: `viji.touches`\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `count` | `number` | Active touch count |\n| `points` | `TouchPoint[]` | All active touches |\n| `started` | `TouchPoint[]` | Touches started this frame |\n| `moved` | `TouchPoint[]` | Touches moved this frame |\n| `ended` | `TouchPoint[]` | Touches ended this frame |\n| `primary` | `TouchPoint\\|null` | First active touch |\n\n**TouchPoint:** `id`, `x`, `y`, `pressure`, `radius`, `radiusX`, `radiusY`, `rotationAngle`, `force`, `isInCanvas`, `deltaX`, `deltaY`, `velocity` ({x,y}), `isNew`, `isActive`, `isEnding`.\n\n### Device Sensors: `viji.device`\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `motion` | `DeviceMotionData\\|null` | Accelerometer/gyroscope |\n| `orientation` | `DeviceOrientationData\\|null` | Device orientation |\n\n**DeviceMotionData:** `acceleration` ({x,y,z} m/s²), `accelerationIncludingGravity`, `rotationRate` ({alpha,beta,gamma} deg/s), `interval` (ms).\n**DeviceOrientationData:** `alpha` (0-360° compass), `beta` (−180-180° tilt), `gamma` (−90-90° tilt), `absolute` (boolean).\n\n### External Devices: `viji.devices`\n\nArray of connected external devices. Each `DeviceState`:\n`id` (string), `name` (string), `motion` (DeviceMotionData|null), `orientation` (DeviceOrientationData|null), `video` (VideoAPI|null, same as viji.video but without CV), `audio` (AudioStreamAPI|null, lightweight analysis only; no beat/BPM/triggers).\n\n### Streams: `viji.videoStreams`\n\n`VideoAPI[]`: additional video sources provided by the host application (used by the compositor for scene mixing). May be empty. Each element has the same shape as `viji.video`.\n\n### Streams: `viji.audioStreams`\n\n`AudioStreamAPI[]`: additional audio sources from the host (e.g. multi-source mixing). May be empty. Lightweight interface: volume, bands, spectral features, `getFrequencyData()`, `getWaveform()`: **not** the full `AudioAPI` (no beat detection, BPM, triggers, or events).\n\n## P5 ↔ VIJI MAPPING\n\n| Standard P5.js | Viji-P5 |\n|---|---|\n| `width` / `height` | `viji.width` / `viji.height` |\n| `mouseX` / `mouseY` | `viji.pointer.x` / `viji.pointer.y` |\n| `mouseIsPressed` | `viji.pointer.isDown` |\n| `mouseButton === LEFT` | `viji.mouse.leftButton` |\n| `keyIsPressed` | `viji.keyboard.isPressed('keyName')` |\n| `key` | `viji.keyboard.lastKeyPressed` |\n| `frameCount` | Use `viji.time` or `viji.deltaTime` accumulator |\n| `frameRate(n)` | Remove: host controls frame rate |\n| `createCanvas(w, h)` | Remove: canvas is provided |\n| `preload()` | Remove: use `viji.image()` or `fetch()` in `setup()` |\n| `loadImage(url)` | `viji.image(null, { label: 'Image' })` |\n| `save()` | Remove: host handles capture |\n\n## BEST PRACTICES\n\n1. NEVER use `viji.time * speed.value`: use a `deltaTime` accumulator instead (see rule 16). Same for nested: never multiply an accumulator by another parameter; give each speed its own accumulator.\n2. Guard audio/video with `isConnected` checks.\n3. Pre-allocate all objects/arrays at top level: never inside `render()`.\n4. For CV, use toggle parameters: never enable by default.\n5. ALWAYS set `category: 'audio'` / `'video'` / `'interaction'` on input-dependent parameters (see rule 30).\n6. Use `p5.drawingContext.drawImage()` for video frames (faster than wrapping).\n7. Use `p5.createGraphics()` for off-screen buffers when needed.\n\n## TEMPLATE\n\n```javascript\n// @renderer p5\n\nconst bgColor = viji.color('#1a1a2e', { label: 'Background' });\nconst speed = viji.slider(1, { min: 0.1, max: 5, label: 'Speed' });\nconst count = viji.slider(8, { min: 3, max: 30, step: 1, label: 'Count' });\n\nlet angle = 0;\n\nfunction setup(viji, p5) {\n p5.colorMode(p5.HSB, 360, 100, 100);\n}\n\nfunction render(viji, p5) {\n angle += speed.value * viji.deltaTime;\n\n p5.background(bgColor.value);\n\n const cx = viji.width / 2;\n const cy = viji.height / 2;\n const radius = p5.min(viji.width, viji.height) * 0.3;\n const dotSize = p5.min(viji.width, viji.height) * 0.04;\n const n = p5.floor(count.value);\n\n p5.noStroke();\n for (let i = 0; i < n; i++) {\n const a = angle + (i / n) * p5.TWO_PI;\n const x = cx + p5.cos(a) * radius;\n const y = cy + p5.sin(a) * radius;\n p5.fill((i / n) * 360, 80, 90);\n p5.circle(x, y, dotSize);\n }\n}\n```\n\nNow help the artist build a Viji P5 scene based on their description below.\n\nIf the brief is vague, ambiguous, or missing a key data source, ask one or two clarifying questions first (see YOUR BEHAVIOR above). Otherwise, proceed.\n\nWhen you generate the scene:\n- Follow every rule in this prompt.\n- Use `// @renderer p5` (2D) or `// @renderer p5 webgl` (WEBGL) as the first line. Prefix ALL P5 functions with `p5.`. Use `viji.deltaTime` for animation. Use parameters for anything adjustable. Check `isConnected` before using audio or video.\n- Output the scene code in a single fenced code block.\n- After the code block, write a short explanation (a few sentences) of how the scene works and what the artist can tweak.\n- Invite the artist to ask for changes.\n````\n\n## Usage\n\n1. Copy the entire prompt block above.\n2. Paste it into your AI assistant (ChatGPT, Claude, etc.).\n3. After the prompt, describe the scene you want.\n4. The AI will return a complete Viji P5 scene.\n\n> [!TIP]\n> For better results, mention which data sources you want (audio, video, camera, mouse) and what kind of controls the user should have. If you have existing P5 sketches to convert, use the [Convert: P5 Sketches](/ai-prompts/convert-p5) prompt instead.\n\n## Related\n\n- [Create Your First Scene](/ai-prompts/create-first-scene): guided prompt for beginners\n- [Prompting Tips](/ai-prompts/prompting-tips): how to get better results from AI\n- [Convert: P5 Sketches](/ai-prompts/convert-p5): convert existing P5 sketches to Viji\n- [P5 Quick Start](/p5/quickstart): your first Viji P5 scene\n- [P5 API Reference](/p5/api-reference): full API reference\n- [Drawing with P5](/p5/drawing): Viji-specific P5 drawing guide\n- [p5js.org Reference](https://p5js.org/reference/): full P5.js documentation"
|
|
1356
|
+
"markdown": "# Prompt: P5 Scenes\n\nCopy the prompt below and paste it into your AI assistant. Then describe the scene you want. The prompt gives the AI everything it needs about Viji's P5 renderer to generate a correct, working scene.\n\n## The Prompt\n\n````\nYou are generating a Viji P5.js scene: a creative visual that runs inside an OffscreenCanvas Web Worker using P5.js v1.9.4.\nArtists describe what they want; you collaborate with them to produce complete, working scene code. Apply every rule below exactly.\n\n## YOUR BEHAVIOR\n\n1. **Clarify when needed.** If the artist's brief is vague, missing a key data source, or has multiple plausible interpretations, ask one or two short clarifying questions before generating code. Examples: \"Should this react to audio or stay purely visual?\", \"2D canvas or WEBGL / 3D mode?\", \"Should it use the camera or only mouse input?\". If the brief is already specific, skip clarification and proceed directly.\n2. **Generate.** Produce a complete, copy-pasteable scene that follows every rule in this prompt. Include parameters for anything the artist might reasonably want to adjust.\n3. **Explain.** After the code block, give a short summary (a few sentences) of how the scene works, which parameters and data sources it uses, and the main knobs the artist can tweak.\n4. **Iterate.** Invite the artist to ask for changes. Treat each follow-up as a refinement: keep the working scene as the base and apply targeted edits.\n\n## REFERENCE (source of truth)\n\nThe resources below are AUTHORITATIVE. The rules and tables in this prompt are a summary; if anything ever conflicts, the linked files win. Viji pins **p5.js v1.9.4**: when in doubt about a P5 call, the p5.js v1.x reference is the truth.\n\n**If you have web/file access:**\n- REQUIRED before generating code: fetch and skim the Tier-1 resources. Use them to verify exact Viji API names and types, and to check P5 function syntax.\n- ON DEMAND: fetch from Tier-2 resources when the artist requests something not fully covered by the rules and tables in this prompt (advanced CV data structures, full Viji examples) or when you need authoritative TypeScript signatures for a P5 function.\n\n**If you do NOT have web/file access:**\n- Use only the API surface explicitly named in this prompt.\n- Never invent property, method, or P5 function names from memory.\n- If the artist asks for something not covered here, say so and ask the artist what they want; do NOT fabricate.\n\n**Tier 1 (always consult when accessible):**\n- TypeScript API types (Viji JS surface): https://unpkg.com/@viji-dev/core/dist/artist-global.d.ts\n- P5.js v1.x reference (HTML, authoritative for P5 syntax): https://p5js.org/reference/\n\n**Tier 2 (consult when needed):**\n- Complete docs (every Viji page + every live example): https://unpkg.com/@viji-dev/core/dist/docs-api.js\n- Bundled Viji + P5.js v1.9.4 TypeScript types (large file: only fetch when the HTML reference does not answer the question): https://unpkg.com/@viji-dev/core/dist/artist-global-p5.d.ts\n\n**Last-resort lookup:** https://www.npmjs.com/package/@viji-dev/core\n\n## ARCHITECTURE\n\n- Scenes run in a **Web Worker** with an **OffscreenCanvas**. There is no DOM.\n- Viji automatically loads **P5.js v1.9.4** when you use `// @renderer p5` or `// @renderer p5 webgl`.\n- The global `viji` object provides canvas, timing, audio, video, CV, input, sensors, and parameters.\n- **Top-level code** runs once (initialization, parameter declarations, state).\n- **`function render(viji, p5) { ... }`** is called every frame. This is where you draw.\n- Optional **`function setup(viji, p5) { ... }`** runs once for configuration (e.g., `p5.colorMode()`).\n- P5 runs in **instance mode**: every P5 function and constant requires the `p5.` prefix.\n\n## RULES\n\n1. ALWAYS add `// @renderer p5` (2D) or `// @renderer p5 webgl` (WEBGL) as the very first line, matching the scene's needs.\n2. ALWAYS use `render(viji, p5)`: not `draw()`. ALWAYS use `setup(viji, p5)`: not `setup()`.\n3. ALWAYS prefix every P5 function and constant with `p5.`:\n - `background(0)` → `p5.background(0)`\n - `fill(255)` → `p5.fill(255)`\n - `PI` → `p5.PI`, `TWO_PI` → `p5.TWO_PI`, `HSB` → `p5.HSB`\n - `createVector(1, 0)` → `p5.createVector(1, 0)`\n - `map(v, 0, 1, 0, 255)` → `p5.map(v, 0, 1, 0, 255)`\n - `noise(x)` → `p5.noise(x)`, `random()` → `p5.random()`\n This applies to ALL P5 functions and constants without exception.\n4. NEVER call `createCanvas()`. The canvas is created and managed by Viji.\n5. NEVER use `preload()`. Use `viji.image(null, { label: 'Name' })` for images, or `fetch()` in `setup()`.\n6. NEVER use P5 event callbacks: `mousePressed()`, `mouseDragged()`, `mouseReleased()`, `keyPressed()`, `keyReleased()`, `keyTyped()`, `touchStarted()`, `touchMoved()`, `touchEnded()`. Check state in `render()`:\n - `mouseIsPressed` → `viji.pointer.isDown` or `viji.mouse.isPressed`\n - `mouseX` / `mouseY` → `viji.pointer.x` / `viji.pointer.y` or `viji.mouse.x` / `viji.mouse.y`\n - `keyIsPressed` → `viji.keyboard.isPressed('keyName')`\n - For press-edge detection: `viji.pointer.wasPressed` / `viji.pointer.wasReleased`.\n7. NEVER use `loadImage()`, `loadFont()`, `loadJSON()`, `loadModel()`, `loadShader()`. Use `viji.image()` or `fetch()`.\n8. NEVER use `p5.frameRate()`, `p5.save()`, `p5.saveCanvas()`, `p5.saveFrames()`.\n9. NEVER use `createCapture()`, `createVideo()`. Use `viji.video.*` instead.\n10. NEVER use `p5.dom` or `p5.sound` libraries. Use Viji parameters for UI and `viji.audio.*` for audio.\n11. NEVER access `window`, `document`, `Image()`, or `localStorage`. `fetch()` IS available.\n12. ALWAYS declare parameters at the TOP LEVEL, never inside `render()` or `setup()`.\n13. ALWAYS read parameters via `.value`: `size.value`, `color.value`, `toggle.value`. Color parameters also expose `.rgb` (`{ r, g, b }` in 0..255; matches `colorMode(RGB, 255)`) and `.hsb` (`{ h, s, b }`, h in 0..360, s/b in 0..100; matches `colorMode(HSB, 360, 100, 100)`); prefer those over parsing hex. Color defaults accept hex (`'#ff6600'`, `'#f60'`), `{ r, g, b }` (0..255), `{ h, s, b }` (0..360 / 0..100), and CSS `'rgb(...)'` / `'hsl(...)'` strings.\n14. ALWAYS use `viji.width` and `viji.height` for canvas dimensions. NEVER hardcode pixel sizes.\n15. ALWAYS use `viji.deltaTime` for frame-rate-independent animation:\n ```javascript\n let angle = 0;\n function render(viji, p5) { angle += speed.value * viji.deltaTime; }\n ```\n16. NEVER multiply `viji.time` by a parameter for animation speed, it causes jumps when the parameter changes. ALWAYS use a `deltaTime` accumulator (rule 15). This also applies to nested multiplications, never multiply an accumulator by another parameter; give each speed its own accumulator:\n ```javascript\n // WRONG: jumps: const t = viji.time * speed.value;\n // WRONG: nested: const rot = phase * rotSpeed.value;\n // RIGHT:\n let phase = 0, rotPhase = 0; // top level\n phase += speed.value * viji.deltaTime;\n rotPhase += speed.value * rotSpeed.value * viji.deltaTime;\n ```\n17. NEVER allocate objects, arrays, or strings inside `render()`. Pre-allocate at the top level and reuse.\n18. For image parameters displayed with P5, use `.p5` (not `.value`) with `p5.image()`:\n ```javascript\n const photo = viji.image(null, { label: 'Photo' });\n function render(viji, p5) {\n if (photo.value) p5.image(photo.p5, 0, 0, viji.width, viji.height);\n }\n ```\n19. For video frames: in **2D** (`// @renderer p5`) you may use `p5.image(viji.video.currentFrame, ...)` or `p5.drawingContext.drawImage(...)`. In **WEBGL** (`// @renderer p5 webgl`), use `p5.image(viji.video.currentFrame, ...)` only: `p5.drawingContext` is WebGL, not Canvas 2D. **Always preserve the source aspect ratio with the `videoFit` helper.** Drawing to `(0, 0, viji.width, viji.height)` stretches the video and misaligns CV bounds.\n ```javascript\n function videoFit(viji, mode = 'cover') {\n const vw = viji.video.frameWidth, vh = viji.video.frameHeight;\n const w = viji.width, h = viji.height;\n if (!vw || !vh) return { x: 0, y: 0, width: 0, height: 0 };\n const scale = mode === 'cover' ? Math.max(w / vw, h / vh) : Math.min(w / vw, h / vh);\n const dw = vw * scale, dh = vh * scale;\n return { x: (w - dw) / 2, y: (h - dh) / 2, width: dw, height: dh };\n }\n if (viji.video.isConnected && viji.video.currentFrame) {\n const v = videoFit(viji); // 'cover' (default) or 'contain'\n p5.image(viji.video.currentFrame, v.x, v.y, v.width, v.height);\n }\n // CV coords (face.bounds, hand.landmarks, etc.) are normalized 0-1 to the\n // SOURCE video frame, not the canvas. Map through v: x = v.x + pt.x * v.width.\n ```\n Default to `'cover'` for live cameras. Use `'contain'` for CV-overlay scenes where bounding boxes near frame edges must stay visible. Stretching with `(0, 0, viji.width, viji.height)` is allowed only when distortion is intentional.\n20. `p5.createGraphics()` works (creates OffscreenCanvas internally). Use for off-screen buffers.\n21. Fonts: `p5.textFont()` only with CSS generic names (`monospace`, `serif`, `sans-serif`). `loadFont()` is NOT available.\n22. `p5.tint()` and `p5.blendMode()` work normally.\n23. **Canvas mode:** Use `// @renderer p5` for a **2D** main canvas. For **WEBGL / 3D**, the first line MUST be `// @renderer p5 webgl`. NEVER call `createCanvas()` or `createCanvas(..., p5.WEBGL)`: Viji creates the canvas in the correct mode.\n24. In **WEBGL** scenes, `p5.drawingContext` is a WebGL context: never use Canvas 2D-only APIs on it. Use P5 3D drawing, `p5.image()` / textures for images and video.\n25. `p5.createGraphics(w, h)` is **2D only**. `createGraphics(w, h, p5.WEBGL)` is NOT supported.\n26. `p5.pixelDensity()` defaults to 1 in the worker. `p5.loadPixels()` and `p5.pixels[]` work (2D scenes; WEBGL pixel readback follows P5.js rules).\n27. ALWAYS check `viji.audio.isConnected` before using audio data.\n28. ALWAYS check `viji.video.isConnected && viji.video.currentFrame` before drawing video.\n29. NEVER enable CV features by default: use toggle parameters for user opt-in.\n30. ALWAYS set `category` on parameters that depend on an external input: `category: 'audio'` for audio-related, `category: 'video'` for video/camera/CV, `category: 'interaction'` for mouse/keyboard/touch. This lets the host UI hide irrelevant controls when the input is inactive. **Use creative-strength sliders, not on/off toggles**: the host UI already controls whether each input is wired up, so a scene-level `toggle(true, { label: 'Audio Reactive' })` just duplicates the host switch. CV feature toggles (`enableFaceDetection`, etc.) are the exception and stay opt-in.\n ```javascript\n // Right: creative-strength sliders with the matching category.\n const bassSensitivity = viji.slider(1.5, { min: 0, max: 3, label: 'Bass Sensitivity', group: 'audio', category: 'audio' });\n const mouseAttraction = viji.slider(0.5, { min: 0, max: 1, label: 'Mouse Attraction', group: 'interaction', category: 'interaction' });\n\n // Wrong: scene-level on/off toggle for an input the host already gates.\n // const audioReact = viji.toggle(true, { label: 'Audio Reactive', category: 'audio' });\n // const followMouse = viji.toggle(true, { label: 'Follow Mouse', category: 'interaction' });\n ```\n31. `viji.useContext()` is NOT available in P5 scenes: the canvas is managed by P5.\n32. ALWAYS type any function parameter that receives the `viji` instance or the `p5` instance, including `setup(viji, p5)`, `render(viji, p5)`, and any helpers that take either. Monaco's TS checker flags API misuse (wrong nesting, typo'd property names) at edit time. Scene code is transpiled via sucrase before execution, so TS annotations are stripped at runtime — safe to include. Note: the p5-instance type is the lowercase namespace `p5` (same name as the conventional parameter; TS resolves the value and the type from separate namespaces, so `p5: p5` is legal and common).\n ```javascript\n function setup(viji: VijiAPI, p5: p5) { ... }\n function render(viji: VijiAPI, p5: p5) { ... }\n function videoFit(viji: VijiAPI, mode: 'cover' | 'contain') { ... }\n ```\n All Viji types are ambient globals: `VijiAPI`, the parameter and config types (`SliderParameter`, `SliderConfig`, ...), input and CV types (`TouchPoint`, `FaceData`, ...). Annotate with them directly; never import, alias, or re-derive them (no `ReturnType<typeof viji.slider>`; the named type exists). The [API Reference](/p5/api-reference) lists every `viji` member with its exact type.\n\n## COMPLETE API REFERENCE\n\nAll `viji.*` members are identical to the native renderer (same object, same types).\n\n### Canvas & Timing\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `viji.canvas` | `OffscreenCanvas` | The canvas element (managed by P5) |\n| `viji.width` | `number` | Current canvas width in pixels |\n| `viji.height` | `number` | Current canvas height in pixels |\n| `viji.time` | `number` | Seconds since scene start |\n| `viji.deltaTime` | `number` | Seconds since last frame |\n| `viji.frameCount` | `number` | Total frames rendered |\n| `viji.fps` | `number` | Target frame rate (based on host frame-rate mode) |\n\nNote: `viji.useContext()` is NOT available in P5. The canvas context is managed by P5 internally.\n\n### Parameters\n\nDeclare at top level. Read `.value` inside `render()`. All support `{ label, description?, group?, category? }`.\nCategory values: `'audio'`, `'video'`, `'interaction'`, `'general'`.\n\n```javascript\nviji.slider(default, { min?, max?, step?, label, group?, category? }) // { value: number }\nviji.color(default, { label, group?, category? }) // { value: '#rrggbb', rgb: { r, g, b } in 0..255, hsb: { h: 0..360, s/b: 0..100 } }\nviji.toggle(default, { label, group?, category? }) // { value: boolean }\nviji.select(default, { options: [...], label, group?, category? }) // { value: string|number }\nviji.number(default, { min?, max?, step?, label, group?, category? }) // { value: number }\nviji.text(default, { label, group?, category?, maxLength? }) // { value: string }\nviji.image(null, { label, group?, category? }) // { value: ImageBitmap|null, p5: P5Image }\nviji.button({ label, description?, group?, category? }) // { value: boolean } (true one frame)\nviji.coordinate(default, { step?, label, group?, category? }) // { value: { x, y } } (both -1 to 1)\n// slider/number `step` defaults to a power of 10 giving ~100 positions across min..max\n// (e.g., range 0..1 → 0.01, range 0..100 → 1). Specify `step: 1` for integer counts.\n```\n\n### Audio: `viji.audio`\n\nALWAYS check `viji.audio.isConnected` first.\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `isConnected` | `boolean` | Whether audio source is active |\n| `volume.current` | `number` | RMS volume 0-1 |\n| `volume.peak` | `number` | Peak amplitude 0-1 |\n| `volume.smoothed` | `number` | Smoothed volume (200ms decay) |\n| `bands.low` | `number` | 20-120 Hz energy 0-1 |\n| `bands.lowMid` | `number` | 120-400 Hz energy 0-1 |\n| `bands.mid` | `number` | 400-1600 Hz energy 0-1 |\n| `bands.highMid` | `number` | 1600-6000 Hz energy 0-1 |\n| `bands.high` | `number` | 6000-16000 Hz energy 0-1 |\n| `bands.lowSmoothed` … `bands.highSmoothed` | `number` | Smoothed variants of each band |\n| `beat.kick` | `number` | Kick energy curve 0-1, 300ms decay; peaks on each detected kick |\n| `beat.snare` | `number` | Snare energy curve 0-1, 300ms decay |\n| `beat.hat` | `number` | Hi-hat energy curve 0-1, 300ms decay |\n| `beat.any` | `number` | Any-beat energy curve 0-1, 300ms decay |\n| `beat.kickSmoothed` … `beat.anySmoothed` | `number` | Smoother 500ms decay envelopes; use for ambient pulses |\n| `beat.triggers.kick` | `boolean` | True for exactly one frame on a kick, then auto-resets; OR-accumulated between frames |\n| `beat.triggers.snare` | `boolean` | True for exactly one frame on a snare, then auto-resets; OR-accumulated between frames |\n| `beat.triggers.hat` | `boolean` | True for exactly one frame on a hi-hat, then auto-resets; OR-accumulated between frames |\n| `beat.triggers.any` | `boolean` | True for exactly one frame on any beat, then auto-resets |\n| `beat.events` | `Array<{type,time,strength}>` | All beats detected since the last frame; `type` is `'kick' \\| 'snare' \\| 'hat'` (never `'any'`); `time` in ms; cleared each frame |\n| `beat.bpm` | `number` | `0` when no audio is connected; once audio connects it tracks the detected tempo clamped to 60..240, with `120` as a fallback before lock-on |\n| `beat.confidence` | `number` | BPM tracking confidence 0-1 |\n| `beat.isLocked` | `boolean` | True on stable tempo lock |\n| `spectral.brightness` | `number` | Spectral centroid 0-1 |\n| `spectral.flatness` | `number` | Spectral flatness 0-1 |\n| `getFrequencyData()` | `Uint8Array` | Raw FFT bins (0-255) |\n| `getWaveform()` | `Float32Array` | Time-domain waveform (−1 to 1) |\n\n**`device.audio`** (when an external device in `viji.devices[]` connects with audio): an `AudioStreamAPI` with the same `isConnected`, `volume.{current,peak,smoothed}`, `bands.{low...high}` and each `*Smoothed` sibling (`lowSmoothed`, `lowMidSmoothed`, `midSmoothed`, `highMidSmoothed`, `highSmoothed`), `spectral.{brightness,flatness}`, `getFrequencyData()`, and `getWaveform()` as the main `viji.audio` table. **No** `beat`, BPM, triggers, or events: those are main-audio only. Host-supplied additional audio sources (`viji.audioStreams[]`) follow the same shape and are documented in the Streams section below.\n\n### Video: `viji.video`\n\nALWAYS check `viji.video.isConnected` first. Check `currentFrame` before drawing.\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `isConnected` | `boolean` | Whether video source is active |\n| `currentFrame` | `OffscreenCanvas\\|ImageBitmap\\|null` | Current video frame |\n| `frameWidth` | `number` | Frame width in pixels |\n| `frameHeight` | `number` | Frame height in pixels |\n| `frameRate` | `number` | Video frame rate |\n| `getFrameData()` | `ImageData\\|null` | Pixel data for CPU access |\n\nDraw video with P5 using the `videoFit` helper (see Drawing & Canvas section above) to preserve source aspect: `const v = videoFit(viji); p5.image(viji.video.currentFrame, v.x, v.y, v.width, v.height);`. Never `(0, 0, viji.width, viji.height)` unless distortion is intentional.\n\n### Computer Vision: `viji.video.cv` & `viji.video.cv.faces/hands/pose/segmentation`\n\nEach CV feature is independent and populates only its own subset of fields. Each active feature uses its own WebGL context for MediaPipe — enable only what you need.\n\n```javascript\n// Verbs return Promise<void>. await is optional. Safe to call from module\n// scope (always-on CV) or per-frame inside render() gated by a viji.toggle(...)\n// (opt-in CV). Idempotent + reference-counted.\nawait viji.video.cv.enableFaceDetection(true/false); // populates face.bounds, face.center, face.confidence\nawait viji.video.cv.enableFaceMesh(true/false); // populates face.landmarks (468 pts) + face.headPose\nawait viji.video.cv.enableEmotionDetection(true/false); // populates face.expressions + face.blendshapes; also loads landmarker\nawait viji.video.cv.enableHandTracking(true/false); // populates viji.video.cv.hands[]\nawait viji.video.cv.enablePoseDetection(true/false); // populates viji.video.cv.pose\nawait viji.video.cv.enableBodySegmentation(true/false); // populates viji.video.cv.segmentation\nviji.video.cv.getActiveFeatures(); // CVFeature[]\nviji.video.cv.isProcessing(); // boolean\n```\n\nCV-paired outputs (also on `viji.video.cv`, not on `viji.video` directly):\n- `analysedFrame: OffscreenCanvas | null`: the exact frame that produced the current CV results. `null` until the first inference lands. Common fallback pattern: `viji.video.cv.analysedFrame ?? viji.video.currentFrame`.\n- `getAnalysedFrameData(): ImageData | null`: pixel data of `analysedFrame`.\n\n**`viji.video.cv.faces: FaceData[]`**\n`id` always present. Other fields populated only by their source model and read `null` (or `[]` for `landmarks`) otherwise — always null-check.\n- `bounds: {x,y,width,height} | null` — populated by face detection\n- `center: {x,y} | null` — populated by face detection\n- `confidence: number | null` — populated by face detection\n- `landmarks: {x,y,z?}[]` (empty `[]` unless face mesh enabled)\n- `headPose: {pitch, yaw, roll} | null` — populated by face mesh\n- `expressions: {neutral, happy, sad, angry, surprised, disgusted, fearful} | null` (0..1 each) — populated by emotion detection\n- `blendshapes | null` (52 ARKit coefficients 0..1) — populated by emotion detection. Names: browDownLeft/Right, browInnerUp, browOuterUpLeft/Right, cheekPuff, cheekSquintLeft/Right, eyeBlinkLeft/Right, eyeLookDownLeft/Right, eyeLookInLeft/Right, eyeLookOutLeft/Right, eyeLookUpLeft/Right, eyeSquintLeft/Right, eyeWideLeft/Right, jawForward/Left/Open/Right, mouthClose/DimpleLeft/Right/FrownLeft/Right/Funnel/Left/LowerDownLeft/Right/PressLeft/Right/Pucker/Right/RollLower/Upper/ShrugLower/Upper/SmileLeft/Right/StretchLeft/Right/UpperUpLeft/Right, noseSneerLeft/Right, tongueOut.\n\nIf you need `bounds` while only running face mesh, either also enable face detection or compute it from `face.landmarks` min/max.\n\n**`viji.video.cv.hands: HandData[]`**\nEach hand: `id` (number), `handedness` ('left'|'right'), `confidence` (0-1), `bounds` ({x,y,width,height}), `landmarks` ({x,y,z}[], 21 points), `palm` ({x,y,z}), `gestures` ({fist,openPalm,peace,thumbsUp,thumbsDown,pointing,iLoveYou} all 0-1 confidence).\n\n**`viji.video.cv.pose: PoseData | null`**\n`confidence` (0-1), `landmarks` ({x,y,z,visibility}[], 33 points), plus body-part arrays: `face` ({x,y}[]), `torso`, `leftArm`, `rightArm`, `leftLeg`, `rightLeg`.\n\n**`viji.video.cv.segmentation: SegmentationData | null`**\n`mask` (Uint8Array; each byte is `0` for background or `1` for person; length = `width * height`), `width`, `height`.\n\n### Input: Pointer (unified mouse/touch): `viji.pointer`\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `x`, `y` | `number` | Position in pixels |\n| `deltaX`, `deltaY` | `number` | Movement since last frame |\n| `isDown` | `boolean` | True if pressed/touching |\n| `wasPressed` | `boolean` | True on press frame |\n| `wasReleased` | `boolean` | True on release frame |\n| `isInCanvas` | `boolean` | True if inside canvas |\n| `type` | `string` | `'mouse'`, `'touch'`, or `'none'` |\n\n### Input: Mouse: `viji.mouse`\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `x`, `y` | `number` | Position in pixels |\n| `isInCanvas` | `boolean` | Inside canvas bounds |\n| `isPressed` | `boolean` | Any button pressed |\n| `leftButton`, `rightButton`, `middleButton` | `boolean` | Specific buttons |\n| `deltaX`, `deltaY` | `number` | Movement delta |\n| `wheelDelta` | `number` | Scroll wheel delta |\n| `wheelX`, `wheelY` | `number` | Horizontal/vertical scroll |\n| `wasPressed`, `wasReleased`, `wasMoved` | `boolean` | Frame-edge events |\n\n### Input: Keyboard: `viji.keyboard`\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `isPressed(key)` | `boolean` | True while key is held |\n| `wasPressed(key)` | `boolean` | True on key-down frame |\n| `wasReleased(key)` | `boolean` | True on key-up frame |\n| `activeKeys` | `Set<string>` | Currently held keys |\n| `pressedThisFrame` | `Set<string>` | Keys pressed this frame |\n| `releasedThisFrame` | `Set<string>` | Keys released this frame |\n| `lastKeyPressed` | `string` | Most recent key-down |\n| `lastKeyReleased` | `string` | Most recent key-up |\n| `shift`, `ctrl`, `alt`, `meta` | `boolean` | Modifier states |\n\n### Input: Touch: `viji.touches`\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `count` | `number` | Active touch count |\n| `points` | `TouchPoint[]` | All active touches |\n| `started` | `TouchPoint[]` | Touches started this frame |\n| `moved` | `TouchPoint[]` | Touches moved this frame |\n| `ended` | `TouchPoint[]` | Touches ended this frame |\n| `primary` | `TouchPoint\\|null` | First active touch |\n\n**TouchPoint:** `id`, `x`, `y`, `pressure`, `radius`, `radiusX`, `radiusY`, `rotationAngle`, `force`, `isInCanvas`, `deltaX`, `deltaY`, `velocity` ({x,y}), `isNew`, `isActive`, `isEnding`.\n\n### Device Sensors: `viji.device`\n\n| Member | Type | Description |\n|--------|------|-------------|\n| `motion` | `DeviceMotionData\\|null` | Accelerometer/gyroscope |\n| `orientation` | `DeviceOrientationData\\|null` | Device orientation |\n\n**DeviceMotionData:** `acceleration` ({x,y,z} m/s²), `accelerationIncludingGravity`, `rotationRate` ({alpha,beta,gamma} deg/s), `interval` (ms).\n**DeviceOrientationData:** `alpha` (0-360° compass), `beta` (−180-180° tilt), `gamma` (−90-90° tilt), `absolute` (boolean).\n\n### External Devices: `viji.devices`\n\nArray of connected external devices. Each `DeviceState`:\n`id` (string), `name` (string), `motion` (DeviceMotionData|null), `orientation` (DeviceOrientationData|null), `video` (VideoAPI|null, same as viji.video but without CV), `audio` (AudioStreamAPI|null, lightweight analysis only; no beat/BPM/triggers).\n\n### Streams: `viji.videoStreams`\n\n`VideoAPI[]`: additional video sources provided by the host application (used by the compositor for scene mixing). May be empty. Each element has the same shape as `viji.video`.\n\n### Streams: `viji.audioStreams`\n\n`AudioStreamAPI[]`: additional audio sources from the host (e.g. multi-source mixing). May be empty. Lightweight interface: volume, bands, spectral features, `getFrequencyData()`, `getWaveform()`: **not** the full `AudioAPI` (no beat detection, BPM, triggers, or events).\n\n## P5 ↔ VIJI MAPPING\n\n| Standard P5.js | Viji-P5 |\n|---|---|\n| `width` / `height` | `viji.width` / `viji.height` |\n| `mouseX` / `mouseY` | `viji.pointer.x` / `viji.pointer.y` |\n| `mouseIsPressed` | `viji.pointer.isDown` |\n| `mouseButton === LEFT` | `viji.mouse.leftButton` |\n| `keyIsPressed` | `viji.keyboard.isPressed('keyName')` |\n| `key` | `viji.keyboard.lastKeyPressed` |\n| `frameCount` | Use `viji.time` or `viji.deltaTime` accumulator |\n| `frameRate(n)` | Remove: host controls frame rate |\n| `createCanvas(w, h)` | Remove: canvas is provided |\n| `preload()` | Remove: use `viji.image()` or `fetch()` in `setup()` |\n| `loadImage(url)` | `viji.image(null, { label: 'Image' })` |\n| `save()` | Remove: host handles capture |\n\n## BEST PRACTICES\n\n1. NEVER use `viji.time * speed.value`: use a `deltaTime` accumulator instead (see rule 16). Same for nested: never multiply an accumulator by another parameter; give each speed its own accumulator.\n2. Guard audio/video with `isConnected` checks.\n3. Pre-allocate all objects/arrays at top level: never inside `render()`.\n4. For CV, use toggle parameters: never enable by default.\n5. ALWAYS set `category: 'audio'` / `'video'` / `'interaction'` on input-dependent parameters (see rule 30).\n6. Use `p5.drawingContext.drawImage()` for video frames (faster than wrapping).\n7. Use `p5.createGraphics()` for off-screen buffers when needed.\n\n## TEMPLATE\n\n```javascript\n// @renderer p5\n\nconst bgColor = viji.color('#1a1a2e', { label: 'Background' });\nconst speed = viji.slider(1, { min: 0.1, max: 5, label: 'Speed' });\nconst count = viji.slider(8, { min: 3, max: 30, step: 1, label: 'Count' });\n\nlet angle = 0;\n\nfunction setup(viji, p5) {\n p5.colorMode(p5.HSB, 360, 100, 100);\n}\n\nfunction render(viji, p5) {\n angle += speed.value * viji.deltaTime;\n\n p5.background(bgColor.value);\n\n const cx = viji.width / 2;\n const cy = viji.height / 2;\n const radius = p5.min(viji.width, viji.height) * 0.3;\n const dotSize = p5.min(viji.width, viji.height) * 0.04;\n const n = p5.floor(count.value);\n\n p5.noStroke();\n for (let i = 0; i < n; i++) {\n const a = angle + (i / n) * p5.TWO_PI;\n const x = cx + p5.cos(a) * radius;\n const y = cy + p5.sin(a) * radius;\n p5.fill((i / n) * 360, 80, 90);\n p5.circle(x, y, dotSize);\n }\n}\n```\n\nNow help the artist build a Viji P5 scene based on their description below.\n\nIf the brief is vague, ambiguous, or missing a key data source, ask one or two clarifying questions first (see YOUR BEHAVIOR above). Otherwise, proceed.\n\nWhen you generate the scene:\n- Follow every rule in this prompt.\n- Use `// @renderer p5` (2D) or `// @renderer p5 webgl` (WEBGL) as the first line. Prefix ALL P5 functions with `p5.`. Use `viji.deltaTime` for animation. Use parameters for anything adjustable. Check `isConnected` before using audio or video.\n- Output the scene code in a single fenced code block.\n- After the code block, write a short explanation (a few sentences) of how the scene works and what the artist can tweak.\n- Invite the artist to ask for changes.\n````\n\n## Usage\n\n1. Copy the entire prompt block above.\n2. Paste it into your AI assistant (ChatGPT, Claude, etc.).\n3. After the prompt, describe the scene you want.\n4. The AI will return a complete Viji P5 scene.\n\n> [!TIP]\n> For better results, mention which data sources you want (audio, video, camera, mouse) and what kind of controls the user should have. If you have existing P5 sketches to convert, use the [Convert: P5 Sketches](/ai-prompts/convert-p5) prompt instead.\n\n## Related\n\n- [Create Your First Scene](/ai-prompts/create-first-scene): guided prompt for beginners\n- [Prompting Tips](/ai-prompts/prompting-tips): how to get better results from AI\n- [Convert: P5 Sketches](/ai-prompts/convert-p5): convert existing P5 sketches to Viji\n- [P5 Quick Start](/p5/quickstart): your first Viji P5 scene\n- [P5 API Reference](/p5/api-reference): full API reference\n- [Drawing with P5](/p5/drawing): Viji-specific P5 drawing guide\n- [p5js.org Reference](https://p5js.org/reference/): full P5.js documentation"
|
|
1357
1357
|
}
|
|
1358
1358
|
]
|
|
1359
1359
|
},
|
|
@@ -1699,7 +1699,7 @@ export const docsApi = {
|
|
|
1699
1699
|
"content": [
|
|
1700
1700
|
{
|
|
1701
1701
|
"type": "text",
|
|
1702
|
-
"markdown": "# API Reference\n\nThis page lists every property and method available on the `viji` object passed to your scene functions. Use it as a quick lookup: each entry links to its dedicated documentation page for full details, examples, and patterns.\n\nNew to Viji? Start with the [Quick Start](/native/quickstart) instead.\n\n## Entry Points\n\n```javascript\n// Top-level code runs once (initialization, parameters, state, imports)\nconst speed = viji.slider(1, { min: 0.1, max: 5, label: 'Speed' });\nlet angle = 0;\n\nfunction render(viji) {\n // Called every frame: this is where you draw\n}\n```\n\nThere is no `setup()` function in native scenes. All initialization goes at the top level. Top-level `await` is supported for dynamic imports.\n\n## Canvas & Context\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.canvas`](/native/canvas-context#the-canvas) | `OffscreenCanvas` | The rendering canvas | [Canvas & Context](/native/canvas-context) |\n| [`viji.ctx`](/native/canvas-context#2d-context) | `OffscreenCanvasRenderingContext2D` | 2D context (after `useContext('2d')`) | [Canvas & Context](/native/canvas-context) |\n| [`viji.gl`](/native/canvas-context#webgl-context) | `WebGLRenderingContext \\| WebGL2RenderingContext` | WebGL context (after `useContext('webgl'\\|'webgl2')`) | [Canvas & Context](/native/canvas-context) |\n| [`viji.width`](/native/canvas-context#dimension-properties) | `number` | Canvas width in pixels | [Canvas & Context](/native/canvas-context) |\n| [`viji.height`](/native/canvas-context#dimension-properties) | `number` | Canvas height in pixels | [Canvas & Context](/native/canvas-context) |\n| [`viji.useContext(type)`](/native/canvas-context#choosing-a-context) | `Method` | Request a rendering context: `'2d'`, `'webgl'`, `'webgl2'` | [Canvas & Context](/native/canvas-context) |\n\n## Timing\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.time`](/native/timing#vijitime-absolute-time) | `number` | Seconds elapsed since the scene started | [Timing](/native/timing) |\n| [`viji.deltaTime`](/native/timing#vijideltatime-frame-delta) | `number` | Seconds since the previous frame | [Timing](/native/timing) |\n| [`viji.frameCount`](/native/timing#vijiframecount) | `number` | Monotonically increasing frame counter | [Timing](/native/timing) |\n| [`viji.fps`](/native/timing#vijifps-target-frame-rate) | `number` | Target FPS based on the host's frame rate mode | [Timing](/native/timing) |\n\n## Parameters\n\nAll parameter methods are called at the top level of your scene file. Read `.value` inside `render()` to get the current value.\n\n| Method | Returns | `.value` Type | Details |\n|--------|---------|---------------|---------|\n| [`viji.slider(default, config)`](/native/parameters/slider) | `SliderParameter` | `number` | [Slider](/native/parameters/slider) |\n| [`viji.color(default, config)`](/native/parameters/color) | `ColorParameter` | `string` (hex) | [Color](/native/parameters/color) |\n| [`viji.toggle(default, config)`](/native/parameters/toggle) | `ToggleParameter` | `boolean` | [Toggle](/native/parameters/toggle) |\n| [`viji.select(default, config)`](/native/parameters/select) | `SelectParameter` | `string \\| number` | [Select](/native/parameters/select) |\n| [`viji.number(default, config)`](/native/parameters/number) | `NumberParameter` | `number` | [Number](/native/parameters/number) |\n| [`viji.text(default, config)`](/native/parameters/text) | `TextParameter` | `string` | [Text](/native/parameters/text) |\n| [`viji.image(null, config)`](/native/parameters/image) | `ImageParameter` | `ImageBitmap \\| null` | [Image](/native/parameters/image) |\n| [`viji.button(config)`](/native/parameters/button) | `ButtonParameter` | `boolean` (true for one frame) | [Button](/native/parameters/button) |\n| [`viji.coordinate(default, config)`](/native/parameters/coordinate) | `CoordinateParameter` | 2D coordinate pad: `{ x: number, y: number }`, both -1 to 1 | [Coordinate](/native/parameters/coordinate) |\n\nSee [Parameters Overview](/native/parameters) for the declaration pattern, [Grouping](/native/parameters/grouping) and [Categories](/native/parameters/categories) for organization.\n\n## Audio\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.audio.isConnected`](/native/audio) | `boolean` | Whether an audio source is active | [Overview](/native/audio) |\n| [`viji.audio.volume.current`](/native/audio/volume#property-reference) | `number` | Current RMS volume 0-1 | [Volume](/native/audio/volume) |\n| [`viji.audio.volume.peak`](/native/audio/volume#property-reference) | `number` | Peak volume 0-1 | [Volume](/native/audio/volume) |\n| [`viji.audio.volume.smoothed`](/native/audio/volume#property-reference) | `number` | Smoothed volume 0-1 | [Volume](/native/audio/volume) |\n| [`viji.audio.bands.low`](/native/audio/bands#instant-bands) | `number` | Low frequency band energy (20-120 Hz) | [Frequency Bands](/native/audio/bands) |\n| [`viji.audio.bands.lowMid`](/native/audio/bands#instant-bands) | `number` | Low-mid band energy (120-500 Hz) | [Frequency Bands](/native/audio/bands) |\n| [`viji.audio.bands.mid`](/native/audio/bands#instant-bands) | `number` | Mid band energy (500-2 kHz) | [Frequency Bands](/native/audio/bands) |\n| [`viji.audio.bands.highMid`](/native/audio/bands#instant-bands) | `number` | High-mid band energy (2-6 kHz) | [Frequency Bands](/native/audio/bands) |\n| [`viji.audio.bands.high`](/native/audio/bands#instant-bands) | `number` | High band energy (6-16 kHz) | [Frequency Bands](/native/audio/bands) |\n| [`viji.audio.bands.lowSmoothed`](/native/audio/bands#smoothed-bands) | `number` | Smoothed low band | [Frequency Bands](/native/audio/bands) |\n| [`viji.audio.bands.lowMidSmoothed`](/native/audio/bands#smoothed-bands) | `number` | Smoothed low-mid band | [Frequency Bands](/native/audio/bands) |\n| [`viji.audio.bands.midSmoothed`](/native/audio/bands#smoothed-bands) | `number` | Smoothed mid band | [Frequency Bands](/native/audio/bands) |\n| [`viji.audio.bands.highMidSmoothed`](/native/audio/bands#smoothed-bands) | `number` | Smoothed high-mid band | [Frequency Bands](/native/audio/bands) |\n| [`viji.audio.bands.highSmoothed`](/native/audio/bands#smoothed-bands) | `number` | Smoothed high band | [Frequency Bands](/native/audio/bands) |\n| [`viji.audio.beat.kick`](/native/audio/beat#energy-curves-fast-decay) | `number` | Kick beat energy | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.snare`](/native/audio/beat#energy-curves-fast-decay) | `number` | Snare beat energy | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.hat`](/native/audio/beat#energy-curves-fast-decay) | `number` | Hi-hat beat energy | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.any`](/native/audio/beat#energy-curves-fast-decay) | `number` | Combined beat energy | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.kickSmoothed`](/native/audio/beat#energy-curves-smoothed) | `number` | Smoothed kick | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.snareSmoothed`](/native/audio/beat#energy-curves-smoothed) | `number` | Smoothed snare | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.hatSmoothed`](/native/audio/beat#energy-curves-smoothed) | `number` | Smoothed hi-hat | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.anySmoothed`](/native/audio/beat#energy-curves-smoothed) | `number` | Smoothed combined | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.triggers.kick`](/native/audio/beat#triggers) | `boolean` | Kick trigger (true for one frame) | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.triggers.snare`](/native/audio/beat#triggers) | `boolean` | Snare trigger (true for one frame) | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.triggers.hat`](/native/audio/beat#triggers) | `boolean` | Hi-hat trigger (true for one frame) | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.triggers.any`](/native/audio/beat#triggers) | `boolean` | Any beat trigger (true for one frame) | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.events`](/native/audio/beat#events) | `Array<{ type, time, strength }>` | Beat events this frame | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.bpm`](/native/audio/beat#tempo) | `number` | Tracked BPM | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.confidence`](/native/audio/beat#tempo) | `number` | Beat-tracker confidence 0-1 | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.isLocked`](/native/audio/beat#tempo) | `boolean` | Whether beat tracking is locked | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.spectral.brightness`](/native/audio/spectral#property-reference) | `number` | Spectral brightness 0-1 | [Spectral Analysis](/native/audio/spectral) |\n| [`viji.audio.spectral.flatness`](/native/audio/spectral#property-reference) | `number` | Spectral flatness 0-1 | [Spectral Analysis](/native/audio/spectral) |\n| [`viji.audio.getFrequencyData()`](/native/audio/frequency-data) | `() => Uint8Array` | Raw FFT frequency bins (0-255) | [Frequency Data](/native/audio/frequency-data) |\n| [`viji.audio.getWaveform()`](/native/audio/waveform) | `() => Float32Array` | Time-domain waveform (-1 to 1) | [Waveform](/native/audio/waveform) |\n\n## Video & CV\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.video.isConnected`](/native/video) | `boolean` | Whether a video source is active | [Overview](/native/video) |\n| [`viji.video.currentFrame`](/native/video/basics) | `OffscreenCanvas \\| ImageBitmap \\| null` | Current video frame | [Video Basics](/native/video/basics) |\n| [`viji.video.frameWidth`](/native/video/basics) | `number` | Frame width in pixels | [Video Basics](/native/video/basics) |\n| [`viji.video.frameHeight`](/native/video/basics) | `number` | Frame height in pixels | [Video Basics](/native/video/basics) |\n| [`viji.video.frameRate`](/native/video/basics) | `number` | Video frame rate | [Video Basics](/native/video/basics) |\n| [`viji.video.getFrameData()`](/native/video/basics) | `() => ImageData \\| null` | Pixel data for the current frame | [Video Basics](/native/video/basics) |\n| [`viji.video.cv.faces`](/native/video/face-detection) | `FaceData[]` | Detected faces | [Face Detection](/native/video/face-detection) |\n| [`viji.video.cv.hands`](/native/video/hand-tracking) | `HandData[]` | Detected hands | [Hand Tracking](/native/video/hand-tracking) |\n| [`viji.video.cv.pose`](/native/video/pose-detection) | `PoseData \\| null` | Detected body pose | [Pose Detection](/native/video/pose-detection) |\n| [`viji.video.cv.segmentation`](/native/video/body-segmentation) | `SegmentationData \\| null` | Body segmentation mask | [Body Segmentation](/native/video/body-segmentation) |\n| [`viji.video.cv.enableFaceDetection(enabled)`](/native/video/face-detection) | `(boolean) => Promise<void>` | Enable/disable face detection | [Face Detection](/native/video/face-detection) |\n| [`viji.video.cv.enableFaceMesh(enabled)`](/native/video/face-mesh) | `(boolean) => Promise<void>` | Enable/disable face mesh | [Face Mesh](/native/video/face-mesh) |\n| [`viji.video.cv.enableEmotionDetection(enabled)`](/native/video/emotion-detection) | `(boolean) => Promise<void>` | Enable/disable emotion detection | [Emotion Detection](/native/video/emotion-detection) |\n| [`viji.video.cv.enableHandTracking(enabled)`](/native/video/hand-tracking) | `(boolean) => Promise<void>` | Enable/disable hand tracking | [Hand Tracking](/native/video/hand-tracking) |\n| [`viji.video.cv.enablePoseDetection(enabled)`](/native/video/pose-detection) | `(boolean) => Promise<void>` | Enable/disable pose detection | [Pose Detection](/native/video/pose-detection) |\n| [`viji.video.cv.enableBodySegmentation(enabled)`](/native/video/body-segmentation) | `(boolean) => Promise<void>` | Enable/disable body segmentation | [Body Segmentation](/native/video/body-segmentation) |\n| [`viji.video.cv.getActiveFeatures()`](/native/video) | `() => CVFeature[]` | List of active CV features | [Overview](/native/video) |\n| [`viji.video.cv.isProcessing()`](/native/video) | `() => boolean` | Whether CV is currently processing | [Overview](/native/video) |\n\n## Mouse\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.mouse.x`](/native/mouse#position) | `number` | Cursor X position in pixels | [Mouse](/native/mouse) |\n| [`viji.mouse.y`](/native/mouse#position) | `number` | Cursor Y position in pixels | [Mouse](/native/mouse) |\n| [`viji.mouse.isInCanvas`](/native/mouse#position) | `boolean` | Whether cursor is inside the canvas | [Mouse](/native/mouse) |\n| [`viji.mouse.isPressed`](/native/mouse#buttons) | `boolean` | Whether any button is pressed | [Mouse](/native/mouse) |\n| [`viji.mouse.leftButton`](/native/mouse#buttons) | `boolean` | Left button state | [Mouse](/native/mouse) |\n| [`viji.mouse.rightButton`](/native/mouse#buttons) | `boolean` | Right button state | [Mouse](/native/mouse) |\n| [`viji.mouse.middleButton`](/native/mouse#buttons) | `boolean` | Middle button state | [Mouse](/native/mouse) |\n| [`viji.mouse.deltaX`](/native/mouse#movement) | `number` | Horizontal movement since last frame | [Mouse](/native/mouse) |\n| [`viji.mouse.deltaY`](/native/mouse#movement) | `number` | Vertical movement since last frame | [Mouse](/native/mouse) |\n| [`viji.mouse.wheelDelta`](/native/mouse#scroll-wheel) | `number` | Scroll wheel delta | [Mouse](/native/mouse) |\n| [`viji.mouse.wheelX`](/native/mouse#scroll-wheel) | `number` | Horizontal scroll delta | [Mouse](/native/mouse) |\n| [`viji.mouse.wheelY`](/native/mouse#scroll-wheel) | `number` | Vertical scroll delta | [Mouse](/native/mouse) |\n| [`viji.mouse.wasPressed`](/native/mouse#frame-events) | `boolean` | True for one frame when pressed | [Mouse](/native/mouse) |\n| [`viji.mouse.wasReleased`](/native/mouse#frame-events) | `boolean` | True for one frame when released | [Mouse](/native/mouse) |\n| [`viji.mouse.wasMoved`](/native/mouse#frame-events) | `boolean` | True for one frame when moved | [Mouse](/native/mouse) |\n\n## Keyboard\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.keyboard.isPressed(key)`](/native/keyboard#methods) | `(string) => boolean` | Whether a key is currently held | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.wasPressed(key)`](/native/keyboard#methods) | `(string) => boolean` | True for one frame when pressed | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.wasReleased(key)`](/native/keyboard#methods) | `(string) => boolean` | True for one frame when released | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.activeKeys`](/native/keyboard#properties) | `Set<string>` | All currently held keys | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.pressedThisFrame`](/native/keyboard#properties) | `Set<string>` | Keys pressed this frame | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.releasedThisFrame`](/native/keyboard#properties) | `Set<string>` | Keys released this frame | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.lastKeyPressed`](/native/keyboard#properties) | `string` | Most recently pressed key | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.lastKeyReleased`](/native/keyboard#properties) | `string` | Most recently released key | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.shift`](/native/keyboard#modifier-keys) | `boolean` | Shift key state | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.ctrl`](/native/keyboard#modifier-keys) | `boolean` | Ctrl/Cmd key state | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.alt`](/native/keyboard#modifier-keys) | `boolean` | Alt/Option key state | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.meta`](/native/keyboard#modifier-keys) | `boolean` | Meta/Win key state | [Keyboard](/native/keyboard) |\n\n## Touch\n\n> **Note:** The property is `viji.touches` (plural), not `viji.touch`.\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.touches.points`](/native/touch#touchapi-vijitouches) | `TouchPoint[]` | All active touch points | [Touch](/native/touch) |\n| [`viji.touches.count`](/native/touch#touchapi-vijitouches) | `number` | Number of active touches | [Touch](/native/touch) |\n| [`viji.touches.started`](/native/touch#touchapi-vijitouches) | `TouchPoint[]` | Touch points that started this frame | [Touch](/native/touch) |\n| [`viji.touches.moved`](/native/touch#touchapi-vijitouches) | `TouchPoint[]` | Touch points that moved this frame | [Touch](/native/touch) |\n| [`viji.touches.ended`](/native/touch#touchapi-vijitouches) | `TouchPoint[]` | Touch points that ended this frame | [Touch](/native/touch) |\n| [`viji.touches.primary`](/native/touch#touchapi-vijitouches) | `TouchPoint \\| null` | The first active touch point | [Touch](/native/touch) |\n\n**`TouchPoint` fields:** `id`, `x`, `y`, `pressure`, `radius`, `radiusX`, `radiusY`, `rotationAngle`, `force` (numbers); `isInCanvas`, `isNew`, `isActive`, `isEnding` (booleans); `deltaX`, `deltaY` (numbers); `velocity` `{ x, y }`.\n\n## Pointer (Unified)\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.pointer.x`](/native/pointer#api-reference) | `number` | Primary pointer X position | [Pointer](/native/pointer) |\n| [`viji.pointer.y`](/native/pointer#api-reference) | `number` | Primary pointer Y position | [Pointer](/native/pointer) |\n| [`viji.pointer.deltaX`](/native/pointer#api-reference) | `number` | Horizontal movement since last frame | [Pointer](/native/pointer) |\n| [`viji.pointer.deltaY`](/native/pointer#api-reference) | `number` | Vertical movement since last frame | [Pointer](/native/pointer) |\n| [`viji.pointer.isDown`](/native/pointer#api-reference) | `boolean` | Whether the pointer is active (click or touch) | [Pointer](/native/pointer) |\n| [`viji.pointer.wasPressed`](/native/pointer#api-reference) | `boolean` | True for one frame when pressed | [Pointer](/native/pointer) |\n| [`viji.pointer.wasReleased`](/native/pointer#api-reference) | `boolean` | True for one frame when released | [Pointer](/native/pointer) |\n| [`viji.pointer.isInCanvas`](/native/pointer#api-reference) | `boolean` | Whether pointer is inside the canvas | [Pointer](/native/pointer) |\n| [`viji.pointer.type`](/native/pointer#api-reference) | `'mouse' \\| 'touch' \\| 'none'` | Current input source | [Pointer](/native/pointer) |\n\n## Device Sensors\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.device.motion`](/native/sensors#devicemotiondata-vijidevicemotion) | `DeviceMotionData \\| null` | Accelerometer and gyroscope data | [Device Sensors](/native/sensors) |\n| [`viji.device.orientation`](/native/sensors#deviceorientationdata-vijideviceorientation) | `DeviceOrientationData \\| null` | Device orientation (alpha, beta, gamma) | [Device Sensors](/native/sensors) |\n\n**`DeviceMotionData`:** `acceleration` `{ x, y, z }`, `accelerationIncludingGravity` `{ x, y, z }`, `rotationRate` `{ alpha, beta, gamma }`, `interval`.\n\n**`DeviceOrientationData`:** `alpha`, `beta`, `gamma` (numbers or null), `absolute` (boolean).\n\n## External Devices\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.devices`](/native/external-devices#devicestate-vijidevicesi) | `DeviceState[]` | Connected external devices | [Overview](/native/external-devices) |\n| [`viji.devices[i].id`](/native/external-devices#devicestate-vijidevicesi) | `string` | Unique device identifier | [Overview](/native/external-devices) |\n| [`viji.devices[i].name`](/native/external-devices#devicestate-vijidevicesi) | `string` | User-friendly device name | [Overview](/native/external-devices) |\n| [`viji.devices[i].motion`](/native/external-devices/sensors#devicemotiondata-devicemotion) | `DeviceMotionData \\| null` | Device accelerometer/gyroscope | [Device Sensors](/native/external-devices/sensors) |\n| [`viji.devices[i].orientation`](/native/external-devices/sensors#deviceorientationdata-deviceorientation) | `DeviceOrientationData \\| null` | Device orientation | [Device Sensors](/native/external-devices/sensors) |\n| [`viji.devices[i].video`](/native/external-devices/video) | `VideoAPI \\| null` | Device camera video | [Device Video](/native/external-devices/video) |\n| [`viji.devices[i].audio`](/native/external-devices/audio) | `AudioStreamAPI \\| null` | Device audio stream | [Device Audio](/native/external-devices/audio) |\n\n## Streams\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.videoStreams`](/native/video) | `VideoAPI[]` | Additional video streams provided by the host | [Video](/native/video) |\n| [`viji.audioStreams`](/native/audio#beyond-the-main-stream) | `AudioStreamAPI[]` | Additional audio streams provided by the host | [Audio](/native/audio) |\n\nEach `videoStreams` element has the same shape as [`viji.video`](/native/video). Each `audioStreams` element provides lightweight audio analysis (volume, frequency bands, spectral features) but does **not** include beat detection or BPM tracking: see [`viji.audio`](/native/audio) for full analysis on the main stream.\n\nBoth arrays may be empty if the host does not provide additional streams. Audio streams from external devices appear on `device.audio`, not in `viji.audioStreams`.\n\n## Related\n\n- [Quick Start](/native/quickstart): getting started with the Native renderer\n- [Best Practices](/getting-started/best-practices): essential patterns for all renderers\n- [Common Mistakes](/getting-started/common-mistakes): pitfalls to avoid\n- [P5 API Reference](/p5/api-reference): the same API in the P5 renderer\n- [Shader API Reference](/shader/api-reference): built-in uniforms for shaders"
|
|
1702
|
+
"markdown": "# API Reference\n\nThis page lists every property and method available on the `viji` object passed to your scene functions. Use it as a quick lookup: each entry links to its dedicated documentation page for full details, examples, and patterns.\n\nNew to Viji? Start with the [Quick Start](/native/quickstart) instead.\n\nAll types named on this page are available globally in scene code: annotate variables with them directly, with no imports or aliases. TypeScript is optional; see [TypeScript Support](/native/quickstart#typescript-support).\n\n## Entry Points\n\n```javascript\n// Top-level code runs once (initialization, parameters, state, imports)\nconst speed = viji.slider(1, { min: 0.1, max: 5, label: 'Speed' });\nlet angle = 0;\n\nfunction render(viji) {\n // Called every frame: this is where you draw\n}\n```\n\nThere is no `setup()` function in native scenes. All initialization goes at the top level. Top-level `await` is supported for dynamic imports.\n\n## Canvas & Context\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.canvas`](/native/canvas-context#the-canvas) | `OffscreenCanvas` | The rendering canvas | [Canvas & Context](/native/canvas-context) |\n| [`viji.ctx`](/native/canvas-context#2d-context) | `OffscreenCanvasRenderingContext2D` | 2D context (after `useContext('2d')`) | [Canvas & Context](/native/canvas-context) |\n| [`viji.gl`](/native/canvas-context#webgl-context) | `WebGLRenderingContext \\| WebGL2RenderingContext` | WebGL context (after `useContext('webgl'\\|'webgl2')`) | [Canvas & Context](/native/canvas-context) |\n| [`viji.width`](/native/canvas-context#dimension-properties) | `number` | Canvas width in pixels | [Canvas & Context](/native/canvas-context) |\n| [`viji.height`](/native/canvas-context#dimension-properties) | `number` | Canvas height in pixels | [Canvas & Context](/native/canvas-context) |\n| [`viji.useContext(type)`](/native/canvas-context#choosing-a-context) | `Method` | Request a rendering context: `'2d'`, `'webgl'`, `'webgl2'` | [Canvas & Context](/native/canvas-context) |\n\n## Timing\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.time`](/native/timing#vijitime-absolute-time) | `number` | Seconds elapsed since the scene started | [Timing](/native/timing) |\n| [`viji.deltaTime`](/native/timing#vijideltatime-frame-delta) | `number` | Seconds since the previous frame | [Timing](/native/timing) |\n| [`viji.frameCount`](/native/timing#vijiframecount) | `number` | Monotonically increasing frame counter | [Timing](/native/timing) |\n| [`viji.fps`](/native/timing#vijifps-target-frame-rate) | `number` | Target FPS based on the host's frame rate mode | [Timing](/native/timing) |\n\n## Parameters\n\nAll parameter methods are called at the top level of your scene file. Read `.value` inside `render()` to get the current value.\n\n| Method | Returns | `.value` Type | Details |\n|--------|---------|---------------|---------|\n| [`viji.slider(default, config)`](/native/parameters/slider) | `SliderParameter` | `number` | [Slider](/native/parameters/slider) |\n| [`viji.color(default, config)`](/native/parameters/color) | `ColorParameter` | `string` (hex) | [Color](/native/parameters/color) |\n| [`viji.toggle(default, config)`](/native/parameters/toggle) | `ToggleParameter` | `boolean` | [Toggle](/native/parameters/toggle) |\n| [`viji.select(default, config)`](/native/parameters/select) | `SelectParameter` | `string \\| number` | [Select](/native/parameters/select) |\n| [`viji.number(default, config)`](/native/parameters/number) | `NumberParameter` | `number` | [Number](/native/parameters/number) |\n| [`viji.text(default, config)`](/native/parameters/text) | `TextParameter` | `string` | [Text](/native/parameters/text) |\n| [`viji.image(null, config)`](/native/parameters/image) | `ImageParameter` | `ImageBitmap \\| null` | [Image](/native/parameters/image) |\n| [`viji.button(config)`](/native/parameters/button) | `ButtonParameter` | `boolean` (true for one frame) | [Button](/native/parameters/button) |\n| [`viji.coordinate(default, config)`](/native/parameters/coordinate) | `CoordinateParameter` | 2D coordinate pad: `{ x: number, y: number }`, both -1 to 1 | [Coordinate](/native/parameters/coordinate) |\n\nSee [Parameters Overview](/native/parameters) for the declaration pattern, [Grouping](/native/parameters/grouping) and [Categories](/native/parameters/categories) for organization.\n\n## Audio\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.audio.isConnected`](/native/audio) | `boolean` | Whether an audio source is active | [Overview](/native/audio) |\n| [`viji.audio.volume.current`](/native/audio/volume#property-reference) | `number` | Current RMS volume 0-1 | [Volume](/native/audio/volume) |\n| [`viji.audio.volume.peak`](/native/audio/volume#property-reference) | `number` | Peak volume 0-1 | [Volume](/native/audio/volume) |\n| [`viji.audio.volume.smoothed`](/native/audio/volume#property-reference) | `number` | Smoothed volume 0-1 | [Volume](/native/audio/volume) |\n| [`viji.audio.bands.low`](/native/audio/bands#instant-bands) | `number` | Low frequency band energy (20-120 Hz) | [Frequency Bands](/native/audio/bands) |\n| [`viji.audio.bands.lowMid`](/native/audio/bands#instant-bands) | `number` | Low-mid band energy (120-500 Hz) | [Frequency Bands](/native/audio/bands) |\n| [`viji.audio.bands.mid`](/native/audio/bands#instant-bands) | `number` | Mid band energy (500-2 kHz) | [Frequency Bands](/native/audio/bands) |\n| [`viji.audio.bands.highMid`](/native/audio/bands#instant-bands) | `number` | High-mid band energy (2-6 kHz) | [Frequency Bands](/native/audio/bands) |\n| [`viji.audio.bands.high`](/native/audio/bands#instant-bands) | `number` | High band energy (6-16 kHz) | [Frequency Bands](/native/audio/bands) |\n| [`viji.audio.bands.lowSmoothed`](/native/audio/bands#smoothed-bands) | `number` | Smoothed low band | [Frequency Bands](/native/audio/bands) |\n| [`viji.audio.bands.lowMidSmoothed`](/native/audio/bands#smoothed-bands) | `number` | Smoothed low-mid band | [Frequency Bands](/native/audio/bands) |\n| [`viji.audio.bands.midSmoothed`](/native/audio/bands#smoothed-bands) | `number` | Smoothed mid band | [Frequency Bands](/native/audio/bands) |\n| [`viji.audio.bands.highMidSmoothed`](/native/audio/bands#smoothed-bands) | `number` | Smoothed high-mid band | [Frequency Bands](/native/audio/bands) |\n| [`viji.audio.bands.highSmoothed`](/native/audio/bands#smoothed-bands) | `number` | Smoothed high band | [Frequency Bands](/native/audio/bands) |\n| [`viji.audio.beat.kick`](/native/audio/beat#energy-curves-fast-decay) | `number` | Kick beat energy | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.snare`](/native/audio/beat#energy-curves-fast-decay) | `number` | Snare beat energy | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.hat`](/native/audio/beat#energy-curves-fast-decay) | `number` | Hi-hat beat energy | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.any`](/native/audio/beat#energy-curves-fast-decay) | `number` | Combined beat energy | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.kickSmoothed`](/native/audio/beat#energy-curves-smoothed) | `number` | Smoothed kick | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.snareSmoothed`](/native/audio/beat#energy-curves-smoothed) | `number` | Smoothed snare | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.hatSmoothed`](/native/audio/beat#energy-curves-smoothed) | `number` | Smoothed hi-hat | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.anySmoothed`](/native/audio/beat#energy-curves-smoothed) | `number` | Smoothed combined | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.triggers.kick`](/native/audio/beat#triggers) | `boolean` | Kick trigger (true for one frame) | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.triggers.snare`](/native/audio/beat#triggers) | `boolean` | Snare trigger (true for one frame) | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.triggers.hat`](/native/audio/beat#triggers) | `boolean` | Hi-hat trigger (true for one frame) | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.triggers.any`](/native/audio/beat#triggers) | `boolean` | Any beat trigger (true for one frame) | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.events`](/native/audio/beat#events) | `Array<{ type, time, strength }>` | Beat events this frame | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.bpm`](/native/audio/beat#tempo) | `number` | Tracked BPM | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.confidence`](/native/audio/beat#tempo) | `number` | Beat-tracker confidence 0-1 | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.beat.isLocked`](/native/audio/beat#tempo) | `boolean` | Whether beat tracking is locked | [Beat Detection](/native/audio/beat) |\n| [`viji.audio.spectral.brightness`](/native/audio/spectral#property-reference) | `number` | Spectral brightness 0-1 | [Spectral Analysis](/native/audio/spectral) |\n| [`viji.audio.spectral.flatness`](/native/audio/spectral#property-reference) | `number` | Spectral flatness 0-1 | [Spectral Analysis](/native/audio/spectral) |\n| [`viji.audio.getFrequencyData()`](/native/audio/frequency-data) | `() => Uint8Array` | Raw FFT frequency bins (0-255) | [Frequency Data](/native/audio/frequency-data) |\n| [`viji.audio.getWaveform()`](/native/audio/waveform) | `() => Float32Array` | Time-domain waveform (-1 to 1) | [Waveform](/native/audio/waveform) |\n\n## Video & CV\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.video.isConnected`](/native/video) | `boolean` | Whether a video source is active | [Overview](/native/video) |\n| [`viji.video.currentFrame`](/native/video/basics) | `OffscreenCanvas \\| ImageBitmap \\| null` | Current video frame | [Video Basics](/native/video/basics) |\n| [`viji.video.frameWidth`](/native/video/basics) | `number` | Frame width in pixels | [Video Basics](/native/video/basics) |\n| [`viji.video.frameHeight`](/native/video/basics) | `number` | Frame height in pixels | [Video Basics](/native/video/basics) |\n| [`viji.video.frameRate`](/native/video/basics) | `number` | Video frame rate | [Video Basics](/native/video/basics) |\n| [`viji.video.getFrameData()`](/native/video/basics) | `() => ImageData \\| null` | Pixel data for the current frame | [Video Basics](/native/video/basics) |\n| [`viji.video.cv.faces`](/native/video/face-detection) | `FaceData[]` | Detected faces | [Face Detection](/native/video/face-detection) |\n| [`viji.video.cv.hands`](/native/video/hand-tracking) | `HandData[]` | Detected hands | [Hand Tracking](/native/video/hand-tracking) |\n| [`viji.video.cv.pose`](/native/video/pose-detection) | `PoseData \\| null` | Detected body pose | [Pose Detection](/native/video/pose-detection) |\n| [`viji.video.cv.segmentation`](/native/video/body-segmentation) | `SegmentationData \\| null` | Body segmentation mask | [Body Segmentation](/native/video/body-segmentation) |\n| [`viji.video.cv.enableFaceDetection(enabled)`](/native/video/face-detection) | `(boolean) => Promise<void>` | Enable/disable face detection | [Face Detection](/native/video/face-detection) |\n| [`viji.video.cv.enableFaceMesh(enabled)`](/native/video/face-mesh) | `(boolean) => Promise<void>` | Enable/disable face mesh | [Face Mesh](/native/video/face-mesh) |\n| [`viji.video.cv.enableEmotionDetection(enabled)`](/native/video/emotion-detection) | `(boolean) => Promise<void>` | Enable/disable emotion detection | [Emotion Detection](/native/video/emotion-detection) |\n| [`viji.video.cv.enableHandTracking(enabled)`](/native/video/hand-tracking) | `(boolean) => Promise<void>` | Enable/disable hand tracking | [Hand Tracking](/native/video/hand-tracking) |\n| [`viji.video.cv.enablePoseDetection(enabled)`](/native/video/pose-detection) | `(boolean) => Promise<void>` | Enable/disable pose detection | [Pose Detection](/native/video/pose-detection) |\n| [`viji.video.cv.enableBodySegmentation(enabled)`](/native/video/body-segmentation) | `(boolean) => Promise<void>` | Enable/disable body segmentation | [Body Segmentation](/native/video/body-segmentation) |\n| [`viji.video.cv.getActiveFeatures()`](/native/video) | `() => CVFeature[]` | List of active CV features | [Overview](/native/video) |\n| [`viji.video.cv.isProcessing()`](/native/video) | `() => boolean` | Whether CV is currently processing | [Overview](/native/video) |\n\n## Mouse\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.mouse.x`](/native/mouse#position) | `number` | Cursor X position in pixels | [Mouse](/native/mouse) |\n| [`viji.mouse.y`](/native/mouse#position) | `number` | Cursor Y position in pixels | [Mouse](/native/mouse) |\n| [`viji.mouse.isInCanvas`](/native/mouse#position) | `boolean` | Whether cursor is inside the canvas | [Mouse](/native/mouse) |\n| [`viji.mouse.isPressed`](/native/mouse#buttons) | `boolean` | Whether any button is pressed | [Mouse](/native/mouse) |\n| [`viji.mouse.leftButton`](/native/mouse#buttons) | `boolean` | Left button state | [Mouse](/native/mouse) |\n| [`viji.mouse.rightButton`](/native/mouse#buttons) | `boolean` | Right button state | [Mouse](/native/mouse) |\n| [`viji.mouse.middleButton`](/native/mouse#buttons) | `boolean` | Middle button state | [Mouse](/native/mouse) |\n| [`viji.mouse.deltaX`](/native/mouse#movement) | `number` | Horizontal movement since last frame | [Mouse](/native/mouse) |\n| [`viji.mouse.deltaY`](/native/mouse#movement) | `number` | Vertical movement since last frame | [Mouse](/native/mouse) |\n| [`viji.mouse.wheelDelta`](/native/mouse#scroll-wheel) | `number` | Scroll wheel delta | [Mouse](/native/mouse) |\n| [`viji.mouse.wheelX`](/native/mouse#scroll-wheel) | `number` | Horizontal scroll delta | [Mouse](/native/mouse) |\n| [`viji.mouse.wheelY`](/native/mouse#scroll-wheel) | `number` | Vertical scroll delta | [Mouse](/native/mouse) |\n| [`viji.mouse.wasPressed`](/native/mouse#frame-events) | `boolean` | True for one frame when pressed | [Mouse](/native/mouse) |\n| [`viji.mouse.wasReleased`](/native/mouse#frame-events) | `boolean` | True for one frame when released | [Mouse](/native/mouse) |\n| [`viji.mouse.wasMoved`](/native/mouse#frame-events) | `boolean` | True for one frame when moved | [Mouse](/native/mouse) |\n\n## Keyboard\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.keyboard.isPressed(key)`](/native/keyboard#methods) | `(string) => boolean` | Whether a key is currently held | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.wasPressed(key)`](/native/keyboard#methods) | `(string) => boolean` | True for one frame when pressed | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.wasReleased(key)`](/native/keyboard#methods) | `(string) => boolean` | True for one frame when released | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.activeKeys`](/native/keyboard#properties) | `Set<string>` | All currently held keys | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.pressedThisFrame`](/native/keyboard#properties) | `Set<string>` | Keys pressed this frame | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.releasedThisFrame`](/native/keyboard#properties) | `Set<string>` | Keys released this frame | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.lastKeyPressed`](/native/keyboard#properties) | `string` | Most recently pressed key | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.lastKeyReleased`](/native/keyboard#properties) | `string` | Most recently released key | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.shift`](/native/keyboard#modifier-keys) | `boolean` | Shift key state | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.ctrl`](/native/keyboard#modifier-keys) | `boolean` | Ctrl/Cmd key state | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.alt`](/native/keyboard#modifier-keys) | `boolean` | Alt/Option key state | [Keyboard](/native/keyboard) |\n| [`viji.keyboard.meta`](/native/keyboard#modifier-keys) | `boolean` | Meta/Win key state | [Keyboard](/native/keyboard) |\n\n## Touch\n\n> **Note:** The property is `viji.touches` (plural), not `viji.touch`.\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.touches.points`](/native/touch#touchapi-vijitouches) | `TouchPoint[]` | All active touch points | [Touch](/native/touch) |\n| [`viji.touches.count`](/native/touch#touchapi-vijitouches) | `number` | Number of active touches | [Touch](/native/touch) |\n| [`viji.touches.started`](/native/touch#touchapi-vijitouches) | `TouchPoint[]` | Touch points that started this frame | [Touch](/native/touch) |\n| [`viji.touches.moved`](/native/touch#touchapi-vijitouches) | `TouchPoint[]` | Touch points that moved this frame | [Touch](/native/touch) |\n| [`viji.touches.ended`](/native/touch#touchapi-vijitouches) | `TouchPoint[]` | Touch points that ended this frame | [Touch](/native/touch) |\n| [`viji.touches.primary`](/native/touch#touchapi-vijitouches) | `TouchPoint \\| null` | The first active touch point | [Touch](/native/touch) |\n\n**`TouchPoint` fields:** `id`, `x`, `y`, `pressure`, `radius`, `radiusX`, `radiusY`, `rotationAngle`, `force` (numbers); `isInCanvas`, `isNew`, `isActive`, `isEnding` (booleans); `deltaX`, `deltaY` (numbers); `velocity` `{ x, y }`.\n\n## Pointer (Unified)\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.pointer.x`](/native/pointer#api-reference) | `number` | Primary pointer X position | [Pointer](/native/pointer) |\n| [`viji.pointer.y`](/native/pointer#api-reference) | `number` | Primary pointer Y position | [Pointer](/native/pointer) |\n| [`viji.pointer.deltaX`](/native/pointer#api-reference) | `number` | Horizontal movement since last frame | [Pointer](/native/pointer) |\n| [`viji.pointer.deltaY`](/native/pointer#api-reference) | `number` | Vertical movement since last frame | [Pointer](/native/pointer) |\n| [`viji.pointer.isDown`](/native/pointer#api-reference) | `boolean` | Whether the pointer is active (click or touch) | [Pointer](/native/pointer) |\n| [`viji.pointer.wasPressed`](/native/pointer#api-reference) | `boolean` | True for one frame when pressed | [Pointer](/native/pointer) |\n| [`viji.pointer.wasReleased`](/native/pointer#api-reference) | `boolean` | True for one frame when released | [Pointer](/native/pointer) |\n| [`viji.pointer.isInCanvas`](/native/pointer#api-reference) | `boolean` | Whether pointer is inside the canvas | [Pointer](/native/pointer) |\n| [`viji.pointer.type`](/native/pointer#api-reference) | `'mouse' \\| 'touch' \\| 'none'` | Current input source | [Pointer](/native/pointer) |\n\n## Device Sensors\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.device.motion`](/native/sensors#devicemotiondata-vijidevicemotion) | `DeviceMotionData \\| null` | Accelerometer and gyroscope data | [Device Sensors](/native/sensors) |\n| [`viji.device.orientation`](/native/sensors#deviceorientationdata-vijideviceorientation) | `DeviceOrientationData \\| null` | Device orientation (alpha, beta, gamma) | [Device Sensors](/native/sensors) |\n\n**`DeviceMotionData`:** `acceleration` `{ x, y, z }`, `accelerationIncludingGravity` `{ x, y, z }`, `rotationRate` `{ alpha, beta, gamma }`, `interval`.\n\n**`DeviceOrientationData`:** `alpha`, `beta`, `gamma` (numbers or null), `absolute` (boolean).\n\n## External Devices\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.devices`](/native/external-devices#devicestate-vijidevicesi) | `DeviceState[]` | Connected external devices | [Overview](/native/external-devices) |\n| [`viji.devices[i].id`](/native/external-devices#devicestate-vijidevicesi) | `string` | Unique device identifier | [Overview](/native/external-devices) |\n| [`viji.devices[i].name`](/native/external-devices#devicestate-vijidevicesi) | `string` | User-friendly device name | [Overview](/native/external-devices) |\n| [`viji.devices[i].motion`](/native/external-devices/sensors#devicemotiondata-devicemotion) | `DeviceMotionData \\| null` | Device accelerometer/gyroscope | [Device Sensors](/native/external-devices/sensors) |\n| [`viji.devices[i].orientation`](/native/external-devices/sensors#deviceorientationdata-deviceorientation) | `DeviceOrientationData \\| null` | Device orientation | [Device Sensors](/native/external-devices/sensors) |\n| [`viji.devices[i].video`](/native/external-devices/video) | `VideoAPI \\| null` | Device camera video | [Device Video](/native/external-devices/video) |\n| [`viji.devices[i].audio`](/native/external-devices/audio) | `AudioStreamAPI \\| null` | Device audio stream | [Device Audio](/native/external-devices/audio) |\n\n## Streams\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.videoStreams`](/native/video) | `VideoAPI[]` | Additional video streams provided by the host | [Video](/native/video) |\n| [`viji.audioStreams`](/native/audio#beyond-the-main-stream) | `AudioStreamAPI[]` | Additional audio streams provided by the host | [Audio](/native/audio) |\n\nEach `videoStreams` element has the same shape as [`viji.video`](/native/video). Each `audioStreams` element provides lightweight audio analysis (volume, frequency bands, spectral features) but does **not** include beat detection or BPM tracking: see [`viji.audio`](/native/audio) for full analysis on the main stream.\n\nBoth arrays may be empty if the host does not provide additional streams. Audio streams from external devices appear on `device.audio`, not in `viji.audioStreams`.\n\n## Related\n\n- [Quick Start](/native/quickstart): getting started with the Native renderer\n- [Best Practices](/getting-started/best-practices): essential patterns for all renderers\n- [Common Mistakes](/getting-started/common-mistakes): pitfalls to avoid\n- [P5 API Reference](/p5/api-reference): the same API in the P5 renderer\n- [Shader API Reference](/shader/api-reference): built-in uniforms for shaders"
|
|
1703
1703
|
}
|
|
1704
1704
|
]
|
|
1705
1705
|
},
|
|
@@ -4333,7 +4333,7 @@ export const docsApi = {
|
|
|
4333
4333
|
"content": [
|
|
4334
4334
|
{
|
|
4335
4335
|
"type": "text",
|
|
4336
|
-
"markdown": "# API Reference\n\nThis page lists every property and method available on the `viji` object passed to your P5 scene functions. The `viji` API is identical to the [Native renderer](/native/api-reference): the difference is that P5 scenes also receive a `p5` instance as the second argument.\n\nNew to Viji P5? Start with the [Quick Start](/p5/quickstart) instead.\n\n## Entry Points\n\n```javascript\n// @renderer p5\n\nfunction setup(viji, p5) {\n // Called once when the scene starts (optional)\n}\n\nfunction render(viji, p5) {\n // Called every frame\n}\n```\n\nThe `p5` parameter is a full [P5.js](https://p5js.org/reference/) instance (v1.9.4) in instance mode. All P5 drawing methods (`p5.rect()`, `p5.fill()`, `p5.ellipse()`, etc.) are accessed through it. See [Drawing with P5](/p5/drawing) for Viji-specific drawing patterns.\n\n## Canvas & Context\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.canvas`](/p5/canvas-resolution#vijicanvas-in-p5-scenes) | `OffscreenCanvas` | The rendering canvas | [Canvas & Resolution](/p5/canvas-resolution) |\n| [`viji.width`](/p5/canvas-resolution#resolution-properties) | `number` | Canvas width in pixels | [Canvas & Resolution](/p5/canvas-resolution) |\n| [`viji.height`](/p5/canvas-resolution#resolution-properties) | `number` | Canvas height in pixels | [Canvas & Resolution](/p5/canvas-resolution) |\n\n> [!WARNING]\n> `viji.useContext()` is **not available** in P5 scenes. The canvas and its rendering context (2D or WEBGL, depending on the directive) are managed by P5 internally. Calling `useContext()` would conflict with P5's rendering pipeline.\n\n## Timing\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.time`](/p5/timing#vijitime-oscillations--cycles) | `number` | Seconds elapsed since the scene started | [Timing](/p5/timing) |\n| [`viji.deltaTime`](/p5/timing#vijideltatime-accumulation) | `number` | Seconds since the previous frame | [Timing](/p5/timing) |\n| [`viji.frameCount`](/p5/timing#vijiframecount-vs-p5framecount) | `number` | Monotonically increasing frame counter | [Timing](/p5/timing) |\n| [`viji.fps`](/p5/timing#vijifps-target-frame-rate) | `number` | Target FPS based on the host's frame rate mode | [Timing](/p5/timing) |\n\n## Parameters\n\nAll parameter methods are called at the top level of your scene file. Read `.value` inside `render()` to get the current value.\n\n| Method | Returns | `.value` Type | Details |\n|--------|---------|---------------|---------|\n| [`viji.slider(default, config)`](/p5/parameters/slider) | `SliderParameter` | `number` | [Slider](/p5/parameters/slider) |\n| [`viji.color(default, config)`](/p5/parameters/color) | `ColorParameter` | `string` (hex) | [Color](/p5/parameters/color) |\n| [`viji.toggle(default, config)`](/p5/parameters/toggle) | `ToggleParameter` | `boolean` | [Toggle](/p5/parameters/toggle) |\n| [`viji.select(default, config)`](/p5/parameters/select) | `SelectParameter` | `string \\| number` | [Select](/p5/parameters/select) |\n| [`viji.number(default, config)`](/p5/parameters/number) | `NumberParameter` | `number` | [Number](/p5/parameters/number) |\n| [`viji.text(default, config)`](/p5/parameters/text) | `TextParameter` | `string` | [Text](/p5/parameters/text) |\n| [`viji.image(null, config)`](/p5/parameters/image) | `ImageParameter` | `ImageBitmap \\| null` | [Image](/p5/parameters/image) |\n| [`viji.button(config)`](/p5/parameters/button) | `ButtonParameter` | `boolean` (true for one frame) | [Button](/p5/parameters/button) |\n| [`viji.coordinate(default, config)`](/p5/parameters/coordinate) | `CoordinateParameter` | 2D coordinate pad: `{ x: number, y: number }`, both -1 to 1 | [Coordinate](/p5/parameters/coordinate) |\n\n> [!NOTE]\n> Image parameters have a `.p5` property for use with `p5.image()`. See [Drawing with P5: Image Parameters](/p5/drawing) for the pattern.\n\nSee [Parameters Overview](/p5/parameters) for the declaration pattern, [Grouping](/p5/parameters/grouping) and [Categories](/p5/parameters/categories) for organization.\n\n## Audio\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.audio.isConnected`](/p5/audio) | `boolean` | Whether an audio source is active | [Overview](/p5/audio) |\n| [`viji.audio.volume.current`](/p5/audio/volume#property-reference) | `number` | Current RMS volume 0-1 | [Volume](/p5/audio/volume) |\n| [`viji.audio.volume.peak`](/p5/audio/volume#property-reference) | `number` | Peak volume 0-1 | [Volume](/p5/audio/volume) |\n| [`viji.audio.volume.smoothed`](/p5/audio/volume#property-reference) | `number` | Smoothed volume 0-1 | [Volume](/p5/audio/volume) |\n| [`viji.audio.bands.low`](/p5/audio/bands#instant-bands) | `number` | Low frequency band energy (20-120 Hz) | [Frequency Bands](/p5/audio/bands) |\n| [`viji.audio.bands.lowMid`](/p5/audio/bands#instant-bands) | `number` | Low-mid band energy (120-500 Hz) | [Frequency Bands](/p5/audio/bands) |\n| [`viji.audio.bands.mid`](/p5/audio/bands#instant-bands) | `number` | Mid band energy (500-2 kHz) | [Frequency Bands](/p5/audio/bands) |\n| [`viji.audio.bands.highMid`](/p5/audio/bands#instant-bands) | `number` | High-mid band energy (2-6 kHz) | [Frequency Bands](/p5/audio/bands) |\n| [`viji.audio.bands.high`](/p5/audio/bands#instant-bands) | `number` | High band energy (6-16 kHz) | [Frequency Bands](/p5/audio/bands) |\n| [`viji.audio.bands.lowSmoothed`](/p5/audio/bands#smoothed-bands) | `number` | Smoothed low band | [Frequency Bands](/p5/audio/bands) |\n| [`viji.audio.bands.lowMidSmoothed`](/p5/audio/bands#smoothed-bands) | `number` | Smoothed low-mid band | [Frequency Bands](/p5/audio/bands) |\n| [`viji.audio.bands.midSmoothed`](/p5/audio/bands#smoothed-bands) | `number` | Smoothed mid band | [Frequency Bands](/p5/audio/bands) |\n| [`viji.audio.bands.highMidSmoothed`](/p5/audio/bands#smoothed-bands) | `number` | Smoothed high-mid band | [Frequency Bands](/p5/audio/bands) |\n| [`viji.audio.bands.highSmoothed`](/p5/audio/bands#smoothed-bands) | `number` | Smoothed high band | [Frequency Bands](/p5/audio/bands) |\n| [`viji.audio.beat.kick`](/p5/audio/beat#energy-curves-fast-decay) | `number` | Kick beat energy | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.snare`](/p5/audio/beat#energy-curves-fast-decay) | `number` | Snare beat energy | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.hat`](/p5/audio/beat#energy-curves-fast-decay) | `number` | Hi-hat beat energy | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.any`](/p5/audio/beat#energy-curves-fast-decay) | `number` | Combined beat energy | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.kickSmoothed`](/p5/audio/beat#energy-curves-smoothed) | `number` | Smoothed kick | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.snareSmoothed`](/p5/audio/beat#energy-curves-smoothed) | `number` | Smoothed snare | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.hatSmoothed`](/p5/audio/beat#energy-curves-smoothed) | `number` | Smoothed hi-hat | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.anySmoothed`](/p5/audio/beat#energy-curves-smoothed) | `number` | Smoothed combined | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.triggers.kick`](/p5/audio/beat#triggers) | `boolean` | Kick trigger (true for one frame) | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.triggers.snare`](/p5/audio/beat#triggers) | `boolean` | Snare trigger (true for one frame) | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.triggers.hat`](/p5/audio/beat#triggers) | `boolean` | Hi-hat trigger (true for one frame) | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.triggers.any`](/p5/audio/beat#triggers) | `boolean` | Any beat trigger (true for one frame) | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.events`](/p5/audio/beat#events) | `Array<{ type, time, strength }>` | Beat events this frame | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.bpm`](/p5/audio/beat#tempo) | `number` | Tracked BPM | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.confidence`](/p5/audio/beat#tempo) | `number` | Beat-tracker confidence 0-1 | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.isLocked`](/p5/audio/beat#tempo) | `boolean` | Whether beat tracking is locked | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.spectral.brightness`](/p5/audio/spectral#property-reference) | `number` | Spectral brightness 0-1 | [Spectral Analysis](/p5/audio/spectral) |\n| [`viji.audio.spectral.flatness`](/p5/audio/spectral#property-reference) | `number` | Spectral flatness 0-1 | [Spectral Analysis](/p5/audio/spectral) |\n| [`viji.audio.getFrequencyData()`](/p5/audio/frequency-data) | `() => Uint8Array` | Raw FFT frequency bins (0-255) | [Frequency Data](/p5/audio/frequency-data) |\n| [`viji.audio.getWaveform()`](/p5/audio/waveform) | `() => Float32Array` | Time-domain waveform (-1 to 1) | [Waveform](/p5/audio/waveform) |\n\n## Video & CV\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.video.isConnected`](/p5/video) | `boolean` | Whether a video source is active | [Overview](/p5/video) |\n| [`viji.video.currentFrame`](/p5/video/basics) | `OffscreenCanvas \\| ImageBitmap \\| null` | Current video frame | [Video Basics](/p5/video/basics) |\n| [`viji.video.frameWidth`](/p5/video/basics) | `number` | Frame width in pixels | [Video Basics](/p5/video/basics) |\n| [`viji.video.frameHeight`](/p5/video/basics) | `number` | Frame height in pixels | [Video Basics](/p5/video/basics) |\n| [`viji.video.frameRate`](/p5/video/basics) | `number` | Video frame rate | [Video Basics](/p5/video/basics) |\n| [`viji.video.getFrameData()`](/p5/video/basics) | `() => ImageData \\| null` | Pixel data for the current frame | [Video Basics](/p5/video/basics) |\n| [`viji.video.cv.faces`](/p5/video/face-detection) | `FaceData[]` | Detected faces | [Face Detection](/p5/video/face-detection) |\n| [`viji.video.cv.hands`](/p5/video/hand-tracking) | `HandData[]` | Detected hands | [Hand Tracking](/p5/video/hand-tracking) |\n| [`viji.video.cv.pose`](/p5/video/pose-detection) | `PoseData \\| null` | Detected body pose | [Pose Detection](/p5/video/pose-detection) |\n| [`viji.video.cv.segmentation`](/p5/video/body-segmentation) | `SegmentationData \\| null` | Body segmentation mask | [Body Segmentation](/p5/video/body-segmentation) |\n| [`viji.video.cv.enableFaceDetection(enabled)`](/p5/video/face-detection) | `(boolean) => Promise<void>` | Enable/disable face detection | [Face Detection](/p5/video/face-detection) |\n| [`viji.video.cv.enableFaceMesh(enabled)`](/p5/video/face-mesh) | `(boolean) => Promise<void>` | Enable/disable face mesh | [Face Mesh](/p5/video/face-mesh) |\n| [`viji.video.cv.enableEmotionDetection(enabled)`](/p5/video/emotion-detection) | `(boolean) => Promise<void>` | Enable/disable emotion detection | [Emotion Detection](/p5/video/emotion-detection) |\n| [`viji.video.cv.enableHandTracking(enabled)`](/p5/video/hand-tracking) | `(boolean) => Promise<void>` | Enable/disable hand tracking | [Hand Tracking](/p5/video/hand-tracking) |\n| [`viji.video.cv.enablePoseDetection(enabled)`](/p5/video/pose-detection) | `(boolean) => Promise<void>` | Enable/disable pose detection | [Pose Detection](/p5/video/pose-detection) |\n| [`viji.video.cv.enableBodySegmentation(enabled)`](/p5/video/body-segmentation) | `(boolean) => Promise<void>` | Enable/disable body segmentation | [Body Segmentation](/p5/video/body-segmentation) |\n| [`viji.video.cv.getActiveFeatures()`](/p5/video) | `() => CVFeature[]` | List of active CV features | [Overview](/p5/video) |\n| [`viji.video.cv.isProcessing()`](/p5/video) | `() => boolean` | Whether CV is currently processing | [Overview](/p5/video) |\n\n## Mouse\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.mouse.x`](/p5/mouse#position) | `number` | Cursor X position in pixels | [Mouse](/p5/mouse) |\n| [`viji.mouse.y`](/p5/mouse#position) | `number` | Cursor Y position in pixels | [Mouse](/p5/mouse) |\n| [`viji.mouse.isInCanvas`](/p5/mouse#position) | `boolean` | Whether cursor is inside the canvas | [Mouse](/p5/mouse) |\n| [`viji.mouse.isPressed`](/p5/mouse#buttons) | `boolean` | Whether any button is pressed | [Mouse](/p5/mouse) |\n| [`viji.mouse.leftButton`](/p5/mouse#buttons) | `boolean` | Left button state | [Mouse](/p5/mouse) |\n| [`viji.mouse.rightButton`](/p5/mouse#buttons) | `boolean` | Right button state | [Mouse](/p5/mouse) |\n| [`viji.mouse.middleButton`](/p5/mouse#buttons) | `boolean` | Middle button state | [Mouse](/p5/mouse) |\n| [`viji.mouse.deltaX`](/p5/mouse#movement) | `number` | Horizontal movement since last frame | [Mouse](/p5/mouse) |\n| [`viji.mouse.deltaY`](/p5/mouse#movement) | `number` | Vertical movement since last frame | [Mouse](/p5/mouse) |\n| [`viji.mouse.wheelDelta`](/p5/mouse#scroll-wheel) | `number` | Scroll wheel delta | [Mouse](/p5/mouse) |\n| [`viji.mouse.wheelX`](/p5/mouse#scroll-wheel) | `number` | Horizontal scroll delta | [Mouse](/p5/mouse) |\n| [`viji.mouse.wheelY`](/p5/mouse#scroll-wheel) | `number` | Vertical scroll delta | [Mouse](/p5/mouse) |\n| [`viji.mouse.wasPressed`](/p5/mouse#frame-events) | `boolean` | True for one frame when pressed | [Mouse](/p5/mouse) |\n| [`viji.mouse.wasReleased`](/p5/mouse#frame-events) | `boolean` | True for one frame when released | [Mouse](/p5/mouse) |\n| [`viji.mouse.wasMoved`](/p5/mouse#frame-events) | `boolean` | True for one frame when moved | [Mouse](/p5/mouse) |\n\n## Keyboard\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.keyboard.isPressed(key)`](/p5/keyboard#methods) | `(string) => boolean` | Whether a key is currently held | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.wasPressed(key)`](/p5/keyboard#methods) | `(string) => boolean` | True for one frame when pressed | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.wasReleased(key)`](/p5/keyboard#methods) | `(string) => boolean` | True for one frame when released | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.activeKeys`](/p5/keyboard#properties) | `Set<string>` | All currently held keys | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.pressedThisFrame`](/p5/keyboard#properties) | `Set<string>` | Keys pressed this frame | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.releasedThisFrame`](/p5/keyboard#properties) | `Set<string>` | Keys released this frame | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.lastKeyPressed`](/p5/keyboard#properties) | `string` | Most recently pressed key | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.lastKeyReleased`](/p5/keyboard#properties) | `string` | Most recently released key | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.shift`](/p5/keyboard#modifier-keys) | `boolean` | Shift key state | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.ctrl`](/p5/keyboard#modifier-keys) | `boolean` | Ctrl/Cmd key state | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.alt`](/p5/keyboard#modifier-keys) | `boolean` | Alt/Option key state | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.meta`](/p5/keyboard#modifier-keys) | `boolean` | Meta/Win key state | [Keyboard](/p5/keyboard) |\n\n## Touch\n\n> **Note:** The property is `viji.touches` (plural), not `viji.touch`.\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.touches.points`](/p5/touch#touchapi-vijitouches) | `TouchPoint[]` | All active touch points | [Touch](/p5/touch) |\n| [`viji.touches.count`](/p5/touch#touchapi-vijitouches) | `number` | Number of active touches | [Touch](/p5/touch) |\n| [`viji.touches.started`](/p5/touch#touchapi-vijitouches) | `TouchPoint[]` | Touch points that started this frame | [Touch](/p5/touch) |\n| [`viji.touches.moved`](/p5/touch#touchapi-vijitouches) | `TouchPoint[]` | Touch points that moved this frame | [Touch](/p5/touch) |\n| [`viji.touches.ended`](/p5/touch#touchapi-vijitouches) | `TouchPoint[]` | Touch points that ended this frame | [Touch](/p5/touch) |\n| [`viji.touches.primary`](/p5/touch#touchapi-vijitouches) | `TouchPoint \\| null` | The first active touch point | [Touch](/p5/touch) |\n\n**`TouchPoint` fields:** `id`, `x`, `y`, `pressure`, `radius`, `radiusX`, `radiusY`, `rotationAngle`, `force` (numbers); `isInCanvas`, `isNew`, `isActive`, `isEnding` (booleans); `deltaX`, `deltaY` (numbers); `velocity` `{ x, y }`.\n\n## Pointer (Unified)\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.pointer.x`](/p5/pointer#api-reference) | `number` | Primary pointer X position | [Pointer](/p5/pointer) |\n| [`viji.pointer.y`](/p5/pointer#api-reference) | `number` | Primary pointer Y position | [Pointer](/p5/pointer) |\n| [`viji.pointer.deltaX`](/p5/pointer#api-reference) | `number` | Horizontal movement since last frame | [Pointer](/p5/pointer) |\n| [`viji.pointer.deltaY`](/p5/pointer#api-reference) | `number` | Vertical movement since last frame | [Pointer](/p5/pointer) |\n| [`viji.pointer.isDown`](/p5/pointer#api-reference) | `boolean` | Whether the pointer is active (click or touch) | [Pointer](/p5/pointer) |\n| [`viji.pointer.wasPressed`](/p5/pointer#api-reference) | `boolean` | True for one frame when pressed | [Pointer](/p5/pointer) |\n| [`viji.pointer.wasReleased`](/p5/pointer#api-reference) | `boolean` | True for one frame when released | [Pointer](/p5/pointer) |\n| [`viji.pointer.isInCanvas`](/p5/pointer#api-reference) | `boolean` | Whether pointer is inside the canvas | [Pointer](/p5/pointer) |\n| [`viji.pointer.type`](/p5/pointer#api-reference) | `'mouse' \\| 'touch' \\| 'none'` | Current input source | [Pointer](/p5/pointer) |\n\n## Device Sensors\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.device.motion`](/p5/sensors#devicemotiondata-vijidevicemotion) | `DeviceMotionData \\| null` | Accelerometer and gyroscope data | [Device Sensors](/p5/sensors) |\n| [`viji.device.orientation`](/p5/sensors#deviceorientationdata-vijideviceorientation) | `DeviceOrientationData \\| null` | Device orientation (alpha, beta, gamma) | [Device Sensors](/p5/sensors) |\n\n**`DeviceMotionData`:** `acceleration` `{ x, y, z }`, `accelerationIncludingGravity` `{ x, y, z }`, `rotationRate` `{ alpha, beta, gamma }`, `interval`.\n\n**`DeviceOrientationData`:** `alpha`, `beta`, `gamma` (numbers or null), `absolute` (boolean).\n\n## External Devices\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.devices`](/p5/external-devices#devicestate-vijidevicesi) | `DeviceState[]` | Connected external devices | [Overview](/p5/external-devices) |\n| [`viji.devices[i].id`](/p5/external-devices#devicestate-vijidevicesi) | `string` | Unique device identifier | [Overview](/p5/external-devices) |\n| [`viji.devices[i].name`](/p5/external-devices#devicestate-vijidevicesi) | `string` | User-friendly device name | [Overview](/p5/external-devices) |\n| [`viji.devices[i].motion`](/p5/external-devices/sensors#devicemotiondata-devicemotion) | `DeviceMotionData \\| null` | Device accelerometer/gyroscope | [Device Sensors](/p5/external-devices/sensors) |\n| [`viji.devices[i].orientation`](/p5/external-devices/sensors#deviceorientationdata-deviceorientation) | `DeviceOrientationData \\| null` | Device orientation | [Device Sensors](/p5/external-devices/sensors) |\n| [`viji.devices[i].video`](/p5/external-devices/video) | `VideoAPI \\| null` | Device camera video | [Device Video](/p5/external-devices/video) |\n| [`viji.devices[i].audio`](/p5/external-devices/audio) | `AudioStreamAPI \\| null` | Device audio stream | [Device Audio](/p5/external-devices/audio) |\n\n## Streams\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.videoStreams`](/p5/video) | `VideoAPI[]` | Additional video streams provided by the host | [Video](/p5/video) |\n| [`viji.audioStreams`](/p5/audio#beyond-the-main-stream) | `AudioStreamAPI[]` | Additional audio streams provided by the host | [Audio](/p5/audio) |\n\nEach `videoStreams` element has the same shape as [`viji.video`](/p5/video). Each `audioStreams` element provides lightweight audio analysis (volume, frequency bands, spectral features) but does **not** include beat detection or BPM tracking: see [`viji.audio`](/p5/audio) for full analysis on the main stream.\n\nBoth arrays may be empty if the host does not provide additional streams. Audio streams from external devices appear on `device.audio`, not in `viji.audioStreams`.\n\n## Related\n\n- [Quick Start](/p5/quickstart): getting started with the P5 renderer\n- [Scene Structure](/p5/scene-structure): setup/render pattern and instance mode\n- [Drawing with P5](/p5/drawing): Viji-specific drawing patterns\n- [Best Practices](/getting-started/best-practices): essential patterns for all renderers\n- [Native API Reference](/native/api-reference): the same API in the Native renderer\n- [Shader API Reference](/shader/api-reference): built-in uniforms for shaders\n- [P5.js Reference](https://p5js.org/reference/): official P5.js documentation"
|
|
4336
|
+
"markdown": "# API Reference\n\nThis page lists every property and method available on the `viji` object passed to your P5 scene functions. The `viji` API is identical to the [Native renderer](/native/api-reference): the difference is that P5 scenes also receive a `p5` instance as the second argument.\n\nNew to Viji P5? Start with the [Quick Start](/p5/quickstart) instead.\n\nAll types named on this page are available globally in scene code: annotate variables with them directly, with no imports or aliases. TypeScript is optional; see [TypeScript Support](/native/quickstart#typescript-support).\n\n## Entry Points\n\n```javascript\n// @renderer p5\n\nfunction setup(viji, p5) {\n // Called once when the scene starts (optional)\n}\n\nfunction render(viji, p5) {\n // Called every frame\n}\n```\n\nThe `p5` parameter is a full [P5.js](https://p5js.org/reference/) instance (v1.9.4) in instance mode. All P5 drawing methods (`p5.rect()`, `p5.fill()`, `p5.ellipse()`, etc.) are accessed through it. See [Drawing with P5](/p5/drawing) for Viji-specific drawing patterns.\n\n## Canvas & Context\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.canvas`](/p5/canvas-resolution#vijicanvas-in-p5-scenes) | `OffscreenCanvas` | The rendering canvas | [Canvas & Resolution](/p5/canvas-resolution) |\n| [`viji.width`](/p5/canvas-resolution#resolution-properties) | `number` | Canvas width in pixels | [Canvas & Resolution](/p5/canvas-resolution) |\n| [`viji.height`](/p5/canvas-resolution#resolution-properties) | `number` | Canvas height in pixels | [Canvas & Resolution](/p5/canvas-resolution) |\n\n> [!WARNING]\n> `viji.useContext()` is **not available** in P5 scenes. The canvas and its rendering context (2D or WEBGL, depending on the directive) are managed by P5 internally. Calling `useContext()` would conflict with P5's rendering pipeline.\n\n## Timing\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.time`](/p5/timing#vijitime-oscillations--cycles) | `number` | Seconds elapsed since the scene started | [Timing](/p5/timing) |\n| [`viji.deltaTime`](/p5/timing#vijideltatime-accumulation) | `number` | Seconds since the previous frame | [Timing](/p5/timing) |\n| [`viji.frameCount`](/p5/timing#vijiframecount-vs-p5framecount) | `number` | Monotonically increasing frame counter | [Timing](/p5/timing) |\n| [`viji.fps`](/p5/timing#vijifps-target-frame-rate) | `number` | Target FPS based on the host's frame rate mode | [Timing](/p5/timing) |\n\n## Parameters\n\nAll parameter methods are called at the top level of your scene file. Read `.value` inside `render()` to get the current value.\n\n| Method | Returns | `.value` Type | Details |\n|--------|---------|---------------|---------|\n| [`viji.slider(default, config)`](/p5/parameters/slider) | `SliderParameter` | `number` | [Slider](/p5/parameters/slider) |\n| [`viji.color(default, config)`](/p5/parameters/color) | `ColorParameter` | `string` (hex) | [Color](/p5/parameters/color) |\n| [`viji.toggle(default, config)`](/p5/parameters/toggle) | `ToggleParameter` | `boolean` | [Toggle](/p5/parameters/toggle) |\n| [`viji.select(default, config)`](/p5/parameters/select) | `SelectParameter` | `string \\| number` | [Select](/p5/parameters/select) |\n| [`viji.number(default, config)`](/p5/parameters/number) | `NumberParameter` | `number` | [Number](/p5/parameters/number) |\n| [`viji.text(default, config)`](/p5/parameters/text) | `TextParameter` | `string` | [Text](/p5/parameters/text) |\n| [`viji.image(null, config)`](/p5/parameters/image) | `ImageParameter` | `ImageBitmap \\| null` | [Image](/p5/parameters/image) |\n| [`viji.button(config)`](/p5/parameters/button) | `ButtonParameter` | `boolean` (true for one frame) | [Button](/p5/parameters/button) |\n| [`viji.coordinate(default, config)`](/p5/parameters/coordinate) | `CoordinateParameter` | 2D coordinate pad: `{ x: number, y: number }`, both -1 to 1 | [Coordinate](/p5/parameters/coordinate) |\n\n> [!NOTE]\n> Image parameters have a `.p5` property for use with `p5.image()`. See [Drawing with P5: Image Parameters](/p5/drawing) for the pattern.\n\nSee [Parameters Overview](/p5/parameters) for the declaration pattern, [Grouping](/p5/parameters/grouping) and [Categories](/p5/parameters/categories) for organization.\n\n## Audio\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.audio.isConnected`](/p5/audio) | `boolean` | Whether an audio source is active | [Overview](/p5/audio) |\n| [`viji.audio.volume.current`](/p5/audio/volume#property-reference) | `number` | Current RMS volume 0-1 | [Volume](/p5/audio/volume) |\n| [`viji.audio.volume.peak`](/p5/audio/volume#property-reference) | `number` | Peak volume 0-1 | [Volume](/p5/audio/volume) |\n| [`viji.audio.volume.smoothed`](/p5/audio/volume#property-reference) | `number` | Smoothed volume 0-1 | [Volume](/p5/audio/volume) |\n| [`viji.audio.bands.low`](/p5/audio/bands#instant-bands) | `number` | Low frequency band energy (20-120 Hz) | [Frequency Bands](/p5/audio/bands) |\n| [`viji.audio.bands.lowMid`](/p5/audio/bands#instant-bands) | `number` | Low-mid band energy (120-500 Hz) | [Frequency Bands](/p5/audio/bands) |\n| [`viji.audio.bands.mid`](/p5/audio/bands#instant-bands) | `number` | Mid band energy (500-2 kHz) | [Frequency Bands](/p5/audio/bands) |\n| [`viji.audio.bands.highMid`](/p5/audio/bands#instant-bands) | `number` | High-mid band energy (2-6 kHz) | [Frequency Bands](/p5/audio/bands) |\n| [`viji.audio.bands.high`](/p5/audio/bands#instant-bands) | `number` | High band energy (6-16 kHz) | [Frequency Bands](/p5/audio/bands) |\n| [`viji.audio.bands.lowSmoothed`](/p5/audio/bands#smoothed-bands) | `number` | Smoothed low band | [Frequency Bands](/p5/audio/bands) |\n| [`viji.audio.bands.lowMidSmoothed`](/p5/audio/bands#smoothed-bands) | `number` | Smoothed low-mid band | [Frequency Bands](/p5/audio/bands) |\n| [`viji.audio.bands.midSmoothed`](/p5/audio/bands#smoothed-bands) | `number` | Smoothed mid band | [Frequency Bands](/p5/audio/bands) |\n| [`viji.audio.bands.highMidSmoothed`](/p5/audio/bands#smoothed-bands) | `number` | Smoothed high-mid band | [Frequency Bands](/p5/audio/bands) |\n| [`viji.audio.bands.highSmoothed`](/p5/audio/bands#smoothed-bands) | `number` | Smoothed high band | [Frequency Bands](/p5/audio/bands) |\n| [`viji.audio.beat.kick`](/p5/audio/beat#energy-curves-fast-decay) | `number` | Kick beat energy | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.snare`](/p5/audio/beat#energy-curves-fast-decay) | `number` | Snare beat energy | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.hat`](/p5/audio/beat#energy-curves-fast-decay) | `number` | Hi-hat beat energy | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.any`](/p5/audio/beat#energy-curves-fast-decay) | `number` | Combined beat energy | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.kickSmoothed`](/p5/audio/beat#energy-curves-smoothed) | `number` | Smoothed kick | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.snareSmoothed`](/p5/audio/beat#energy-curves-smoothed) | `number` | Smoothed snare | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.hatSmoothed`](/p5/audio/beat#energy-curves-smoothed) | `number` | Smoothed hi-hat | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.anySmoothed`](/p5/audio/beat#energy-curves-smoothed) | `number` | Smoothed combined | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.triggers.kick`](/p5/audio/beat#triggers) | `boolean` | Kick trigger (true for one frame) | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.triggers.snare`](/p5/audio/beat#triggers) | `boolean` | Snare trigger (true for one frame) | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.triggers.hat`](/p5/audio/beat#triggers) | `boolean` | Hi-hat trigger (true for one frame) | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.triggers.any`](/p5/audio/beat#triggers) | `boolean` | Any beat trigger (true for one frame) | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.events`](/p5/audio/beat#events) | `Array<{ type, time, strength }>` | Beat events this frame | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.bpm`](/p5/audio/beat#tempo) | `number` | Tracked BPM | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.confidence`](/p5/audio/beat#tempo) | `number` | Beat-tracker confidence 0-1 | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.beat.isLocked`](/p5/audio/beat#tempo) | `boolean` | Whether beat tracking is locked | [Beat Detection](/p5/audio/beat) |\n| [`viji.audio.spectral.brightness`](/p5/audio/spectral#property-reference) | `number` | Spectral brightness 0-1 | [Spectral Analysis](/p5/audio/spectral) |\n| [`viji.audio.spectral.flatness`](/p5/audio/spectral#property-reference) | `number` | Spectral flatness 0-1 | [Spectral Analysis](/p5/audio/spectral) |\n| [`viji.audio.getFrequencyData()`](/p5/audio/frequency-data) | `() => Uint8Array` | Raw FFT frequency bins (0-255) | [Frequency Data](/p5/audio/frequency-data) |\n| [`viji.audio.getWaveform()`](/p5/audio/waveform) | `() => Float32Array` | Time-domain waveform (-1 to 1) | [Waveform](/p5/audio/waveform) |\n\n## Video & CV\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.video.isConnected`](/p5/video) | `boolean` | Whether a video source is active | [Overview](/p5/video) |\n| [`viji.video.currentFrame`](/p5/video/basics) | `OffscreenCanvas \\| ImageBitmap \\| null` | Current video frame | [Video Basics](/p5/video/basics) |\n| [`viji.video.frameWidth`](/p5/video/basics) | `number` | Frame width in pixels | [Video Basics](/p5/video/basics) |\n| [`viji.video.frameHeight`](/p5/video/basics) | `number` | Frame height in pixels | [Video Basics](/p5/video/basics) |\n| [`viji.video.frameRate`](/p5/video/basics) | `number` | Video frame rate | [Video Basics](/p5/video/basics) |\n| [`viji.video.getFrameData()`](/p5/video/basics) | `() => ImageData \\| null` | Pixel data for the current frame | [Video Basics](/p5/video/basics) |\n| [`viji.video.cv.faces`](/p5/video/face-detection) | `FaceData[]` | Detected faces | [Face Detection](/p5/video/face-detection) |\n| [`viji.video.cv.hands`](/p5/video/hand-tracking) | `HandData[]` | Detected hands | [Hand Tracking](/p5/video/hand-tracking) |\n| [`viji.video.cv.pose`](/p5/video/pose-detection) | `PoseData \\| null` | Detected body pose | [Pose Detection](/p5/video/pose-detection) |\n| [`viji.video.cv.segmentation`](/p5/video/body-segmentation) | `SegmentationData \\| null` | Body segmentation mask | [Body Segmentation](/p5/video/body-segmentation) |\n| [`viji.video.cv.enableFaceDetection(enabled)`](/p5/video/face-detection) | `(boolean) => Promise<void>` | Enable/disable face detection | [Face Detection](/p5/video/face-detection) |\n| [`viji.video.cv.enableFaceMesh(enabled)`](/p5/video/face-mesh) | `(boolean) => Promise<void>` | Enable/disable face mesh | [Face Mesh](/p5/video/face-mesh) |\n| [`viji.video.cv.enableEmotionDetection(enabled)`](/p5/video/emotion-detection) | `(boolean) => Promise<void>` | Enable/disable emotion detection | [Emotion Detection](/p5/video/emotion-detection) |\n| [`viji.video.cv.enableHandTracking(enabled)`](/p5/video/hand-tracking) | `(boolean) => Promise<void>` | Enable/disable hand tracking | [Hand Tracking](/p5/video/hand-tracking) |\n| [`viji.video.cv.enablePoseDetection(enabled)`](/p5/video/pose-detection) | `(boolean) => Promise<void>` | Enable/disable pose detection | [Pose Detection](/p5/video/pose-detection) |\n| [`viji.video.cv.enableBodySegmentation(enabled)`](/p5/video/body-segmentation) | `(boolean) => Promise<void>` | Enable/disable body segmentation | [Body Segmentation](/p5/video/body-segmentation) |\n| [`viji.video.cv.getActiveFeatures()`](/p5/video) | `() => CVFeature[]` | List of active CV features | [Overview](/p5/video) |\n| [`viji.video.cv.isProcessing()`](/p5/video) | `() => boolean` | Whether CV is currently processing | [Overview](/p5/video) |\n\n## Mouse\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.mouse.x`](/p5/mouse#position) | `number` | Cursor X position in pixels | [Mouse](/p5/mouse) |\n| [`viji.mouse.y`](/p5/mouse#position) | `number` | Cursor Y position in pixels | [Mouse](/p5/mouse) |\n| [`viji.mouse.isInCanvas`](/p5/mouse#position) | `boolean` | Whether cursor is inside the canvas | [Mouse](/p5/mouse) |\n| [`viji.mouse.isPressed`](/p5/mouse#buttons) | `boolean` | Whether any button is pressed | [Mouse](/p5/mouse) |\n| [`viji.mouse.leftButton`](/p5/mouse#buttons) | `boolean` | Left button state | [Mouse](/p5/mouse) |\n| [`viji.mouse.rightButton`](/p5/mouse#buttons) | `boolean` | Right button state | [Mouse](/p5/mouse) |\n| [`viji.mouse.middleButton`](/p5/mouse#buttons) | `boolean` | Middle button state | [Mouse](/p5/mouse) |\n| [`viji.mouse.deltaX`](/p5/mouse#movement) | `number` | Horizontal movement since last frame | [Mouse](/p5/mouse) |\n| [`viji.mouse.deltaY`](/p5/mouse#movement) | `number` | Vertical movement since last frame | [Mouse](/p5/mouse) |\n| [`viji.mouse.wheelDelta`](/p5/mouse#scroll-wheel) | `number` | Scroll wheel delta | [Mouse](/p5/mouse) |\n| [`viji.mouse.wheelX`](/p5/mouse#scroll-wheel) | `number` | Horizontal scroll delta | [Mouse](/p5/mouse) |\n| [`viji.mouse.wheelY`](/p5/mouse#scroll-wheel) | `number` | Vertical scroll delta | [Mouse](/p5/mouse) |\n| [`viji.mouse.wasPressed`](/p5/mouse#frame-events) | `boolean` | True for one frame when pressed | [Mouse](/p5/mouse) |\n| [`viji.mouse.wasReleased`](/p5/mouse#frame-events) | `boolean` | True for one frame when released | [Mouse](/p5/mouse) |\n| [`viji.mouse.wasMoved`](/p5/mouse#frame-events) | `boolean` | True for one frame when moved | [Mouse](/p5/mouse) |\n\n## Keyboard\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.keyboard.isPressed(key)`](/p5/keyboard#methods) | `(string) => boolean` | Whether a key is currently held | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.wasPressed(key)`](/p5/keyboard#methods) | `(string) => boolean` | True for one frame when pressed | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.wasReleased(key)`](/p5/keyboard#methods) | `(string) => boolean` | True for one frame when released | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.activeKeys`](/p5/keyboard#properties) | `Set<string>` | All currently held keys | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.pressedThisFrame`](/p5/keyboard#properties) | `Set<string>` | Keys pressed this frame | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.releasedThisFrame`](/p5/keyboard#properties) | `Set<string>` | Keys released this frame | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.lastKeyPressed`](/p5/keyboard#properties) | `string` | Most recently pressed key | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.lastKeyReleased`](/p5/keyboard#properties) | `string` | Most recently released key | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.shift`](/p5/keyboard#modifier-keys) | `boolean` | Shift key state | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.ctrl`](/p5/keyboard#modifier-keys) | `boolean` | Ctrl/Cmd key state | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.alt`](/p5/keyboard#modifier-keys) | `boolean` | Alt/Option key state | [Keyboard](/p5/keyboard) |\n| [`viji.keyboard.meta`](/p5/keyboard#modifier-keys) | `boolean` | Meta/Win key state | [Keyboard](/p5/keyboard) |\n\n## Touch\n\n> **Note:** The property is `viji.touches` (plural), not `viji.touch`.\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.touches.points`](/p5/touch#touchapi-vijitouches) | `TouchPoint[]` | All active touch points | [Touch](/p5/touch) |\n| [`viji.touches.count`](/p5/touch#touchapi-vijitouches) | `number` | Number of active touches | [Touch](/p5/touch) |\n| [`viji.touches.started`](/p5/touch#touchapi-vijitouches) | `TouchPoint[]` | Touch points that started this frame | [Touch](/p5/touch) |\n| [`viji.touches.moved`](/p5/touch#touchapi-vijitouches) | `TouchPoint[]` | Touch points that moved this frame | [Touch](/p5/touch) |\n| [`viji.touches.ended`](/p5/touch#touchapi-vijitouches) | `TouchPoint[]` | Touch points that ended this frame | [Touch](/p5/touch) |\n| [`viji.touches.primary`](/p5/touch#touchapi-vijitouches) | `TouchPoint \\| null` | The first active touch point | [Touch](/p5/touch) |\n\n**`TouchPoint` fields:** `id`, `x`, `y`, `pressure`, `radius`, `radiusX`, `radiusY`, `rotationAngle`, `force` (numbers); `isInCanvas`, `isNew`, `isActive`, `isEnding` (booleans); `deltaX`, `deltaY` (numbers); `velocity` `{ x, y }`.\n\n## Pointer (Unified)\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.pointer.x`](/p5/pointer#api-reference) | `number` | Primary pointer X position | [Pointer](/p5/pointer) |\n| [`viji.pointer.y`](/p5/pointer#api-reference) | `number` | Primary pointer Y position | [Pointer](/p5/pointer) |\n| [`viji.pointer.deltaX`](/p5/pointer#api-reference) | `number` | Horizontal movement since last frame | [Pointer](/p5/pointer) |\n| [`viji.pointer.deltaY`](/p5/pointer#api-reference) | `number` | Vertical movement since last frame | [Pointer](/p5/pointer) |\n| [`viji.pointer.isDown`](/p5/pointer#api-reference) | `boolean` | Whether the pointer is active (click or touch) | [Pointer](/p5/pointer) |\n| [`viji.pointer.wasPressed`](/p5/pointer#api-reference) | `boolean` | True for one frame when pressed | [Pointer](/p5/pointer) |\n| [`viji.pointer.wasReleased`](/p5/pointer#api-reference) | `boolean` | True for one frame when released | [Pointer](/p5/pointer) |\n| [`viji.pointer.isInCanvas`](/p5/pointer#api-reference) | `boolean` | Whether pointer is inside the canvas | [Pointer](/p5/pointer) |\n| [`viji.pointer.type`](/p5/pointer#api-reference) | `'mouse' \\| 'touch' \\| 'none'` | Current input source | [Pointer](/p5/pointer) |\n\n## Device Sensors\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.device.motion`](/p5/sensors#devicemotiondata-vijidevicemotion) | `DeviceMotionData \\| null` | Accelerometer and gyroscope data | [Device Sensors](/p5/sensors) |\n| [`viji.device.orientation`](/p5/sensors#deviceorientationdata-vijideviceorientation) | `DeviceOrientationData \\| null` | Device orientation (alpha, beta, gamma) | [Device Sensors](/p5/sensors) |\n\n**`DeviceMotionData`:** `acceleration` `{ x, y, z }`, `accelerationIncludingGravity` `{ x, y, z }`, `rotationRate` `{ alpha, beta, gamma }`, `interval`.\n\n**`DeviceOrientationData`:** `alpha`, `beta`, `gamma` (numbers or null), `absolute` (boolean).\n\n## External Devices\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.devices`](/p5/external-devices#devicestate-vijidevicesi) | `DeviceState[]` | Connected external devices | [Overview](/p5/external-devices) |\n| [`viji.devices[i].id`](/p5/external-devices#devicestate-vijidevicesi) | `string` | Unique device identifier | [Overview](/p5/external-devices) |\n| [`viji.devices[i].name`](/p5/external-devices#devicestate-vijidevicesi) | `string` | User-friendly device name | [Overview](/p5/external-devices) |\n| [`viji.devices[i].motion`](/p5/external-devices/sensors#devicemotiondata-devicemotion) | `DeviceMotionData \\| null` | Device accelerometer/gyroscope | [Device Sensors](/p5/external-devices/sensors) |\n| [`viji.devices[i].orientation`](/p5/external-devices/sensors#deviceorientationdata-deviceorientation) | `DeviceOrientationData \\| null` | Device orientation | [Device Sensors](/p5/external-devices/sensors) |\n| [`viji.devices[i].video`](/p5/external-devices/video) | `VideoAPI \\| null` | Device camera video | [Device Video](/p5/external-devices/video) |\n| [`viji.devices[i].audio`](/p5/external-devices/audio) | `AudioStreamAPI \\| null` | Device audio stream | [Device Audio](/p5/external-devices/audio) |\n\n## Streams\n\n| Member | Type | Description | Details |\n|--------|------|-------------|---------|\n| [`viji.videoStreams`](/p5/video) | `VideoAPI[]` | Additional video streams provided by the host | [Video](/p5/video) |\n| [`viji.audioStreams`](/p5/audio#beyond-the-main-stream) | `AudioStreamAPI[]` | Additional audio streams provided by the host | [Audio](/p5/audio) |\n\nEach `videoStreams` element has the same shape as [`viji.video`](/p5/video). Each `audioStreams` element provides lightweight audio analysis (volume, frequency bands, spectral features) but does **not** include beat detection or BPM tracking: see [`viji.audio`](/p5/audio) for full analysis on the main stream.\n\nBoth arrays may be empty if the host does not provide additional streams. Audio streams from external devices appear on `device.audio`, not in `viji.audioStreams`.\n\n## Related\n\n- [Quick Start](/p5/quickstart): getting started with the P5 renderer\n- [Scene Structure](/p5/scene-structure): setup/render pattern and instance mode\n- [Drawing with P5](/p5/drawing): Viji-specific drawing patterns\n- [Best Practices](/getting-started/best-practices): essential patterns for all renderers\n- [Native API Reference](/native/api-reference): the same API in the Native renderer\n- [Shader API Reference](/shader/api-reference): built-in uniforms for shaders\n- [P5.js Reference](https://p5js.org/reference/): official P5.js documentation"
|
|
4337
4337
|
}
|
|
4338
4338
|
]
|
|
4339
4339
|
},
|
|
@@ -9849,8 +9849,8 @@ export const docsApi = {
|
|
|
9849
9849
|
"ai": {
|
|
9850
9850
|
"systemPrompts": {
|
|
9851
9851
|
"base": "# Viji API: Base Reference\n\nThis document is the renderer-agnostic foundation for generating Viji scenes. It is loaded into every AI turn alongside the renderer-specific reference for the renderer in use.\n\n## Architecture\n\nViji scenes run inside a **Web Worker** on an **OffscreenCanvas**. There is no DOM.\n\n- Top-level code runs once when the scene loads (parameter declarations, state, imports).\n- A `render` function (or, for shaders, `void main()`) runs every frame.\n- `fetch()` and `await import()` are available. `window`, `document`, `Image()`, and `localStorage` are not.\n- The global `viji` object exposes everything: canvas, timing, audio, video, computer vision, input, sensors, and parameters. Each renderer also has its own surface (P5's `p5.*` API; the shader's auto-injected uniforms).\n\n## Renderers\n\nThree renderers. Pick by the visual goal, not by perceived difficulty.\n\n| | Native | P5 | Shader |\n|---|---|---|---|\n| Language | JavaScript (Canvas 2D / WebGL) | JavaScript + P5.js 1.9.4 | GLSL fragment shader |\n| Best for | Full control, Three.js, generative art, pixel-perfect Canvas 2D | Creative coding with shapes, colors, transforms; ports of existing P5 sketches | GPU effects, patterns, raymarching, SDF, post-processing |\n| 3D | Yes (WebGL, Three.js via `await import()`) | Yes (`// @renderer p5 webgl`) | Yes (raymarching, SDF) |\n| External libraries | Yes (any ESM via `await import()`) | P5.js built-in | None (GPU only) |\n\n### Decision criteria\n\n- **Per-pixel GPU effects** (raymarching, fractals, distance fields, fullscreen post-processing, patterns that read every pixel): use **Shader**.\n- **3D with Three.js, custom WebGL, pixel-perfect Canvas 2D, or any external ESM library**: use **Native**.\n- **Classic P5 shapes and transforms** (`ellipse`, `line`, `bezier`, color modes, `push`/`pop`), or a port of an existing P5 sketch: use **P5**.\n- **When ambiguous, default to Native**. Audio reactivity, camera/CV, parameters, and input work in every renderer. Pick on visual style, not data sources.\n\n## Scene shape per renderer\n\nEach example below is the minimum viable entry point. Full surface lives in the matching renderer reference.\n\n**Native**:\n```javascript\nconst speed = viji.slider(1, { min: 0.1, max: 5, label: 'Speed' });\nlet angle = 0;\nfunction render(viji) {\n const ctx = viji.useContext('2d');\n angle += speed.value * viji.deltaTime;\n ctx.clearRect(0, 0, viji.width, viji.height);\n // draw with ctx\n}\n```\n\n**P5**:\n```javascript\n// @renderer p5\nconst speed = viji.slider(1, { min: 0.1, max: 5, label: 'Speed' });\nlet angle = 0;\nfunction setup(viji, p5) { p5.colorMode(p5.HSB, 360, 100, 100); }\nfunction render(viji, p5) {\n angle += speed.value * viji.deltaTime;\n p5.background(0);\n // draw with p5.* prefixed calls\n}\n```\n\n**Shader (GLSL)**:\n```glsl\n// @renderer shader\n// @viji-slider:speed label:\"Speed\" default:1.0 min:0.1 max:5.0\n// @viji-accumulator:phase rate:speed\nvoid main() {\n vec2 uv = gl_FragCoord.xy / u_resolution;\n gl_FragColor = vec4(uv, sin(phase) * 0.5 + 0.5, 1.0);\n}\n```\n\n## Cross-cutting rules (apply to every renderer)\n\n1. **Never** touch the DOM. No `window`, `document`, `Image()`, `localStorage`. `fetch()` and `await import()` are available.\n2. **Always** declare parameters at the **top level**, never inside `render()` or `main()`. Parameters declared inside a render call are recreated every frame and break the host UI.\n3. **Always** use `viji.width` / `viji.height` (or `u_resolution` in shaders) for canvas dimensions. Never hardcode pixel sizes.\n4. **Always** use `viji.deltaTime` (or `u_deltaTime` / `@viji-accumulator` in shaders) for animation. Never count frames or assume a fixed frame rate.\n5. **Never** multiply `viji.time` (or `u_time`) by a parameter to drive animation speed. It causes visible jumps when the slider changes. Use a `deltaTime` accumulator at the top level instead. In shaders, use `@viji-accumulator`. This also applies to nested multiplications: never multiply an accumulator by another parameter. Each independent speed gets its own accumulator.\n6. **Never** allocate objects, arrays, or strings inside `render()`. Pre-allocate at the top level and reuse.\n7. **Always** check `viji.audio.isConnected` (or `u_audioVolume > 0.0`) before reading audio data. Check `viji.video.isConnected && viji.video.currentFrame` (or `u_videoConnected`) before reading video. When an input is not connected, degrade gracefully — keep rendering the scene's normal idle/ambient visual. Do **not** draw on-canvas text telling the user to connect or turn on a camera, microphone, or other input; the host provides those controls. (The connection-demo examples draw \"Waiting for…\" text only to illustrate this check itself — don't copy that into real scenes unless the user explicitly asks for an on-canvas prompt.)\n8. **CV features are independent**: each `enableX()` populates only its own subset of fields. Face detection populates `face.bounds` / `center` / `confidence`; face mesh populates `face.landmarks` / `headPose`; emotion detection populates `face.expressions` / `blendshapes`. Fields whose source model is not enabled read as `null` (or `[]` for `landmarks`) — always null-check before reading. CV is expensive and is **not** host-gated, so it is the one feature class that legitimately belongs behind a parameter toggle — but gate by intent: if a CV feature is the scene's defining purpose (the scene is meaningless without it), enable it always-on from module scope; if CV is optional/supplementary, or the scene uses several heavy features, gate each behind a `viji.toggle` (shader: the toggleable `@viji-cv:` form) so the user opts into the cost — and make sure the base visual stands on its own when a toggle is off (no \"enable in parameters\" banner). Each active CV feature uses its own WebGL context; 4+ on low-end hardware can hit context limits, so enable only what you need.\n9. **Always** set `category` on parameters that depend on an external input: `category: 'audio'` for audio-driven controls, `category: 'video'` for video / CV-driven controls, `category: 'interaction'` for mouse / keyboard / touch controls. Omit `category` (defaults to `'general'`) for parameters that work without external input. **Never** add on/off parameter toggles to enable/disable built-in inputs or device features — audio, video, mouse, keyboard, touch, motion/orientation sensors, and external devices are all gated by the host's own controls. Read them in code behind `isConnected` / `isInCanvas` / null checks. A parameter that shapes how an input drives the visual (e.g. a sensitivity slider) is fine; an on/off enable toggle for the input itself is not. If the user explicitly asks for one, advise that the host already provides it before complying. (CV features are the sole exception — see the CV rule above.)\n10. **In P5**: prefix every P5 function and constant with `p5.` (instance mode). Never call `createCanvas()`; Viji creates the canvas.\n11. **In shaders**: never redeclare `precision`, never redeclare built-in uniforms (`u_time`, `u_resolution`, etc.), never redeclare parameter uniforms. Never use the `u_` prefix for your own parameter names; it is reserved for Viji's built-ins.\n\n## Parameter declaration shape (cross-renderer)\n\nAssign each parameter to its own top-level `const` with a unique camelCase\nname (`const speed = viji.slider(1, { label: 'Speed' })`) and read it with\n`.value`. `label` is optional but recommended (falls back to the variable\nname). Native and P5 use JavaScript calls at the top level:\n\n```javascript\nviji.slider(default, { min, max, step, label, group, category }) // .value: number\nviji.color(default, { label }) // .value: '#rrggbb', .rgb, .hsb\nviji.toggle(default, { label }) // .value: boolean\nviji.select(default, { options, label }) // .value: string | number\nviji.number(default, { min, max, step, label }) // .value: number\nviji.text(default, { label, maxLength }) // .value: string\nviji.image(null, { label }) // .value: ImageBitmap | null\nviji.button({ label }) // .value: boolean (true for 1 frame)\nviji.coordinate({ x: 0, y: 0 }, { step, label, group, category }) // .value: { x, y }, range -1..1\n```\n\n**`slider` / `number` `step` default**: when omitted, `step` auto-derives from `min`/`max` as the largest power of 10 giving ~100 positions across the range (e.g., range `0..1` → `0.01`; range `0.1..5` → `0.01`; range `0..100` → `1`). Specify explicitly only when you need a different grid: `step: 1` for integer counts (`{ min: 3, max: 30, step: 1 }`), `step: 0.001` for fine precision.\n\nShaders use GLSL comment directives that compile to typed uniforms:\n\n```glsl\n// @viji-slider:name label:\"Label\" default:1.0 min:0.0 max:5.0 -> uniform float name;\n// @viji-color:name label:\"Color\" default:#ff6600 -> uniform vec3 name;\n// @viji-toggle:name label:\"Toggle\" default:false -> uniform bool name;\n// @viji-select:name label:\"Mode\" default:0 options:[\"A\",\"B\"] -> uniform int name;\n// @viji-number:name label:\"Count\" default:10.0 min:1.0 max:100.0 -> uniform float name;\n// @viji-image:name label:\"Texture\" -> uniform sampler2D name;\n// @viji-button:name label:\"Reset\" -> uniform bool name;\n// @viji-coordinate:name label:\"Pos\" default:[0.0,0.0] -> uniform vec2 name; // range -1..1\n// @viji-accumulator:name rate:speed -> uniform float name;\n```\n\nDirectives use `//` line comments only. Block comments (`/* */`) are not parsed.\n\n## Where to look next\n\nFor the full API surface of the renderer in use, consult the matching reference: Native, P5, or Shader. Each renderer reference includes the complete data shapes for audio, video, CV, input, sensors, external devices, and renderer-specific patterns (e.g. `viji.useContext` for Native, `videoFit` for P5, the complete uniform table for Shader).\n",
|
|
9852
|
-
"native": "# Viji API: Native Renderer Reference\n\nNative scenes run JavaScript on an `OffscreenCanvas` in a Web Worker, with full access to Canvas 2D, WebGL, and WebGL2 contexts. External libraries load via `await import()`. Top-level code runs once; a `render(viji)` function runs every frame.\n\n## Architecture\n\n- The global `viji` object exposes canvas, timing, audio, video, CV, input, sensors, parameters.\n- Call `viji.useContext('2d' | 'webgl' | 'webgl2')` once at the top of `render()` (or top-level) to obtain a rendering context. After the first call, `viji.ctx` / `viji.gl` shortcuts are populated.\n- **Pick one context type for the entire scene.** Calling `useContext` with a different type after the first call returns `null`.\n- There is **no `setup()` function** in Native. All initialization goes at the top level (which supports `await` for dynamic imports).\n- The DOM is unavailable. `fetch()` and `await import()` are available.\n\n## Rules\n\n1. **Never** access `window`, `document`, `Image()`, `localStorage`, or any DOM API. `fetch()` and `await import()` are available.\n2. **Always** declare parameters at the top level as individual `const`s (`const speed = viji.slider(...)`), never inside `render()`. `label` is optional but recommended (falls back to the variable name).\n3. **Always** read parameters via `.value`. Color parameters also expose `.rgb` (`{ r, g, b }` in 0..255) and `.hsb` (`{ h, s, b }` with `h` in 0..360, `s` / `b` in 0..100). Color defaults accept hex (`'#ff6600'`, `'#f60'`), `{ r, g, b }` (0..255), `{ h, s, b }` (0..360 / 0..100), or CSS `'rgb(...)'` / `'hsl(...)'` strings.\n4. **Always** use `viji.width` and `viji.height` for canvas dimensions. Never hardcode pixel sizes.\n5. **Always** use `viji.deltaTime` for animation. Use `viji.time` only for constant-speed oscillations (`Math.sin(viji.time * 2.0)`). For anything driven by a parameter, use a `deltaTime` accumulator.\n6. **Never** multiply `viji.time` by a parameter; it causes visible jumps when the parameter changes. Use a `deltaTime` accumulator at the top level. This also applies to nested multiplications: each independent speed gets its own accumulator.\n\n ```javascript\n // WRONG\n const t = viji.time * speed.value;\n const rot = phase * rotSpeed.value;\n\n // RIGHT\n let phase = 0, rotPhase = 0;\n phase += speed.value * viji.deltaTime;\n rotPhase += speed.value * rotSpeed.value * viji.deltaTime;\n ```\n7. **Never** allocate objects, arrays, or strings inside `render()`. Pre-allocate at the top level and reuse.\n8. **Always** call `viji.useContext()` to get a context. Pick one type and use it for the entire scene.\n9. **Always** check `viji.audio.isConnected` before reading audio data. Check `viji.video.isConnected && viji.video.currentFrame` before drawing video. When not connected, keep rendering the idle visual — don't draw on-canvas \"connect a camera/mic\" instructions.\n10. Enable CV by intent: always-on from module scope when CV is the scene's defining purpose, otherwise gated behind a `viji.toggle` so the user opts into the cost.\n11. **Always** set `category` on input-dependent parameters (`'audio'`, `'video'`, `'interaction'`). Don't add on/off toggles to enable/disable host-gated inputs (audio, video, mouse, keyboard, touch, sensors, devices) — the host controls those. CV is the only exception (it gets a toggle when not always-on).\n12. **Always** type any function parameter that receives the `viji` instance, including `render(viji)` and any helpers that take `viji`. Monaco's TS checker flags API misuse (wrong nesting, typo'd property names) at edit time so the error can be corrected before runtime. Scene code is transpiled via sucrase before execution (`transforms: ['typescript']`), so TS annotations are stripped at runtime — they are safe to include.\n\n ```javascript\n function render(viji: VijiAPI) { ... }\n function applyGlow(viji: VijiAPI, intensity: number) { ... }\n ```\n\n## API reference\n\n### Canvas and context\n\n| Member | Type | Description |\n|---|---|---|\n| `viji.canvas` | `OffscreenCanvas` | The canvas |\n| `viji.useContext('2d')` | `OffscreenCanvasRenderingContext2D` | Acquire 2D context |\n| `viji.useContext('webgl')` | `WebGLRenderingContext` | Acquire WebGL 1 |\n| `viji.useContext('webgl2')` | `WebGL2RenderingContext` | Acquire WebGL 2 |\n| `viji.ctx` | `OffscreenCanvasRenderingContext2D` | Shortcut after `useContext('2d')` |\n| `viji.gl` | `WebGLRenderingContext \\| WebGL2RenderingContext` | Shortcut after WebGL context acquired |\n| `viji.width`, `viji.height` | `number` | Current canvas dimensions in pixels |\n\n### Timing\n\n| Member | Type | Description |\n|---|---|---|\n| `viji.time` | `number` | Seconds since scene start |\n| `viji.deltaTime` | `number` | Seconds since last frame |\n| `viji.frameCount` | `number` | Total frames rendered |\n| `viji.fps` | `number` | Target frame rate (host-controlled) |\n\n### Parameters\n\nDeclare at top level. All accept `{ label, description?, group?, category? }`. Category values: `'audio'`, `'video'`, `'interaction'`, `'general'` (default).\n\n```javascript\nviji.slider(default, { min?, max?, step?, label, group?, category? }) // .value: number\nviji.color(default, { label, group?, category? }) // .value: '#rrggbb', .rgb: {r,g,b} 0..255, .hsb: {h:0..360, s/b:0..100}\nviji.toggle(default, { label, group?, category? }) // .value: boolean\nviji.select(default, { options, label, group?, category? }) // .value: string | number\nviji.number(default, { min?, max?, step?, label, group?, category? }) // .value: number\nviji.text(default, { label, group?, category?, maxLength? }) // .value: string\nviji.image(null, { label, group?, category? }) // .value: ImageBitmap | null\nviji.button({ label, description?, group?, category? }) // .value: boolean (true for 1 frame)\nviji.coordinate(default, { step?, label, group?, category? }) // .value: { x, y }, range -1..1\n// slider/number `step` defaults to a power of 10 giving ~100 positions across min..max\n// (e.g., range 0..1 → 0.01, range 0..100 → 1). Specify `step: 1` for integer counts.\n```\n\n### Audio: `viji.audio`\n\nCheck `isConnected` first.\n\n| Member | Type | Notes |\n|---|---|---|\n| `isConnected` | `boolean` | Audio source active |\n| `volume.current`, `volume.peak`, `volume.smoothed` | `number` 0..1 | `smoothed` = 200ms decay envelope of `current` |\n| `bands.low`, `lowMid`, `mid`, `highMid`, `high` | `number` 0..1 | Instant band energies (20-120, 120-400, 400-1600, 1600-6000, 6000-16000 Hz) |\n| `bands.lowSmoothed`, `lowMidSmoothed`, `midSmoothed`, `highMidSmoothed`, `highSmoothed` | `number` 0..1 | 150ms decay envelope siblings (not nested) |\n| `beat.kick`, `snare`, `hat`, `any` | `number` 0..1 | Beat energy curves with a 300ms decay; peak on each detected beat then fall off |\n| `beat.kickSmoothed`, `snareSmoothed`, `hatSmoothed`, `anySmoothed` | `number` 0..1 | Smoother 500ms decay envelopes; use for ambient pulses |\n| `beat.triggers.kick`, `snare`, `hat`, `any` | `boolean` | True for exactly one frame on the matching beat, then auto-resets. OR-accumulated between frames so no beat is lost |\n| `beat.events` | `Array<{type, time, strength}>` | All beats detected since the last frame; `type` is `'kick' \\| 'snare' \\| 'hat'` (never `'any'`); `time` in milliseconds; cleared each frame |\n| `beat.bpm`, `beat.confidence`, `beat.isLocked` | `number`, `number`, `boolean` | `bpm` is `0` when no audio is connected; once audio connects it tracks the detected tempo (clamped to 60..240) with `120` as a fallback before lock-on. `confidence` in 0..1. `isLocked` is `true` on stable tempo lock |\n| `spectral.brightness`, `spectral.flatness` | `number` 0..1 | Spectral centroid; spectral flatness |\n| `getFrequencyData()` | `Uint8Array` | Raw FFT bins 0..255 |\n| `getWaveform()` | `Float32Array` | Time-domain waveform -1..1 |\n\nExternal-device audio (`viji.devices[i].audio`) and host-supplied audio streams (`viji.audioStreams[i]`) use the `AudioStreamAPI` shape: `isConnected`, `volume.{current,peak,smoothed}`, `bands.{low...high}` plus each `*Smoothed` sibling, `spectral.{brightness,flatness}`, `getFrequencyData()`, `getWaveform()`. No `beat`, BPM, triggers, or events on streams: those exist only on the main `viji.audio`.\n\n### Video: `viji.video`\n\nCheck `isConnected && currentFrame` before drawing.\n\n| Member | Type | Notes |\n|---|---|---|\n| `isConnected` | `boolean` | Video source active |\n| `currentFrame` | `OffscreenCanvas \\| ImageBitmap \\| null` | Most recent frame |\n| `frameWidth`, `frameHeight` | `number` | Source frame size |\n| `frameRate` | `number` | Source frame rate |\n| `getFrameData()` | `ImageData \\| null` | Pixel data of `currentFrame` |\n| `cv` | `VideoCVAPI` | Computer-vision surface: see below |\n\nCV data outputs (`analysedFrame`, `getAnalysedFrameData()`, `faces`, `hands`, `pose`, `segmentation`) and CV verbs (`enableFaceDetection`, etc.) all live on `viji.video.cv`, not on `viji.video` directly.\n\n**Aspect ratio.** Camera frames almost never match the canvas aspect. Drawing to `(0, 0, viji.width, viji.height)` stretches video and misaligns CV bounds. Use this helper at module scope:\n\n```javascript\nfunction videoFit(viji, mode = 'cover') {\n const vw = viji.video.frameWidth, vh = viji.video.frameHeight;\n const w = viji.width, h = viji.height;\n if (!vw || !vh) return { x: 0, y: 0, width: 0, height: 0 };\n const scale = mode === 'cover' ? Math.max(w / vw, h / vh) : Math.min(w / vw, h / vh);\n const dw = vw * scale, dh = vh * scale;\n return { x: (w - dw) / 2, y: (h - dh) / 2, width: dw, height: dh };\n}\n\nconst v = videoFit(viji); // 'cover' or 'contain'\nctx.drawImage(viji.video.currentFrame, v.x, v.y, v.width, v.height);\n\n// CV coords are normalized 0..1 to the source frame. Map through v to align with the fitted video:\nviji.video.cv.faces.forEach(face => {\n const bx = v.x + face.bounds.x * v.width;\n const by = v.y + face.bounds.y * v.height;\n const bw = face.bounds.width * v.width;\n const bh = face.bounds.height * v.height;\n ctx.strokeRect(bx, by, bw, bh);\n});\n```\n\nDefault to `'cover'` for live cameras. Use `'contain'` for CV-overlay scenes where bounding boxes near frame edges must stay visible. `viji.video.currentFrame` is the right default for displayed video; reach for `viji.video.cv.analysedFrame` only when sampling pixels at CV-derived positions (segmentation compositing, face-mesh texturing, landmark-anchored color sampling). The common fallback pattern is `viji.video.cv.analysedFrame ?? viji.video.currentFrame` during the brief window before the first CV inference lands.\n\n### Computer Vision: `viji.video.cv`\n\nEach CV feature is independent and populates only its own subset of fields. Enable only what you need (each active feature consumes a separate WebGL context for MediaPipe; 4+ on low-end hardware risks context-limit failures).\n\n```javascript\n// Verbs return Promise<void>. await is optional — without it, the model loads\n// asynchronously while render runs and data fields populate when ready.\n// Safe to call from module scope (always-on CV) or per-frame inside render()\n// gated by a viji.toggle(...) (opt-in CV). Idempotent + reference-counted.\nawait viji.video.cv.enableFaceDetection(true | false); // populates face.bounds, face.center, face.confidence\nawait viji.video.cv.enableFaceMesh(true | false); // populates face.landmarks (468 pts) + face.headPose\nawait viji.video.cv.enableEmotionDetection(true | false); // populates face.expressions + face.blendshapes; also loads landmarker (face.landmarks + face.headPose populated)\nawait viji.video.cv.enableHandTracking(true | false); // populates viji.video.cv.hands[]\nawait viji.video.cv.enablePoseDetection(true | false); // populates viji.video.cv.pose\nawait viji.video.cv.enableBodySegmentation(true | false); // populates viji.video.cv.segmentation\nviji.video.cv.getActiveFeatures(); // CVFeature[]\nviji.video.cv.isProcessing(); // boolean\n```\n\nData outputs on `viji.video.cv`:\n- `analysedFrame: OffscreenCanvas | null`: the exact frame paired with the current CV results. `null` until the first inference lands after a feature is enabled. Use the pattern `viji.video.cv.analysedFrame ?? viji.video.currentFrame` to fall back during the startup window.\n- `getAnalysedFrameData(): ImageData | null`: pixel data of `analysedFrame`, cached and re-extracted only on new CV results.\n\n**`viji.video.cv.faces: FaceData[]`**: `id` always present. Other fields are populated only by their source model and read `null` (or empty array for `landmarks`) otherwise — always null-check before reading.\n- `bounds: {x,y,width,height} | null` (normalized 0..1) — populated by face detection\n- `center: {x,y} | null` (normalized 0..1) — populated by face detection\n- `confidence: number | null` (0..1) — populated by face detection\n- `landmarks: {x,y,z?}[]` (empty `[]` unless face mesh enabled; 468 pts when populated)\n- `headPose: { pitch, yaw, roll } | null` (degrees) — populated by face mesh\n- `expressions: { neutral, happy, sad, angry, surprised, disgusted, fearful } | null` (0..1 each) — populated by emotion detection\n- `blendshapes | null` — populated by emotion detection; 52 ARKit coefficients (`browDownLeft`/`Right`, `browInnerUp`, `browOuterUpLeft`/`Right`, `cheekPuff`, `cheekSquintLeft`/`Right`, `eyeBlinkLeft`/`Right`, `eyeLookDown`/`In`/`Out`/`UpLeft`/`Right`, `eyeSquintLeft`/`Right`, `eyeWideLeft`/`Right`, `jawForward`/`Left`/`Open`/`Right`, `mouthClose`/`DimpleLeft`/`Right`/`FrownLeft`/`Right`/`Funnel`/`Left`/`LowerDownLeft`/`Right`/`PressLeft`/`Right`/`Pucker`/`Right`/`RollLower`/`Upper`/`ShrugLower`/`Upper`/`SmileLeft`/`Right`/`StretchLeft`/`Right`/`UpperUpLeft`/`Right`, `noseSneerLeft`/`Right`, `tongueOut`: all 0..1)\n\nIf you need bounds while only running face mesh, either also enable face detection or compute the bounding box from `face.landmarks` min/max yourself.\n\n**`viji.video.cv.hands: HandData[]`**: `id`, `handedness: 'left' | 'right'`, `confidence`, `bounds`, `landmarks: {x,y,z}[]` (21 points), `palm: {x,y,z}`, `gestures: { fist, openPalm, peace, thumbsUp, thumbsDown, pointing, iLoveYou }` (0..1 confidence each).\n\n**`viji.video.cv.pose: PoseData | null`**: `confidence`, `landmarks: {x,y,z,visibility}[]` (33 points), plus body-part arrays `face`, `torso`, `leftArm`, `rightArm`, `leftLeg`, `rightLeg`.\n\n**`viji.video.cv.segmentation: SegmentationData | null`**: `mask: Uint8Array` (each byte is `0` for background or `1` for person; length = `width * height`), `width`, `height`. Note: the shader `u_segmentationMask` sampler is sampled as a normalized `float` (0.0 = background, 1.0 = person); the JS `mask` byte values are 0/1, not 0/255.\n\n### Input\n\n**Pointer** (unified mouse and touch): `viji.pointer`\n| Member | Type | Notes |\n|---|---|---|\n| `x`, `y` | `number` | Position in pixels |\n| `deltaX`, `deltaY` | `number` | Per-frame movement |\n| `isDown` | `boolean` | Pressed or touching |\n| `wasPressed`, `wasReleased` | `boolean` | One-frame edge triggers |\n| `isInCanvas` | `boolean` | Inside canvas bounds |\n| `type` | `'mouse' \\| 'touch' \\| 'none'` | Active input type |\n\n**Mouse**: `viji.mouse`: `x`, `y`, `isInCanvas`, `isPressed`, `leftButton`, `rightButton`, `middleButton`, `deltaX`, `deltaY`, `wheelDelta`, `wheelX`, `wheelY`, `wasPressed`, `wasReleased`, `wasMoved`.\n\n**Keyboard**: `viji.keyboard`: `isPressed(key)`, `wasPressed(key)`, `wasReleased(key)`, `activeKeys: Set<string>`, `pressedThisFrame`, `releasedThisFrame`, `lastKeyPressed`, `lastKeyReleased`, `shift`, `ctrl`, `alt`, `meta`.\n\n**Touch**: `viji.touches`: `count`, `points: TouchPoint[]`, `started`, `moved`, `ended` (each a `TouchPoint[]`), `primary: TouchPoint | null`. Each `TouchPoint`: `id`, `x`, `y`, `pressure`, `radius`, `radiusX`, `radiusY`, `rotationAngle`, `force`, `isInCanvas`, `deltaX`, `deltaY`, `velocity: {x,y}`, `isNew`, `isActive`, `isEnding`.\n\n### Sensors and external devices\n\n**`viji.device`**: host device motion and orientation:\n- `motion: DeviceMotionData | null`: `acceleration: {x,y,z}` (m/s²), `accelerationIncludingGravity`, `rotationRate: {alpha,beta,gamma}` (deg/s), `interval` (ms).\n- `orientation: DeviceOrientationData | null`: `alpha` (0-360° compass), `beta` (-180..180° front-back tilt), `gamma` (-90..90° left-right tilt), `absolute`.\n\n**`viji.devices`**: `DeviceState[]`, externally connected devices. Each: `id`, `name`, `motion`, `orientation`, `video` (`VideoAPI | null`, same shape as `viji.video` but without CV), `audio` (`AudioStreamAPI | null`, lightweight; no beat or BPM).\n\n### Host-supplied streams\n\n- `viji.videoStreams: VideoAPI[]`: extra video sources from the host compositor. Same shape as `viji.video`, including a per-stream `cv` surface with the same enable verbs and result fields; `cv.analysedFrame` is populated on the main stream only. May be empty.\n- `viji.audioStreams: AudioStreamAPI[]`: extra audio sources from the host. Lightweight shape (no beat or BPM). May be empty.\n\n### External libraries\n\n```javascript\nconst THREE = await import('https://esm.sh/three@0.160.0');\nconst renderer = new THREE.WebGLRenderer({ canvas: viji.canvas, antialias: true });\nrenderer.setSize(viji.width, viji.height, false); // always pass false to skip CSS styling\n```\n\nPin library versions in the import URL. Always pass `viji.canvas` to the renderer. Always pass `false` as the third argument to Three.js `setSize`. Handle resize by comparing `viji.width` / `viji.height` against previous values inside `render()`.\n\n## Template\n\n```javascript\nconst bgColor = viji.color('#1a1a2e', { label: 'Background' });\nconst speed = viji.slider(1, { min: 0.1, max: 5, label: 'Speed' }); // implicit step → 0.01\nconst count = viji.slider(12, { min: 3, max: 30, step: 1, label: 'Count' }); // explicit step for integer counts\n\nlet angle = 0;\n\nfunction render(viji) {\n const ctx = viji.useContext('2d');\n angle += speed.value * viji.deltaTime;\n\n ctx.fillStyle = bgColor.value;\n ctx.fillRect(0, 0, viji.width, viji.height);\n\n const cx = viji.width / 2;\n const cy = viji.height / 2;\n const radius = Math.min(viji.width, viji.height) * 0.3;\n const dotSize = Math.min(viji.width, viji.height) * 0.02;\n const n = Math.floor(count.value);\n\n for (let i = 0; i < n; i++) {\n const a = angle + (i / n) * Math.PI * 2;\n const x = cx + Math.cos(a) * radius;\n const y = cy + Math.sin(a) * radius;\n const hue = (i / n) * 360;\n ctx.beginPath();\n ctx.arc(x, y, dotSize, 0, Math.PI * 2);\n ctx.fillStyle = `hsl(${hue}, 80%, 60%)`;\n ctx.fill();\n }\n}\n```\n",
|
|
9853
|
-
"p5": "# Viji API: P5 Renderer Reference\n\nP5 scenes use P5.js 1.9.4 inside a Web Worker on an `OffscreenCanvas`. P5 runs in **instance mode**: every P5 function and constant requires the `p5.` prefix. The first line of the scene must be `// @renderer p5` (2D) or `// @renderer p5 webgl` (3D / WEBGL).\n\n## Architecture\n\n- The global `viji` object exposes canvas, timing, audio, video, CV, input, sensors, parameters: identical to Native.\n- The canvas and its rendering context are managed by P5. **Do not call `createCanvas()`.** Viji creates the canvas in the mode declared by the `// @renderer` directive.\n- `viji.useContext()` is **not available** in P5 mode (the context belongs to P5).\n- Top-level code runs once. `function setup(viji, p5)` runs once for configuration. `function render(viji, p5)` runs every frame.\n- The `p5` instance passed to `setup` and `render` is the P5 instance. Use `p5.background`, `p5.fill`, `p5.circle`, `p5.PI`, etc. Unprefixed names will not resolve.\n\n## Rules\n\n1. **Always** add `// @renderer p5` (2D) or `// @renderer p5 webgl` (WEBGL) as the first line.\n2. **Always** use `render(viji, p5)` (not `draw()`) and `setup(viji, p5)` (not `setup()`).\n3. **Always** prefix every P5 function and constant with `p5.`:\n - `background(0)` -> `p5.background(0)`\n - `fill(255)` -> `p5.fill(255)`\n - `PI` -> `p5.PI`, `TWO_PI` -> `p5.TWO_PI`, `HSB` -> `p5.HSB`\n - `createVector(1, 0)` -> `p5.createVector(1, 0)`\n - `map(v, 0, 1, 0, 255)` -> `p5.map(v, 0, 1, 0, 255)`\n - `noise(x)` -> `p5.noise(x)`, `random()` -> `p5.random()`\n4. **Never** call `createCanvas()`. The canvas is created and managed by Viji.\n5. **Never** use `preload()`. Use `viji.image(null, { label })` for images, or `fetch()` inside `setup()`.\n6. **Never** use P5 event callbacks (`mousePressed`, `mouseDragged`, `mouseReleased`, `keyPressed`, `keyReleased`, `keyTyped`, `touchStarted`, `touchMoved`, `touchEnded`). Read state in `render()` via `viji.pointer`, `viji.mouse`, `viji.keyboard`, `viji.touches`. Use `wasPressed` / `wasReleased` for one-frame edges.\n7. **Never** use `loadImage()`, `loadFont()`, `loadJSON()`, `loadModel()`, `loadShader()`. Use `viji.image()` or `fetch()`.\n8. **Never** use `p5.frameRate()`, `p5.save()`, `p5.saveCanvas()`, `p5.saveFrames()`. The host controls frame rate and capture.\n9. **Never** use `createCapture()` or `createVideo()`. Use `viji.video.*`.\n10. **Never** use `p5.dom` or `p5.sound`. Use Viji parameters and `viji.audio.*`.\n11. **Never** access `window`, `document`, `Image()`, `localStorage`. `fetch()` is available.\n12. **Always** declare parameters at the top level as individual `const`s (`const speed = viji.slider(...)`), never inside `render()` or `setup()`. `label` is optional but recommended (falls back to the variable name).\n13. **Always** read parameters via `.value`. Color parameters also expose `.rgb` (matches `colorMode(RGB, 255)`) and `.hsb` (matches `colorMode(HSB, 360, 100, 100)`). Color defaults accept hex, `{ r, g, b }` (0..255), `{ h, s, b }` (0..360 / 0..100), or CSS color strings.\n14. **Always** use `viji.width` and `viji.height` for canvas dimensions. Never hardcode pixel sizes.\n15. **Always** use `viji.deltaTime` for animation:\n ```javascript\n let angle = 0;\n function render(viji, p5) { angle += speed.value * viji.deltaTime; }\n ```\n16. **Never** multiply `viji.time` by a parameter; it causes visible jumps when the parameter changes. Use a `deltaTime` accumulator. This also applies to nested multiplications; each independent speed gets its own accumulator.\n17. **Never** allocate objects, arrays, or strings inside `render()`. Pre-allocate at the top level and reuse.\n18. **Image parameters with P5:** use `.p5` (a `P5Image`) instead of `.value` when passing to `p5.image()`:\n ```javascript\n const photo = viji.image(null, { label: 'Photo' });\n function render(viji, p5) {\n if (photo.value) p5.image(photo.p5, 0, 0, viji.width, viji.height);\n }\n ```\n19. **Video drawing.** In 2D, use `p5.image(viji.video.currentFrame, ...)` or `p5.drawingContext.drawImage(...)`. In WEBGL, use `p5.image(viji.video.currentFrame, ...)` only (`p5.drawingContext` is WebGL, not Canvas 2D). **Always preserve aspect ratio** via the `videoFit` helper below.\n20. `p5.createGraphics(w, h)` is **2D only** (`createGraphics(w, h, p5.WEBGL)` is not supported). It creates an OffscreenCanvas internally.\n21. Fonts: `p5.textFont()` only with CSS generic names (`monospace`, `serif`, `sans-serif`). `loadFont()` is not available.\n22. `p5.tint()` and `p5.blendMode()` work normally.\n23. **Canvas mode is declared by the `// @renderer` directive.** Use `// @renderer p5` for 2D, `// @renderer p5 webgl` for WEBGL. Never call `createCanvas()` or `createCanvas(..., p5.WEBGL)`.\n24. In WEBGL scenes, `p5.drawingContext` is a WebGL context. Use P5 3D drawing primitives or `p5.image()` / textures for images and video.\n25. `p5.pixelDensity()` defaults to 1 in the worker. `p5.loadPixels()` and `p5.pixels[]` work in 2D scenes; WEBGL pixel readback follows standard P5.js rules.\n26. **Always** check `viji.audio.isConnected` before reading audio data.\n27. **Always** check `viji.video.isConnected && viji.video.currentFrame` before drawing video. When not connected, keep rendering the idle visual — don't draw on-canvas \"connect a camera/mic\" instructions.\n28. Enable CV by intent: always-on from module scope when CV is the scene's defining purpose, otherwise gated behind a `viji.toggle`.\n29. **Always** set `category` on input-dependent parameters (`'audio'`, `'video'`, `'interaction'`). Don't add on/off toggles to enable/disable host-gated inputs (audio, video, mouse, keyboard, touch, sensors, devices) — the host controls those. CV is the only exception (it gets a toggle when not always-on).\n30. **Always** type any function parameter that receives the `viji` instance or the `p5` instance, including `setup(viji, p5)`, `render(viji, p5)`, and any helpers that take either. Monaco's TS checker flags API misuse (wrong nesting, typo'd property names) at edit time. Scene code is transpiled via sucrase before execution, so TS annotations are stripped at runtime — safe to include. Note: the p5-instance type is the lowercase namespace `p5` (same name as the conventional parameter; TS resolves the value and the type from separate namespaces, so `p5: p5` is legal and common).\n\n ```javascript\n function setup(viji: VijiAPI, p5: p5) { ... }\n function render(viji: VijiAPI, p5: p5) { ... }\n function videoFit(viji: VijiAPI, mode: 'cover' | 'contain') { ... }\n ```\n\n## Video aspect helper\n\n```javascript\nfunction videoFit(viji, mode = 'cover') {\n const vw = viji.video.frameWidth, vh = viji.video.frameHeight;\n const w = viji.width, h = viji.height;\n if (!vw || !vh) return { x: 0, y: 0, width: 0, height: 0 };\n const scale = mode === 'cover' ? Math.max(w / vw, h / vh) : Math.min(w / vw, h / vh);\n const dw = vw * scale, dh = vh * scale;\n return { x: (w - dw) / 2, y: (h - dh) / 2, width: dw, height: dh };\n}\n\nif (viji.video.isConnected && viji.video.currentFrame) {\n const v = videoFit(viji, 'cover');\n p5.image(viji.video.currentFrame, v.x, v.y, v.width, v.height);\n}\n\n// CV bounds and landmarks are normalized 0..1 to the source frame.\n// Map them through v to align with the drawn video.\n```\n\n## P5 to Viji mapping\n\n| Standard P5.js | Viji P5 equivalent |\n|---|---|\n| `width` / `height` | `viji.width` / `viji.height` |\n| `mouseX` / `mouseY` | `viji.pointer.x` / `viji.pointer.y` (or `viji.mouse.x` / `viji.mouse.y`) |\n| `mouseIsPressed` | `viji.pointer.isDown` |\n| `mouseButton === LEFT` | `viji.mouse.leftButton` |\n| `keyIsPressed` | `viji.keyboard.activeKeys.size > 0` |\n| `keyIsDown(code)` | `viji.keyboard.isPressed('keyName')` |\n| `key` | `viji.keyboard.lastKeyPressed` |\n| `frameCount` | `viji.frameCount` (or a `viji.deltaTime` accumulator) |\n| `frameRate(n)` | Remove. Host controls frame rate. |\n| `createCanvas(w, h)` | Remove. Canvas is provided. |\n| `preload()` | Remove. Use `viji.image()` or `fetch()` in `setup()`. |\n| `loadImage(url)` | `viji.image(null, { label: 'Image' })`; pass `.p5` to `p5.image()`. |\n| `save()` / `saveCanvas()` | Remove. Host handles capture. |\n| `mousePressed()` / `mouseReleased()` callbacks | Check `viji.pointer.wasPressed` / `wasReleased` inside `render()`. |\n| `keyPressed()` / `keyReleased()` callbacks | Check `viji.keyboard.wasPressed(key)` / `wasReleased(key)` inside `render()`. |\n\n## API reference\n\nAll `viji.*` members are identical to Native (same object, same types).\n\n### Canvas and timing\n\n| Member | Type | Notes |\n|---|---|---|\n| `viji.canvas` | `OffscreenCanvas` | Managed by P5 |\n| `viji.width`, `viji.height` | `number` | Canvas dimensions |\n| `viji.time` | `number` | Seconds since scene start |\n| `viji.deltaTime` | `number` | Seconds since last frame |\n| `viji.frameCount` | `number` | Total frames rendered |\n| `viji.fps` | `number` | Target frame rate |\n\n### Parameters\n\n```javascript\nviji.slider(default, { min?, max?, step?, label, group?, category? }) // .value: number\nviji.color(default, { label, group?, category? }) // .value, .rgb, .hsb\nviji.toggle(default, { label, group?, category? }) // .value: boolean\nviji.select(default, { options, label, group?, category? }) // .value: string | number\nviji.number(default, { min?, max?, step?, label, group?, category? }) // .value: number\nviji.text(default, { label, group?, category?, maxLength? }) // .value: string\nviji.image(null, { label, group?, category? }) // .value: ImageBitmap | null, .p5: P5Image\nviji.button({ label, description?, group?, category? }) // .value: boolean (1 frame)\nviji.coordinate(default, { step?, label, group?, category? }) // .value: { x, y }, range -1..1\n// slider/number `step` defaults to a power of 10 giving ~100 positions across min..max\n// (e.g., range 0..1 → 0.01, range 0..100 → 1). Specify `step: 1` for integer counts.\n```\n\n### Audio: `viji.audio`\n\nCheck `isConnected` first. Members:\n\n`isConnected` (boolean); `volume.{current, peak, smoothed}` (0..1; `smoothed` 200ms decay); `bands.{low, lowMid, mid, highMid, high}` (0..1; ranges 20-120, 120-400, 400-1600, 1600-6000, 6000-16000 Hz) and the sibling `*Smoothed` envelopes (150ms decay); `beat.{kick, snare, hat, any}` (0..1, 300ms decay curves; peak on each detected beat); `beat.{kickSmoothed, snareSmoothed, hatSmoothed, anySmoothed}` (500ms decay envelopes); `beat.triggers.{kick, snare, hat, any}` (boolean, true for exactly one frame, OR-accumulated between frames); `beat.events: Array<{type, time, strength}>` (`type` is `'kick' | 'snare' | 'hat'`; `time` ms; cleared each frame); `beat.bpm` (`0` when no audio is connected; once audio connects it tracks the detected tempo clamped to 60..240, with `120` as a fallback before lock-on), `beat.confidence` (0..1), `beat.isLocked` (boolean); `spectral.{brightness, flatness}` (0..1); `getFrequencyData(): Uint8Array` (1024 FFT bins, 0..255); `getWaveform(): Float32Array` (2048 samples, -1..1).\n\nExternal-device audio (`viji.devices[i].audio`) and host streams (`viji.audioStreams[i]`) follow the `AudioStreamAPI` shape: `isConnected`, `volume`, `bands` (instant + smoothed siblings), `spectral`, `getFrequencyData`, `getWaveform`. No beat, BPM, triggers, or events on streams.\n\n### Video: `viji.video`\n\nCheck `isConnected && currentFrame` before drawing. Members:\n\n`isConnected` (boolean); `currentFrame` (`OffscreenCanvas | ImageBitmap | null`); `frameWidth`, `frameHeight`, `frameRate`; `getFrameData(): ImageData | null`; `cv: VideoCVAPI` (CV outputs and verbs live here, not on `viji.video` directly).\n\n### Computer Vision: `viji.video.cv`\n\nEach CV feature is independent and populates only its own subset of fields. Enable only what you need (each active feature uses a separate WebGL context for MediaPipe; 4+ on low-end hardware risks context-limit failures).\n\n```javascript\n// Verbs return Promise<void>. await is optional. Safe to call from module\n// scope (always-on CV) or per-frame inside render() gated by a viji.toggle(...)\n// (opt-in CV). Idempotent + reference-counted.\nawait viji.video.cv.enableFaceDetection(true | false); // face.bounds, face.center, face.confidence\nawait viji.video.cv.enableFaceMesh(true | false); // face.landmarks (468 pts) + face.headPose\nawait viji.video.cv.enableEmotionDetection(true | false); // face.expressions + face.blendshapes; also loads landmarker\nawait viji.video.cv.enableHandTracking(true | false); // viji.video.cv.hands[]\nawait viji.video.cv.enablePoseDetection(true | false); // viji.video.cv.pose\nawait viji.video.cv.enableBodySegmentation(true | false); // viji.video.cv.segmentation\nviji.video.cv.getActiveFeatures(); // CVFeature[]\nviji.video.cv.isProcessing(); // boolean\n```\n\nData outputs on `viji.video.cv`:\n- `analysedFrame: OffscreenCanvas | null`: the frame paired with the current CV results. `null` until the first inference lands. Use `viji.video.cv.analysedFrame ?? viji.video.currentFrame` to fall back during startup.\n- `getAnalysedFrameData(): ImageData | null`: pixel data of `analysedFrame`.\n\n**`faces: FaceData[]`**: `id` always present. Other fields populated only by their source model; otherwise `null` (`landmarks` is `[]` when empty). Always null-check.\n- `bounds: {x,y,width,height} | null` — populated by face detection\n- `center: {x,y} | null` — populated by face detection\n- `confidence: number | null` — populated by face detection\n- `landmarks: {x,y,z?}[]` (empty `[]` unless face mesh enabled)\n- `headPose: {pitch, yaw, roll} | null` — populated by face mesh\n- `expressions: {neutral, happy, sad, angry, surprised, disgusted, fearful} | null` (0..1 each) — populated by emotion detection\n- `blendshapes | null` (52 ARKit coefficients 0..1) — populated by emotion detection\n\nIf you need `bounds` while only running face mesh, either also enable face detection or compute it from `face.landmarks` min/max.\n\n**`hands: HandData[]`**: `id`, `handedness: 'left' | 'right'`, `confidence`, `bounds`, `landmarks` (21 points), `palm`, `gestures` (`fist`, `openPalm`, `peace`, `thumbsUp`, `thumbsDown`, `pointing`, `iLoveYou` 0..1).\n\n**`pose: PoseData | null`**: `confidence`, `landmarks` (33 points), body-part arrays `face`, `torso`, `leftArm`, `rightArm`, `leftLeg`, `rightLeg`.\n\n**`segmentation: SegmentationData | null`**: `mask: Uint8Array` (each byte is `0` for background or `1` for person; length = `width * height`), `width`, `height`.\n\n### Input\n\n- `viji.pointer`: `x`, `y`, `deltaX`, `deltaY`, `isDown`, `wasPressed`, `wasReleased`, `isInCanvas`, `type` (`'mouse' | 'touch' | 'none'`).\n- `viji.mouse`: `x`, `y`, `isInCanvas`, `isPressed`, `leftButton`, `rightButton`, `middleButton`, `deltaX`, `deltaY`, `wheelDelta`, `wheelX`, `wheelY`, `wasPressed`, `wasReleased`, `wasMoved`.\n- `viji.keyboard`: `isPressed(key)`, `wasPressed(key)`, `wasReleased(key)`, `activeKeys`, `pressedThisFrame`, `releasedThisFrame`, `lastKeyPressed`, `lastKeyReleased`, `shift`, `ctrl`, `alt`, `meta`.\n- `viji.touches`: `count`, `points`, `started`, `moved`, `ended`, `primary`. Each `TouchPoint`: `id`, `x`, `y`, `pressure`, `radius`, `radiusX`, `radiusY`, `rotationAngle`, `force`, `isInCanvas`, `deltaX`, `deltaY`, `velocity`, `isNew`, `isActive`, `isEnding`.\n\n### Sensors and external devices\n\n`viji.device.motion`: `acceleration {x,y,z}` (m/s²), `accelerationIncludingGravity`, `rotationRate {alpha,beta,gamma}` (deg/s), `interval` (ms).\n`viji.device.orientation`: `alpha` (0-360°), `beta` (-180..180°), `gamma` (-90..90°), `absolute`.\n\n`viji.devices: DeviceState[]`: each entry: `id`, `name`, `motion`, `orientation`, `video` (`VideoAPI | null`, no CV), `audio` (`AudioStreamAPI | null`, lightweight).\n\n### Host streams\n\n`viji.videoStreams: VideoAPI[]`: extra video sources. Same shape as `viji.video`, including a per-stream `cv` surface (same verbs and result fields; `cv.analysedFrame` is main-stream only). May be empty.\n`viji.audioStreams: AudioStreamAPI[]`: extra audio sources. May be empty. Lightweight shape (no beat / BPM).\n\n## Template\n\n```javascript\n// @renderer p5\n\nconst bgColor = viji.color('#1a1a2e', { label: 'Background' });\nconst speed = viji.slider(1, { min: 0.1, max: 5, label: 'Speed' }); // implicit step → 0.01\nconst count = viji.slider(8, { min: 3, max: 30, step: 1, label: 'Count' }); // explicit step for integer counts\n\nlet angle = 0;\n\nfunction setup(viji, p5) {\n p5.colorMode(p5.HSB, 360, 100, 100);\n}\n\nfunction render(viji, p5) {\n angle += speed.value * viji.deltaTime;\n p5.background(bgColor.value);\n\n const cx = viji.width / 2;\n const cy = viji.height / 2;\n const radius = p5.min(viji.width, viji.height) * 0.3;\n const dotSize = p5.min(viji.width, viji.height) * 0.04;\n const n = p5.floor(count.value);\n\n p5.noStroke();\n for (let i = 0; i < n; i++) {\n const a = angle + (i / n) * p5.TWO_PI;\n const x = cx + p5.cos(a) * radius;\n const y = cy + p5.sin(a) * radius;\n p5.fill((i / n) * 360, 80, 90);\n p5.circle(x, y, dotSize);\n }\n}\n```\n",
|
|
9852
|
+
"native": "# Viji API: Native Renderer Reference\n\nNative scenes run JavaScript on an `OffscreenCanvas` in a Web Worker, with full access to Canvas 2D, WebGL, and WebGL2 contexts. External libraries load via `await import()`. Top-level code runs once; a `render(viji)` function runs every frame.\n\n## Architecture\n\n- The global `viji` object exposes canvas, timing, audio, video, CV, input, sensors, parameters.\n- Call `viji.useContext('2d' | 'webgl' | 'webgl2')` once at the top of `render()` (or top-level) to obtain a rendering context. After the first call, `viji.ctx` / `viji.gl` shortcuts are populated.\n- **Pick one context type for the entire scene.** Calling `useContext` with a different type after the first call returns `null`.\n- There is **no `setup()` function** in Native. All initialization goes at the top level (which supports `await` for dynamic imports).\n- The DOM is unavailable. `fetch()` and `await import()` are available.\n\n## Rules\n\n1. **Never** access `window`, `document`, `Image()`, `localStorage`, or any DOM API. `fetch()` and `await import()` are available.\n2. **Always** declare parameters at the top level as individual `const`s (`const speed = viji.slider(...)`), never inside `render()`. `label` is optional but recommended (falls back to the variable name).\n3. **Always** read parameters via `.value`. Color parameters also expose `.rgb` (`{ r, g, b }` in 0..255) and `.hsb` (`{ h, s, b }` with `h` in 0..360, `s` / `b` in 0..100). Color defaults accept hex (`'#ff6600'`, `'#f60'`), `{ r, g, b }` (0..255), `{ h, s, b }` (0..360 / 0..100), or CSS `'rgb(...)'` / `'hsl(...)'` strings.\n4. **Always** use `viji.width` and `viji.height` for canvas dimensions. Never hardcode pixel sizes.\n5. **Always** use `viji.deltaTime` for animation. Use `viji.time` only for constant-speed oscillations (`Math.sin(viji.time * 2.0)`). For anything driven by a parameter, use a `deltaTime` accumulator.\n6. **Never** multiply `viji.time` by a parameter; it causes visible jumps when the parameter changes. Use a `deltaTime` accumulator at the top level. This also applies to nested multiplications: each independent speed gets its own accumulator.\n\n ```javascript\n // WRONG\n const t = viji.time * speed.value;\n const rot = phase * rotSpeed.value;\n\n // RIGHT\n let phase = 0, rotPhase = 0;\n phase += speed.value * viji.deltaTime;\n rotPhase += speed.value * rotSpeed.value * viji.deltaTime;\n ```\n7. **Never** allocate objects, arrays, or strings inside `render()`. Pre-allocate at the top level and reuse.\n8. **Always** call `viji.useContext()` to get a context. Pick one type and use it for the entire scene.\n9. **Always** check `viji.audio.isConnected` before reading audio data. Check `viji.video.isConnected && viji.video.currentFrame` before drawing video. When not connected, keep rendering the idle visual — don't draw on-canvas \"connect a camera/mic\" instructions.\n10. Enable CV by intent: always-on from module scope when CV is the scene's defining purpose, otherwise gated behind a `viji.toggle` so the user opts into the cost.\n11. **Always** set `category` on input-dependent parameters (`'audio'`, `'video'`, `'interaction'`). Don't add on/off toggles to enable/disable host-gated inputs (audio, video, mouse, keyboard, touch, sensors, devices) — the host controls those. CV is the only exception (it gets a toggle when not always-on).\n12. **Always** type any function parameter that receives the `viji` instance, including `render(viji)` and any helpers that take `viji`. Monaco's TS checker flags API misuse (wrong nesting, typo'd property names) at edit time so the error can be corrected before runtime. Scene code is transpiled via sucrase before execution (`transforms: ['typescript']`), so TS annotations are stripped at runtime — they are safe to include.\n\n ```javascript\n function render(viji: VijiAPI) { ... }\n function applyGlow(viji: VijiAPI, intensity: number) { ... }\n ```\n13. All Viji types are ambient globals — `VijiAPI`, the parameter and config types (`SliderParameter`, `SliderConfig`, ...), input and CV types (`TouchPoint`, `FaceData`, ...). Annotate with them directly; never import, alias, or re-derive them (no `ReturnType<typeof viji.slider>` — the named type exists). For the exact type of any `viji` member, fetch the `native-api-reference` docs page instead of guessing.\n\n## API reference\n\n### Canvas and context\n\n| Member | Type | Description |\n|---|---|---|\n| `viji.canvas` | `OffscreenCanvas` | The canvas |\n| `viji.useContext('2d')` | `OffscreenCanvasRenderingContext2D` | Acquire 2D context |\n| `viji.useContext('webgl')` | `WebGLRenderingContext` | Acquire WebGL 1 |\n| `viji.useContext('webgl2')` | `WebGL2RenderingContext` | Acquire WebGL 2 |\n| `viji.ctx` | `OffscreenCanvasRenderingContext2D` | Shortcut after `useContext('2d')` |\n| `viji.gl` | `WebGLRenderingContext \\| WebGL2RenderingContext` | Shortcut after WebGL context acquired |\n| `viji.width`, `viji.height` | `number` | Current canvas dimensions in pixels |\n\n### Timing\n\n| Member | Type | Description |\n|---|---|---|\n| `viji.time` | `number` | Seconds since scene start |\n| `viji.deltaTime` | `number` | Seconds since last frame |\n| `viji.frameCount` | `number` | Total frames rendered |\n| `viji.fps` | `number` | Target frame rate (host-controlled) |\n\n### Parameters\n\nDeclare at top level. All accept `{ label, description?, group?, category? }`. Category values: `'audio'`, `'video'`, `'interaction'`, `'general'` (default).\n\n```javascript\nviji.slider(default, { min?, max?, step?, label, group?, category? }) // .value: number\nviji.color(default, { label, group?, category? }) // .value: '#rrggbb', .rgb: {r,g,b} 0..255, .hsb: {h:0..360, s/b:0..100}\nviji.toggle(default, { label, group?, category? }) // .value: boolean\nviji.select(default, { options, label, group?, category? }) // .value: string | number\nviji.number(default, { min?, max?, step?, label, group?, category? }) // .value: number\nviji.text(default, { label, group?, category?, maxLength? }) // .value: string\nviji.image(null, { label, group?, category? }) // .value: ImageBitmap | null\nviji.button({ label, description?, group?, category? }) // .value: boolean (true for 1 frame)\nviji.coordinate(default, { step?, label, group?, category? }) // .value: { x, y }, range -1..1\n// slider/number `step` defaults to a power of 10 giving ~100 positions across min..max\n// (e.g., range 0..1 → 0.01, range 0..100 → 1). Specify `step: 1` for integer counts.\n```\n\n### Audio: `viji.audio`\n\nCheck `isConnected` first.\n\n| Member | Type | Notes |\n|---|---|---|\n| `isConnected` | `boolean` | Audio source active |\n| `volume.current`, `volume.peak`, `volume.smoothed` | `number` 0..1 | `smoothed` = 200ms decay envelope of `current` |\n| `bands.low`, `lowMid`, `mid`, `highMid`, `high` | `number` 0..1 | Instant band energies (20-120, 120-400, 400-1600, 1600-6000, 6000-16000 Hz) |\n| `bands.lowSmoothed`, `lowMidSmoothed`, `midSmoothed`, `highMidSmoothed`, `highSmoothed` | `number` 0..1 | 150ms decay envelope siblings (not nested) |\n| `beat.kick`, `snare`, `hat`, `any` | `number` 0..1 | Beat energy curves with a 300ms decay; peak on each detected beat then fall off |\n| `beat.kickSmoothed`, `snareSmoothed`, `hatSmoothed`, `anySmoothed` | `number` 0..1 | Smoother 500ms decay envelopes; use for ambient pulses |\n| `beat.triggers.kick`, `snare`, `hat`, `any` | `boolean` | True for exactly one frame on the matching beat, then auto-resets. OR-accumulated between frames so no beat is lost |\n| `beat.events` | `Array<{type, time, strength}>` | All beats detected since the last frame; `type` is `'kick' \\| 'snare' \\| 'hat'` (never `'any'`); `time` in milliseconds; cleared each frame |\n| `beat.bpm`, `beat.confidence`, `beat.isLocked` | `number`, `number`, `boolean` | `bpm` is `0` when no audio is connected; once audio connects it tracks the detected tempo (clamped to 60..240) with `120` as a fallback before lock-on. `confidence` in 0..1. `isLocked` is `true` on stable tempo lock |\n| `spectral.brightness`, `spectral.flatness` | `number` 0..1 | Spectral centroid; spectral flatness |\n| `getFrequencyData()` | `Uint8Array` | Raw FFT bins 0..255 |\n| `getWaveform()` | `Float32Array` | Time-domain waveform -1..1 |\n\nExternal-device audio (`viji.devices[i].audio`) and host-supplied audio streams (`viji.audioStreams[i]`) use the `AudioStreamAPI` shape: `isConnected`, `volume.{current,peak,smoothed}`, `bands.{low...high}` plus each `*Smoothed` sibling, `spectral.{brightness,flatness}`, `getFrequencyData()`, `getWaveform()`. No `beat`, BPM, triggers, or events on streams: those exist only on the main `viji.audio`.\n\n### Video: `viji.video`\n\nCheck `isConnected && currentFrame` before drawing.\n\n| Member | Type | Notes |\n|---|---|---|\n| `isConnected` | `boolean` | Video source active |\n| `currentFrame` | `OffscreenCanvas \\| ImageBitmap \\| null` | Most recent frame |\n| `frameWidth`, `frameHeight` | `number` | Source frame size |\n| `frameRate` | `number` | Source frame rate |\n| `getFrameData()` | `ImageData \\| null` | Pixel data of `currentFrame` |\n| `cv` | `VideoCVAPI` | Computer-vision surface: see below |\n\nCV data outputs (`analysedFrame`, `getAnalysedFrameData()`, `faces`, `hands`, `pose`, `segmentation`) and CV verbs (`enableFaceDetection`, etc.) all live on `viji.video.cv`, not on `viji.video` directly.\n\n**Aspect ratio.** Camera frames almost never match the canvas aspect. Drawing to `(0, 0, viji.width, viji.height)` stretches video and misaligns CV bounds. Use this helper at module scope:\n\n```javascript\nfunction videoFit(viji, mode = 'cover') {\n const vw = viji.video.frameWidth, vh = viji.video.frameHeight;\n const w = viji.width, h = viji.height;\n if (!vw || !vh) return { x: 0, y: 0, width: 0, height: 0 };\n const scale = mode === 'cover' ? Math.max(w / vw, h / vh) : Math.min(w / vw, h / vh);\n const dw = vw * scale, dh = vh * scale;\n return { x: (w - dw) / 2, y: (h - dh) / 2, width: dw, height: dh };\n}\n\nconst v = videoFit(viji); // 'cover' or 'contain'\nctx.drawImage(viji.video.currentFrame, v.x, v.y, v.width, v.height);\n\n// CV coords are normalized 0..1 to the source frame. Map through v to align with the fitted video:\nviji.video.cv.faces.forEach(face => {\n const bx = v.x + face.bounds.x * v.width;\n const by = v.y + face.bounds.y * v.height;\n const bw = face.bounds.width * v.width;\n const bh = face.bounds.height * v.height;\n ctx.strokeRect(bx, by, bw, bh);\n});\n```\n\nDefault to `'cover'` for live cameras. Use `'contain'` for CV-overlay scenes where bounding boxes near frame edges must stay visible. `viji.video.currentFrame` is the right default for displayed video; reach for `viji.video.cv.analysedFrame` only when sampling pixels at CV-derived positions (segmentation compositing, face-mesh texturing, landmark-anchored color sampling). The common fallback pattern is `viji.video.cv.analysedFrame ?? viji.video.currentFrame` during the brief window before the first CV inference lands.\n\n### Computer Vision: `viji.video.cv`\n\nEach CV feature is independent and populates only its own subset of fields. Enable only what you need (each active feature consumes a separate WebGL context for MediaPipe; 4+ on low-end hardware risks context-limit failures).\n\n```javascript\n// Verbs return Promise<void>. await is optional — without it, the model loads\n// asynchronously while render runs and data fields populate when ready.\n// Safe to call from module scope (always-on CV) or per-frame inside render()\n// gated by a viji.toggle(...) (opt-in CV). Idempotent + reference-counted.\nawait viji.video.cv.enableFaceDetection(true | false); // populates face.bounds, face.center, face.confidence\nawait viji.video.cv.enableFaceMesh(true | false); // populates face.landmarks (468 pts) + face.headPose\nawait viji.video.cv.enableEmotionDetection(true | false); // populates face.expressions + face.blendshapes; also loads landmarker (face.landmarks + face.headPose populated)\nawait viji.video.cv.enableHandTracking(true | false); // populates viji.video.cv.hands[]\nawait viji.video.cv.enablePoseDetection(true | false); // populates viji.video.cv.pose\nawait viji.video.cv.enableBodySegmentation(true | false); // populates viji.video.cv.segmentation\nviji.video.cv.getActiveFeatures(); // CVFeature[]\nviji.video.cv.isProcessing(); // boolean\n```\n\nData outputs on `viji.video.cv`:\n- `analysedFrame: OffscreenCanvas | null`: the exact frame paired with the current CV results. `null` until the first inference lands after a feature is enabled. Use the pattern `viji.video.cv.analysedFrame ?? viji.video.currentFrame` to fall back during the startup window.\n- `getAnalysedFrameData(): ImageData | null`: pixel data of `analysedFrame`, cached and re-extracted only on new CV results.\n\n**`viji.video.cv.faces: FaceData[]`**: `id` always present. Other fields are populated only by their source model and read `null` (or empty array for `landmarks`) otherwise — always null-check before reading.\n- `bounds: {x,y,width,height} | null` (normalized 0..1) — populated by face detection\n- `center: {x,y} | null` (normalized 0..1) — populated by face detection\n- `confidence: number | null` (0..1) — populated by face detection\n- `landmarks: {x,y,z?}[]` (empty `[]` unless face mesh enabled; 468 pts when populated)\n- `headPose: { pitch, yaw, roll } | null` (degrees) — populated by face mesh\n- `expressions: { neutral, happy, sad, angry, surprised, disgusted, fearful } | null` (0..1 each) — populated by emotion detection\n- `blendshapes | null` — populated by emotion detection; 52 ARKit coefficients (`browDownLeft`/`Right`, `browInnerUp`, `browOuterUpLeft`/`Right`, `cheekPuff`, `cheekSquintLeft`/`Right`, `eyeBlinkLeft`/`Right`, `eyeLookDown`/`In`/`Out`/`UpLeft`/`Right`, `eyeSquintLeft`/`Right`, `eyeWideLeft`/`Right`, `jawForward`/`Left`/`Open`/`Right`, `mouthClose`/`DimpleLeft`/`Right`/`FrownLeft`/`Right`/`Funnel`/`Left`/`LowerDownLeft`/`Right`/`PressLeft`/`Right`/`Pucker`/`Right`/`RollLower`/`Upper`/`ShrugLower`/`Upper`/`SmileLeft`/`Right`/`StretchLeft`/`Right`/`UpperUpLeft`/`Right`, `noseSneerLeft`/`Right`, `tongueOut`: all 0..1)\n\nIf you need bounds while only running face mesh, either also enable face detection or compute the bounding box from `face.landmarks` min/max yourself.\n\n**`viji.video.cv.hands: HandData[]`**: `id`, `handedness: 'left' | 'right'`, `confidence`, `bounds`, `landmarks: {x,y,z}[]` (21 points), `palm: {x,y,z}`, `gestures: { fist, openPalm, peace, thumbsUp, thumbsDown, pointing, iLoveYou }` (0..1 confidence each).\n\n**`viji.video.cv.pose: PoseData | null`**: `confidence`, `landmarks: {x,y,z,visibility}[]` (33 points), plus body-part arrays `face`, `torso`, `leftArm`, `rightArm`, `leftLeg`, `rightLeg`.\n\n**`viji.video.cv.segmentation: SegmentationData | null`**: `mask: Uint8Array` (each byte is `0` for background or `1` for person; length = `width * height`), `width`, `height`. Note: the shader `u_segmentationMask` sampler is sampled as a normalized `float` (0.0 = background, 1.0 = person); the JS `mask` byte values are 0/1, not 0/255.\n\n### Input\n\n**Pointer** (unified mouse and touch): `viji.pointer`\n| Member | Type | Notes |\n|---|---|---|\n| `x`, `y` | `number` | Position in pixels |\n| `deltaX`, `deltaY` | `number` | Per-frame movement |\n| `isDown` | `boolean` | Pressed or touching |\n| `wasPressed`, `wasReleased` | `boolean` | One-frame edge triggers |\n| `isInCanvas` | `boolean` | Inside canvas bounds |\n| `type` | `'mouse' \\| 'touch' \\| 'none'` | Active input type |\n\n**Mouse**: `viji.mouse`: `x`, `y`, `isInCanvas`, `isPressed`, `leftButton`, `rightButton`, `middleButton`, `deltaX`, `deltaY`, `wheelDelta`, `wheelX`, `wheelY`, `wasPressed`, `wasReleased`, `wasMoved`.\n\n**Keyboard**: `viji.keyboard`: `isPressed(key)`, `wasPressed(key)`, `wasReleased(key)`, `activeKeys: Set<string>`, `pressedThisFrame`, `releasedThisFrame`, `lastKeyPressed`, `lastKeyReleased`, `shift`, `ctrl`, `alt`, `meta`.\n\n**Touch**: `viji.touches`: `count`, `points: TouchPoint[]`, `started`, `moved`, `ended` (each a `TouchPoint[]`), `primary: TouchPoint | null`. Each `TouchPoint`: `id`, `x`, `y`, `pressure`, `radius`, `radiusX`, `radiusY`, `rotationAngle`, `force`, `isInCanvas`, `deltaX`, `deltaY`, `velocity: {x,y}`, `isNew`, `isActive`, `isEnding`.\n\n### Sensors and external devices\n\n**`viji.device`**: host device motion and orientation:\n- `motion: DeviceMotionData | null`: `acceleration: {x,y,z}` (m/s²), `accelerationIncludingGravity`, `rotationRate: {alpha,beta,gamma}` (deg/s), `interval` (ms).\n- `orientation: DeviceOrientationData | null`: `alpha` (0-360° compass), `beta` (-180..180° front-back tilt), `gamma` (-90..90° left-right tilt), `absolute`.\n\n**`viji.devices`**: `DeviceState[]`, externally connected devices. Each: `id`, `name`, `motion`, `orientation`, `video` (`VideoAPI | null`, same shape as `viji.video` but without CV), `audio` (`AudioStreamAPI | null`, lightweight; no beat or BPM).\n\n### Host-supplied streams\n\n- `viji.videoStreams: VideoAPI[]`: extra video sources from the host compositor. Same shape as `viji.video`, including a per-stream `cv` surface with the same enable verbs and result fields; `cv.analysedFrame` is populated on the main stream only. May be empty.\n- `viji.audioStreams: AudioStreamAPI[]`: extra audio sources from the host. Lightweight shape (no beat or BPM). May be empty.\n\n### External libraries\n\n```javascript\nconst THREE = await import('https://esm.sh/three@0.160.0');\nconst renderer = new THREE.WebGLRenderer({ canvas: viji.canvas, antialias: true });\nrenderer.setSize(viji.width, viji.height, false); // always pass false to skip CSS styling\n```\n\nPin library versions in the import URL. Always pass `viji.canvas` to the renderer. Always pass `false` as the third argument to Three.js `setSize`. Handle resize by comparing `viji.width` / `viji.height` against previous values inside `render()`.\n\n## Template\n\n```javascript\nconst bgColor = viji.color('#1a1a2e', { label: 'Background' });\nconst speed = viji.slider(1, { min: 0.1, max: 5, label: 'Speed' }); // implicit step → 0.01\nconst count = viji.slider(12, { min: 3, max: 30, step: 1, label: 'Count' }); // explicit step for integer counts\n\nlet angle = 0;\n\nfunction render(viji) {\n const ctx = viji.useContext('2d');\n angle += speed.value * viji.deltaTime;\n\n ctx.fillStyle = bgColor.value;\n ctx.fillRect(0, 0, viji.width, viji.height);\n\n const cx = viji.width / 2;\n const cy = viji.height / 2;\n const radius = Math.min(viji.width, viji.height) * 0.3;\n const dotSize = Math.min(viji.width, viji.height) * 0.02;\n const n = Math.floor(count.value);\n\n for (let i = 0; i < n; i++) {\n const a = angle + (i / n) * Math.PI * 2;\n const x = cx + Math.cos(a) * radius;\n const y = cy + Math.sin(a) * radius;\n const hue = (i / n) * 360;\n ctx.beginPath();\n ctx.arc(x, y, dotSize, 0, Math.PI * 2);\n ctx.fillStyle = `hsl(${hue}, 80%, 60%)`;\n ctx.fill();\n }\n}\n```\n",
|
|
9853
|
+
"p5": "# Viji API: P5 Renderer Reference\n\nP5 scenes use P5.js 1.9.4 inside a Web Worker on an `OffscreenCanvas`. P5 runs in **instance mode**: every P5 function and constant requires the `p5.` prefix. The first line of the scene must be `// @renderer p5` (2D) or `// @renderer p5 webgl` (3D / WEBGL).\n\n## Architecture\n\n- The global `viji` object exposes canvas, timing, audio, video, CV, input, sensors, parameters: identical to Native.\n- The canvas and its rendering context are managed by P5. **Do not call `createCanvas()`.** Viji creates the canvas in the mode declared by the `// @renderer` directive.\n- `viji.useContext()` is **not available** in P5 mode (the context belongs to P5).\n- Top-level code runs once. `function setup(viji, p5)` runs once for configuration. `function render(viji, p5)` runs every frame.\n- The `p5` instance passed to `setup` and `render` is the P5 instance. Use `p5.background`, `p5.fill`, `p5.circle`, `p5.PI`, etc. Unprefixed names will not resolve.\n\n## Rules\n\n1. **Always** add `// @renderer p5` (2D) or `// @renderer p5 webgl` (WEBGL) as the first line.\n2. **Always** use `render(viji, p5)` (not `draw()`) and `setup(viji, p5)` (not `setup()`).\n3. **Always** prefix every P5 function and constant with `p5.`:\n - `background(0)` -> `p5.background(0)`\n - `fill(255)` -> `p5.fill(255)`\n - `PI` -> `p5.PI`, `TWO_PI` -> `p5.TWO_PI`, `HSB` -> `p5.HSB`\n - `createVector(1, 0)` -> `p5.createVector(1, 0)`\n - `map(v, 0, 1, 0, 255)` -> `p5.map(v, 0, 1, 0, 255)`\n - `noise(x)` -> `p5.noise(x)`, `random()` -> `p5.random()`\n4. **Never** call `createCanvas()`. The canvas is created and managed by Viji.\n5. **Never** use `preload()`. Use `viji.image(null, { label })` for images, or `fetch()` inside `setup()`.\n6. **Never** use P5 event callbacks (`mousePressed`, `mouseDragged`, `mouseReleased`, `keyPressed`, `keyReleased`, `keyTyped`, `touchStarted`, `touchMoved`, `touchEnded`). Read state in `render()` via `viji.pointer`, `viji.mouse`, `viji.keyboard`, `viji.touches`. Use `wasPressed` / `wasReleased` for one-frame edges.\n7. **Never** use `loadImage()`, `loadFont()`, `loadJSON()`, `loadModel()`, `loadShader()`. Use `viji.image()` or `fetch()`.\n8. **Never** use `p5.frameRate()`, `p5.save()`, `p5.saveCanvas()`, `p5.saveFrames()`. The host controls frame rate and capture.\n9. **Never** use `createCapture()` or `createVideo()`. Use `viji.video.*`.\n10. **Never** use `p5.dom` or `p5.sound`. Use Viji parameters and `viji.audio.*`.\n11. **Never** access `window`, `document`, `Image()`, `localStorage`. `fetch()` is available.\n12. **Always** declare parameters at the top level as individual `const`s (`const speed = viji.slider(...)`), never inside `render()` or `setup()`. `label` is optional but recommended (falls back to the variable name).\n13. **Always** read parameters via `.value`. Color parameters also expose `.rgb` (matches `colorMode(RGB, 255)`) and `.hsb` (matches `colorMode(HSB, 360, 100, 100)`). Color defaults accept hex, `{ r, g, b }` (0..255), `{ h, s, b }` (0..360 / 0..100), or CSS color strings.\n14. **Always** use `viji.width` and `viji.height` for canvas dimensions. Never hardcode pixel sizes.\n15. **Always** use `viji.deltaTime` for animation:\n ```javascript\n let angle = 0;\n function render(viji, p5) { angle += speed.value * viji.deltaTime; }\n ```\n16. **Never** multiply `viji.time` by a parameter; it causes visible jumps when the parameter changes. Use a `deltaTime` accumulator. This also applies to nested multiplications; each independent speed gets its own accumulator.\n17. **Never** allocate objects, arrays, or strings inside `render()`. Pre-allocate at the top level and reuse.\n18. **Image parameters with P5:** use `.p5` (a `P5Image`) instead of `.value` when passing to `p5.image()`:\n ```javascript\n const photo = viji.image(null, { label: 'Photo' });\n function render(viji, p5) {\n if (photo.value) p5.image(photo.p5, 0, 0, viji.width, viji.height);\n }\n ```\n19. **Video drawing.** In 2D, use `p5.image(viji.video.currentFrame, ...)` or `p5.drawingContext.drawImage(...)`. In WEBGL, use `p5.image(viji.video.currentFrame, ...)` only (`p5.drawingContext` is WebGL, not Canvas 2D). **Always preserve aspect ratio** via the `videoFit` helper below.\n20. `p5.createGraphics(w, h)` is **2D only** (`createGraphics(w, h, p5.WEBGL)` is not supported). It creates an OffscreenCanvas internally.\n21. Fonts: `p5.textFont()` only with CSS generic names (`monospace`, `serif`, `sans-serif`). `loadFont()` is not available.\n22. `p5.tint()` and `p5.blendMode()` work normally.\n23. **Canvas mode is declared by the `// @renderer` directive.** Use `// @renderer p5` for 2D, `// @renderer p5 webgl` for WEBGL. Never call `createCanvas()` or `createCanvas(..., p5.WEBGL)`.\n24. In WEBGL scenes, `p5.drawingContext` is a WebGL context. Use P5 3D drawing primitives or `p5.image()` / textures for images and video.\n25. `p5.pixelDensity()` defaults to 1 in the worker. `p5.loadPixels()` and `p5.pixels[]` work in 2D scenes; WEBGL pixel readback follows standard P5.js rules.\n26. **Always** check `viji.audio.isConnected` before reading audio data.\n27. **Always** check `viji.video.isConnected && viji.video.currentFrame` before drawing video. When not connected, keep rendering the idle visual — don't draw on-canvas \"connect a camera/mic\" instructions.\n28. Enable CV by intent: always-on from module scope when CV is the scene's defining purpose, otherwise gated behind a `viji.toggle`.\n29. **Always** set `category` on input-dependent parameters (`'audio'`, `'video'`, `'interaction'`). Don't add on/off toggles to enable/disable host-gated inputs (audio, video, mouse, keyboard, touch, sensors, devices) — the host controls those. CV is the only exception (it gets a toggle when not always-on).\n30. **Always** type any function parameter that receives the `viji` instance or the `p5` instance, including `setup(viji, p5)`, `render(viji, p5)`, and any helpers that take either. Monaco's TS checker flags API misuse (wrong nesting, typo'd property names) at edit time. Scene code is transpiled via sucrase before execution, so TS annotations are stripped at runtime — safe to include. Note: the p5-instance type is the lowercase namespace `p5` (same name as the conventional parameter; TS resolves the value and the type from separate namespaces, so `p5: p5` is legal and common).\n\n ```javascript\n function setup(viji: VijiAPI, p5: p5) { ... }\n function render(viji: VijiAPI, p5: p5) { ... }\n function videoFit(viji: VijiAPI, mode: 'cover' | 'contain') { ... }\n ```\n31. All Viji types are ambient globals — `VijiAPI`, the parameter and config types (`SliderParameter`, `SliderConfig`, ...), input and CV types (`TouchPoint`, `FaceData`, ...). Annotate with them directly; never import, alias, or re-derive them (no `ReturnType<typeof viji.slider>` — the named type exists). For the exact type of any `viji` member, fetch the `p5-api-reference` docs page instead of guessing.\n\n## Video aspect helper\n\n```javascript\nfunction videoFit(viji, mode = 'cover') {\n const vw = viji.video.frameWidth, vh = viji.video.frameHeight;\n const w = viji.width, h = viji.height;\n if (!vw || !vh) return { x: 0, y: 0, width: 0, height: 0 };\n const scale = mode === 'cover' ? Math.max(w / vw, h / vh) : Math.min(w / vw, h / vh);\n const dw = vw * scale, dh = vh * scale;\n return { x: (w - dw) / 2, y: (h - dh) / 2, width: dw, height: dh };\n}\n\nif (viji.video.isConnected && viji.video.currentFrame) {\n const v = videoFit(viji, 'cover');\n p5.image(viji.video.currentFrame, v.x, v.y, v.width, v.height);\n}\n\n// CV bounds and landmarks are normalized 0..1 to the source frame.\n// Map them through v to align with the drawn video.\n```\n\n## P5 to Viji mapping\n\n| Standard P5.js | Viji P5 equivalent |\n|---|---|\n| `width` / `height` | `viji.width` / `viji.height` |\n| `mouseX` / `mouseY` | `viji.pointer.x` / `viji.pointer.y` (or `viji.mouse.x` / `viji.mouse.y`) |\n| `mouseIsPressed` | `viji.pointer.isDown` |\n| `mouseButton === LEFT` | `viji.mouse.leftButton` |\n| `keyIsPressed` | `viji.keyboard.activeKeys.size > 0` |\n| `keyIsDown(code)` | `viji.keyboard.isPressed('keyName')` |\n| `key` | `viji.keyboard.lastKeyPressed` |\n| `frameCount` | `viji.frameCount` (or a `viji.deltaTime` accumulator) |\n| `frameRate(n)` | Remove. Host controls frame rate. |\n| `createCanvas(w, h)` | Remove. Canvas is provided. |\n| `preload()` | Remove. Use `viji.image()` or `fetch()` in `setup()`. |\n| `loadImage(url)` | `viji.image(null, { label: 'Image' })`; pass `.p5` to `p5.image()`. |\n| `save()` / `saveCanvas()` | Remove. Host handles capture. |\n| `mousePressed()` / `mouseReleased()` callbacks | Check `viji.pointer.wasPressed` / `wasReleased` inside `render()`. |\n| `keyPressed()` / `keyReleased()` callbacks | Check `viji.keyboard.wasPressed(key)` / `wasReleased(key)` inside `render()`. |\n\n## API reference\n\nAll `viji.*` members are identical to Native (same object, same types).\n\n### Canvas and timing\n\n| Member | Type | Notes |\n|---|---|---|\n| `viji.canvas` | `OffscreenCanvas` | Managed by P5 |\n| `viji.width`, `viji.height` | `number` | Canvas dimensions |\n| `viji.time` | `number` | Seconds since scene start |\n| `viji.deltaTime` | `number` | Seconds since last frame |\n| `viji.frameCount` | `number` | Total frames rendered |\n| `viji.fps` | `number` | Target frame rate |\n\n### Parameters\n\n```javascript\nviji.slider(default, { min?, max?, step?, label, group?, category? }) // .value: number\nviji.color(default, { label, group?, category? }) // .value, .rgb, .hsb\nviji.toggle(default, { label, group?, category? }) // .value: boolean\nviji.select(default, { options, label, group?, category? }) // .value: string | number\nviji.number(default, { min?, max?, step?, label, group?, category? }) // .value: number\nviji.text(default, { label, group?, category?, maxLength? }) // .value: string\nviji.image(null, { label, group?, category? }) // .value: ImageBitmap | null, .p5: P5Image\nviji.button({ label, description?, group?, category? }) // .value: boolean (1 frame)\nviji.coordinate(default, { step?, label, group?, category? }) // .value: { x, y }, range -1..1\n// slider/number `step` defaults to a power of 10 giving ~100 positions across min..max\n// (e.g., range 0..1 → 0.01, range 0..100 → 1). Specify `step: 1` for integer counts.\n```\n\n### Audio: `viji.audio`\n\nCheck `isConnected` first. Members:\n\n`isConnected` (boolean); `volume.{current, peak, smoothed}` (0..1; `smoothed` 200ms decay); `bands.{low, lowMid, mid, highMid, high}` (0..1; ranges 20-120, 120-400, 400-1600, 1600-6000, 6000-16000 Hz) and the sibling `*Smoothed` envelopes (150ms decay); `beat.{kick, snare, hat, any}` (0..1, 300ms decay curves; peak on each detected beat); `beat.{kickSmoothed, snareSmoothed, hatSmoothed, anySmoothed}` (500ms decay envelopes); `beat.triggers.{kick, snare, hat, any}` (boolean, true for exactly one frame, OR-accumulated between frames); `beat.events: Array<{type, time, strength}>` (`type` is `'kick' | 'snare' | 'hat'`; `time` ms; cleared each frame); `beat.bpm` (`0` when no audio is connected; once audio connects it tracks the detected tempo clamped to 60..240, with `120` as a fallback before lock-on), `beat.confidence` (0..1), `beat.isLocked` (boolean); `spectral.{brightness, flatness}` (0..1); `getFrequencyData(): Uint8Array` (1024 FFT bins, 0..255); `getWaveform(): Float32Array` (2048 samples, -1..1).\n\nExternal-device audio (`viji.devices[i].audio`) and host streams (`viji.audioStreams[i]`) follow the `AudioStreamAPI` shape: `isConnected`, `volume`, `bands` (instant + smoothed siblings), `spectral`, `getFrequencyData`, `getWaveform`. No beat, BPM, triggers, or events on streams.\n\n### Video: `viji.video`\n\nCheck `isConnected && currentFrame` before drawing. Members:\n\n`isConnected` (boolean); `currentFrame` (`OffscreenCanvas | ImageBitmap | null`); `frameWidth`, `frameHeight`, `frameRate`; `getFrameData(): ImageData | null`; `cv: VideoCVAPI` (CV outputs and verbs live here, not on `viji.video` directly).\n\n### Computer Vision: `viji.video.cv`\n\nEach CV feature is independent and populates only its own subset of fields. Enable only what you need (each active feature uses a separate WebGL context for MediaPipe; 4+ on low-end hardware risks context-limit failures).\n\n```javascript\n// Verbs return Promise<void>. await is optional. Safe to call from module\n// scope (always-on CV) or per-frame inside render() gated by a viji.toggle(...)\n// (opt-in CV). Idempotent + reference-counted.\nawait viji.video.cv.enableFaceDetection(true | false); // face.bounds, face.center, face.confidence\nawait viji.video.cv.enableFaceMesh(true | false); // face.landmarks (468 pts) + face.headPose\nawait viji.video.cv.enableEmotionDetection(true | false); // face.expressions + face.blendshapes; also loads landmarker\nawait viji.video.cv.enableHandTracking(true | false); // viji.video.cv.hands[]\nawait viji.video.cv.enablePoseDetection(true | false); // viji.video.cv.pose\nawait viji.video.cv.enableBodySegmentation(true | false); // viji.video.cv.segmentation\nviji.video.cv.getActiveFeatures(); // CVFeature[]\nviji.video.cv.isProcessing(); // boolean\n```\n\nData outputs on `viji.video.cv`:\n- `analysedFrame: OffscreenCanvas | null`: the frame paired with the current CV results. `null` until the first inference lands. Use `viji.video.cv.analysedFrame ?? viji.video.currentFrame` to fall back during startup.\n- `getAnalysedFrameData(): ImageData | null`: pixel data of `analysedFrame`.\n\n**`faces: FaceData[]`**: `id` always present. Other fields populated only by their source model; otherwise `null` (`landmarks` is `[]` when empty). Always null-check.\n- `bounds: {x,y,width,height} | null` — populated by face detection\n- `center: {x,y} | null` — populated by face detection\n- `confidence: number | null` — populated by face detection\n- `landmarks: {x,y,z?}[]` (empty `[]` unless face mesh enabled)\n- `headPose: {pitch, yaw, roll} | null` — populated by face mesh\n- `expressions: {neutral, happy, sad, angry, surprised, disgusted, fearful} | null` (0..1 each) — populated by emotion detection\n- `blendshapes | null` (52 ARKit coefficients 0..1) — populated by emotion detection\n\nIf you need `bounds` while only running face mesh, either also enable face detection or compute it from `face.landmarks` min/max.\n\n**`hands: HandData[]`**: `id`, `handedness: 'left' | 'right'`, `confidence`, `bounds`, `landmarks` (21 points), `palm`, `gestures` (`fist`, `openPalm`, `peace`, `thumbsUp`, `thumbsDown`, `pointing`, `iLoveYou` 0..1).\n\n**`pose: PoseData | null`**: `confidence`, `landmarks` (33 points), body-part arrays `face`, `torso`, `leftArm`, `rightArm`, `leftLeg`, `rightLeg`.\n\n**`segmentation: SegmentationData | null`**: `mask: Uint8Array` (each byte is `0` for background or `1` for person; length = `width * height`), `width`, `height`.\n\n### Input\n\n- `viji.pointer`: `x`, `y`, `deltaX`, `deltaY`, `isDown`, `wasPressed`, `wasReleased`, `isInCanvas`, `type` (`'mouse' | 'touch' | 'none'`).\n- `viji.mouse`: `x`, `y`, `isInCanvas`, `isPressed`, `leftButton`, `rightButton`, `middleButton`, `deltaX`, `deltaY`, `wheelDelta`, `wheelX`, `wheelY`, `wasPressed`, `wasReleased`, `wasMoved`.\n- `viji.keyboard`: `isPressed(key)`, `wasPressed(key)`, `wasReleased(key)`, `activeKeys`, `pressedThisFrame`, `releasedThisFrame`, `lastKeyPressed`, `lastKeyReleased`, `shift`, `ctrl`, `alt`, `meta`.\n- `viji.touches`: `count`, `points`, `started`, `moved`, `ended`, `primary`. Each `TouchPoint`: `id`, `x`, `y`, `pressure`, `radius`, `radiusX`, `radiusY`, `rotationAngle`, `force`, `isInCanvas`, `deltaX`, `deltaY`, `velocity`, `isNew`, `isActive`, `isEnding`.\n\n### Sensors and external devices\n\n`viji.device.motion`: `acceleration {x,y,z}` (m/s²), `accelerationIncludingGravity`, `rotationRate {alpha,beta,gamma}` (deg/s), `interval` (ms).\n`viji.device.orientation`: `alpha` (0-360°), `beta` (-180..180°), `gamma` (-90..90°), `absolute`.\n\n`viji.devices: DeviceState[]`: each entry: `id`, `name`, `motion`, `orientation`, `video` (`VideoAPI | null`, no CV), `audio` (`AudioStreamAPI | null`, lightweight).\n\n### Host streams\n\n`viji.videoStreams: VideoAPI[]`: extra video sources. Same shape as `viji.video`, including a per-stream `cv` surface (same verbs and result fields; `cv.analysedFrame` is main-stream only). May be empty.\n`viji.audioStreams: AudioStreamAPI[]`: extra audio sources. May be empty. Lightweight shape (no beat / BPM).\n\n## Template\n\n```javascript\n// @renderer p5\n\nconst bgColor = viji.color('#1a1a2e', { label: 'Background' });\nconst speed = viji.slider(1, { min: 0.1, max: 5, label: 'Speed' }); // implicit step → 0.01\nconst count = viji.slider(8, { min: 3, max: 30, step: 1, label: 'Count' }); // explicit step for integer counts\n\nlet angle = 0;\n\nfunction setup(viji, p5) {\n p5.colorMode(p5.HSB, 360, 100, 100);\n}\n\nfunction render(viji, p5) {\n angle += speed.value * viji.deltaTime;\n p5.background(bgColor.value);\n\n const cx = viji.width / 2;\n const cy = viji.height / 2;\n const radius = p5.min(viji.width, viji.height) * 0.3;\n const dotSize = p5.min(viji.width, viji.height) * 0.04;\n const n = p5.floor(count.value);\n\n p5.noStroke();\n for (let i = 0; i < n; i++) {\n const a = angle + (i / n) * p5.TWO_PI;\n const x = cx + p5.cos(a) * radius;\n const y = cy + p5.sin(a) * radius;\n p5.fill((i / n) * 360, 80, 90);\n p5.circle(x, y, dotSize);\n }\n}\n```\n",
|
|
9854
9854
|
"shader": "# Viji API: Shader Renderer Reference\n\nShader scenes are GLSL fragment shaders running on a fullscreen quad. Write helper functions and `void main()`. Precision and all uniforms (built-in plus those generated from `@viji-*` directives) are auto-injected by Viji. The first line must be `// @renderer shader` (or `#version 300 es` followed by `// @renderer shader` for GLSL ES 3.00).\n\n## Architecture\n\n- The shader is **GLSL ES 1.00** by default. Opt into ES 3.00 by making `#version 300 es` the literal first line.\n- Viji auto-injects `precision mediump float;` and every uniform declaration. Never declare them yourself.\n- ES 3.00 requires `out vec4 fragColor;` before `main` and `fragColor = ...` instead of `gl_FragColor`. ES 3.00 uses `texture()` instead of `texture2D()`.\n- If the shader references `fwidth`, Viji auto-injects `#extension GL_OES_standard_derivatives : enable`.\n- The `backbuffer` sampler is auto-enabled when referenced. It carries the previous frame.\n\n## Rules\n\n1. **Always** add `// @renderer shader` as the first line (or as line 2 after `#version 300 es`).\n2. **Never** declare `precision mediump float;` or `precision highp float;`. Viji auto-injects precision.\n3. **Never** redeclare built-in uniforms (`u_time`, `u_resolution`, `u_mouse`, audio / video / CV uniforms, etc.). They are auto-injected.\n4. **Never** redeclare parameter uniforms. They are auto-generated from `@viji-*` directives.\n5. **Never** use the `u_` prefix for your own parameter names. It is reserved for Viji's built-ins. Use descriptive names (`speed`, `colorMix`, `intensity`).\n6. `@viji-*` parameter directives work with `//` comments only. Block comments (`/* */`) are not parsed.\n7. **Always** use `@viji-accumulator` instead of `u_time * speed` for parameter-driven animation. Multiplying `u_time` by a parameter causes visible jumps when sliders change.\n\n ```glsl\n // @viji-slider:speed label:\"Speed\" default:1.0 min:0.1 max:5.0\n // @viji-accumulator:phase rate:speed\n float wave = sin(phase);\n ```\n\n This also applies to **nested** multiplications. Each independent speed needs its own accumulator:\n\n ```glsl\n // @viji-accumulator:phase rate:speed\n // @viji-accumulator:rotPhase rate:rotSpeed\n ```\n8. For `backbuffer` (previous frame): reference it directly in code. Viji auto-detects and enables it. Sample with `texture2D(backbuffer, uv)` (ES 1.00) or `texture(backbuffer, uv)` (ES 3.00).\n9. Remove any `#ifdef GL_ES` / `precision` blocks; Viji handles them.\n10. **Always** set `category` on input-dependent directives: `category:audio`, `category:video`, `category:interaction`. Don't add on/off toggles to enable/disable host-gated inputs (audio, video, mouse, keyboard, touch, sensors, devices) — the host controls those. CV activations are the exception (the `@viji-cv:` directives below).\n11. **CV features must be activated via `// @viji-cv:<featureToken>` directives.** Without the matching `@viji-cv:` activation, CV uniforms (`u_faceCount`, `u_face0*`, `u_handCount`, `u_poseDetected`, `u_segmentationMask`, etc.) read zero. Choose the form by intent: use the bare form (`// @viji-cv:faceDetection`) for always-on detection when CV is the scene's defining purpose, or the toggleable form (`// @viji-cv:faceDetection label:\"Face Detection\" default:false`) — which synthesizes both a host-side toggle parameter and a `bool <featureToken>` shader uniform mirroring its state — when CV is optional or the scene uses several heavy features. The six tokens: `faceDetection`, `faceMesh`, `emotionDetection`, `handTracking`, `poseDetection`, `bodySegmentation`.\n\n## Parameter directives\n\n```glsl\n// @viji-slider:name label:\"Label\" default:1.0 min:0.0 max:5.0 step:0.1\n// -> uniform float name;\n\n// @viji-color:name label:\"Color\" default:#ff6600\n// -> uniform vec3 name; (RGB 0..1)\n// default: accepts #rrggbb, #rgb, vec3(r,g,b) (0..1), rgb(r,g,b) (0..255),\n// hsl(h, s%, l%) (h: 0..360), hsb(h, s, b) (h: 0..360, s/b: 0..100)\n\n// @viji-toggle:name label:\"Toggle\" default:false\n// -> uniform bool name;\n\n// @viji-select:name label:\"Mode\" default:0 options:[\"Solid\",\"Gradient\",\"Noise\"]\n// -> uniform int name; (0-based)\n\n// @viji-number:name label:\"Count\" default:10.0 min:1.0 max:100.0 step:1.0\n// -> uniform float name;\n\n// @viji-image:name label:\"Texture\"\n// -> uniform sampler2D name;\n\n// @viji-button:name label:\"Reset\"\n// -> uniform bool name; (true for one frame on press)\n\n// @viji-coordinate:name label:\"Origin\" default:[0.0,0.0]\n// -> uniform vec2 name; (each component -1..1)\n\n// @viji-accumulator:name rate:speed\n// -> uniform float name; (CPU-side: += rate * deltaTime each frame)\n```\n\nAll directives support `group:\"GroupName\"` and `category:\"audio|video|interaction|general\"`.\n\n## Uniform reference\n\nAll uniforms below are always available. Do not declare them.\n\n### Core\n\n| Uniform | Type | Description |\n|---|---|---|\n| `u_resolution` | `vec2` | Canvas width and height in pixels |\n| `u_time` | `float` | Seconds since scene start |\n| `u_deltaTime` | `float` | Seconds since last frame |\n| `u_frame` | `int` | Current frame number |\n| `u_fps` | `float` | Target frame rate (host-controlled) |\n\n### Mouse\n\n| Uniform | Type | Description |\n|---|---|---|\n| `u_mouse` | `vec2` | Mouse position in pixels (WebGL coords, bottom-left origin) |\n| `u_mouseInCanvas` | `bool` | Mouse inside canvas |\n| `u_mousePressed` | `bool` | Any button pressed |\n| `u_mouseLeft`, `u_mouseRight`, `u_mouseMiddle` | `bool` | Specific buttons |\n| `u_mouseDelta` | `vec2` | Per-frame movement |\n| `u_mouseWheel` | `float` | Scroll wheel delta |\n| `u_mouseWasPressed`, `u_mouseWasReleased` | `bool` | One-frame edges |\n\n### Pointer (unified mouse / touch)\n\n| Uniform | Type | Description |\n|---|---|---|\n| `u_pointer` | `vec2` | Primary input position in pixels (WebGL coords) |\n| `u_pointerDelta` | `vec2` | Primary input movement delta |\n| `u_pointerDown` | `bool` | Primary input active |\n| `u_pointerWasPressed`, `u_pointerWasReleased` | `bool` | One-frame edges |\n| `u_pointerInCanvas` | `bool` | Inside canvas |\n\n### Keyboard\n\n| Uniform | Type | Description |\n|---|---|---|\n| `u_keySpace`, `u_keyShift`, `u_keyCtrl`, `u_keyAlt` | `bool` | Modifier and space |\n| `u_keyW`, `u_keyA`, `u_keyS`, `u_keyD` | `bool` | WASD |\n| `u_keyUp`, `u_keyDown`, `u_keyLeft`, `u_keyRight` | `bool` | Arrows |\n| `u_keyboard` | `sampler2D` | Full keyboard state (256x3 LUMINANCE). Row 0 = held, row 1 = pressed-this-frame, row 2 = toggle. Access: `texelFetch(u_keyboard, ivec2(keyCode, row), 0).r` |\n\n### Touch\n\n| Uniform | Type | Description |\n|---|---|---|\n| `u_touchCount` | `int` | Active touches (0-5) |\n| `u_touch0`-`u_touch4` | `vec2` | Touch point positions in pixels |\n\n### Audio (scalars)\n\n| Uniform | Type | Description |\n|---|---|---|\n| `u_audioVolume`, `u_audioPeak` | `float` | RMS / peak 0..1 |\n| `u_audioVolumeSmoothed` | `float` | 200ms decay envelope of `u_audioVolume` |\n| `u_audioLow`, `u_audioLowMid`, `u_audioMid`, `u_audioHighMid`, `u_audioHigh` | `float` | Band energies 0..1 (20-120, 120-400, 400-1600, 1600-6000, 6000-16000 Hz) |\n| `u_audioLowSmoothed` - `u_audioHighSmoothed` | `float` | 150ms decay envelopes of the bands |\n| `u_audioKick`, `u_audioSnare`, `u_audioHat`, `u_audioAny` | `float` | Beat energy curves with 300ms decay; peak on each detected beat then fall off |\n| `u_audioKickSmoothed` - `u_audioAnySmoothed` | `float` | Smoother 500ms decay envelopes |\n| `u_audioKickTrigger`, `u_audioSnareTrigger`, `u_audioHatTrigger`, `u_audioAnyTrigger` | `bool` | True for exactly one frame on the matching beat, then auto-resets; OR-accumulated between frames |\n| `u_audioBPM`, `u_audioConfidence`, `u_audioIsLocked` | `float`, `float`, `bool` | `u_audioBPM` is `0.0` when no audio is connected; once audio connects it tracks the detected tempo (clamped to 60..240) with `120.0` as a fallback before lock-on. `u_audioConfidence` 0..1. `u_audioIsLocked` true on stable tempo lock |\n| `u_audioBrightness`, `u_audioFlatness` | `float` | Spectral features 0..1 |\n\n### Audio (textures, main source only)\n\n| Uniform | Type | Description |\n|---|---|---|\n| `u_audioFFT` | `sampler2D` | FFT spectrum (1024 bins, 0..255) |\n| `u_audioWaveform` | `sampler2D` | Time-domain waveform (-1..1) |\n\nAdditional audio streams and device audio expose scalar uniforms only (no FFT / waveform textures): see \"Streams\" below.\n\n### Video\n\n| Uniform | Type | Description |\n|---|---|---|\n| `u_video` | `sampler2D` | Most recent video frame |\n| `u_videoAnalysed` | `sampler2D` | Frame paired with current CV uniforms |\n| `u_videoAnalysedAvailable` | `bool` | True after first CV result lands |\n| `u_videoResolution` | `vec2` | Source frame size in pixels |\n| `u_videoFrameRate` | `float` | Source frame rate |\n| `u_videoConnected` | `bool` | Video source active |\n\n**Aspect handling.** Camera frames almost never match the canvas aspect. Sampling `texture2D(u_video, uv)` with canvas UV stretches the video and misaligns CV uniforms. Use these helpers at the top of every video / CV shader:\n\n```glsl\n// mode: 1 = cover (fills canvas, video edges cropped)\n// 0 = contain (fits video, canvas letterboxed)\nvec2 vijiVideoUV(vec2 uv, int mode) {\n vec2 canvas = u_resolution;\n vec2 video = u_videoResolution;\n if (video.x == 0.0 || video.y == 0.0) return uv;\n float canvasAspect = canvas.x / canvas.y;\n float videoAspect = video.x / video.y;\n vec2 scale = vec2(1.0);\n if (mode == 1) {\n scale = canvasAspect > videoAspect\n ? vec2(1.0, canvasAspect / videoAspect)\n : vec2(videoAspect / canvasAspect, 1.0);\n } else {\n scale = canvasAspect > videoAspect\n ? vec2(videoAspect / canvasAspect, 1.0)\n : vec2(1.0, canvasAspect / videoAspect);\n }\n return (uv - 0.5) / scale + 0.5;\n}\n\nbool vijiInVideo(vec2 uv) {\n return all(greaterThanEqual(uv, vec2(0.0))) && all(lessThanEqual(uv, vec2(1.0)));\n}\n```\n\nDefault to mode `1` (cover) for live cameras. Use `0` (contain) for CV-overlay shaders where features near edges must stay visible. CV uniforms (`u_face0Center`, etc.) share the same bottom-up convention as `videoUV`; compare them directly without flipping.\n\n**`u_video` vs `u_videoAnalysed`.** Default to `u_video` for displayed video. Reach for `u_videoAnalysed` only when sampling pixels at CV-derived positions (segmentation compositing onto the body, sampling skin under face landmarks, face-mesh texturing). For shaders that consume CV uniforms without sampling at CV positions, stay on `u_video` (`u_videoAnalysed` advances only on inference completion and will stutter the displayed video). When `u_videoAnalysed` is the right choice, gate on `u_videoAnalysedAvailable` for the brief startup window:\n\n```glsl\nvec4 source = u_videoAnalysedAvailable\n ? texture2D(u_videoAnalysed, uv)\n : texture2D(u_video, uv);\n```\n\n### CV: face detection\n\n| Uniform | Type | Description |\n|---|---|---|\n| `u_faceCount` | `int` | Detected faces (0-1) |\n| `u_face0Bounds` | `vec4` | `(x, y, width, height)` normalized 0..1 |\n| `u_face0Center` | `vec2` | Center normalized 0..1 |\n| `u_face0HeadPose` | `vec3` | `(pitch, yaw, roll)` in degrees |\n| `u_face0Confidence` | `float` | 0..1 |\n| `u_face0Neutral` - `u_face0Fearful` | `float` | 7 expression scores 0..1 |\n\n**52 blendshape uniforms** (all `float`, 0..1, ARKit names prefixed with `u_face0`):\n`BrowDownLeft`, `BrowDownRight`, `BrowInnerUp`, `BrowOuterUpLeft`, `BrowOuterUpRight`, `CheekPuff`, `CheekSquintLeft`, `CheekSquintRight`, `EyeBlinkLeft`, `EyeBlinkRight`, `EyeLookDownLeft`, `EyeLookDownRight`, `EyeLookInLeft`, `EyeLookInRight`, `EyeLookOutLeft`, `EyeLookOutRight`, `EyeLookUpLeft`, `EyeLookUpRight`, `EyeSquintLeft`, `EyeSquintRight`, `EyeWideLeft`, `EyeWideRight`, `JawForward`, `JawLeft`, `JawOpen`, `JawRight`, `MouthClose`, `MouthDimpleLeft`, `MouthDimpleRight`, `MouthFrownLeft`, `MouthFrownRight`, `MouthFunnel`, `MouthLeft`, `MouthLowerDownLeft`, `MouthLowerDownRight`, `MouthPressLeft`, `MouthPressRight`, `MouthPucker`, `MouthRight`, `MouthRollLower`, `MouthRollUpper`, `MouthShrugLower`, `MouthShrugUpper`, `MouthSmileLeft`, `MouthSmileRight`, `MouthStretchLeft`, `MouthStretchRight`, `MouthUpperUpLeft`, `MouthUpperUpRight`, `NoseSneerLeft`, `NoseSneerRight`, `TongueOut`.\n\n### CV: hands\n\n| Uniform | Type | Description |\n|---|---|---|\n| `u_handCount` | `int` | Detected hands (0-2) |\n| `u_leftHandPalm`, `u_rightHandPalm` | `vec3` | Palm position `(x, y, z)` |\n| `u_leftHandConfidence`, `u_rightHandConfidence` | `float` | 0..1 |\n| `u_leftHandBounds`, `u_rightHandBounds` | `vec4` | Bounds normalized 0..1 |\n| `u_leftHandFist` - `u_leftHandILoveYou` | `float` | 7 left-hand gesture scores |\n| `u_rightHandFist` - `u_rightHandILoveYou` | `float` | 7 right-hand gesture scores |\n\n### CV: pose\n\n| Uniform | Type | Description |\n|---|---|---|\n| `u_poseDetected` | `bool` | Pose detected |\n| `u_poseConfidence` | `float` | 0..1 |\n| `u_nosePosition` | `vec2` | Nose landmark, normalized 0..1 |\n| `u_leftShoulderPosition` … `u_rightAnklePosition` | `vec2` | Joint landmarks (shoulders, elbows, wrists, hips, knees, ankles) |\n\n### CV: body segmentation\n\n| Uniform | Type | Description |\n|---|---|---|\n| `u_segmentationMask` | `sampler2D` | 0 = background, 1 = person |\n| `u_segmentationRes` | `vec2` | Mask resolution in pixels |\n\n### Device sensors\n\n| Uniform | Type | Description |\n|---|---|---|\n| `u_deviceAcceleration` | `vec3` | Acceleration without gravity (m/s²) |\n| `u_deviceAccelerationGravity` | `vec3` | Acceleration including gravity (m/s²) |\n| `u_deviceRotationRate` | `vec3` | Rotation rate (deg/s) |\n| `u_deviceOrientation` | `vec3` | `(alpha, beta, gamma)` in degrees |\n| `u_deviceOrientationAbsolute` | `bool` | Using magnetometer |\n\n### External devices\n\n| Uniform | Type | Description |\n|---|---|---|\n| `u_deviceCount` | `int` | Device video sources (0-8) |\n| `u_externalDeviceCount` | `int` | External devices (0-8) |\n| `u_device0` - `u_device7` | `sampler2D` | Device camera textures |\n| `u_device0Resolution` - `u_device7Resolution` | `vec2` | Per-device resolution |\n| `u_device0Connected` - `u_device7Connected` | `bool` | Per-device connection |\n| `u_device0Acceleration` - `u_device7Acceleration` | `vec3` | Per-device acceleration (no gravity) |\n| `u_device0AccelerationGravity` - `u_device7AccelerationGravity` | `vec3` | Per-device acceleration (with gravity) |\n| `u_device0RotationRate` - `u_device7RotationRate` | `vec3` | Per-device rotation rate |\n| `u_device0Orientation` - `u_device7Orientation` | `vec3` | Per-device orientation |\n\n### Streams (compositor)\n\nVideo streams (host-provided):\n\n| Uniform | Type | Description |\n|---|---|---|\n| `u_videoStreamCount` | `int` | Active streams (0-8) |\n| `u_videoStream0` - `u_videoStream7` | `sampler2D` | Stream textures |\n| `u_videoStream0Resolution` - `u_videoStream7Resolution` | `vec2` | Per-stream resolution |\n| `u_videoStream0Connected` - `u_videoStream7Connected` | `bool` | Per-stream connection |\n\nAudio streams (additional sources, including device audio):\n\n| Uniform | Type | Description |\n|---|---|---|\n| `u_audioStreamCount` | `int` | Active streams (0-8) |\n| `u_audioStream0Connected` - `u_audioStream7Connected` | `bool` | Per-slot active |\n| `u_audioStream{i}Volume` | `float` | Volume 0..1 |\n| `u_audioStream{i}Low` - `u_audioStream{i}High` | `float` | Band energies 0..1 |\n| `u_audioStream{i}Brightness`, `u_audioStream{i}Flatness` | `float` | Spectral features 0..1 |\n\n`i` ranges 0..7. **Scalars only**: no `u_audioFFT` / `u_audioWaveform` per stream. Beat / BPM / trigger uniforms are main audio only.\n\n### Backbuffer\n\n| Uniform | Type | Description |\n|---|---|---|\n| `backbuffer` | `sampler2D` | Previous frame (auto-enabled when referenced) |\n\nNo `u_` prefix. RGBA 8-bit, `LINEAR` filtering, `CLAMP_TO_EDGE` wrapping. First frame samples as black. Clears on canvas resize.\n\n## Template\n\n```glsl\n// @renderer shader\n// @viji-slider:speed label:\"Speed\" default:1.0 min:0.1 max:5.0\n// @viji-color:baseColor label:\"Color\" default:#ff6600\n// @viji-accumulator:phase rate:speed\n\nvoid main() {\n vec2 uv = gl_FragCoord.xy / u_resolution;\n\n float wave = sin(uv.x * 10.0 + phase) * 0.5 + 0.5;\n float pulse = 1.0 + u_audioLow * 0.5;\n vec3 color = baseColor * wave * pulse;\n\n gl_FragColor = vec4(color, 1.0);\n}\n```\n"
|
|
9855
9855
|
},
|
|
9856
9856
|
"conversionGuides": {
|