Spaces:
Sleeping

File size: 2,472 Bytes
d091b2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import {Scene,Group,AmbientLight,DirectionalLight,OrthographicCamera,Color,Vector3} from 'three';
import {SVGRenderer} from 'three/examples/jsm/renderers/SVGRenderer.js';
import {makeObject,viewSize,initialRotation} from './studio-object.js';

export function mountStudy(host,label){
  const scene=new Scene();
  const group=new Group();
  makeObject(group);
  group.rotation.y=initialRotation;
  scene.add(group,new AmbientLight(0xffffff,1.55));
  const light=new DirectionalLight(0xfff3dd,2.25);light.position.set(-4,7,6);scene.add(light);
  const camera=new OrthographicCamera(-3,3,2,-2,.1,100);
  camera.position.set(4,3.1,6);camera.lookAt(new Vector3(0,.03,0));
  const renderer=new SVGRenderer();
  renderer.setQuality('high');renderer.setClearColor(new Color('#fff'),0);
  const svg=renderer.domElement;svg.dataset.engine='three';svg.setAttribute('aria-hidden','true');
  host.appendChild(svg);
  const render=()=>{
    const {width,height}=host.getBoundingClientRect();if(width<1||height<1)return;
    const aspect=width/height,halfHeight=Math.max(viewSize,viewSize*1.4/aspect);
    camera.left=-halfHeight*aspect;camera.right=halfHeight*aspect;camera.top=halfHeight;camera.bottom=-halfHeight;camera.updateProjectionMatrix();
    renderer.setSize(width,height);renderer.render(scene,camera);svg.style.backgroundColor='transparent';
    svg.dataset.angle=group.rotation.y.toFixed(2);
  };
  const turn=dir=>{group.rotation.y+=dir*Math.PI/7;render();};
  let pointer=null;
  const start=e=>{if(!e.isPrimary || e.button!==0)return;pointer={id:e.pointerId,x:e.clientX,rotation:group.rotation.y};};
  const move=e=>{if(pointer?.id!==e.pointerId)return;const delta=e.clientX-pointer.x;if(Math.abs(delta)>4){if(!host.hasPointerCapture(e.pointerId))host.setPointerCapture(e.pointerId);group.rotation.y=pointer.rotation+delta*.015;render();}};
  const end=()=>{pointer=null;};
  const events={pointerdown:start,pointermove:move,pointerup:end,pointercancel:end,pointerleave:e=>{if(!host.hasPointerCapture(e.pointerId))end();}};
  for(const [name,fn] of Object.entries(events))host.addEventListener(name,fn);
  const observer=new ResizeObserver(render);observer.observe(host);render();
  return {turn,reset:()=>{group.rotation.y=initialRotation;render();},dispose(){
    observer.disconnect();for(const [name,fn] of Object.entries(events))host.removeEventListener(name,fn);
    scene.traverse(item=>{item.geometry?.dispose();item.material?.dispose();});svg.remove();
  }};
}