Diorama

Made for a big screen.

This site is one 3D scene, built for a computer: a wide window and a mouse. Open dioramajs.dev on a desktop or a laptop to see it.This site is one 3D scene, built for a wide window. Make this one wider, or open dioramajs.dev on a larger screen.

GitHub

DioramaDocs

Performance and quality

What Diorama loads and when, which frames it draws, what costs GPU time and memory, and the options that trade quality for speed.

View as Markdown
On this page

Diorama keeps the cost of a page near zero until an effect is about to be seen, and near zero again once nothing moves. This guide lists what each part costs and the options that change it.

What loads and when

PartSize, min+gzipWhen it loads
start() with effects, transitions and cacheabout 44 KBwith your page script
CDN build @dioramajs/diorama/autoabout 44 KBwith the script tag
Engine: three.js and the Diorama runtimeabout 225 KBwhen the first effect element nears the viewport
One effect moduleunder 1 KBwith the engine, when an element with it nears view
Decoders for Draco, Meshopt, KTX2per decoderonly for a model file that uses that compression

“Nears the viewport” means within one viewport height by default. After the window load event the engine also downloads in idle time, so it is usually cached before the first scroll. Change both in start().

import {
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
} from '@dioramajs/diorama'
export const
const app: App
app
=
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
({
StartOptions.load?:
| "near"
| "eager"
| "manual"
| undefined

When the engine boots: 'near' (default), 'eager' or 'manual'.

load
: 'near', // 'eager' boots at start, 'manual' waits for app.effects.load()
StartOptions.margin?: string | undefined

IntersectionObserver rootMargin that starts loading. Default '100% 0px'.

margin
: '50% 0px', // IntersectionObserver rootMargin, default '100% 0px'
StartOptions.prefetch?: boolean | undefined

Download the engine in idle time after window load. Default true.

prefetch
: false, // no idle download after window load
})

Some visitors never load the engine at all:

  • With enabled: 'auto', the default, Save-Data turns the app off. A browser without WebGPU and WebGL 2 makes it unavailable, with enabled: true too, which only ignores Save-Data. The check runs before anything downloads, the idle-time prefetch included, and the page stays plain HTML.
  • An effect with when: 'hover' is skipped on touch devices, which never load the engine for it.
  • An effect with reducedMotion: 'off' is skipped for visitors who prefer reduced motion.

In each case the element stays plain HTML with data-dio-state="off", so CSS can tell these visitors apart.

Frames on demand

The loop draws a frame only when something asks for one: a scroll, a pointer move over an effect, a param write, a resize, a flight. A page at rest draws 0 frames, and so does a hidden tab.

Each effect has a frame policy. The default is derived from what the effect reads: u.time animates every frame while visible, u.hoverTime while hovered and while hover fades, and neither means input only. An update that returns true or false decides for itself. Set it yourself when you need less.

src/effects/drift.ts
import {
function effect(
setup: EffectSetup<Empty>
): Effect<Empty> (+2 overloads)

Short form of defineEffect: defaults, optional options, setup. An unnamed effect takes its registry key (the file name when a build plugin finds it).

export default effect({ strength: 1 }, ({ surface, u }) => { ... })

effect
} from '@dioramajs/diorama'
import {
const sin: UnaryFloatVecFunction
sin
} from 'three/tsl'
export default
effect<P>(
params: P & CheckSpec<P>,
options: EffectOptions<ColorsIn<P>>,
setup: EffectSetup<ColorsIn<P>>
): Effect<WidenSpec<P>> (+2 overloads)
type P = {
readonly strength: 0.02;
}

Short form of defineEffect: defaults, optional options, setup. An unnamed effect takes its registry key (the file name when a build plugin finds it).

export default effect({ strength: 1 }, ({ surface, u }) => { ... })

effect
(
{
strength: 0.02
strength
: 0.02 },
{
animate?:
| AnimatePolicy<ColorsIn<{ readonly strength: 0.02; }>>
| undefined

Defaults to the update's answer when it returns a boolean, else to what the effect reads: time animates every visible frame, hoverTime while hovered or hover decays, neither means 'input'.

animate
: {
fps:
| number
| (
(
ctx: EffectContext<ColorsIn<{ readonly strength: 0.02; }>>
) => number
)
fps
: 30 } },
({
surface: Surface

The shared GL copy of the element, created on first access.

surface
,
u: Uniforms<ColorsIn<{
readonly strength: 0.02;
}>>

Input uniforms and one uniform per live param, for TSL graphs.

u
}) => {
surface: Surface

The shared GL copy of the element, created on first access.

surface
.
Surface.uv(transform: (uv: Node<"vec2">) => Node): Off

Bends box UV (0..1, y up) before sampling.

uv
((
uv: Node<"vec2">
uv
) =>
uv: Node<"vec2">
uv
.
add: (
b: Vec2OrLessOrNumberParameterForNumType<"float">,
...params: Vec2OrLessOrNumberParameterForNumType<"float">[]
) => Node<"vec2"> (+3 overloads)
add
(
function sin(x: FloatOrNumber): Node<"float"> (+3 overloads)
sin
(
u: Uniforms<ColorsIn<{
readonly strength: 0.02;
}>>

Input uniforms and one uniform per live param, for TSL graphs.

u
.
InputUniforms.time: UniformNode<"float">

Seconds that advance only while visible. Frozen under reduced motion.

time
).
mul: (
b: NumberParameterForNumType<"float">,
...params: NumberParameterForNumType<"float">[]
) => Node<"float"> (+7 overloads)
mul
(
u: Uniforms<ColorsIn<{
readonly strength: 0.02;
}>>

Input uniforms and one uniform per live param, for TSL graphs.

u
.
strength: UniformNode<"float">
strength
)))
},
)

{ fps: 30 } draws time-driven frames at most 30 times a second while visible; input frames still run at full rate. An element off screen is not updated or drawn, and a param write to it requests no frame. How a frame is decided explains the rules.

Check what the loop does from the console.

function setInterval(
handler: TimerHandler,
timeout?: number,
...arguments: any[]
): number
setInterval
(() => {
const {
const frames: number

Frames run so far.

frames
,
const reason: FrameReason | "none"

Why the last frame ran.

reason
} =
const app: App
app
.
AppCore<Services & Empty, string>.loop: Loop

Live state of the frame loop.

loop
.
Loop.stats: FrameStats

Loop counters.

stats
var console: Console
console
.
Console.log(...data: any[]): void

The console.log() static method outputs a message to the console.

MDN Reference

log
(
const frames: number

Frames run so far.

frames
,
const reason: FrameReason | "none"

Why the last frame ran.

reason
,
const app: App
app
.
Services.effects: EffectsApi
effects
.
EffectsApi.stats(): EffectsStats

Counters for tests and devtools, zeros without the runtime.

stats
())
}, 1000)

frames counts every frame so far and reason says why the last one ran: invalidate, hold, timed, always or step. app.effects.stats() counts layers, instances and textures.

Pixels

The canvas covers the viewport, so its cost grows with the screen. Two limits keep it in bounds.

  • The device pixel ratio is capped at 2.
  • The drawing buffer holds at most 4 million device pixels. On a 2560 by 1440 screen at ratio 2 that is about 14.7 million, so the ratio drops to about 1.04.

Lower the budget for heavy effects, or cap the ratio at runtime, for example when frames get slow. The cap applies at the next frame.

import {
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
} from '@dioramajs/diorama'
export const
const app: App
app
=
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
({
StartOptions.render?:
| Partial<RenderOptions>
| undefined

Renderer options beyond background. start() defaults to antialias: 'auto' and environment: 'room'.

render
: {
maxPixels?: number | undefined

Upper bound for the drawing buffer, in device pixels. The pixel ratio drops to fit, so a large high-DPI screen cannot demand gigabytes of GPU memory. Default 4 million.

maxPixels
: 2_000_000 } })
// Once the engine runs:
const
const render: RenderApi | undefined
render
=
const app: App
app
.
Services.effects: EffectsApi
effects
.
EffectsApi.render: RenderApi | undefined

The renderer once ready.

render
if (
const render: RenderApi | undefined
render
)
const render: RenderApi
render
.
RenderApi.maxPixelRatio: Signal<number>

Upper bound of the pixel ratio, applied at the next frame. Default Infinity.

maxPixelRatio
.
Signal<number>.value: number

Current value. Writing a different value notifies its readers.

value
= 1.5

antialias: 'auto', the default in start(), turns on multisampling only when the pixel ratio at start is below 2. At higher ratios the extra memory buys little. Pass render: { antialias: false } to turn it off everywhere.

What costs GPU time and memory

  • Each element with effects is one layer: one plane drawn with one material that combines all its effects, plus whatever its effects place. A gallery of 40 images is 40 draws.
  • Every visible pixel of a layer runs the effect’s shader. A full-screen layer or a large bleed costs more than a thumbnail.
  • An image decodes once per URL and is shared by every effect that shows it. Each element uploads its own texture, so 40 copies of one image take 40 textures of GPU memory.
  • A model’s geometry, materials and textures load once and are shared by every instance.
  • The first frame of a new material compiles a GPU pipeline, which can hold the main thread for 50 to 100 ms on mid-range hardware.
  • Unused cache entries stay in memory up to 32 MB for reuse. Lower it with the retain option of assets().
<img
src="/img/tile-01.avif"
data-dio="image"
data-dio-track="layout"
/>

Scroll that keeps up

The browser scrolls on the compositor thread for touch, keyboard, the scrollbar and the wheel without smooth scrolling, ahead of the main thread. followScroll, on by default, moves the canvas with the page on the compositor until the next frame lands, so copies stay on their elements even on a slow GPU. It costs a CSS animation and nothing on the GPU.

While a frame is late, content fixed to the viewport moves with the page too. A site with a full-screen scene and native scrolling turns it off on the stage.

src/main.ts
import {
const stage: Plugin<
"stage",
StageOptions,
StageApi,
never
>

One canvas for the whole site. It outlives page transitions.

stage
,
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
} from '@dioramajs/diorama'
export const
const app: App
app
=
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
({
StartOptions.plugins?:
| readonly PluginEntry[]
| undefined

Extra plugins, your own or official ones with more options.

plugins
: [
function stage(
options?: Partial<StageOptions> | undefined
): Plugin<"stage", StageOptions, StageApi, never>

One canvas for the whole site. It outlives page transitions.

stage
({
followScroll?: boolean | undefined

Keeps GL copies on their elements while the browser scrolls the page ahead of the next frame (keyboard, scrollbar, native wheel, touch). The created canvas moves with the page on the compositor until the frame lands, and GL content fixed to the viewport moves with it for that time. While a stage.hold predicate is true (effects: a pinned sticky stage of a scroll section) the canvas stays fixed to the viewport instead. Vertical page scroll only. Needs CSS scroll-driven animations. Default true.

followScroll
: false })] })

How a layer follows scroll shows the mechanism.

Trade quality for speed

Start from the cheapest change that helps.

  1. Limit time-driven effects with animate: { fps } or move them to 'hover'.
  2. Lower render.maxPixels or maxPixelRatio on pages with full-screen effects.
  3. Keep heavy effects off touch devices with when: 'hover' or a media query of your own, such as when: '(min-width: 64em)'.
  4. Give the visitor a still frame with reducedMotion: 'static', the default, rather than an animation they asked not to see.
  5. Turn an effect off everywhere for a session with app.effects.disable('ripple'). The returned function turns it back on.