1
0

viewer.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. import * as THREE from "three";
  2. import { Model } from "./model";
  3. import { loadVRMAnimation } from "@/lib/VRMAnimation/loadVRMAnimation";
  4. import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
  5. /**
  6. * three.jsを使った3Dビューワー
  7. *
  8. * setup()でcanvasを渡してから使う
  9. */
  10. export class Viewer {
  11. public isReady: boolean;
  12. public model?: Model;
  13. public _renderer?: THREE.WebGLRenderer;
  14. private _clock: THREE.Clock;
  15. private _scene: THREE.Scene;
  16. public _camera?: THREE.PerspectiveCamera;
  17. private _cameraControls?: OrbitControls;
  18. private _raycaster?: THREE.Raycaster;
  19. private _mouse?: THREE.Vector2;
  20. private sendScreenshotToCallback: boolean;
  21. private screenshotCallback: BlobCallback | undefined;
  22. constructor() {
  23. this.isReady = false;
  24. this.sendScreenshotToCallback = false;
  25. this.screenshotCallback = undefined;
  26. // scene
  27. const scene = new THREE.Scene();
  28. this._scene = scene;
  29. // light
  30. const directionalLight = new THREE.DirectionalLight(0xffffff, 1.2);
  31. directionalLight.position.set(1.0, 1.0, 1.0).normalize();
  32. scene.add(directionalLight);
  33. const ambientLight = new THREE.AmbientLight(0xffffff, 0.8);
  34. scene.add(ambientLight);
  35. // animate
  36. this._clock = new THREE.Clock();
  37. this._clock.start();
  38. }
  39. public loadVrm(url: string) {
  40. if (this.model?.vrm) {
  41. this.unloadVRM();
  42. }
  43. // gltf and vrm
  44. this.model = new Model(this._camera || new THREE.Object3D());
  45. return this.model.loadVRM(url).then(async () => {
  46. if (!this.model?.vrm) return;
  47. // Disable frustum culling
  48. this.model.vrm.scene.traverse((obj) => {
  49. obj.frustumCulled = false;
  50. });
  51. this._scene.add(this.model.vrm.scene);
  52. const animation = await loadVRMAnimation("/animations/idle_loop.vrma")
  53. if (animation) this.model.loadAnimation(animation);
  54. // HACK: アニメーションの原点がずれているので再生後にカメラ位置を調整する
  55. requestAnimationFrame(() => {
  56. this.resetCamera();
  57. });
  58. });
  59. }
  60. public unloadVRM(): void {
  61. if (this.model?.vrm) {
  62. this._scene.remove(this.model.vrm.scene);
  63. this.model?.unLoadVrm();
  64. }
  65. }
  66. /**
  67. * Reactで管理しているCanvasを後から設定する
  68. */
  69. public setup(canvas: HTMLCanvasElement) {
  70. const parentElement = canvas.parentElement;
  71. const width = parentElement?.clientWidth || canvas.width;
  72. const height = parentElement?.clientHeight || canvas.height;
  73. // renderer
  74. this._renderer = new THREE.WebGLRenderer({
  75. canvas: canvas,
  76. alpha: true,
  77. antialias: true,
  78. });
  79. this._renderer.outputColorSpace = THREE.SRGBColorSpace;
  80. this._renderer.setSize(width, height);
  81. this._renderer.setPixelRatio(window.devicePixelRatio);
  82. // camera
  83. this._camera = new THREE.PerspectiveCamera(20.0, width / height, 0.1, 20.0);
  84. this._camera.position.set(0, 1.3, 1.5);
  85. this._cameraControls?.target.set(0, 1.3, 0);
  86. this._cameraControls?.update();
  87. // camera controls
  88. this._cameraControls = new OrbitControls(
  89. this._camera,
  90. this._renderer.domElement
  91. );
  92. this._cameraControls.screenSpacePanning = true;
  93. this._cameraControls.minDistance = 0.5;
  94. this._cameraControls.maxDistance = 4;
  95. this._cameraControls.update();
  96. // raycaster and mouse
  97. this._raycaster = new THREE.Raycaster();
  98. this._mouse = new THREE.Vector2();
  99. window.addEventListener("resize", () => {
  100. this.resize();
  101. });
  102. this.isReady = true;
  103. this.update();
  104. }
  105. /**
  106. * canvasの親要素を参照してサイズを変更する
  107. */
  108. public resize() {
  109. if (!this._renderer) return;
  110. const parentElement = this._renderer.domElement.parentElement;
  111. if (!parentElement) return;
  112. this._renderer.setPixelRatio(window.devicePixelRatio);
  113. this._renderer.setSize(
  114. parentElement.clientWidth,
  115. parentElement.clientHeight
  116. );
  117. if (!this._camera) return;
  118. this._camera.aspect =
  119. parentElement.clientWidth / parentElement.clientHeight;
  120. this._camera.updateProjectionMatrix();
  121. }
  122. public resizeChatMode(on: boolean){
  123. if (!this._renderer) return;
  124. const parentElement = this._renderer.domElement.parentElement;
  125. if (!parentElement) return;
  126. this._renderer.setPixelRatio(window.devicePixelRatio);
  127. let width = parentElement.clientWidth;
  128. let height = parentElement.clientHeight;
  129. if (on) {width = width/2; height = height/2; }
  130. this._renderer.setSize(
  131. width,
  132. height
  133. );
  134. if (!this._camera) return;
  135. this._camera.aspect =
  136. parentElement.clientWidth / parentElement.clientHeight;
  137. this._camera.updateProjectionMatrix();
  138. }
  139. /**
  140. * VRMのheadノードを参照してカメラ位置を調整する
  141. */
  142. public resetCamera() {
  143. const headNode = this.model?.vrm?.humanoid.getNormalizedBoneNode("head");
  144. if (headNode) {
  145. const headWPos = headNode.getWorldPosition(new THREE.Vector3());
  146. this._camera?.position.set(
  147. this._camera.position.x,
  148. headWPos.y,
  149. this._camera.position.z
  150. );
  151. this._cameraControls?.target.set(headWPos.x, headWPos.y, headWPos.z);
  152. this._cameraControls?.update();
  153. }
  154. }
  155. public resetCameraLerp() {
  156. // y = 1.3 is from initial setup position of camera
  157. const newPosition = new THREE.Vector3(
  158. this._camera?.position.x,
  159. 1.3,
  160. this._camera?.position.z
  161. );
  162. this._camera?.position.lerpVectors(this._camera?.position,newPosition,0);
  163. // this._cameraControls?.target.lerpVectors(this._cameraControls?.target,headWPos,0.5);
  164. // this._cameraControls?.update();
  165. }
  166. public update = () => {
  167. requestAnimationFrame(this.update);
  168. const delta = this._clock.getDelta();
  169. // update vrm components
  170. if (this.model) {
  171. this.model.update(delta);
  172. }
  173. if (this._renderer && this._camera) {
  174. this._renderer.render(this._scene, this._camera);
  175. if (this.sendScreenshotToCallback && this.screenshotCallback) {
  176. this._renderer.domElement.toBlob(this.screenshotCallback, "image/jpeg");
  177. this.sendScreenshotToCallback = false;
  178. }
  179. }
  180. };
  181. public onMouseClick(event: MouseEvent): boolean {
  182. if (!this._renderer || !this._camera || !this.model?.vrm) return false;
  183. const rect = this._renderer.domElement.getBoundingClientRect();
  184. // calculate mouse position in normalized device coordinates
  185. this._mouse!.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
  186. this._mouse!.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
  187. // update the picking ray with the camera and mouse position
  188. this._raycaster!.setFromCamera(this._mouse!, this._camera);
  189. // calculate objects intersecting the picking ray
  190. const intersects = this._raycaster!.intersectObject(this.model.vrm.scene, true);
  191. if (intersects.length > 0) {
  192. return true;
  193. }
  194. return false;
  195. }
  196. public getScreenshotBlob = (callback: BlobCallback) => {
  197. this.screenshotCallback = callback;
  198. this.sendScreenshotToCallback = true;
  199. };
  200. }