scene.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. function texture_geometry(coords) {
  2. const geometry = new THREE.BufferGeometry();
  3. const nI = coords[0].length;
  4. const nJ = coords.length;
  5. const vertices = [];
  6. const indices = [];
  7. const uvs = [];
  8. for (let j = 0; j < nJ; ++j) {
  9. for (let i = 0; i < nI; ++i) {
  10. const XYZ = coords[j][i] || [0, 0, 0];
  11. vertices.push(...XYZ);
  12. uvs.push(i / (nI - 1), j / (nJ - 1));
  13. }
  14. }
  15. for (let j = 0; j < nJ - 1; ++j) {
  16. for (let i = 0; i < nI - 1; ++i) {
  17. if (coords[j][i] && coords[j][i + 1] && coords[j + 1][i] && coords[j + 1][i + 1]) {
  18. const idx00 = i + j * nI;
  19. const idx10 = i + j * nI + 1;
  20. const idx01 = i + j * nI + nI;
  21. const idx11 = i + j * nI + 1 + nI;
  22. indices.push(idx10, idx00, idx01);
  23. indices.push(idx11, idx10, idx01);
  24. }
  25. }
  26. }
  27. geometry.setIndex(new THREE.Uint32BufferAttribute(indices, 1));
  28. geometry.setAttribute("position", new THREE.Float32BufferAttribute(vertices, 3));
  29. geometry.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2));
  30. geometry.computeVertexNormals();
  31. geometry.computeFaceNormals();
  32. return geometry;
  33. }
  34. function texture_material(texture) {
  35. texture.flipY = false;
  36. texture.minFilter = THREE.LinearFilter;
  37. return new THREE.MeshLambertMaterial({
  38. map: texture,
  39. side: THREE.DoubleSide,
  40. });
  41. }
  42. export default {
  43. template: `
  44. <div style="position:relative">
  45. <canvas style="position:relative"></canvas>
  46. <div style="position:absolute;pointer-events:none;top:0"></div>
  47. <div style="position:absolute;pointer-events:none;top:0"></div>
  48. </div>`,
  49. mounted() {
  50. this.scene = new THREE.Scene();
  51. this.objects = new Map();
  52. this.objects.set("scene", this.scene);
  53. this.look_at = new THREE.Vector3(0, 0, 0);
  54. this.camera = new THREE.PerspectiveCamera(75, this.width / this.height, 0.1, 1000);
  55. this.camera.lookAt(this.look_at);
  56. this.camera.up = new THREE.Vector3(0, 0, 1);
  57. this.camera.position.set(0, -3, 5);
  58. this.scene.add(new THREE.AmbientLight(0xffffff, 0.7));
  59. const light = new THREE.DirectionalLight(0xffffff, 0.3);
  60. light.position.set(5, 10, 40);
  61. this.scene.add(light);
  62. const renderer = new THREE.WebGLRenderer({
  63. antialias: true,
  64. alpha: true,
  65. canvas: this.$el.children[0],
  66. });
  67. renderer.setClearColor("#eee");
  68. renderer.setSize(this.width, this.height);
  69. const text_renderer = new THREE.CSS2DRenderer({
  70. element: this.$el.children[1],
  71. });
  72. text_renderer.setSize(this.width, this.height);
  73. const text3d_renderer = new THREE.CSS3DRenderer({
  74. element: this.$el.children[2],
  75. });
  76. text3d_renderer.setSize(this.width, this.height);
  77. const ground = new THREE.Mesh(new THREE.PlaneGeometry(100, 100), new THREE.MeshPhongMaterial({ color: "#eee" }));
  78. ground.translateZ(-0.01);
  79. ground.object_id = "ground";
  80. this.scene.add(ground);
  81. const grid = new THREE.GridHelper(100, 100);
  82. grid.material.transparent = true;
  83. grid.material.opacity = 0.2;
  84. grid.rotateX(Math.PI / 2);
  85. this.scene.add(grid);
  86. new THREE.OrbitControls(this.camera, renderer.domElement);
  87. const render = () => {
  88. requestAnimationFrame(() => setTimeout(() => render(), 1000 / 20));
  89. TWEEN.update();
  90. renderer.render(this.scene, this.camera);
  91. text_renderer.render(this.scene, this.camera);
  92. text3d_renderer.render(this.scene, this.camera);
  93. };
  94. render();
  95. const raycaster = new THREE.Raycaster();
  96. const click_handler = (mouseEvent) => {
  97. let x = (mouseEvent.offsetX / renderer.domElement.width) * 2 - 1;
  98. let y = -(mouseEvent.offsetY / renderer.domElement.height) * 2 + 1;
  99. raycaster.setFromCamera({ x: x, y: y }, this.camera);
  100. this.$emit("click", {
  101. hits: raycaster
  102. .intersectObjects(this.scene.children, true)
  103. .filter((o) => o.object.object_id)
  104. .map((o) => ({
  105. object_id: o.object.object_id,
  106. point: o.point,
  107. })),
  108. click_type: mouseEvent.type,
  109. shift_key: mouseEvent.shiftKey,
  110. });
  111. };
  112. this.$el.onclick = click_handler;
  113. this.$el.ondblclick = click_handler;
  114. this.texture_loader = new THREE.TextureLoader();
  115. this.stl_loader = new THREE.STLLoader();
  116. this.is_initialized = false;
  117. const sendConnectEvent = () => {
  118. if (!this.is_initialized) this.$emit("connect");
  119. else clearInterval(connectInterval);
  120. };
  121. const connectInterval = setInterval(sendConnectEvent, 100);
  122. },
  123. methods: {
  124. init() {
  125. this.is_initialized = true;
  126. },
  127. create(type, id, parent_id, ...args) {
  128. let mesh;
  129. if (type == "group") {
  130. mesh = new THREE.Group();
  131. } else if (type == "line") {
  132. const start = new THREE.Vector3(...args[0]);
  133. const end = new THREE.Vector3(...args[1]);
  134. const geometry = new THREE.BufferGeometry().setFromPoints([start, end]);
  135. const material = new THREE.LineBasicMaterial({ transparent: true });
  136. mesh = new THREE.Line(geometry, material);
  137. } else if (type == "curve") {
  138. const curve = new THREE.CubicBezierCurve3(
  139. new THREE.Vector3(...args[0]),
  140. new THREE.Vector3(...args[1]),
  141. new THREE.Vector3(...args[2]),
  142. new THREE.Vector3(...args[3])
  143. );
  144. const points = curve.getPoints(args[4] - 1);
  145. const geometry = new THREE.BufferGeometry().setFromPoints(points);
  146. const material = new THREE.LineBasicMaterial({ transparent: true });
  147. mesh = new THREE.Line(geometry, material);
  148. } else if (type == "text") {
  149. const div = document.createElement("div");
  150. div.textContent = args[0];
  151. div.style.cssText = args[1];
  152. mesh = new THREE.CSS2DObject(div);
  153. } else if (type == "text3d") {
  154. const div = document.createElement("div");
  155. div.textContent = args[0];
  156. div.style.cssText = "userSelect:none;" + args[1];
  157. mesh = new THREE.CSS3DObject(div);
  158. } else if (type == "texture") {
  159. const url = args[0];
  160. const coords = args[1];
  161. const geometry = texture_geometry(coords);
  162. const material = texture_material(this.texture_loader.load(url));
  163. mesh = new THREE.Mesh(geometry, material);
  164. } else if (type == "spot_light") {
  165. mesh = new THREE.Group();
  166. const light = new THREE.SpotLight(...args);
  167. light.position.set(0, 0, 0);
  168. light.target = new THREE.Object3D();
  169. light.target.position.set(1, 0, 0);
  170. mesh.add(light);
  171. mesh.add(light.target);
  172. } else {
  173. let geometry;
  174. const wireframe = args.pop();
  175. if (type == "box") geometry = new THREE.BoxGeometry(...args);
  176. if (type == "sphere") geometry = new THREE.SphereGeometry(...args);
  177. if (type == "cylinder") geometry = new THREE.CylinderGeometry(...args);
  178. if (type == "ring") geometry = new THREE.RingGeometry(...args);
  179. if (type == "quadratic_bezier_tube") {
  180. const curve = new THREE.QuadraticBezierCurve3(
  181. new THREE.Vector3(...args[0]),
  182. new THREE.Vector3(...args[1]),
  183. new THREE.Vector3(...args[2])
  184. );
  185. geometry = new THREE.TubeGeometry(curve, ...args.slice(3));
  186. }
  187. if (type == "extrusion") {
  188. const shape = new THREE.Shape();
  189. const outline = args[0];
  190. const height = args[1];
  191. shape.autoClose = true;
  192. shape.moveTo(outline[0][0], outline[0][1]);
  193. outline.slice(1).forEach((p) => shape.lineTo(p[0], p[1]));
  194. const settings = { depth: height, bevelEnabled: false };
  195. geometry = new THREE.ExtrudeGeometry(shape, settings);
  196. }
  197. if (type == "stl") {
  198. const url = args[0];
  199. geometry = new THREE.BufferGeometry();
  200. this.stl_loader.load(url, (geometry) => (mesh.geometry = geometry));
  201. }
  202. let material;
  203. if (wireframe) {
  204. mesh = new THREE.LineSegments(
  205. new THREE.EdgesGeometry(geometry),
  206. new THREE.LineBasicMaterial({ transparent: true })
  207. );
  208. } else {
  209. material = new THREE.MeshPhongMaterial({ transparent: true });
  210. mesh = new THREE.Mesh(geometry, material);
  211. }
  212. }
  213. mesh.object_id = id;
  214. this.objects.set(id, mesh);
  215. this.objects.get(parent_id).add(this.objects.get(id));
  216. },
  217. material(object_id, color, opacity, side) {
  218. const material = this.objects.get(object_id).material;
  219. if (!material) return;
  220. material.color.set(color);
  221. material.opacity = opacity;
  222. if (side == "front") material.side = THREE.FrontSide;
  223. else if (side == "back") material.side = THREE.BackSide;
  224. else material.side = THREE.DoubleSide;
  225. },
  226. move(object_id, x, y, z) {
  227. this.objects.get(object_id).position.set(x, y, z);
  228. },
  229. scale(object_id, sx, sy, sz) {
  230. this.objects.get(object_id).scale.set(sx, sy, sz);
  231. },
  232. rotate(object_id, R) {
  233. const R4 = new THREE.Matrix4().makeBasis(
  234. new THREE.Vector3(...R[0]),
  235. new THREE.Vector3(...R[1]),
  236. new THREE.Vector3(...R[2])
  237. );
  238. this.objects.get(object_id).rotation.setFromRotationMatrix(R4.transpose());
  239. },
  240. visible(object_id, value) {
  241. this.objects.get(object_id).visible = value;
  242. },
  243. delete(object_id) {
  244. this.objects.get(object_id).removeFromParent();
  245. this.objects.delete(object_id);
  246. },
  247. set_texture_url(object_id, url) {
  248. const obj = this.objects.get(object_id);
  249. if (obj.busy) return;
  250. obj.busy = true;
  251. const on_success = (texture) => {
  252. obj.material = texture_material(texture);
  253. obj.busy = false;
  254. };
  255. const on_error = () => (obj.busy = false);
  256. this.texture_loader.load(url, on_success, undefined, on_error);
  257. },
  258. set_texture_coordinates(object_id, coords) {
  259. this.objects.get(object_id).geometry = texture_geometry(coords);
  260. },
  261. move_camera(x, y, z, look_at_x, look_at_y, look_at_z, up_x, up_y, up_z, duration) {
  262. if (this.camera_tween) this.camera_tween.stop();
  263. this.camera_tween = new TWEEN.Tween([
  264. this.camera.position.x,
  265. this.camera.position.y,
  266. this.camera.position.z,
  267. this.camera.up.x,
  268. this.camera.up.y,
  269. this.camera.up.z,
  270. this.look_at.x,
  271. this.look_at.y,
  272. this.look_at.z,
  273. ])
  274. .to(
  275. [
  276. x === null ? this.camera.position.x : x,
  277. y === null ? this.camera.position.y : y,
  278. z === null ? this.camera.position.z : z,
  279. up_x === null ? this.camera.up.x : up_x,
  280. up_y === null ? this.camera.up.y : up_y,
  281. up_z === null ? this.camera.up.z : up_z,
  282. look_at_x === null ? this.look_at.x : look_at_x,
  283. look_at_y === null ? this.look_at.y : look_at_y,
  284. look_at_z === null ? this.look_at.z : look_at_z,
  285. ],
  286. duration * 1000
  287. )
  288. .onUpdate((p) => {
  289. this.camera.position.set(p[0], p[1], p[2]);
  290. this.camera.up.set(p[3], p[4], p[5]); // NOTE: before calling lookAt
  291. this.look_at.set(p[6], p[7], p[8]);
  292. this.camera.lookAt(p[6], p[7], p[8]);
  293. })
  294. .start();
  295. },
  296. },
  297. props: {
  298. width: Number,
  299. height: Number,
  300. },
  301. };