From 9371ba1ab3a6d5b38041d0a1e67b081d9c468322 Mon Sep 17 00:00:00 2001 From: Mike Lynch Date: Sat, 22 Jul 2023 14:52:42 +1000 Subject: [PATCH] Almost there with the links --- main.js | 39 ++++++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/main.js b/main.js index aff7c0f..675b629 100644 --- a/main.js +++ b/main.js @@ -3,17 +3,37 @@ import * as THREE from 'three'; const NODE_SIZE = 0.1; const LINK_SIZE = 0.05; + +function makeLink(link_m, n1, n2) { + const length = n1.distanceTo(n2); + const centre = new THREE.Vector3(); + centre.lerpVectors(n1, n2, 0.5); + const geometry = new THREE.CylinderGeometry(LINK_SIZE, LINK_SIZE,length); +// const geometry = new THREE.SphereGeometry(LINK_SIZE); + const cyl = new THREE.Mesh(geometry, link_m); + cyl.position.x = centre.x; + cyl.position.y = centre.y; + cyl.position.z = centre.z; + cyl.lookAt(n2); + return cyl; +} + + + function makeWireFrame(node_m, link_m, graph) { const nodeids = {} const group = new THREE.Group(); for ( const n of graph.nodes ) { - nodeids[n.id] = [ n.x, n.y, n.z ]; + const v3 = new THREE.Vector3(n.x, n.y, n.z); + nodeids[n.id] = v3.clone(); const geometry = new THREE.SphereGeometry(NODE_SIZE); const sphere = new THREE.Mesh(geometry, node_m); + sphere.position.copy(v3); group.add(sphere); - sphere.position.x = n.x; - sphere.position.y = n.y; - sphere.position.z = n.z; + } + for ( const l of graph.links ) { + const link = makeLink(link_m, nodeids[l.source], nodeids[l.target]); + group.add(link); } return group; } @@ -27,12 +47,12 @@ renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement ); const node_m = new THREE.MeshBasicMaterial( { color: 0x33ff00 } ); -const link_m = new THREE.MeshBasicMaterial( { color: 0x009930 } ); +const link_m = new THREE.MeshBasicMaterial( { color: 0x990030 } ); -const octahedron = makeWireFrame(node_m, link_m, { +const shape = makeWireFrame(node_m, link_m, { nodes: [ { id: 1, x: 0, y: -1, z: 0 }, { id: 2, x: 0, y: 0, z: -1 }, @@ -59,7 +79,8 @@ const octahedron = makeWireFrame(node_m, link_m, { -scene.add(octahedron); + +scene.add(shape); @@ -70,8 +91,8 @@ let tick = 0; function animate() { requestAnimationFrame( animate ); - octahedron.rotation.x = tick * 0.3; - octahedron.rotation.y = tick * 0.5; + shape.rotation.x = tick * 0.03; + shape.rotation.y = tick * 0.05; tick += 0.01; renderer.render( scene, camera );