Test forum

Информация о пользователе

Привет, Гость! Войдите или зарегистрируйтесь.


Вы здесь » Test forum » Новый форум » free


free

Сообщений 1 страница 7 из 7

1

2

3

[html]
<div id="rabbit-check-module" style="padding:16px;background:#332e2e;color:#7beeff;text-align:center;border-radius:8px;">
  Проверяем загрузчик...
</div>
<script>
(function () {
  var box = document.getElementById('rabbit-check-module');
  var s = document.createElement('script');

  s.src = 'https://cdn.jsdelivr.net/npm/three-stdlib@2.35.12/index.cjs';

  s.onload = function () {
    box.textContent = 'Скрипт загрузился. Проверяем совместимость...';
  };

  s.onerror = function () {
    box.textContent = 'Эта сборка не подходит для прямого подключения';
  };

  document.head.appendChild(s);
})();
</script>
[/html]

Тут есть нюанс: `three-stdlib` распространяется как библиотека для сборщиков и модульных окружений. Этот тест не гарантирует, что она станет доступна как глобальный `THREE.GLTFLoader`; он лишь проверяет, можно ли вообще получить её таким способом. Если нет — перейдём к более надёжному варианту с CDN, который отдаёт готовые браузерные сборки.

И ещё, бро: **не удаляй рабочий тест Three.js + GSAP**, где отображаются их версии. Он нам пригодится для финальной сборки. 🐇🥕

0

4

5

[html]
<div id="bunny-scene-ru" style="position:relative;width:100%;height:460px;overflow:hidden;background:#332e2e;border:1px solid #7beeff;border-radius:8px;isolation:isolate;">
  <canvas class="bunny-webgl" style="display:block;width:100%;height:100%;outline:none;touch-action:none;"></canvas>
  <div class="bunny-status" style="position:absolute;left:10px;top:10px;color:#7beeff;font:12px monospace;z-index:2;pointer-events:none;">Загружаем кролика...</div>
  <div style="position:absolute;bottom:32px;left:0;width:100%;text-align:center;color:#ff3434;font:11px Arial,sans-serif;letter-spacing:2px;text-transform:uppercase;pointer-events:none;">Move to guide · Click to jump</div>
  <div style="position:absolute;bottom:9px;left:0;width:100%;text-align:center;color:#7beeff;font:10px Arial,sans-serif;opacity:.7;pointer-events:none;">Skating bunny · Three.js</div>
</div>

<script type="x-shader/x-vertex" id="bunny-reflector-v">
uniform mat4 textureMatrix;
varying vec4 vUvReflection;
varying vec2 vUv;
#include <common>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
void main(){
#include <beginnormal_vertex>
#include <defaultnormal_vertex>
#include <begin_vertex>
vUvReflection=textureMatrix*vec4(position,1.0);
vUv=uv;
gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);
#include <logdepthbuf_vertex>
#include <worldpos_vertex>
#include <shadowmap_vertex>
}
</script>

<script type="x-shader/x-fragment" id="bunny-reflector-f">
uniform vec3 color;
uniform sampler2D tDiffuse;
uniform sampler2D tScratches;
varying vec4 vUvReflection;
varying vec2 vUv;
#include <common>
#include <packing>
#include <lights_pars_begin>
#include <shadowmap_pars_fragment>
#include <shadowmask_pars_fragment>
#include <logdepthbuf_pars_fragment>
vec4 blur9(sampler2D image,vec4 uv,vec2 resolution,vec2 direction){
vec4 c=vec4(0.0);
vec2 o1=vec2(1.3846153846)*direction;
vec2 o2=vec2(3.2307692308)*direction;
c+=texture2DProj(image,uv)*0.2270270270;
c+=texture2DProj(image,uv+vec4(o1/resolution,o1/resolution))*0.3162162162;
c+=texture2DProj(image,uv-vec4(o1/resolution,o1/resolution))*0.3162162162;
c+=texture2DProj(image,uv+vec4(o2/resolution,o2/resolution))*0.0702702703;
c+=texture2DProj(image,uv-vec4(o2/resolution,o2/resolution))*0.0702702703;
return c;
}
float blendOverlay(float a,float b){
return a<0.5?2.0*a*b:1.0-2.0*(1.0-a)*(1.0-b);
}
vec3 blendOverlay(vec3 a,vec3 b){
return vec3(blendOverlay(a.r,b.r),blendOverlay(a.g,b.g),blendOverlay(a.b,b.b));
}
void main(){
#include <logdepthbuf_fragment>
vec4 d=vec4(sin(vUvReflection.y*3.0)*0.05,sin(vUvReflection.x*3.0)*0.05,0.0,0.0);
vec2 r=vec2(30.0,30.0);
vec4 base=blur9(tDiffuse,vUvReflection+d,r,vec2(1.0,0.0))*0.25;
base+=blur9(tDiffuse,vUvReflection+d,r,vec2(-1.0,0.0))*0.25;
base+=blur9(tDiffuse,vUvReflection+d,r,vec2(0.0,1.0))*0.25;
base+=blur9(tDiffuse,vUvReflection+d,r,vec2(0.0,-1.0))*0.25;
vec4 scratches=texture2D(tScratches,vUv);
vec3 col=mix(color,base.rgb,0.5);
col.rgb+=scratches.r*0.02;
col.gb-=scratches.g*0.01;
col.gb-=(1.0-getShadowMask())*0.015;
gl_FragColor=vec4(col,1.0);
#include <tonemapping_fragment>
#include <colorspace_fragment>
}
</script>

<script type="x-shader/x-vertex" id="bunny-sim-v">
precision highp float;
uniform float time;
varying vec2 vUv;
void main(){
vUv=uv;
gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);
}
</script>

<script type="x-shader/x-fragment" id="bunny-sim-f">
precision highp float;
uniform sampler2D inputTexture;
uniform vec2 blade1PosOld;
uniform vec2 blade1PosNew;
uniform float strength;
uniform float time;
varying vec2 vUv;
float lineSegment(vec2 p,vec2 a,vec2 b,float thickness){
vec2 pa=p-a;
vec2 ba=b-a;
float h=clamp(dot(pa,ba)/max(dot(ba,ba),0.000001),0.0,1.0);
float d=length(pa-ba*h);
return smoothstep(thickness,0.2*thickness,d);
}
void main(){
vec4 prev=texture2D(inputTexture,vUv);
vec3 col=prev.rgb*0.999;
if(strength>0.0){
  float space=0.001;
  float crease=0.001;
  float thick=0.001+strength*0.001;
  float lr=lineSegment(vUv+vec2(space),blade1PosOld,blade1PosNew,thick);
  float lg=lineSegment(vUv+vec2(space+crease),blade1PosOld,blade1PosNew,thick);
  float rr=lineSegment(vUv-vec2(space+crease),blade1PosOld,blade1PosNew,thick);
  float rg=lineSegment(vUv-vec2(space),blade1PosOld,blade1PosNew,thick);
  col.r=clamp(col.r+(lr+rr)*strength*3.0,0.0,1.0);
  col.g=clamp(col.g+(lg+rg)*strength*3.0,0.0,1.0);
}
gl_FragColor=vec4(col,1.0);
}
</script>

<script type="x-shader/x-fragment" id="bunny-outline-f">
uniform vec3 color;
void main(){gl_FragColor=vec4(color,1.0);}
</script>

<script type="x-shader/x-vertex" id="bunny-outline-v">
uniform float size;
uniform float time;
void main(){
vec3 p=position+normal*size*(1.0+abs(sin(position.y*time*0.02)*2.0));
gl_Position=projectionMatrix*modelViewMatrix*vec4(p,1.0);
}
</script>

<script>
(function(){
  var root=document.getElementById('bunny-scene-ru');
  if(!root||root.dataset.started)return;
  root.dataset.started='1';
  var status=root.querySelector('.bunny-status');
  var canvas=root.querySelector('canvas');
  var alive=true;

  function fail(err){
    if(status)status.textContent='Не удалось запустить сцену: '+(err&&err.message?err.message:String(err));
    if(window.console)console.error('Skating bunny:',err);
  }

  Promise.all([
    import('https://esm.sh/three@0.156.1'),
    import('https://esm.sh/three@0.156.1/examples/jsm/loaders/GLTFLoader.js'),
    import('https://esm.sh/three@0.156.1/examples/jsm/objects/Reflector.js'),
    import('https://esm.sh/gsap')
  ]).then(function(modules){
    if(!alive||!root.isConnected)return;
    var THREE=modules[0];
    var GLTFLoader=modules[1].GLTFLoader;
    var Reflector=modules[2].Reflector;
    var gsap=modules[3].gsap||modules[3].default;
    if(!THREE||!GLTFLoader||!Reflector||!gsap)throw new Error('Не все модули доступны');

    class BufferSim{
      constructor(renderer,width,height,shader){
        this.renderer=renderer;
        this.shader=shader;
        this.orthoScene=new THREE.Scene();
        var fbo=new THREE.WebGLRenderTarget(width,height,{
          wrapS:THREE.ClampToEdgeWrapping,
          wrapT:THREE.ClampToEdgeWrapping,
          minFilter:THREE.LinearFilter,
          magFilter:THREE.LinearFilter,
          format:THREE.RGBAFormat,
          type:THREE.HalfFloatType,
          stencilBuffer:false,
          depthBuffer:false
        });
        fbo.texture.generateMipmaps=false;
        this.fbos=[fbo,fbo.clone()];
        this.current=0;
        this.output=this.fbos[0];
        this.orthoCamera=new THREE.OrthographicCamera(width/-2,width/2,height/2,height/-2,0.00001,1000);
        this.orthoQuad=new THREE.Mesh(new THREE.PlaneGeometry(width,height),this.shader);
        this.orthoScene.add(this.orthoQuad);
      }
      render(){
        this.shader.uniforms.inputTexture.value=this.fbos[this.current].texture;
        this.current=1-this.current;
        this.output=this.fbos[this.current];
        this.renderer.setRenderTarget(this.output);
        this.renderer.render(this.orthoScene,this.orthoCamera);
        this.renderer.setRenderTarget(null);
      }
    }

    class App{
      constructor(){
        this.root=root;
        this.canvas=canvas;
        this.bgrColor=0x332e2e;
        this.floorSize=30;
        this.winWidth=Math.max(1,root.clientWidth);
        this.winHeight=Math.max(1,root.clientHeight);
        this.gltfFile='https://assets.codepen.io/264161/rabbit6.glb';
        this.clock=new THREE.Clock();
        this.time=0;
        this.heroAngularSpeed=0;
        this.heroOldRot=0;
        this.heroDistance=0;
        this.heroOldUVPos=new THREE.Vector2(0.5,0.5);
        this.heroNewUVPos=new THREE.Vector2(0.5,0.5);
        this.heroSpeed=new THREE.Vector2(0,0);
        this.targetHeroUVPos=new THREE.Vector2(0.5,0.5);
        this.targetHeroAbsMousePos=new THREE.Vector2(0,0);
        this.raycaster=new THREE.Raycaster();
        this.mouse=new THREE.Vector2();
        this.isJumping=false;
        this.isExploding=false;
        this.jumpParams={jumpProgress:0};
        this.scene=new THREE.Scene();
        this.scene.fog=new THREE.Fog(this.bgrColor,13,20);
        this.camera=new THREE.PerspectiveCamera(60,this.winWidth/this.winHeight,1,100);
        this.camera.position.set(0,4,8);
        this.camera.lookAt(0,0,0);
        this.scene.add(this.camera);
        this.createRenderer();
        this.createSim();
        this.createMaterials();
        this.createListeners();
        new GLTFLoader().load(this.gltfFile,(gltf)=>{
          if(!alive||!root.isConnected)return;
          this.model=gltf.scene;
          this.processModel();
          this.createFloor();
          this.createLine();
          this.createLight();
          this.createParticles();
          if(status)status.textContent='Двигай мышью — кролик побежит. Клик — прыжок.';
          this.draw();
        },undefined,(e)=>fail(e));
      }

      createRenderer(){
        this.renderer=new THREE.WebGLRenderer({canvas:this.canvas,antialias:true,alpha:false});
        this.renderer.setClearColor(new THREE.Color(this.bgrColor));
        this.renderer.setPixelRatio(Math.min(window.devicePixelRatio||1,2));
        this.renderer.setSize(this.winWidth,this.winHeight,false);
        this.renderer.toneMapping=THREE.LinearToneMapping;
        this.renderer.toneMappingExposure=1;
        this.renderer.shadowMap.enabled=true;
        this.renderer.shadowMap.type=THREE.VSMShadowMap;
        this.renderer.localClippingEnabled=true;
      }

      createSim(){
        this.floorSimMat=new THREE.ShaderMaterial({
          uniforms:{
            inputTexture:{value:null},
            time:{value:0},
            blade1PosOld:{value:new THREE.Vector2(0.5,0.5)},
            blade1PosNew:{value:new THREE.Vector2(0.5,0.5)},
            strength:{value:0}
          },
          vertexShader:document.getElementById('bunny-sim-v').textContent,
          fragmentShader:document.getElementById('bunny-sim-f').textContent
        });
        this.bufferSim=new BufferSim(this.renderer,1024,1024,this.floorSimMat);
      }

      createMaterials(){
        this.primMat=new THREE.MeshToonMaterial({color:0x7beeff});
        this.secMat=new THREE.MeshToonMaterial({color:this.bgrColor});
        this.bonusMat=new THREE.MeshToonMaterial({color:0xff3434});
        this.outlineMat=new THREE.ShaderMaterial({
          uniforms:{
            color:{value:new THREE.Color(0x000000)},
            size:{value:0.02},
            time:{value:0}
          },
          vertexShader:document.getElementById('bunny-outline-v').textContent,
          fragmentShader:document.getElementById('bunny-outline-f').textContent,
          side:THREE.BackSide
        });
      }

      addOutline(origin){
        var outline=origin.clone();
        outline.children=[];
        outline.position.set(0,0,0);
        outline.rotation.set(0,0,0);
        outline.scale.set(1,1,1);
        outline.material=this.outlineMat;
        origin.add(outline);
      }

      processModel(){
        var get=(name)=>this.model.getObjectByName(name);
        this.rabbit=get('Rabbit');
        this.rabbitBody=get('body');
        this.earRight=get('earRight');
        this.earLeft=get('earLeft');
        this.tail=get('tail');
        this.footLeft=get('footLeft');
        this.footRight=get('footRight');
        this.eyeLeft=get('eyeLeft');
        this.eyeRight=get('eyeRight');
        this.carrot=get('carrot');
        this.carrotLeaf=get('carrotLeaf');
        this.carrotLeaf2=get('carrotLeaf2');

        if(!this.rabbit||!this.rabbitBody||!this.carrot)throw new Error('В модели не найдены основные части кролика или морковка');

        this.carrot.rotation.z=0.2;
        this.carrot.rotation.x=0.2;
        this.rabbitBody.material=this.primMat;
        this.earRight.material=this.primMat;
        this.earLeft.material=this.primMat;
        this.tail.material=this.primMat;
        this.footLeft.material=this.secMat;
        this.footRight.material=this.secMat;
        this.eyeLeft.material=this.secMat;
        this.eyeRight.material=this.secMat;
        this.carrot.material=this.bonusMat;
        this.carrotLeaf.material=this.primMat;
        this.carrotLeaf2.material=this.primMat;
        [this.rabbitBody,this.earRight,this.earLeft,this.tail,this.carrot].forEach(o=>this.addOutline(o));
        this.rabbit.traverse(o=>{if(o.isMesh){o.castShadow=true;o.receiveShadow=true;}});
        this.carrot.traverse(o=>{if(o.isMesh)o.castShadow=true;});
        this.scene.add(this.rabbit);
        this.scene.add(this.carrot);
      }

      createFloor(){
        this.floor=new Reflector(new THREE.PlaneGeometry(this.floorSize,this.floorSize),{
          color:new THREE.Color(this.bgrColor),
          textureWidth:1024,
          textureHeight:1024
        });
        this.floor.rotation.x=-Math.PI/2;
        this.floor.receiveShadow=true;
        this.modifyFloorShader();
        this.scene.add(this.floor);
      }

      modifyFloorShader(){
        var renderTarget=this.floor.getRenderTarget();
        var textureMatrix=this.floor.material.uniforms.textureMatrix;
        var uniforms=THREE.UniformsUtils.merge([
          THREE.UniformsLib.common,
          THREE.UniformsLib.shadowmap,
          THREE.UniformsLib.lights,
          this.floor.material.uniforms,
          {tScratches:{value:this.bufferSim.output.texture}}
        ]);
        this.floor.material.lights=true;
        this.floor.material.uniforms=uniforms;
        this.floor.material.uniforms.tDiffuse.value=renderTarget.texture;
        this.floor.material.uniforms.textureMatrix.value=textureMatrix.value;
        this.floor.material.vertexShader=document.getElementById('bunny-reflector-v').textContent;
        this.floor.material.fragmentShader=document.getElementById('bunny-reflector-f').textContent;
      }

      createLine(){
        var material=new THREE.LineDashedMaterial({
          color:0x7beeff,linewidth:1,scale:1,dashSize:0.2,gapSize:0.1
        });
        var geometry=new THREE.BufferGeometry().setFromPoints([
          new THREE.Vector3(0,0.2,0),
          new THREE.Vector3(3,0.2,3)
        ]);
        this.line=new THREE.Line(geometry,material);
        this.scene.add(this.line);
      }

      createParticles(){
        this.particles1=[];
        this.particles2=[];
        var geometry=new THREE.BoxGeometry(0.2,0.2,0.2);
        for(var i=0;i<20;i++){
          var a=new THREE.Mesh(geometry,this.bonusMat);
          a.scale.set(0,0,0);
          this.particles1.push(a);
          this.scene.add(a);
        }
        for(var j=0;j<5;j++){
          var b=new THREE.Mesh(geometry,this.primMat);
          b.scale.set(0,0,0);
          this.particles2.push(b);
          this.scene.add(b);
        }
      }

      createLight(){
        this.scene.add(new THREE.AmbientLight(0xffffff));
        this.light=new THREE.DirectionalLight(0xffffff,1);
        this.light.position.set(1,5,1);
        this.light.castShadow=true;
        this.light.shadow.mapSize.set(512,512);
        this.light.shadow.camera.near=0.5;
        this.light.shadow.camera.far=12;
        this.light.shadow.camera.left=-12;
        this.light.shadow.camera.right=12;
        this.light.shadow.camera.bottom=-12;
        this.light.shadow.camera.top=12;
        this.light.shadow.radius=3;
        this.light.shadow.blurSamples=4;
        this.scene.add(this.light);
      }

      createListeners(){
        this.onResize=this.onWindowResize.bind(this);
        this.onMove=this.onMouseMove.bind(this);
        this.onDown=this.onMouseDown.bind(this);
        this.onTouch=this.onTouchMove.bind(this);
        window.addEventListener('resize',this.onResize);
        this.canvas.addEventListener('mousemove',this.onMove);
        this.canvas.addEventListener('mousedown',this.onDown);
        this.canvas.addEventListener('touchstart',this.onTouch,{passive:false});
        this.canvas.addEventListener('touchmove',this.onTouch,{passive:false});
      }

      onWindowResize(){
        if(!this.root.isConnected)return;
        this.winWidth=Math.max(1,this.root.clientWidth);
        this.winHeight=Math.max(1,this.root.clientHeight);
        this.camera.aspect=this.winWidth/this.winHeight;
        this.camera.updateProjectionMatrix();
        this.renderer.setSize(this.winWidth,this.winHeight,false);
      }

      onMouseMove(e){
        var r=this.canvas.getBoundingClientRect();
        this.updateMouse(((e.clientX-r.left)/r.width)*2-1,-(((e.clientY-r.top)/r.height)*2-1));
      }

      onTouchMove(e){
        if(e.cancelable)e.preventDefault();
        if(!e.touches.length)return;
        var t=e.touches[0],r=this.canvas.getBoundingClientRect();
        this.updateMouse(((t.clientX-r.left)/r.width)*2-1,-(((t.clientY-r.top)/r.height)*2-1));
        if(e.type==='touchstart'&&this.rabbit&&!this.isJumping)this.jump();
      }

      updateMouse(x,y){
        this.mouse.set(x,y);
        if(this.floor)this.raycast();
      }

      onMouseDown(){
        if(this.rabbit&&!this.isJumping)this.jump();
      }

      raycast(){
        this.raycaster.setFromCamera(this.mouse,this.camera);
        var hits=this.raycaster.intersectObject(this.floor);
        if(hits.length){
          this.targetHeroUVPos.copy(hits[0].uv);
        }
      }

      draw(){
        if(!alive||!this.root.isConnected)return;
        this.updateGame();
        this.renderer.render(this.scene,this.camera);
        requestAnimationFrame(this.draw.bind(this));
      }

      updateGame(){
        this.dt=Math.min(this.clock.getDelta(),0.3);
        this.time+=this.dt;
        if(!this.rabbit||!this.floor)return;

        var dx=this.constrain(this.targetHeroUVPos.x-0.5,-0.3,0.3)*this.floorSize-this.rabbit.position.x;
        var dy=-this.constrain(this.targetHeroUVPos.y-0.5,-0.3,0.3)*this.floorSize-this.rabbit.position.z;
        var angle=Math.atan2(dy,dx);
        this.heroDistance=Math.sqrt(dx*dx+dy*dy);
        this.heroSpeed.x+=dx*this.dt*0.5;
        this.heroSpeed.y+=dy*this.dt*0.5;
        this.heroSpeed.x*=Math.pow(this.dt,0.005);
        this.heroSpeed.y*=Math.pow(this.dt,0.005);
        this.rabbit.position.x+=this.heroSpeed.x;
        this.rabbit.position.z+=this.heroSpeed.y;

        var targetRot=-angle+Math.PI/2;
        if(this.heroDistance>0.3)this.rabbit.rotation.y+=this.getShortestAngle(targetRot-this.rabbit.rotation.y)*3*this.dt;
        this.heroAngularSpeed=this.getShortestAngle(this.rabbit.rotation.y-this.heroOldRot);
        this.heroOldRot=this.rabbit.rotation.y;
        if(!this.isJumping)this.earLeft.rotation.x=this.earRight.rotation.x=-this.heroSpeed.length()*2;

        var p=this.line.geometry.attributes.position.array;
        p[0]=this.targetHeroAbsMousePos.x;
        p[2]=this.targetHeroAbsMousePos.y;
        p[3]=this.rabbit.position.x;
        p[4]=this.rabbit.position.y;
        p[5]=this.rabbit.position.z;
        this.line.geometry.attributes.position.needsUpdate=true;
        this.line.computeLineDistances();

        this.heroNewUVPos.set(0.5+this.rabbit.position.x/this.floorSize,0.5-this.rabbit.position.z/this.floorSize);
        this.floorSimMat.uniforms.time.value=this.time;
        this.floorSimMat.uniforms.blade1PosNew.value=this.heroNewUVPos;
        this.floorSimMat.uniforms.blade1PosOld.value=this.heroOldUVPos;
        this.floorSimMat.uniforms.strength.value=this.isJumping?0:1/(1+this.heroSpeed.length()*10);
        this.bufferSim.render();
        this.floor.material.uniforms.tScratches.value=this.bufferSim.output.texture;
        this.heroOldUVPos=this.heroNewUVPos.clone();
        this.carrot.rotation.y+=this.dt;
        this.outlineMat.uniforms.time.value=this.time;
        this.testCollision();
      }

      jump(){
        this.isJumping=true;
        var turns=Math.floor(this.heroSpeed.length()*5)+1;
        var duration=0.5+turns*0.2;
        var targetRot=this.heroAngularSpeed>0?Math.PI*2*turns:-Math.PI*2*turns;
        gsap.to(this.rabbitBody.rotation,{duration:duration,ease:'none',y:targetRot,onComplete:()=>{this.rabbitBody.rotation.y=0;}});
        gsap.to([this.earLeft.rotation,this.earRight.rotation],{duration:duration*0.8,ease:'power4.out',x:Math.PI/4});
        gsap.to([this.earLeft.rotation,this.earRight.rotation],{duration:duration*0.2,delay:duration*0.8,ease:'power4.in',x:0});
        gsap.to(this.jumpParams,{
          duration:duration*0.5,ease:'power2.out',jumpProgress:0.5,
          onUpdate:()=>{this.rabbit.position.y=Math.pow(Math.sin(this.jumpParams.jumpProgress*Math.PI),4)*turns;}
        });
        gsap.to(this.jumpParams,{
          duration:duration*0.5,ease:'power2.in',delay:duration*0.5,jumpProgress:1,
          onUpdate:()=>{this.rabbit.position.y=Math.sin(this.jumpParams.jumpProgress*Math.PI)*turns;},
          onComplete:()=>{this.rabbit.position.y=0;this.jumpParams.jumpProgress=0;this.isJumping=false;}
        });
      }

      testCollision(){
        if(this.isExploding)return;
        var d=this.rabbit.position.clone().sub(this.carrot.position);
        if(d.length()<=1){
          this.carrot.visible=false;
          this.explode(this.carrot.position.clone());
        }
      }

      explode(pos){
        this.isExploding=true;
        var all=this.particles1.concat(this.particles2);
        all.forEach((m)=>{
          m.position.copy(pos);
          m.scale.set(2,2,2);
          gsap.to(m.position,{
            x:pos.x+(-0.5+Math.random())*1.5,
            y:pos.y+(0.5+Math.random())*1.5,
            z:pos.z+(-0.5+Math.random())*1.5,
            duration:1,ease:'power4.out'
          });
          gsap.to(m.scale,{
            x:0,y:0,z:0,duration:1,ease:'power4.out',
            onComplete:()=>{if(m===all[all.length-1]){this.spawnCarrot();this.isExploding=false;}}
          });
        });
      }

      spawnCarrot(){
        var px=(Math.random()-0.5)*0.3;
        var py=(Math.random()-0.5)*0.3;
        var h=0.2+Math.random();
        this.carrot.position.set(px*this.floorSize,-1,py*this.floorSize);
        this.carrot.scale.set(0,0,0);
        this.carrot.visible=true;
        gsap.to(this.carrot.scale,{duration:1.5,ease:'elastic.out',x:1,y:1,z:1});
        gsap.to(this.carrot.position,{duration:1.5,ease:'elastic.out',y:h});
      }

      getShortestAngle(v){
        var a=v%(Math.PI*2);
        if(a<-Math.PI)a+=Math.PI*2;
        else if(a>Math.PI)a-=Math.PI*2;
        return a;
      }

      constrain(v,min,max){return Math.min(max,Math.max(min,v));}
    }

    new App();
  }).catch(fail);
})();
</script>
[/html]

0

6

[html]
<div id="bunny-scene-ru" style="position:relative;width:100%;height:460px;overflow:hidden;background:#332e2e;border:1px solid #7beeff;border-radius:8px;isolation:isolate;">
  <canvas class="bunny-webgl" style="display:block;width:100%;height:100%;outline:none;touch-action:none;"></canvas>
  <div class="bunny-status" style="position:absolute;left:10px;top:10px;color:#7beeff;font:12px monospace;z-index:2;pointer-events:none;">Загружаем кролика...</div>
  <div style="position:absolute;bottom:32px;left:0;width:100%;text-align:center;color:#ff3434;font:11px Arial,sans-serif;letter-spacing:2px;text-transform:uppercase;pointer-events:none;">Move to guide · Click to jump</div>
  <div style="position:absolute;bottom:9px;left:0;width:100%;text-align:center;color:#7beeff;font:10px Arial,sans-serif;opacity:.7;pointer-events:none;">Skating bunny · Three.js</div>
</div>

<script type="x-shader/x-vertex" id="bunny-reflector-v">
uniform mat4 textureMatrix;
varying vec4 vUvReflection;
varying vec2 vUv;
#include <common>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
void main(){
#include <beginnormal_vertex>
#include <defaultnormal_vertex>
#include <begin_vertex>
vUvReflection=textureMatrix*vec4(position,1.0);
vUv=uv;
gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);
#include <logdepthbuf_vertex>
#include <worldpos_vertex>
#include <shadowmap_vertex>
}
</script>

<script type="x-shader/x-fragment" id="bunny-reflector-f">
uniform vec3 color;
uniform sampler2D tDiffuse;
uniform sampler2D tScratches;
varying vec4 vUvReflection;
varying vec2 vUv;
#include <common>
#include <packing>
#include <lights_pars_begin>
#include <shadowmap_pars_vertex>
#include <shadowmap_pars_fragment>
#include <shadowmask_pars_fragment>
#include <logdepthbuf_pars_fragment>
vec4 blur9(sampler2D image,vec4 uv,vec2 resolution,vec2 direction){
vec4 c=vec4(0.0);
vec2 o1=vec2(1.3846153846)*direction;
vec2 o2=vec2(3.2307692308)*direction;
c+=texture2DProj(image,uv)*0.2270270270;
c+=texture2DProj(image,uv+vec4(o1/resolution,o1/resolution))*0.3162162162;
c+=texture2DProj(image,uv-vec4(o1/resolution,o1/resolution))*0.3162162162;
c+=texture2DProj(image,uv+vec4(o2/resolution,o2/resolution))*0.0702702703;
c+=texture2DProj(image,uv-vec4(o2/resolution,o2/resolution))*0.0702702703;
return c;
}
float blendOverlay(float a,float b){
return a<0.5?2.0*a*b:1.0-2.0*(1.0-a)*(1.0-b);
}
vec3 blendOverlay(vec3 a,vec3 b){
return vec3(blendOverlay(a.r,b.r),blendOverlay(a.g,b.g),blendOverlay(a.b,b.b));
}
void main(){
#include <logdepthbuf_fragment>
vec4 d=vec4(sin(vUvReflection.y*3.0)*0.05,sin(vUvReflection.x*3.0)*0.05,0.0,0.0);
vec2 r=vec2(30.0,30.0);
vec4 base=blur9(tDiffuse,vUvReflection+d,r,vec2(1.0,0.0))*0.25;
base+=blur9(tDiffuse,vUvReflection+d,r,vec2(-1.0,0.0))*0.25;
base+=blur9(tDiffuse,vUvReflection+d,r,vec2(0.0,1.0))*0.25;
base+=blur9(tDiffuse,vUvReflection+d,r,vec2(0.0,-1.0))*0.25;
vec4 scratches=texture2D(tScratches,vUv);
vec3 col=mix(color,base.rgb,0.5);
col.rgb+=scratches.r*0.02;
col.gb-=scratches.g*0.01;
col.gb-=(1.0-getShadowMask())*0.015;
gl_FragColor=vec4(col,1.0);
#include <tonemapping_fragment>
#include <colorspace_fragment>
}
</script>

<script type="x-shader/x-vertex" id="bunny-sim-v">
precision highp float;
uniform float time;
varying vec2 vUv;
void main(){
vUv=uv;
gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);
}
</script>

<script type="x-shader/x-fragment" id="bunny-sim-f">
precision highp float;
uniform sampler2D inputTexture;
uniform vec2 blade1PosOld;
uniform vec2 blade1PosNew;
uniform float strength;
uniform float time;
varying vec2 vUv;
float lineSegment(vec2 p,vec2 a,vec2 b,float thickness){
vec2 pa=p-a;
vec2 ba=b-a;
float h=clamp(dot(pa,ba)/max(dot(ba,ba),0.000001),0.0,1.0);
float d=length(pa-ba*h);
return smoothstep(thickness,0.2*thickness,d);
}
void main(){
vec4 prev=texture2D(inputTexture,vUv);
vec3 col=prev.rgb*0.999;
if(strength>0.0){
  float space=0.001;
  float crease=0.001;
  float thick=0.001+strength*0.001;
  float lr=lineSegment(vUv+vec2(space),blade1PosOld,blade1PosNew,thick);
  float lg=lineSegment(vUv+vec2(space+crease),blade1PosOld,blade1PosNew,thick);
  float rr=lineSegment(vUv-vec2(space+crease),blade1PosOld,blade1PosNew,thick);
  float rg=lineSegment(vUv-vec2(space),blade1PosOld,blade1PosNew,thick);
  col.r=clamp(col.r+(lr+rr)*strength*3.0,0.0,1.0);
  col.g=clamp(col.g+(lg+rg)*strength*3.0,0.0,1.0);
}
gl_FragColor=vec4(col,1.0);
}
</script>

<script type="x-shader/x-fragment" id="bunny-outline-f">
uniform vec3 color;
void main(){gl_FragColor=vec4(color,1.0);}
</script>

<script type="x-shader/x-vertex" id="bunny-outline-v">
uniform float size;
uniform float time;
void main(){
vec3 p=position+normal*size*(1.0+abs(sin(position.y*time*0.02)*2.0));
gl_Position=projectionMatrix*modelViewMatrix*vec4(p,1.0);
}
</script>

<script>
(function(){
  var root=document.getElementById('bunny-scene-ru');
  if(!root||root.dataset.started)return;
  root.dataset.started='1';

  var status=root.querySelector('.bunny-status');
  var canvas=root.querySelector('canvas');
  var alive=true;

  function fail(err){
    if(status)status.textContent='Ошибка: '+(err&&err.message?err.message:String(err));
    if(window.console)console.error('Skating bunny:',err);
  }

  Promise.all([
    import('https://esm.sh/three@0.156.1'),
    import('https://esm.sh/three@0.156.1/examples/jsm/loaders/GLTFLoader.js'),
    import('https://esm.sh/three@0.156.1/examples/jsm/objects/Reflector.js'),
    import('https://esm.sh/gsap')
  ]).then(function(modules){
    if(!alive||!root.isConnected)return;

    var THREE=modules[0];
    var GLTFLoader=modules[1].GLTFLoader;
    var Reflector=modules[2].Reflector;
    var gsap=modules[3].gsap||modules[3].default;

    if(!THREE||!GLTFLoader||!Reflector||!gsap){
      throw new Error('Не все модули загружены');
    }

    class BufferSim{
      constructor(renderer,width,height,shader){
        this.renderer=renderer;
        this.shader=shader;
        this.orthoScene=new THREE.Scene();

        var fbo=new THREE.WebGLRenderTarget(width,height,{
          wrapS:THREE.ClampToEdgeWrapping,
          wrapT:THREE.ClampToEdgeWrapping,
          minFilter:THREE.LinearFilter,
          magFilter:THREE.LinearFilter,
          format:THREE.RGBAFormat,
          type:THREE.HalfFloatType,
          stencilBuffer:false,
          depthBuffer:false
        });

        fbo.texture.generateMipmaps=false;
        this.fbos=[fbo,fbo.clone()];
        this.current=0;
        this.output=this.fbos[0];

        this.orthoCamera=new THREE.OrthographicCamera(
          width/-2,width/2,height/2,height/-2,0.00001,1000
        );

        this.orthoQuad=new THREE.Mesh(
          new THREE.PlaneGeometry(width,height),this.shader
        );
        this.orthoScene.add(this.orthoQuad);
      }

      render(){
        this.shader.uniforms.inputTexture.value=this.fbos[this.current].texture;
        this.current=1-this.current;
        this.output=this.fbos[this.current];

        this.renderer.setRenderTarget(this.output);
        this.renderer.render(this.orthoScene,this.orthoCamera);
        this.renderer.setRenderTarget(null);
      }
    }

    class App{
      constructor(){
        this.root=root;
        this.canvas=canvas;
        this.bgrColor=0x332e2e;
        this.floorSize=30;
        this.winWidth=Math.max(1,root.clientWidth);
        this.winHeight=Math.max(1,root.clientHeight);

        this.gltfFile='https://assets.codepen.io/264161/rabbit6.glb';
        this.clock=new THREE.Clock();
        this.time=0;

        this.rafId=0;
        this.isVisible=true;
        this.wasPaused=false;

        this.heroAngularSpeed=0;
        this.heroOldRot=0;
        this.heroDistance=0;
        this.heroOldUVPos=new THREE.Vector2(0.5,0.5);
        this.heroNewUVPos=new THREE.Vector2(0.5,0.5);
        this.heroSpeed=new THREE.Vector2(0,0);
        this.targetHeroUVPos=new THREE.Vector2(0.5,0.5);
        this.targetHeroAbsMousePos=new THREE.Vector2(0,0);

        this.raycaster=new THREE.Raycaster();
        this.mouse=new THREE.Vector2();
        this.isJumping=false;
        this.isExploding=false;
        this.jumpParams={jumpProgress:0};

        this.scene=new THREE.Scene();
        this.scene.fog=new THREE.Fog(this.bgrColor,13,20);

        this.camera=new THREE.PerspectiveCamera(
          60,this.winWidth/this.winHeight,1,100
        );
        this.camera.position.set(0,4,8);
        this.camera.lookAt(0,0,0);
        this.scene.add(this.camera);

        this.createRenderer();
        this.createSim();
        this.createMaterials();
        this.createListeners();

        new GLTFLoader().load(
          this.gltfFile,
          (gltf)=>{
            if(!alive||!root.isConnected)return;

            this.model=gltf.scene;
            this.processModel();
            this.createFloor();
            this.createLine();
            this.createLight();
            this.createParticles();

            if(status){
              status.textContent='Двигай мышью — кролик побежит. Клик — прыжок.';
            }

            this.startLoop();
          },
          undefined,
          (e)=>fail(e)
        );
      }

      createRenderer(){
        this.renderer=new THREE.WebGLRenderer({
          canvas:this.canvas,
          antialias:true,
          alpha:false
        });

        this.renderer.setClearColor(new THREE.Color(this.bgrColor));

        /* Ограничиваем нагрузку на видеокарту */
        this.renderer.setPixelRatio(
          Math.min(window.devicePixelRatio||1,1.5)
        );

        this.renderer.setSize(this.winWidth,this.winHeight,false);
        this.renderer.toneMapping=THREE.LinearToneMapping;
        this.renderer.toneMappingExposure=1;
        this.renderer.shadowMap.enabled=true;
        this.renderer.shadowMap.type=THREE.VSMShadowMap;
        this.renderer.localClippingEnabled=true;
      }

      createSim(){
        this.floorSimMat=new THREE.ShaderMaterial({
          uniforms:{
            inputTexture:{value:null},
            time:{value:0},
            blade1PosOld:{value:new THREE.Vector2(0.5,0.5)},
            blade1PosNew:{value:new THREE.Vector2(0.5,0.5)},
            strength:{value:0}
          },
          vertexShader:document.getElementById('bunny-sim-v').textContent,
          fragmentShader:document.getElementById('bunny-sim-f').textContent
        });

        /* Было 1024 × 1024; теперь 512 × 512 */
        this.bufferSim=new BufferSim(
          this.renderer,512,512,this.floorSimMat
        );
      }

      createMaterials(){
        this.primMat=new THREE.MeshToonMaterial({color:0x7beeff});
        this.secMat=new THREE.MeshToonMaterial({color:this.bgrColor});
        this.bonusMat=new THREE.MeshToonMaterial({color:0xff3434});

        this.outlineMat=new THREE.ShaderMaterial({
          uniforms:{
            color:{value:new THREE.Color(0x000000)},
            size:{value:0.02},
            time:{value:0}
          },
          vertexShader:document.getElementById('bunny-outline-v').textContent,
          fragmentShader:document.getElementById('bunny-outline-f').textContent,
          side:THREE.BackSide
        });
      }

      addOutline(origin){
        var outline=origin.clone();
        outline.children=[];
        outline.position.set(0,0,0);
        outline.rotation.set(0,0,0);
        outline.scale.set(1,1,1);
        outline.material=this.outlineMat;
        origin.add(outline);
      }

      processModel(){
        var get=(name)=>this.model.getObjectByName(name);

        this.rabbit=get('Rabbit');
        this.rabbitBody=get('body');
        this.earRight=get('earRight');
        this.earLeft=get('earLeft');
        this.tail=get('tail');
        this.footLeft=get('footLeft');
        this.footRight=get('footRight');
        this.eyeLeft=get('eyeLeft');
        this.eyeRight=get('eyeRight');
        this.carrot=get('carrot');
        this.carrotLeaf=get('carrotLeaf');
        this.carrotLeaf2=get('carrotLeaf2');

        if(!this.rabbit||!this.rabbitBody||!this.carrot){
          throw new Error('Не найдены части модели кролика или морковка');
        }

        this.carrot.rotation.z=0.2;
        this.carrot.rotation.x=0.2;

        this.rabbitBody.material=this.primMat;
        this.earRight.material=this.primMat;
        this.earLeft.material=this.primMat;
        this.tail.material=this.primMat;
        this.footLeft.material=this.secMat;
        this.footRight.material=this.secMat;
        this.eyeLeft.material=this.secMat;
        this.eyeRight.material=this.secMat;
        this.carrot.material=this.bonusMat;
        this.carrotLeaf.material=this.primMat;
        this.carrotLeaf2.material=this.primMat;

        [
          this.rabbitBody,
          this.earRight,
          this.earLeft,
          this.tail,
          this.carrot
        ].forEach(o=>this.addOutline(o));

        this.rabbit.traverse(o=>{
          if(o.isMesh){
            o.castShadow=true;
            o.receiveShadow=true;
          }
        });

        this.carrot.traverse(o=>{
          if(o.isMesh)o.castShadow=true;
        });

        this.scene.add(this.rabbit);
        this.scene.add(this.carrot);
      }

      createFloor(){
        this.floor=new Reflector(
          new THREE.PlaneGeometry(this.floorSize,this.floorSize),
          {
            color:new THREE.Color(this.bgrColor),
            textureWidth:512,
            textureHeight:512
          }
        );

        this.floor.rotation.x=-Math.PI/2;
        this.floor.receiveShadow=true;
        this.modifyFloorShader();
        this.scene.add(this.floor);
      }

      modifyFloorShader(){
        var renderTarget=this.floor.getRenderTarget();
        var textureMatrix=this.floor.material.uniforms.textureMatrix;

        var uniforms=THREE.UniformsUtils.merge([
          THREE.UniformsLib.common,
          THREE.UniformsLib.shadowmap,
          THREE.UniformsLib.lights,
          this.floor.material.uniforms,
          {tScratches:{value:this.bufferSim.output.texture}}
        ]);

        this.floor.material.lights=true;
        this.floor.material.uniforms=uniforms;
        this.floor.material.uniforms.tDiffuse.value=renderTarget.texture;
        this.floor.material.uniforms.textureMatrix.value=textureMatrix.value;
        this.floor.material.vertexShader=document.getElementById('bunny-reflector-v').textContent;
        this.floor.material.fragmentShader=document.getElementById('bunny-reflector-f').textContent;
      }

      createLine(){
        var material=new THREE.LineDashedMaterial({
          color:0x7beeff,
          linewidth:1,
          scale:1,
          dashSize:0.2,
          gapSize:0.1
        });

        var geometry=new THREE.BufferGeometry().setFromPoints([
          new THREE.Vector3(0,0.2,0),
          new THREE.Vector3(3,0.2,3)
        ]);

        this.line=new THREE.Line(geometry,material);
        this.scene.add(this.line);
      }

      createParticles(){
        this.particles1=[];
        this.particles2=[];

        var geometry=new THREE.BoxGeometry(0.2,0.2,0.2);

        for(var i=0;i<20;i++){
          var a=new THREE.Mesh(geometry,this.bonusMat);
          a.scale.set(0,0,0);
          this.particles1.push(a);
          this.scene.add(a);
        }

        for(var j=0;j<5;j++){
          var b=new THREE.Mesh(geometry,this.primMat);
          b.scale.set(0,0,0);
          this.particles2.push(b);
          this.scene.add(b);
        }
      }

      createLight(){
        this.scene.add(new THREE.AmbientLight(0xffffff));

        this.light=new THREE.DirectionalLight(0xffffff,1);
        this.light.position.set(1,5,1);
        this.light.castShadow=true;
        this.light.shadow.mapSize.set(512,512);
        this.light.shadow.camera.near=0.5;
        this.light.shadow.camera.far=12;
        this.light.shadow.camera.left=-12;
        this.light.shadow.camera.right=12;
        this.light.shadow.camera.bottom=-12;
        this.light.shadow.camera.top=12;
        this.light.shadow.radius=3;
        this.light.shadow.blurSamples=4;

        this.scene.add(this.light);
      }

      createListeners(){
        this.onResize=()=>this.onWindowResize();
        this.onMove=e=>this.onMouseMove(e);
        this.onDown=()=>this.onMouseDown();
        this.onTouch=e=>this.onTouchMove(e);

        this.onVisibilityChange=()=>{
          if(document.hidden){
            this.stopLoop();
          }else{
            this.startLoop();
          }
        };

        window.addEventListener('resize',this.onResize);
        document.addEventListener('visibilitychange',this.onVisibilityChange);

        this.canvas.addEventListener('mousemove',this.onMove);
        this.canvas.addEventListener('mousedown',this.onDown);
        this.canvas.addEventListener('touchstart',this.onTouch,{passive:false});
        this.canvas.addEventListener('touchmove',this.onTouch,{passive:false});

        if('IntersectionObserver' in window){
          this.visibilityObserver=new IntersectionObserver(entries=>{
            entries.forEach(entry=>{
              this.isVisible=entry.isIntersecting;

              if(this.isVisible&&!document.hidden){
                this.startLoop();
              }else{
                this.stopLoop();
              }
            });
          },{threshold:0.01});

          this.visibilityObserver.observe(this.root);
        }
      }

      startLoop(){
        if(!alive||!this.root.isConnected)return;
        if(!this.isVisible||document.hidden)return;
        if(this.rafId)return;

        /* Не считаем длинную паузу одним огромным кадром */
        this.clock.getDelta();
        this.rafId=requestAnimationFrame(()=>this.draw());
      }

      stopLoop(){
        if(this.rafId){
          cancelAnimationFrame(this.rafId);
          this.rafId=0;
        }

        this.wasPaused=true;
      }

      onWindowResize(){
        if(!this.root.isConnected)return;

        this.winWidth=Math.max(1,this.root.clientWidth);
        this.winHeight=Math.max(1,this.root.clientHeight);
        this.camera.aspect=this.winWidth/this.winHeight;
        this.camera.updateProjectionMatrix();
        this.renderer.setSize(this.winWidth,this.winHeight,false);
      }

      onMouseMove(e){
        var r=this.canvas.getBoundingClientRect();

        this.updateMouse(
          ((e.clientX-r.left)/r.width)*2-1,
          -(((e.clientY-r.top)/r.height)*2-1)
        );
      }

      onTouchMove(e){
        if(e.cancelable)e.preventDefault();
        if(!e.touches.length)return;

        var t=e.touches[0];
        var r=this.canvas.getBoundingClientRect();

        this.updateMouse(
          ((t.clientX-r.left)/r.width)*2-1,
          -(((t.clientY-r.top)/r.height)*2-1)
        );

        if(e.type==='touchstart'&&this.rabbit&&!this.isJumping){
          this.jump();
        }
      }

      updateMouse(x,y){
        this.mouse.set(x,y);
        if(this.floor)this.raycast();
      }

      onMouseDown(){
        if(this.rabbit&&!this.isJumping)this.jump();
      }

      raycast(){
        this.raycaster.setFromCamera(this.mouse,this.camera);
        var hits=this.raycaster.intersectObject(this.floor);

        if(hits.length){
          this.targetHeroUVPos.copy(hits[0].uv);
        }
      }

      draw(){
        this.rafId=0;

        if(!alive||!this.root.isConnected)return;
        if(!this.isVisible||document.hidden)return;

        this.updateGame();
        this.renderer.render(this.scene,this.camera);

        this.rafId=requestAnimationFrame(()=>this.draw());
      }

      updateGame(){
        this.dt=Math.min(this.clock.getDelta(),0.3);
        this.time+=this.dt;

        if(!this.rabbit||!this.floor)return;

        var dx=this.constrain(
          this.targetHeroUVPos.x-0.5,-0.3,0.3
        )*this.floorSize-this.rabbit.position.x;

        var dy=-this.constrain(
          this.targetHeroUVPos.y-0.5,-0.3,0.3
        )*this.floorSize-this.rabbit.position.z;

        var angle=Math.atan2(dy,dx);
        this.heroDistance=Math.sqrt(dx*dx+dy*dy);

        this.heroSpeed.x+=dx*this.dt*0.5;
        this.heroSpeed.y+=dy*this.dt*0.5;
        this.heroSpeed.x*=Math.pow(this.dt,0.005);
        this.heroSpeed.y*=Math.pow(this.dt,0.005);

        this.rabbit.position.x+=this.heroSpeed.x;
        this.rabbit.position.z+=this.heroSpeed.y;

        var targetRot=-angle+Math.PI/2;

        if(this.heroDistance>0.3){
          this.rabbit.rotation.y+=this.getShortestAngle(
            targetRot-this.rabbit.rotation.y
          )*3*this.dt;
        }

        this.heroAngularSpeed=this.getShortestAngle(
          this.rabbit.rotation.y-this.heroOldRot
        );
        this.heroOldRot=this.rabbit.rotation.y;

        if(!this.isJumping){
          this.earLeft.rotation.x=this.earRight.rotation.x=
            -this.heroSpeed.length()*2;
        }

        var p=this.line.geometry.attributes.position.array;
        p[0]=this.targetHeroAbsMousePos.x;
        p[2]=this.targetHeroAbsMousePos.y;
        p[3]=this.rabbit.position.x;
        p[4]=this.rabbit.position.y;
        p[5]=this.rabbit.position.z;

        this.line.geometry.attributes.position.needsUpdate=true;
        this.line.computeLineDistances();

        this.heroNewUVPos.set(
          0.5+this.rabbit.position.x/this.floorSize,
          0.5-this.rabbit.position.z/this.floorSize
        );

        this.floorSimMat.uniforms.time.value=this.time;
        this.floorSimMat.uniforms.blade1PosNew.value=this.heroNewUVPos;
        this.floorSimMat.uniforms.blade1PosOld.value=this.heroOldUVPos;
        this.floorSimMat.uniforms.strength.value=
          this.isJumping?0:1/(1+this.heroSpeed.length()*10);

        this.bufferSim.render();
        this.floor.material.uniforms.tScratches.value=
          this.bufferSim.output.texture;

        this.heroOldUVPos=this.heroNewUVPos.clone();
        this.carrot.rotation.y+=this.dt;
        this.outlineMat.uniforms.time.value=this.time;

        this.testCollision();
      }

      jump(){
        this.isJumping=true;

        var turns=Math.floor(this.heroSpeed.length()*5)+1;
        var duration=0.5+turns*0.2;
        var targetRot=this.heroAngularSpeed>0?
          Math.PI*2*turns:-Math.PI*2*turns;

        gsap.to(this.rabbitBody.rotation,{
          duration:duration,
          ease:'none',
          y:targetRot,
          onComplete:()=>{this.rabbitBody.rotation.y=0;}
        });

        gsap.to([this.earLeft.rotation,this.earRight.rotation],{
          duration:duration*0.8,
          ease:'power4.out',
          x:Math.PI/4
        });

        gsap.to([this.earLeft.rotation,this.earRight.rotation],{
          duration:duration*0.2,
          delay:duration*0.8,
          ease:'power4.in',
          x:0
        });

        gsap.to(this.jumpParams,{
          duration:duration*0.5,
          ease:'power2.out',
          jumpProgress:0.5,
          onUpdate:()=>{
            this.rabbit.position.y=
              Math.pow(Math.sin(this.jumpParams.jumpProgress*Math.PI),4)*turns;
          }
        });

        gsap.to(this.jumpParams,{
          duration:duration*0.5,
          ease:'power2.in',
          delay:duration*0.5,
          jumpProgress:1,
          onUpdate:()=>{
            this.rabbit.position.y=
              Math.sin(this.jumpParams.jumpProgress*Math.PI)*turns;
          },
          onComplete:()=>{
            this.rabbit.position.y=0;
            this.jumpParams.jumpProgress=0;
            this.isJumping=false;
          }
        });
      }

      testCollision(){
        if(this.isExploding)return;

        var d=this.rabbit.position.clone().sub(this.carrot.position);

        if(d.length()<=1){
          this.carrot.visible=false;
          this.explode(this.carrot.position.clone());
        }
      }

      explode(pos){
        this.isExploding=true;
        var all=this.particles1.concat(this.particles2);

        all.forEach((m,index)=>{
          m.position.copy(pos);
          m.scale.set(2,2,2);

          gsap.to(m.position,{
            x:pos.x+(-0.5+Math.random())*1.5,
            y:pos.y+(0.5+Math.random())*1.5,
            z:pos.z+(-0.5+Math.random())*1.5,
            duration:1,
            ease:'power4.out'
          });

          gsap.to(m.scale,{
            x:0,y:0,z:0,
            duration:1,
            ease:'power4.out',
            onComplete:()=>{
              if(index===all.length-1){
                this.spawnCarrot();
                this.isExploding=false;
              }
            }
          });
        });
      }

      spawnCarrot(){
        var px=(Math.random()-0.5)*0.3;
        var py=(Math.random()-0.5)*0.3;
        var h=0.2+Math.random();

        this.carrot.position.set(
          px*this.floorSize,-1,py*this.floorSize
        );
        this.carrot.scale.set(0,0,0);
        this.carrot.visible=true;

        gsap.to(this.carrot.scale,{
          duration:1.5,
          ease:'elastic.out',
          x:1,y:1,z:1
        });

        gsap.to(this.carrot.position,{
          duration:1.5,
          ease:'elastic.out',
          y:h
        });
      }

      getShortestAngle(v){
        var a=v%(Math.PI*2);
        if(a<-Math.PI)a+=Math.PI*2;
        else if(a>Math.PI)a-=Math.PI*2;
        return a;
      }

      constrain(v,min,max){
        return Math.min(max,Math.max(min,v));
      }
    }

    new App();
  }).catch(fail);
})();
</script>
[/html]

0

7

[html]
<div id="bunny-scene-ru" style="position:relative;width:100%;height:460px;overflow:hidden;background:#332e2e;border:1px solid #7beeff;border-radius:8px;isolation:isolate;">
  <canvas class="bunny-webgl" style="display:block;width:100%;height:100%;outline:none;touch-action:none;"></canvas>
  <div class="bunny-status" style="position:absolute;left:10px;top:10px;color:#7beeff;font:12px monospace;z-index:2;pointer-events:none;">погоди ща всё будет 3..2..1.. хоп</div>
  <div style="position:absolute;bottom:32px;left:0;width:100%;text-align:center;color:#ff3434;font:11px Arial,sans-serif;letter-spacing:2px;text-transform:uppercase;pointer-events:none;">банни настолько любит юну что готов доедать за ней корочки от пиццы ах</div>
  <div style="position:absolute;bottom:9px;left:0;width:100%;text-align:center;color:#7beeff;font:10px Arial,sans-serif;opacity:.7;pointer-events:none;">а ещё он любит когда она улыбается</div>
</div>

<script type="x-shader/x-vertex" id="bunny-reflector-v">
uniform mat4 textureMatrix;
varying vec4 vUvReflection;
varying vec2 vUv;
#include <common>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
void main(){
  #include <beginnormal_vertex>
  #include <defaultnormal_vertex>
  #include <begin_vertex>
  vUvReflection=textureMatrix*vec4(position,1.0);
  vUv=uv;
  gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);
  #include <logdepthbuf_vertex>
  #include <worldpos_vertex>
  #include <shadowmap_vertex>
}
</script>

<script type="x-shader/x-fragment" id="bunny-reflector-f">
uniform vec3 color;
uniform sampler2D tDiffuse;
uniform sampler2D tScratches;
varying vec4 vUvReflection;
varying vec2 vUv;
#include <common>
#include <packing>
#include <lights_pars_begin>
#include <shadowmap_pars_vertex>
#include <shadowmap_pars_fragment>
#include <shadowmask_pars_fragment>
#include <logdepthbuf_pars_fragment>
vec4 blur9(sampler2D image,vec4 uv,vec2 resolution,vec2 direction){
  vec4 c=vec4(0.0);
  vec2 o1=vec2(1.3846153846)*direction;
  vec2 o2=vec2(3.2307692308)*direction;
  c+=texture2DProj(image,uv)*0.2270270270;
  c+=texture2DProj(image,uv+vec4(o1/resolution,o1/resolution))*0.3162162162;
  c+=texture2DProj(image,uv-vec4(o1/resolution,o1/resolution))*0.3162162162;
  c+=texture2DProj(image,uv+vec4(o2/resolution,o2/resolution))*0.0702702703;
  c+=texture2DProj(image,uv-vec4(o2/resolution,o2/resolution))*0.0702702703;
  return c;
}
float blendOverlay(float a,float b){
  return a<0.5?2.0*a*b:1.0-2.0*(1.0-a)*(1.0-b);
}
vec3 blendOverlay(vec3 a,vec3 b){
  return vec3(blendOverlay(a.r,b.r),blendOverlay(a.g,b.g),blendOverlay(a.b,b.b));
}
void main(){
  #include <logdepthbuf_fragment>
  vec4 d=vec4(sin(vUvReflection.y*3.0)*0.05,sin(vUvReflection.x*3.0)*0.05,0.0,0.0);
  vec2 r=vec2(30.0,30.0);
  vec4 base=blur9(tDiffuse,vUvReflection+d,r,vec2(1.0,0.0))*0.25;
  base+=blur9(tDiffuse,vUvReflection+d,r,vec2(-1.0,0.0))*0.25;
  base+=blur9(tDiffuse,vUvReflection+d,r,vec2(0.0,1.0))*0.25;
  base+=blur9(tDiffuse,vUvReflection+d,r,vec2(0.0,-1.0))*0.25;
  vec4 scratches=texture2D(tScratches,vUv);
  vec3 col=mix(color,base.rgb,0.5);
  col.rgb+=scratches.r*0.02;
  col.gb-=scratches.g*0.01;
  col.gb-=(1.0-getShadowMask())*0.015;
  gl_FragColor=vec4(col,1.0);
  #include <tonemapping_fragment>
  #include <colorspace_fragment>
}
</script>

<script type="x-shader/x-vertex" id="bunny-sim-v">
precision highp float;
uniform float time;
varying vec2 vUv;
void main(){
  vUv=uv;
  gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);
}
</script>

<script type="x-shader/x-fragment" id="bunny-sim-f">
precision highp float;
uniform sampler2D inputTexture;
uniform vec2 blade1PosOld;
uniform vec2 blade1PosNew;
uniform float strength;
uniform float time;
varying vec2 vUv;
float lineSegment(vec2 p,vec2 a,vec2 b,float thickness){
  vec2 pa=p-a;
  vec2 ba=b-a;
  float h=clamp(dot(pa,ba)/max(dot(ba,ba),0.000001),0.0,1.0);
  float d=length(pa-ba*h);
  return smoothstep(thickness,0.2*thickness,d);
}
void main(){
  vec4 prev=texture2D(inputTexture,vUv);
  vec3 col=prev.rgb*0.999;
  if(strength>0.0){
    float space=0.001;
    float crease=0.001;
    float thick=0.001+strength*0.001;
    float lr=lineSegment(vUv+vec2(space),blade1PosOld,blade1PosNew,thick);
    float lg=lineSegment(vUv+vec2(space+crease),blade1PosOld,blade1PosNew,thick);
    float rr=lineSegment(vUv-vec2(space+crease),blade1PosOld,blade1PosNew,thick);
    float rg=lineSegment(vUv-vec2(space),blade1PosOld,blade1PosNew,thick);
    col.r=clamp(col.r+(lr+rr)*strength*3.0,0.0,1.0);
    col.g=clamp(col.g+(lg+rg)*strength*3.0,0.0,1.0);
  }
  gl_FragColor=vec4(col,1.0);
}
</script>

<script type="x-shader/x-fragment" id="bunny-outline-f">
uniform vec3 color;
void main(){gl_FragColor=vec4(color,1.0);}
</script>

<script type="x-shader/x-vertex" id="bunny-outline-v">
uniform float size;
uniform float time;
void main(){
  vec3 p=position+normal*size*(1.0+abs(sin(position.y*time*0.02)*2.0));
  gl_Position=projectionMatrix*modelViewMatrix*vec4(p,1.0);
}
</script>

<script>
(function(){
  var root=document.getElementById('bunny-scene-ru');
  if(!root||root.dataset.started)return;
  root.dataset.started='1';

  var status=root.querySelector('.bunny-status');
  var canvas=root.querySelector('canvas');
  var alive=true;

  function fail(err){
    if(status)status.textContent='Ошибка: '+(err&&err.message?err.message:String(err));
    if(window.console)console.error('Skating bunny:',err);
  }

  Promise.all([
    import('https://esm.sh/three@0.156.1'),
    import('https://esm.sh/three@0.156.1/examples/jsm/loaders/GLTFLoader.js'),
    import('https://esm.sh/three@0.156.1/examples/jsm/objects/Reflector.js'),
    import('https://esm.sh/gsap')
  ]).then(function(modules){
    if(!alive||!root.isConnected)return;

    var THREE=modules[0];
    var GLTFLoader=modules[1].GLTFLoader;
    var Reflector=modules[2].Reflector;
    var gsap=modules[3].gsap||modules[3].default;

    if(!THREE||!GLTFLoader||!Reflector||!gsap){
      throw new Error('Не все модули загружены');
    }

    class BufferSim{
      constructor(renderer,width,height,shader){
        this.renderer=renderer;
        this.shader=shader;
        this.orthoScene=new THREE.Scene();

        var fbo=new THREE.WebGLRenderTarget(width,height,{
          wrapS:THREE.ClampToEdgeWrapping,
          wrapT:THREE.ClampToEdgeWrapping,
          minFilter:THREE.LinearFilter,
          magFilter:THREE.LinearFilter,
          format:THREE.RGBAFormat,
          type:THREE.HalfFloatType,
          stencilBuffer:false,
          depthBuffer:false
        });

        fbo.texture.generateMipmaps=false;
        this.fbos=[fbo,fbo.clone()];
        this.current=0;
        this.output=this.fbos[0];

        this.orthoCamera=new THREE.OrthographicCamera(
          width/-2,width/2,height/2,height/-2,0.00001,1000
        );

        this.orthoQuad=new THREE.Mesh(
          new THREE.PlaneGeometry(width,height),this.shader
        );
        this.orthoScene.add(this.orthoQuad);
      }

      render(){
        this.shader.uniforms.inputTexture.value=this.fbos[this.current].texture;
        this.current=1-this.current;
        this.output=this.fbos[this.current];

        this.renderer.setRenderTarget(this.output);
        this.renderer.render(this.orthoScene,this.orthoCamera);
        this.renderer.setRenderTarget(null);
      }
    }

    class App{
      constructor(){
        this.root=root;
        this.canvas=canvas;
        this.bgrColor=0x332e2e;
        this.floorSize=30;
        this.winWidth=Math.max(1,root.clientWidth);
        this.winHeight=Math.max(1,root.clientHeight);

        this.gltfFile='https://assets.codepen.io/264161/rabbit6.glb';
        this.clock=new THREE.Clock();
        this.time=0;

        this.rafId=0;
        this.isVisible=true;
        this.wasPaused=false;

        this.heroAngularSpeed=0;
        this.heroOldRot=0;
        this.heroDistance=0;
        this.heroOldUVPos=new THREE.Vector2(0.5,0.5);
        this.heroNewUVPos=new THREE.Vector2(0.5,0.5);
        this.heroSpeed=new THREE.Vector2(0,0);
        this.targetHeroUVPos=new THREE.Vector2(0.5,0.5);
        this.targetHeroAbsMousePos=new THREE.Vector2(0,0);

        this.raycaster=new THREE.Raycaster();
        this.mouse=new THREE.Vector2();
        this.isJumping=false;
        this.isExploding=false;
        this.jumpParams={jumpProgress:0};

        this.scene=new THREE.Scene();
        this.scene.fog=new THREE.Fog(this.bgrColor,13,20);

        this.camera=new THREE.PerspectiveCamera(
          60,this.winWidth/this.winHeight,1,100
        );
        this.camera.position.set(0,4,8);
        this.camera.lookAt(0,0,0);
        this.scene.add(this.camera);

        this.createRenderer();
        this.createSim();
        this.createMaterials();
        this.createListeners();

        new GLTFLoader().load(
          this.gltfFile,
          (gltf)=>{
            if(!alive||!root.isConnected)return;

            this.model=gltf.scene;
            this.processModel();
            this.createFloor();
            this.createLine();
            this.createLight();
            this.createParticles();

            if(status){
              status.textContent='помоги банни собрать всю юну он кстати может прыгать по клику мышки';
            }

            this.startLoop();
          },
          undefined,
          (e)=>fail(e)
        );
      }

      createRenderer(){
        this.renderer=new THREE.WebGLRenderer({
          canvas:this.canvas,
          antialias:true,
          alpha:false
        });

        this.renderer.setClearColor(new THREE.Color(this.bgrColor));

        this.renderer.setPixelRatio(
          Math.min(window.devicePixelRatio||1,1.5)
        );

        this.renderer.setSize(this.winWidth,this.winHeight,false);
        this.renderer.toneMapping=THREE.LinearToneMapping;
        this.renderer.toneMappingExposure=1;
        this.renderer.shadowMap.enabled=true;
        this.renderer.shadowMap.type=THREE.VSMShadowMap;
        this.renderer.localClippingEnabled=true;
      }

      createSim(){
        this.floorSimMat=new THREE.ShaderMaterial({
          uniforms:{
            inputTexture:{value:null},
            time:{value:0},
            blade1PosOld:{value:new THREE.Vector2(0.5,0.5)},
            blade1PosNew:{value:new THREE.Vector2(0.5,0.5)},
            strength:{value:0}
          },
          vertexShader:document.getElementById('bunny-sim-v').textContent,
          fragmentShader:document.getElementById('bunny-sim-f').textContent
        });

        this.bufferSim=new BufferSim(
          this.renderer,512,512,this.floorSimMat
        );
      }

      createMaterials(){
        this.primMat=new THREE.MeshToonMaterial({color:0x7beeff});
        this.secMat=new THREE.MeshToonMaterial({color:this.bgrColor});
        this.bonusMat=new THREE.MeshToonMaterial({color:0xff3434});

        this.outlineMat=new THREE.ShaderMaterial({
          uniforms:{
            color:{value:new THREE.Color(0x000000)},
            size:{value:0.02},
            time:{value:0}
          },
          vertexShader:document.getElementById('bunny-outline-v').textContent,
          fragmentShader:document.getElementById('bunny-outline-f').textContent,
          side:THREE.BackSide
        });
      }

      addOutline(origin){
        var outline=origin.clone();
        outline.children=[];
        outline.position.set(0,0,0);
        outline.rotation.set(0,0,0);
        outline.scale.set(1,1,1);
        outline.material=this.outlineMat;
        origin.add(outline);
      }

      processModel(){
        var get=(name)=>this.model.getObjectByName(name);

        this.rabbit=get('Rabbit');
        this.rabbitBody=get('body');
        this.earRight=get('earRight');
        this.earLeft=get('earLeft');
        this.tail=get('tail');
        this.footLeft=get('footLeft');
        this.footRight=get('footRight');
        this.eyeLeft=get('eyeLeft');
        this.eyeRight=get('eyeRight');
        this.carrot=get('carrot');
        this.carrotLeaf=get('carrotLeaf');
        this.carrotLeaf2=get('carrotLeaf2');

        if(!this.rabbit||!this.rabbitBody||!this.carrot){
          throw new Error('Не найдены части модели кролика или морковка');
        }

        this.carrot.rotation.z=0.2;
        this.carrot.rotation.x=0.2;

        this.rabbitBody.material=this.primMat;
        this.earRight.material=this.primMat;
        this.earLeft.material=this.primMat;
        this.tail.material=this.primMat;
        this.footLeft.material=this.secMat;
        this.footRight.material=this.secMat;
        this.eyeLeft.material=this.secMat;
        this.eyeRight.material=this.secMat;
        this.carrot.material=this.bonusMat;
        this.carrotLeaf.material=this.primMat;
        this.carrotLeaf2.material=this.primMat;

        [
          this.rabbitBody,
          this.earRight,
          this.earLeft,
          this.tail,
          this.carrot
        ].forEach(o=>this.addOutline(o));

        this.rabbit.traverse(o=>{
          if(o.isMesh){
            o.castShadow=true;
            o.receiveShadow=true;
          }
        });

        this.carrot.traverse(o=>{
          if(o.isMesh)o.castShadow=true;
        });

        this.scene.add(this.rabbit);
        this.scene.add(this.carrot);
      }

      createFloor(){
        this.floor=new Reflector(
          new THREE.PlaneGeometry(this.floorSize,this.floorSize),
          {
            color:new THREE.Color(this.bgrColor),
            textureWidth:512,
            textureHeight:512
          }
        );

        this.floor.rotation.x=-Math.PI/2;
        this.floor.receiveShadow=true;
        this.modifyFloorShader();
        this.scene.add(this.floor);
      }

      modifyFloorShader(){
        var renderTarget=this.floor.getRenderTarget();
        var textureMatrix=this.floor.material.uniforms.textureMatrix;

        var uniforms=THREE.UniformsUtils.merge([
          THREE.UniformsLib.common,
          THREE.UniformsLib.shadowmap,
          THREE.UniformsLib.lights,
          this.floor.material.uniforms,
          {tScratches:{value:this.bufferSim.output.texture}}
        ]);

        this.floor.material.lights=true;
        this.floor.material.uniforms=uniforms;
        this.floor.material.uniforms.tDiffuse.value=renderTarget.texture;
        this.floor.material.uniforms.textureMatrix.value=textureMatrix.value;
        this.floor.material.vertexShader=document.getElementById('bunny-reflector-v').textContent;
        this.floor.material.fragmentShader=document.getElementById('bunny-reflector-f').textContent;
      }

      createLine(){
        var material=new THREE.LineDashedMaterial({
          color:0x7beeff,
          linewidth:1,
          scale:1,
          dashSize:0.2,
          gapSize:0.1
        });

        var geometry=new THREE.BufferGeometry().setFromPoints([
          new THREE.Vector3(0,0.2,0),
          new THREE.Vector3(3,0.2,3)
        ]);

        this.line=new THREE.Line(geometry,material);
        this.scene.add(this.line);
      }

      createParticles(){
        this.particles1=[];
        this.particles2=[];

        var geometry=new THREE.BoxGeometry(0.2,0.2,0.2);

        for(var i=0;i<20;i++){
          var a=new THREE.Mesh(geometry,this.bonusMat);
          a.scale.set(0,0,0);
          this.particles1.push(a);
          this.scene.add(a);
        }

        for(var j=0;j<5;j++){
          var b=new THREE.Mesh(geometry,this.primMat);
          b.scale.set(0,0,0);
          this.particles2.push(b);
          this.scene.add(b);
        }

        this.carrotLabel=this.createCarrotLabel('любимая Юна');
        this.scene.add(this.carrotLabel);
      }

      createCarrotLabel(text){
        var labelCanvas=document.createElement('canvas');
        labelCanvas.width=512;
        labelCanvas.height=128;

        var ctx=labelCanvas.getContext('2d');
        ctx.clearRect(0,0,512,128);
        ctx.font='bold 66px Arial';
        ctx.textAlign='center';
        ctx.textBaseline='middle';
        ctx.lineJoin='round';

        ctx.strokeStyle='#171717';
        ctx.lineWidth=12;
        ctx.strokeText(text,256,64);

        ctx.fillStyle='#7beeff';
        ctx.fillText(text,256,64);

        var texture=new THREE.CanvasTexture(labelCanvas);
        texture.colorSpace=THREE.SRGBColorSpace;

        var material=new THREE.SpriteMaterial({
          map:texture,
          transparent:true,
          depthTest:false
        });

        var sprite=new THREE.Sprite(material);
        sprite.scale.set(1.65,0.42,1);
        sprite.renderOrder=999;

        return sprite;
      }

      createLight(){
        this.scene.add(new THREE.AmbientLight(0xffffff));

        this.light=new THREE.DirectionalLight(0xffffff,1);
        this.light.position.set(1,5,1);
        this.light.castShadow=true;
        this.light.shadow.mapSize.set(512,512);
        this.light.shadow.camera.near=0.5;
        this.light.shadow.camera.far=12;
        this.light.shadow.camera.left=-12;
        this.light.shadow.camera.right=12;
        this.light.shadow.camera.bottom=-12;
        this.light.shadow.camera.top=12;
        this.light.shadow.radius=3;
        this.light.shadow.blurSamples=4;

        this.scene.add(this.light);
      }

      createListeners(){
        this.onResize=()=>this.onWindowResize();
        this.onMove=e=>this.onMouseMove(e);
        this.onDown=()=>this.onMouseDown();
        this.onTouch=e=>this.onTouchMove(e);

        this.onVisibilityChange=()=>{
          if(document.hidden){
            this.stopLoop();
          }else{
            this.startLoop();
          }
        };

        window.addEventListener('resize',this.onResize);
        document.addEventListener('visibilitychange',this.onVisibilityChange);

        this.canvas.addEventListener('mousemove',this.onMove);
        this.canvas.addEventListener('mousedown',this.onDown);
        this.canvas.addEventListener('touchstart',this.onTouch,{passive:false});
        this.canvas.addEventListener('touchmove',this.onTouch,{passive:false});

        if('IntersectionObserver' in window){
          this.visibilityObserver=new IntersectionObserver(entries=>{
            entries.forEach(entry=>{
              this.isVisible=entry.isIntersecting;

              if(this.isVisible&&!document.hidden){
                this.startLoop();
              }else{
                this.stopLoop();
              }
            });
          },{threshold:0.01});

          this.visibilityObserver.observe(this.root);
        }
      }

      startLoop(){
        if(!alive||!this.root.isConnected)return;
        if(!this.isVisible||document.hidden)return;
        if(this.rafId)return;

        this.clock.getDelta();
        this.rafId=requestAnimationFrame(()=>this.draw());
      }

      stopLoop(){
        if(this.rafId){
          cancelAnimationFrame(this.rafId);
          this.rafId=0;
        }

        this.wasPaused=true;
      }

      onWindowResize(){
        if(!this.root.isConnected)return;

        this.winWidth=Math.max(1,this.root.clientWidth);
        this.winHeight=Math.max(1,this.root.clientHeight);
        this.camera.aspect=this.winWidth/this.winHeight;
        this.camera.updateProjectionMatrix();
        this.renderer.setSize(this.winWidth,this.winHeight,false);
      }

      onMouseMove(e){
        var r=this.canvas.getBoundingClientRect();

        this.updateMouse(
          ((e.clientX-r.left)/r.width)*2-1,
          -(((e.clientY-r.top)/r.height)*2-1)
        );
      }

      onTouchMove(e){
        if(e.cancelable)e.preventDefault();
        if(!e.touches.length)return;

        var t=e.touches[0];
        var r=this.canvas.getBoundingClientRect();

        this.updateMouse(
          ((t.clientX-r.left)/r.width)*2-1,
          -(((t.clientY-r.top)/r.height)*2-1)
        );

        if(e.type==='touchstart'&&this.rabbit&&!this.isJumping){
          this.jump();
        }
      }

      updateMouse(x,y){
        this.mouse.set(x,y);
        if(this.floor)this.raycast();
      }

      onMouseDown(){
        if(this.rabbit&&!this.isJumping)this.jump();
      }

      raycast(){
        this.raycaster.setFromCamera(this.mouse,this.camera);
        var hits=this.raycaster.intersectObject(this.floor);

        if(hits.length){
          this.targetHeroUVPos.copy(hits[0].uv);
        }
      }

      draw(){
        this.rafId=0;

        if(!alive||!this.root.isConnected)return;
        if(!this.isVisible||document.hidden)return;

        this.updateGame();
        this.renderer.render(this.scene,this.camera);

        this.rafId=requestAnimationFrame(()=>this.draw());
      }

      updateGame(){
        this.dt=Math.min(this.clock.getDelta(),0.3);
        this.time+=this.dt;

        if(!this.rabbit||!this.floor)return;

        var dx=this.constrain(
          this.targetHeroUVPos.x-0.5,-0.3,0.3
        )*this.floorSize-this.rabbit.position.x;

        var dy=-this.constrain(
          this.targetHeroUVPos.y-0.5,-0.3,0.3
        )*this.floorSize-this.rabbit.position.z;

        var angle=Math.atan2(dy,dx);
        this.heroDistance=Math.sqrt(dx*dx+dy*dy);

        this.heroSpeed.x+=dx*this.dt*0.5;
        this.heroSpeed.y+=dy*this.dt*0.5;
        this.heroSpeed.x*=Math.pow(this.dt,0.005);
        this.heroSpeed.y*=Math.pow(this.dt,0.005);

        this.rabbit.position.x+=this.heroSpeed.x;
        this.rabbit.position.z+=this.heroSpeed.y;

        var targetRot=-angle+Math.PI/2;

        if(this.heroDistance>0.3){
          this.rabbit.rotation.y+=this.getShortestAngle(
            targetRot-this.rabbit.rotation.y
          )*3*this.dt;
        }

        this.heroAngularSpeed=this.getShortestAngle(
          this.rabbit.rotation.y-this.heroOldRot
        );
        this.heroOldRot=this.rabbit.rotation.y;

        if(!this.isJumping){
          this.earLeft.rotation.x=this.earRight.rotation.x=
            -this.heroSpeed.length()*2;
        }

        var p=this.line.geometry.attributes.position.array;
        p[0]=this.targetHeroAbsMousePos.x;
        p[2]=this.targetHeroAbsMousePos.y;
        p[3]=this.rabbit.position.x;
        p[4]=this.rabbit.position.y;
        p[5]=this.rabbit.position.z;

        this.line.geometry.attributes.position.needsUpdate=true;
        this.line.computeLineDistances();

        this.heroNewUVPos.set(
          0.5+this.rabbit.position.x/this.floorSize,
          0.5-this.rabbit.position.z/this.floorSize
        );

        this.floorSimMat.uniforms.time.value=this.time;
        this.floorSimMat.uniforms.blade1PosNew.value=this.heroNewUVPos;
        this.floorSimMat.uniforms.blade1PosOld.value=this.heroOldUVPos;
        this.floorSimMat.uniforms.strength.value=
          this.isJumping?0:1/(1+this.heroSpeed.length()*10);

        this.bufferSim.render();
        this.floor.material.uniforms.tScratches.value=
          this.bufferSim.output.texture;

        this.heroOldUVPos=this.heroNewUVPos.clone();
        this.carrot.rotation.y+=this.dt;

        if(this.carrotLabel){
          this.carrotLabel.position.set(
            this.carrot.position.x,
            this.carrot.position.y+1.15,
            this.carrot.position.z
          );
          this.carrotLabel.visible=this.carrot.visible;
        }

        this.outlineMat.uniforms.time.value=this.time;

        this.testCollision();
      }

      jump(){
        this.isJumping=true;

        var turns=Math.floor(this.heroSpeed.length()*5)+1;
        var duration=0.5+turns*0.2;
        var targetRot=this.heroAngularSpeed>0?
          Math.PI*2*turns:-Math.PI*2*turns;

        gsap.to(this.rabbitBody.rotation,{
          duration:duration,
          ease:'none',
          y:targetRot,
          onComplete:()=>{this.rabbitBody.rotation.y=0;}
        });

        gsap.to([this.earLeft.rotation,this.earRight.rotation],{
          duration:duration*0.8,
          ease:'power4.out',
          x:Math.PI/4
        });

        gsap.to([this.earLeft.rotation,this.earRight.rotation],{
          duration:duration*0.2,
          delay:duration*0.8,
          ease:'power4.in',
          x:0
        });

        gsap.to(this.jumpParams,{
          duration:duration*0.5,
          ease:'power2.out',
          jumpProgress:0.5,
          onUpdate:()=>{
            this.rabbit.position.y=
              Math.pow(Math.sin(this.jumpParams.jumpProgress*Math.PI),4)*turns;
          }
        });

        gsap.to(this.jumpParams,{
          duration:duration*0.5,
          ease:'power2.in',
          delay:duration*0.5,
          jumpProgress:1,
          onUpdate:()=>{
            this.rabbit.position.y=
              Math.sin(this.jumpParams.jumpProgress*Math.PI)*turns;
          },
          onComplete:()=>{
            this.rabbit.position.y=0;
            this.jumpParams.jumpProgress=0;
            this.isJumping=false;
          }
        });
      }

      testCollision(){
        if(this.isExploding)return;

        var d=this.rabbit.position.clone().sub(this.carrot.position);

        if(d.length()<=1){
          this.carrot.visible=false;
          this.explode(this.carrot.position.clone());
        }
      }

      explode(pos){
        this.isExploding=true;
        var all=this.particles1.concat(this.particles2);

        all.forEach((m,index)=>{
          m.position.copy(pos);
          m.scale.set(2,2,2);

          gsap.to(m.position,{
            x:pos.x+(-0.5+Math.random())*1.5,
            y:pos.y+(0.5+Math.random())*1.5,
            z:pos.z+(-0.5+Math.random())*1.5,
            duration:1,
            ease:'power4.out'
          });

          gsap.to(m.scale,{
            x:0,y:0,z:0,
            duration:1,
            ease:'power4.out',
            onComplete:()=>{
              if(index===all.length-1){
                this.spawnCarrot();
                this.isExploding=false;
              }
            }
          });
        });
      }

      spawnCarrot(){
        var px=(Math.random()-0.5)*0.3;
        var py=(Math.random()-0.5)*0.3;
        var h=0.2+Math.random();

        this.carrot.position.set(
          px*this.floorSize,-1,py*this.floorSize
        );
        this.carrot.scale.set(0,0,0);
        this.carrot.visible=true;

        gsap.to(this.carrot.scale,{
          duration:1.5,
          ease:'elastic.out',
          x:1,y:1,z:1
        });

        gsap.to(this.carrot.position,{
          duration:1.5,
          ease:'elastic.out',
          y:h
        });
      }

      getShortestAngle(v){
        var a=v%(Math.PI*2);
        if(a<-Math.PI)a+=Math.PI*2;
        else if(a>Math.PI)a-=Math.PI*2;
        return a;
      }

      constrain(v,min,max){
        return Math.min(max,Math.max(min,v));
      }
    }

    new App();
  }).catch(fail);
})();
</script>
[/html]

0

Быстрый ответ

Напишите ваше сообщение и нажмите «Отправить»



Вы здесь » Test forum » Новый форум » free


Рейтинг форумов | Создать форум бесплатно