useThree.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. import * as THREE from 'three';
  2. import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader.js';
  3. // 导入轨道控制器
  4. import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
  5. import { CSS3DRenderer } from 'three/examples/jsm/renderers/CSS3DRenderer.js';
  6. // import gsap from 'gsap';
  7. import ResourceTracker from '/@/utils/threejs/ResourceTracker.js';
  8. import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
  9. import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js';
  10. import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js';
  11. import { FXAAShader } from 'three/examples/jsm/shaders/FXAAShader.js';
  12. import { ShaderPass } from 'three/examples/jsm/postprocessing/ShaderPass.js';
  13. import { setModalCenter } from '/@/utils/threejs/util';
  14. import Stats from 'three/examples/jsm/libs/stats.module.js';
  15. import { useModelStore } from '/@/store/modules/threejs';
  16. class UseThree {
  17. stats: Stats | null = null; // 帧
  18. canvasContainer: HTMLCanvasElement | null; //canvas 容器
  19. CSSCanvasContainer: HTMLCanvasElement | null = null; // css canvas 容器
  20. camera: THREE.PerspectiveCamera | null = null; // 相机
  21. scene: THREE.Scene | null = null;
  22. renderer: THREE.WebGLRenderer | null = null;
  23. css3dRender: CSS3DRenderer | null = null;
  24. orbitControls: OrbitControls | null = null;
  25. animationAction: THREE.AnimationAction | null = null;
  26. clock: THREE.Clock | null = new THREE.Clock(); // 计时器
  27. timeoutId: NodeJS.Timeout | null = null;
  28. animationId = 0;
  29. spriteText: THREE.Sprite | null = null;
  30. mouse = new THREE.Vector2();
  31. rayCaster: THREE.Raycaster | null = null;
  32. animations: THREE.AnimationClip[] = [];
  33. mixers: THREE.AnimationMixer[] = [];
  34. FPS = 40;
  35. timeS = 0;
  36. resourceTracker: ResourceTracker | null = null;
  37. track: any = null;
  38. composer; //后期
  39. constructor(canvasSelector, cssCanvas?) {
  40. this.resourceTracker = new ResourceTracker();
  41. this.track = this.resourceTracker.track.bind(this.resourceTracker);
  42. this.animationId = 0;
  43. this.canvasContainer = document.querySelector(canvasSelector);
  44. //初始化
  45. this.init(cssCanvas);
  46. // this.animate();
  47. window.addEventListener('resize', this.resizeRenderer.bind(this));
  48. // 添加滚动事件,鼠标滚动模型执行动画
  49. // window.addEventListener('wheel', this.wheelRenderer.bind(this));
  50. }
  51. init(cssCanvas?) {
  52. // 初始化场景
  53. this.initScene();
  54. // 初始化环境光
  55. // this.initLight();
  56. // 初始化相机
  57. this.initCamera();
  58. //初始化渲染器
  59. this.initRenderer();
  60. // 初始化控制器
  61. this.initControles();
  62. if (cssCanvas) {
  63. this.initCSSRenderer(cssCanvas);
  64. }
  65. // this.setTestPlane();
  66. this.rayCaster = this.track(new THREE.Raycaster());
  67. this.createStats();
  68. // this.removeSawtooth();
  69. }
  70. createStats() {
  71. this.stats = Stats();
  72. this.stats?.setMode(0);
  73. this.stats.domElement.style.position = 'absolute';
  74. this.stats.domElement.style.left = '200px';
  75. this.stats.domElement.style.top = '100px';
  76. document.body.appendChild(this.stats.domElement);
  77. }
  78. initScene() {
  79. this.scene = this.track(new THREE.Scene());
  80. // const axesHelper = new THREE.AxesHelper(100);
  81. // this.scene?.add(axesHelper);
  82. // const size = 1000;
  83. // const divisions = 10;
  84. // const gridHelper = new THREE.GridHelper(size, divisions);
  85. // this.scene?.add(gridHelper);
  86. }
  87. initLight() {
  88. const light = this.track(new THREE.AmbientLight(0xffffff, 1));
  89. light.position.set(0, 1000, 1000);
  90. (this.scene as THREE.Scene).add(light);
  91. }
  92. initCamera() {
  93. this.camera = this.track(new THREE.PerspectiveCamera(50, this.canvasContainer.clientWidth / this.canvasContainer.clientHeight, 0.000001, 10000));
  94. // const helper = new THREE.CameraHelper(this.camera);
  95. // this.scene?.add(helper);
  96. }
  97. initRenderer() {
  98. this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, logarithmicDepthBuffer: true }) as THREE.WebGLRenderer;
  99. // 设置屏幕像素比
  100. this.renderer?.setPixelRatio(window.devicePixelRatio);
  101. // 设置渲染的尺寸
  102. this.renderer?.setSize(this.canvasContainer.clientWidth, this.canvasContainer.clientHeight);
  103. // 色调映射
  104. this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
  105. this.renderer.outputEncoding = THREE.sRGBEncoding;
  106. this.renderer.shadowMap.enabled = true;
  107. // this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  108. // 曝光程度
  109. this.renderer.toneMappingExposure = 1;
  110. this.canvasContainer?.appendChild(this.renderer.domElement);
  111. }
  112. initCSSRenderer(cssCanvas) {
  113. this.CSSCanvasContainer = document.querySelector(cssCanvas);
  114. this.css3dRender = this.track(new CSS3DRenderer()) as CSS3DRenderer;
  115. this.css3dRender.setSize(this.canvasContainer.clientWidth, this.canvasContainer.clientHeight);
  116. this.CSSCanvasContainer?.appendChild(this.css3dRender.domElement);
  117. this.css3dRender.render(this.scene as THREE.Scene, this.camera as THREE.PerspectiveCamera);
  118. this.orbitControls = this.track(new OrbitControls(this.camera as THREE.Camera, this.css3dRender?.domElement)) as OrbitControls;
  119. this.orbitControls.update();
  120. }
  121. initControles() {
  122. this.orbitControls = this.track(new OrbitControls(this.camera as THREE.Camera, this.renderer?.domElement)) as OrbitControls;
  123. // this.orbitControls.enableDamping = true;
  124. }
  125. setModel(modalName) {
  126. const modelStore = useModelStore();
  127. return new Promise(async (resolve, reject) => {
  128. try {
  129. const a = new Date().getTime();
  130. let modalValue = modelStore.modelArr.get(modalName);
  131. if (!modalValue) {
  132. const db = window['CustomDB'];
  133. const modalArr = await db.modal.where('modalName').equals(modalName).toArray();
  134. modalValue = modalArr[0].modalVal;
  135. }
  136. if (modalValue) {
  137. console.log('模型下载速度', new Date().getTime() - a);
  138. const b = new Date().getTime();
  139. try {
  140. const gltfLoader = this.track(new GLTFLoader());
  141. const dracoLoader = this.track(new DRACOLoader());
  142. dracoLoader.setDecoderPath('/model/draco/gltf/');
  143. dracoLoader.setDecoderConfig({ type: 'js' }); //使用兼容性强的draco_decoder.js解码器
  144. dracoLoader.preload();
  145. gltfLoader.setDRACOLoader(dracoLoader);
  146. gltfLoader.setPath('/model/glft/');
  147. gltfLoader.parse(
  148. modalValue,
  149. '/model/glft/',
  150. (gltf) => {
  151. const object = this.track(gltf.scene);
  152. setModalCenter(object);
  153. object.traverse((obj) => {
  154. if (obj instanceof THREE.Mesh) {
  155. obj.material.emissiveIntensity = 1;
  156. obj.material.emissiveMap = obj.material.map;
  157. obj.material.blending = THREE.CustomBlending;
  158. // if (obj.name !== 'buxiugangse') {
  159. // obj.receiveShadow = true;
  160. // }
  161. // obj.castShadow = true;
  162. }
  163. });
  164. object.name = modalName;
  165. console.log('模型渲染时间', object, new Date().getTime() - b);
  166. resolve(gltf);
  167. dracoLoader.dispose();
  168. },
  169. (err) => {
  170. console.log(err);
  171. }
  172. );
  173. } catch (error) {
  174. console.log(error);
  175. }
  176. }
  177. } catch (error) {
  178. reject('加载模型出错');
  179. }
  180. });
  181. }
  182. setTestPlane() {
  183. const plane = this.track(new THREE.Mesh(new THREE.PlaneGeometry(10, 10), new THREE.MeshPhongMaterial({ color: 0x999999, specular: 0x101010 })));
  184. plane.rotation.x = -Math.PI / 2;
  185. plane.position.y = 0.03;
  186. plane.receiveShadow = true;
  187. this.scene?.add(plane);
  188. }
  189. removeSawtooth() {
  190. this.composer = this.track(new EffectComposer(this.renderer as THREE.WebGLRenderer));
  191. const FXAAShaderPass = this.track(new ShaderPass(FXAAShader));
  192. FXAAShaderPass.uniforms['resolution'].value.set(1 / this.canvasContainer.clientWidth, 1 / this.canvasContainer.clientHeight);
  193. FXAAShaderPass.renderToScreen = true;
  194. this.composer.addPass(FXAAShaderPass);
  195. }
  196. /* 场景环境背景 */
  197. setEnvMap(hdr) {
  198. const pmremGenerator = new THREE.PMREMGenerator(this.renderer as THREE.WebGLRenderer); // 使用hdr作为背景色
  199. pmremGenerator.compileEquirectangularShader();
  200. this.track(new THREE.TextureLoader())
  201. .setPath('/model/hdr/')
  202. .load(hdr + '.jpeg', (texture) => {
  203. texture.mapping = THREE.EquirectangularReflectionMapping;
  204. const envMap = pmremGenerator.fromEquirectangular(texture).texture;
  205. (this.scene as THREE.Scene).environment = envMap;
  206. pmremGenerator.dispose();
  207. });
  208. }
  209. render() {
  210. this.stats?.update();
  211. this.startAnimation();
  212. this.orbitControls?.update();
  213. this.camera?.updateMatrixWorld();
  214. // this.composer?.render();
  215. // this.css3dRender?.render(this.scene as THREE.Scene, this.camera as THREE.PerspectiveCamera)
  216. this.renderer?.render(this.scene as THREE.Object3D, this.camera as THREE.Camera);
  217. }
  218. /* 漫游 */
  219. startMY() {}
  220. /* 初始动画 */
  221. startAnimation() {}
  222. animate() {
  223. if (this.animationId != -1) {
  224. setTimeout(() => {
  225. this.animationId = requestAnimationFrame(this.animate.bind(this));
  226. }, 1000 / 30);
  227. this.render();
  228. }
  229. }
  230. resizeRenderer() {
  231. // 更新相机比例
  232. (this.camera as THREE.PerspectiveCamera).aspect = this.canvasContainer.clientWidth / this.canvasContainer.clientHeight;
  233. // 刷新相机矩阵
  234. this.camera?.updateProjectionMatrix();
  235. // 设置场景尺寸
  236. this.renderer?.setSize(this.canvasContainer.clientWidth, this.canvasContainer.clientHeight);
  237. // this.css3dRender?.setSize(this.canvasContainer.clientWidth, this.canvasContainer.clientHeight);
  238. }
  239. wheelRenderer(e: WheelEvent) {
  240. const timeScale = e.deltaY > 0 ? 1 : -1;
  241. this.animationAction?.setEffectiveTimeScale(timeScale);
  242. (this.animationAction as THREE.AnimationAction).paused = false;
  243. this.animationAction?.play();
  244. if (this.timeoutId) {
  245. clearTimeout(this.timeoutId);
  246. }
  247. this.timeoutId = setTimeout(() => {
  248. this.animationAction?.halt(0.5);
  249. }, 500);
  250. }
  251. deleteModal() {
  252. try {
  253. const gl = this.renderer?.domElement?.getContext('webgl');
  254. gl && gl.getExtension('WEBGL_lose_context')?.loseContext();
  255. const gl1 = this.css3dRender?.domElement?.getContext('webgl');
  256. gl1 && gl1.getExtension('WEBGL_lose_context')?.loseContext();
  257. this.renderer?.forceContextLoss();
  258. this.renderer?.dispose();
  259. if (this.renderer) this.renderer.domElement = null;
  260. this.renderer = null;
  261. this.resourceTracker && this.resourceTracker.dispose();
  262. if (this.canvasContainer) this.canvasContainer.innerHTML = '';
  263. this.canvasContainer = null;
  264. this.orbitControls = null;
  265. this.css3dRender = null;
  266. this.camera = null;
  267. this.clock = null;
  268. cancelAnimationFrame(this.animationId);
  269. this.animationId = -1;
  270. this.scene = null;
  271. this.mixers = [];
  272. console.log('销毁场景', this.scene);
  273. } catch (error) {
  274. console.log(error);
  275. }
  276. THREE.Cache.clear();
  277. console.log('3D环境已清理干净');
  278. }
  279. deleteModal1() {
  280. this.scene?.children.forEach((obj) => {
  281. if (obj.type === 'Group') {
  282. obj.traverse(function (item) {
  283. if (item.type === 'Mesh') {
  284. item.geometry.dispose();
  285. item.material.dispose();
  286. !!item.clear && item.clear();
  287. }
  288. });
  289. } else if (obj.material) {
  290. obj.material.dispose();
  291. } else if (obj.geometry) {
  292. obj.geometry.dispose();
  293. }
  294. this.scene?.remove(obj);
  295. !!obj.clear ?? obj.clear();
  296. obj = null;
  297. });
  298. const gl = this.renderer?.domElement.getContext('webgl');
  299. gl && gl.getExtension('WEBGL_lose_context')?.loseContext();
  300. this.renderer?.forceContextLoss();
  301. this.renderer?.dispose();
  302. this.camera = null;
  303. this.orbitControls = null;
  304. if (this.renderer) this.renderer.domElement = null;
  305. this.renderer = null;
  306. if (this.css3dRender) this.css3dRender.domElement = null;
  307. this.css3dRender = null;
  308. if (this.canvasContainer) this.canvasContainer.innerHTML = '';
  309. if (this.CSSCanvasContainer) this.CSSCanvasContainer.innerHTML = '';
  310. this.resourceTracker && this.resourceTracker.dispose();
  311. !!this.scene?.clear ?? this.scene?.clear();
  312. cancelAnimationFrame(this.animationId);
  313. this.animationId = -1;
  314. this.stats = null;
  315. this.scene = null;
  316. THREE.Cache.clear();
  317. }
  318. }
  319. export default UseThree;