Using Rollshade effects in three.js
Rollshade gives three.js games ready-made moves, status effects and placed effects. The easiest way to use them is the npm package rollshade (part 1). The tool can also export effects as files and generate looping TSL shaders you edit as node graphs (part 2). Everything runs on WebGPURenderer, which falls back to WebGL2.
Part 1 · The rollshade package
Install
npm i rollshade [email protected]
The package is the same runtime the tool uses, under the MIT License. It needs three r186 and a WebGPURenderer from three/webgpu, which falls back to WebGL2 on its own. Try everything in the demo game first if you like.
import * as THREE from 'three/webgpu';
import { FXSystem, effect } from 'rollshade';
const renderer = new THREE.WebGPURenderer({ antialias: true });
renderer.toneMapping = THREE.ACESFilmicToneMapping;
await renderer.init();
const fx = new FXSystem({ scene, camera, renderer, post: true, feel: true });
fx.add(effect('meteor', 'fire'));
await fx.prewarm();
const timer = new THREE.Timer();
renderer.setAnimationLoop((ms) => {
timer.update(ms);
fx.update(Math.min(timer.getDelta(), 0.05));
fx.render();
});
Moves
A move is a complete attack, heal or warp: charge-up, travel, impact, lights and smoke. effect(recipe, element) makes its definition; fx.play() fires it and returns a handle whose hit events tell your game when to apply damage.
fx.play('fire-meteor', { from: hero.hand, to: enemy }).on('hit', (e) => enemy.damage(10 * e.power));
- 46 recipes, 11 elements. Magic (projectile, lance, beam, explosion, pillar, meteor, nova, barrier, shockwave, summon, missiles, tornado, storm, drill, torrent, pillars, nine, chain, bind, prison, pyramid), blade (slash, swipe, rising, cleave, combo, wave, dash, flurry, thrust, spin, cross, smash, iaido), fists and kicks (strike, rush, uppercut, kick, heel, palm, tackle, pound), support (heal, buff, warp) and events (finale), in plain, fire, ice, thunder, wind, earth, water, light, dark, poison and arcane.
plainhas no magic (metal sparks and dust), for games without spells;{ color: 0xff3355 }recolours any element. - Variations.
effect('meteor', 'fire', { seed: 'k3x9ab' })picks a variation. The easiest way to find one is the Motion mode of the tool: roll seeds, move the sliders, and copy the code under Use it from npm, which reproduces exactly what you see. - Anchors and events.
fromandtotake aVector3or anObject3D. Both are read every frame, so a moving object, or a vector you change in place, is followed. Hits carrypower, aroleand suggested shake and hit-stop values; warps sendvanishandappear. The hit count, power and timing of every move are inMOVESand in the table of the README. - Definitions.
fx.add()registers definitions to play by id. When they come and go (per enemy or per placed object), pass the definition tofx.play()instead;fx.has(id)andfx.remove(id)manage the added ones.
Status effects
Put a status on any mesh or animated character. Its textures stay, the pattern sticks to the surface while it animates, and the original materials come back when the status is gone.
await fx.prewarmStatus(enemyModel); // once per kind of model; it need not be in the scene
const frozen = fx.status(enemy, 'freeze', { duration: 1.2 });
frozen.on('full', () => (mixer.timeScale = 0)); // stopping the animation is up to you
frozen.stop(); // thaw; the ice shatters
Burn, freeze, shock, poison, petrify, dissolve, appear, bless, curse, shield and stun. progress (0–1) drives how far freeze, petrify and dissolve have spread; a shield ripples where you call impact(point). Statuses last until you stop them, or for lasts seconds (fx.status(enemy, 'burn', { lasts: 4 })); appear ends by itself. Browse them in the Status effects group of the Motion mode.
Placed effects
fx.loop('torch', new THREE.Vector3(2, 0, -3));
fx.loop('portal', gate.position, { rotation: Math.PI / 2, element: 'dark' });
const aura = fx.loop('aura', hero); // follows the character
aura.stop();
Torch (torch), campfire (campfire), candles (candles), portal (portal), magic circle (sigil), save point (savepoint), barrier dome (barrier), aura (aura) and beacon (beacon). They come with simple low-poly stands; pass prop: false to put the effect on your own model. Loops share a fixed pool of point lights (loopLights, 4 by default) because changing the number of lights makes three.js recompile every material.
React Three Fiber
import { FX, useFX, Status, Loop } from 'rollshade/react';
<Canvas gl={async (props) => { const r = new THREE.WebGPURenderer(props); await r.init(); return r; }}>
<FX effects={[effect('meteor', 'fire')]} feel>
<Status target={enemyRef} name="burn" active={burning} />
<Loop name="torch" position={[2, 0, -3]} />
</FX>
</Canvas>
useFX() returns the system once it has prewarmed, for fx.play(). Needs React Three Fiber 9 or later.
Coming from WebGLRenderer
rollshade is written in TSL, which only WebGPURenderer runs, so a game on the classic WebGLRenderer switches renderers first. You do not lose devices without WebGPU: WebGPURenderer falls back to WebGL2 by itself. Meshes, lights, standard materials, textures, GLTF models, skinning and animation, loaders, controls and raycasting carry over. What changes (checked against three r186):
- Imports. Your own
import * as THREE from 'three'becomes'three/webgpu'. Addons such asGLTFLoaderandOrbitControlsstay as they are: both builds share one core. - Start-up.
new THREE.WebGPURenderer({ antialias: true })takes the same size, tone mapping and shadow settings.await renderer.init()before the firstrender(), which throws otherwise. - Custom shaders.
ShaderMaterial,RawShaderMaterialandonBeforeCompiledo not run, not even on the WebGL2 fallback. Rewrite them as node materials with TSL: setcolorNode,emissiveNodeorpositionNodeon aMeshStandardNodeMaterialinstead of editing GLSL strings. - Addons built on shaders have node versions:
SkyMesh,WaterMesh,Water2Mesh,LensflareMesh,three/addons/lines/webgpu/for fat lines andreflector()for mirrors. - Post processing.
EffectComposerdoes not run. If it only did bloom, drop it and passpost: truetoFXSystem(post: { bloom: 'scene' }blooms everything bright, likeUnrealBloomPass;fx.glow(object)adds your own glowing objects to the default bloom). Other passes become TSL nodes in aTHREE.RenderPipelinewith effects fromthree/addons/tsl/display/; then passpost: false, which leaves out rollshade's bloom and camera shake.OutputPassneeds no replacement. - Small renames.
PCFSoftShadowMapis gone in r186 (usePCFShadowMap),Clockis deprecated in favour ofTimer, andrenderer.backend.isWebGPUBackendtells WebGPU from the fallback.
The step-by-step list with code is in the README under “Coming from WebGLRenderer”, and the three.js manual page “WebGPURenderer” gives the official overview.
With AI coding assistants
The package ships an agent skill at node_modules/rollshade/skills/rollshade/SKILL.md; install it for Claude Code, Cursor, Codex and others with npx skills add ./node_modules/rollshade/skills/rollshade. An overview for language models is at /llms.txt and the full reference at /llms-full.txt. Unknown names throw errors that list the valid ones, so an assistant can correct itself.
A request that works well: “Use the rollshade npm package for the spell effects in my three.js game. Read https://rollshade.tsuyatt.com/llms-full.txt first.” We tested it by having assistants with no prior knowledge build small games from these docs alone; what they stumbled on is now in the docs.
Performance
- Call
fx.prewarm()andfx.prewarmStatus()while loading so no shader compiles mid-game (this matters most on WebGL2). quality: 'auto'lowers particle counts and the render resolution while frames run over budget and raises them again;fx.setQuality('medium' | 'low')fixes them (75% and 55% resolution),'high'goes back to full and'auto'back to automatic, andfx.renderScalesets the resolution directly. Particles never grow past half the screen and fade near the camera.- Bloom covers only rollshade's effects, so bright models and floors do not blow out.
fx.glow(object)adds your own glowing parts (crystals, rings, edges) to it;post: { bloom: 'scene' }blooms the whole picture. For less glow, passpost: { strength: 0.2 }(default 0.3) or callfx.setBloom({ strength: 0.2 })at any time, for example from a settings menu. The Bloom slider in the Motion mode shows the difference and writes the option into the code. - If effects look too white even without bloom, pass
look: { core, hot, limit }or callfx.setLook():coreis how white the centre colour of each element is,hothow much the brightest parts turn white, andlimitcaps the brightness where effects overlap so they keep their colour (withpost). The defaults are{ core: 0.1, hot: 0.2, limit: 1.5 };{ core: 1, hot: 1, limit: 0 }is the whiter look of 0.4 and earlier.look: { particles }sets how many particles of every kind (flames, sparks, smoke…) the effects emit (default 0.25), andlook: { smoke }how much smoke (default 0.2, 0 = none).{ core: 1, hot: 1, limit: 0, smoke: 1, particles: 1 }brings back the look of 0.4 and earlier. The Motion mode has sliders for all of them. - With your own post processing, pass
post: falseand render as usual; you lose the built-in bloom and camera shake.
Part 2 · Exporting from the tool and the TSL shader lab
Every mode exports for the same shared runtime, rollshade-fx.js (also on npm as rollshade). The export area at the top of the right-hand panel works the same in every mode: Video…, Sprite sheet… and PNG save what you see, Download sample (.zip) gives you a project that runs with a double-click, and Project saves or reopens your work as a .json file. The Shader modes write a TSL module that does export default defineLoop(...): node materials, the meshes the effect needs and its bloom settings.
Set up the renderer
npm install three
The quickest start is Download sample (.zip): it holds the runtime, the effect as fx/<id>.js, an fx/index.js that imports it, a runnable example.html with the same code as example.js, a README.md and LICENSE.txt. To add an effect to your own project, copy the runtime and the definition (Definition .js and Runtime .js under Files) next to your script:
import * as THREE from 'three/webgpu';
import { FXSystem } from './rollshade-fx.js';
import fire from './fx/fire-loop-k3x9ab.js';
const renderer = new THREE.WebGPURenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
document.body.append(renderer.domElement);
await renderer.init();
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(35, innerWidth / innerHeight, 0.05, 100);
camera.position.set(0, 1.6, 6);
camera.lookAt(0, 0.75, 0);
const fx = new FXSystem({ scene, camera, renderer, post: true });
fx.add(fire);
Import everything from three/webgpu, not from three. Loading both copies in one page breaks node materials. The definition imports its helpers from ../rollshade-fx.js; if you use the npm package instead, change that import to 'rollshade'.
A standalone effect
const h = fx.spawn(fire.id, { at: new THREE.Vector3(0, 0, 0) });
const timer = new THREE.Timer();
renderer.setAnimationLoop((ms) => {
timer.update(ms);
fx.update(Math.min(timer.getDelta(), 0.05));
fx.render();
});
The effect stands on the ground at at and is about two units tall. at can also be an Object3D, which the effect follows; h.moveTo() moves it later and scale in the spawn options resizes it. Place as many as you like: they share one render pass and one bloom with the Motion effects, and the helpers are never duplicated.
An effect on a model
Effects made in Shader on a model take the object to decorate:
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
const gltf = await new GLTFLoader().loadAsync('hero.glb');
scene.add(gltf.scene);
scene.environment = myEnvironmentMap;
const h = fx.spawn(aura.id, { object: gltf.scene });
- Every mesh inside
objectgets a node material that keeps its color, texture, normal map, roughness and transparency, with the effect layered on top. Meshes with several materials get the effect on each of them. - Shells, outlines, ground effects and particles are sized from the model's bounding box, measured when you call
spawn. Add the model to the scene and place and scale it first. - Skinned and morphing models keep animating. Shells and outlines follow the animation, and surface patterns stay attached to the skin.
- The surface layers use standard materials, so they need light: give the scene lights or an environment map. The preview uses a key light, a hemisphere light and
RoomEnvironmentat 0.45.
Time and the loop
fx.update(seconds) advances every placed effect, and each one sets its phase to (time / period) % 1. Every moving part repeats exactly once per period, so the effect always loops seamlessly. The period defaults to the loop length you picked in Rollshade; pass period to fx.spawn to change it. h.pause() and h.resume() stop and restart one effect, and setting h.time scrubs it.
Motion effects
Effects from the Motion mode are built differently from the other modes. Instead of one file that holds everything, you get two kinds of files:
- The shared runtime
rollshade-fx.js. Particles, lights, post processing and the scheduler live here. You need one copy no matter how many effects you use. - One definition per effect,
fx/<id>.js. A few hundred bytes with the recipe, element and tuned values.
Download sample (.zip) packs the runtime, its types, the chosen effects, an fx/index.js that imports them all, a runnable example.html with the same code as example.js, a README.md and LICENSE.txt. example.html opens straight from the folder with a double-click; no local server is needed. To put several effects in one sample, press Add this one under Several in one sample for each of them, then download them together.
import * as THREE from 'three/webgpu';
import { FXSystem } from './rollshade-fx.js';
import effects from './fx/index.js';
const fx = new FXSystem({ scene, camera, renderer, post: true, feel: true });
fx.add(...effects);
await fx.prewarm();
const h = fx.play('fire-projectile-k3', { from: hero.hand, to: enemy });
h.on('hit', (e) => enemy.damage(10 * e.power));
const timer = new THREE.Timer();
renderer.setAnimationLoop((ms) => {
timer.update(ms);
fx.update(Math.min(timer.getDelta(), 0.05));
fx.render();
});
- Play as often as you like. Every
fx.play()starts a new instance and returns its own handle. Spamming one effect or firing different ones together all share one set of particle buffers and one post pass. - Aiming.
fromandtoaccept aVector3or anObject3D; anObject3Dis followed while it moves. For melee effects pass the character's chest asfrom. The blade position is written toh.blade.baseandh.blade.tipevery frame so you can move your own sword model with it. - Events.
h.on(name, fn)takes'cast'(charge starts),'release'(fired or swung),'hit'and'end'(the move is over; its last particles may still be fading).barrier,buffandwarpsend no hit. Callingh.stop()orfx.clear()inside a handler is safe, and an error in your handler does not stop the effects. A hit carries the point, the power, suggested shake and hit-stop values and arole('first','link','final'or'tick'); multi-hit moves suggest a full stop only on the first and final hits. Drive collisions and damage from it. Heals send a hit with power 0 at the moment the heal lands. Warp sends'vanish'(where the caster disappears) and'appear'(where they reappear); move your character on those. - Screen effects are opt-in.
feel: trueapplies camera shake, hit-stop and chromatic aberration on hits. Without it nothing touches your camera; use the suggested values yourself (or callfx.shake()andfx.hitStop()).post: truerenders through a pipeline with bloom and distortion. If you already have post processing, passpost: falseand render as usual instead of callingfx.render(). - Call
prewarm()once. It compiles every shader while loading. Without it the first use of each part stalls for a frame. - Performance. Particles never grow past half the screen height (
maxScreenSize, default 0.5) and fade out between 0.4 and 1.4 m from the camera (nearFade). Withquality: 'auto'the runtime lowers particle counts, and withpostthe render resolution, when frames keep running over budget (frameBudget, default 1/58 s) and raises them again once things are light. AddautoResolution: trueto let it change the renderer pixel ratio as well; that affects your whole scene, so leave it off if you manage resolution yourself. - Time. Pass the seconds since the last frame to
fx.update().fx.timeScalegives slow motion, and hit-stop slows every running effect together. - Photosensitivity.
photosensitive: truetones down screen flashes. One-frame inverted impact frames (impactFrames) are off by default. - Cleanup.
fx.clear()stops everything that is playing;fx.dispose()frees the GPU resources.
Sprite sheets for 2D games
Sprite sheet… plays the effect once and lays every frame out in one PNG. The dummies, the sword and the floor are left out; only the effect remains. For freeze, petrify, dissolve and appear, which change the body itself, tick Include the dummy.
- Part. The whole attack, or one part of it: cast, projectile (a loop), impact, target circle, beam, swing or main. Which parts there are depends on the move.
- Camera. Current view, side (for side-scrollers), oblique 30°, 45° or 60°, behind the caster, top-down (for top-down games), isometric 2:1 or a high three-quarter angle. Status and placed effects offer a front view instead of behind the caster. Every preset except the current view uses a long lens, so there is almost no perspective distortion. Zoom adjusts the framing.
- Size and timing. Frames sets how many frames the sheet has, Fade-out how much of the fading tail is kept, Scale either fits the effect to the frame or fixes 1 m to a number of pixels, and Wide frames makes 2:1 cells for long effects. A projectile can be exported in 1, 8 or 16 Directions.
- Style. HD, Pixel art (colour count, palette, dithering, outline) or Anime (cel) (tones, outlines, line boil).
- Background. Transparent renders each frame on black and on white and derives alpha from the difference, so both glows and smoke keep their partial transparency. Black suits engines that draw the sprite with additive blending.
- JSON. TexturePacker hash format, read directly by Phaser's
load.atlasand PixiJSAssets.load.animationsholds the frame order,meta.fpsthe frame rate andmeta.hitFramesthe frames where hits land, so you can apply damage on those frames. Depending on the options,metaalso haspart,pivot,pixelsPerMeteranddirections. - Loops. The projectile part of flying moves, the
mainpart of the power-up aura, the storm and the tornado, and status and placed effects are exported as seamless loops (meta.loopis true). Repeat them for as long as the effect lasts in your game.
Video
Video… plays the effect once from the start and writes WebM, MP4 or numbered PNGs. Choose the size and frame rate, the Part (the camera then centres on that part and follows a projectile), the Camera (the preview's view or the sprite sheet views), Zoom, the Background (the scene with floor and fog, black, or transparent, which needs WebM or PNG) and whether to show the caster and target. In the Shader modes it records whole loops instead (choose the length) and can turn the camera once per loop.
PNG and project files
PNG saves the current view at the chosen size (the long side, in pixels). Save .json under Project writes everything you set up, in every mode, and Open .json brings it back.
Bloom and your render loop
With post: true, fx.render() renders the scene and adds bloom only to the effects, so the rest of your scene does not glow. With Bloom ticked under Include, the definition carries the bloom settings you tuned, and the runtime uses the strongest of the effects that are placed. fx.setBloom() changes it while running.
If you already have your own post-processing, create the system with post: false and render as usual with renderer.render(scene, camera) or your own pipeline. The effect still writes its glow to the emissive output, so a bloom pass that reads emissive picks it up.
Adjusting the effect at runtime
h.uniforms holds the sliders from the Layers panel, named after the layer:
h.uniforms.flame1Intensity.value = 2;
h.uniforms.flame1Color.value.set('#ff8800');
Changing a uniform does not rebuild any shader, so it is cheap to animate every frame.
Removing the effect
h.stop();
stop puts the original materials back on the model, removes the meshes and particles the effect added and frees its GPU resources. fx.dispose() frees everything the system made.
Models without UVs
Some patterns can follow a mesh's UV layout. With Coordinates set to Auto, the code checks each mesh and uses its UVs when it has them and its positions when it does not, so models without UVs still work. If you know your models, choose UV only or Position only under Include to remove that branch from the code. Most patterns use positions in any case, so they stay attached to the surface and need no UVs.
What to include
- Material: the patterns on the model's own surface.
- Shell & outline: glowing shells around the model and outlines behind it.
- Elements & particles: flames, glows, magic circles, rings and particles.
- Bloom: the bloom settings described above.
The preview follows these switches, so what you see is what the code does.
TypeScript
The code is JavaScript. The sample carries rollshade-fx.d.ts (and the npm package its own types), so editors and TypeScript projects get types for the runtime; allow JavaScript files (allowJs) to import the definitions from TypeScript.
Troubleshooting
- Nothing appears. Wait for
await renderer.init()before the first frame, and check that all imports come fromthree/webgpuandthree/tsl(a hand-written import map also needsthree/addons/). three/addons/…cannot be found. That path maps tothree/examples/jsm/…inside the three package. Bundlers such as Vite resolve it; with an import map, mapthree/addons/to that folder.- It looks brighter or darker than the preview. The preview uses ACES Filmic tone mapping, a key light and an environment map. Match those, or adjust the intensity uniforms.
- It is slow on phones. Particle counts and noise octaves are plain numbers in the code; lower them, or reduce the pixel ratio.
- Flashing. Effects can flicker. Keep flashes to three per second or fewer for people who are sensitive to light; a longer loop period lowers the rate.
License
Everything you export from Rollshade (effect definitions and code, sprite sheets, images and videos) is released under CC0 1.0: no conditions, no credit needed. Use it, modify it, share it or sell it, commercial or not. The shared runtime (rollshade-fx.js, also on npm as rollshade) is under the MIT License, so keep its copyright notice. The helper functions based on psrdnoise are MIT too; keep the notice at the top of the file. three.js is MIT. Every ZIP carries LICENSE.txt. Models shown in images and videos keep their own license: the preset Rollpoly models are CC0 1.0 as well. See License and Terms of Use for the details.