# Integrate Glassen with a coding agent Source: https://glassen.mintlify.app/agents Help a coding agent install Glassen, choose a source and clean up when the glass is removed. Install `glassen` from npm and give your coding agent these instructions. ```sh theme={null} npx skills add OutThisLife/glassen ``` 1. Choose `glassen` for vanilla rendering or `glassen/react` for components. Use one `GlassSurface` or `createGlassSurface` for multiple lenses. 2. Load `glassen/style.css`, size the surface/slots and initialize the exported WASM URL when the bundler relocates it. 3. Choose explicit source pixels. React children use DOM snapshots; glass does not automatically capture the page beneath it. 4. Keep motion and geometry in the Rust core. Host adapters supply input, clocks, pixels and draw calls. 5. Keep source identity/version stable until pixels change. Allocate GPU resources per context and dispose them at the owning layer. 6. Preserve color and orientation. Glassen consumes premultiplied display-encoded RGBA; GPU textures use bottom-left coordinates. 7. Retain shared shapes until all consumers are removed. Match renderer `zIndex` with DOM input stacking. 8. Verify a real mounted example, source updates, cleanup and target-browser presentation. Do not claim native, WebGPU, arbitrary nested mesh or universal high-FPS support from an import/build alone. Start with [quickstart](/quickstart), [sources](/sources) and [porting](/porting). The package includes `skills/glassen/SKILL.md` for local agent installation. Use [llms.txt](https://glassen.mintlify.site/llms.txt) to find a guide, or [llms-full.txt](https://glassen.mintlify.site/llms-full.txt) to read the whole site as plain text. Mintlify generates both from these pages. # Glassen API reference Source: https://glassen.mintlify.app/api Reference the Glassen entry points, lens settings, mount lifetimes, frame values and optional DOM and ASCII adapters without pulling in unused engines. Glassen exports factories and optional adapters. Each mount owns its rendering resources; caller-provided sources and shared shapes retain their own lifetime. ## Entry points | Import | Exports | | - | - | | `glassen` | `createGlass`, `createGlassSurface`, `glassDefaults`, `initGlass`, `createPathShape`, `createMaskShape` | | `glassen/react` | `Glass`, `GlassSurface`, `GlassContent` | | `glassen/dom` | `createDOMSource` | | `glassen/crt` | `createCRTSource` | | `glassen/nested` | `createNestedOrbScene`, `initNestedGlass` | | `glassen/nested/react` | `NestedOrbs` | | `glassen/ascii` | `createAsciiSource`, `asciiPresets` | | `glassen/glsl` | Default shader body, named `PREPARE` helper | | `glassen/style.css` | DOM layout styles | | `glassen/wasm/*.wasm` | Compiled lens and nested scene modules | ## Lens options Pass these to `createGlass(canvas, options)`, `surface.add(element, options)` or `mount.update(options)`. | Option | Meaning | | - | - | | `appearance` | `'light'`, `'dark'` or `'system'`; omitted follows the system | | `shape` | Shared shape object, or `null` for the default orb | | `source` | `GlassSource`; omitted on a surface samples its scene content when present | | `refraction` | Bend strength; default 190, clamped to 0–350 | | `dispersion` | Chromatic separation; default 4, clamped to 0–12 | | `shadow` | Shadow multiplier; default 1, clamped to 0–2 | | `highlights` | Highlight multiplier; default 1, clamped to 0–3 | | `interactive` | Set `false` to disable pointer and keyboard interaction | | `zIndex` | Back-to-front paint order; default 0, stable for ties | | `onMove(delta, element)` | Incremental damped CSS-pixel movement; host applies positioning | `await glassDefaults(dark = false)` returns the appearance's `refraction`, `dispersion`, `shadow`, `highlights` and CSS `background` string from Rust. Do not duplicate those defaults in a host adapter. `createGlass` resolves to a mount with `update` and `destroy`. `createGlassSurface` resolves to a surface with `add`, `addContent`, `stats` and `destroy`. `addContent` accepts `source` and `appearance`. Updates merge into existing options. Destroy methods are idempotent. ## Source frame `time` is seconds on the surface clock. `size`, `width` and `height` describe CSS dimensions; `pixels`, `pixelWidth` and `pixelHeight` describe physical dimensions. `look` is a normalized pointer point, `reduced` reflects reduced-motion preference, and `owner` identifies the consuming surface resource. ## DOM capture ```js theme={null} import { createDOMSource } from 'glassen/dom' const source = createDOMSource(element, { live: false, onError: console.error }) // source.invalidate() after changes not observed by the DOM adapter. // source.destroy() after removing all consumers. ``` DOM capture observes mutations, resize, image loads and fonts. Canvas pixel writes and CSS-only animation do not produce DOM mutations. Prefer a canvas/GPU source for animation. Captured DOM should still have accessible original content. ## ASCII sources ```js theme={null} import { createAsciiSource } from 'glassen/ascii' const source = createAsciiSource({ preset: 'moire', opacity: 0.32 }) source.update({ zoom: 0.9 }) ``` Options are `dark`, `scale`, `speed`, `opacity`, `preset`, `colored` and `zoom`. Presets are `wobbly`, `moire`, `mobius`, `trefoil`, `sphere`, `poem`, `sigils` and `shards`. The surface owns the GPU renderer returned by the source. Keep the bundled ASCII credits when copying these adaptations. # glassen Source: https://glassen.mintlify.app/index Elastic glass for your content. Pull, stretch and reshape it. [JavaScript](/quickstart) · [React](/react) · [Shapes](/shapes) · [Shared surfaces](/surfaces) · [Agent instructions](/agents) Interactive glass type playground ## Use it ```sh theme={null} npm install glassen ``` Follow the [quickstart](/quickstart) to load WASM, mount a lens and supply pixels. In React, use [`Glass` with children](/react); for many lenses, use one [`GlassSurface`](/surfaces). Your host owns the content and placement. ## Use it with an agent Give your agent the package’s `skills/glassen/SKILL.md`, or link the [agent guide](/agents). It covers source adapters, instancing, cleanup and which integrations are supported. ## Compose it [SVG paths and masks](/shapes) · [Images, DOM and GPU textures](/sources) · [Nested scenes](/nested) Rust supplies geometry and spring motion; WebGL 2 renders the refraction. The nested scene adds rigid-body physics. See [performance](/performance) and [porting](/porting) for measured limits and native integration status. # Render a nested bubble scene Source: https://glassen.mintlify.app/nested Mount the included nested glass composition, initialize its separate Rapier WASM module and choose automatic playback or deterministic frame stepping. The nested entry point renders the included bubble composition using a separate Rust/Rapier simulation. It is a fixed composition API, not a general tree of arbitrary React children or nested meshes. ```js theme={null} import { createNestedOrbScene, initNestedGlass } from 'glassen/nested' import lens from 'glassen/wasm/goo_core_bg.wasm?url' import scene from 'glassen/wasm/nested_scene_bg.wasm?url' await initNestedGlass({ lens, scene }) const nested = await createNestedOrbScene(canvas, { seed: 7341, speed: 0.6, onError: console.error, }) // nested.update({ speed: 0.4, playing: true }) // nested.destroy() ``` Give the canvas a CSS width. The renderer derives its aspect ratio from the scene. Defaults are `seed: 7341`, `speed: 0.6` and `playing: true`. Hidden/offscreen playback pauses; reduced-motion preferences stop automatic advancement. For a host-controlled clock, call `nested.draw(elapsedSeconds)`. This stops automatic playback, advances the simulation by the supplied duration and renders once. It is an incremental step, not a seek to an absolute timestamp. Recreate the scene with the same seed to reset it. ```jsx theme={null} import { NestedOrbs } from 'glassen/nested/react' ``` The React wrapper also accepts `playing`, `className` and `onError`. It releases the scene on unmount. The single-lens entry point does not import or initialize this physics module. `nested.stats` reports frames, instances, CPU submission, interval, texture storage, targets, draw calls, copied pixels and allocations. These are diagnostic counters; they do not establish displayed FPS. # Measure and tune glass performance Source: https://glassen.mintlify.app/performance Measure frame pacing and memory use, and reduce the work each lens adds. Glassen shares a clock, sources and GPU resources within a surface. Performance depends on the pixel area covered, source work and overlap, as well as the number of lenses. Use one shared surface for collections. Reuse source and shape objects. Keep static source versions stable, and use GPU sources for continuously changing content. DOM snapshots are suitable for text and occasional updates, but repeated captures add CPU work and uploads. ## Read the counters | `surface.stats` field | Meaning | | - | - | | `instances`, `visible` | Mounted lenses and those painted this frame | | `drawCalls` | Glass draws this frame | | `sceneDrawCalls` | Scene content work this frame | | `backdropCopies` | GPU snapshots required by overlapping paint bounds | | `uploads` | Sampled image/canvas uploads this frame; GPU producers may do their own work | | `textureBytes` | Estimated owned texture storage | | `cpuMs` | JavaScript submission time for the frame | | `intervalMs` | Interval between rendered animation callbacks | | `frames` | Completed render callbacks | These counters do not measure GPU completion or displayed frames. Browser/GPU caches and driver allocations are outside `textureBytes`. ## Frame pacing Surfaces stop issuing draws when their canvas leaves the viewport, including inside an embedded preview, and resume when it returns. Source activity follows the same visibility boundary. The renderer follows `requestAnimationFrame` and device pixel ratio, without adaptive resolution. A 120 Hz display gives about 8.3 ms per frame; 60 Hz gives about 16.7 ms. Large lenses, overlapping layers and expensive source rendering can exceed those budgets. No device-independent FPS or instance-count guarantee is made. Measure in a visible browser on the target device. Chrome's frame-rendering stats and Performance trace distinguish presentation stalls, CPU work and GPU pressure. Test dragging, resize, multiple instances, background/resume and removal. A deterministic 4K60 recording proves the captured frame sequence; it does not prove real-time playback at 4K60. ## Lifetime checks Repeatedly mount and unmount the same scene. Owned textures and subscriptions should be released after consumers are removed; the WASM allocator may keep its grown memory for reuse. A memory plateau is different from growth on every cycle. Close GPU consumers before destroying their source or shape. Hidden/offscreen rendering pauses. A source can stop background work through `setActive`; it must account for every owner when shared. Avoid adding independent timers or render loops inside source adapters. # Port Glassen to another host Source: https://glassen.mintlify.app/porting Adapt the Rust core and glass shader to another renderer. See what ships and what a native host still needs. Rust owns lens geometry, motion and appearance. Hosts supply input, pixels and a clock, and draw with the shared shader. Preserve the existing geometry and optics when changing packaging or adapters. ## Web sources `GlassSource` offers `sample(frame)` for images/canvases or `createRenderer(gl)` for a GPU producer. A GPU renderer returns `{target, version}`; the target has `texture`, `framebuffer`, `width`, `height`, `bytes` and `dispose()`. It belongs to the supplied WebGL 2 context. The host disposes the renderer, which disposes its own targets; shared resources stay with their actual owner. A source can be mounted on multiple surfaces, so every `createRenderer` call must allocate independent context-local resources. `setActive(active, owner)` distinguishes those consumers. GPU textures use bottom-left texture coordinates and premultiplied, display-encoded RGBA. Sampled DOM/canvas images use the browser's top-left convention; the upload adapter handles it. Do not feed tone-mapped linear Three/pmndrs buffers directly; encode through the appropriate host adapter first. Versions identify pixel changes, including resize and configuration. Image sources should provide a new version for changed pixels; GPU renderers must return a version whenever their result changes. `subscribe(notify)` wakes a suspended surface after invalidation. No extra animation clock belongs inside a source adapter. GPU producers must establish their own draw state; the surface establishes its own state before drawing the scene and lenses. A source should not change framebuffer orientation. Context loss releases source renderers; restoration creates them again. Constructors must clean up partial allocations if they fail. Dispose is idempotent. ## Custom renderers `glassen/glsl` exports the generated shader body, not a complete drop-in material. It expects seven geometry float4 slots, four appearance slots, `tap`, `baseTap` and the binding macros used by `www/goo/orb/glass.js`. These reference sources, the Rust layout in `crates/glass-core/src/` and `crates/glass-core/shaders/orb.h` are included in the package. They document the host bindings; they are not a standalone native SDK. Do not hand-edit the generated bindings or duplicate core motion in JavaScript/Swift. The default field is a smooth union of circles. Custom outlines use Rust's `DistanceField` from square alpha coverage. Each texel contains distance in core canvas units, outward normal X/Y, and 1. Distances are negative inside; rows run downwards. Normals use a filtered derivative to avoid magnifying raster slope noise into refraction spikes. Coverage and CPU hit testing retain the unfiltered distance. Generation uses `sdf_glyph_renderer` without its FreeType feature. The WebGL host uploads RGBA16F with linear filtering and no mipmaps. `shapeField(p)` converts core coordinates to `p / canvas + 0.5`; `ORB_SHAPE_SCALE` selects and scales the custom field. Geometry slot 3.w carries that scale before the instanced vertex stage reuses the circle padding for the inverse transform. Zero retains the original orb. Hosts preserve the shape until all consumers are removed, including across context restoration. Metal hosts need equivalent texture bindings; the preserved Goop Metal adapter has not been extended or verified with custom masks. For scene-backed overlap, draw from back to front and snapshot completed layers before a dependent lens samples them. Do not sample the texture currently attached as the draw destination. The web surface batches independent paint bounds, and reuses one GPU snapshot for overlap. Explicit source lenses retain their own source. The Three.js study uses two alternating render targets, with one instanced draw per generation. Its mesh adapter maps local refraction offsets into screen space through UV derivatives; sibling cubes share their generation's backdrop. Before calling a host supported, execute its shaders and compare matched-time frames with the existing renderer, including light/dark, stretching, tiny/large lenses, source alpha, corners and resource disposal. Shader compilation alone does not validate the appearance. Native integration sources still depend on Goop; WebGPU and standalone iOS builds are not supplied here. # Render your first glass lens Source: https://glassen.mintlify.app/quickstart Install Glassen and render a glass lens over a canvas. Glassen takes a canvas and a source of pixels. This example uses a small canvas so you can run it without external images, fonts or CORS configuration. ## Install ```sh theme={null} npm install glassen ``` Rendering needs WebGL 2 and WebAssembly. The package contains both WASM modules; the core import does not load nested physics or require React. ## Render With Vite, import the WASM URL explicitly. This also makes asset relocation visible to the bundler. ```html theme={null}
``` ```js theme={null} import { createGlass, initGlass } from 'glassen' import wasmUrl from 'glassen/wasm/goo_core_bg.wasm?url' import 'glassen/style.css' await initGlass(wasmUrl) const image = document.createElement('canvas') image.width = image.height = 128 const pen = image.getContext('2d') pen.fillStyle = '#e84040' pen.fillRect(32, 32, 64, 64) const source = { sample: () => ({ image, version: 1 }) } const lens = await createGlass(document.querySelector('#lens canvas'), { source, appearance: 'light', }) // When removing the lens: // lens.destroy() ``` Keep space around the slot for stretch and shadow. The CSS paints beyond the slot; an ancestor with `overflow: hidden` clips it. The renderer's `goop-orb` class names are internal names retained from the original host. ## Other bundlers and plain modules Call `initGlass(urlOrBytes)` before mounting when your bundler does not preserve the generated `new URL(..., import.meta.url)` asset. Copy the exported WASM to your application's public assets and pass that URL. Serve it as `application/wasm`. Plain browser ESM can load it beside the package's JS chunks without explicit initialization. Imports are safe during SSR. Call mount methods only in a browser lifecycle hook, and catch rejected initialization to display your application's fallback. React handles its mount failures in the component. [Shared surfaces](/surfaces) use one canvas and clock for many lenses. # Glass components in React Source: https://glassen.mintlify.app/react Render React children inside a glass lens, share one surface across lenses and keep animated sources outside DOM snapshots with explicit cleanup. Glassen's React entry point mounts and releases the renderer with your component. Import the layout stylesheet once and initialize the WASM asset before rendering the application. ```jsx theme={null} import { initGlass } from 'glassen' import wasmUrl from 'glassen/wasm/goo_core_bg.wasm?url' import { Glass } from 'glassen/react' import 'glassen/style.css' // Run in your browser entry point before mounting React. await initGlass(wasmUrl) export function Example() { return ( hello ) } ``` Children are captured with `modern-screenshot`. DOM mutations, size changes and font loads invalidate the snapshot. This does not capture arbitrary content behind the component. Use an explicit [source](/sources) for canvas animation or GPU content; `liveChildren` requests repeated DOM captures and can be expensive. ## Stationary content, moving glass ```jsx theme={null} import { Glass, GlassSurface, GlassContent } from 'glassen/react' export function Scene() { return ( GLASS ) } ``` `GlassContent` requires `GlassSurface`. Lenses without their own `source` sample the shared scene. A `source` prop takes precedence over children. Shared surfaces own one WebGL context and animation clock; individual lenses keep independent spring state. `Glass` accepts the [lens options](/api), plus `size`, `style`, `label`, `children` and `liveChildren`. The default size is 480 CSS pixels. `GlassSurface` accepts `style`, `className` and `onReady(surface)` for reading statistics. Keep React state updates out of the frame loop; use DOM transforms in `onMove`, or position the lens through your application's existing motion layer. The component responds to arrow keys as well as pointer drags. `interactive={false}` disables these handlers. Keep important text and controls accessible in DOM; a rendered texture does not provide semantics. # Shape glass with paths and masks Source: https://glassen.mintlify.app/shapes Build reusable glass outlines from SVG paths or canvas alpha, including concave shapes and holes, while retaining the same spring and hit testing. Glassen accepts a filled SVG path or a canvas alpha mask. Rust builds a signed distance field once; the field supplies both shading and hit testing during stretch. ```js theme={null} import { createPathShape } from 'glassen' const heart = await createPathShape( 'M50 90 C10 65 0 35 20 20 C35 10 45 20 50 30 C55 20 65 10 80 20 C100 35 90 65 50 90 Z', { viewBox: [0, 0, 100, 100], padding: 0.12, resolution: 512 }, ) const lens = surface.add(element, { shape: heart }) // Remove all consumers before freeing the shape. // lens.destroy() // heart.destroy() ``` `createPathShape(path, options)` accepts path data, not an SVG document. Defaults are `viewBox: [0,0,100,100]`, `padding: 0.12`, `resolution: 512` and `fillRule: 'nonzero'`. Use `fillRule: 'evenodd'` for a path with holes. ## Canvas masks ```js theme={null} import { createMaskShape } from 'glassen' const ring = await createMaskShape({ resolution: 512, draw(pen, size) { pen.beginPath() pen.arc(size / 2, size / 2, size * 0.38, 0, Math.PI * 2) pen.arc(size / 2, size / 2, size * 0.22, 0, Math.PI * 2, true) pen.fill('evenodd') }, }) ``` The callback receives a cleared canvas with white fill. Alpha defines the filled area, so you can draw paths or text with native canvas APIs. Wait for fonts before drawing text. The mask must have a filled area and a transparent outer border. Resolution must be an integer from 16 to 1024. Share one shape object across lenses and retain it through context restoration. `lens.update({ shape: null })` restores the default orb. Filtered shading normals reduce raster spikes, but a finite-resolution mask cannot reproduce arbitrarily thin features. Inspect corners, holes, minification and stretched silhouettes at the sizes you ship. Custom shapes use the same screen-space optical approximation; they are not solid meshes with modeled wall thickness. The web adapter supports these masks. The preserved Metal host does not yet bind custom fields; see [porting](/porting). # Supply images, canvases and GPU textures Source: https://glassen.mintlify.app/sources Implement a Glassen source for static or animated pixels, with versioned uploads, context-local GPU resources and explicit ownership on teardown. A `GlassSource` supplies pixels to one or more lenses. Choose a canvas/image source for browser content or a GPU renderer when your application already renders textures. ## Images and canvases ```js theme={null} const image = new Image() image.src = '/artwork.png' await image.decode() const source = { sample: () => ({ image, version: 1, sampling: 'linear' }) } ``` Set `crossOrigin = 'anonymous'` before `src` for a cross-origin image, and configure the image server to allow it. Image uploads use premultiplied RGBA; the adapter handles top-left browser coordinates. `sampling: 'nearest'` preserves pixel edges. Use a stable version until the pixels change. Increment it after drawing into the same canvas; replacing the image object also invalidates the upload. Every mounted surface can share a source identity without sharing a WebGL texture between contexts. ## Animated drawing ```js theme={null} const source = { draw(pen, frame) { const p = frame.pixels pen.fillStyle = '#e84040' pen.beginPath() pen.arc(p * (0.5 + Math.sin(frame.time) * 0.15), p / 2, p * 0.12, 0, Math.PI * 2) pen.fill() }, } ``` The host clears a canvas matching `frame.pixelWidth` × `frame.pixelHeight` and calls `draw` on its display clock. This path uploads pixels each frame. Use `sample` for static sources or `createRenderer(gl)` to keep animation entirely on the GPU. Do not start a second animation clock inside a source. ## GPU source `createRenderer(gl)` returns `{ bytes, render(frame), dispose() }`. `render` returns `{ target, version }`, where `target` contains `texture`, `framebuffer`, `width`, `height`, `bytes` and `dispose()`. The texture must belong to `gl`, use bottom-left texture coordinates, and contain premultiplied, display-encoded RGBA. Establish your renderer's own draw state. Linear Three.js render targets require the appropriate color conversion before Glassen samples them. Create independent resources for every `createRenderer` call. The surface disposes those renderers when the final consumer leaves or the context is lost. It never destroys the caller's source object. Make disposal idempotent and clean up partial allocations if construction fails. ## Updates and activity `subscribe(notify)` returns an unsubscribe function. Notify after source changes to wake suspended surfaces. `setActive(active, owner)` identifies each consumer so a shared producer can pause only when no consumers remain active. `look(point)` optionally receives pointer coordinates. [DOM capture](/api#dom-capture) is an optional adapter. # Share a surface across glass lenses Source: https://glassen.mintlify.app/surfaces Use one WebGL context and display clock for multiple independent lenses, place stationary content beneath them and control overlapping paint order. A shared surface separates the glass from its content. Add stationary content once, then move independently sized lenses over the completed scene. ```js theme={null} import { createGlassSurface } from 'glassen' const surface = await createGlassSurface(canvas, { onError: console.error }) const content = surface.addContent(contentElement, { source }) let x = 0, y = 0 const lens = surface.add(lensElement, { appearance: 'light', onMove(delta, element) { x += delta.x y += delta.y element.style.transform = `translate(${x}px, ${y}px)` }, }) // Releases lenses, subscriptions, targets and the animation clock: // surface.destroy() ``` Put the canvas inside a positioned `.goop-orb-surface` element. Size the surface explicitly. Place the content and lens elements inside it, with the `.goop-orb-scene-content` and `.goop-orb` classes respectively. Lens elements need a measurable box; interactive vanilla lenses need `tabindex="0"`, `role="group"` and an accessible label. Ordinary drag stretches. Command-drag, or Command plus arrow keys, requests movement through `onMove`. The callback receives damped incremental CSS-pixel displacement, not an absolute position. The host applies it to the element. Without `onMove`, Command-drag retains stretch behavior. The built-in move modifier uses the Meta key; touch and hosts where the operating system reserves Meta need a host-provided positioning control. ## Overlap `zIndex` sets back-to-front lens order; equal values keep mounting order. Match DOM input stacking with that order. Scene-backed lenses refract completed layers beneath them. A lens with its own explicit `source` continues sampling that source. Independent lenses batch when texture bindings permit. Overlapping paint bounds require GPU backdrop copies; a hundred overlapping lenses cost more than a hundred separated lenses. This is one shared context with instanced draws, not a promise of one draw for every scene. ## Removal and reuse `add` and `addContent` return `{ update(options), destroy() }`. Destroying a mount releases its own resources and source lease. It does not remove the host element or destroy caller-owned sources or shapes. Remove all consumers before destroying a shared shape or source. Read `surface.stats` without copying it into React state each frame. See [performance](/performance) for interpreting its counters.