]> gitweb.ps.run Git - cloth_sim/blob - Scripts/cloth.js
cloth-cloth collision
[cloth_sim] / Scripts / cloth.js
1 /**\r
2  *  Convenience Function for calculating the distance between two vectors\r
3  *  because THREE JS Vector functions mutate variables\r
4  * @param {Vector3} a - Vector A\r
5  * @param {Vector3} b - Vector B\r
6  */\r
7 function vectorLength(a, b) {\r
8   let v1 = new THREE.Vector3();\r
9   v1.copy(a);\r
10   let v2 = new THREE.Vector3();\r
11   v2.copy(b);\r
12 \r
13   return v1.sub(v2).length();\r
14 }\r
15 \r
16 /**\r
17  * Class representing a quad face\r
18  * Each face consists of two triangular mesh faces\r
19  * containts four indices for determining vertices\r
20  * and six springs, one between each of the vertices\r
21  */\r
22 export class Face {\r
23   a;\r
24   b;\r
25   c;\r
26   d;\r
27 \r
28   springs = [];\r
29 \r
30   constructor(a, b, c, d) {\r
31     this.a = a;\r
32     this.b = b;\r
33     this.c = c;\r
34     this.d = d;\r
35   }\r
36 }\r
37 \r
38 /**\r
39  * Class representing a single spring\r
40  * has a current and resting length\r
41  * and indices to the two connected vertices\r
42  */\r
43 export class Spring {\r
44   restLength;\r
45   currentLength;\r
46   index1;\r
47   index2;\r
48 \r
49 \r
50   /**\r
51    * set vertex indices\r
52    * and calculate inital length based on the\r
53    * vertex positions\r
54    * @param {Array<Vector3>} vertices \r
55    * @param {number} index1 \r
56    * @param {number} index2 \r
57    */\r
58   constructor(vertices, index1, index2) {\r
59     this.index1 = index1;\r
60     this.index2 = index2;\r
61 \r
62     let length = vectorLength(vertices[index1], vertices[index2]);\r
63     this.restLength = length;\r
64     this.currentLength = length;\r
65   }\r
66 \r
67   getDirection(vertices) {\r
68     let direction = new THREE.Vector3();\r
69     direction.copy(vertices[this.index1]);\r
70 \r
71     direction.sub(vertices[this.index2]);\r
72     direction.divideScalar(vectorLength(vertices[this.index1], vertices[this.index2]));\r
73 \r
74     return direction;\r
75   }\r
76 \r
77   update(vertices) {\r
78     let length = vectorLength(vertices[this.index1], vertices[this.index2]);\r
79     this.currentLength = length;\r
80   }\r
81 }\r
82 \r
83 /**\r
84  * Class representing a single piece of cloth\r
85  * contains THREE JS geometry,\r
86  * logically represented by an array of adjacent faces\r
87  * and vertex weights which are accessed by the same\r
88  * indices as the vertices in the Mesh\r
89  */\r
90 export class Cloth {\r
91   VertexWeight = 1;\r
92 \r
93   geometry = new THREE.Geometry();\r
94 \r
95   faces = [];\r
96 \r
97   vertexWeights = [];\r
98 \r
99   vertexRigidness = [];\r
100 \r
101   fixedPoints = [];\r
102 \r
103   externalForces = [];\r
104   windForce = 50;\r
105 \r
106   /**\r
107    * creates a rectangular piece of cloth\r
108    * takes the size of the cloth\r
109    * and the number of vertices it should be composed of\r
110    * @param {number} width - width of the cloth\r
111    * @param {number} height - height of the cloth\r
112    * @param {number} numPointsWidth - number of vertices in horizontal direction\r
113    * @param {number} numPointsHeight  - number of vertices in vertical direction\r
114    */\r
115   createBasic(width, height, numPointsWidth, numPointsHeight) {\r
116     /** resulting vertices and faces */\r
117     let vertices = [];\r
118     let faces = [];\r
119 \r
120     this.numPointsWidth = numPointsWidth;\r
121     this.numPointsHeight = numPointsHeight;\r
122 \r
123     /**\r
124      * distance between two vertices horizontally/vertically\r
125      * divide by the number of points minus one\r
126      * because there are (n - 1) lines between n vertices\r
127      */\r
128     let stepWidth = width / (numPointsWidth - 1);\r
129     let stepHeight = height / (numPointsHeight - 1);\r
130 \r
131     /**\r
132      * iterate over the number of vertices in x/y axis\r
133      * and add a new Vector3 to "vertices"\r
134      */\r
135     for (let y = 0; y < numPointsHeight; y++) {\r
136       for (let x = 0; x < numPointsWidth; x++) {\r
137         vertices.push(\r
138           new THREE.Vector3((x - (numPointsWidth/2)) * stepWidth, height - y * stepHeight, 0)\r
139         );\r
140       }\r
141     }\r
142 \r
143     /**\r
144      * helper function to calculate index of vertex\r
145      * in "vertices" array based on its x and y positions\r
146      * in the mesh\r
147      * @param {number} x - x index of vertex\r
148      * @param {number} y - y index of vertex\r
149      */\r
150     function getVertexIndex(x, y) {\r
151       return y * numPointsWidth + x;\r
152     }\r
153 \r
154     /**\r
155      * generate faces based on 4 vertices\r
156      * and 6 springs each\r
157      */\r
158     for (let y = 0; y < numPointsHeight - 1; y++) {\r
159       for (let x = 0; x < numPointsWidth - 1; x++) {\r
160         let newFace = new Face(\r
161           getVertexIndex(x, y),\r
162           getVertexIndex(x, y + 1),\r
163           getVertexIndex(x + 1, y),\r
164           getVertexIndex(x + 1, y + 1),\r
165         );\r
166 \r
167         newFace.springs.push(new Spring(vertices, getVertexIndex(x, y), getVertexIndex(x + 1, y)));         // oben\r
168         newFace.springs.push(new Spring(vertices, getVertexIndex(x, y), getVertexIndex(x, y + 1)));         // links\r
169         newFace.springs.push(new Spring(vertices, getVertexIndex(x, y), getVertexIndex(x + 1, y + 1)));     // oben links  -> unten rechts diagonal\r
170         newFace.springs.push(new Spring(vertices, getVertexIndex(x + 1, y), getVertexIndex(x, y + 1)));     // oben rechts -> unten links diagonal\r
171         newFace.springs.push(new Spring(vertices, getVertexIndex(x + 1, y), getVertexIndex(x + 1, y + 1))); // rechts\r
172         newFace.springs.push(new Spring(vertices, getVertexIndex(x, y + 1), getVertexIndex(x + 1, y + 1))); // unten\r
173 \r
174         faces.push(newFace);\r
175       }\r
176     }\r
177 \r
178     /**\r
179      * call createExplicit\r
180      * with generated vertices and faces\r
181      */\r
182     this.createExplicit(vertices, faces);\r
183 \r
184     /**\r
185      * hand cloth from left and right upper corners\r
186      */\r
187     //this.vertexRigidness[0] = true;\r
188     //this.vertexRigidness[numPointsWidth * (numPointsHeight - 1)] = true;\r
189     this.fixedPoints.push(getVertexIndex(8, 10));\r
190     this.fixedPoints.push(getVertexIndex(12, 9));\r
191   }\r
192 \r
193   /**\r
194    * Generate THREE JS Geometry\r
195    * (list of vertices and list of indices representing triangles)\r
196    * and calculate the weight of each face and split it between\r
197    * surrounding vertices\r
198    * @param {Array<Vector3>} vertices \r
199    * @param {Array<Face>} faces \r
200    */\r
201   createExplicit(vertices, faces) {\r
202 \r
203     /**\r
204      * Copy vertices and initialize vertex weights to 0\r
205      */\r
206     for (let i in vertices) {\r
207       this.geometry.vertices.push(vertices[i].clone());\r
208       this.previousPositions.push(vertices[i].clone());\r
209       // this.geometry.vertices.push(vertices[i]);\r
210       // this.previousPositions.push(vertices[i]);\r
211       this.vertexWeights.push(0);\r
212       this.vertexRigidness.push(false);\r
213       this.externalForces.push(new THREE.Vector3(0,0,0));\r
214     }\r
215     /**\r
216      * copy faces,\r
217      * generate two triangles per face,\r
218      * calculate weight of face as its area\r
219      * and split between the 4 vertices\r
220      */\r
221     for (let i in faces) {\r
222       let face = faces[i];\r
223 \r
224       /** copy faces to class member */\r
225       this.faces.push(face);\r
226 \r
227       /** generate triangles */\r
228       this.geometry.faces.push(new THREE.Face3(\r
229         face.a, face.b, face.c\r
230       ));\r
231       this.geometry.faces.push(new THREE.Face3(\r
232         face.c, face.b, face.d\r
233       ));\r
234 \r
235       /**\r
236        * calculate area of face as combined area of\r
237        * its two composing triangles\r
238        */\r
239       let xLength = vectorLength(this.geometry.vertices[face.b], this.geometry.vertices[face.a]);\r
240       let yLength = vectorLength(this.geometry.vertices[face.c], this.geometry.vertices[face.a]);\r
241       let weight = xLength * yLength / 2;\r
242 \r
243       xLength = vectorLength(this.geometry.vertices[face.b], this.geometry.vertices[face.d]);\r
244       yLength = vectorLength(this.geometry.vertices[face.c], this.geometry.vertices[face.d]);\r
245       weight += xLength * yLength / 2;\r
246 \r
247       /**\r
248        * split weight equally between four surrounding vertices\r
249        */\r
250       this.vertexWeights[face.a] += weight / 4;\r
251       this.vertexWeights[face.b] += weight / 4;\r
252       this.vertexWeights[face.c] += weight / 4;\r
253       this.vertexWeights[face.d] += weight / 4;\r
254     }\r
255 \r
256     /**\r
257      * let THREE JS compute bounding sphere around generated mesh\r
258      * needed for View Frustum Culling internally\r
259      */\r
260     this.geometry.computeBoundingSphere();\r
261     this.geometry.computeFaceNormals();\r
262     this.geometry.computeVertexNormals();\r
263   }\r
264 \r
265   /**\r
266    * generate a debug mesh for visualizing\r
267    * vertices and springs of the cloth\r
268    * and add it to scene for rendering\r
269    * @param {Scene} scene - Scene to add Debug Mesh to\r
270    */\r
271   createDebugMesh(scene) {\r
272     /**\r
273      * helper function to generate a single line\r
274      * between two Vertices with a given color\r
275      * @param {Vector3} from \r
276      * @param {Vector3} to \r
277      * @param {number} color \r
278      */\r
279     function addLine(from, to, color) {\r
280       let geometry = new THREE.Geometry();\r
281       geometry.vertices.push(from);\r
282       geometry.vertices.push(to);\r
283       let material = new THREE.LineBasicMaterial({ color: color, linewidth: 10 });\r
284       let line = new THREE.Line(geometry, material);\r
285       line.renderOrder = 1;\r
286       scene.add(line);\r
287     }\r
288     /**\r
289      * helper function to generate a small sphere\r
290      * at a given Vertex Position with color\r
291      * @param {Vector3} point \r
292      * @param {number} color \r
293      */\r
294     function addPoint(point, color) {\r
295       const geometry = new THREE.SphereGeometry(0.05, 32, 32);\r
296       const material = new THREE.MeshBasicMaterial({ color: color });\r
297       const sphere = new THREE.Mesh(geometry, material);\r
298       sphere.position.set(point.x, point.y, point.z);\r
299       scene.add(sphere);\r
300     }\r
301 \r
302     let lineColor = 0x000000;\r
303     let pointColor = 0xff00000;\r
304 \r
305     /**\r
306      * generate one line for each of the 6 springs\r
307      * and one point for each of the 4 vertices\r
308      * for all of the faces\r
309      */\r
310     for (let i in this.faces) {\r
311       let face = this.faces[i];\r
312       addLine(this.geometry.vertices[face.a], this.geometry.vertices[face.b], lineColor);\r
313       addLine(this.geometry.vertices[face.a], this.geometry.vertices[face.c], lineColor);\r
314       addLine(this.geometry.vertices[face.a], this.geometry.vertices[face.d], lineColor);\r
315       addLine(this.geometry.vertices[face.b], this.geometry.vertices[face.c], lineColor);\r
316       addLine(this.geometry.vertices[face.b], this.geometry.vertices[face.d], lineColor);\r
317       addLine(this.geometry.vertices[face.c], this.geometry.vertices[face.d], lineColor);\r
318 \r
319       addPoint(this.geometry.vertices[face.a], pointColor);\r
320       addPoint(this.geometry.vertices[face.b], pointColor);\r
321       addPoint(this.geometry.vertices[face.c], pointColor);\r
322       addPoint(this.geometry.vertices[face.d], pointColor);\r
323     }\r
324   }\r
325 \r
326   previousPositions = [];\r
327   time = 0;\r
328   /**\r
329    * \r
330    * @param {number} dt time in seconds since last frame\r
331    */\r
332   simulate(dt) {\r
333     for (let i in this.geometry.vertices) {\r
334       let acceleration = this.getAcceleration(i, dt);\r
335 \r
336       //acceleration.clampLength(0, 10);\r
337 \r
338       if (Math.abs(acceleration.length()) <= 10e-4) {\r
339         acceleration.set(0, 0, 0);\r
340       }\r
341  \r
342       let currentPosition = this.verlet(this.geometry.vertices[i].clone(), this.previousPositions[i].clone(), acceleration, dt);\r
343       //let currentPosition = this.euler(this.geometry.vertices[i], acceleration, dt);\r
344      \r
345       this.previousPositions[i].copy(this.geometry.vertices[i]);\r
346       this.geometry.vertices[i].copy(currentPosition);\r
347     }\r
348     \r
349     this.checkIntersect();\r
350     \r
351     this.time += dt;\r
352 \r
353     for (let face of this.faces) {\r
354       for (let spring of face.springs) {\r
355         spring.update(this.geometry.vertices);\r
356       }\r
357     }\r
358 \r
359     /**\r
360      * let THREE JS compute bounding sphere around generated mesh\r
361      * needed for View Frustum Culling internally\r
362      */\r
363 \r
364     this.geometry.verticesNeedUpdate = true;\r
365     this.geometry.elementsNeedUpdate = true;\r
366     this.geometry.computeBoundingSphere();\r
367     this.geometry.computeFaceNormals();\r
368     this.geometry.computeVertexNormals();\r
369 \r
370   }\r
371 \r
372 checkIntersect() {\r
373   let npw = this.numPointsWidth;\r
374   function getX(i, ) { return i % npw; }\r
375   function getY(i) { return Math.floor(i / npw); }\r
376   for (let i in this.geometry.vertices) {\r
377     for (let j in this.geometry.vertices) {\r
378       this.vertexRigidness[i] = false;\r
379       this.vertexRigidness[j] = false;\r
380       if (i == j || (Math.abs(getX(i) - getX(j)) == 1 && Math.abs(getY(i) - getY(j)) == 1))\r
381         continue;\r
382       let posI = this.geometry.vertices[i];\r
383       let posJ = this.geometry.vertices[j];\r
384       let dist = posI.distanceTo(posJ);\r
385       const collisionDistance = 0.5;\r
386       if (dist < collisionDistance) {\r
387         this.vertexRigidness[i] = true;\r
388         this.vertexRigidness[j] = true;\r
389         let diff = this.geometry.vertices[i].clone().sub(this.geometry.vertices[j]).normalize().multiplyScalar((collisionDistance - dist) * 1.001 / 2);\r
390         this.geometry.vertices[i].add(diff);\r
391         this.geometry.vertices[j].sub(diff);\r
392         console.log(this.geometry.vertices[i].distanceTo(this.geometry.vertices[j]));\r
393       }\r
394     }\r
395   }\r
396 }\r
397 \r
398 /**\r
399  * Equation of motion for each vertex which represents the acceleration \r
400  * @param {number} vertexIndex The index of the current vertex whose acceleration should be calculated\r
401  *  @param {number} dt The time passed since last frame\r
402  */\r
403 getAcceleration(vertexIndex, dt) {\r
404   if (this.fixedPoints.includes(parseInt(vertexIndex)) ||\r
405       this.vertexRigidness[vertexIndex]) {\r
406     return new THREE.Vector3(0, 0, 0);\r
407   }\r
408 \r
409   let externalForce = this.externalForces[vertexIndex];\r
410   let vertex = this.geometry.vertices[vertexIndex];//.add(externalForce);\r
411 \r
412   // Mass of vertex\r
413   let M = this.vertexWeights[vertexIndex];\r
414   // constant gravity\r
415   let g = new THREE.Vector3(0, -9.8, 0);\r
416   // stiffness\r
417   let k = 500;\r
418 \r
419   // Wind vector\r
420   let fWind = new THREE.Vector3(\r
421     Math.sin(vertex.x * vertex.y * this.time),\r
422     Math.cos(vertex.z * this.time),\r
423     Math.sin(Math.cos(5 * vertex.x * vertex.y * vertex.z))\r
424   );\r
425 \r
426   /**\r
427    * constant determined by the properties of the surrounding fluids (air)\r
428    * achievement of cloth effects through try out\r
429    * */\r
430   let a = 0.1;\r
431   \r
432   let velocity = new THREE.Vector3(\r
433     (this.previousPositions[vertexIndex].x - vertex.x) / dt,\r
434     (this.previousPositions[vertexIndex].y - vertex.y) / dt,\r
435     (this.previousPositions[vertexIndex].z - vertex.z) / dt\r
436   );\r
437 \r
438   //console.log(velocity, vertex, this.previousPositions[vertexIndex]);\r
439 \r
440   let fAirResistance = velocity.multiply(velocity).multiplyScalar(-a);\r
441   \r
442   let springSum = new THREE.Vector3(0, 0, 0);\r
443 \r
444   // Get the bounding springs and add them to the needed springs\r
445   // TODO: optimize\r
446 \r
447   const numPointsX = this.numPointsWidth;\r
448   const numPointsY = this.numPointsHeight;\r
449   const numFacesX = numPointsX - 1;\r
450   const numFacesY = numPointsY - 1;\r
451 \r
452   function getFaceIndex(x, y) {\r
453     return y * numFacesX + x;\r
454   }\r
455 \r
456   let indexX = vertexIndex % numPointsX;\r
457   let indexY = Math.floor(vertexIndex / numPointsX);\r
458 \r
459   let springs = [];\r
460 \r
461   // 0  oben\r
462   // 1  links\r
463   // 2  oben links  -> unten rechts diagonal\r
464   // 3  oben rechts -> unten links diagonal\r
465   // 4  rechts\r
466   // 5  unten\r
467 \r
468   let ul = indexX > 0 && indexY < numPointsY - 1;\r
469   let ur = indexX < numPointsX - 1 && indexY < numPointsY - 1;\r
470   let ol = indexX > 0 && indexY > 0;\r
471   let or = indexX < numPointsX - 1 && indexY > 0;\r
472 \r
473   if (ul) {\r
474     let faceUL = this.faces[getFaceIndex(indexX - 1, indexY)];\r
475     springs.push(faceUL.springs[3]);\r
476     if (!ol)\r
477       springs.push(faceUL.springs[0]);\r
478     springs.push(faceUL.springs[4]);\r
479   }\r
480   if (ur) {\r
481     let faceUR = this.faces[getFaceIndex(indexX, indexY)];\r
482     springs.push(faceUR.springs[2]);\r
483     if (!or)\r
484       springs.push(faceUR.springs[0]);\r
485     if (!ul)\r
486       springs.push(faceUR.springs[1]);\r
487   }\r
488   if (ol) {\r
489     let faceOL = this.faces[getFaceIndex(indexX - 1, indexY - 1)];\r
490     springs.push(faceOL.springs[2]);\r
491     springs.push(faceOL.springs[4]);\r
492     springs.push(faceOL.springs[5]);\r
493   }\r
494   if (or) {\r
495     let faceOR = this.faces[getFaceIndex(indexX , indexY - 1)];\r
496     springs.push(faceOR.springs[3]);\r
497     if (!ol)\r
498       springs.push(faceOR.springs[1]);\r
499     springs.push(faceOR.springs[5]);\r
500   }\r
501 \r
502   for (let spring of springs) {\r
503     let springDirection = spring.getDirection(this.geometry.vertices);\r
504 \r
505     if (spring.index1 == vertexIndex)\r
506       springDirection.multiplyScalar(-1);\r
507 \r
508     springSum.add(springDirection.multiplyScalar(k * (spring.restLength - spring.currentLength)));\r
509   }\r
510   \r
511   let result = new THREE.Vector3(1, 1, 1);\r
512   result.multiplyScalar(M).multiply(g).add(fWind).add(externalForce).add(fAirResistance).sub(springSum);\r
513 \r
514   document.getElementById("Output").innerText = "SpringSum: " + Math.floor(springSum.y);\r
515 \r
516   let threshold = 1;\r
517   let forceReduktion = 0.8;\r
518   if(Math.abs(externalForce.z) > threshold){\r
519     externalForce.z *= forceReduktion;\r
520   } else {\r
521     externalForce.z = 0;\r
522   }\r
523 \r
524   if(Math.abs(externalForce.y) > threshold){\r
525     externalForce.y *= forceReduktion;\r
526   } else {\r
527     externalForce.y = 0;\r
528   }\r
529 \r
530   if(Math.abs(externalForce.x) > threshold){\r
531     externalForce.x *= forceReduktion;\r
532   } else {\r
533     externalForce.x = 0;\r
534   }\r
535     \r
536   \r
537 \r
538   return result;\r
539 }\r
540 \r
541 /**\r
542  * The Verlet algorithm as an integrator \r
543  * to get the next position of a vertex  \r
544  * @param {Vector3} currentPosition \r
545  * @param {Vector3} previousPosition \r
546  * @param {Vector3} acceleration \r
547  * @param {number} passedTime The delta time since last frame\r
548  */\r
549 verlet(currentPosition, previousPosition, acceleration, passedTime) {\r
550   // verlet algorithm\r
551   // next position = 2 * current Position - previous position + acceleration * (passed time)^2\r
552   // acceleration (dv/dt) = F(net)\r
553   // Dependency for one vertex: gravity, fluids/air, springs\r
554   const DRAG = 0.96;\r
555   let nextPosition = new THREE.Vector3(\r
556     (currentPosition.x - previousPosition.x) * DRAG + currentPosition.x + acceleration.x * (passedTime * passedTime),\r
557     (currentPosition.y - previousPosition.y) * DRAG + currentPosition.y + acceleration.y * (passedTime * passedTime),\r
558     (currentPosition.z - previousPosition.z) * DRAG + currentPosition.z + acceleration.z * (passedTime * passedTime),\r
559   );\r
560 \r
561   // let nextPosition = new THREE.Vector3(\r
562   //   (2 * currentPosition.x) - previousPosition.x + acceleration.x * (passedTime * passedTime),\r
563   //   (2 * currentPosition.y) - previousPosition.y + acceleration.y * (passedTime * passedTime),\r
564   //   (2 * currentPosition.z) - previousPosition.z + acceleration.z * (passedTime * passedTime),\r
565   // );\r
566 \r
567   return nextPosition;\r
568 }\r
569 \r
570 euler(currentPosition, acceleration, passedTime) {\r
571   let nextPosition = new THREE.Vector3(\r
572     currentPosition.x + acceleration.x * passedTime,\r
573     currentPosition.y + acceleration.y * passedTime,\r
574     currentPosition.z + acceleration.z * passedTime,\r
575   );\r
576 \r
577   return nextPosition;\r
578 }\r
579 \r
580 wind(intersects) {\r
581   let intersect = intersects[0];\r
582   this.externalForces[intersect.face.a].z -= this.windForce;\r
583   this.externalForces[intersect.face.b].z -= this.windForce;\r
584   this.externalForces[intersect.face.c].z -= this.windForce;\r
585 }\r
586 \r
587 mousePressed = false;\r
588 mouseMoved = false;\r
589 intersects;\r
590 \r
591 mousePress(intersects){\r
592   this.mousePressed = true;\r
593   this.intersects = intersects;\r
594 \r
595 }\r
596 \r
597 mouseMove(mousePos){\r
598   this.mouseMoved = true;\r
599   if(this.mousePressed){\r
600     let intersect = this.intersects[0];\r
601     this.externalForces[intersect.face.a].add(mousePos.clone().sub(this.geometry.vertices[intersect.face.a]).multiplyScalar(90));\r
602     /*\r
603     this.geometry.vertices[intersect.face.a].x = mousePos.x;\r
604     this.geometry.vertices[intersect.face.a].y = mousePos.y;\r
605     this.geometry.vertices[intersect.face.a].z = mousePos.z;\r
606   */  \r
607   }\r
608 }\r
609 \r
610 mouseRelease(){\r
611   this.mousePressed = false;\r
612 }\r
613 \r
614 }\r
615 \r