]> gitweb.ps.run Git - cloth_sim/blobdiff - Scripts/cloth.js
orbit/background, flag, wind control
[cloth_sim] / Scripts / cloth.js
index e84facc28dc840447f4848723d33ef722bb9f85f..546f7d34ff05b7a561cee2a6fda279087ae63240 100644 (file)
@@ -6,9 +6,9 @@
  */\r
 function vectorLength(a, b) {\r
   let v1 = new THREE.Vector3();\r
-  v1.set(a.x, a.y, a.z);\r
+  v1.copy(a);\r
   let v2 = new THREE.Vector3();\r
-  v2.set(b.x, b.y, b.z);\r
+  v2.copy(b);\r
 \r
   return v1.sub(v2).length();\r
 }\r
@@ -46,12 +46,12 @@ export class Spring {
   index1;\r
   index2;\r
 \r
\r
+\r
   /**\r
    * set vertex indices\r
    * and calculate inital length based on the\r
    * vertex positions\r
-   * @param {Array of Vector3} vertices \r
+   * @param {Array<Vector3>} vertices \r
    * @param {number} index1 \r
    * @param {number} index2 \r
    */\r
@@ -63,6 +63,21 @@ export class Spring {
     this.restLength = length;\r
     this.currentLength = length;\r
   }\r
+\r
+  getDirection(vertices) {\r
+    let direction = new THREE.Vector3();\r
+    direction.copy(vertices[this.index1]);\r
+\r
+    direction.sub(vertices[this.index2]);\r
+    direction.divideScalar(vectorLength(vertices[this.index1], vertices[this.index2]));\r
+\r
+    return direction;\r
+  }\r
+\r
+  update(vertices) {\r
+    let length = vectorLength(vertices[this.index1], vertices[this.index2]);\r
+    this.currentLength = length;\r
+  }\r
 }\r
 \r
 /**\r
@@ -81,7 +96,15 @@ export class Cloth {
 \r
   vertexWeights = [];\r
 \r
-  \r
+  vertexRigidness = [];\r
+\r
+  fixedPoints = [];\r
+\r
+  externalForces = [];\r
+  windForce = 50;\r
+\r
+  windFactor = new THREE.Vector3(0, 0, 0);\r
+\r
   /**\r
    * creates a rectangular piece of cloth\r
    * takes the size of the cloth\r
@@ -96,6 +119,11 @@ export class Cloth {
     let vertices = [];\r
     let faces = [];\r
 \r
+    this.width = width;\r
+    this.height = height;\r
+    this.numPointsWidth = numPointsWidth;\r
+    this.numPointsHeight = numPointsHeight;\r
+\r
     /**\r
      * distance between two vertices horizontally/vertically\r
      * divide by the number of points minus one\r
@@ -111,7 +139,7 @@ export class Cloth {
     for (let y = 0; y < numPointsHeight; y++) {\r
       for (let x = 0; x < numPointsWidth; x++) {\r
         vertices.push(\r
-          new THREE.Vector3(x * stepWidth, height - y * stepHeight, 0)\r
+          new THREE.Vector3((x - ((numPointsWidth-1)/2)) * stepWidth, height - (y + ((numPointsHeight-1)/2)) * stepHeight, 0)\r
         );\r
       }\r
     }\r
@@ -126,7 +154,7 @@ export class Cloth {
     function getVertexIndex(x, y) {\r
       return y * numPointsWidth + x;\r
     }\r
-    \r
+\r
     /**\r
      * generate faces based on 4 vertices\r
      * and 6 springs each\r
@@ -140,13 +168,13 @@ export class Cloth {
           getVertexIndex(x + 1, y + 1),\r
         );\r
 \r
-        newFace.springs.push(new Spring(vertices, getVertexIndex(x, y), getVertexIndex(x + 1, y)));\r
-        newFace.springs.push(new Spring(vertices, getVertexIndex(x, y), getVertexIndex(x, y + 1)));\r
-        newFace.springs.push(new Spring(vertices, getVertexIndex(x, y), getVertexIndex(x + 1, y + 1)));\r
-        newFace.springs.push(new Spring(vertices, getVertexIndex(x + 1, y), getVertexIndex(x, y + 1)));\r
-        newFace.springs.push(new Spring(vertices, getVertexIndex(x + 1, y), getVertexIndex(x + 1, y + 1)));\r
-        newFace.springs.push(new Spring(vertices, getVertexIndex(x, y + 1), getVertexIndex(x + 1, y + 1)));\r
-        \r
+        newFace.springs.push(new Spring(vertices, getVertexIndex(x, y), getVertexIndex(x + 1, y)));         // oben\r
+        newFace.springs.push(new Spring(vertices, getVertexIndex(x, y), getVertexIndex(x, y + 1)));         // links\r
+        newFace.springs.push(new Spring(vertices, getVertexIndex(x, y), getVertexIndex(x + 1, y + 1)));     // oben links  -> unten rechts diagonal\r
+        newFace.springs.push(new Spring(vertices, getVertexIndex(x + 1, y), getVertexIndex(x, y + 1)));     // oben rechts -> unten links diagonal\r
+        newFace.springs.push(new Spring(vertices, getVertexIndex(x + 1, y), getVertexIndex(x + 1, y + 1))); // rechts\r
+        newFace.springs.push(new Spring(vertices, getVertexIndex(x, y + 1), getVertexIndex(x + 1, y + 1))); // unten\r
+\r
         faces.push(newFace);\r
       }\r
     }\r
@@ -156,6 +184,12 @@ export class Cloth {
      * with generated vertices and faces\r
      */\r
     this.createExplicit(vertices, faces);\r
+\r
+    /**\r
+     * hand cloth from left and right upper corners\r
+     */\r
+    this.fixedPoints.push(getVertexIndex(0, 0));\r
+    this.fixedPoints.push(getVertexIndex(0, 19));\r
   }\r
 \r
   /**\r
@@ -163,16 +197,22 @@ export class Cloth {
    * (list of vertices and list of indices representing triangles)\r
    * and calculate the weight of each face and split it between\r
    * surrounding vertices\r
-   * @param {Array of Vector3} vertices \r
-   * @param {Array of Face} faces \r
+   * @param {Array<Vector3>} vertices \r
+   * @param {Array<Face>} faces \r
    */\r
   createExplicit(vertices, faces) {\r
+\r
     /**\r
      * Copy vertices and initialize vertex weights to 0\r
      */\r
     for (let i in vertices) {\r
-      this.geometry.vertices.push(vertices[i]);\r
+      this.geometry.vertices.push(vertices[i].clone());\r
+      this.previousPositions.push(vertices[i].clone());\r
+      // this.geometry.vertices.push(vertices[i]);\r
+      // this.previousPositions.push(vertices[i]);\r
       this.vertexWeights.push(0);\r
+      this.vertexRigidness.push(false);\r
+      this.externalForces.push(new THREE.Vector3(0,0,0));\r
     }\r
     /**\r
      * copy faces,\r
@@ -193,7 +233,7 @@ export class Cloth {
       this.geometry.faces.push(new THREE.Face3(\r
         face.c, face.b, face.d\r
       ));\r
-      \r
+\r
       /**\r
        * calculate area of face as combined area of\r
        * its two composing triangles\r
@@ -206,6 +246,8 @@ export class Cloth {
       yLength = vectorLength(this.geometry.vertices[face.c], this.geometry.vertices[face.d]);\r
       weight += xLength * yLength / 2;\r
 \r
+      weight *= 10;\r
+\r
       /**\r
        * split weight equally between four surrounding vertices\r
        */\r
@@ -220,6 +262,8 @@ export class Cloth {
      * needed for View Frustum Culling internally\r
      */\r
     this.geometry.computeBoundingSphere();\r
+    this.geometry.computeFaceNormals();\r
+    this.geometry.computeVertexNormals();\r
   }\r
 \r
   /**\r
@@ -240,7 +284,7 @@ export class Cloth {
       let geometry = new THREE.Geometry();\r
       geometry.vertices.push(from);\r
       geometry.vertices.push(to);\r
-      let material = new THREE.LineBasicMaterial( { color: color, linewidth: 10 } );\r
+      let material = new THREE.LineBasicMaterial({ color: color, linewidth: 10 });\r
       let line = new THREE.Line(geometry, material);\r
       line.renderOrder = 1;\r
       scene.add(line);\r
@@ -252,11 +296,11 @@ export class Cloth {
      * @param {number} color \r
      */\r
     function addPoint(point, color) {\r
-      const geometry = new THREE.SphereGeometry( 0.05, 32, 32 );\r
-      const material = new THREE.MeshBasicMaterial( { color: color } );\r
-      const sphere = new THREE.Mesh( geometry, material );\r
+      const geometry = new THREE.SphereGeometry(0.05, 32, 32);\r
+      const material = new THREE.MeshBasicMaterial({ color: color });\r
+      const sphere = new THREE.Mesh(geometry, material);\r
       sphere.position.set(point.x, point.y, point.z);\r
-      scene.add( sphere );\r
+      scene.add(sphere);\r
     }\r
 \r
     let lineColor = 0x000000;\r
@@ -282,4 +326,296 @@ export class Cloth {
       addPoint(this.geometry.vertices[face.d], pointColor);\r
     }\r
   }\r
-}
\ No newline at end of file
+\r
+  previousPositions = [];\r
+  time = 0;\r
+  /**\r
+   * \r
+   * @param {number} dt time in seconds since last frame\r
+   */\r
+  simulate(dt) {\r
+    for (let i in this.geometry.vertices) {\r
+      let acceleration = this.getAcceleration(i, dt);\r
+\r
+      //acceleration.clampLength(0, 10);\r
+\r
+      if (Math.abs(acceleration.length()) <= 10e-4) {\r
+        acceleration.set(0, 0, 0);\r
+      }\r
\r
+      let currentPosition = this.verlet(this.geometry.vertices[i].clone(), this.previousPositions[i].clone(), acceleration, dt);\r
+      //let currentPosition = this.euler(this.geometry.vertices[i], acceleration, dt);\r
+     \r
+      this.previousPositions[i].copy(this.geometry.vertices[i]);\r
+      this.geometry.vertices[i].copy(currentPosition);\r
+    }\r
+    \r
+    this.checkIntersect();\r
+    \r
+    this.time += dt;\r
+\r
+    for (let face of this.faces) {\r
+      for (let spring of face.springs) {\r
+        spring.update(this.geometry.vertices);\r
+      }\r
+    }\r
+\r
+    /**\r
+     * let THREE JS compute bounding sphere around generated mesh\r
+     * needed for View Frustum Culling internally\r
+     */\r
+\r
+    this.geometry.verticesNeedUpdate = true;\r
+    this.geometry.elementsNeedUpdate = true;\r
+    this.geometry.computeBoundingSphere();\r
+    this.geometry.computeFaceNormals();\r
+    this.geometry.computeVertexNormals();\r
+\r
+  }\r
+\r
+checkIntersect() {\r
+  let npw = this.numPointsWidth;\r
+  function getX(i, ) { return i % npw; }\r
+  function getY(i) { return Math.floor(i / npw); }\r
+  for (let i in this.geometry.vertices) {\r
+    for (let j in this.geometry.vertices) {\r
+      this.vertexRigidness[i] = false;\r
+      this.vertexRigidness[j] = false;\r
+      if (i == j || (Math.abs(getX(i) - getX(j)) == 1 && Math.abs(getY(i) - getY(j)) == 1))\r
+        continue;\r
+      let posI = this.geometry.vertices[i];\r
+      let posJ = this.geometry.vertices[j];\r
+      let dist = posI.distanceTo(posJ);\r
+      const collisionDistance = Math.min(this.width / this.numPointsWidth, this.height / this.numPointsHeight);\r
+      if (dist < collisionDistance) {\r
+        this.vertexRigidness[i] = true;\r
+        this.vertexRigidness[j] = true;\r
+        let diff = this.geometry.vertices[i].clone().sub(this.geometry.vertices[j]).normalize().multiplyScalar((collisionDistance - dist) * 1.001 / 2);\r
+        if (!(this.fixedPoints.includes(i) || this.fixedPoints.includes(j))) {\r
+          this.geometry.vertices[i].add(diff);\r
+          this.geometry.vertices[j].sub(diff);\r
+        }\r
+      }\r
+    }\r
+  }\r
+}\r
+\r
+/**\r
+ * Equation of motion for each vertex which represents the acceleration \r
+ * @param {number} vertexIndex The index of the current vertex whose acceleration should be calculated\r
+ *  @param {number} dt The time passed since last frame\r
+ */\r
+getAcceleration(vertexIndex, dt) {\r
+  if (this.fixedPoints.includes(parseInt(vertexIndex)) ||\r
+      this.vertexRigidness[vertexIndex]) {\r
+    return new THREE.Vector3(0, 0, 0);\r
+  }\r
+\r
+  let externalForce = this.externalForces[vertexIndex];\r
+  let vertex = this.geometry.vertices[vertexIndex];//.add(externalForce);\r
+\r
+  // Mass of vertex\r
+  let M = this.vertexWeights[vertexIndex];\r
+  // constant gravity\r
+  let g = new THREE.Vector3(0, -9.8, 0);\r
+  // stiffness\r
+  let k = 1000;\r
+\r
+  // Wind vector\r
+  let fWind = new THREE.Vector3(\r
+    this.windFactor.x * (Math.sin(vertex.x * vertex.y * this.time)+1),\r
+    this.windFactor.y * Math.cos(vertex.z * this.time),\r
+    this.windFactor.z * Math.sin(Math.cos(5 * vertex.x * vertex.y * vertex.z))\r
+  );\r
+  //console.log(fWind);\r
+\r
+  /**\r
+   * constant determined by the properties of the surrounding fluids (air)\r
+   * achievement of cloth effects through try out\r
+   * */\r
+  let a = 0.1;\r
+  \r
+  let velocity = new THREE.Vector3(\r
+    (this.previousPositions[vertexIndex].x - vertex.x) / dt,\r
+    (this.previousPositions[vertexIndex].y - vertex.y) / dt,\r
+    (this.previousPositions[vertexIndex].z - vertex.z) / dt\r
+  );\r
+\r
+  //console.log(velocity, vertex, this.previousPositions[vertexIndex]);\r
+\r
+  let fAirResistance = velocity.multiply(velocity).multiplyScalar(-a);\r
+  \r
+  let springSum = new THREE.Vector3(0, 0, 0);\r
+\r
+  // Get the bounding springs and add them to the needed springs\r
+  // TODO: optimize\r
+\r
+  const numPointsX = this.numPointsWidth;\r
+  const numPointsY = this.numPointsHeight;\r
+  const numFacesX = numPointsX - 1;\r
+  const numFacesY = numPointsY - 1;\r
+\r
+  function getFaceIndex(x, y) {\r
+    return y * numFacesX + x;\r
+  }\r
+\r
+  let indexX = vertexIndex % numPointsX;\r
+  let indexY = Math.floor(vertexIndex / numPointsX);\r
+\r
+  let springs = [];\r
+\r
+  // 0  oben\r
+  // 1  links\r
+  // 2  oben links  -> unten rechts diagonal\r
+  // 3  oben rechts -> unten links diagonal\r
+  // 4  rechts\r
+  // 5  unten\r
+\r
+  let ul = indexX > 0 && indexY < numPointsY - 1;\r
+  let ur = indexX < numPointsX - 1 && indexY < numPointsY - 1;\r
+  let ol = indexX > 0 && indexY > 0;\r
+  let or = indexX < numPointsX - 1 && indexY > 0;\r
+\r
+  if (ul) {\r
+    let faceUL = this.faces[getFaceIndex(indexX - 1, indexY)];\r
+    springs.push(faceUL.springs[3]);\r
+    if (!ol)\r
+      springs.push(faceUL.springs[0]);\r
+    springs.push(faceUL.springs[4]);\r
+  }\r
+  if (ur) {\r
+    let faceUR = this.faces[getFaceIndex(indexX, indexY)];\r
+    springs.push(faceUR.springs[2]);\r
+    if (!or)\r
+      springs.push(faceUR.springs[0]);\r
+    if (!ul)\r
+      springs.push(faceUR.springs[1]);\r
+  }\r
+  if (ol) {\r
+    let faceOL = this.faces[getFaceIndex(indexX - 1, indexY - 1)];\r
+    springs.push(faceOL.springs[2]);\r
+    springs.push(faceOL.springs[4]);\r
+    springs.push(faceOL.springs[5]);\r
+  }\r
+  if (or) {\r
+    let faceOR = this.faces[getFaceIndex(indexX , indexY - 1)];\r
+    springs.push(faceOR.springs[3]);\r
+    if (!ol)\r
+      springs.push(faceOR.springs[1]);\r
+    springs.push(faceOR.springs[5]);\r
+  }\r
+\r
+  for (let spring of springs) {\r
+    let springDirection = spring.getDirection(this.geometry.vertices);\r
+\r
+    if (spring.index1 == vertexIndex)\r
+      springDirection.multiplyScalar(-1);\r
+\r
+    springSum.add(springDirection.multiplyScalar(k * (spring.restLength - spring.currentLength)));\r
+  }\r
+  \r
+  let result = new THREE.Vector3(1, 1, 1);\r
+  result.multiplyScalar(M).multiply(g).add(fWind).add(externalForce).add(fAirResistance).sub(springSum);\r
+\r
+  document.getElementById("Output").innerText = "SpringSum: " + Math.floor(springSum.y);\r
+\r
+  let threshold = 1;\r
+  let forceReduktion = 0.8;\r
+  if(Math.abs(externalForce.z) > threshold){\r
+    externalForce.z *= forceReduktion;\r
+  } else {\r
+    externalForce.z = 0;\r
+  }\r
+\r
+  if(Math.abs(externalForce.y) > threshold){\r
+    externalForce.y *= forceReduktion;\r
+  } else {\r
+    externalForce.y = 0;\r
+  }\r
+\r
+  if(Math.abs(externalForce.x) > threshold){\r
+    externalForce.x *= forceReduktion;\r
+  } else {\r
+    externalForce.x = 0;\r
+  }\r
+    \r
+  \r
+\r
+  return result;\r
+}\r
+\r
+/**\r
+ * The Verlet algorithm as an integrator \r
+ * to get the next position of a vertex  \r
+ * @param {Vector3} currentPosition \r
+ * @param {Vector3} previousPosition \r
+ * @param {Vector3} acceleration \r
+ * @param {number} passedTime The delta time since last frame\r
+ */\r
+verlet(currentPosition, previousPosition, acceleration, passedTime) {\r
+  // verlet algorithm\r
+  // next position = 2 * current Position - previous position + acceleration * (passed time)^2\r
+  // acceleration (dv/dt) = F(net)\r
+  // Dependency for one vertex: gravity, fluids/air, springs\r
+  const DRAG = 0.97;\r
+  let nextPosition = new THREE.Vector3(\r
+    (currentPosition.x - previousPosition.x) * DRAG + currentPosition.x + acceleration.x * (passedTime * passedTime),\r
+    (currentPosition.y - previousPosition.y) * DRAG + currentPosition.y + acceleration.y * (passedTime * passedTime),\r
+    (currentPosition.z - previousPosition.z) * DRAG + currentPosition.z + acceleration.z * (passedTime * passedTime),\r
+  );\r
+\r
+  // let nextPosition = new THREE.Vector3(\r
+  //   (2 * currentPosition.x) - previousPosition.x + acceleration.x * (passedTime * passedTime),\r
+  //   (2 * currentPosition.y) - previousPosition.y + acceleration.y * (passedTime * passedTime),\r
+  //   (2 * currentPosition.z) - previousPosition.z + acceleration.z * (passedTime * passedTime),\r
+  // );\r
+\r
+  return nextPosition;\r
+}\r
+\r
+euler(currentPosition, acceleration, passedTime) {\r
+  let nextPosition = new THREE.Vector3(\r
+    currentPosition.x + acceleration.x * passedTime,\r
+    currentPosition.y + acceleration.y * passedTime,\r
+    currentPosition.z + acceleration.z * passedTime,\r
+  );\r
+\r
+  return nextPosition;\r
+}\r
+\r
+wind(intersects) {\r
+  let intersect = intersects[0];\r
+  this.externalForces[intersect.face.a].z -= this.windForce;\r
+  this.externalForces[intersect.face.b].z -= this.windForce;\r
+  this.externalForces[intersect.face.c].z -= this.windForce;\r
+}\r
+\r
+mousePressed = false;\r
+mouseMoved = false;\r
+intersects;\r
+\r
+mousePress(intersects){\r
+  this.mousePressed = true;\r
+  this.intersects = intersects;\r
+\r
+}\r
+\r
+mouseMove(mousePos){\r
+  this.mouseMoved = true;\r
+  if(this.mousePressed){\r
+    let intersect = this.intersects[0];\r
+    this.externalForces[intersect.face.a].add(mousePos.clone().sub(this.geometry.vertices[intersect.face.a]).multiplyScalar(90));\r
+    /*\r
+    this.geometry.vertices[intersect.face.a].x = mousePos.x;\r
+    this.geometry.vertices[intersect.face.a].y = mousePos.y;\r
+    this.geometry.vertices[intersect.face.a].z = mousePos.z;\r
+  */  \r
+  }\r
+}\r
+\r
+mouseRelease(){\r
+  this.mousePressed = false;\r
+}\r
+\r
+}\r
+\r