]> gitweb.ps.run Git - cloth_sim/blobdiff - Scripts/cloth.js
README
[cloth_sim] / Scripts / cloth.js
index aaa9d249a25a9702d3abd95d46a1d317f5a95f76..712ed63a7250971788ab0424bba30bd9a0490003 100644 (file)
@@ -1,14 +1,15 @@
 const DAMPING = 0.03;\r
 const DRAG = 1 - DAMPING;\r
-const MASS = 0.35;\r
+const MASS = 0.1;\r
 const GRAVITY = new THREE.Vector3(0, -9.81 * MASS, 0);\r
 const K = 1;\r
+const MAX_STRETCH = 1.5;\r
 \r
 const options = {\r
   wind: true,\r
 };\r
 \r
-class Constraint {\r
+class Spring {\r
   constructor(p1, p2, restDist) {\r
     this.p1 = p1;\r
     this.p2 = p2;\r
@@ -16,27 +17,36 @@ class Constraint {
   }\r
 \r
   satisfy() {\r
+    /** calculate current spring length */\r
     const diff = this.p2.position.clone().sub(this.p1.position);\r
     const currentDist = diff.length();\r
     if (currentDist == 0) return;\r
     if (currentDist <= this.restDist) return;\r
     //const correction = diff.multiplyScalar(1 - (this.restDist / currentDist));\r
+\r
+    /** calculate necessary correction length and direction */\r
     const correction = diff.multiplyScalar((currentDist - this.restDist) / currentDist);\r
     correction.multiplyScalar(K);\r
-    correction.clampLength(0, 1);\r
     const correctionHalf = correction.multiplyScalar(0.5);\r
-    if (this.p1.movable && this.p2.movable) {\r
+\r
+    let p1movable = this.p1.movable && this.p1.movableTmp;\r
+    let p2movable = this.p2.movable && this.p2.movableTmp;\r
+\r
+    /** apply correction if masses aren't fixed */\r
+    /** divide correction if both are movable */\r
+    if (p1movable && p2movable) {\r
       this.p1.position.add(correctionHalf);\r
       this.p2.position.sub(correctionHalf);\r
-    } else if (! this.p1.movable && this.p2.movable) {\r
+    } else if (! p1movable && p2movable) {\r
       this.p2.position.sub(correction);\r
-    } else if (this.p1.movable && ! this.p2.movable) {\r
+    } else if (p1movable && ! p2movable) {\r
       this.p1.position.add(correction);\r
     }\r
   }\r
 }\r
 \r
-class Particle {\r
+class Mass {\r
+  movableTmp = true;\r
   movable = true;\r
 \r
   constructor(x, y, z, mass) {\r
@@ -54,16 +64,20 @@ class Particle {
     // verlet algorithm\r
     // next position = 2 * current Position - previous position + acceleration * (passed time)^2\r
     // acceleration (dv/dt) = F(net)\r
+    /** calculate velocity */\r
     const nextPosition = this.position.clone().sub(this.previous);\r
+    /** apply drag */\r
     nextPosition.multiplyScalar(DRAG);\r
+    /** add to current position and add acceleration */\r
     nextPosition.add(this.position);\r
     nextPosition.add(this.acceleration.multiplyScalar(dt*dt));\r
 \r
-    if (this.movable) {\r
+    if (this.movable && this.movableTmp) {\r
       this.previous = this.position;\r
       this.position = nextPosition;\r
     }\r
 \r
+    /** reset for next frame */\r
     this.acceleration.set(0, 0, 0);\r
   }\r
 }\r
@@ -74,7 +88,7 @@ class Cloth {
     this.height = height;\r
     this.numPointsWidth = numPointsWidth;\r
     this.numPointsHeight = numPointsHeight;\r
-    this.windFactor = new THREE.Vector3(5, 2, 2);\r
+    this.windFactor = new THREE.Vector3(3, 2, 2);\r
 \r
     /**\r
      * distance between two vertices horizontally/vertically\r
@@ -86,13 +100,13 @@ class Cloth {
 \r
     /**\r
      * iterate over the number of vertices in x/y axis\r
-     * and add a new Particle to "particles"\r
+     * and add a new Particle to "masses"\r
      */\r
-    this.particles = [];\r
+    this.masses = [];\r
     for (let y = 0; y < numPointsHeight; y++) {\r
       for (let x = 0; x < numPointsWidth; x++) {\r
-        this.particles.push(\r
-          new Particle(\r
+        this.masses.push(\r
+          new Mass(\r
             (x - ((numPointsWidth-1)/2)) * stepWidth,\r
             height - (y + ((numPointsHeight-1)/2)) * stepHeight,\r
             0,\r
@@ -101,33 +115,31 @@ class Cloth {
       }\r
     }\r
 \r
-    //this.particles[this.getVertexIndex(0, 0)].movable = false;\r
+    /** attach cloth to flag pole */\r
     const n = 3;\r
-    for (let i = 0; i <= n; i++)\r
-      this.particles[this.getVertexIndex(0, Math.floor((numPointsHeight-1)*(i/n)))].movable = false;\r
-    //this.particles[this.getVertexIndex(0, numPointsHeight-1)].movable = false;\r
-    //this.particles[this.getVertexIndex(numPointsWidth-1, 0)].movable = false;\r
+    for (let i = 0; i < numPointsHeight; i++)\r
+      this.masses[this.getVertexIndex(0, i)].movable = false;\r
 \r
     const REST_DIST_X = width / (numPointsWidth-1);\r
     const REST_DIST_Y = height / (numPointsHeight-1);\r
 \r
     /**\r
-     * generate constraints (springs)\r
+     * generate springs (constraints)\r
      */\r
-    this.constraints = [];\r
+    this.springs = [];\r
     for (let y = 0; y < numPointsHeight; y++) {\r
       for (let x = 0; x < numPointsWidth; x++) {\r
         if (x < numPointsWidth-1) {\r
-          this.constraints.push(new Constraint(\r
-            this.particles[this.getVertexIndex(x, y)],\r
-            this.particles[this.getVertexIndex(x+1, y)],\r
+          this.springs.push(new Spring(\r
+            this.masses[this.getVertexIndex(x, y)],\r
+            this.masses[this.getVertexIndex(x+1, y)],\r
             REST_DIST_X\r
           ));\r
         }\r
         if (y < numPointsHeight-1) {\r
-          this.constraints.push(new Constraint(\r
-            this.particles[this.getVertexIndex(x, y)],\r
-            this.particles[this.getVertexIndex(x, y+1)],\r
+          this.springs.push(new Spring(\r
+            this.masses[this.getVertexIndex(x, y)],\r
+            this.masses[this.getVertexIndex(x, y+1)],\r
             REST_DIST_Y\r
           ));\r
         }\r
@@ -138,25 +150,28 @@ class Cloth {
     const geometry = new THREE.BufferGeometry();\r
 \r
     const vertices = [];\r
-    const normals = [];\r
     const indices = [];\r
+    const uvs = [];\r
 \r
-    for (let particle of this.particles) {\r
+    /** create one vertex and one uv coordinate per mass */\r
+    for (let i in this.masses) {\r
+      let particle = this.masses[i];\r
       vertices.push(\r
         particle.position.x,\r
         particle.position.y,\r
         particle.position.z);\r
+      uvs.push(\r
+        this.getX(i) / (this.numPointsWidth-1),\r
+        1 - (this.getY(i) / (this.numPointsHeight-1))\r
+      );\r
     }\r
 \r
-    const numPointsWidth = this.numPointsWidth;\r
-    const numPointsHeight = this.numPointsHeight;\r
-\r
     /**\r
      * generate faces based on 4 vertices\r
      * and 6 springs each\r
      */\r
-    for (let y = 0; y < numPointsHeight - 1; y++) {\r
-      for (let x = 0; x < numPointsWidth - 1; x++) {\r
+    for (let y = 0; y < this.numPointsHeight - 1; y++) {\r
+      for (let x = 0; x < this.numPointsWidth - 1; x++) {\r
         indices.push(\r
           this.getVertexIndex(x, y),\r
           this.getVertexIndex(x+1, y),\r
@@ -170,30 +185,37 @@ class Cloth {
       }\r
     }\r
 \r
+    /** set up geometry */\r
     geometry.setIndex(indices);\r
     geometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));\r
-    //geometry.setAttribute('normal', new THREE.Float32BufferAttribute(normals, 3));\r
+    geometry.setAttribute('uv', new THREE.Float32BufferAttribute(uvs, 2));\r
     geometry.computeBoundingSphere();\r
     geometry.computeVertexNormals();\r
 \r
     return geometry;\r
   }\r
   updateGeometry(geometry) {\r
+    /** update vertex positions in place */\r
     const positions = geometry.attributes.position.array;\r
-    for (let i in this.particles) {\r
-      let p = this.particles[i];\r
+    for (let i in this.masses) {\r
+      let p = this.masses[i];\r
       positions[i*3+0] = p.position.x;\r
       positions[i*3+1] = p.position.y;\r
       positions[i*3+2] = p.position.z;\r
     }\r
+    /** update internally and recalculate bounding volume */\r
     geometry.attributes.position.needsUpdate = true;\r
     geometry.computeBoundingSphere();\r
     geometry.computeVertexNormals();\r
   }\r
   simulate(dt) {\r
     let now = performance.now();\r
-    for (let particle of this.particles) {\r
-      let vertex = particle.position;\r
+    for (let mass of this.masses) {\r
+      /** accumulate acceleration:\r
+       *  - wind\r
+       *  - gravity\r
+       */\r
+      let vertex = mass.position;\r
       let fWind = new THREE.Vector3(\r
         this.windFactor.x * (Math.sin(vertex.x * vertex.y * now)+1),\r
         this.windFactor.y * Math.cos(vertex.z * now),\r
@@ -201,20 +223,85 @@ class Cloth {
       );\r
       // normalize then multiply?\r
       if (options.wind)\r
-        particle.addForce(fWind);\r
+        mass.addForce(fWind);\r
       // calculate wind with normal?\r
 \r
-      particle.addForce(GRAVITY);\r
+      mass.addForce(GRAVITY);\r
 \r
-      particle.verlet(dt);\r
+      /** integrate motion */\r
+      mass.verlet(dt);\r
     }\r
 \r
-    \r
-    for (let constraint of this.constraints) {\r
+    /** run satisfy step */\r
+    for (let constraint of this.springs) {\r
       constraint.satisfy();\r
     }\r
-    //console.log(tmpCorrection);\r
+\r
+    /** prevent self-intersections */\r
+    this.intersect();\r
   }\r
+\r
+  intersect() {\r
+    for (let i in this.masses) {\r
+      for (let j in this.masses) {  \r
+        let p1 = this.masses[i];\r
+        let p2 = this.masses[j];\r
+\r
+        p1.movableTmp = true;\r
+        p2.movableTmp = true;\r
+\r
+        /** skip if i == j or if masses are adjacent */\r
+        if (i == j || (Math.abs(this.getX(i) - this.getX(j)) == 1 && Math.abs(this.getY(i) - this.getY(j)) == 1))\r
+          continue;\r
+\r
+        /** calculate distance of points  */\r
+        let dist = p1.position.distanceTo(p2.position);\r
+        /** calculate minimal resting distance (largest distance that should not be fallen below) */\r
+        let collisionDistance = Math.min(this.width / this.numPointsWidth, this.height / this.numPointsHeight);\r
+        // collisionDistance /= 2;\r
+        /** calculate "sphere intersection" */\r
+        if (dist < collisionDistance) {\r
+          // p1.movableTmp = false;\r
+          // p2.movableTmp = false;\r
+\r
+          /** vectors from p1 to p2 and the other way round */\r
+          let diffP2P1 = p1.position.clone().sub(p2.position).normalize();\r
+          diffP2P1.multiplyScalar((collisionDistance - dist) * 1.001 / 2);\r
+          let diffP1P2 = diffP2P1.clone().multiplyScalar(-1);\r
+\r
+          // let v1 = p1.position.clone().sub(p1.previous).normalize();\r
+          // let v2 = p2.position.clone().sub(p2.previous).normalize();\r
+\r
+          // let factor1 = (Math.PI - Math.acos(v1.dot(diffP2P1))) / Math.PI * 2;\r
+          // let factor2 = (Math.PI - Math.acos(v2.dot(diffP1P2))) / Math.PI * 2;\r
+\r
+          /** move masses apart */\r
+          if (p1.movable)\r
+            p1.position.add(diffP2P1);\r
+            //p1.position.add(diffP2P1.multiplyScalar(factor1));\r
+          if (p2.movable)\r
+            p2.position.add(diffP1P2);\r
+            //p2.position.add(diffP1P2.multiplyScalar(factor2));\r
+        }\r
+      }\r
+    }\r
+  }\r
+  blow(camPos, intersects) {\r
+    let face = intersects[0].face;\r
+    /** vector from cam to intersection (wind) */\r
+    let dir = intersects[0].point.clone().sub(camPos).multiplyScalar(100);\r
+    /** apply to all vertices of affected face */\r
+    this.masses[face.a].addForce(dir);\r
+    this.masses[face.b].addForce(dir);\r
+    this.masses[face.c].addForce(dir);\r
+  }\r
+  drag(mousePosWorld, index) {\r
+    /** calculate vector from vertex to cursor */\r
+    let dir = mousePosWorld.clone().sub(this.masses[index].position).multiplyScalar(200);\r
+    /** apply to grabbed vertex */\r
+    this.masses[index].addForce(dir);\r
+  }\r
+\r
   /**\r
    * helper function to calculate index of vertex\r
    * in "vertices" array based on its x and y positions\r
@@ -225,4 +312,6 @@ class Cloth {
   getVertexIndex(x, y) {\r
     return y * this.numPointsWidth + x;\r
   }\r
+  getX(i) { return i % this.numPointsWidth; }\r
+  getY(i) { return Math.floor(i / this.numPointsWidth); }\r
 }
\ No newline at end of file