Animation · project 33 of 37

Dot and the Shape Friends.

A narrated 3D game for little ones: lines, flat shapes and solid shapes as characters to tap, pop, dress up and feed to Munchy.

Open the project ↗Get the skill and the code
After: Shapes with faces to tap, pop, dress up and feed to a monster, with a narrator who says what to do. Before: A worksheet that asks a four-year-old to tell a square from a cube.

BeforeA worksheet that asks a four-year-old to tell a square from a cube.

AfterShapes with faces to tap, pop, dress up and feed to a monster, with a narrator who says what to do.

What it is worthLines, flat shapes and solids learned by playing, with no reading needed. Instead of flashcards and a definition nobody remembers.

More like this: games to play ›

How to use it

  1. Press play with the sound on (it plays even when an iPhone or iPad is on silent) and hand it over: on a tablet it goes full screen by itself, everything is tapping, and the narrator says what to do. Dot's story comes first and teaches the idea.
  2. Then the star for the pop-up shelf, the purple monster to feed Munchy (tap him, or rub him to tickle), and the magnifying glass: 19 shapes wait there in four teams on coloured mats. Tap a team (its mat, any of its shapes or its button at the top) and a big window shows that team's shapes; pick one to put it on the stand, then turn it over and press 1D, 2D or 3D. The music note starts a dance, a light show or a party; the gift is a surprise any time.
  3. Grown-ups: hold the gear for a second (a quick tap does nothing, so little hands can't change settings). Inside are the full-screen switch, a name box for the "Good job!" line, the finger moves (in the look-closely place one finger spins the view and two fingers pinch to zoom; three fingers change place) and the music and voice switches. The cloud button turns fart mode on or off.
  4. On an iPad or iPhone, tap "Make it a full-screen app" and follow the four pictures to add it to the Home Screen: from there it always opens full screen. Guided Access (Settings, Accessibility) keeps the iPad in the game.

Where it helps most

  • A first look at shapes and dimensions for a child of three to six, on a phone or tablet.
  • A pattern for any lesson for little ones: characters, one idea per place, short spoken lines and a reward for every tap.
  • A starting point for a narrated three.js game with recorded voice, live music and multi-finger gestures.

The idea

I wanted to show a preschooler what 1D, 2D and 3D mean without a single definition: something that talks, surprises and rewards tapping, where every shape is a character and the lesson is hidden inside the play.

The build

Claude built it in three.js after a first slider version I found far too weak. Every shape is a glossy toy with a face that blinks and looks around. Three places teach one idea each: Dot's story turns a dot into a line, a square and a cube as the child taps (the square turns sideways and vanishes, which is flat versus solid in one joke); the shelf pops flat shapes into the solids that belong to them, each with its own trick and real-world costumes; and Munchy's mouth changes between a circle, a square and a triangle so the child finds the flat shape hiding on each solid. Every line is narrated with the Kokoro "Heart" voice, recorded ahead into small MP3 clips, and the music and sound effects are played live in the browser, all in one key so they blend. The places flow into each other on their own (story, shelf, Munchy, look closely). A fourth place puts one see-through shape on a stand, with all eight solids shown around it and buttons to build a solid from a circle, square or triangle base (straight up or to a point): one finger spins the view all the way around it (keep going and it turns over to show the bottom, a flick lets it coast), two fingers pinch to zoom in and out, a tap flips it, and the 1D, 2D and 3D buttons squeeze it into a flat drawing or a line and back. The music-note button switches between three dance modes, each with its own music and lighting: dancing in daylight, a night light show with glowing shapes, and a party with a disco ball and light beams. Munchy has his own voice (the Kokoro "Puck" voice, played a little lower), arms, googly eyes that wobble with every move, and a stage so his mouth is never hidden. Each right choice is praised by name (the name is typed once under the gear and kept on the device). After a meal he laughs, dances and sings (a vowel-filtered voice made live in the browser), or, only when the fart-mode button is on, toots: seven kinds, each with its own sound, puff colour and stink level, up to a super-stinky one that sends flies buzzing and makes the shapes faint. Rubbing him tickles, and five laughs start a giggle party. One finger spins the view only in the look-closely place; three-finger swipes change place; stars and found shapes are kept on the device. The look-closely place holds every shape the game knows, 19 in all, harder ones included (a dome, an egg, hexagonal, pentagonal and star prisms, pentagon and hexagon pyramids, and gems with 8, 12 and 20 faces), sitting in four teams on coloured mats; a team is picked as a whole (its mat, any of its shapes or its button), and a big window shows its shapes as large 3D pictures to choose from, because the shapes on the mats are too small for little fingers. On a tablet it goes full screen when Play is pressed, and if the browser lets go (a pinch, a swipe down, its close button) the next tap puts it back; only the grown-ups' switch, behind a gear that has to be held for a second, turns that off. A picture guide shows how to add it to an iPad or iPhone Home Screen, where it runs as an app that is always full screen. On iPhone and iPad the sound plays even on silent: the first tap asks iOS for playback audio (a tiny looping silent clip does it on older iPhones), and every tap or return to the page wakes the sound if the phone paused it. Nothing is downloaded but the page, the voices and three.js.

Free to take

Build your own.

Copy the skill, paste it into your own AI, and say what you want different. How to use a skill, step by step ›

Get the skillThe instructions your AI follows. Works in Claude, ChatGPT, Gemini or any other

# Master prompt: Dot and the Shape Friends

You are a children's game designer and creative coder. Build "Dot and the Shape Friends": a narrated 3D tap-and-play web game that teaches a 4-year-old the difference between a line (1D), a flat shape (2D) and a solid shape (3D), with no reading needed. three.js r128 from a local file, no inline scripts or styles (it must run under a strict Content-Security-Policy), one page, works on a phone, a tablet (iPad first), a laptop and a TV.

WORLD AND LOOK
A bright toy meadow built from the shapes it teaches: cone and sphere trees, a cube house with a pyramid roof, pyramid mountains, half a donut as a rainbow, grass blades, flowers, a smiling sun, soft shadows, a rim light and a gentle vignette. Every shape is a glossy plastic toy with rounded edges and a face: blinking eyes that look around, a smile and rosy cheeks. Picture buttons only, no words for the child to read. Rounded Fredoka font for captions.

FOUR PLACES THAT FLOW INTO EACH OTHER ON THEIR OWN
1) Dot's story: a tiny dot grows into a long thin line, a square, then a cube, three taps per step; the square turns sideways and vanishes (flat versus solid in one joke); confetti when it becomes a cube. When the story ends the game moves on by itself.
2) Pop-up shelf: a flat circle, square and triangle on a shelf; tapping one inflates a solid from its family (circle: sphere, cylinder, cone, donut; square: cube, brick; triangle: prism, pyramid). Each solid names itself, does a trick that shows what it can do (roll, flop, spin on its point, slide) and on the next taps dresses up as real things (beach ball, drum, ice cream, present, dice, bus, cake, tent, cheese, snowy mountain). A sticker row fills as the eight are found, with stars that fly to a counter; after all eight it moves on to Munchy.
3) Munchy: three solids wait in front of a friendly monster whose mouth is a circle, square or triangle; only the solid with that flat shape on it fits. Feeding is forgiving: a tap, a sloppy tap or any drag picks a shape. A wrong one bonks off kindly with the reason; after a wrong try the right one hops and an arrow points at it. Every right choice says "Yes! Good job, <name>!" (the name is typed once by a grown-up and kept on the device; ship no default name). After eight feeds it moves on to the look-closely place.
4) Look closely (magnifying glass): one see-through shape (clear glass with bright edges drawn on top, so the back and bottom edges show) on a stand under a soft light beam. Around it sit 19 shapes in four teams, each on its own matte coloured mat with a name sign: the Round team (sphere, dome or hemisphere, egg, cylinder, cone, donut), the Stack team (cube, brick, triangular prism, hexagonal prism, pentagonal prism, star prism), the Pointy team (square, triangle, pentagon and hexagon pyramids) and the Gem team (octahedron, dodecahedron, icosahedron). On wide screens the mats stand in a horseshoe beside and behind the stand; on a tall phone they sit two by two on the grass in front of it so the shapes stay big. The shapes on the mats are too small for little fingers to pick one by one, so a team is picked as a whole: tapping its mat, its sign, any of its shapes or one of four team buttons (which replace the shape chips) names the team ('The gem team! Lots of flat sides, like jewels.'), makes its shapes hop and opens a big window with one large button per shape: a real 3D picture of the shape with its face (rendered once into an image), and its name. Rows stay even (three by two for six, two by two for four, one row on short screens, two per row under 360 px); the tap that opened the window must not pick in it, so clicks are ignored for half a second. Picking closes the window and puts the shape on the stand with its name spoken; the X or a tap outside closes it. Big 1D / 2D / 3D buttons squeeze it flat toward the viewer (2D, its drawing) or to a thin line (1D) and back, with the narrator naming each. Build buttons make a solid from a circle, square or triangle base, pulled straight up or to a point (cylinder, cone, cube, pyramid, triangular prism and pyramid).

MUNCHY
An original character (not borrowed from any film): purple, big googly eyes whose pupils move on a spring and bounce with every move (huge and loose on cue), little fangs, a hair tuft, spots, arms that wave, hold his tummy when he laughs and dance, sunglasses at the party, and a small stage under him so his mouth shape always shows above the shapes. His own recorded voice, played a little lower than the narrator. After a meal he laughs (shake, squint, happy tears), dances and sings 'la la la' (a sawtooth through two vowel band-pass filters with vibrato, over a drum beat) or shows his googly eyes. Rubbing him tickles; a giggle meter fills with each laugh and five laughs start a giggle party.
Fart mode: a cloud button, off at the start. Only when it is on, Munchy sometimes toots after a meal: seven kinds (tiny, squeaky, bubbly, trumpet, machine-gun, super-stinky with a dark cloud, buzzing flies and fainting shapes, and a singing toot with rainbow puffs), each with its own made-live sound, puff colour and stink level. With fart mode off there are no toots anywhere.

DANCE MODES
A music-note button cycles: dance (daylight, everyone dances on the beat), light show (night, moon and stars, glowing shapes, slow coloured lights), party (disco ball, turning light beams, confetti on the beat, no flashing), then back to normal. Each mode has its own tempo and music.

VOICE: ONE AT A TIME, ALWAYS
Every line is short and warm, shown as a caption with a small grown-up line under it (1D, 2D, 3D, the proper names). Record every line ahead with Kokoro (kokoro-onnx, free and offline): narrator "af_heart", Munchy "am_puck". Trim the silence, match the loudness, save small MP3s named by a hash of the line, list them in the game (line to file) and play them through Web Audio. Fall back to the device voice only if a clip is missing.
All speech goes through one queue so the narrator and Munchy never talk over each other under any circumstances: the line being spoken always finishes; instructions and praise wait their turn; Munchy's dance line and song are never dropped; small chatter is skipped if someone is already speaking and goes stale after 4 seconds; changing place drops what was still waiting. A watchdog ends a line whose audio never reports that it ended. Music ducks while anyone speaks.

MUSIC AND SOUND
A gentle eight-bar tune (C, A minor, F, G) with marimba, pad and a soft melody, made live with Web Audio through a compressor and a little reverb. Every sound effect is a mallet, spring or pop tuned to the same key so nothing clashes.
Sound on iPhone and iPad: in the first tap, set navigator.audioSession.type = 'playback' before any sound (where navigator.audioSession is missing on an iPhone, loop a one-second silent same-origin MP3 in an <audio> element instead), create and resume the AudioContext there, and resume it again on every tap and whenever the page becomes visible, so it plays on silent and after the screen locks. The grown-ups panel says: 'No sound? Turn the volume up with the side buttons and tap the screen once.'

FINGERS, MOUSE AND KEYS
Everywhere: one finger taps and drags a friend into Munchy's mouth, but never turns the world. Three fingers: tap for a surprise, swipe sideways to change place, swipe up to make everyone jump, swipe down to reset the view.
In the look-closely place only: one finger spins the view freely all the way around the shape; past the top or bottom of the camera's range the shape itself keeps turning over, so the turn never stops and the bottom shows; a quick flick coasts and slows down, holding still before lifting does not. Two fingers only pinch to zoom in and out; lifting one of two fingers lets the other keep spinning. A tap flips the shape over. Mouse drag or trackpad scroll spins, trackpad pinch zooms; keys: arrows turn, + and - zoom, 1 to 4 change place, D dances, F fart mode, space is a surprise.

SURPRISES
A gift button, and tappable sun and clouds: shape rain, a dance party, giant or tiny shapes, googly eyes, a spin round the world, a group sneeze. Tapping the grass sparkles.

GROWN-UPS AND THE DEVICE
Title screen with a big play button and a loading bar for the voices. Full screen that stays: on a touch tablet, Play goes full screen; if the browser drops out (a pinch, a swipe down, its close button), the next tap anywhere puts it back, and a back swipe does not leave the game; only the grown-ups' 'Keep full screen' switch (remembered on the device, off by default on computers) stops it. A grown-ups panel opens only when the gear is held for a moment (a quick tap just says 'Grown-ups: hold the gear'): full screen switch, music and voice switches, the name box for 'Good job', the finger and key list. A 'Make it a full-screen app' button on iPad and iPhone opens a picture guide (Share, Add to Home Screen, keep Open as Web App on, open it from the Home Screen) with a tip on Guided Access to lock the device to the game; on Android and desktop Chrome it uses the browser's own install prompt. Opened from the Home Screen it is always full screen and hides those buttons. Keep stars, found shapes and the name in the browser only (a Home Screen app keeps its own). A web-app manifest, icons and a translucent status bar with safe-area padding. Respect prefers-reduced-motion. Free every geometry, material and texture a removed shape or costume used, so a long session does not grow.

TEST BEFORE SHARING
Every screen from 320 px phones to 1920 px desktops, sideways phones and iPads (no button covering a shape or Munchy's mouth); a long random-tapping session (memory flat, no errors); a full playthrough (story, eight shapes, eight feeds, stars kept after a reload); and a voice test that taps fast while lines are queued, checking that no two lines ever overlap.
Get the code5 files, exactly as they run on this site · free under the MIT license

The first four files are exactly what runs at sghadimi.com/shapes. The page needs three.js r128 loaded before game.js, the three Fredoka font files in fonts/ (SIL Open Font License) and the voice clips in v/. Make the clips yourself with voices.py and the free Kokoro voices: python3 voices.py check game.js lists what is missing, python3 voices.py record game.js records it and updates the voice lists inside game.js. Without clips, every line still shows as a caption and the device voice reads it.

game.js (the whole game)1,615 lines

Raw file

/* Dot and the Shape Friends. Needs three.js r128 loaded first. Voice clips live in v/. */
(function(){
'use strict';
function $(id){return document.getElementById(id);}
var T=window.THREE,canvas=$('c'),R=null;
if(T){try{R=new T.WebGLRenderer({canvas:canvas,antialias:true,alpha:true});}catch(e){R=null;}}
if(!R){$('fail').hidden=false;$('start').hidden=true;return;}

var PI=Math.PI,rnd=Math.random;
function pick(a){return a[Math.floor(rnd()*a.length)];}
function shuffle(a){a=a.slice();for(var i=a.length-1;i>0;i--){var j=Math.floor(rnd()*(i+1)),t=a[i];a[i]=a[j];a[j]=t;}return a;}
function clamp(v,a,b){return Math.max(a,Math.min(b,v));}
var reduce=window.matchMedia('(prefers-reduced-motion: reduce)').matches;

/* ---------- sound: every effect is tuned to the key of the music ---------- */
var AC=null,out=null,sfxG=null,musG=null,voG=null,rev=null,muted=false,musicOn=true,MUS=.6,N=null;
/* iPhone and iPad: Web Audio follows the silent switch unless the page asks for "playback" audio, and iOS
   pauses the audio when the screen locks or the tab goes to the back. Ask for playback on the first tap (a looping
   silent clip does it on iPhones without navigator.audioSession), and wake the audio on every tap and on return. */
var silentEl=null,IOSDEV=/iPad|iPhone|iPod/.test(navigator.userAgent||'')||(navigator.platform==='MacIntel'&&navigator.maxTouchPoints>1);
function iosUnlock(){
  try{if(navigator.audioSession&&navigator.audioSession.type!=='playback')navigator.audioSession.type='playback';}catch(e){}
  if(!('audioSession' in navigator)&&IOSDEV){
    try{
      if(!silentEl){silentEl=new Audio('audio/silence.mp3');silentEl.loop=true;silentEl.setAttribute('playsinline','');}
      if(silentEl.paused){var p=silentEl.play();if(p&&p.catch)p.catch(function(){});}
    }catch(e){}
  }
}
function wake(){
  iosUnlock();
  var C=window.AudioContext||window.webkitAudioContext;
  if(AC&&C&&AC instanceof C&&AC.state!=='running'){try{var p=AC.resume();if(p&&p.catch)p.catch(function(){});}catch(e){}}
}
['pointerdown','touchend','click','keydown'].forEach(function(t){document.addEventListener(t,wake,{passive:true,capture:true});});
document.addEventListener('visibilitychange',function(){if(!document.hidden)wake();});
function audioInit(ctx){
  if(AC)return;
  try{
    var C=window.AudioContext||window.webkitAudioContext;AC=ctx||new C();
    var comp=AC.createDynamicsCompressor();comp.threshold.value=-16;comp.knee.value=12;comp.ratio.value=4;comp.connect(AC.destination);
    out=AC.createGain();out.gain.value=.9;out.connect(comp);
    sfxG=AC.createGain();sfxG.gain.value=.55;sfxG.connect(out);
    musG=AC.createGain();musG.gain.value=MUS;musG.connect(out);
    voG=AC.createGain();voG.gain.value=1.3;voG.connect(out);
    var len=Math.floor(AC.sampleRate*1.8),ir=AC.createBuffer(2,len,AC.sampleRate);
    for(var c=0;c<2;c++){var d=ir.getChannelData(c);for(var i=0;i<len;i++)d[i]=(rnd()*2-1)*Math.pow(1-i/len,3);}
    rev=AC.createConvolver();rev.buffer=ir;var rg=AC.createGain();rg.gain.value=.2;rev.connect(rg);rg.connect(out);
  }catch(e){AC=null;}
}
function m2f(n){return 261.63*Math.pow(2,n/12);}
var PENT=[12,14,16,19,21,24];
/* a soft mallet, like a marimba or a music box */
function mallet(f,o){
  if(!AC)return;o=o||{};
  var t=o.t||(AC.currentTime+(o.at||0)),v=o.vol||.3,d=o.d||.5,dest=o.dest||sfxG;
  if(dest===sfxG&&muted)return;
  var g=AC.createGain();g.gain.setValueAtTime(.0001,t);g.gain.exponentialRampToValueAtTime(v,t+.005);g.gain.exponentialRampToValueAtTime(.0001,t+d);
  g.connect(dest);if(rev&&!o.dry)g.connect(rev);
  var a=AC.createOscillator();a.type=o.type||'sine';a.frequency.setValueAtTime(f,t);if(o.to)a.frequency.exponentialRampToValueAtTime(o.to,t+d*.8);
  a.connect(g);a.start(t);a.stop(t+d+.05);
  if(!o.soft){
    var b=AC.createOscillator(),bg=AC.createGain();b.frequency.value=f*4;bg.gain.setValueAtTime(.3,t);bg.gain.exponentialRampToValueAtTime(.0001,t+Math.min(.12,d*.3));
    b.connect(bg);bg.connect(g);b.start(t);b.stop(t+.2);
  }
}
function hiss(d,o){
  if(!AC)return;o=o||{};var dest=o.dest||sfxG;if(dest===sfxG&&muted)return;
  var t=o.t||(AC.currentTime+(o.at||0)),n=Math.floor(AC.sampleRate*d),b=AC.createBuffer(1,n,AC.sampleRate),ch=b.getChannelData(0);
  for(var i=0;i<n;i++)ch[i]=rnd()*2-1;
  var s=AC.createBufferSource();s.buffer=b;
  var f=AC.createBiquadFilter();f.type=o.ft||'bandpass';f.frequency.setValueAtTime(o.f||1200,t);
  if(o.fto)f.frequency.exponentialRampToValueAtTime(o.fto,t+d);
  var g=AC.createGain();g.gain.setValueAtTime(o.vol||.2,t);g.gain.exponentialRampToValueAtTime(.001,t+d);
  s.connect(f);f.connect(g);g.connect(dest);s.start(t);
}
function tone(f,d,o){o=o||{};mallet(f,{at:o.at,vol:o.vol||.25,d:d,to:o.to,type:o.type&&o.type!=='sine'?'triangle':'sine'});}
function noise(d,o){hiss(d,o);}
function spring(f1,f2,d,v){
  if(!AC||muted)return;
  var t=AC.currentTime,o=AC.createOscillator(),g=AC.createGain(),lf=AC.createOscillator(),lg=AC.createGain();
  o.frequency.setValueAtTime(f1,t);o.frequency.exponentialRampToValueAtTime(f2,t+d);
  lf.frequency.setValueAtTime(22,t);lf.frequency.linearRampToValueAtTime(9,t+d);lg.gain.value=f1*.12;lf.connect(lg);lg.connect(o.frequency);
  g.gain.setValueAtTime(.0001,t);g.gain.exponentialRampToValueAtTime(v,t+.01);g.gain.exponentialRampToValueAtTime(.0001,t+d);
  o.connect(g);g.connect(sfxG);if(rev)g.connect(rev);o.start(t);o.stop(t+d+.05);lf.start(t);lf.stop(t+d+.05);
}
function fartTone(o){
  if(!AC||muted)return;
  var t=AC.currentTime+(o.at||0),l=o.d||.6,f0=o.f0||(70+rnd()*45),f1=o.f1||f0*(rnd()<.5?.7:1.4);
  var os=AC.createOscillator(),f=AC.createBiquadFilter(),g=AC.createGain(),lf=AC.createOscillator(),lg=AC.createGain(),pf=AC.createOscillator(),pg=AC.createGain();
  os.type=o.w||'sawtooth';os.frequency.setValueAtTime(f0,t);os.frequency.linearRampToValueAtTime(f1,t+l);
  pf.frequency.value=5+rnd()*6;pg.gain.value=f0*(o.pd==null?.22:o.pd);pf.connect(pg);pg.connect(os.frequency);
  f.type='lowpass';f.Q.value=6;f.frequency.setValueAtTime(o.cut||760,t);f.frequency.linearRampToValueAtTime((o.cut||760)*.45,t+l);
  var v=o.vol||.32;g.gain.setValueAtTime(.0001,t);g.gain.exponentialRampToValueAtTime(v,t+.02);g.gain.setValueAtTime(v*.9,t+l*.72);g.gain.exponentialRampToValueAtTime(.0001,t+l);
  lf.frequency.value=o.lr==null?22+rnd()*16:Math.max(.1,o.lr);lg.gain.value=o.ld==null?.17:o.ld;lf.connect(lg);lg.connect(g.gain);
  os.connect(f);f.connect(g);g.connect(sfxG);
  [os,lf,pf].forEach(function(x){x.start(t);x.stop(t+l+.05);});
}
var FARTS={
  tiny:{say:'Pip! A teeny tiny toot!',stink:1,col:0xfff0a0,n:2,size:.5,snd:function(){fartTone({f0:150,f1:120,d:.22,cut:1100,ld:.12,vol:.22});}},
  squeaky:{say:'Squeak! A squeaky toot!',stink:1,col:0xffb3d8,n:3,size:.55,snd:function(){fartTone({f0:360,f1:580,d:.6,cut:2600,lr:34,ld:.2,vol:.18,w:'square',pd:.06});}},
  bubbly:{say:'Blub, blub! A bubbly toot!',stink:2,col:0xbdf0a0,n:8,size:.42,snd:function(){for(var i=0;i<11;i++)fartTone({f0:80+rnd()*140,f1:70+rnd()*90,d:.05+rnd()*.05,cut:700,lr:1,ld:0,vol:.26,at:i*.075});}},
  trumpet:{say:'Toot, toot! A trumpet toot!',stink:2,col:0x9bd65a,n:5,size:.7,snd:function(){fartTone({f0:120,f1:118,d:.18,cut:1500,ld:.1,vol:.3});fartTone({f0:126,f1:122,d:.18,cut:1500,ld:.1,vol:.3,at:.26});fartTone({f0:118,f1:76,d:.75,cut:1300,ld:.22,vol:.33,at:.52});}},
  machine:{say:'Rat-a-tat! A machine toot!',stink:2,col:0x8fd14f,n:6,size:.6,snd:function(){for(var i=0;i<8;i++)fartTone({f0:95+rnd()*45,f1:78,d:.075,cut:950,lr:1,ld:0,vol:.3,at:i*.1});}},
  rumble:{say:'Pee-yew! Super stinky!',stink:3,col:0x6f7f24,n:10,size:1.15,snd:function(){fartTone({f0:58,f1:43,d:1.9,cut:430,lr:17,ld:.32,vol:.46});hiss(1.6,{f:170,vol:.08,ft:'lowpass'});}},
  singing:{say:'A singing toot! La la la!',stink:0,col:-1,n:7,size:.6,snd:function(){[0,4,7,12,7,4,0].forEach(function(n,i){fartTone({f0:m2f(n-24),f1:m2f(n-24)*1.01,d:.17,cut:1700,lr:6,ld:.04,vol:.3,at:i*.19,pd:.02});});}}
};
var FKINDS=['tiny','squeaky','bubbly','trumpet','machine','rumble','singing'];
/* Munchy sings: a sawtooth voice through two vowel filters, "la la la" */
function singNote(f,t,d,vol){
  var o=AC.createOscillator(),vb=AC.createOscillator(),vg=AC.createGain(),g=AC.createGain(),f1=AC.createBiquadFilter(),f2=AC.createBiquadFilter();
  o.type='sawtooth';o.frequency.value=f;vb.frequency.value=5.5;vg.gain.value=f*.022;vb.connect(vg);vg.connect(o.frequency);
  f1.type='bandpass';f1.Q.value=5;f1.frequency.setValueAtTime(380,t);f1.frequency.linearRampToValueAtTime(760,t+.07);
  f2.type='bandpass';f2.Q.value=6;f2.frequency.value=1150;
  o.connect(f1);o.connect(f2);f1.connect(g);f2.connect(g);
  g.gain.setValueAtTime(.0001,t);g.gain.linearRampToValueAtTime(vol,t+.05);g.gain.setValueAtTime(vol,Math.max(t+.06,t+d-.06));g.gain.linearRampToValueAtTime(.0001,t+d);
  g.connect(sfxG);if(rev)g.connect(rev);o.start(t);o.stop(t+d+.05);vb.start(t);vb.stop(t+d+.05);
}
function sing(notes,step){if(!AC||muted)return;var t=AC.currentTime+.05;notes.forEach(function(n,i){if(n!=null)singNote(m2f(n-12),t+i*step,step*.92,.55);});}
function riff(step,len){
  if(!AC||muted)return;var t=AC.currentTime+.05,B=[0,0,7,7,5,5,7,7];
  for(var i=0;i<len;i++){var at=t+i*step;if(i%4===0)drum('kick',at,sfxG);if(i%8===4)drum('snare',at,sfxG);if(i%2===1)drum('hat',at,sfxG);mallet(m2f(B[i%8]-12),{t:at,d:step*.9,vol:.2,dry:true,type:'triangle'});}
}
var sfx={
  pop:function(){mallet(m2f(24),{to:m2f(31),d:.14,vol:.4});hiss(.035,{f:3000,vol:.1});},
  boing:function(k){k=k||0;spring(m2f(k*4-5),m2f(k*4+7),.34,.3);},
  giggle:function(hi){var b=hi?24:12;[4,7,4,7,12].forEach(function(n,i){mallet(m2f(b+n),{at:i*.075,d:.16,vol:.2});});},
  tada:function(){[12,16,19,24].forEach(function(n,i){mallet(m2f(n),{at:i*.1,d:.5,vol:.28});});[24,28,31].forEach(function(n){mallet(m2f(n),{at:.42,d:1,vol:.16});});},
  bonk:function(){mallet(m2f(-5),{to:m2f(-12),d:.22,vol:.42,soft:true});mallet(m2f(7),{d:.06,vol:.2});},
  thud:function(){mallet(95,{to:45,d:.2,vol:.6,soft:true,dry:true});},
  pump:function(i){hiss(.16,{f:800+i*500,fto:1600+i*600,vol:.14});mallet(m2f([0,4,7][i%3]),{d:.18,vol:.25});},
  whoosh:function(){hiss(.45,{f:350,fto:2600,vol:.12});},
  chomp:function(){for(var i=0;i<2;i++){mallet(m2f(4),{at:i*.17,d:.07,vol:.4});hiss(.06,{f:900,vol:.22,ft:'lowpass',at:i*.17});}},
  burp:function(l){
    if(!AC||muted)return;l=l||.5;
    var t=AC.currentTime,o=AC.createOscillator(),f=AC.createBiquadFilter(),g=AC.createGain(),lf=AC.createOscillator(),lg=AC.createGain();
    o.type='sawtooth';o.frequency.setValueAtTime(150,t);o.frequency.exponentialRampToValueAtTime(62,t+l);
    f.type='lowpass';f.Q.value=4;f.frequency.setValueAtTime(900,t);f.frequency.exponentialRampToValueAtTime(260,t+l);
    g.gain.setValueAtTime(.0001,t);g.gain.exponentialRampToValueAtTime(.3,t+.03);g.gain.exponentialRampToValueAtTime(.0001,t+l);
    lf.frequency.value=27;lg.gain.value=.12;lf.connect(lg);lg.connect(g.gain);
    o.connect(f);f.connect(g);g.connect(sfxG);o.start(t);o.stop(t+l+.05);lf.start(t);lf.stop(t+l+.05);
  },
  sparkle:function(){for(var i=0;i<6;i++)mallet(m2f(24+pick(PENT)),{at:i*.05,d:.3,vol:.1});},
  plink:function(){mallet(m2f(pick(PENT)),{d:.35,vol:.2});},
  fart:function(l){fartTone({d:l||.6});},
  fartOld:function(l){
    if(!AC||muted)return;l=l||.6;
    var t=AC.currentTime,o=AC.createOscillator(),f=AC.createBiquadFilter(),g=AC.createGain(),lf=AC.createOscillator(),lg=AC.createGain(),pf=AC.createOscillator(),pg=AC.createGain(),f0=70+rnd()*45;
    o.type='sawtooth';o.frequency.setValueAtTime(f0,t);o.frequency.linearRampToValueAtTime(f0*(rnd()<.5?.7:1.4),t+l);
    pf.frequency.value=5+rnd()*6;pg.gain.value=f0*.22;pf.connect(pg);pg.connect(o.frequency);
    f.type='lowpass';f.Q.value=6;f.frequency.setValueAtTime(760,t);f.frequency.linearRampToValueAtTime(330,t+l);
    g.gain.setValueAtTime(.0001,t);g.gain.exponentialRampToValueAtTime(.34,t+.03);g.gain.setValueAtTime(.3,t+l*.72);g.gain.exponentialRampToValueAtTime(.0001,t+l);
    lf.frequency.value=22+rnd()*16;lg.gain.value=.17;lf.connect(lg);lg.connect(g.gain);
    o.connect(f);f.connect(g);g.connect(sfxG);
    [o,lf,pf].forEach(function(x){x.start(t);x.stop(t+l+.05);});
    hiss(l*.9,{f:280,vol:.06,ft:'lowpass'});
  },
  star:function(){mallet(m2f(31),{d:.3,vol:.25});mallet(m2f(36),{at:.09,d:.6,vol:.25});}
};
/* background music: a gentle eight-bar tune, C, A minor, F, G */
var CH=[[0,4,7],[-3,0,4],[-7,-3,0],[-5,-1,2]],CH2=[[-7,-3,0],[-5,-1,2],[-8,-5,-1],[-3,0,4]],ARP=[0,2,1,2,0,2,1,2],STEP=.3,STEPS=[.3,.22,.34,.17],MODE=0,mus={next:0,step:0,t0:0};
var MELC=[[24,N,N,N,19,N,N,N],[26,N,N,N,23,N,N,N],[23,N,N,N,19,N,N,N],[21,N,N,N,24,N,N,N]];
var MELA=[[16,N,19,N,16,N,12,N],[21,N,19,N,16,N,N,N],[17,N,21,N,17,N,12,N],[14,N,19,N,14,N,N,N]];
var MELB=[[24,N,19,16,19,N,N,N],[21,N,16,12,16,N,N,N],[17,N,21,24,21,N,17,N],[19,N,23,N,26,N,N,N]];
function pad(f,t,d){
  var o=AC.createOscillator(),g=AC.createGain(),lp=AC.createBiquadFilter();o.type='triangle';o.frequency.value=f;lp.type='lowpass';lp.frequency.value=900;
  g.gain.setValueAtTime(.0001,t);g.gain.linearRampToValueAtTime(.05,t+.5);g.gain.linearRampToValueAtTime(.035,t+d-.4);g.gain.linearRampToValueAtTime(.0001,t+d);
  o.connect(lp);lp.connect(g);g.connect(musG);if(rev)g.connect(rev);o.start(t);o.stop(t+d+.05);
}
function drum(k,t,dest){dest=dest||musG;
  if(k==='kick'){var o=AC.createOscillator(),g=AC.createGain();o.frequency.setValueAtTime(150,t);o.frequency.exponentialRampToValueAtTime(42,t+.13);g.gain.setValueAtTime(.55,t);g.gain.exponentialRampToValueAtTime(.001,t+.22);o.connect(g);g.connect(dest);o.start(t);o.stop(t+.25);}
  else if(k==='snare'){hiss(.13,{t:t,f:1900,vol:.11,dest:dest});mallet(m2f(-5),{t:t,d:.08,vol:.08,dest:dest,soft:true,dry:true});}
  else hiss(.03,{t:t,f:8000,vol:.03,dest:dest,ft:'highpass'});
}
function musStep(t,s){
  var bar=Math.floor(s/8)%8,e=s%8,c=bar%4,ch=MODE===2?CH2[c]:CH[c],i,m;
  if(e===0)for(i=0;i<3;i++)pad(m2f(ch[i]),t,STEP*8+.3);
  if(MODE===2){
    if(e===0)mallet(m2f(ch[0]-12),{t:t,d:1.3,vol:.2,dest:musG,dry:true,soft:true});
    mallet(m2f(ch[ARP[e]]+24),{t:t,d:.9,vol:.05,dest:musG});
    m=MELC[c][e];if(m!=null)mallet(m2f(m),{t:t,d:1.5,vol:.13,dest:musG});
    return;
  }
  if(MODE===0){
    if(e===0||e===4)mallet(m2f(ch[0]-12+(e===4?7:0)),{t:t,d:.5,vol:.22,dest:musG,dry:true});
    mallet(m2f(ch[ARP[e]]),{t:t,d:.4,vol:.07,dest:musG});
    m=(bar<4?MELA:MELB)[c][e];if(m!=null)mallet(m2f(m),{t:t,d:.9,vol:.15,dest:musG});
    if(e%2===1)hiss(.04,{t:t,f:6000,vol:.02,dest:musG,ft:'highpass'});
    return;
  }
  var party=MODE===3;
  if(party?e%2===0:e%4===0)drum('kick',t);
  if(e%4===2)drum('snare',t);
  if(party||e%2===1)drum('hat',t);
  mallet(m2f(ch[0]-12+(e%2?12:0)),{t:t,d:party?.16:.24,vol:.22,dest:musG,dry:true,type:'triangle'});
  mallet(m2f(ch[ARP[e]]+12),{t:t,d:.25,vol:.05,dest:musG});
  m=(party?MELB:MELA)[c][e];if(m!=null)mallet(m2f(m),{t:t,d:party?.35:.6,vol:.14,dest:musG});
}
function setMode(m){MODE=m;STEP=STEPS[m];mus.step=0;mus.next=AC?AC.currentTime+.08:0;mus.t0=mus.next;}
function beatNow(){if(AC&&AC.state==='running'&&musicOn&&!muted&&mus.t0)return Math.max(0,(AC.currentTime-mus.t0)/(STEP*2));return time/(STEP*2);}
function musTick(){
  if(!AC||!started||!musicOn||muted||document.hidden||AC.state!=='running')return;
  var now=AC.currentTime;if(mus.next<now){mus.next=now+.06;mus.t0=mus.next-mus.step*STEP;}
  while(mus.next<now+.35){musStep(mus.next,mus.step++);mus.next+=STEP;}
}
setInterval(musTick,110);

/* ---------- voice (recorded, Kokoro "Heart") and caption ---------- */
var VOX={"A brick can be a birthday cake!": "242b3e4b.mp3", "A brick can be a bus! Beep, beep!": "6b1cd8b7.mp3", "A brick cannot roll. It slides!": "a0445d87.mp3", "A brick! Long, with flat sides.": "822834e9.mp3", "A cone can be a party hat!": "8e19783b.mp3", "A cone can be an ice cream! Yum!": "a0a3d111.mp3", "A cone can spin on its point!": "9aaa5569.mp3", "A cone! Pointy on top, round at the bottom.": "9ccb34de.mp3", "A cube can be a dice! Roll it!": "a416e634.mp3", "A cube can be a present!": "9547f595.mp3", "A cube cannot roll. Flop, flop, flop!": "8e9052ab.mp3", "A cube! Every side is a square.": "cc484c06.mp3", "A cylinder can be a candle!": "fad6d6cc.mp3", "A cylinder can be a drum! Boom, boom!": "f5e0088e.mp3", "A cylinder! Like a can.": "f21d99cf.mp3", "A donut shape can be a swim ring!": "942fdbd6.mp3", "A donut! Round, with a hole in the middle.": "7b87b0df.mp3", "A prism can be a piece of cheese!": "31c6e3d4.mp3", "A prism can be a tent!": "27120ed1.mp3", "A prism! Like a tent.": "10b409df.mp3", "A pyramid can be a sand pyramid!": "ca0e3557.mp3", "A pyramid can be a snowy mountain!": "760e5862.mp3", "A pyramid! Triangle sides and a pointy top.": "215b7323.mp3", "A sphere can be a beach ball!": "de591078.mp3", "A sphere can be a planet!": "dc348714.mp3", "A sphere can be an orange!": "96fb28a8.mp3", "A sphere rolls and rolls!": "622b79d7.mp3", "A sphere! Round like a ball.": "5ee7b499.mp3", "Ah... ah... ah... choo!": "c2619a08.mp3", "Back to a plain brick!": "533dedbe.mp3", "Back to a plain cone!": "48379708.mp3", "Back to a plain cube!": "484165de.mp3", "Back to a plain cylinder!": "a7f19b0d.mp3", "Back to a plain donut!": "43cca32b.mp3", "Back to a plain prism!": "71a14a3a.mp3", "Back to a plain pyramid!": "b0a97815.mp3", "Back to a plain sphere!": "e9e0bcd6.mp3", "Bonk! The brick does not fit. Try again!": "a2b4af27.mp3", "Bonk! The cone does not fit. Try again!": "6ca70ff1.mp3", "Bonk! The cube does not fit. Try again!": "84d55027.mp3", "Bonk! The cylinder does not fit. Try again!": "a6e8d934.mp3", "Bonk! The donut does not fit. Try again!": "d59ecef2.mp3", "Bonk! The prism does not fit. Try again!": "fdc9b1a3.mp3", "Bonk! The pyramid does not fit. Try again!": "5fedb54c.mp3", "Bonk! The sphere does not fit. Try again!": "6961cb2f.mp3", "Chomp! The brick fits!": "ef1c99fc.mp3", "Chomp! The cone fits!": "8e3dc10a.mp3", "Chomp! The cube fits!": "61729b1c.mp3", "Chomp! The cylinder fits!": "d5d3d3af.mp3", "Chomp! The donut fits!": "d1e0e709.mp3", "Chomp! The prism fits!": "68ebc7f8.mp3", "Chomp! The pyramid fits!": "929c2c77.mp3", "Chomp! The sphere fits!": "e64c2f14.mp3", "Dance party!": "3970eba7.mp3", "Dot is a square! Flat, like paper.": "908ff541.mp3", "Dot is too flat to hug. Pump Dot up! Tap, tap, tap!": "f27c4a43.mp3", "Flat shapes! Tap one to pop it up!": "cf5af9ab.mp3", "Giant shapes!": "2540ea6d.mp3", "Googly eyes!": "e7b8763b.mp3", "Gulp! Tasty brick!": "df3ecfd1.mp3", "Gulp! Tasty cone!": "a9baa407.mp3", "Gulp! Tasty cube!": "a9c26151.mp3", "Gulp! Tasty cylinder!": "9ee0b602.mp3", "Gulp! Tasty donut!": "ec6d8e44.mp3", "Gulp! Tasty prism!": "06faef55.mp3", "Gulp! Tasty pyramid!": "a7bd0c7a.mp3", "Gulp! Tasty sphere!": "90192959.mp3", "Hee hee! Dot wants to be long. Tap, tap, tap!": "e196b158.mp3", "It can roll, and it can stand up tall!": "d0290962.mp3", "It rolls like a wheel!": "86c97f8e.mp3", "It's raining shapes!": "47d9ade5.mp3", "Jump!": "0d2cddc6.mp3", "Look! A triangle at the front and at the back.": "fc4f7683.mp3", "Munchy wants a circle. Who fits?": "023a24e4.mp3", "Munchy wants a square. Who fits?": "28d59bb7.mp3", "Munchy wants a triangle. Who fits?": "125a18b8.mp3", "Now make Dot tall. Tap, tap, tap!": "9ca595b1.mp3", "One, two, three, four triangles!": "5f5cd01d.mp3", "Peekaboo! There you are!": "a8e87406.mp3", "Pop! Dot is a cube! Big and fat. Now you can hug Dot!": "b306d8f8.mp3", "Tap it again for a surprise!": "a65868cf.mp3", "Teeny tiny shapes!": "50fc5e51.mp3", "This is Dot. Dot is teeny tiny. Tap Dot!": "9fb68131.mp3", "Turn around... where did Dot go?": "7801dd99.mp3", "Wheee! Round and round!": "7d5e7ab4.mp3", "Whoa! Dot is a line! Long, long, long.": "75c218ba.mp3", "You found all eight shapes! Hooray!": "07d86158.mp3", "Yum! Sprinkles on the donut!": "867012df.mp3", "Yum, yum! A brick!": "1a8420f9.mp3", "Yum, yum! A cone!": "279d196f.mp3", "Yum, yum! A cube!": "27ad58b9.mp3", "Yum, yum! A cylinder!": "c3ed6f6a.mp3", "Yum, yum! A donut!": "26a2e16c.mp3", "Yum, yum! A prism!": "423bff7d.mp3", "Yum, yum! A pyramid!": "1fd61a12.mp3", "Yum, yum! A sphere!": "4620bbb1.mp3", "1D! Now it is just a line.": "155ec9d9.mp3", "2D! Now it is flat, like a drawing.": "5c984094.mp3", "3D! A solid shape again.": "c87c1e2e.mp3", "Back to normal.": "2ed441e8.mp3", "Dance time!": "85e2cffc.mp3", "Light show!": "75d1e1f9.mp3", "Look closely! Two fingers turn it. Tap it to flip it over.": "aa16bb2d.mp3", "Look! A see-through brick.": "82987d58.mp3", "Look! A see-through cone.": "be31a7ce.mp3", "Look! A see-through cube.": "be32f498.mp3", "Look! A see-through cylinder.": "91e34acb.mp3", "Look! A see-through donut.": "8670994d.mp3", "Look! A see-through prism.": "b3189bdc.mp3", "Look! A see-through pyramid.": "51f8b173.mp3", "Look! A see-through sphere.": "a76a3590.mp3", "Oops! Munchy tooted!": "382ca183.mp3", "Party time!": "5618d25f.mp3", "Pee-yew! Stinky!": "d768ebc1.mp3", "Right side up!": "b18a657a.mp3", "Toot toot! Hee hee!": "71fb2f25.mp3", "Toot, toot, toot! Everybody tooted!": "0c5134c9.mp3", "Upside down! There is the bottom.": "aafc3824.mp3", "A singing toot! La la la!": "71a3eefa.mp3", "Blub, blub! A bubbly toot!": "2e803c2a.mp3", "Pee-yew! Super stinky!": "5d5d93c0.mp3", "Pip! A teeny tiny toot!": "07664344.mp3", "Rat-a-tat! A machine toot!": "6cf20d66.mp3", "Squeak! A squeaky toot!": "f25cb3bd.mp3", "Toot, toot! A trumpet toot!": "55eeaa37.mp3", "Yes! Good job!": "d8a762ee.mp3", "A circle base! Now pull it up, straight or to a point.": "faf65166.mp3", "A square base! Now pull it up, straight or to a point.": "e6b4fc55.mp3", "A triangle base! Now pull it up, straight or to a point.": "9157853a.mp3", "Dot wants to meet friends. Let's go!": "1758d5c8.mp3", "Fart mode off.": "d974d406.mp3", "Fart mode on! Get ready!": "5823e83b.mp3", "Now let's feed Munchy!": "0a1a6edd.mp3", "Straight up! The circle makes a cylinder!": "c2f7589f.mp3", "Straight up! The square makes a cube!": "b2de14bf.mp3", "Straight up! The triangle makes a prism!": "bb66a6b4.mp3", "To a point! The circle makes a cone!": "2466d44f.mp3", "To a point! The square makes a pyramid!": "6b5eb6a1.mp3", "To a point! The triangle makes a triangle pyramid!": "afa093c0.mp3", "What a full tummy! Let's look closely at the shapes.": "b9a8f3b7.mp3", "Look closely! Slide one finger to spin around. Pinch to zoom.": "ae999f6e.mp3", "Look! A see-through dodecahedron.": "8e5406db.mp3", "Look! A see-through dome.": "be417b0a.mp3", "Look! A see-through egg.": "a8ad228c.mp3", "Look! A see-through hexagon prism.": "3780c9ae.mp3", "Look! A see-through hexagon pyramid.": "db634f41.mp3", "Look! A see-through icosahedron.": "aa16ad84.mp3", "Look! A see-through octahedron.": "513968aa.mp3", "Look! A see-through pentagon prism.": "8d35c1d4.mp3", "Look! A see-through pentagon pyramid.": "7da5f37b.mp3", "Look! A see-through star prism.": "02274b48.mp3", "Look! A see-through triangle pyramid.": "4da2881d.mp3", "The gem team! Lots of flat sides, like jewels.": "d238da1e.mp3", "The pointy team! A flat bottom and a point on top.": "34867d86.mp3", "The round team! Curvy shapes that can roll.": "e33ce943.mp3", "The stack team! Flat on top, so they stack up.": "db6e414e.mp3"},VOXM={"Boing! Big googly eyes!": "m5abc70fb.mp3", "Giggle party! Everybody laugh!": "m46f6d1d6.mp3", "Ha ha ha ha ha!": "me498558d.mp3", "Ha ha ha! That tickles!": "m356de48a.mp3", "Hee hee hee! Again! Again!": "m1a426eac.mp3", "Hee hee! Excuse me!": "m663fa130.mp3", "Hi! I am Munchy! Feed me shapes!": "m3795a9f2.mp3", "Ho ho ho! Hee hee hee!": "mbd79c0ea.mp3", "Let me dance! Wiggle, wiggle!": "m41ab76b1.mp3", "Not me! Ha ha!": "ma5aa9138.mp3", "Oops! Ha ha ha!": "m097188cf.mp3", "Whoa! Look at my googly eyes!": "md82e0e2d.mp3"},DEFAULT_NAME='',SITE=true;
var voRaw={},voBuf={},voNode=null,voTok=0,lastLine=['',''],synth=null;
try{synth=window.speechSynthesis||null;}catch(e){}
var mRaw={},mBuf={};
function preload(onp){
  var list=Object.keys(VOX).map(function(k){return [VOX[k],voRaw,k];}).concat(Object.keys(VOXM).map(function(k){return [VOXM[k],mRaw,k];})),n=0,i=0;if(!list.length){onp(1);return;}
  function next(){
    if(i>=list.length)return;var it=list[i++];
    fetch('v/'+it[0]).then(function(r){return r.ok?r.arrayBuffer():null;}).then(function(b){if(b)it[1][it[2]]=b;}).catch(function(){}).then(function(){n++;onp(n/list.length);next();});
  }
  for(var j=0;j<6;j++)next();
}
function duck(on){if(AC&&musG)musG.gain.setTargetAtTime(on?MUS*.3:MUS,AC.currentTime,.12);}
/* One line of speech at a time, for the narrator and Munchy alike. A line never cuts off another:
   it waits in the queue. p:2 lines are never dropped, p:1 lines (instructions, praise) always wait,
   p:0 chatter is skipped when the queue is busy and goes stale after 4 s. */
var Q=[],curL=null,wdog=0,vlog=[];
function getBuf(it,cb){
  var t=it.t,m=it.who==='m',map=m?VOXM:VOX,raw=m?mRaw:voRaw,buf=m?mBuf:voBuf;
  if(buf[t])return cb(buf[t]);
  function dec(r){try{var pr=AC.decodeAudioData(r.slice(0),function(b){buf[t]=b;cb(b);},function(){delete raw[t];cb(null);});if(pr&&pr.catch)pr.catch(function(){});}catch(e){cb(null);}}
  if(raw[t])return dec(raw[t]);
  if(map[t]){fetch('v/'+map[t]).then(function(r){if(!r.ok)throw 0;return r.arrayBuffer();}).then(function(b){raw[t]=b;dec(b);}).catch(function(){cb(null);});return;}
  (window.__miss=window.__miss||[]).push(t);cb(null);
}
function lineDone(it){
  if(curL!==it)return;clearTimeout(wdog);curL=null;voNode=null;duck(false);
  vlog.push([it.t,it.t0,performance.now()]);if(vlog.length>80)vlog.shift();
  var e=it.end;it.end=null;if(e){try{e();}catch(x){}}
  nextLine();
}
function nextLine(){
  while(Q.length){var it=Q.shift();if(!it.p&&time-it.at>4){var e=it.end;it.end=null;if(e)e();continue;}startLine(it);return;}
}
function startLine(it){
  curL=it;it.t0=performance.now();lastLine=[it.t,it.sub||'',it.who||''];setCap(it.t,it.sub,it.who);
  if(it.sing){if(it.start){try{it.start();}catch(x){}}wdog=setTimeout(function(){lineDone(it);},it.dur*1000);return;}
  if(muted||!AC){wdog=setTimeout(function(){lineDone(it);},300);return;}
  getBuf(it,function(b){
    if(curL!==it)return;
    if(!b){deviceLine(it);return;}
    var r=it.who==='m'?.93:1,src=AC.createBufferSource();src.buffer=b;src.playbackRate.value=r;src.connect(voG);voNode=src;duck(true);
    src.onended=function(){lineDone(it);};src.start();
    clearTimeout(wdog);wdog=setTimeout(function(){lineDone(it);},b.duration/r*1000+900);
  });
}
function deviceLine(it){
  var est=1300+it.t.length*80;
  if(!synth){wdog=setTimeout(function(){lineDone(it);},est*.6);return;}
  try{var u=new SpeechSynthesisUtterance(it.t);u.rate=.9;u.pitch=it.who==='m'?.8:1.2;u.lang='en-US';u.onend=u.onerror=function(){lineDone(it);};synth.speak(u);wdog=setTimeout(function(){lineDone(it);},est+1600);}
  catch(e){lineDone(it);}
}
function queueLine(it){
  it.at=time;if(it.p==null)it.p=1;
  if(!curL&&!Q.length){startLine(it);return;}
  if(curL&&curL.t===it.t&&!it.sing){if(it.end)it.end();return;}
  if(!it.p){if(Q.length){if(it.end)it.end();return;}Q.push(it);return;}
  Q=Q.filter(function(q){if(!q.p){if(q.end)q.end();return false;}return true;});
  Q.push(it);
  while(Q.filter(function(q){return q.p===1;}).length>3){for(var k=0;k<Q.length;k++)if(Q[k].p===1){var x=Q.splice(k,1)[0];if(x.end)x.end();break;}}
}
function dropQueued(){Q=[];}
function hush(){
  var old=Q,c=curL;Q=[];curL=null;clearTimeout(wdog);
  if(voNode){try{voNode.onended=null;voNode.stop();}catch(e){}voNode=null;}
  if(synth){try{synth.cancel();}catch(e){}}
  duck(false);
  if(c&&c.end)c.end();old.forEach(function(q){if(q.end)q.end();});
}
function setCap(t,sub,who){
  $('capT').textContent=t;$('capS').textContent=sub||'';
  var c=$('cap');c.classList.toggle('mun',who==='m');c.classList.remove('pop');void c.offsetWidth;c.classList.add('pop');
}
function say(t,sub,p){queueLine({t:t,sub:sub,who:'',p:p==null?1:p});}
function munSay(t,sub,o){o=o||{};queueLine({t:t,sub:sub,who:'m',p:o.p==null?0:o.p,end:o.end});}

/* ---------- little animation engine ---------- */
var E={
  lin:function(p){return p;},
  io:function(p){return p*p*(3-2*p);},
  out:function(p){return 1-Math.pow(1-p,3);},
  back:function(p){var c=1.9;return 1+(c+1)*Math.pow(p-1,3)+c*Math.pow(p-1,2);},
  el:function(p){return p<=0?0:p>=1?1:Math.pow(2,-10*p)*Math.sin((p*10-.75)*2*PI/3)+1;}
};
var runs=[],gen=0;
function run(d,fn,ease,cb,keep){runs.push({d:Math.max(.001,d),t:0,fn:fn,e:ease||E.io,cb:cb,gen:keep?-1:gen});}
function after(s,cb,keep){run(s,null,E.lin,cb,keep);}
function tw(o,to,d,ease,cb){var from={},k;for(k in to)from[k]=o[k];run(d,function(p){for(var k in to)o[k]=from[k]+(to[k]-from[k])*p;},ease,cb);}
function stepRuns(dt){
  var list=runs;runs=[];
  for(var i=0;i<list.length;i++){
    var r=list[i];if(r.gen!==-1&&r.gen!==gen)continue;
    r.t+=dt;var p=Math.min(1,r.t/r.d);
    if(r.fn)r.fn(r.e(p));
    if(p>=1){if(r.cb)r.cb();}else runs.push(r);
  }
}

/* ---------- world: built from the same shapes the game teaches ---------- */
R.setPixelRatio(Math.min(window.devicePixelRatio||1,2));
R.shadowMap.enabled=true;R.shadowMap.type=T.PCFSoftShadowMap;
var scene=new T.Scene(),cam=new T.PerspectiveCamera(40,1,.1,240);
scene.fog=new T.Fog(0xd9f0ff,42,130);
var hemi=new T.HemisphereLight(0xffffff,0x7ccf7a,.5);scene.add(hemi);
var sunL=new T.DirectionalLight(0xfff2d9,.7);sunL.position.set(5,10,7);sunL.castShadow=true;
var SM=Math.min(window.innerWidth,window.innerHeight)>700?2048:1024;sunL.shadow.mapSize.set(SM,SM);sunL.shadow.camera.left=-9;sunL.shadow.camera.right=9;sunL.shadow.camera.top=9;sunL.shadow.camera.bottom=-9;sunL.shadow.camera.far=40;sunL.shadow.bias=-.0006;sunL.shadow.radius=4;
scene.add(sunL);
var rimL=new T.DirectionalLight(0xcfe6ff,.42);rimL.position.set(-5,6,-9);scene.add(rimL);

var PINK=0xff6fa5,YEL=0xffc93c,BLUE=0x4db8ff,GRN=0x4fd08a,PUR=0x9b7bff,ORA=0xff9547,RED=0xff5d5d,TEAL=0x2fd0c5;
var PAL=[PINK,YEL,BLUE,GRN,PUR,ORA,RED,TEAL];
/* glossy toy plastic */
function mat(c,o){var m=new T.MeshPhysicalMaterial({color:c,roughness:.42,metalness:0,clearcoat:.6,clearcoatRoughness:.25,envMapIntensity:.5});if(o)for(var k in o)m[k]=o[k];return m;}
function flat(c){return new T.MeshLambertMaterial({color:c});}
function basic(c,o){var m=new T.MeshBasicMaterial({color:c});if(o)for(var k in o)m[k]=o[k];return m;}
function mesh(g,m,x,y,z,sh){var o=new T.Mesh(g,m);o.position.set(x||0,y||0,z||0);if(sh)o.castShadow=true;return o;}
(function(){
  try{
    var es=new T.Scene(),sg=new T.SphereGeometry(1,24,16);
    var sky=mesh(sg,basic(0xa9d8ff,{side:T.BackSide}));sky.scale.setScalar(40);es.add(sky);
    var fl=mesh(new T.CircleGeometry(40,24),basic(0x74c96f),0,-4,0);fl.rotation.x=-PI/2;es.add(fl);
    var a=mesh(sg,basic(0xffffff),12,16,9);a.scale.setScalar(6);es.add(a);
    var b=mesh(sg,basic(0xfff0c8),-14,9,7);b.scale.setScalar(4);es.add(b);
    var pm=new T.PMREMGenerator(R);scene.environment=pm.fromScene(es,.04).texture;pm.dispose();
  }catch(e){}
})();
var clouds=[],extras=[],motes=null,bows=[];
/* grass tufts and flowers, kept off the play area */
(function(){
  var m4=new T.Matrix4(),q=new T.Quaternion(),sc=new T.Vector3(),p=new T.Vector3(),eu=new T.Euler();
  function spot(){for(;;){var a=rnd()*PI*2,r=6.2+rnd()*15,x=Math.cos(a)*r,z=Math.sin(a)*r-2;if(z<2.5)return [x,z];}}
  var tg=new T.ConeGeometry(.07,.34,5);tg.translate(0,.17,0);
  var tuft=new T.InstancedMesh(tg,new T.MeshLambertMaterial({color:0x3fa94f}),220);
  for(var i=0;i<220;i++){var xz=spot();p.set(xz[0],0,xz[1]);eu.set((rnd()-.5)*.5,rnd()*3,(rnd()-.5)*.5);q.setFromEuler(eu);var s=.7+rnd()*.9;sc.set(s,s*(.8+rnd()*.9),s);m4.compose(p,q,sc);tuft.setMatrixAt(i,m4);}
  scene.add(tuft);
  var stemG=new T.CylinderGeometry(.018,.018,.34,5);stemG.translate(0,.17,0);var headG=new T.SphereGeometry(.1,10,8);
  var stems=new T.InstancedMesh(stemG,new T.MeshLambertMaterial({color:0x2f8f45}),70),cols=[0xff6fa5,0xffc93c,0xffffff,0xb48bff,0xff8f5a],heads=cols.map(function(c){return new T.InstancedMesh(headG,new T.MeshLambertMaterial({color:c}),14);});
  for(i=0;i<70;i++){var f=spot(),h=.85+rnd()*.5;q.set(0,0,0,1);sc.set(1,h,1);p.set(f[0],0,f[1]);m4.compose(p,q,sc);stems.setMatrixAt(i,m4);sc.set(1,.75,1);p.set(f[0],.34*h,f[1]);m4.compose(p,q,sc);heads[i%5].setMatrixAt(Math.floor(i/5),m4);}
  scene.add(stems);heads.forEach(function(hm){scene.add(hm);});
})();
(function(){
  var g=mesh(new T.CircleGeometry(110,48),flat(0x63c764));g.rotation.x=-PI/2;g.receiveShadow=true;scene.add(g);
  var s=mesh(new T.CircleGeometry(5.2,64),flat(0x8fe07e),0,.01,.2);s.rotation.x=-PI/2;s.receiveShadow=true;scene.add(s);
  var ring=mesh(new T.RingGeometry(5.2,5.42,64),flat(0xf4ffe9),0,.012,.2);ring.rotation.x=-PI/2;ring.receiveShadow=true;scene.add(ring);
  var hg=new T.SphereGeometry(1,24,16);
  [[-18,-32,13,0x79cf7b],[4,-40,17,0x6cc474],[24,-32,12,0x85d684],[-36,-38,15,0x6cc474],[40,-42,16,0x79cf7b]].forEach(function(h){
    var m=mesh(hg,flat(h[3]),h[0],-h[2]*.45,h[1]);m.scale.setScalar(h[2]);scene.add(m);
  });
  var fg=new T.SphereGeometry(.09,8,6);
  for(var i=0;i<34;i++){
    var a=PI+rnd()*PI,r=6+rnd()*14;
    scene.add(mesh(fg,basic(pick([0xffffff,0xff9ecb,0xffe066,0xb9a3ff])),Math.cos(a)*r,.08,Math.sin(a)*r-4));
  }
  /* trees: a cylinder with cones or a sphere on top */
  var trunkG=new T.CylinderGeometry(.2,.28,1.2,10),coneG=new T.ConeGeometry(1,1.6,16),ballG=new T.SphereGeometry(1.1,18,14),wood=flat(0x9a6b43);
  [[-7,-6,1.2,0],[7.5,-7,1.4,1],[-10.5,-12,1.7,1],[11,-13,1.6,0],[-4.6,-11.5,1.15,0],[5.2,-12.5,1.25,1],[14.5,-6,1.3,0],[-14.5,-5,1.2,1],[2.2,-17,1.5,0]].forEach(function(t){
    var tr=new T.Group();tr.add(mesh(trunkG,wood,0,.6,0,true));
    if(t[3]){tr.add(mesh(ballG,flat(0x4fbf66),0,2.05,0,true));}
    else{tr.add(mesh(coneG,flat(0x3fae5b),0,1.9,0,true));var c2=mesh(coneG,flat(0x4fbf66),0,2.75,0,true);c2.scale.setScalar(.75);tr.add(c2);}
    tr.position.set(t[0],0,t[1]);tr.scale.setScalar(t[2]);scene.add(tr);
  });
  /* a house: a cube with a pyramid roof */
  var hx=-9,hz=-9.5,box=new T.BoxGeometry(1,1,1),roof=new T.ConeGeometry(.75,1.1,4).rotateY(PI/4);
  var hb=mesh(box,flat(0xfff1d6),hx,1,hz,true);hb.scale.set(2.4,2,2.2);scene.add(hb);
  var hr=mesh(roof,flat(0xff6b6b),hx,2.7,hz,true);hr.scale.set(2.6,1.3,2.6);scene.add(hr);
  var hd=mesh(box,flat(0x9a6b43),hx-.4,.5,hz+1.12);hd.scale.set(.55,1,.05);scene.add(hd);
  var hw=mesh(box,flat(0x9fdcff),hx+.6,1.2,hz+1.12);hw.scale.set(.55,.55,.05);scene.add(hw);
  /* far mountains are pyramids, the rainbow is half of a donut */
  [[-34,-78,24,19],[10,-90,34,27],[46,-80,22,17]].forEach(function(m){
    var a=mesh(roof,flat(0x9fb0e6),m[0],m[3]*.55,m[1]);a.scale.set(m[2],m[3],m[2]);scene.add(a);
    var c=mesh(roof,flat(0xffffff),m[0],m[3]*.55+m[3]*.385,m[1]);c.scale.set(m[2]*.31,m[3]*.31,m[2]*.31);scene.add(c);
  });
  [0xff5d5d,0xff9547,0xffc93c,0x4fd08a,0x4db8ff,0x9b7bff].forEach(function(c,i){
    var bw=mesh(new T.TorusGeometry(22-i*.95,.5,6,48,PI),basic(c,{fog:false,transparent:true,opacity:.8}),16,-1.5,-62);bows.push(bw);scene.add(bw);
  });
  var cg=new T.SphereGeometry(1,16,12),cm=flat(0xffffff);
  [[-9,8,-18,1.3],[6,10,-24,1.7],[14,7,-16,1.1],[-18,11,-28,1.9]].forEach(function(c){
    var g=new T.Group();
    [[0,0,0,1],[.9,-.1,0,.75],[-.9,-.15,0,.7],[.3,.45,0,.7]].forEach(function(b){var m=mesh(cg,cm,b[0],b[1],b[2]);m.scale.setScalar(b[3]);m.userData.tap=function(){rain();say("It's raining shapes!",null,0);};extras.push(m);g.add(m);});
    g.position.set(c[0],c[1],c[2]);g.scale.setScalar(c[3]);scene.add(g);clouds.push(g);
  });
  var mp=new Float32Array(60*3);for(var j=0;j<60;j++){mp[j*3]=(rnd()-.5)*16;mp[j*3+1]=.4+rnd()*5;mp[j*3+2]=-7+rnd()*11;}
  var mg=new T.BufferGeometry();mg.setAttribute('position',new T.BufferAttribute(mp,3));
  motes=new T.Points(mg,new T.PointsMaterial({color:0xffffff,size:.07,transparent:true,opacity:.75,depthWrite:false}));scene.add(motes);
})();

/* ---------- faces ---------- */
var eyeG=new T.SphereGeometry(.105,16,12),pupG=new T.SphereGeometry(.055,12,10),hiG=new T.SphereGeometry(.02,8,6);
var smileG=new T.TorusGeometry(.085,.022,8,16,PI),cheekG=new T.CircleGeometry(.05,16);
var whiteM=mat(0xffffff,{roughness:.3}),blackM=mat(0x2b2140,{roughness:.3}),hiM=basic(0xffffff),cheekM=basic(0xff7fa8,{transparent:true,opacity:.55});
function makeFace(){
  var f=new T.Group();f.eyes=[];
  [-1,1].forEach(function(sx){
    var e=new T.Group();e.position.set(sx*.17,.04,0);
    var w=mesh(eyeG,whiteM);w.scale.set(1,1,.55);e.add(w);
    var p=mesh(pupG,blackM,0,0,.05);p.scale.set(1,1,.5);e.add(p);e.pupil=p;
    e.add(mesh(hiG,hiM,.022,.028,.078));
    f.add(e);f.eyes.push(e);
    f.add(mesh(cheekG,cheekM,sx*.28,-.09,.012));
  });
  f.mouth=mesh(smileG,blackM,0,-.11,.02);f.mouth.rotation.z=PI;f.add(f.mouth);
  f.oh=mesh(pupG,blackM,0,-.15,.02);f.oh.scale.set(1.2,1.4,.4);f.oh.visible=false;f.add(f.oh);
  return f;
}

/* ---------- shapes ---------- */
function rbox(w,h,d){
  var b=.07,r=.03,x=w/2-b,y=h/2-b,s=new T.Shape();
  s.moveTo(-x+r,-y);s.lineTo(x-r,-y);s.quadraticCurveTo(x,-y,x,-y+r);s.lineTo(x,y-r);s.quadraticCurveTo(x,y,x-r,y);s.lineTo(-x+r,y);s.quadraticCurveTo(-x,y,-x,y-r);s.lineTo(-x,-y+r);s.quadraticCurveTo(-x,-y,-x+r,-y);
  var g=new T.ExtrudeGeometry(s,{depth:d-2*b,bevelEnabled:true,bevelThickness:b,bevelSize:b,bevelSegments:4,curveSegments:5});g.translate(0,0,-(d-2*b)/2);return g;
}
/* two shapes as one (a dome is half a sphere plus its flat bottom) */
function joinGeo(a,b){
  a=a.index?a.toNonIndexed():a;b=b.index?b.toNonIndexed():b;var g=new T.BufferGeometry();
  ['position','normal','uv'].forEach(function(n){var x=a.attributes[n].array,y=b.attributes[n].array,z=new Float32Array(x.length+y.length);z.set(x);z.set(y,x.length);g.setAttribute(n,new T.BufferAttribute(z,a.attributes[n].itemSize));});
  a.dispose();b.dispose();return g;
}
var GEO={};
function geo(k){
  if(GEO[k])return GEO[k];var g;
  switch(k){
    case 'sphere':g=new T.SphereGeometry(.6,40,28);break;
    case 'cylinder':g=new T.CylinderGeometry(.5,.5,1.1,40);break;
    case 'cone':g=new T.ConeGeometry(.6,1.3,40);break;
    case 'donut':g=new T.TorusGeometry(.45,.22,20,44);break;
    case 'cube':g=rbox(1,1,1);break;
    case 'brick':g=rbox(1.6,.7,.8);break;
    case 'prism':g=new T.CylinderGeometry(.7,.7,1,3).rotateX(-PI/2).translate(0,-.175,0);break;
    case 'pyramid':g=new T.ConeGeometry(.75,1.1,4).rotateY(PI/4);break;
    case 'tprism':g=new T.CylinderGeometry(.66,.66,1,3).rotateY(PI);break;
    case 'tpyramid':g=new T.ConeGeometry(.72,1.1,3).rotateY(PI);break;
    case 'circle':g=new T.CylinderGeometry(.6,.6,.06,40).rotateX(PI/2);break;
    case 'square':g=new T.BoxGeometry(1.05,1.05,.06);break;
    case 'triangle':g=new T.CylinderGeometry(.7,.7,.06,3).rotateX(-PI/2).translate(0,-.175,0);break;
    case 'ball1':g=new T.SphereGeometry(.5,28,20);break;
    case 'dome':g=joinGeo(new T.SphereGeometry(.62,40,14,0,PI*2,0,PI/2),new T.CircleGeometry(.62,40).rotateX(PI/2)).translate(0,-.31,0);break;
    case 'egg':g=new T.SphereGeometry(.5,40,28);(function(){var P=g.attributes.position;for(var i=0;i<P.count;i++){var y=P.getY(i),k=1-.13*Math.max(0,y)/.5;P.setXYZ(i,P.getX(i)*k,y*1.3,P.getZ(i)*k);}g.computeVertexNormals();})();break;
    case 'hexprism':g=new T.CylinderGeometry(.58,.58,1,6).rotateY(PI/6);break;
    case 'pentprism':g=new T.CylinderGeometry(.6,.6,1,5).rotateY(PI/5);break;
    case 'star':g=(function(){var sh=new T.Shape();for(var i=0;i<10;i++){var r=i%2?.29:.66,an=PI/2+i*PI/5;if(i)sh.lineTo(Math.cos(an)*r,Math.sin(an)*r);else sh.moveTo(Math.cos(an)*r,Math.sin(an)*r);}sh.closePath();
      var e=new T.ExtrudeGeometry(sh,{depth:.3,bevelEnabled:true,bevelThickness:.05,bevelSize:.04,bevelSegments:3});e.translate(0,-.063,-.15);return e;})();break;
    case 'pentpyramid':g=new T.ConeGeometry(.72,1.1,5).rotateY(PI/5);break;
    case 'hexpyramid':g=new T.ConeGeometry(.72,1.1,6).rotateY(PI/6);break;
    case 'octa':g=new T.OctahedronGeometry(.72).rotateY(PI/4);break;
    case 'dodeca':g=new T.DodecahedronGeometry(.62);break;
    case 'icosa':g=new T.IcosahedronGeometry(.64);break;
  }
  return GEO[k]=g;
}
/* hy: half height. f: face [y, z, size, lean]. pre: how it lies while it is still flat. */
var DEF={
  sphere:{hy:.6,f:[.05,.52,1,0],name:'sphere',say:'A sphere! Round like a ball.',fact:'A sphere rolls and rolls!',sub:'Sphere: round all over, no flat sides.',trick:'roll',r:.6},
  cylinder:{hy:.55,f:[.08,.45,1,0],pre:[PI/2,0],name:'cylinder',say:'A cylinder! Like a can.',fact:'It can roll, and it can stand up tall!',sub:'Cylinder: two flat circles and one curved side.',trick:'canroll',r:.5},
  cone:{hy:.65,f:[-.27,.36,.82,-.43],pre:[PI/2,0],name:'cone',say:'A cone! Pointy on top, round at the bottom.',fact:'A cone can spin on its point!',sub:'Cone: one flat circle and one point.',trick:'top'},
  donut:{hy:.67,f:[.45,.18,.7,0],name:'donut',say:'A donut! Round, with a hole in the middle.',fact:'It rolls like a wheel!',sub:'Its grown-up name is a torus.',trick:'roll',r:.67},
  cube:{hy:.5,f:[.05,.5,1,0],name:'cube',say:'A cube! Every side is a square.',fact:'A cube cannot roll. Flop, flop, flop!',sub:'Cube: six flat square sides.',trick:'flop'},
  brick:{hy:.35,f:[0,.4,.82,0],pre:[0,PI/2],name:'brick',say:'A brick! Long, with flat sides.',fact:'A brick cannot roll. It slides!',sub:'Its grown-up name is a rectangular prism.',trick:'slide'},
  prism:{hy:.525,f:[-.2,.5,.82,0],name:'prism',say:'A prism! Like a tent.',fact:'Look! A triangle at the front and at the back.',sub:'Triangular prism: two triangles joined by flat sides.',trick:'turn'},
  pyramid:{hy:.55,f:[-.25,.36,.78,-.45],name:'pyramid',say:'A pyramid! Triangle sides and a pointy top.',fact:'One, two, three, four triangles!',sub:'Pyramid: a square bottom and four triangles.',trick:'turn'},
  circle:{hy:.6,f:[0,.035,1,0],name:'circle'},
  square:{hy:.525,f:[0,.035,1,0],name:'square'},
  triangle:{hy:.525,f:[-.2,.035,.8,0],name:'triangle'}
};
DEF.tprism={hy:.5,f:[0,.34,.8,0],name:'prism',sub:'Triangle prism: two triangles and three flat sides.'};
DEF.tpyramid={hy:.55,f:[-.22,.22,.6,-.5],name:'triangle pyramid',sub:'Triangle pyramid: a triangle bottom and a point. Grown-ups call it a tetrahedron.'};
DEF.dome={hy:.31,f:[-.02,.53,.8,-.5],name:'dome',sub:'Its grown-up name is a hemisphere: half a sphere.'};
DEF.egg={hy:.65,f:[.02,.47,.82,0],name:'egg',sub:'An egg shape: a sphere stretched long. Grown-ups say ovoid.'};
DEF.hexprism={hy:.5,f:[.02,.51,.88,0],name:'hexagon prism',sub:'Hexagonal prism: two hexagons and six flat sides, like a pencil.'};
DEF.pentprism={hy:.5,f:[.02,.49,.86,0],name:'pentagon prism',sub:'Pentagonal prism: two pentagons and five flat sides.'};
DEF.star={hy:.6,f:[-.03,.21,.72,0],name:'star prism',sub:'Star prism: two stars joined by flat sides.'};
DEF.pentpyramid={hy:.55,f:[-.25,.37,.72,-.5],name:'pentagon pyramid',sub:'Pentagonal pyramid: a pentagon bottom and five triangles.'};
DEF.hexpyramid={hy:.55,f:[-.25,.41,.72,-.5],name:'hexagon pyramid',sub:'Hexagonal pyramid: a hexagon bottom and six triangles.'};
DEF.octa={hy:.72,f:[.2,.37,.66,-.62],name:'octahedron',sub:'Octahedron: eight triangle faces, like two pyramids back to back.'};
DEF.dodeca={hy:.62,f:[.04,.55,.82,0],name:'dodecahedron',sub:'Dodecahedron: twelve faces, and every face is a pentagon.'};
DEF.icosa={hy:.64,f:[.04,.56,.82,0],name:'icosahedron',sub:'Icosahedron: twenty triangle faces.'};
var SOLIDS=['sphere','cylinder','cone','donut','cube','brick','prism','pyramid'];
var actors=[];
/* free what a removed shape, costume, Munchy or shelf owned; shared shapes and face parts stay */
function shared(g){
  if(g===unitB||g===unitC||g===smallS||g===pipG||g===eyeG||g===pupG||g===hiG||g===smileG||g===cheekG)return true;
  for(var k in GEO)if(GEO[k]===g)return true;
  return false;
}
function freeTree(o){
  var keep=[whiteM,blackM,hiM,cheekM];
  o.traverse(function(n){
    if(n.geometry&&!n.isSprite&&!shared(n.geometry))n.geometry.dispose();
    var m=n.material;if(m&&keep.indexOf(m)<0){if(m.map)m.map.dispose();m.dispose();}
  });
}
function Actor(kind,color){
  var a=this,d=DEF[kind];a.kind=kind;a.d=d;a.color=color;
  a.g=new T.Group();a.sq=new T.Group();a.spin=new T.Group();a.tilt=new T.Group();
  a.g.add(a.sq);a.sq.add(a.spin);a.spin.add(a.tilt);a.spin.position.y=d.hy;
  a.mat=mat(color);a.body=mesh(geo(kind),a.mat,0,0,0,true);a.body.userData.a=a;a.tilt.add(a.body);
  a.face=makeFace();a.face.position.set(0,d.f[0],d.f[1]);a.face.rotation.x=d.f[3];a.tilt.add(a.face);
  a.s=1;a.sc=1;a.zs=1;a.ys=1;a.fs=1;a.by=0;a.hopping=false;a.fb=d.f[2];a.bl=1+rnd()*4;a.blT=0;a.ph=rnd()*6;a.dance=0;
  scene.add(a.g);actors.push(a);
}
Actor.prototype.kill=function(){scene.remove(this.g);freeTree(this.g);var i=actors.indexOf(this);if(i>=0)actors.splice(i,1);if(hintA===this)hintA=null;};
Actor.prototype.hop=function(h,d,cb){
  var a=this;
  if(a.hopping){if(cb)after(d||.4,cb);return;}
  a.hopping=true;
  run(d||.4,function(p){a.g.position.y=a.by+h*4*p*(1-p);},E.lin,function(){a.hopping=false;a.g.position.y=a.by;a.squish();if(cb)cb();});
};
Actor.prototype.squish=function(k){var a=this;k=k||.22;run(.3,function(p){a.s=1-k*Math.sin(p*PI)*(1-p*.4);},E.lin,function(){a.s=1;});};
Actor.prototype.wow=function(on){this.face.oh.visible=on;this.face.mouth.visible=!on;};
Actor.prototype.top=function(){return this.g.position.y+(this.dims?this.dims.H:this.d.hy*2)*this.sc;};
var GS=1,GST=1,GE=1,GET=1,disco=0,DANCE=0,dmode=1,danceD=0,nightD=0,partyD=0,glowD=0,bt=0;
/* dance-mode lights, stars, moon, disco ball and beams */
var dl=[0xff6fa5,0x4db8ff,0xffc93c].map(function(c){var l=new T.PointLight(c,0,9,2);scene.add(l);return l;});
var starsP=(function(){var n=320,p=new Float32Array(n*3);for(var i=0;i<n;i++){var a=PI*(.05+rnd()*.9),r=60+rnd()*25;p[i*3]=Math.cos(a)*r*(rnd()<.5?-1:1)*.9;p[i*3+1]=6+rnd()*38;p[i*3+2]=-Math.abs(Math.sin(a)*r)-10;}
  var g=new T.BufferGeometry();g.setAttribute('position',new T.BufferAttribute(p,3));var m=new T.Points(g,new T.PointsMaterial({color:0xffffff,size:.5,transparent:true,opacity:0,depthWrite:false,fog:false}));m.visible=false;scene.add(m);return m;})();
var moon=new T.Group();
var ball=new T.Group(),beams=new T.Group();
function ambientToot(){
  if(busy)return;
  if(curName==='munch'&&mun){if(mun.act==='idle')munFart(null,false);return;}
  var c=actors.filter(function(a){return !a.glass&&!a.isPaper;});if(c.length)tootA(pick(c));
}
function setFart(on){
  FARTMODE=on;$('fartb').classList.toggle('on',on);$('fartb').setAttribute('aria-pressed',on?'true':'false');
  if(on){say('Fart mode on! Get ready!');fartT=2.2;sfx.fart(.4);}else{say('Fart mode off.');sfx.sparkle();}
}
function stepDance(dt){
  if(FARTMODE&&started&&!document.hidden){fartT-=dt;if(fartT<0){fartT=8+rnd()*6;ambientToot();}}
  danceD+=((DANCE>0?1:0)-danceD)*Math.min(1,dt*3);
  nightD+=((DANCE>=2?1:0)-nightD)*Math.min(1,dt*1.8);
  partyD+=((DANCE===3?1:0)-partyD)*Math.min(1,dt*1.8);
  glowD+=((DANCE===2?1:DANCE===3?.4:0)-glowD)*Math.min(1,dt*2);
  bt=beatNow();
  hemi.intensity=.5*(1-.84*nightD);sunL.intensity=.7*(1-.93*nightD);rimL.intensity=.42*(1-.5*nightD);
  scene.fog.color.setRGB(.85-.78*nightD,.94-.86*nightD,1-.75*nightD);
  $('night').style.opacity=nightD.toFixed(3);
  for(var i=0;i<3;i++){
    var L=dl[i],sp=partyD>.5?1.6:.6,an=time*sp+i*2.094;
    L.intensity=nightD*(.95+partyD*.45);L.position.set(Math.cos(an)*3.6,2.6+Math.sin(time*1.3+i)*.8,Math.sin(an)*3.6+.5);
    L.color.setHSL((time*(partyD>.5?.12:.04)+i/3)%1,.85,.6);
  }
  starsP.visible=nightD>.02;starsP.material.opacity=nightD*(.85+.15*Math.sin(time*3));
  sun.visible=nightD<.5;moon.visible=nightD>=.5;
  for(i=0;i<bows.length;i++)bows[i].material.opacity=.8*(1-nightD);
  ball.visible=beams.visible=partyD>.02;
  ball.position.y=9.5-4.2*partyD;ball.rotation.y=time*1.2;
  beams.position.copy(ball.position);beams.rotation.y=-time*.9;
  beams.children.forEach(function(arm,j){var b=arm.children[0];b.material.opacity=.13*partyD;b.material.color.setHSL((time*.15+j/6)%1,.9,.6);});
  if(partyD>.9){var bi=Math.floor(bt);if(bi!==stepDance.lb){stepDance.lb=bi;if(bi%4===0)burst((rnd()-.5)*4,4.6,(rnd()-.5)*2,14,{up:2,sp:3});}}
}
function danceMove(i,ph){
  var D=danceD,m=dmode,b=bt+(i%2)*.5,y=0,rz=0,ry=0,s=1;
  if(D<.002)return null;
  if(m===1){y=Math.abs(Math.sin(PI*b))*.35;rz=Math.sin(PI*b+ph)*.16;s=1+.08*Math.cos(2*PI*b);}
  else if(m===2){y=.15+.12*Math.sin(PI*b/2+ph);rz=Math.sin(PI*b/2+ph)*.2;ry=Math.sin(PI*b/4+ph)*.5;}
  else{y=Math.abs(Math.sin(PI*b))*.55;rz=Math.sin(2*PI*b)*.1;s=1+.12*Math.cos(2*PI*b);var bar=Math.floor(bt/4);if(bar%2===i%2)ry=(bt/4-bar)*2*PI;}
  return {y:y*D,rz:rz*D,ry:ry*D,s:1+(s-1)*D};
}
function stepActors(dt,t){
  GS+=(GST-GS)*Math.min(1,dt*6);GE+=(GET-GE)*Math.min(1,dt*6);
  for(var i=0;i<actors.length;i++){
    var a=actors[i];
    a.bl-=dt;if(a.bl<0){a.bl=1.5+rnd()*4;a.blT=.13;}
    var by=1;if(a.blT>0){a.blT-=dt;by=.12;}
    var lx=Math.sin(t*.7+a.ph)*.012,ly=Math.cos(t*.9+a.ph)*.008;
    for(var j=0;j<2;j++){var e=a.face.eyes[j];e.scale.set(GE,GE*by,GE);e.pupil.position.x=lx;e.pupil.position.y=ly;}
    var dm=a.glass?null:danceMove(i,a.ph);
    var s=a.s*(1+Math.sin(t*2.2+a.ph)*.014)*(dm?dm.s:1),k=a.sc*GS,q=1/Math.sqrt(s);
    k=Math.max(.0001,k);a.sq.scale.set(k*q,k*s*a.ys,k*q*a.zs);
    a.sq.position.y=(disco>0?Math.abs(Math.sin(t*7+a.ph))*.35:0)+(dm?dm.y:0);
    a.sq.rotation.z=dm?dm.rz:0;a.sq.rotation.y=dm?dm.ry:0;
    if(a.mat.emissive)a.mat.emissive.setHex(a.color).multiplyScalar(.42*glowD);
    var fb=a.fb;
    if(a.dims){
      var D=a.dims;a.body.scale.set(D.L,D.H,D.D);a.spin.position.y=D.H/2;a.face.position.set(0,0,D.D/2+.004);
      fb=clamp(Math.min(D.L,D.H)*1.25,.62,1.5);
    }
    a.face.scale.setScalar(Math.max(.0001,fb*a.fs));
    if(a.idle)a.idle(t,dt);
  }
}

/* ---------- confetti and shape rain ---------- */
var parts=[],pI=0;
(function(){
  var g=new T.PlaneGeometry(.15,.09);
  for(var i=0;i<110;i++){var m=mesh(g,basic(0xffffff,{side:T.DoubleSide}));m.visible=false;scene.add(m);parts.push({m:m,v:new T.Vector3(),life:0,g:9});}
})();
function burst(x,y,z,n,o){
  o=o||{};
  for(var i=0;i<n;i++){
    var p=parts[pI++%parts.length],a=rnd()*PI*2,sp=(o.sp||4)*(.3+rnd()*.8);
    p.m.visible=true;p.m.position.set(x,y,z);p.m.material.color.setHex(o.col||pick(PAL));
    p.v.set(Math.cos(a)*sp,(o.up==null?6:o.up)*(.5+rnd()*.7),Math.sin(a)*sp*.7);p.life=1.3+rnd();p.g=o.g==null?9:o.g;
    p.m.scale.setScalar(o.size||1);
  }
}
function stepParts(dt){
  for(var i=0;i<parts.length;i++){
    var p=parts[i];if(!p.m.visible)continue;
    p.v.y-=p.g*dt;p.m.position.addScaledVector(p.v,dt);p.m.rotation.x+=dt*9;p.m.rotation.y+=dt*7;p.life-=dt;
    if(p.life<0||p.m.position.y<0)p.m.visible=false;
  }
}
var minis=[];
(function(){
  for(var i=0;i<26;i++){var m=mesh(geo(SOLIDS[i%8]),mat(PAL[i%8]),0,0,0,true);m.visible=false;scene.add(m);minis.push({m:m,vy:0,life:0,b:0,w:0});}
})();
function rain(){
  minis.forEach(function(o){
    o.m.visible=true;o.m.position.set((rnd()-.5)*8,7+rnd()*9,(rnd()-.5)*5+.6);o.vy=0;o.life=5.5;o.b=0;o.w=rnd()*6;
  });
}
function stepMinis(dt){
  for(var i=0;i<minis.length;i++){
    var o=minis[i];if(!o.m.visible)continue;
    o.vy-=15*dt;o.m.position.y+=o.vy*dt;o.m.rotation.x+=dt*3;o.m.rotation.z+=dt*2;
    if(o.m.position.y<.22&&o.vy<0){o.m.position.y=.22;o.vy=-o.vy*.45;if(o.b++<2&&rnd()<.4)sfx.plink();}
    o.life-=dt;o.m.scale.setScalar(.3*Math.min(1,o.life));
    if(o.life<=0)o.m.visible=false;
  }
}

/* ---------- pointing arrow ---------- */
var puffs=[],pfI=0;
(function(){var g=new T.SphereGeometry(.4,12,10);for(var i=0;i<24;i++){var m=mesh(g,new T.MeshLambertMaterial({color:0x8fd14f,emissive:0x2a4a10,transparent:true,opacity:0,depthWrite:false}));m.visible=false;scene.add(m);puffs.push({m:m,v:new T.Vector3(),life:0,max:1,s:.5});}})();
function puff(x,y,z,n,big,col,life){
  for(var i=0;i<n;i++){var p=puffs[pfI++%puffs.length];p.m.visible=true;p.m.position.set(x+(rnd()-.5)*.4,y+rnd()*.2,z);
    p.v.set((rnd()-.5)*1.4+(x<0?-.5:x>0?.5:0),.45+rnd()*.7,(rnd()-.3)*.5);p.max=p.life=(life||1.6)+rnd()*.8;p.s=(big?1:.62)*(.7+rnd()*.6);
    if(col===-1)p.m.material.color.setHSL(rnd(),.85,.65);else p.m.material.color.setHex(col||0x8fd14f);}
}
var flies=[];
(function(){var bg=new T.SphereGeometry(.07,8,6),wg=new T.SphereGeometry(.06,8,6),bm=basic(0x222222),wm=basic(0xffffff,{transparent:true,opacity:.7});
  for(var i=0;i<5;i++){var f=new T.Group();f.add(mesh(bg,bm));var w1=mesh(wg,wm,-.05,.06,0),w2=mesh(wg,wm,.05,.06,0);w1.scale.set(1,.4,.6);w2.scale.set(1,.4,.6);f.add(w1);f.add(w2);f.visible=false;scene.add(f);flies.push({g:f,life:0,ph:rnd()*6,c:new T.Vector3()});}})();
function stink(x,y,z,sec){
  flies.forEach(function(f,i){f.g.visible=true;f.life=sec;f.c.set(x+(rnd()-.5),y,z);f.ph=rnd()*6;});
  if(AC&&!muted){var t=AC.currentTime,o=AC.createOscillator(),g=AC.createGain(),l=AC.createOscillator(),lg=AC.createGain();o.type='sawtooth';o.frequency.value=230;l.frequency.value=19;lg.gain.value=.04;l.connect(lg);lg.connect(g.gain);g.gain.setValueAtTime(.0001,t);g.gain.linearRampToValueAtTime(.05,t+.3);g.gain.linearRampToValueAtTime(.0001,t+sec);var lp=AC.createBiquadFilter();lp.type='bandpass';lp.frequency.value=900;o.connect(lp);lp.connect(g);g.connect(sfxG);o.start(t);o.stop(t+sec+.1);l.start(t);l.stop(t+sec+.1);}
}
function stepFlies(dt){
  for(var i=0;i<flies.length;i++){var f=flies[i];if(!f.g.visible)continue;f.life-=dt;var a=time*(5+i)+f.ph;
    f.g.position.set(f.c.x+Math.cos(a)*(.6+.2*Math.sin(a*1.7)),f.c.y+.5+Math.sin(a*2.3)*.35,f.c.z+Math.sin(a)*.6);
    f.g.children[1].scale.y=f.g.children[2].scale.y=.2+Math.abs(Math.sin(time*60))*.4;if(f.life<=0)f.g.visible=false;}
}
function stepPuffs(dt){
  for(var i=0;i<puffs.length;i++){var p=puffs[i];if(!p.m.visible)continue;
    p.life-=dt;p.m.position.addScaledVector(p.v,dt);p.v.multiplyScalar(.97);var k=1-p.life/p.max;
    p.m.scale.setScalar(p.s*(.4+k*1.7));p.m.material.opacity=.8*(1-k*k);if(p.life<=0)p.m.visible=false;}
}
function tootA(a,silent){var F=FARTS[pick(['tiny','squeaky','bubbly','trumpet','singing'])];if(!silent)F.snd();a.squish(.2);puff(a.g.position.x,a.g.position.y+.25,a.g.position.z-.2,Math.min(5,F.n),false,F.col);a.wow(true);after(.9,function(){a.wow(false);sfx.giggle(true);});}
var hintA=null,hintM=mesh(new T.ConeGeometry(.24,.5,20),basic(0xffe14a));
hintM.rotation.x=PI;hintM.visible=false;scene.add(hintM);
function hint(a){hintA=a||null;}

/* ---------- surprises ---------- */
var spinCam=0,lastBoo=-1;
function everyone(fn){actors.slice().forEach(fn);}
var BOO=[
  function(){rain();say("It's raining shapes!",null,0);},
  function(){disco=5;document.body.classList.add('disco');say('Dance party!',null,0);for(var i=0;i<12;i++)tone(pick([262,330,392,523]),.16,{at:i*.4,type:'square',vol:.08});after(5,function(){disco=0;document.body.classList.remove('disco');},true);},
  function(){GST=1.5;sfx.boing(0);say('Giant shapes!',null,0);after(3.6,function(){GST=1;},true);},
  function(){GST=.42;sfx.giggle(true);say('Teeny tiny shapes!',null,0);after(3.6,function(){GST=1;},true);},
  function(){sfx.whoosh();say('Wheee! Round and round!',null,0);run(2.4,function(p){spinCam=p*PI*2;},E.io,function(){spinCam=0;},true);},
  function(){GET=2.2;sfx.boing(2);say('Googly eyes!',null,0);after(4.2,function(){GET=1;},true);},
  function(){
    say('Ah... ah... ah... choo!',null,0);everyone(function(a){a.wow(true);});
    after(1.7,function(){noise(.35,{f:1800,vol:.4});everyone(function(a){a.wow(false);a.hop(1+rnd()*.6,.5);burst(a.g.position.x,a.top(),a.g.position.z,8,{col:0xffffff,up:3});});},true);
  }
];
BOO.push(function(){
  say('Toot, toot, toot! Everybody tooted!',null,0);
  actors.slice().forEach(function(a,i){after(.5+i*.45,function(){if(actors.indexOf(a)>=0)tootA(a);});});
  if(mun)after(.5+actors.length*.45,function(){munFart('trumpet',true);});
});
function surprise(){
  var i;do{i=Math.floor(rnd()*BOO.length);}while(i===lastBoo||(reduce&&i===4)||(!FARTMODE&&i===BOO.length-1));
  lastBoo=i;BOO[i]();
}

/* sun: tap it for a surprise */
var sun=new T.Group();
(function(){
  var b=mesh(new T.SphereGeometry(1.5,28,20),basic(0xffd84a));b.userData.tap=function(){sfx.sparkle();surprise();};sun.add(b);extras.push(b);
  var rg=new T.ConeGeometry(.28,.8,10);sun.rays=new T.Group();
  for(var i=0;i<10;i++){var a=i/10*PI*2,r=mesh(rg,basic(0xffb93c),Math.cos(a)*2.1,Math.sin(a)*2.1,0);r.rotation.z=a-PI/2;sun.rays.add(r);}
  sun.add(sun.rays);
  var f=makeFace();f.scale.setScalar(3.4);f.position.set(0,-.05,1.4);sun.add(f);
  sun.position.set(-8.5,10.5,-24);scene.add(sun);
  var mb=mesh(new T.SphereGeometry(1.3,28,20),basic(0xfff3c4));moon.add(mb);
  var mf=makeFace();mf.scale.setScalar(2.9);mf.position.set(0,-.05,1.2);moon.add(mf);
  moon.position.set(-8.5,10.5,-24);moon.visible=false;scene.add(moon);
  var bm=new T.MeshStandardMaterial({color:0xe8e8f0,metalness:1,roughness:.18,flatShading:true});
  ball.add(mesh(new T.IcosahedronGeometry(.6,1),bm));ball.add(mesh(new T.CylinderGeometry(.015,.015,4,6),basic(0x888888),0,2.2,0));
  for(var i=0;i<6;i++){
    var cg=new T.ConeGeometry(1.15,7,18,1,true);cg.translate(0,-3.5,0);
    var bmat=new T.MeshBasicMaterial({color:0xffffff,transparent:true,opacity:0,blending:T.AdditiveBlending,depthWrite:false,side:T.DoubleSide,fog:false});
    var arm=new T.Group();arm.rotation.y=i/6*PI*2;var cone=mesh(cg,bmat);cone.rotation.x=.55;arm.add(cone);beams.add(arm);
  }
  ball.position.set(0,9.5,-.6);beams.position.copy(ball.position);ball.visible=beams.visible=false;scene.add(ball);scene.add(beams);
})();

/* ---------- costumes ---------- */
function tex(draw,w,h){var c=document.createElement('canvas');c.width=w||256;c.height=h||256;draw(c.getContext('2d'),c.width,c.height);return new T.CanvasTexture(c);}
function stripes(cols,n){return tex(function(x,w,h){for(var i=0;i<n;i++){x.fillStyle=cols[i%cols.length];x.fillRect(Math.floor(i*w/n),0,Math.ceil(w/n)+1,h);}});}
function spots(bg,cols){return tex(function(x,w,h){x.fillStyle=bg;x.fillRect(0,0,w,h);for(var i=0;i<8;i++)for(var j=0;j<5;j++){x.fillStyle=cols[(i+j)%cols.length];x.beginPath();x.arc(i*32+16+(j%2)*16,j*52+26,10,0,7);x.fill();}});}
function bricks(bg,ln){return tex(function(x,w,h){x.fillStyle=bg;x.fillRect(0,0,w,h);x.strokeStyle=ln;x.lineWidth=3;for(var j=0;j<8;j++){x.beginPath();x.moveTo(0,j*32);x.lineTo(w,j*32);x.stroke();for(var i=0;i<8;i++){x.beginPath();x.moveTo(i*32+(j%2)*16,j*32);x.lineTo(i*32+(j%2)*16,j*32+32);x.stroke();}}});}
var smallS=new T.SphereGeometry(1,16,12),unitB=new T.BoxGeometry(1,1,1),unitC=new T.CylinderGeometry(1,1,1,20),pipG=new T.CircleGeometry(.09,16);
function part(c,g,m,x,y,z,sx,sy,sz){var o=mesh(g,m,x,y,z,true);o.scale.set(sx,sy==null?sx:sy,sz==null?sx:sz);c.add(o);return o;}
function flame(c,x,y,z){part(c,geo('cone'),basic(0xffa51f),x,y,z,.16,.2,.16);part(c,geo('cone'),basic(0xfff06a),x,y-.02,z,.09,.12,.09);}
var COS={
  sphere:[
    {say:'A sphere can be a beach ball!',on:function(a){a.mat.map=stripes(['#ff5d5d','#ffffff','#4db8ff','#ffffff','#ffc93c','#ffffff'],12);a.mat.color.setHex(0xffffff);}},
    {say:'A sphere can be an orange!',on:function(a,c){a.mat.color.setHex(0xff9a2e);part(c,unitC,mat(0x6b4a2b),0,.63,0,.03,.12,.03);var l=part(c,smallS,mat(0x4fb85a),.13,.66,0,.16,.04,.09);l.rotation.z=.4;}},
    {say:'A sphere can be a planet!',on:function(a,c){a.mat.color.setHex(0x4d8dff);var r=part(c,new T.TorusGeometry(.92,.07,8,48),mat(YEL),0,0,0,1,1,.25);r.rotation.x=PI/2.3;}}
  ],
  cylinder:[
    {say:'A cylinder can be a drum! Boom, boom!',on:function(a,c){a.mat.color.setHex(RED);part(c,unitC,mat(0xfff7e6),0,.56,0,.5,.04,.5);part(c,unitC,mat(YEL),0,.5,0,.52,.07,.52);part(c,unitC,mat(YEL),0,-.5,0,.52,.07,.52);[-1,1].forEach(function(s){var k=part(c,unitC,mat(0xc98f4e),s*.42,.86,.12,.025,.6,.025);k.rotation.z=s*.6;part(c,smallS,mat(0xc98f4e),s*.24,1.1,.12,.06);});tone(120,.25,{to:60,vol:.4,at:.3});tone(120,.25,{to:60,vol:.4,at:.6});}},
    {say:'A cylinder can be a candle!',on:function(a,c){a.mat.map=stripes(['#ffffff','#ff9ecb'],10);a.mat.color.setHex(0xffffff);part(c,unitC,mat(0x333333),0,.6,0,.012,.12,.012);flame(c,0,.82,0);}}
  ],
  cone:[
    {say:'A cone can be a party hat!',on:function(a,c){a.mat.map=spots('#9b7bff',['#ffc93c','#ffffff','#ff6fa5']);a.mat.color.setHex(0xffffff);part(c,smallS,mat(0xffffff),0,.66,0,.13);}},
    {say:'A cone can be an ice cream! Yum!',on:function(a,c){a.mat.color.setHex(0xe5ad62);a.body.rotation.x=PI;part(c,smallS,mat(0xff9ecb),0,.95,0,.62);part(c,smallS,mat(0xe23c52),0,1.6,0,.11);a.face.position.set(0,.95,.6);a.face.rotation.x=0;a.fb=1;}}
  ],
  donut:[
    {say:'Yum! Sprinkles on the donut!',on:function(a,c){a.mat.color.setHex(0xe2aa66);part(c,new T.TorusGeometry(.45,.2,16,44),mat(0xff8fc0),0,0,.07,1);for(var i=0;i<16;i++){var t=i/16*PI*2+rnd()*.2,r=.45+(rnd()-.5)*.16,s=part(c,unitB,basic(pick(PAL)),Math.cos(t)*r,Math.sin(t)*r,.275,.07,.022,.022);s.rotation.z=rnd()*3;}}},
    {say:'A donut shape can be a swim ring!',on:function(a){a.mat.map=stripes(['#ff5d5d','#ffffff'],12);a.mat.color.setHex(0xffffff);}}
  ],
  cube:[
    {say:'A cube can be a present!',on:function(a,c){a.mat.color.setHex(BLUE);part(c,unitB,mat(YEL),0,0,0,1.03,.17,1.03);part(c,unitB,mat(YEL),0,0,0,.17,1.03,1.03);[-1,1].forEach(function(s){var b=part(c,smallS,mat(YEL),s*.17,.6,0,.19,.12,.1);b.rotation.z=s*.4;});}},
    {say:'A cube can be a dice! Roll it!',on:function(a,c){a.mat.color.setHex(0xffffff);[[-.32,.32],[.32,.32],[-.32,-.32],[.32,-.32]].forEach(function(p){c.add(mesh(pipG,basic(0x2b2140),p[0],p[1],.503));});var t=mesh(pipG,basic(0xff5d5d),0,.503,0);t.rotation.x=-PI/2;t.scale.setScalar(1.6);c.add(t);}}
  ],
  brick:[
    {say:'A brick can be a bus! Beep, beep!',on:function(a,c){a.mat.color.setHex(YEL);[-.5,.5].forEach(function(x){var w=part(c,unitC,mat(0x2b2140),x,-.19,.37,.16,.12,.16);w.rotation.x=PI/2;});[-.62,.62].forEach(function(x){part(c,unitB,mat(0xbfe9ff),x,.12,.4,.26,.24,.02);});tone(420,.14,{type:'square',vol:.12,at:.4});tone(420,.2,{type:'square',vol:.12,at:.6});}},
    {say:'A brick can be a birthday cake!',on:function(a,c){a.mat.color.setHex(0xffb3d1);part(c,unitB,mat(0xffffff),0,.39,0,1.63,.1,.83);[-.5,0,.5].forEach(function(x,i){part(c,unitC,mat(PAL[i+1]),x,.57,0,.035,.26,.035);flame(c,x,.82,0);});}}
  ],
  prism:[
    {say:'A prism can be a tent!',on:function(a,c){a.mat.map=stripes(['#ff9547','#ffe3b8'],8);a.mat.color.setHex(0xffffff);part(c,unitC,mat(0x8a6a4a),0,.75,0,.02,.5,.02);var f=part(c,geo('triangle'),mat(RED),.14,.9,0,.22,.22,1);f.rotation.z=-PI/2;}},
    {say:'A prism can be a piece of cheese!',on:function(a,c){a.mat.color.setHex(0xffd84d);[[-.36,-.34,.11],[.34,-.36,.08],[0,.2,.07],[.12,-.42,.05]].forEach(function(h){var m=mesh(pipG,basic(0xe0a92a),h[0],h[1],.503);m.scale.setScalar(h[2]/.09);c.add(m);});}}
  ],
  pyramid:[
    {say:'A pyramid can be a sand pyramid!',on:function(a){a.mat.map=bricks('#ecc98a','#c79b55');a.mat.color.setHex(0xffffff);}},
    {say:'A pyramid can be a snowy mountain!',on:function(a,c){a.mat.color.setHex(0x8e9ab5);var s=part(c,geo('pyramid'),mat(0xffffff),0,.342,0,.42);s.castShadow=false;}}
  ]
};
function undress(a){
  if(a.cos){a.tilt.remove(a.cos);freeTree(a.cos);a.cos=null;}
  if(a.mat.map)a.mat.map.dispose();a.mat.map=null;a.mat.color.setHex(a.color);a.mat.needsUpdate=true;a.body.rotation.x=0;
  a.face.position.set(0,a.d.f[0],a.d.f[1]);a.face.rotation.x=a.d.f[3];a.fb=a.d.f[2];
}
function dress(a){
  var list=COS[a.kind];a.ci=((a.ci==null?-1:a.ci)+1)%(list.length+1);
  undress(a);
  burst(a.g.position.x,a.top()*.6,a.g.position.z+.3,14,{col:0xffffff,up:3,sp:3});sfx.sparkle();a.hop(.35,.3);
  if(a.ci===list.length){say('Back to a plain '+a.d.name+'!',a.d.sub);return;}
  a.cos=new T.Group();a.tilt.add(a.cos);list[a.ci].on(a,a.cos);a.mat.needsUpdate=true;
  say(list[a.ci].say,'Same shape, new clothes. Tap again!');
}

/* ---------- tricks ---------- */
var TR={
  roll:function(a,done){var r=a.d.r*a.sc,w=nar()?1.05:1.9;run(3,function(p){var x=Math.sin(p*PI*2)*w;a.g.position.x=x;a.spin.rotation.z=-x/r;},E.lin,done);},
  canroll:function(a,done){
    a.hop(.3,.35);tw(a.tilt.rotation,{x:-PI/2},.35,E.io);tw(a.spin.position,{y:.5},.35,E.io,function(){
      
      TR.roll(a,function(){a.hop(.4,.4);tw(a.spin.position,{y:a.d.hy},.4,E.io);tw(a.tilt.rotation,{x:0},.4,E.back,done);});
    });
  },
  flop:function(a,done){
    var seq=nar()?[1,-1,-1,1]:[1,1,-1,-1],i=0,st1=a.sc;
    (function next(){
      if(i>=seq.length)return done();
      var dir=seq[i++],x0=a.g.position.x,r0=a.spin.rotation.z;
      run(.5,function(p){a.g.position.x=x0+dir*p*st1;a.spin.rotation.z=r0-dir*PI/2*p;a.spin.position.y=a.d.hy+Math.sin(p*PI)*.207;},E.io,function(){sfx.thud();a.squish(.12);after(.12,next);});
    })();
  },
  top:function(a,done){
    a.hop(.9,.5);tw(a.tilt.rotation,{x:PI},.5,E.io,function(){
      sfx.whoosh();
      run(2.6,function(p){a.spin.rotation.y=E.out(p)*PI*12;a.spin.rotation.z=Math.sin(p*26)*.16*p;},E.lin,function(){
        a.spin.rotation.z=0;a.spin.rotation.y=0;a.hop(.9,.5);tw(a.tilt.rotation,{x:0},.5,E.io,done);
      });
    });
  },
  turn:function(a,done){run(2.6,function(p){a.spin.rotation.y=p*PI*2;},E.io,function(){a.spin.rotation.y=0;a.hop(.4,.35,done);});},
  slide:function(a,done){sfx.whoosh();var w=nar()?.9:1.7;run(2.2,function(p){a.g.position.x=Math.sin(p*PI*2)*w;a.spin.rotation.z=-Math.cos(p*PI*2)*.07*Math.sin(p*PI);},E.lin,done);}
};
function settle(a){a.g.position.x=0;a.g.position.y=a.by;a.spin.rotation.set(0,0,0);a.tilt.rotation.set(0,0,0);a.spin.position.y=a.d.hy;}

/* ---------- camera ---------- */
var camP={ly:1,d:9,w:5},look=new T.Vector3(0,1,0),want=new T.Vector3(),orbit=0,view={zoom:1,zoomT:1,tilt:0,tiltT:0,idle:9,held:0};
function setCam(ly,d,w){camP={ly:ly,d:d,w:w};}
function resetView(){orbit=0;view.zoomT=1;view.tiltT=0;view.idle=9;}
function stepCam(dt){
  var fov=cam.aspect<1?50:40;if(cam.fov!==fov){cam.fov=fov;cam.updateProjectionMatrix();}
  view.idle+=dt;
  if(!view.held&&view.idle>6&&curName!=='look'){var k=Math.min(1,dt*1.6);orbit+=(0-orbit)*k;view.zoomT+=(1-view.zoomT)*k;view.tiltT+=(0-view.tiltT)*k;}
  view.zoom+=(view.zoomT-view.zoom)*Math.min(1,dt*10);view.tilt+=(view.tiltT-view.tilt)*Math.min(1,dt*10);
  var d=Math.max(camP.d,camP.w/(2*Math.tan(fov/2*PI/180)*cam.aspect))*view.zoom,an=orbit+spinCam,el=clamp(.266+view.tilt,curName==='look'?-.07:.06,1.4);
  want.set(Math.sin(an)*d*Math.cos(el),camP.ly+d*Math.sin(el),Math.cos(an)*d*Math.cos(el));
  cam.position.lerp(want,Math.min(1,dt*(spinCam||view.held?14:3.2)));
  look.y+=(camP.ly-look.y)*Math.min(1,dt*3);cam.lookAt(look);
}

/* ---------- scenes ---------- */
var S={},cur=null,curName='',started=false,busy=false,props=[];
function nar(){return cam.aspect<.8;}
function prop(m){scene.add(m);props.push(m);return m;}
var goT=0;
function go(name){
  var w=$('wipe');w.classList.remove('go');void w.offsetWidth;w.classList.add('go');sfx.whoosh();
  clearTimeout(goT);goT=setTimeout(function(){goNow(name);},240);
}
function goNow(name){
  gen++;resetView();dropQueued();busy=false;hint(null);
  actors.slice().forEach(function(a){a.kill();});
  if(cur&&cur.exit)cur.exit();
  props.forEach(function(m){scene.remove(m);freeTree(m);});props=[];
  puffs.forEach(function(p){p.m.visible=false;});
  curName=name;cur=S[name];
  var bs=document.querySelectorAll('#nav button[data-go]');
  for(var i=0;i<bs.length;i++){bs[i].classList.toggle('on',bs[i].getAttribute('data-go')===name);bs[i].classList.remove('beg');}
  $('stickers').hidden=name!=='pop';$('giggle').hidden=name!=='munch';
  cur.enter();
}
function tickle(a){
  var k=Math.floor(rnd()*(FARTMODE?6:4));if(k>=4&&!a.glass){tootA(a);return k;}if(k>=4)k=0;
  if(k===0){sfx.giggle();a.hop(.5+rnd()*.5,.4);}
  else if(k===1){sfx.boing(1);run(.6,function(p){a.spin.rotation.y=p*PI*2;},E.io,function(){a.spin.rotation.y=0;});}
  else if(k===2){sfx.giggle(true);a.squish(.35);}
  else{sfx.boing(2);a.hop(1.1,.55);burst(a.g.position.x,a.top(),a.g.position.z,6,{up:3});}
  return k;
}

/* Scene 1: Dot grows from a dot to a line to a square to a cube */
var dot,st;
S.story={
  enter:function(){
    setCam(.3,3,1.5);
    st={stage:0,taps:0,tL:.6,tH:.6,tD:.6};
    dot=new Actor('cube',PINK);dot.body.geometry=geo('ball1');dot.dims={L:.6,H:.6,D:.6};
    dot.idle=function(t,dt){var D=dot.dims,k=Math.min(1,dt*9);D.L+=(st.tL-D.L)*k;D.H+=(st.tH-D.H)*k;D.D+=(st.tD-D.D)*k;};
    dot.sc=0;tw(dot,{sc:1},.6,E.el);sfx.pop();
    say('This is Dot. Dot is teeny tiny. Tap Dot!','A dot has no size at all.');hint(dot);
  },
  tap:function(a){
    if(a!==dot)return;
    if(busy||st.stage>3){tickle(dot);return;}
    var s=st.stage;
    if(s===0){
      sfx.giggle();dot.hop(.7,.4);dot.body.geometry=geo('cube');st.stage=1;st.taps=0;st.tH=st.tD=.11;setCam(.35,4.6,nar()?3.4:4);
      say('Hee hee! Dot wants to be long. Tap, tap, tap!');return;
    }
    st.taps++;var p=st.taps/3;sfx.boing(st.taps);dot.squish(.12);
    if(s===1){st.tL=.6+2.4*p;}
    if(s===2){st.tH=.11+2.89*p;st.tD=.11-.06*p;}
    if(s===3){st.tD=.05+2.95*p;sfx.pump(st.taps);tw(dot.spin.rotation,{y:-.6*p},.3,E.io);}
    if(st.taps<3)return;
    busy=true;hint(null);
    if(s===1){
      sfx.tada();setCam(.4,5.2,nar()?3.5:4.4);say('Whoa! Dot is a line! Long, long, long.','1D: a line only has length.');
      after(1.4,function(){run(2.6,function(p){dot.g.position.x=Math.sin(p*PI*4)*.45;},E.lin);});
      after(4.4,function(){st.stage=2;st.taps=0;busy=false;hint(dot);setCam(1.5,8.6,4.2);say('Now make Dot tall. Tap, tap, tap!');});
    }else if(s===2){
      sfx.tada();say('Dot is a square! Flat, like paper.','2D: flat shapes have length and height, but no thickness.');
      after(3.2,function(){sfx.whoosh();dot.wow(true);say('Turn around... where did Dot go?');tw(dot.spin.rotation,{y:PI/2},.9,E.io);});
      after(6.2,function(){dot.wow(false);sfx.giggle();say('Peekaboo! There you are!');tw(dot.spin.rotation,{y:0},.7,E.back);});
      after(8.8,function(){st.stage=3;st.taps=0;busy=false;hint(dot);setCam(1.6,9.6,4.9);say('Dot is too flat to hug. Pump Dot up! Tap, tap, tap!');});
    }else{
      sfx.pop();sfx.tada();burst(0,3.2,0,60,{up:8,sp:5});
      say('Pop! Dot is a cube! Big and fat. Now you can hug Dot!','3D: solid shapes have length, height and depth.');
      setCam(1.7,10.2,nar()?6:5.4);
      dot.hop(1.2,.6);run(1.6,function(p){dot.spin.rotation.y=-.6+p*PI*2;},E.io);
      after(3,function(){addStar(3);});
      after(3.7,function(){say(goodJob());});
      after(5.4,function(){st.stage=4;busy=false;say("Dot wants to meet friends. Let's go!");beg('pop');after(3,function(){if(curName==='story')go('pop');});});
    }
  }
};
function beg(name){var b=document.querySelector('#nav button[data-go="'+name+'"]');if(b)b.classList.add('beg');}

/* Scene 2: flat shapes pop up into solid friends */
var papers,solid,found={},firstDress=true;
var FAM={circle:['sphere','cylinder','cone','donut'],square:['cube','brick'],triangle:['prism','pyramid']};
var ICON={
  sphere:'<circle cx="12" cy="12" r="9"/>',
  cylinder:'<path d="M5 6c0-1.700 3.100-3 7-3s7 1.300 7 3v12c0 1.700-3.100 3-7 3s-7-1.300-7-3z"/>',
  cone:'<path d="M12 2l8 16c0 1.700-3.600 3-8 3s-8-1.300-8-3z"/>',
  donut:'<path fill-rule="evenodd" d="M12 3a9 9 0 1 0 0 18a9 9 0 0 0 0-18zm0 5.500a3.500 3.500 0 1 1 0 7a3.500 3.500 0 0 1 0-7z"/>',
  cube:'<path d="M12 2l9 5v10l-9 5l-9-5V7z"/>',
  brick:'<path d="M2 10l5-4h15v8l-5 4H2z"/>',
  prism:'<path d="M2 19L8 6l6 13zM10.500 6H17l5 13h-6z"/>',
  pyramid:'<path d="M12 3l10 16H2z"/>'
};
(function(){
  var h='';SOLIDS.forEach(function(k){h+='<span id="st_'+k+'"><svg viewBox="0 0 24 24">'+ICON[k]+'</svg></span>';});
  $('stickers').innerHTML=h;
  SOLIDS.forEach(function(k,i){$('st_'+k).style.setProperty('--c','#'+('00000'+PAL[i].toString(16)).slice(-6));});
})();
function collect(k){
  if(found[k])return;found[k]=1;save.found.push(k);$('st_'+k).classList.add('got');addStar(1);
  if(Object.keys(found).length===8)after(5.5,function(){sfx.tada();burst(0,3,1,90,{up:9,sp:6});rain();addStar(5);say('You found all eight shapes! Hooray!');after(3,function(){say(goodJob());},true);after(5.2,function(){if(curName!=='pop')return;say("Now let's feed Munchy!");beg('munch');after(2.4,function(){if(curName==='pop')go('munch');},true);},true);},true);
}
S.pop={
  enter:function(){
    var n=nar(),dx=n?1.22:1.75;setCam(n?1.45:1.25,7,n?3.9:6.4);solid=null;papers=[];
    var wood=mat(0xd9a066),sh=prop(mesh(unitB,wood,0,1.6,-2.2,true));sh.scale.set(dx*2+1.5,.22,1.1);sh.receiveShadow=true;
    [-1,1].forEach(function(s){var l=prop(mesh(unitB,wood,s*(dx+.45),.75,-2.2,true));l.scale.set(.22,1.5,.9);});
    [['circle',BLUE,-dx],['square',YEL,0],['triangle',GRN,dx]].forEach(function(p,i){
      var a=new Actor(p[0],p[1]);a.isPaper=true;a.fam=shuffle(FAM[p[0]]);a.fi=0;a.by=1.72;a.g.position.set(p[2],1.72,-2.1);
      a.idle=function(t){if(!a.busy){a.spin.rotation.z=Math.sin(t*1.6+i)*.07;a.spin.rotation.y=Math.sin(t*.9+i*2)*.25;}};
      a.sc=0;after(.15*i,function(){sfx.pop();tw(a,{sc:1},.5,E.el);});papers.push(a);
    });
    say('Flat shapes! Tap one to pop it up!','Flat shapes are 2D. Popped-up shapes are 3D.');hint(papers[1]);
  },
  tap:function(a){
    if(a.isPaper){if(!busy)popFrom(a);else tickle(a);}
    else if(a===solid){if(busy)tickle(a);else{dress(a);if(firstDress)firstDress=false;}}
  }
};
function popFrom(pa){
  busy=true;hint(null);
  if(solid){var old=solid;solid=null;sfx.whoosh();tw(old,{sc:0},.3,E.io,function(){old.kill();});}
  var kind=pa.fam[pa.fi++];if(pa.fi>=pa.fam.length){var lastK=kind;do{pa.fam=shuffle(pa.fam);}while(pa.fam.length>1&&pa.fam[0]===lastK);pa.fi=0;}
  var d=DEF[kind];
  pa.busy=true;sfx.boing(1);pa.hop(.5,.5);pa.spin.rotation.z=0;
  run(.7,function(p){pa.spin.rotation.y=p*PI*2;},E.io,function(){pa.busy=false;});
  after(.45,function(){
    var a=new Actor(kind,pa.color);solid=a;a.fs=0;a.zs=.05;a.sc=.9;
    if(d.pre){a.tilt.rotation.x=d.pre[0];a.spin.rotation.y=d.pre[1];}
    a.g.position.copy(pa.g.position);
    var x0=pa.g.position.x,z0=pa.g.position.z;
    var PZ=nar()?1.2:.5;run(.6,function(p){a.g.position.set(x0*(1-p),1.72*(1-p)+Math.sin(p*PI)*.9,z0+(PZ-z0)*p);},E.io,function(){
      var i=0;
      (function puff(){
        if(i<3){sfx.pump(i);var to=[.3,.62,1][i++];tw(a,{zs:to},.2,E.back,function(){after(.1,puff);});return;}
        sfx.pop();burst(0,1,PZ+.2,26,{up:6});a.squish(.25);tw(a,{sc:1.25},.3,E.back);
        tw(a.tilt.rotation,{x:0},.45,E.back);tw(a.spin.rotation,{y:0},.45,E.back);
        after(.4,function(){tw(a,{fs:1},.5,E.el);say(d.say,d.sub);collect(kind);});
        after(2.6,function(){
          say(d.fact,d.sub);
          TR[d.trick](a,function(){settle(a);busy=false;if(firstDress){hint(a);after(.4,function(){say('Tap it again for a surprise!');});}});
        });
      })();
    });
  });
}

/* Scene 3: Munchy only eats shapes that fit the mouth */
var mun,friends,fed=0,lastHole='',wrong=0,MY=.5;
function goodJob(){var n=(save.name||'').trim();return n?'Yes! Good job, '+n+'!':'Yes! Good job!';}
var FIT={circle:['sphere','cylinder','cone','donut'],square:['cube','pyramid'],triangle:['prism']};
var NOFIT={circle:['cube','brick','prism','pyramid'],square:['sphere','cylinder','cone','donut','prism'],triangle:['sphere','cylinder','cube','donut','brick']};
var WHY={sphere:'is round all over',cylinder:'has a circle on its end',cone:'has a circle on its bottom',donut:'is a round ring',cube:'has square sides',pyramid:'has a square bottom',prism:'has a triangle on its end',brick:'has long flat sides'};
var SHOW={cylinder:PI/2,cone:PI/2,pyramid:PI/2};
function makeMunchy(){
  var g=new T.Group(),m={g:g,s:1,sc:1};
  m.mat=mat(PUR);m.body=mesh(smallS,m.mat,0,1.25,0,true);m.body.scale.set(1.35,1.28,1.2);m.body.userData.tap=function(){munTap();};
  m.in=new T.Group();g.add(m.in);m.in.add(m.body);
  var dark=basic(0x3a1030);m.holes={};
  ['circle','square','triangle'].forEach(function(k){var h=mesh(geo(k),dark,0,.95,1.17);h.visible=false;m.in.add(h);m.holes[k]=h;});
  m.face=makeFace();m.face.scale.setScalar(2.3);m.face.position.set(0,1.95,.92);m.face.mouth.visible=false;m.face.rotation.x=-.35;m.in.add(m.face);
  [-1,1].forEach(function(s){
    var h=mesh(geo('cone'),mat(YEL),s*.75,2.5,0,true);h.scale.setScalar(.45);h.rotation.z=-s*.45;m.in.add(h);
    var f=mesh(smallS,mat(ORA),s*.62,.14,.75,true);f.scale.set(.4,.16,.5);g.add(f);
    var fg=mesh(geo('cone'),mat(0xffffff),s*.3,1.5,1.13,true);fg.scale.set(.14,.2,.14);fg.rotation.x=PI;m.in.add(fg);
  });
  [-1,0,1].forEach(function(i){var t=mesh(geo('cone'),mat(0x7d5ce0),i*.17,2.66,.1,true);t.scale.set(.17,.42,.17);t.rotation.z=-i*.38;m.in.add(t);});
  [[-.75,.35,.56],[.8,.25,.55],[-.55,.75,-.38],[.9,-.2,-.4],[0,.55,-.84],[-.95,-.3,.1]].forEach(function(d){
    var v=new T.Vector3(d[0],d[1],d[2]).normalize(),sp=mesh(smallS,mat(0xc9b4ff),v.x*1.33,1.25+v.y*1.26,v.z*1.18);sp.scale.setScalar(.15);m.in.add(sp);
  });
  function arm(sd){var a=new T.Group();a.position.set(sd*1.22,1.38,.25);var u=mesh(unitC,mat(PUR),0,-.32,0,true);u.scale.set(.11,.64,.11);a.add(u);var h=mesh(smallS,mat(PUR),0,-.68,0,true);h.scale.setScalar(.2);a.add(h);a.rotation.z=sd*.35;m.in.add(a);return a;}
  m.armL=arm(-1);m.armR=arm(1);
  var sm=mat(0x1a1830,{roughness:.15,metalness:.4}),lens=new T.CylinderGeometry(.13,.13,.02,24).rotateX(PI/2);
  m.shades=new T.Group();m.shades.add(mesh(lens,sm,-.17,.04,.1));m.shades.add(mesh(lens,sm,.17,.04,.1));var br=mesh(unitB,sm,0,.08,.1);br.scale.set(.12,.025,.02);m.shades.add(br);
  m.shades.scale.setScalar(.001);m.face.add(m.shades);
  m.act='idle';m.ex={y:0,rz:0,ry:0};m.eyeS=1;m.ps=1;m.loose=0;m.squint=0;m.idleT=0;m.prev=0;m.prevR=0;
  m.gp=[{x:0,y:0,vx:0,vy:0},{x:0,y:0,vx:0,vy:0}];
  g.position.set(0,MY,-1.5);scene.add(g);return m;
}
function munKick(k){if(!mun)return;mun.gp.forEach(function(p){p.vx+=(rnd()-.5)*k;p.vy+=(rnd()-.2)*k;});}
var MREACT=['laugh','dance','googly','toot','laugh'],mri=0,gig=0,FARTMODE=false,fartT=3;
function munTap(){
  if(!mun)return;
  if(mun.act!=='idle'){sfx.giggle();munKick(.8);munSquash(.1);return;}
  var r=rnd()<.3?pick(MREACT):MREACT[mri++%MREACT.length];if(r==='toot'&&!FARTMODE)r='laugh';else if(FARTMODE&&rnd()<.5)r='toot';
  munReact(r);
}
function munReact(r,done){
  if(!mun){if(done)done();return;}
  if(r==='laugh')munLaugh(done,true);else if(r==='dance')munDance(done);else if(r==='googly')munGoogly(done);
  else if(r==='burp'){sfx.burp(.6);munSquash(.14);after(.9,function(){munLaugh(done,false);});}
  else munFart(null,false,done);
}
function gigAdd(){
  gig++;$('gfill').style.width=Math.min(100,gig*20)+'%';
  var gm=$('giggle');gm.classList.remove('bump');void gm.offsetWidth;gm.classList.add('bump');
  if(gig>=5){gig=0;after(1.4,function(){gigParty();});after(1.6,function(){$('gfill').style.width='0%';});}
}
function gigParty(){
  if(!mun)return;munSay('Giggle party! Everybody laugh!',null,{p:1});addStar(2);rain();
  for(var i=0;i<5;i++)after(i*.5,function(){burst((rnd()-.5)*5,3.5,(rnd()-.5)*2,18,{up:4,sp:4});sfx.giggle(rnd()<.5);});
  friends.forEach(function(f,i){for(var j=0;j<4;j++)after(.3+j*.55+i*.1,function(){if(actors.indexOf(f)>=0)f.hop(.7,.4);});});
  after(1.6,function(){munShake(2.2,.12,true);});
}
function munShake(sec,amp,tears){
  if(!mun)return;var m=mun;m.act='laugh';tw(m,{squint:1},.2,E.io);
  run(sec,function(p){m.ex.rz=Math.sin(p*sec*28)*amp*(1-p*.4);m.s=1-.07*Math.abs(Math.sin(p*sec*14));m.ex.y=Math.abs(Math.sin(p*sec*14))*.12;},E.lin,function(){m.ex.rz=0;m.ex.y=0;m.s=1;tw(m,{squint:0},.25,E.io);m.act='idle';});
  if(tears)[.3,.9,1.5].forEach(function(t){after(t,function(){if(!mun)return;[-1,1].forEach(function(sd){burst(sd*.55,2.1+MY,-.35,4,{col:0x7fd3ff,up:2.5,sp:1.6,size:.7});});});});
}
function munLaugh(done,big){
  if(!mun){if(done)done();return;}
  munSay(pick(['Ha ha ha! That tickles!','Hee hee hee! Again! Again!','Ha ha ha ha ha!','Ho ho ho! Hee hee hee!']));
  munShake(2,big?.13:.09,big);sfx.giggle();after(.5,function(){sfx.giggle(true);});
  if(rnd()<.6)friends.forEach(function(f,i){after(.4+i*.2,function(){if(actors.indexOf(f)>=0){f.hop(.5,.35);sfx.giggle(true);}});});
  after(1.2,gigAdd);
  after(2.3,function(){if(done)done();});
}
function munGoogly(done){
  if(!mun){if(done)done();return;}
  mun.act='googly';munSay(pick(['Whoa! Look at my googly eyes!','Boing! Big googly eyes!']));sfx.boing(2);
  tw(mun,{eyeS:2.1,ps:.72,loose:1},.6,E.el);munKick(3);
  run(2.6,function(p){mun.ex.rz=Math.sin(p*PI*7)*.16;mun.ex.y=Math.abs(Math.sin(p*PI*7))*.2;},E.lin,function(){mun.ex.rz=0;mun.ex.y=0;});
  after(1.4,function(){sfx.boing(1);munKick(4);});
  after(4,function(){if(!mun)return;tw(mun,{eyeS:1,ps:1,loose:0},.5,E.back,function(){if(mun)mun.act='idle';if(done)done();});});
}
var SONG=[7,9,7,4,7,9,12,null,12,9,7,4,0,2,4,null];
function munDance(done){
  if(!mun){if(done)done();return;}
  mun.act='dance';var st=.22;munSay('Let me dance! Wiggle, wiggle!',null,{p:2});
  queueLine({t:'\u266a La la la! I love shapes! \u266a',sub:'Munchy is singing.',who:'m',p:2,sing:true,dur:st*16+.35,start:function(){
    if(!mun){if(done)done();return;}
    if(DANCE===0)riff(st,16);sing(SONG,st);
    run(st*16,function(p){mun.ex.y=Math.abs(Math.sin(p*PI*8))*.45;mun.ex.rz=Math.sin(p*PI*8)*.18;mun.ex.ry=p>.45&&p<.7?(p-.45)/.25*PI*2:0;},E.lin,function(){
      mun.ex.y=0;mun.ex.rz=0;mun.ex.ry=0;if(!mun)return;sfx.tada();burst(0,3.2,-1,30,{up:5});mun.act='idle';gigAdd();after(.8,function(){if(done)done();});
    });
    friends.forEach(function(f,i){for(var j=0;j<6;j++)after(j*st*2.6+i*.12,function(){if(actors.indexOf(f)>=0)f.hop(.45,.3);});});
  }});
}
function munFart(kind,quiet,done){
  if(!mun){if(done)done();return;}
  var k=kind||pick(FKINDS),F=FARTS[k];F.snd();munSquash(.15);munKick(2);
  var y0=mun.g.position.y;run(.5,function(p){mun.g.position.y=y0+Math.sin(p*PI)*(F.stink>=3?.8:.35);},E.out,function(){mun.g.position.y=y0;});
  var big=F.stink>=3,lf=big?3.2:1.6;
  puff(-1.05,.35+MY,-1.1,Math.ceil(F.n/2),big,F.col,lf);puff(1.05,.35+MY,-1.1,Math.ceil(F.n/2),big,F.col,lf);
  if(big){stink(0,.6+MY,-.6,3.4);friends.forEach(function(f,i){if(actors.indexOf(f)<0)return;f.wow(true);tw(f.tilt.rotation,{x:-1.25},.45,E.out);after(1.9+i*.2,function(){if(actors.indexOf(f)<0)return;tw(f.tilt.rotation,{x:0},.4,E.back);f.wow(false);sfx.boing(0);});});}
  else friends.forEach(function(f){if(actors.indexOf(f)>=0){f.wow(true);after(1.1,function(){f.wow(false);});}});
  if(!quiet)say(F.say,null,0);
  after(quiet?1:1.9,function(){if(!mun){if(done)done();return;}munSay(pick(['Hee hee! Excuse me!','Oops! Ha ha ha!','Not me! Ha ha!']));munShake(1.5,.1,false);after(.8,gigAdd);after(1.7,function(){if(done)done();});});
}
function stepMun(dt){
  if(!mun)return;var m=mun;
  if(m.act==='idle'&&!busy){m.idleT+=dt;if(m.idleT>16+rnd()*6){m.idleT=0;sfx.boing(3);m.hiccup=1;var y0=m.ex.y;run(.3,function(p){m.ex.y=Math.sin(p*PI)*.25;},E.lin,function(){m.ex.y=0;});munKick(2.5);}}else m.idleT=0;
  var mo=m.g.position.y+m.ex.y,dv=(mo-m.prev)/Math.max(dt,.001),dr=(m.ex.rz-m.prevR)/Math.max(dt,.001);m.prev=mo;m.prevR=m.ex.rz;
  var R=.105-.055*m.ps-.004;
  for(var j=0;j<2;j++){
    var p=m.gp[j],tx=Math.sin(time*.7+j)*.012,ty=Math.cos(time*.9)*.008,K=m.loose?0:60,D=m.loose?1.2:7;
    p.vx+=((tx-p.x)*K-p.vx*D-dr*.04)*dt;p.vy+=((ty-p.y)*K-p.vy*D-dv*.02-(m.loose?2.2:0))*dt;
    p.x+=p.vx*dt;p.y+=p.vy*dt;var d=Math.sqrt(p.x*p.x+p.y*p.y);
    if(d>R){p.x*=R/d;p.y*=R/d;var nx=p.x/R,ny=p.y/R,vn=p.vx*nx+p.vy*ny;if(vn>0){p.vx-=1.6*vn*nx;p.vy-=1.6*vn*ny;}}
    var e=m.face.eyes[j],sd=j===0?-1:1;e.pupil.position.set(p.x,p.y,.05);e.pupil.scale.set(m.ps,m.ps,m.ps*.5);
    e.position.set(sd*(.17+(m.eyeS-1)*.075),.04+(m.eyeS-1)*.05,(m.eyeS-1)*.03);
  }
  var t=time,L,Rr;
  if(m.act==='laugh'){L=.8+Math.sin(t*22)*.1;Rr=-.8-Math.sin(t*22)*.1;}
  else if(m.act==='dance'||(m.act==='idle'&&danceD>.5)){L=-(1.7+Math.sin(t*8)*1.0);Rr=1.7+Math.sin(t*8+PI)*1.0;}
  else if(m.act==='googly'){L=-2.3+Math.sin(t*9)*.15;Rr=2.3-Math.sin(t*9)*.15;}
  else if(m.act==='wave'){L=-.35;Rr=2.5+Math.sin(t*12)*.4;}
  else{L=-.35+Math.sin(t*1.5)*.08;Rr=.35+Math.sin(t*1.5+1)*.08;}
  var k=Math.min(1,dt*12);m.armL.rotation.z+=(L-m.armL.rotation.z)*k;m.armR.rotation.z+=(Rr-m.armR.rotation.z)*k;
  var sh=partyD>.5?1:.001;m.shades.scale.setScalar(m.shades.scale.x+(sh-m.shades.scale.x)*Math.min(1,dt*8));
}
function munFartOld(big,quiet){
  if(!mun)return;sfx.fart(big?1.15:.7);munSquash(.15);
  var y0=mun.g.position.y;run(.5,function(p){mun.g.position.y=y0+Math.sin(p*PI)*(big?.7:.35);},E.out,function(){mun.g.position.y=y0;});
  puff(-1.05,.35,-1.1,big?6:4,big);puff(1.05,.35,-1.1,big?6:4,big);
  friends.forEach(function(f){if(actors.indexOf(f)>=0){f.wow(true);after(1.1,function(){f.wow(false);});}});
  GET=1.6;after(1.2,function(){GET=1;});
  after(1.2,function(){sfx.giggle();});
  if(!quiet)say(pick(['Oops! Munchy tooted!','Toot toot! Hee hee!','Pee-yew! Stinky!']));
}
function munSquash(k){if(!mun)return;var m=mun;run(.4,function(p){m.s=1-k*Math.sin(p*PI);},E.lin,function(){m.s=1;});}
var MUNCH=[
  function(){tw(mun,{sc:1.3},.4,E.back,function(){after(.8,function(){tw(mun,{sc:1},.4,E.io);});});},
  function(){mun.mat.color.setHex(pick([PINK,TEAL,ORA,GRN,BLUE,PUR]));burst(0,2.6,-1.2,20,{up:5});},
  function(){for(var i=0;i<4;i++)after(i*.22,function(){burst((rnd()-.5)*.4,1.6,-.2,5,{col:0xffffff,up:4,g:-1,sp:1});sfx.plink();});},
  function(){run(.9,function(p){mun.g.rotation.y=p*PI*2;mun.g.position.y=Math.sin(p*PI)*1.2;},E.io,function(){mun.g.rotation.y=0;mun.g.position.y=0;sfx.thud();munSquash(.25);});},
  function(){GET=2;after(2,function(){GET=1;});sfx.boing(2);},
  function(){tw(mun.g.position,{y:2.2},1.1,E.out,function(){after(.5,function(){tw(mun.g.position,{y:0},.35,E.io,function(){sfx.thud();munSquash(.3);});});});}
];
S.munch={
  enter:function(){
    setCam(nar()?1.55:1.3,8.4,nar()?4.1:6.4);mun=makeMunchy();fed=0;friends=[];
    var stg=prop(mesh(unitC,mat(0xff8fc0),0,MY/2,-1.5,true));stg.scale.set(1.75,MY,1.75);stg.receiveShadow=true;
    var rim=prop(mesh(new T.TorusGeometry(1.75,.07,10,56),mat(YEL),0,MY,-1.5));rim.rotation.x=PI/2;
    for(var si=0;si<10;si++){var an=si/10*PI*2,dt_=prop(mesh(smallS,basic(0xfff6c9),Math.cos(an)*1.76,MY*.5,-1.5+Math.sin(an)*1.76));dt_.scale.setScalar(.07);}
    mun.sc=.01;tw(mun,{sc:1},.6,E.el);sfx.boing(0);gig=0;$('gfill').style.width='0%';wrong=0;
    mun.act='wave';munSay('Hi! I am Munchy! Feed me shapes!',null,{p:1});after(2.6,function(){if(mun)mun.act='idle';});after(2.9,round);
  },
  exit:function(){if(mun){scene.remove(mun.g);freeTree(mun.g);mun=null;}},
  tap:function(a){
    if(!a.isFriend)return;if(busy){tickle(a);return;}
    busy=true;hint(null);
    var ok=FIT[mun.hole].indexOf(a.kind)>=0,d=a.d,x0=a.g.position.x,z0=a.g.position.z;
    sfx.boing(1);if(SHOW[a.kind])tw(a.tilt.rotation,{x:SHOW[a.kind]},.4,E.io);
    var y0=a.g.position.y;run(.6,function(p){a.g.position.set(x0*(1-p),y0*(1-p)+p*(.95+MY-d.hy)+Math.sin(p*PI)*1.3,z0+(.1-z0)*p);},E.io,function(){
      if(ok){
        sfx.chomp();munSquash(.18);tw(a,{sc:0},.3,E.io);tw(a.g.position,{z:-.7},.3,E.io,function(){a.kill();});
        fed++;addStar(1);hint(null);say(goodJob(),'The '+d.name+' '+WHY[a.kind]+', so it fits the '+mun.hole+'.');
        burst(0,2.4,-.8,24,{up:5});munKick(2);
        var ev=FARTMODE?(fed%3===0?'rumble':pick(['toot','toot','toot','laugh','dance'])):(fed%4===0?'party':pick(['laugh','laugh','dance','googly','burp']));
        after(1.9,function(){
          if(!mun)return;
          if(mun.act!=='idle'){after(1.2,round);return;}
          if(ev==='rumble'){munFart('rumble',false,function(){after(.4,round);});}
          else if(ev==='party'){gigParty();after(4.8,round);}
          else munReact(ev,function(){after(.4,round);});
        });
      }else{
        sfx.bonk();a.wow(true);run(.5,function(p){mun.g.rotation.y=Math.sin(p*PI*4)*.25;},E.lin,function(){mun.g.rotation.y=0;});
        say('Bonk! The '+d.name+' does not fit. Try again!','The '+d.name+' '+WHY[a.kind]+'. The mouth is a '+mun.hole+'.');
        wrong++;munKick(2);
        run(.6,function(p){a.g.position.set(a.home.x*p,(1-p)*(.95+MY-d.hy)+Math.sin(p*PI)*1.2,.1+(a.home.z-.1)*p);},E.io,function(){
          a.wow(false);a.squish(.3);tw(a.tilt.rotation,{x:0},.3,E.io);busy=false;
          var rt=friends.filter(function(f){return actors.indexOf(f)>=0&&FIT[mun.hole].indexOf(f.kind)>=0;})[0];
          if(rt){hint(rt);after(.3,function(){if(actors.indexOf(rt)>=0){rt.hop(.6,.4);sfx.plink();}});}
        });
      }
    });
  }
};
function goHome(a){a.s=1;tw(a.g.position,{x:a.home.x,y:0,z:a.home.z},.35,E.back);sfx.boing(0);}
function round(){
  if(!mun||curName!=='munch')return;
  if(fed>=8){fed=0;say("What a full tummy! Let's look closely at the shapes.");beg('look');after(3.6,function(){if(curName==='munch')go('look');});return;}
  var hole;do{hole=pick(['circle','square','triangle']);}while(hole===lastHole);lastHole=hole;mun.hole=hole;
  for(var k in mun.holes){mun.holes[k].visible=k===hole;}
  var h=mun.holes[hole];h.scale.setScalar(.01);tw(h.scale,{x:1,y:1,z:1},.5,E.el);sfx.pop();
  var kinds=shuffle([pick(FIT[hole])].concat(shuffle(NOFIT[hole]).slice(0,2))),cols=shuffle(PAL);
  (friends||[]).forEach(function(f){if(actors.indexOf(f)>=0)tw(f,{sc:0},.3,E.io,function(){f.kill();});});
  friends=[];wrong=0;hint(null);
  kinds.forEach(function(kd,i){
    var a=new Actor(kd,cols[i]);a.isFriend=true;a.g.position.set((i-1)*(nar()?1.12:1.8),0,nar()?1.5:1.25);a.home={x:a.g.position.x,z:a.g.position.z};a.sc=0;
    after(.5+i*.15,function(){tw(a,{sc:nar()?.76:.92},.5,E.el);sfx.plink();});friends.push(a);
  });
  busy=false;
  say('Munchy wants a '+hole+'. Who fits?','Each solid shape has flat shapes hiding on it.');
}

/* Scene 4: one clear shape to turn over, flatten to 2D or squeeze to 1D */
var lk=null,lkI=0,lkDim=3,lkFlip=false,lkBusy=false,AX=new T.Vector3(1,0,0),AY=new T.Vector3(0,1,0),AZ=new T.Vector3(0,0,1);
var DIMSAY=['','1D! Now it is just a line.','2D! Now it is flat, like a drawing.','3D! A solid shape again.'];
function circleLine(r,plane,z,m){
  var pts=[];for(var i=0;i<=64;i++){var t=i/64*PI*2,x=Math.cos(t)*r,y=Math.sin(t)*r;pts.push(plane==='xy'?new T.Vector3(x,y,z):plane==='xz'?new T.Vector3(x,z,y):new T.Vector3(z,x,y));}
  return new T.Line(new T.BufferGeometry().setFromPoints(pts),m);
}
function glassify(a){
  a.glass=true;a.mat.dispose();
  a.mat=new T.MeshPhysicalMaterial({color:a.color,roughness:.08,metalness:0,clearcoat:1,clearcoatRoughness:.05,transparent:true,opacity:lkDim===3?.34:lkDim===2?.78:.95,depthWrite:false,side:T.DoubleSide,envMapIntensity:1.3});
  a.body.material=a.mat;
  var c=new T.Color(a.color).lerp(new T.Color(0x2b2140),.45),lm=new T.LineBasicMaterial({color:c,transparent:true,opacity:.95,depthTest:false});
  var e=new T.LineSegments(new T.EdgesGeometry(geo(a.kind),a.kind==='star'?50:20),lm);e.renderOrder=2;a.body.add(e);
  var extra=[];
  if(a.kind==='sphere')extra=[[.6,'xy',0],[.6,'xz',0],[.6,'yz',0]];
  if(a.kind==='donut')extra=[[.67,'xy',0],[.23,'xy',0],[.45,'xy',.22],[.45,'xy',-.22]];
  if(a.kind==='egg')extra=[[.5,'xz',0]];
  extra.forEach(function(x){var l=circleLine(x[0],x[1],x[2],lm);l.renderOrder=2;a.body.add(l);});
  if(a.kind==='egg')['xy','yz'].forEach(function(pl){var l=circleLine(.5,pl,0,lm);l.scale.y=1.3;l.renderOrder=2;a.body.add(l);});
}
var LKS=function(){return nar()?1.45:1.2;},lkB=null;
/* every shape in the look-closely place, in four teams */
var TEAMS=[
  {name:'Round team',say:'The round team! Curvy shapes that can roll.',sub:'Curved surfaces: sphere, dome, egg, cylinder, cone and donut.',col:PINK,mat:0xff86b6,icon:'<circle cx="12" cy="12" r="9"/>',ks:['sphere','dome','egg','cylinder','cone','donut']},
  {name:'Stack team',say:'The stack team! Flat on top, so they stack up.',sub:'Prisms: the same shape all the way through.',col:YEL,mat:0xffc93c,icon:'<path d="M12 2l9 5v10l-9 5l-9-5V7z"/>',ks:['cube','brick','prism','hexprism','pentprism','star']},
  {name:'Pointy team',say:'The pointy team! A flat bottom and a point on top.',sub:'Pyramids: flat sides that meet at one point.',col:GRN,mat:0x63d998,icon:'<path d="M12 3l10 16H2z"/>',ks:['pyramid','tpyramid','pentpyramid','hexpyramid']},
  {name:'Gem team',say:'The gem team! Lots of flat sides, like jewels.',sub:'Polyhedra with eight, twelve and twenty faces.',col:PUR,mat:0xab93ff,icon:'<path d="M7 3h10l5 6-10 12L2 9z"/>',ks:['octa','dodeca','icosa']}
];
var LOOKS=[],LTEAM=[];TEAMS.forEach(function(t,ti){t.ks.forEach(function(k){LOOKS.push(k);LTEAM.push(ti);});});
var LCOL={sphere:PINK,dome:TEAL,egg:ORA,cylinder:YEL,cone:BLUE,donut:GRN,cube:PUR,brick:ORA,prism:RED,hexprism:BLUE,pentprism:GRN,star:YEL,pyramid:TEAL,tpyramid:PINK,pentpyramid:PUR,hexpyramid:ORA,octa:BLUE,dodeca:PINK,icosa:PUR};
function hexC(c){return '#'+('00000'+c.toString(16)).slice(-6);}
function teamSign(t){
  var c=document.createElement('canvas');c.width=512;c.height=144;var x=c.getContext('2d');
  function rr(a,b,w,h,r){x.beginPath();x.moveTo(a+r,b);x.arcTo(a+w,b,a+w,b+h,r);x.arcTo(a+w,b+h,a,b+h,r);x.arcTo(a,b+h,a,b,r);x.arcTo(a,b,a+w,b,r);x.closePath();}
  x.fillStyle='#2b2140';rr(6,6,500,132,62);x.fill();x.fillStyle=hexC(t.col);rr(16,16,480,112,54);x.fill();
  x.fillStyle='#2b2140';x.font='700 62px Fredoka, "Trebuchet MS", sans-serif';x.textAlign='center';x.textBaseline='middle';x.fillText(t.name,256,76);
  var tx=new T.CanvasTexture(c);tx.anisotropy=4;
  return new T.Sprite(new T.SpriteMaterial({map:tx,transparent:true,depthWrite:false}));
}
function markTeam(ti){var cs=document.querySelectorAll('#chips button');for(var j=0;j<cs.length;j++)cs[j].classList.toggle('on',j===ti);}
/* a team is picked as a whole (its mat, sign, any of its shapes or its button), then a popup shows its shapes big */
var THUMB={},thS=null,thRT=null,thCam=null,thC=null,popTeam=-1,popAt=0;
function thumbOf(k){
  if(THUMB[k]||!R)return THUMB[k]||'';
  var N=256;
  if(!thS){thS=new T.Scene();thS.add(new T.HemisphereLight(0xffffff,0xcfe9ff,.9));var dl=new T.DirectionalLight(0xffffff,.85);dl.position.set(2,4,5);thS.add(dl);
    thRT=new T.WebGLRenderTarget(N,N);thCam=new T.PerspectiveCamera(30,1,.1,50);thC=document.createElement('canvas');thC.width=thC.height=N;}
  var a=new Actor(k,LCOL[k]);scene.remove(a.g);var ix=actors.indexOf(a);if(ix>=0)actors.splice(ix,1);
  var h=a.d.hy;a.spin.rotation.set(0,.42,0);thCam.position.set(0,h+.55,4.1);thCam.lookAt(0,h,0);thS.add(a.g);
  var oc=R.getClearColor(new T.Color()).getHex(),oa=R.getClearAlpha(),px=new Uint8Array(N*N*4);
  try{R.setRenderTarget(thRT);R.setClearColor(0x000000,0);R.clear();R.render(thS,thCam);R.readRenderTargetPixels(thRT,0,0,N,N,px);}catch(e){}
  R.setRenderTarget(null);R.setClearColor(oc,oa);thS.remove(a.g);freeTree(a.g);
  var x=thC.getContext('2d'),im=x.createImageData(N,N);
  for(var y=0;y<N;y++)im.data.set(px.subarray((N-1-y)*N*4,(N-y)*N*4),y*N*4);
  x.clearRect(0,0,N,N);x.putImageData(im,0,0);
  try{THUMB[k]=thC.toDataURL('image/png');}catch(e){THUMB[k]='';}
  return THUMB[k];
}
function openTeam(ti){
  if(curName!=='look')return;
  var t=TEAMS[ti],g=$('tpGrid'),h='';popTeam=ti;markTeam(ti);
  gal.forEach(function(a){if(LTEAM[a.galI]===ti)after(rnd()*.25,function(){a.hop(.45,.4);});});
  t.ks.forEach(function(k){var i=LOOKS.indexOf(k);h+='<button type="button" class="tpb'+(i===lkI&&!lkB?' on':'')+'" data-i="'+i+'"><img alt="" src="'+thumbOf(k)+'"><span>'+DEF[k].name+'</span></button>';});
  var n=t.ks.length;g.style.setProperty('--cols',String(n===6?3:n===4?2:n));g.style.setProperty('--colsS',String(n));
  g.innerHTML=h;$('tpH').textContent=t.name;$('tpSub').textContent=t.sub;
  $('teamPop').querySelector('.sheet').style.setProperty('--c',hexC(t.col));$('teamPop').style.setProperty('--c',hexC(t.col));
  $('teamPop').hidden=false;popAt=performance.now();sfx.pop();say(t.say,t.sub);
}
function closeTeam(){$('teamPop').hidden=true;popTeam=-1;}
function tapTeam(ti){openTeam(ti);}
var lkTap=[];
var BASES={square:{up:'cube',point:'pyramid',col:YEL},circle:{up:'cylinder',point:'cone',col:BLUE},triangle:{up:'tprism',point:'tpyramid',col:GRN}};
function makeLook(k,col,stand){
  var old=lk;if(old){lk=null;tw(old,{sc:0},.25,E.io,function(){old.kill();});}
  var a=new Actor(k,col);glassify(a);lk=a;lkFlip=false;a.stand=!!stand;
  a.spin.position.y=0;a.by=1.55;a.g.position.set(0,stand?.3:1.55,.2);a.sc=0;a.zs=lkDim<3?.03:1;a.ys=lkDim===1?.03:1;
  if(stand)a.spin.rotation.set(0,.5,0);else a.spin.rotation.set(-.25,.6,0);
  a.idle=function(t,dt){
    if(a!==lk)return;
    if(a.stand){a.g.position.y=.27+DEF[a.kind].hy*a.sc*a.ys;if(!lkBusy&&view.idle>2.5)a.spin.rotateOnWorldAxis(AY,dt*.35);return;}
    if(!lkBusy&&view.idle>2.5)a.spin.rotateOnWorldAxis(AY,dt*.45);a.g.position.y=a.by+Math.sin(t*1.3)*.07;
  };
  return a;
}
function showLook(i,first,quiet){
  lkI=i;lkB=null;markBuild();var k=LOOKS[i],a=makeLook(k,LCOL[k],false);
  after(first?.1:.2,function(){tw(a,{sc:LKS()},.5,E.el);sfx.pop();});
  markTeam(LTEAM[i]);
  if(!first&&!quiet)say('Look! A see-through '+DEF[k].name+'.',DEF[k].sub);
}
function markBuild(g){
  var bs=document.querySelectorAll('#build button');
  for(var j=0;j<bs.length;j++){var b=bs[j];b.classList.toggle('on',(b.getAttribute('data-b')&&b.getAttribute('data-b')===lkB)||(!!g&&b.getAttribute('data-g')===g));}
}
function setBase(b,quiet){
  lkB=b;lkDim=3;markDims();markBuild();
  var cs=document.querySelectorAll('#chips button');for(var j=0;j<cs.length;j++)cs[j].classList.remove('on');
  var a=makeLook(BASES[b].up,BASES[b].col,true);a.ys=.03;a.zs=1;a.mat.opacity=.85;
  after(.1,function(){tw(a,{sc:LKS()},.45,E.el);sfx.pop();});
  if(!quiet)say('A '+b+' base! Now pull it up, straight or to a point.');
}
function grow(g){
  if(!lkB){setBase('square',true);after(.5,function(){grow(g);});return;}
  var b=lkB,k=BASES[b][g],a=makeLook(k,BASES[b].col,true);a.ys=.03;a.zs=1;a.sc=LKS();a.mat.opacity=.85;markBuild(g);lkBusy=true;
  sfx.pump(0);after(.2,function(){sfx.pump(1);});after(.4,function(){sfx.pump(2);});
  tw(a,{ys:1},1.1,E.back,function(){lkBusy=false;sfx.pop();burst(0,2.4,.2,26,{up:5});});tw(a.mat,{opacity:.34},1.1,E.io);
  say((g==='up'?'Straight up! The ':'To a point! The ')+b+' makes a '+DEF[k].name+'!',DEF[k].sub);
}
function markDims(){var db=document.querySelectorAll('#dims button');for(var j=0;j<db.length;j++)db[j].classList.toggle('on',+db[j].getAttribute('data-d')===lkDim);}
function lookSize(f){if(lk&&!lkBusy)lk.sc=clamp(lk.sc*f,.45,2.1);}
var gal=[];
function setDim(n){
  if(!lk)return;lkDim=n;var a=lk;
  markDims();
  tw(a.mat,{opacity:n===3?.34:n===2?.78:.95},.5,E.io);
  if(n===3){sfx.pump(0);after(.15,function(){sfx.pump(1);});after(.3,function(){sfx.pop();});tw(a,{zs:1,ys:1},.6,E.back);}
  else{sfx.whoosh();tw(a,{zs:.03,ys:n===1?.03:1},.55,E.io);}
  say(DIMSAY[n],n===1?'A line has length only.':n===2?'Flat shapes have length and height, no thickness.':'Solid shapes have length, height and depth.');
}
function flipLook(){
  if(!lk||lkBusy)return;lkBusy=true;var a=lk,prev=0;lkFlip=!lkFlip;sfx.boing(1);
  run(.8,function(p){a.spin.rotateOnWorldAxis(AX,PI*(p-prev));prev=p;},E.io,function(){lkBusy=false;});
  say(lkFlip?'Upside down! There is the bottom.':'Right side up!');
}
S.look={
  enter:function(){
    setCam(nar()?1.15:1.3,6.6,nar()?4.9+Math.max(0,cam.aspect-.46)*8:8);
    var base=prop(mesh(unitC,mat(0xff8fc0),0,.06,.2,true));base.scale.set(1.55,.12,1.55);base.receiveShadow=true;
    var ped=prop(mesh(unitC,mat(0xffffff),0,.18,.2,true));ped.scale.set(1.25,.18,1.25);ped.receiveShadow=true;
    var rg=prop(mesh(new T.TorusGeometry(1.25,.06,10,48),mat(YEL),0,.27,.2));rg.rotation.x=PI/2;
    var beam=prop(mesh(new T.CylinderGeometry(.9,1.4,6,32,1,true),new T.MeshBasicMaterial({color:0xfff6c9,transparent:true,opacity:.09,blending:T.AdditiveBlending,depthWrite:false,side:T.DoubleSide}),0,3.2,.2));
    var sp=new Float32Array(36*3);for(var i=0;i<36;i++){var an=i/36*PI*2;sp[i*3]=Math.cos(an)*1.7;sp[i*3+1]=.5+(i%3)*.75;sp[i*3+2]=Math.sin(an)*1.7;}
    var sg=new T.BufferGeometry();sg.setAttribute('position',new T.BufferAttribute(sp,3));
    var spk=prop(new T.Points(sg,new T.PointsMaterial({color:0xfff1a8,size:.09,transparent:true,opacity:.9,depthWrite:false})));spk.position.set(0,0,.2);spk.userData.spin=1;
    /* wide screens: a horseshoe of team mats beside and behind the stand; tall phones: two by two on the grass in front */
    gal=[];lkTap=[];var NR=nar(),SC=NR?.3:.36,SP=NR?.46:.6,gi=0,ANG=[1,1.27,1.73,2],FR=[[-.96,2.5],[.96,2.5],[-.96,3.9],[.96,3.9]];
    TEAMS.forEach(function(t,ti){
      var an=PI*ANG[ti],cx=NR?FR[ti][0]:Math.cos(an)*2.95,cz=NR?FR[ti][1]:.2+Math.sin(an)*2.3;
      var ux=NR?0:-cx,uz=NR?-1:.2-cz,ul=Math.sqrt(ux*ux+uz*uz)||1;ux/=ul;uz/=ul;var vx=-uz,vz=ux;
      var n=t.ks.length,cols=n===4?2:Math.min(3,n),rows=Math.ceil(n/cols),rad=SP*(Math.max(cols,rows)/2+.3);
      var m=prop(mesh(unitC,mat(t.mat,{clearcoat:0,roughness:.85,envMapIntensity:.12}),cx,.03,cz,false));m.scale.set(rad,.06,rad);m.receiveShadow=true;m.userData.tap=function(){tapTeam(ti);};
      var rim=prop(mesh(new T.TorusGeometry(rad,.04,8,40),mat(0xffffff),cx,.06,cz));rim.rotation.x=PI/2;
      var sg=prop(teamSign(t));if(NR)sg.position.set(cx,.16,cz+rad+.12);else sg.position.set(cx,1.22,cz-rad*.35);sg.scale.set(NR?.98:1.3,NR?.28:.37,1);sg.userData.tap=m.userData.tap;
      lkTap.push(m,sg);
      t.ks.forEach(function(k,j){
        var r=Math.floor(j/cols),c=j%cols,inRow=Math.min(cols,n-r*cols),off=(c-(inRow-1)/2)*SP,back=(r-(rows-1)/2)*SP*.9;
        var g=new Actor(k,LCOL[k]);g.isGal=true;g.galI=LOOKS.indexOf(k);g.sc=0;g.by=.06;g.g.position.set(cx+vx*off-ux*back,.06,cz+vz*off-uz*back);
        after(.2+gi*.025,function(){tw(g,{sc:SC},.4,E.el);});gal.push(g);gi++;
      });
    });
    extras.push.apply(extras,lkTap);
    $('chips').hidden=false;$('dims').hidden=false;$('build').hidden=false;
    markDims();
    showLook(lkI,true);
    say('Look closely! Slide one finger to spin around. Pinch to zoom.','Tap 1D, 2D or 3D. Or build one: pick a base, then pull it up.');
  },
  exit:function(){closeTeam();$('chips').hidden=true;$('dims').hidden=true;$('build').hidden=true;lk=null;lkBusy=false;lkB=null;gal=[];extras=extras.filter(function(e){return lkTap.indexOf(e)<0;});lkTap=[];},
  tap:function(a){if(a===lk){if(lk.stand){sfx.boing(1);lk.hop(.5,.4);}else flipLook();}else if(a.isGal){openTeam(LTEAM[a.galI]);}}
};
var lkV={x:0,y:0},camR=new T.Vector3(),LZ0=.42,LZ1=1.7;
function lookDrag(dx,dy){
  orbit-=dx*.009;
  var t=view.tiltT+dy*.006,c=clamp(t,-.33,1.13),o=t-c;view.tiltT=c;
  if(o&&lk&&!lkBusy){camR.setFromMatrixColumn(cam.matrixWorld,0).normalize();lk.spin.rotateOnWorldAxis(camR,o);}
}
function lookZoom(f){view.zoomT=clamp(view.zoomT*f,LZ0,LZ1);}
function stepLook(dt){
  if(curName!=='look'||view.held){return;}
  if(Math.abs(lkV.x)+Math.abs(lkV.y)<.01){lkV.x=lkV.y=0;return;}
  lookDrag(lkV.x*dt*1000,lkV.y*dt*1000);var k=Math.exp(-dt*4);lkV.x*=k;lkV.y*=k;view.idle=0;
}
function turnLook(dx,dy,da){if(!lk)return;lk.spin.rotateOnWorldAxis(AY,dx);lk.spin.rotateOnWorldAxis(AX,dy);lk.spin.rotateOnWorldAxis(AZ,da);}
function setDance(m){
  DANCE=m;if(m)dmode=m;setMode(m);
  $('dance').classList.toggle('on',m>0);$('dance').setAttribute('aria-pressed',m>0?'true':'false');
  if(m===0){sfx.sparkle();say('Back to normal.');}
  else{sfx.tada();say(['','Dance time!','Light show!','Party time!'][m],['','Everybody dance!','Tap the music button again for a party.','Tap the music button again to stop.'][m]);}
  if(m===3)burst(0,4.5,0,40,{up:4,sp:4});
}

/* ---------- input: one, two and three fingers ---------- */
var ray=new T.Raycaster(),ptr=new T.Vector2(),v3=new T.Vector3(),pts={},one=null,g2=null,g3=null,lock3=false;
function fingers(){var a=[];for(var k in pts)a.push(pts[k]);return a;}
function castAt(cx,cy){var r=canvas.getBoundingClientRect();ptr.set((cx-r.left)/r.width*2-1,-(cy-r.top)/r.height*2+1);ray.setFromCamera(ptr,cam);return r;}
function toScreen(x,y,z,r){v3.set(x,y,z).project(cam);return {x:(v3.x*.5+.5)*r.width+r.left,y:(-v3.y*.5+.5)*r.height+r.top};}
function groundAt(){if(ray.ray.direction.y>-.02)return null;var k=-ray.ray.origin.y/ray.ray.direction.y;if(k>60)return null;return v3.copy(ray.ray.origin).addScaledVector(ray.ray.direction,k);}
function hitAt(cx,cy){
  var r=castAt(cx,cy),list=actors.map(function(a){return a.body;}).concat(extras);
  if(mun)list.push(mun.body);
  var h=ray.intersectObjects(list,false);
  if(h.length)return h[0].object;
  var best=null,bd=64;
  actors.forEach(function(a){
    var s=toScreen(a.g.position.x,a.top()*.5,a.g.position.z,r),dx=s.x-cx,dy=s.y-cy,dd=Math.sqrt(dx*dx+dy*dy);
    if(dd<bd){bd=dd;best=a.body;}
  });
  return best;
}
function fireTap(){
  if(!one||one.fired)return;one.fired=true;var o=one.o;
  if(o&&o.userData.a){if(cur.tap)cur.tap(o.userData.a);}
  else if(o&&o.userData.tap)o.userData.tap();
  else{castAt(one.x,one.y);var p=groundAt();if(p){burst(p.x,.15,p.z,7,{up:4,sp:2});sfx.plink();}}
}
function start2(f){
  var dx=f[1].x-f[0].x,dy=f[1].y-f[0].y;
  return {d:Math.max(20,Math.sqrt(dx*dx+dy*dy)),a:Math.atan2(dy,dx),la:Math.atan2(dy,dx),lx:(f[0].x+f[1].x)/2,ly:(f[0].y+f[1].y)/2,zoom:view.zoomT};
}
function cen(f){var x=0,y=0;f.forEach(function(p){x+=p.x;y+=p.y;});return {x:x/f.length,y:y/f.length};}
var ORDER=['story','pop','munch','look'];
function finish3(){
  var ax=Math.abs(g3.dx),ay=Math.abs(g3.dy);
  if(ax>60&&ax>ay){var i=ORDER.indexOf(curName);go(ORDER[(i+(g3.dx<0?1:ORDER.length-1))%ORDER.length]);}
  else if(ay>60){
    if(g3.dy<0){sfx.boing(2);say('Jump!',null,0);everyone(function(a){a.hop(1+rnd()*.5,.5);});}
    else{sfx.whoosh();resetView();}
  }else if(performance.now()-g3.t<800){sfx.sparkle();surprise();}
}
canvas.addEventListener('pointerdown',function(e){
  if(!started)return;
  try{canvas.setPointerCapture(e.pointerId);}catch(x){}
  pts[e.pointerId]={x:e.clientX,y:e.clientY};var n=fingers().length;view.idle=0;view.held=n;lkV.x=lkV.y=0;
  if(lock3)return;
  if(n===1){
    var o=hitAt(e.clientX,e.clientY),a=o&&o.userData.a;
    one={o:o,x:e.clientX,y:e.clientY,moved:0,fired:false,orb:orbit,tilt:view.tiltT,grab:(a&&a.isFriend&&!busy)?a:null,timer:0,t0:performance.now(),isMun:!!(mun&&o===mun.body)};
    one.lx=e.clientX;one.ly=e.clientY;one.lt=e.timeStamp;
    if(o&&!one.grab&&!one.isMun&&curName!=='look')one.timer=setTimeout(fireTap,110);
  }else{
    if(one){clearTimeout(one.timer);if(one.grab&&one.dragging)goHome(one.grab);one=null;}
    if(n===2){g3=null;g2=start2(fingers());}
    else if(n===3){g2=null;var c=cen(fingers());g3={x:c.x,y:c.y,dx:0,dy:0,t:performance.now()};}
  }
});
canvas.addEventListener('pointermove',function(e){
  var p=pts[e.pointerId];if(!p)return;p.x=e.clientX;p.y=e.clientY;view.idle=0;
  var f=fingers(),n=f.length;if(lock3)return;
  if(n===1&&one){
    var dx=e.clientX-one.x,dy=e.clientY-one.y;one.moved=Math.max(one.moved,Math.abs(dx)+Math.abs(dy));
    if(curName==='look'&&!one.grab){
      var mx=e.clientX-one.lx,my=e.clientY-one.ly,nw=e.timeStamp,dtm=Math.max(6,nw-one.lt);one.lx=e.clientX;one.ly=e.clientY;one.lt=nw;
      if(one.moved>=12){lookDrag(mx,my);lkV.x=clamp(lkV.x*.5+mx/dtm*.5,-3,3);lkV.y=clamp(lkV.y*.5+my/dtm*.5,-3,3);}
    }
    if(one.isMun&&one.moved>36&&!one.tk){one.tk=true;if(mun&&mun.act==='idle')munLaugh(null,true);else munKick(2);}
    if(one.grab){
      if(one.moved>14&&!busy){
        one.dragging=true;castAt(e.clientX,e.clientY);var q=groundAt();
        if(q){one.grab.g.position.set(clamp(q.x,-3.2,3.2),.45,clamp(q.z,-.4,3.4));one.grab.s=1.08;}
      }
    }
  }else if(n===2&&g2&&curName==='look'){
    var ddx=f[1].x-f[0].x,ddy=f[1].y-f[0].y,d=Math.max(20,Math.sqrt(ddx*ddx+ddy*ddy));
    view.zoomT=clamp(g2.zoom*g2.d/d,LZ0,LZ1);
  }else if(n===3&&g3){var c=cen(f);g3.dx=c.x-g3.x;g3.dy=c.y-g3.y;}
});
function lift(e){
  if(!pts[e.pointerId])return;var n=fingers().length;
  if(!lock3){
    if(n===1&&one){
      clearTimeout(one.timer);
      if(one.grab){
        var a=one.grab;a.s=1;
        if(cur.tap&&!busy)cur.tap(a);else if(one.dragging)goHome(a);
      }else if(one.isMun){if(!one.tk&&one.moved<30)fireTap();}
      else if(one.moved<12)fireTap();
      if(!(curName==='look'&&one.moved>=12&&e.timeStamp-one.lt<90))lkV.x=lkV.y=0;
      one=null;
    }
    if(n===3&&g3){finish3();g3=null;lock3=true;}
  }
  delete pts[e.pointerId];n=fingers().length;view.held=n;
  if(n<2)g2=null;
  if(n===1&&!lock3&&curName==='look'){var q=fingers()[0];one={o:null,x:q.x,y:q.y,lx:q.x,ly:q.y,lt:e.timeStamp,moved:99,fired:true,grab:null,timer:0,isMun:false};}
  if(n===0)lock3=false;
}
canvas.addEventListener('pointerup',lift);canvas.addEventListener('pointercancel',lift);
canvas.addEventListener('wheel',function(e){
  e.preventDefault();if(!started)return;view.idle=0;
  if(e.ctrlKey){if(curName==='look')lookZoom(Math.exp(e.deltaY*.01));else view.zoomT=clamp(view.zoomT*(1+e.deltaY*.01),.55,1.6);return;}
  if(curName==='look'){lkV.x=lkV.y=0;lookDrag(e.deltaX*.55,e.deltaY*.5);return;}
  orbit-=e.deltaX*.005;view.tiltT=clamp(view.tiltT+e.deltaY*.003,-.14,1.1);
},{passive:false});
var gS=1;
document.addEventListener('gesturestart',function(e){e.preventDefault();if(fingers().length)return;gS=1;});
document.addEventListener('gesturechange',function(e){e.preventDefault();if(fingers().length||!started)return;var f=e.scale/gS;gS=e.scale;view.idle=0;if(curName==='look')lookZoom(1/f);else view.zoomT=clamp(view.zoomT/f,.55,1.6);});
/* the tap that opened the popup must not also pick in it: ignore clicks for a moment */
function popFresh(){return performance.now()-popAt<500;}
$('tpGrid').addEventListener('click',function(e){if(popFresh())return;var b=e.target.closest&&e.target.closest('.tpb');if(!b)return;var i=+b.getAttribute('data-i');closeTeam();showLook(i,false);});
$('tpX').addEventListener('click',closeTeam);
$('teamPop').addEventListener('click',function(e){if(e.target===this&&!popFresh())closeTeam();});
window.addEventListener('keydown',function(e){if(e.key==='Escape'&&!$('teamPop').hidden){closeTeam();e.preventDefault();}});
window.addEventListener('keydown',function(e){
  if(!started)return;var k=e.key;view.idle=0;
  var L=curName==='look';
  if(k==='ArrowLeft')orbit+=.2;else if(k==='ArrowRight')orbit-=.2;
  else if(L&&k==='ArrowUp')lookDrag(0,20);else if(L&&k==='ArrowDown')lookDrag(0,-20);
  else if(k==='ArrowUp')view.tiltT=clamp(view.tiltT+.12,-.14,1.1);else if(k==='ArrowDown')view.tiltT=clamp(view.tiltT-.12,-.14,1.1);
  else if(L&&(k==='+'||k==='='))lookZoom(1/1.15);else if(L&&k==='-')lookZoom(1.15);
  else if(k==='f'||k==='F')setFart(!FARTMODE);
  else if(k==='1'||k==='2'||k==='3'||k==='4')go(ORDER[+k-1]);
  else if(k==='d'||k==='D')setDance((DANCE+1)%4);
  else if(k===' '){e.preventDefault();surprise();}
  else if(k==='0')resetView();
});

/* ---------- buttons, stars and saved progress ---------- */
var save={stars:0,found:[],name:DEFAULT_NAME};
try{var sv=JSON.parse(localStorage.getItem('shape-friends')||'null');if(sv&&typeof sv.stars==='number'&&sv.found&&sv.found.length>=0){save=sv;if(typeof save.name!=='string')save.name=DEFAULT_NAME;}}catch(e){}
function store(){try{localStorage.setItem('shape-friends',JSON.stringify(save));}catch(e){}}
function addStar(n){
  save.stars+=n;store();sfx.star();$('starN').textContent=save.stars;
  var c=$('stars');c.classList.remove('bump');void c.offsetWidth;c.classList.add('bump');
  var f=document.createElement('div');f.className='fly';f.textContent='\u2605';document.body.appendChild(f);setTimeout(function(){if(f.parentNode)f.parentNode.removeChild(f);},950);
}
save.found.forEach(function(k){if(DEF[k]){found[k]=1;$('st_'+k).classList.add('got');}});
$('starN').textContent=save.stars;
var navB=document.querySelectorAll('#nav button[data-go]');
for(var ni=0;ni<navB.length;ni++)(function(b){b.addEventListener('click',function(){audioInit();sfx.pop();go(b.getAttribute('data-go'));});})(navB[ni]);
$('boo').addEventListener('click',function(){audioInit();sfx.sparkle();surprise();});
$('dance').addEventListener('click',function(){audioInit();setDance((DANCE+1)%4);});
$('fartb').addEventListener('click',function(){audioInit();setFart(!FARTMODE);});
(function(){var bs=document.querySelectorAll('#build button');for(var j=0;j<bs.length;j++)(function(b){b.addEventListener('click',function(){audioInit();if(b.getAttribute('data-b'))setBase(b.getAttribute('data-b'));else grow(b.getAttribute('data-g'));});})(bs[j]);})();
(function(){
  var h='';TEAMS.forEach(function(t){h+='<button type="button" aria-label="'+t.name+'"><svg viewBox="0 0 24 24">'+t.icon+'</svg></button>';});
  $('chips').innerHTML=h;var cs=document.querySelectorAll('#chips button');
  for(var i=0;i<cs.length;i++)(function(i){cs[i].style.setProperty('--c',hexC(TEAMS[i].col));cs[i].addEventListener('click',function(){audioInit();tapTeam(i);});})(i);
  var db=document.querySelectorAll('#dims button');
  for(var j=0;j<db.length;j++)(function(b){b.addEventListener('click',function(){setDim(+b.getAttribute('data-d'));});})(db[j]);
})();
$('again').addEventListener('click',function(){audioInit();if(lastLine[0]&&lastLine[0].charAt(0)!=='\u266a')queueLine({t:lastLine[0],sub:lastLine[1],who:lastLine[2],p:1});});
$('kidName').value=save.name||'';
$('kidName').addEventListener('input',function(){save.name=this.value.replace(/[<>]/g,'').slice(0,16);store();});
$('close').addEventListener('click',function(){$('panel').hidden=true;});
$('bMusic').addEventListener('click',function(){musicOn=!musicOn;this.setAttribute('aria-pressed',musicOn?'true':'false');});
$('bSound').addEventListener('click',function(){
  muted=!muted;this.setAttribute('aria-pressed',muted?'false':'true');
  if(muted)hush();
});
/* ---------- full screen that stays, and the Home Screen app ----------
   On a touch tablet the game goes full screen when Play is pressed. If the browser drops out of full screen
   (a pinch, a swipe down, its own close button), the next tap anywhere puts it back. Only the grown-ups'
   "Keep full screen" switch stops that. Added to the Home Screen it runs as an app and is always full screen. */
var UA=navigator.userAgent||'',isIOS=/iPad|iPhone|iPod/.test(UA)||(navigator.platform==='MacIntel'&&navigator.maxTouchPoints>1),isPhone=/iPhone|iPod/.test(UA);
function mq(q){try{return window.matchMedia(q).matches;}catch(e){return false;}}
var isTab=navigator.maxTouchPoints>1&&mq('(pointer:coarse)');
function isApp(){return navigator.standalone===true||mq('(display-mode: standalone)')||mq('(display-mode: fullscreen)');}
var fsOK=!!(document.fullscreenEnabled||document.webkitFullscreenEnabled),fsAsk=0,guideOpen=false,installEv=null;
function fsEl(){return document.fullscreenElement||document.webkitFullscreenElement||null;}
if(typeof save.fs!=='boolean')save.fs=isTab;
function fsEnter(){
  if(!fsOK||fsEl()||isApp()||guideOpen)return;var n=performance.now();if(n-fsAsk<800)return;fsAsk=n;
  var el=document.documentElement;
  try{var p=el.requestFullscreen?el.requestFullscreen():(el.webkitRequestFullscreen?el.webkitRequestFullscreen():null);if(p&&p.catch)p.catch(function(){});}catch(e){}
}
function fsLeave(){if(!fsEl())return;try{if(document.exitFullscreen){var p=document.exitFullscreen();if(p&&p.catch)p.catch(function(){});}else if(document.webkitExitFullscreen)document.webkitExitFullscreen();}catch(e){}}
function fsBack(e){if(save.fs&&started&&!fsEl()&&!(e.target&&e.target.closest&&e.target.closest('#panel,#guide')))fsEnter();}
['touchend','pointerup','click','keyup'].forEach(function(t){document.addEventListener(t,fsBack,true);});
function fsUI(){
  var app=isApp(),canApp=!app&&SITE&&(isIOS||!!installEv);
  $('bFull').hidden=app||!fsOK;$('bFull').setAttribute('aria-pressed',save.fs?'true':'false');
  $('bApp').hidden=!canApp;$('appBtn').hidden=!canApp||started;
  $('bApp').querySelector('span').textContent=isIOS?(isPhone?'Make it an app on this iPhone':'Make it an app on this iPad'):'Install as an app';
  $('fsNote').textContent=app?'Opened from the Home Screen, so it is always full screen.'
    :!fsOK?(isIOS?'On iPhone, full screen only works as a Home Screen app.':'This browser cannot go full screen.')
    :save.fs?'On: Play goes full screen, and if it slips out, the next tap puts it back. Tap the switch to turn it off.'
    :'Off: the game stays in the browser window.';
}
document.addEventListener('fullscreenchange',fsUI);document.addEventListener('webkitfullscreenchange',fsUI);
window.addEventListener('beforeinstallprompt',function(e){e.preventDefault();installEv=e;fsUI();});
window.addEventListener('appinstalled',function(){installEv=null;fsUI();});
function guardBack(){if(save.fs&&!isApp()&&!(history.state&&history.state.sf)){try{history.pushState({sf:1},'');}catch(e){}}}
window.addEventListener('popstate',function(){if(save.fs&&started&&!isApp()){try{history.pushState({sf:1},'');}catch(e){}}});
$('bFull').addEventListener('click',function(){
  save.fs=!save.fs;store();
  if(save.fs){fsEnter();guardBack();}else{fsLeave();if(history.state&&history.state.sf){try{history.back();}catch(e){}}}
  fsUI();
});
function openGuide(){
  if(installEv&&!isIOS){var ev=installEv;installEv=null;try{ev.prompt();}catch(e){}fsUI();return;}
  if(isPhone){$('gS1').innerHTML='In Safari, tap <em>&bull;&bull;&bull;</em> next to the address bar, then <em>Share</em>.';$('gDev').textContent='iPhone';}
  guideOpen=true;fsLeave();$('panel').hidden=true;$('guide').hidden=false;
}
$('bApp').addEventListener('click',openGuide);$('appBtn').addEventListener('click',openGuide);
$('guideClose').addEventListener('click',function(){guideOpen=false;$('guide').hidden=true;});
/* grown-ups: hold the gear for a moment, so a tap by a little hand does nothing */
var gearT=0,gearRAF=0,gearOpened=0,tipT=0;
function gearReset(){cancelAnimationFrame(gearRAF);gearT=0;$('gear').classList.remove('hold');$('gear').style.setProperty('--p','0');}
function openPanel(){gearReset();$('gearTip').hidden=true;$('panel').hidden=false;gearOpened=performance.now();fsUI();}
$('gear').addEventListener('pointerdown',function(e){
  e.preventDefault();gearT=performance.now();this.classList.add('hold');
  (function tick(){if(!gearT)return;var p=Math.min(1,(performance.now()-gearT)/800);$('gear').style.setProperty('--p',p.toFixed(3));if(p>=1){openPanel();return;}gearRAF=requestAnimationFrame(tick);})();
});
$('gear').addEventListener('pointerup',function(){
  if(!gearT)return;var held=performance.now()-gearT;gearReset();
  if(held<800&&$('panel').hidden){$('gearTip').hidden=false;clearTimeout(tipT);tipT=setTimeout(function(){$('gearTip').hidden=true;},2400);}
});
$('gear').addEventListener('pointercancel',gearReset);
$('gear').addEventListener('click',function(e){if(e.detail===0)openPanel();});
$('panel').addEventListener('click',function(e){if(performance.now()-gearOpened<450){e.stopPropagation();e.preventDefault();}},true);
fsUI();
$('play').addEventListener('click',function(){
  if(save.fs)fsEnter();guardBack();
  iosUnlock();audioInit();wake();
  started=true;$('start').hidden=true;$('appBtn').hidden=true;sfx.tada();goNow('story');
});
preload(function(p){$('bar').style.width=Math.round(p*100)+'%';if(p>=1)$('load').textContent='Voices ready';});

/* ---------- loop ---------- */
function size(){var w=window.innerWidth,h=window.innerHeight;R.setSize(w,h,false);cam.aspect=w/h;cam.updateProjectionMatrix();}
size();window.addEventListener('resize',size);
cam.position.set(0,4,12);
var last=0,time=0;
function frame(ts){
  var dt=Math.min(.05,(ts-last)/1000||0);last=ts;time+=dt;
  stepRuns(dt);stepDance(dt);stepActors(dt,time);stepParts(dt);stepMinis(dt);stepPuffs(dt);stepFlies(dt);stepMun(dt);stepLook(dt);stepCam(dt);
  if(mun){
    var q=1/Math.sqrt(mun.s),k=mun.sc*GS,md=mun.act==='idle'?danceMove(1,0):null;mun.g.scale.set(k*q,k*mun.s*(1+Math.sin(time*2)*.02)*(md?md.s:1),k*q);
    for(var j=0;j<2;j++){var es=GE*mun.eyeS;mun.face.eyes[j].scale.set(es,es*(1-.8*mun.squint),es);}
    mun.in.position.y=(md?md.y:0)+mun.ex.y;mun.in.rotation.z=(md?md.rz*.8:0)+mun.ex.rz;mun.in.rotation.y=(md?md.ry:0)+mun.ex.ry;
    mun.mat.emissive.setHex(PUR).multiplyScalar(.35*glowD);
  }
  if(hintA&&actors.indexOf(hintA)>=0){var hs=clamp(cam.position.distanceTo(hintA.g.position)/9,.3,1.1);hintM.visible=true;hintM.scale.setScalar(hs);hintM.position.set(hintA.g.position.x,hintA.top()+(.6+Math.abs(Math.sin(time*4))*.3)*hs,hintA.g.position.z);hintM.rotation.y=time*2;}
  else hintM.visible=false;
  for(var i=0;i<clouds.length;i++){var c=clouds[i];c.position.x+=dt*.25;if(c.position.x>26)c.position.x=-26;}
  for(var pi=0;pi<props.length;pi++)if(props[pi].userData.spin)props[pi].rotation.y=time*.5;
  if(motes){motes.rotation.y=time*.03;motes.position.y=Math.sin(time*.4)*.3;}
  sun.rays.rotation.z=time*.25;sun.position.y=10.5+Math.sin(time*.8)*.25;
  if(disco>0)sunL.color.setHSL((time*.9)%1,.8,.7);else sunL.color.setHex(0xfff2d9);
  R.render(scene,cam);
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);

function munLines(){return ['Hi! I am Munchy! Feed me shapes!','Ha ha ha! That tickles!','Hee hee hee! Again! Again!','Ha ha ha ha ha!','Ho ho ho! Hee hee hee!','Whoa! Look at my googly eyes!','Boing! Big googly eyes!','Let me dance! Wiggle, wiggle!','Hee hee! Excuse me!','Oops! Ha ha ha!','Not me! Ha ha!','Giggle party! Everybody laugh!'];}
function allLines(){
  var L=[];
  SOLIDS.forEach(function(k){
    var d=DEF[k];L.push(d.say,d.fact,'Back to a plain '+d.name+'!','Bonk! The '+d.name+' does not fit. Try again!','Chomp! The '+d.name+' fits!','Yum, yum! A '+d.name+'!','Gulp! Tasty '+d.name+'!');
    COS[k].forEach(function(c){L.push(c.say);});
  });
  ['circle','square','triangle'].forEach(function(h){L.push('Munchy wants a '+h+'. Who fits?');});
  LOOKS.forEach(function(k){L.push('Look! A see-through '+DEF[k].name+'.');});TEAMS.forEach(function(t){L.push(t.say);});
  FKINDS.forEach(function(k){L.push(FARTS[k].say);});
  L.push('Yes! Good job!',"Dot wants to meet friends. Let's go!","Now let's feed Munchy!","What a full tummy! Let's look closely at the shapes.",'Fart mode on! Get ready!','Fart mode off.');
  Object.keys(BASES).forEach(function(b){L.push('A '+b+' base! Now pull it up, straight or to a point.');['up','point'].forEach(function(g){L.push((g==='up'?'Straight up! The ':'To a point! The ')+b+' makes a '+DEF[BASES[b][g]].name+'!');});});
  L.push(DIMSAY[1],DIMSAY[2],DIMSAY[3],'Upside down! There is the bottom.','Right side up!','Look closely! Two fingers turn it. Tap it to flip it over.','Dance time!','Light show!','Party time!','Back to normal.','Toot, toot, toot! Everybody tooted!','Oops! Munchy tooted!','Toot toot! Hee hee!','Pee-yew! Stinky!');
  return L;
}
window.__sf={go:goNow,vlog:function(){return vlog.slice();},queue:function(){return {cur:curL?curL.t:null,q:Q.map(function(q){return q.t;})};},base:function(b){setBase(b);},grow:function(g){grow(g);},fartmode:function(o){setFart(o);},size:function(f){lookSize(f);},lkq:function(){return lk?lk.spin.quaternion.toArray():null;},fling:function(){return [lkV.x,lkV.y];},audio:function(){return {state:AC?AC.state:null,session:navigator.audioSession?navigator.audioSession.type:null,silent:!!silentEl,silentPlaying:!!(silentEl&&!silentEl.paused)};},unlock:function(){iosUnlock();},suspend:function(){return AC&&AC.suspend?AC.suspend():null;},fs:function(){return {keep:save.fs,on:!!fsEl(),ok:fsOK,app:isApp(),ios:isIOS,tab:isTab,guide:!$('guide').hidden,panel:!$('panel').hidden,appBtn:!$('appBtn').hidden,bApp:!$('bApp').hidden,hist:history.length,state:history.state};},teams:function(){return {n:LOOKS.length,gal:gal.length,lk:lk?lk.kind:null,team:LTEAM[lkI],taps:lkTap.length,pop:popTeam,popN:document.querySelectorAll('#tpGrid .tpb').length};},team:function(i){tapTeam(i);},showk:function(k){showLook(LOOKS.indexOf(k),false,true);},lkAt:function(){var r=canvas.getBoundingClientRect();return lk?toScreen(lk.g.position.x,lk.top()*.5,lk.g.position.z,r):null;},view:function(o,t){orbit=o;view.tiltT=t;view.idle=0;},lines:allLines,munLines:munLines,react:function(r){munReact(r);},farty:function(k){munFart(k);},mun:function(){return mun?{act:mun.act,eyeS:mun.eyeS,gig:gig,hole:mun.hole}:null;},tapKind:function(k){var a=actors.filter(function(x){return x.kind===k;})[0];if(a&&cur.tap)cur.tap(a);return !!a;},
  info:function(){var m=R.info.memory;return {geo:m.geometries,tex:m.textures,actors:actors.length,kids:scene.children.length,runs:runs.length,calls:R.info.render.calls,tris:R.info.render.triangles,vox:Object.keys(voBuf).length,ac:AC?AC.state:'none'};},
  where:function(k){var r=canvas.getBoundingClientRect(),a=actors.filter(function(x){return x.kind===k;})[0];if(!a)return null;return toScreen(a.g.position.x,a.top()*.5,a.g.position.z,r);},
  mouth:function(){var r=canvas.getBoundingClientRect();return toScreen(0,1+MY,-.3,r);},
  state:function(){return {scene:curName,busy:busy,actors:actors.map(function(a){return a.kind;}),line:lastLine[0],hole:mun?mun.hole:'',found:Object.keys(found),stars:save.stars,zoom:view.zoomT,tilt:view.tiltT,orbit:orbit};},
  surprise:function(i){BOO[i]();},dance:function(m){setDance(m);},dim:function(n){setDim(n);},look:function(i){showLook(i,false);},flip:function(){flipLook();},fart:function(){munFart(null,false);},turn:function(a,b,c){turnLook(a,b,c);},dress:function(){if(solid)dress(solid);},
  render:function(sec){
    var C=window.OfflineAudioContext||window.webkitOfflineAudioContext,ctx=new C(2,44100*sec,44100);AC=null;audioInit(ctx);
    for(var n=0,t=.05;t<sec-1;n++,t+=STEP)musStep(t,n);
    return ctx.startRendering().then(function(b){var d=b.getChannelData(0),pk=0,sq=0;for(var i=0;i<d.length;i++){var v=Math.abs(d[i]);if(v>pk)pk=v;sq+=v*v;}AC=null;return {peak:pk,rms:Math.sqrt(sq/d.length)};});
  }};
})();
index.html120 lines

Raw file

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
<title>Dot and the Shape Friends</title>
<meta name="description" content="A 3D tap-and-play game that teaches lines, flat shapes and solid shapes to young children.">
<meta name="theme-color" content="#6ec6ff">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="Shape Friends">
<link rel="preload" href="./fonts/fredoka-600.woff2" as="font" type="font/woff2" crossorigin>
<link rel="manifest" href="./manifest.webmanifest">
<link rel="icon" href="./icon-192.png" type="image/png">
<link rel="apple-touch-icon" href="./icon-192.png">
<link rel="stylesheet" href="./game.css">
</head>
<body>
<div id="night"></div>
<canvas id="c" aria-label="A 3D world of friendly shapes. Tap the shapes to play."></canvas>
<div id="vig"></div>
<div id="top">
  <div id="cap"><div id="capT">Dot and the Shape Friends</div><div id="capS"></div></div>
  <div id="stickers" hidden></div>
  <div id="giggle" hidden aria-label="Giggle meter"><svg viewBox="0 0 48 48" aria-hidden="true"><path d="M12 12 9 3l9 5zM36 12l3-9-9 5z" fill="#ffc93c"/><circle cx="24" cy="27" r="17" fill="#9b7bff"/><path d="M15 21q3-4 6 0M27 21q3-4 6 0" stroke="#2b2140" stroke-width="3" fill="none" stroke-linecap="round"/><path d="M14 29q10 12 20 0z" fill="#3a1030"/></svg><div class="gbar"><div id="gfill"></div></div></div>
  <div id="chips" hidden role="group" aria-label="Pick a shape"></div>
</div>
<div id="build" hidden role="group" aria-label="Build a shape from a base">
  <button type="button" data-b="circle" aria-label="Circle base"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8" fill="#4db8ff"/></svg></button>
  <button type="button" data-b="square" aria-label="Square base"><svg viewBox="0 0 24 24"><rect x="4.500" y="4.500" width="15" height="15" rx="1.500" fill="#ffc93c"/></svg></button>
  <button type="button" data-b="triangle" aria-label="Triangle base"><svg viewBox="0 0 24 24"><path d="M12 4l9 15H3z" fill="#4fd08a"/></svg></button>
  <i class="sep"></i>
  <button type="button" data-g="up" aria-label="Pull straight up"><svg viewBox="0 0 24 24"><rect x="6" y="9" width="12" height="11" rx="1.500" fill="#9b7bff"/><path d="M12 2l4 5h-8z" fill="#2b2140"/></svg></button>
  <button type="button" data-g="point" aria-label="Pull to a point"><svg viewBox="0 0 24 24"><path d="M12 3l8 17H4z" fill="#ff6fa5"/></svg></button>
</div>
<div id="dims" hidden role="group" aria-label="Line, flat or solid"><button type="button" data-d="1">1D</button><button type="button" data-d="2">2D</button><button type="button" data-d="3">3D</button></div>
<div id="tools">
  <button type="button" id="gear" aria-label="For grown-ups: settings and gestures"><svg viewBox="0 0 24 24"><path d="M12 8.500a3.500 3.500 0 1 0 0 7a3.500 3.500 0 0 0 0-7zm8.300 5.200l1.700 1.300l-2 3.400l-2-.800a7.600 7.600 0 0 1-1.700 1l-.300 2.100h-4l-.300-2.100a7.600 7.600 0 0 1-1.700-1l-2 .800l-2-3.400l1.700-1.300a7.300 7.300 0 0 1 0-2l-1.700-1.300l2-3.400l2 .800a7.600 7.600 0 0 1 1.700-1l.300-2.100h4l.300 2.100a7.600 7.600 0 0 1 1.700 1l2-.800l2 3.400l-1.700 1.300a7.300 7.300 0 0 1 0 2z" fill-rule="evenodd"/></svg></button>
  <button type="button" id="again" aria-label="Say it again"><svg viewBox="0 0 24 24"><path d="M4 9v6h4l5 4V5L8 9zm11.500 3a4 4 0 0 0-2-3.500v7a4 4 0 0 0 2-3.500zm-2-8v2.100a6 6 0 0 1 0 11.800V20a8 8 0 0 0 0-16z"/></svg></button>
  <div id="stars" aria-label="Stars"><span class="s">&#9733;</span><span id="starN">0</span></div>
</div>
<div id="panel" hidden>
  <div class="sheet">
    <h2>For grown-ups</h2>
    <h3>Full screen</h3>
    <div class="toggles">
      <button type="button" id="bFull" aria-pressed="true">Keep full screen</button>
      <button type="button" id="bApp" hidden><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="4" y="2.5" width="16" height="19" rx="3" fill="#6ec6ff" stroke="#2b2140" stroke-width="2"/><path d="M8.5 9 5 5.5M15.5 9 19 5.5M8.5 15 5 18.5M15.5 15 19 18.5" stroke="#2b2140" stroke-width="1.8" stroke-linecap="round"/></svg><span>Make it an app</span></button>
    </div>
    <p id="fsNote" class="note"></p>
    <h3>Sound</h3>
    <div class="toggles">
      <button type="button" id="bMusic" aria-pressed="true">Music</button>
      <button type="button" id="bSound" aria-pressed="true">Voice and sounds</button>
    </div>
    <p class="note">No sound? Turn the volume up with the side buttons and tap the screen once. It plays even when an iPhone is on silent.</p>
    <h3>Fingers</h3>
    <dl>
      <dt><i></i></dt><dd>Tap a shape to play. Drag a friend into Munchy's mouth. One finger spins the view only in the magnifying-glass place.</dd>
      <dt><i></i><i></i></dt><dd>In the magnifying-glass place: slide one finger to spin all the way around the clear shape (keep going to see its bottom), flick to let it coast, pinch with two fingers to zoom in and out. Tap it to flip it over. On a computer, drag or two-finger scroll spins it and pinch zooms.</dd>
      <dt><i></i><i></i><i></i></dt><dd>Tap for a surprise. Swipe sideways to change place. Swipe up to make everyone jump, down to reset the view.</dd>
    </dl>
    <p>The cloud button turns fart mode on or off (off at the start). The music-note button changes the dance: dance, light show, party, then back to normal. With a keyboard: 1 to 4 change place, D dances, space is a surprise, and in the magnifying-glass place the arrow keys turn the shape.</p>
    <p class="cr">Narration: Kokoro "Heart" voice. Music and sounds are made live in the browser.</p>
    <h3>Name for "Good job!"</h3>
    <input id="kidName" type="text" maxlength="16" autocomplete="off" spellcheck="false" placeholder="Child's first name" aria-label="Child's first name">
    <button type="button" id="close">Back to the game</button>
    <a class="back" href="../animations/">Back to Animations</a>
  </div>
</div>
<div id="guide" hidden>
  <div class="sheet" role="dialog" aria-labelledby="guideH">
    <h2 id="guideH">Make it a full-screen app</h2>
    <p class="lead">Added to the Home Screen, the game opens full screen every time, with no Safari bar to slip out of.</p>
    <ol class="steps">
      <li><b>1</b><svg viewBox="0 0 40 40" aria-hidden="true"><rect x="9" y="15" width="22" height="20" rx="4" fill="#e9f3ff" stroke="#2f7bf6" stroke-width="2.6"/><path d="M20 25V5m-6 6 6-6 6 6" stroke="#2f7bf6" stroke-width="2.6" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg><span id="gS1">In Safari, tap <em>Share</em>: the square with an arrow at the top right. If you don't see it, tap <em>&bull;&bull;&bull;</em> first.</span></li>
      <li><b>2</b><svg viewBox="0 0 40 40" aria-hidden="true"><rect x="7" y="7" width="26" height="26" rx="6" fill="#fff" stroke="#2b2140" stroke-width="2.6"/><path d="M20 13v14M13 20h14" stroke="#2b2140" stroke-width="2.6" stroke-linecap="round"/></svg><span>Tap <em>Add to Home Screen</em>.</span></li>
      <li><b>3</b><svg viewBox="0 0 40 40" aria-hidden="true"><rect x="4" y="12" width="32" height="16" rx="8" fill="#34c759"/><circle cx="28" cy="20" r="6.5" fill="#fff"/></svg><span>Leave <em>Open as Web App</em> on, then tap <em>Add</em>.</span></li>
      <li><b>4</b><svg viewBox="0 0 40 40" aria-hidden="true"><rect x="5" y="5" width="30" height="30" rx="8" fill="#6ec6ff" stroke="#2b2140" stroke-width="2.4"/><rect x="12" y="13" width="16" height="16" rx="3" fill="#ffc93c"/><circle cx="17" cy="19" r="1.8" fill="#2b2140"/><circle cx="23" cy="19" r="1.8" fill="#2b2140"/><path d="M16.5 23.5q3.5 3 7 0" stroke="#2b2140" stroke-width="1.8" fill="none" stroke-linecap="round"/></svg><span>Open <em>Shape Friends</em> from the Home Screen. The app keeps its own stars, so type the name again under the gear.</span></li>
    </ol>
    <div class="tip"><b>Keep little hands in the game</b>Turn on Guided Access once: Settings, Accessibility, Guided Access. Then, with the game open, triple-click the top button (or the Home button) and tap Start. The <span id="gDev">iPad</span> stays in the game until you triple-click again and enter your code.</div>
    <button type="button" id="guideClose">Got it</button>
  </div>
</div>
<div id="gearTip" hidden>Grown-ups: hold the gear</div>
<div id="teamPop" hidden>
  <div class="sheet tp" role="dialog" aria-labelledby="tpH">
    <button type="button" id="tpX" aria-label="Close"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18" stroke="#2b2140" stroke-width="3" stroke-linecap="round"/></svg></button>
    <h2 id="tpH"></h2>
    <p id="tpSub" class="note"></p>
    <div id="tpGrid"></div>
  </div>
</div>
<div id="wipe"></div>
<nav id="nav" aria-label="Places to play">
  <button type="button" data-go="story" aria-label="Dot's story"><svg viewBox="0 0 48 48"><rect x="8" y="8" width="32" height="32" rx="7" fill="#ff6fa5"/><circle cx="18" cy="22" r="5" fill="#fff"/><circle cx="30" cy="22" r="5" fill="#fff"/><circle cx="19" cy="23" r="2.4" fill="#2b2140"/><circle cx="31" cy="23" r="2.4" fill="#2b2140"/><path d="M18 31q6 5 12 0" stroke="#2b2140" stroke-width="2.5" fill="none" stroke-linecap="round"/></svg></button>
  <button type="button" data-go="pop" aria-label="Pop up shapes"><svg viewBox="0 0 48 48"><path d="M24 4l5.6 12.4L43 18l-10 9.2L35.8 41 24 34.2 12.2 41 15 27.200 5 18l13.400-1.600z" fill="#ffc93c" stroke="#f39a1e" stroke-width="2" stroke-linejoin="round"/></svg></button>
  <button type="button" data-go="munch" aria-label="Feed Munchy"><svg viewBox="0 0 48 48"><path d="M12 12 9 3l9 5zM36 12l3-9-9 5z" fill="#ffc93c"/><circle cx="24" cy="27" r="17" fill="#9b7bff"/><circle cx="17" cy="21" r="5" fill="#fff"/><circle cx="31" cy="21" r="5" fill="#fff"/><circle cx="18" cy="22" r="2.4" fill="#2b2140"/><circle cx="30" cy="22" r="2.4" fill="#2b2140"/><circle cx="24" cy="33" r="6" fill="#3a1030"/></svg></button>
  <button type="button" data-go="look" aria-label="Look closely"><svg viewBox="0 0 48 48"><circle cx="20" cy="20" r="12" fill="#bfe9ff" stroke="#2b2140" stroke-width="4"/><path d="M29 29l11 11" stroke="#2b2140" stroke-width="6" stroke-linecap="round"/><path d="M14 17a7 7 0 0 1 6-5" stroke="#fff" stroke-width="3" fill="none" stroke-linecap="round"/></svg></button>
  <button type="button" id="dance" aria-label="Dance" aria-pressed="false"><svg viewBox="0 0 48 48"><path d="M18 34V10l20-5v24" stroke="#ff6fa5" stroke-width="4" fill="none" stroke-linejoin="round"/><ellipse cx="13" cy="35" rx="6" ry="5" fill="#9b7bff"/><ellipse cx="33" cy="30" rx="6" ry="5" fill="#4db8ff"/></svg></button>
  <button type="button" id="fartb" aria-label="Fart mode" aria-pressed="false"><svg viewBox="0 0 48 48"><circle cx="17" cy="30" r="9" fill="#9bd65a"/><circle cx="28" cy="25" r="11" fill="#8fd14f"/><circle cx="35" cy="33" r="7" fill="#a6dc6c"/><path d="M14 14q3-4 0-8M24 12q3-4 0-8M34 14q3-4 0-8" stroke="#6f7f24" stroke-width="3" fill="none" stroke-linecap="round"/><circle cx="25" cy="25" r="2" fill="#2b2140"/><circle cx="31" cy="25" r="2" fill="#2b2140"/></svg></button>
  <button type="button" id="boo" aria-label="Surprise"><svg viewBox="0 0 48 48"><rect x="8" y="20" width="32" height="22" rx="4" fill="#4db8ff"/><rect x="5" y="13" width="38" height="9" rx="3" fill="#2f9be6"/><rect x="21" y="13" width="6" height="29" fill="#ffc93c"/><path d="M24 13c-9-12-16-1-6 0zM24 13c9-12 16-1 6 0z" fill="#ff6fa5"/></svg></button>
</nav>
<div id="start">
  <div class="card">
    <h1>Dot and the<br>Shape Friends</h1>
    <p>A tap-and-play world of lines, flat shapes and solid shapes. Turn the sound on.</p>
    <div class="bar"><div id="bar"></div></div><div id="load">Getting the voices ready</div>
    <button type="button" id="play" aria-label="Play"><svg viewBox="0 0 48 48"><path d="M17 11 39 24 17 37z" fill="#fff" stroke="#fff" stroke-width="4" stroke-linejoin="round"/></svg></button>
    <button type="button" id="appBtn" class="appbtn" hidden><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="4" y="2.5" width="16" height="19" rx="3" fill="#6ec6ff" stroke="#2b2140" stroke-width="2"/><path d="M8.5 9 5 5.5M15.5 9 19 5.5M8.5 15 5 18.5M15.5 15 19 18.5" stroke="#2b2140" stroke-width="1.8" stroke-linecap="round"/></svg><span>Make it a full-screen app</span></button>
    <a class="back" href="../animations/">Back to Animations</a>
  </div>
</div>
<p id="fail" hidden>This needs 3D, and this browser has it switched off.</p>
<script src="../animations/vendor/three-r128.min.js"></script>
<script src="./game.js"></script>
</body>
</html>
game.css (look, layout and the Fredoka font)148 lines

Raw file

/* Dot and the Shape Friends. Fredoka font: SIL Open Font License. */
@font-face{font-family:"Fredoka";font-style:normal;font-weight:500;font-display:swap;src:url(./fonts/fredoka-500.woff2) format("woff2")}
@font-face{font-family:"Fredoka";font-style:normal;font-weight:600;font-display:swap;src:url(./fonts/fredoka-600.woff2) format("woff2")}
@font-face{font-family:"Fredoka";font-style:normal;font-weight:700;font-display:swap;src:url(./fonts/fredoka-700.woff2) format("woff2")}
:root{--ink:#2b2140;--font:"Fredoka","Baloo 2",ui-rounded,"SF Pro Rounded","Arial Rounded MT Bold","Nunito",system-ui,sans-serif}
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{height:100%;margin:0;overflow:hidden;overscroll-behavior:none}
body{font-family:var(--font);color:var(--ink);background:radial-gradient(circle at 22% 16%,rgba(255,244,190,.9) 0,rgba(255,244,190,0) 26%),linear-gradient(#58b8ff 0%,#a9dcff 42%,#e9f7ff 70%,#fff3d1 100%);touch-action:none;user-select:none;-webkit-user-select:none}
body.disco{animation:disco 1s linear infinite}
@keyframes disco{0%{filter:hue-rotate(0)}100%{filter:hue-rotate(360deg)}}
#night{position:fixed;inset:0;pointer-events:none;opacity:0;background:radial-gradient(circle at 26% 18%,rgba(255,240,190,.35) 0,rgba(255,240,190,0) 18%),linear-gradient(#0b1033 0%,#26206a 55%,#5a3584 100%)}
#c{position:fixed;inset:0;width:100%;height:100%;display:block;touch-action:none}
button{font:inherit;color:inherit;border:0;cursor:pointer;padding:0}
button:focus-visible{outline:4px solid #2b2140;outline-offset:3px}
[hidden]{display:none !important}
#top{position:fixed;left:0;right:0;top:0;padding:max(10px,env(safe-area-inset-top)) 66px 0;display:flex;flex-direction:column;align-items:center;gap:8px;pointer-events:none}
#cap{background:#fff;border-radius:22px;padding:9px 18px 10px;max-width:560px;text-align:center;box-shadow:0 5px 0 rgba(43,33,64,.14);border:3px solid #2b2140}
#cap.pop{animation:cap .45s cubic-bezier(.3,1.6,.5,1)}
@keyframes cap{0%{transform:scale(.8) rotate(-2deg)}100%{transform:none}}
#capT{font-size:21px;line-height:1.2;font-weight:600;text-wrap:balance}
#capS{font-size:12.5px;line-height:1.3;color:#6d6485;font-weight:500;margin-top:2px}
#capS:empty{display:none}
#stickers{display:flex;gap:5px;background:rgba(255,255,255,.75);border-radius:999px;padding:5px 8px}
#stickers span{width:30px;height:30px;display:grid;place-items:center;border-radius:50%;background:#e8edf5;transition:background .3s}
#stickers svg{width:20px;height:20px;fill:#c2cbd9;transition:fill .3s}
#stickers span.got{background:#fff;animation:got .6s cubic-bezier(.3,1.8,.5,1)}
#stickers span.got svg{fill:var(--c)}
@keyframes got{0%{transform:scale(.3) rotate(-40deg)}100%{transform:none}}
#tools{position:fixed;right:10px;top:max(10px,env(safe-area-inset-top));display:flex;flex-direction:column;gap:8px;align-items:center}
#tools button{width:46px;height:46px;border-radius:50%;background:#fff;border:3px solid #2b2140;display:grid;place-items:center;box-shadow:0 4px 0 rgba(43,33,64,.14)}
#tools svg{width:24px;height:24px;fill:#2b2140}
#stars{min-width:46px;background:#fff6c9;border:3px solid #2b2140;border-radius:16px;padding:3px 6px 4px;text-align:center;font-weight:700;font-size:15px;line-height:1.05;box-shadow:0 4px 0 rgba(43,33,64,.14)}
#stars .s{display:block;color:#f5a400;font-size:19px}
#stars.bump{animation:got .55s cubic-bezier(.3,1.8,.5,1)}
.fly{position:fixed;left:50%;top:45%;font-size:64px;color:#ffc93c;text-shadow:0 3px 0 #2b2140;pointer-events:none;animation:fly .9s cubic-bezier(.5,0,.3,1) forwards}
@keyframes fly{0%{transform:translate(-50%,-50%) scale(.2) rotate(-40deg);opacity:0}25%{transform:translate(-50%,-50%) scale(1.3) rotate(10deg);opacity:1}100%{transform:translate(calc(50vw - 60px),calc(-45vh + 130px)) scale(.3) rotate(200deg);opacity:.9}}
#panel{position:fixed;inset:0;background:rgba(43,33,64,.45);display:grid;place-items:center;padding:14px;z-index:5}
.sheet{background:#fff;border:4px solid #2b2140;border-radius:26px;padding:18px 20px 20px;max-width:440px;width:100%;max-height:100%;overflow:auto;box-shadow:0 10px 0 rgba(43,33,64,.25)}
.sheet h2{margin:0 0 12px;font-size:22px;font-weight:700}
.sheet h3{margin:16px 0 6px;font-size:15px;font-weight:700}
.toggles{display:flex;flex-wrap:wrap;gap:8px}
.toggles button,#close{min-height:44px;padding:0 16px;border-radius:999px;border:3px solid #2b2140;background:#fff;font-weight:600;font-size:15px}
.toggles button[aria-pressed="true"]{background:#c9f5d3}
.toggles button[aria-pressed="false"]{background:#e6e6ee;color:#7c7691;text-decoration:line-through}
.sheet dl{margin:0;display:grid;grid-template-columns:58px 1fr;gap:10px 8px;align-items:center}
.sheet dt{display:flex;gap:4px}
.sheet dt i{width:14px;height:14px;border-radius:50%;background:#ff6fa5;border:2px solid #2b2140}
.sheet dd{margin:0;font-size:14px;line-height:1.4;font-weight:500}
.sheet p{margin:12px 0 0;font-size:13.5px;line-height:1.4;color:#6d6485;font-weight:500}
.sheet .cr{font-size:12px}
#close{margin-top:16px;background:#ff6fa5;color:#fff;width:100%}
.toggles button svg{width:20px;height:20px;vertical-align:-4px;margin-right:6px}
.sheet .note{margin:8px 0 0}
.appbtn{display:flex;align-items:center;justify-content:center;gap:8px;margin:18px auto 0;min-height:46px;padding:0 18px 0 14px;border-radius:999px;border:3px solid #2b2140;background:#fff6d6;font-family:inherit;font-weight:600;font-size:15px;color:#2b2140;box-shadow:0 4px 0 rgba(43,33,64,.14)}
.appbtn svg{width:22px;height:22px}
#guide{position:fixed;inset:0;background:rgba(43,33,64,.45);display:grid;place-items:center;padding:14px;z-index:6}
.sheet .lead{margin:0 0 4px;color:#2b2140;font-size:15px}
.steps{list-style:none;margin:12px 0 0;padding:0;display:grid;gap:12px}
.steps li{display:grid;grid-template-columns:30px 40px 1fr;gap:10px;align-items:center;font-size:15px;line-height:1.35;font-weight:500}
.steps b{width:30px;height:30px;border-radius:50%;background:#ff6fa5;color:#fff;display:grid;place-items:center;font-weight:700;font-size:15px;border:3px solid #2b2140;box-sizing:border-box}
.steps svg{width:40px;height:40px}
.steps em{font-style:normal;font-weight:700}
.tip{margin-top:16px;padding:12px 14px;border-radius:16px;background:#eef7ff;border:2px dashed #4db8ff;font-size:14px;line-height:1.4;font-weight:500}
.tip b{display:block;margin-bottom:3px}
#guideClose{margin-top:16px;min-height:46px;width:100%;border-radius:999px;border:3px solid #2b2140;background:#ff6fa5;color:#fff;font-family:inherit;font-weight:600;font-size:16px}
#gear{position:relative}
#teamPop{position:fixed;inset:0;background:rgba(43,33,64,.38);display:flex;overflow:auto;padding:max(14px,env(safe-area-inset-top)) 14px max(14px,env(safe-area-inset-bottom));z-index:5}
.sheet.tp{margin:auto;max-width:560px;position:relative;border-top-width:10px;border-top-color:var(--c,#ff6fa5);padding-top:16px}
.tp h2{margin:0 52px 0 0;font-size:26px}
#tpX{position:absolute;top:10px;right:10px;width:46px;height:46px;border-radius:50%;border:3px solid #2b2140;background:#fff;display:grid;place-items:center;padding:0}
#tpX svg{width:22px;height:22px}
#tpGrid{display:grid;grid-template-columns:repeat(var(--cols,3),minmax(0,1fr));gap:12px;margin-top:14px}
.tpb{display:flex;flex-direction:column;align-items:center;gap:2px;padding:8px 6px 10px;border-radius:24px;border:3px solid #2b2140;background:#fff;font-family:inherit;font-weight:600;font-size:14px;line-height:1.2;color:#2b2140;box-shadow:0 5px 0 var(--c,#ff6fa5);cursor:pointer}
.tpb img{width:100%;max-width:128px;height:auto;aspect-ratio:1;display:block}
.tpb.on{background:#fff6d6}
.tpb:active{transform:translateY(3px);box-shadow:0 2px 0 var(--c,#ff6fa5)}
@media (max-width:359px){#tpGrid{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media (max-height:520px){.sheet.tp{max-width:720px}.tp h2{font-size:21px}.tpb img{max-width:76px}#tpGrid{grid-template-columns:repeat(var(--colsS,6),minmax(0,1fr));gap:8px;margin-top:10px}}
#gear::after{content:'';position:absolute;inset:-7px;border-radius:50%;background:conic-gradient(#ff6fa5 calc(var(--p,0)*1turn),rgba(255,111,165,.15) 0);-webkit-mask:radial-gradient(farthest-side,transparent calc(100% - 5px),#000 calc(100% - 4px));mask:radial-gradient(farthest-side,transparent calc(100% - 5px),#000 calc(100% - 4px));opacity:0;transition:opacity .15s;pointer-events:none}
#gear.hold::after{opacity:1}
#gearTip{position:fixed;right:68px;top:max(14px,env(safe-area-inset-top));background:#2b2140;color:#fff;border-radius:14px;padding:9px 13px;font-size:14px;font-weight:600;z-index:4;pointer-events:none;box-shadow:0 4px 0 rgba(43,33,64,.18)}
#wipe{position:fixed;inset:0;background:#fff6c9;pointer-events:none;opacity:0;z-index:4}
#wipe.go{animation:wipe .62s ease-out}
@keyframes wipe{0%{opacity:1;clip-path:circle(0% at 50% 55%)}40%{opacity:1;clip-path:circle(80% at 50% 55%)}100%{opacity:0;clip-path:circle(80% at 50% 55%)}}
.bar{height:10px;border-radius:999px;background:#e8edf5;overflow:hidden;margin:0 6px 6px;border:2px solid #2b2140}
#bar{height:100%;width:0;background:#4fd08a;transition:width .2s}
#load{font-size:12.5px;color:#6d6485;font-weight:500;margin-bottom:28px}
#nav{position:fixed;left:0;right:0;bottom:max(12px,env(safe-area-inset-bottom));display:flex;justify-content:center;gap:8px;pointer-events:none}
#nav button{pointer-events:auto;width:clamp(36px,calc((100vw - 96px) / 7),66px);height:clamp(36px,calc((100vw - 96px) / 7),66px);border-radius:50%;background:#fff;border:4px solid #2b2140;display:grid;place-items:center;box-shadow:0 6px 0 rgba(43,33,64,.2);transition:transform .15s}
#nav button:active{transform:translateY(4px) scale(.95);box-shadow:0 2px 0 rgba(43,33,64,.2)}
#nav svg{width:62%;height:62%}
#nav button.on{background:#fff6c9;transform:translateY(-6px) scale(1.08)}
#nav button.beg{animation:beg .7s ease-in-out infinite alternate}
@keyframes beg{to{transform:translateY(-14px) scale(1.18) rotate(6deg)}}
#boo{margin-left:10px}
#start{position:fixed;inset:0;display:flex;overflow:auto;background:rgba(110,198,255,.35);padding:max(14px,env(safe-area-inset-top)) 14px max(14px,env(safe-area-inset-bottom))}
#start .card{margin:auto}
.card{background:#fff;border:4px solid #2b2140;border-radius:34px;padding:26px 26px 30px;text-align:center;max-width:380px;box-shadow:0 10px 0 rgba(43,33,64,.18)}
.card h1{margin:0;font-size:34px;line-height:1.05;font-weight:700}
.card p{margin:10px 0 14px;font-size:15px;line-height:1.4;color:#6d6485;font-weight:500}
#play{width:112px;height:112px;border-radius:50%;background:#ff6fa5;border:5px solid #2b2140;display:inline-grid;place-items:center;box-shadow:0 8px 0 #2b2140;animation:beg .8s ease-in-out infinite alternate}
#play svg{width:60px;height:60px;margin-left:6px}
#fail{position:fixed;inset:0;margin:0;display:grid;place-items:center;font-size:18px;padding:30px;text-align:center}
#cap.mun{border-color:#7c5cff;background:#f3eeff}
#giggle{display:flex;align-items:center;gap:6px;background:rgba(255,255,255,.85);border-radius:999px;padding:4px 10px 4px 5px;align-self:center}
#giggle svg{width:30px;height:30px}
#giggle .gbar{width:120px;height:14px;border-radius:999px;background:#ece6ff;border:2px solid #2b2140;overflow:hidden}
#gfill{height:100%;width:0;background:linear-gradient(90deg,#ff6fa5,#ffc93c,#4fd08a);transition:width .5s cubic-bezier(.3,1.6,.5,1)}
#giggle.bump{animation:got .5s cubic-bezier(.3,1.8,.5,1)}
#kidName{width:100%;min-height:44px;border:3px solid #2b2140;border-radius:14px;padding:0 12px;font:600 16px var(--font);color:#2b2140}
#chips{display:flex;flex-wrap:wrap;justify-content:center;gap:6px;background:rgba(255,255,255,.82);border-radius:22px;padding:5px 7px;pointer-events:auto;align-self:center}
#chips button{width:40px;height:40px;border-radius:50%;background:#eef1f7;display:grid;place-items:center;border:3px solid transparent;transition:transform .15s}
#chips svg{width:22px;height:22px;fill:var(--c)}
#chips button.on{background:#fff;border-color:#2b2140;transform:scale(1.12)}
#dims{position:fixed;right:12px;top:50%;transform:translateY(-50%);display:flex;flex-direction:column;gap:12px;z-index:2}
#dims button{width:66px;height:66px;border-radius:22px;background:#fff;border:4px solid #2b2140;font:700 23px/1 var(--font);color:#2b2140;box-shadow:0 5px 0 rgba(43,33,64,.2)}
#dims button.on{background:#ffc93c;transform:scale(1.08)}
#dims button:active{transform:translateY(3px)}
#vig{position:fixed;inset:0;pointer-events:none;background:radial-gradient(ellipse 85% 75% at 50% 46%,rgba(0,0,0,0) 58%,rgba(18,28,70,.2) 100%)}
#build{position:fixed;left:12px;top:50%;transform:translateY(-50%);display:flex;flex-direction:column;gap:9px;z-index:2}
#build button{width:56px;height:56px;border-radius:18px;background:#fff;border:4px solid #2b2140;display:grid;place-items:center;box-shadow:0 4px 0 rgba(43,33,64,.2)}
#build svg{width:62%;height:62%}
#build button.on{background:#fff1b8;transform:scale(1.08)}
#build .sep{height:6px}
#fartb.on{background:#e6f7d4;animation:beg .5s ease-in-out infinite alternate}
#dance.on{background:#ffe0f0;animation:beg .45s ease-in-out infinite alternate}
@media (max-width:420px){#capT{font-size:18px}#top{padding-left:10px;padding-right:62px;align-items:stretch}#stickers{align-self:center}#nav{gap:7px}#nav button{border-width:3px}#boo{margin-left:4px}#dims button{width:58px;height:58px;font-size:20px}#build button{width:46px;height:46px;border-width:3px}#build{gap:7px}#chips{gap:3px;padding:4px 5px}#chips button{width:31px;height:31px;border-width:2px}#chips svg{width:18px;height:18px}}
@media (max-height:480px){#nav button{width:54px;height:54px}#nav svg{width:34px;height:34px}#capT{font-size:17px}}
@media (max-height:520px) and (orientation:landscape){
  #nav{left:max(10px,env(safe-area-inset-left));right:auto;top:0;bottom:0;flex-direction:column;justify-content:center;gap:8px}
  #nav button{width:42px;height:42px;border-width:3px}
  #nav svg{width:28px;height:28px}
  #build{top:auto;left:50%;bottom:max(10px,env(safe-area-inset-bottom));transform:translateX(-50%);flex-direction:row}
  #build .sep{width:6px;height:auto}
  #build button{width:46px;height:46px}
  #dims{top:auto;bottom:max(10px,env(safe-area-inset-bottom));transform:none;flex-direction:row}
  #dims button{width:54px;height:54px;font-size:19px}
  #nav button.on{transform:translateX(6px) scale(1.06)}
  #boo{margin-left:0;margin-top:6px}
  #top{padding-left:76px}
  #stickers{position:fixed;left:50%;bottom:max(8px,env(safe-area-inset-bottom));transform:translateX(-50%)}
}
@media (max-height:520px){.card{padding:14px 22px 16px;border-radius:26px}.card h1{font-size:24px}.card p{margin:6px 0 8px;font-size:13px}#play{width:78px;height:78px;box-shadow:0 6px 0 #2b2140}#play svg{width:42px;height:42px}.appbtn{margin-top:10px;min-height:40px;font-size:14px}#load{margin-bottom:22px}}
@media (prefers-reduced-motion:reduce){#play,#nav button.beg,#dance.on,#fartb.on{animation:none}}
.back{display:block;margin-top:14px;font-size:13px;font-weight:600;color:#6d6485;text-decoration:none}
.back:hover{color:#2b2140}
.sheet .back{text-align:center}
manifest.webmanifest (save it to a home screen as a full-screen app)24 lines

Raw file

{
 "name": "Dot and the Shape Friends",
 "short_name": "Shape Friends",
 "description": "A 3D tap-and-play game that teaches lines, flat shapes and solid shapes to young children.",
 "start_url": "./",
 "scope": "./",
 "display": "fullscreen",
 "orientation": "any",
 "background_color": "#6ec6ff",
 "theme_color": "#6ec6ff",
 "icons": [
  {
   "src": "icon-192.png",
   "sizes": "192x192",
   "type": "image/png"
  },
  {
   "src": "icon-512.png",
   "sizes": "512x512",
   "type": "image/png",
   "purpose": "any maskable"
  }
 ]
}
voices.py (records every narrator and Munchy line, free and offline)187 lines

Raw file

#!/usr/bin/env python3
"""Record every spoken line of Dot and the Shape Friends, free and offline, with Kokoro.

The narrator is Kokoro "af_heart"; Munchy is Kokoro "am_puck" (the game plays him a little slower).
Each line becomes one small MP3 in v/ next to game.js, named by a hash of the line, and the VOX
(narrator) and VOXM (Munchy) lists at the top of game.js's voice section are rewritten to match.
A line with no clip still shows as a caption and is read by the device voice instead.

Setup (once):
  pip install kokoro-onnx soundfile numpy
  put kokoro-v1.0.onnx and voices-v1.0.bin (from the kokoro-onnx releases) next to this file
  install ffmpeg (it turns the recordings into MP3)

Use:
  python3 voices.py check game.js          what is missing, without recording anything
  python3 voices.py record game.js         record only the lines that have no clip yet
  python3 voices.py record game.js --all   record every line again (new voice, new speed)
  python3 voices.py selftest               checks the line finder and the file names

Where the lines come from: the VOX and VOXM lists already in game.js, every say('...') and
munSay('...') with a plain line in quotes, and Munchy's munLines() list. Lines the game builds
from pieces ('Look! A see-through ' + name) are not visible here: open the game, run
copy(__sf.lines().join('\\n')) in the browser console, paste into a text file and add
--lines that-file.txt (and --munchy-lines for Munchy's own).
"""
import json, os, re, subprocess, sys, tempfile

HERE = os.path.dirname(os.path.abspath(__file__))
NARRATOR, MUNCHY = 'af_heart', 'am_puck'
# How a line is said, when the written form reads badly aloud. The clip keeps the written line's name.
SAY_AS = {
    'Wheee! Round and round!': 'Whee! Round and round!',
    'Ah... ah... ah... choo!': 'Ah, ah, ah, choo!',
    'Pee-yew! Stinky!': 'Pee-yoo! Stinky!',
    '1D! Now it is just a line.': 'One D! Now it is just a line.',
    '2D! Now it is flat, like a drawing.': 'Two D! Now it is flat, like a drawing.',
    '3D! A solid shape again.': 'Three D! A solid shape again.',
}


def name_for(line, munchy=False):
    """The clip's file name: a 32-bit hash of the line, 8 hex digits; Munchy's start with m."""
    v = 5381
    for ch in line:
        v = ((v * 33) ^ ord(ch)) & 0xffffffff
    return ('m' if munchy else '') + '%08x' % v + '.mp3'


def read_list(js, var):
    """The JSON object after 'var NAME=' (or 'NAME=') in game.js, and where it sits."""
    m = re.search(r'(?<![A-Za-z_$])' + var + r'=\{', js)
    if not m:
        raise SystemExit(f'could not find {var}={{...}} in game.js')
    i = m.end() - 1
    depth, j, quote = 0, i, None
    while j < len(js):
        c = js[j]
        if quote:
            if c == '\\':
                j += 1
            elif c == quote:
                quote = None
        elif c in '"\'':
            quote = c
        elif c == '{':
            depth += 1
        elif c == '}':
            depth -= 1
            if depth == 0:
                break
        j += 1
    return json.loads(js[i:j + 1]), (i, j + 1)


def unquote(s):
    return s.replace("\\'", "'").replace('\\"', '"')


def find_lines(js):
    """Narrator and Munchy lines written out in full in game.js."""
    lit = r"(['\"])((?:\\.|(?!\1).)*)\1\s*[,)]"
    narr = {unquote(m.group(2)) for m in re.finditer(r'(?<![A-Za-z_$])say\(\s*' + lit, js)}
    mun = {unquote(m.group(2)) for m in re.finditer(r'(?<![A-Za-z_$])munSay\(\s*' + lit, js)}
    m = re.search(r'function munLines\(\)\{return \[(.*?)\];\}', js, re.S)
    if m:
        mun |= {unquote(q.group(2)) for q in re.finditer(r"(['\"])((?:\\.|(?!\1).)*)\1", m.group(1))}
    return {l for l in narr if l.strip()}, {l for l in mun if l.strip()}


def plan(js_path, extra_narr=(), extra_mun=(), redo=False):
    js = open(js_path, encoding='utf-8').read()
    vox, _ = read_list(js, 'VOX')
    voxm, _ = read_list(js, 'VOXM')
    narr, mun = find_lines(js)
    narr |= set(vox) | set(extra_narr)
    mun |= set(voxm) | set(extra_mun)
    vdir = os.path.join(os.path.dirname(os.path.abspath(js_path)), 'v')
    todo = []
    for lines, have, munchy in ((narr, vox, False), (mun, voxm, True)):
        for line in sorted(lines):
            f = have.get(line) or name_for(line, munchy)
            if redo or not os.path.exists(os.path.join(vdir, f)):
                todo.append((line, f, munchy))
    return js, vox, voxm, narr, mun, vdir, todo


def record(js_path, extra_narr, extra_mun, redo):
    js, vox, voxm, narr, mun, vdir, todo = plan(js_path, extra_narr, extra_mun, redo)
    print(f'{len(narr)} narrator lines, {len(mun)} Munchy lines, {len(todo)} to record')
    if todo:
        import numpy as np, soundfile as sf
        from kokoro_onnx import Kokoro
        k = Kokoro(os.path.join(HERE, 'kokoro-v1.0.onnx'), os.path.join(HERE, 'voices-v1.0.bin'))
        os.makedirs(vdir, exist_ok=True)
        wav = os.path.join(tempfile.gettempdir(), 'shape-friends-line.wav')
        for n, (line, f, munchy) in enumerate(todo, 1):
            s, sr = k.create(SAY_AS.get(line, line), voice=MUNCHY if munchy else NARRATOR,
                             speed=1.0 if munchy else 0.95, lang='en-us')
            s = np.asarray(s, dtype=np.float32)
            loud = np.where(np.abs(s) > 0.012)[0]                     # trim the silence at both ends
            if len(loud):
                s = s[max(0, loud[0] - int(.03 * sr)):min(len(s), loud[-1] + int(.12 * sr))]
            s = s / max(1e-6, float(np.max(np.abs(s)))) * 0.86     # same loudness for every line
            fade = int(.04 * sr)
            s[-fade:] *= np.linspace(1, 0, fade)
            sf.write(wav, s, sr)
            subprocess.run(['ffmpeg', '-y', '-loglevel', 'error', '-i', wav, '-ac', '1', '-ar', '24000',
                            '-b:a', '48k', os.path.join(vdir, f)], check=True)
            print(f'  {n}/{len(todo)} {f}  {line}')
    for line in narr:
        vox.setdefault(line, name_for(line))
    for line in mun:
        voxm.setdefault(line, name_for(line, True))
    for var, table in (('VOX', vox), ('VOXM', voxm)):          # write the lists back into game.js
        _, (a, b) = read_list(js, var)
        js = js[:a] + json.dumps(dict(sorted(table.items())), ensure_ascii=False) + js[b:]
    open(js_path, 'w', encoding='utf-8').write(js)
    print('game.js lists updated')


def check(js_path, extra_narr, extra_mun):
    _, vox, voxm, narr, mun, vdir, todo = plan(js_path, extra_narr, extra_mun)
    print(f'{len(narr)} narrator lines, {len(mun)} Munchy lines, clips in {vdir}')
    for line, f, munchy in todo:
        print(f'  missing {"Munchy " if munchy else ""}{f}  {line}')
    print('all lines have clips' if not todo else f'{len(todo)} missing: run "record" to make them')
    return len(todo)


def selftest():
    js = ("var VOX={\"Hi!\": \"x.mp3\"};var VOXM={};function munLines(){return ['Ha ha!','Hee \\'hee\\'!'];}"
          "say('Tap Dot!');say(\"It's a cube!\",'sub');munSay('Yum!',null,{p:0});dismay('no');say('A '+n+'!');")
    narr, mun = find_lines(js)
    assert narr == {'Tap Dot!', "It's a cube!"}, narr
    assert mun == {'Yum!', 'Ha ha!', "Hee 'hee'!"}, mun
    assert read_list(js, 'VOX')[0] == {'Hi!': 'x.mp3'} and read_list(js, 'VOXM')[0] == {}
    assert name_for('This is Dot. Dot is teeny tiny. Tap Dot!') == name_for('This is Dot. Dot is teeny tiny. Tap Dot!')
    assert name_for('Hi!', True).startswith('m') and len(name_for('Hi!')) == 12
    print('selftest passed')


def main(argv):
    if not argv or argv[0] not in ('check', 'record', 'selftest'):
        print(__doc__)
        return 2
    if argv[0] == 'selftest':
        selftest()
        return 0
    if len(argv) < 2:
        print('give the path to game.js')
        return 2
    js_path, rest = argv[1], argv[2:]

    def lines_from(flag):
        if flag in rest:
            return [l.strip() for l in open(rest[rest.index(flag) + 1], encoding='utf-8') if l.strip()]
        return []
    extra_n, extra_m = lines_from('--lines'), lines_from('--munchy-lines')
    if argv[0] == 'check':
        return 1 if check(js_path, extra_n, extra_m) else 0
    record(js_path, extra_n, extra_m, '--all' in rest)
    return 0


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

Need an interactive piece for your business or audience?

A product explainer, a training walkthrough, a simulation people can play with. This one is free to take. I can build yours for a fixed price agreed up front, and the first call is free.

How it works and what it costs Book a free call ↗

Or write to me · how to use what is here