/* 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=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=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=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=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;i0?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.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;i0){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;i0?.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=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=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=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:'', cylinder:'', cone:'', donut:'', cube:'', brick:'', prism:'', pyramid:'' }; (function(){ var h='';SOLIDS.forEach(function(k){h+=''+ICON[k]+'';}); $('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:'',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:'',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:'',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:'',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=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'+DEF[k].name+'';}); 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;j0);$('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(dd60&&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'+t.icon+'';}); $('chips').innerHTML=h;var cs=document.querySelectorAll('#chips button'); for(var i=0;i]/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 ••• next to the address bar, then Share.';$('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;i26)c.position.x=-26;} for(var pi=0;pi0)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;tpk)pk=v;sq+=v*v;}AC=null;return {peak:pk,rms:Math.sqrt(sq/d.length)};}); }}; })();