]> gitweb.ps.run Git - cloth_sim/blob - Scripts/cloth.js
fix spring force calculation
[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   /**\r
102    * creates a rectangular piece of cloth\r
103    * takes the size of the cloth\r
104    * and the number of vertices it should be composed of\r
105    * @param {number} width - width of the cloth\r
106    * @param {number} height - height of the cloth\r
107    * @param {number} numPointsWidth - number of vertices in horizontal direction\r
108    * @param {number} numPointsHeight  - number of vertices in vertical direction\r
109    */\r
110   createBasic(width, height, numPointsWidth, numPointsHeight) {\r
111     /** resulting vertices and faces */\r
112     let vertices = [];\r
113     let faces = [];\r
114 \r
115     this.numPointsWidth = numPointsWidth;\r
116     this.numPointsHeight = numPointsHeight;\r
117 \r
118     /**\r
119      * distance between two vertices horizontally/vertically\r
120      * divide by the number of points minus one\r
121      * because there are (n - 1) lines between n vertices\r
122      */\r
123     let stepWidth = width / (numPointsWidth - 1);\r
124     let stepHeight = height / (numPointsHeight - 1);\r
125 \r
126     /**\r
127      * iterate over the number of vertices in x/y axis\r
128      * and add a new Vector3 to "vertices"\r
129      */\r
130     for (let y = 0; y < numPointsHeight; y++) {\r
131       for (let x = 0; x < numPointsWidth; x++) {\r
132         vertices.push(\r
133           new THREE.Vector3(x * stepWidth, height - y * stepHeight, 0)\r
134         );\r
135       }\r
136     }\r
137 \r
138     /**\r
139      * helper function to calculate index of vertex\r
140      * in "vertices" array based on its x and y positions\r
141      * in the mesh\r
142      * @param {number} x - x index of vertex\r
143      * @param {number} y - y index of vertex\r
144      */\r
145     function getVertexIndex(x, y) {\r
146       return y * numPointsWidth + x;\r
147     }\r
148 \r
149     /**\r
150      * generate faces based on 4 vertices\r
151      * and 6 springs each\r
152      */\r
153     for (let y = 0; y < numPointsHeight - 1; y++) {\r
154       for (let x = 0; x < numPointsWidth - 1; x++) {\r
155         let newFace = new Face(\r
156           getVertexIndex(x, y),\r
157           getVertexIndex(x, y + 1),\r
158           getVertexIndex(x + 1, y),\r
159           getVertexIndex(x + 1, y + 1),\r
160         );\r
161 \r
162         newFace.springs.push(new Spring(vertices, getVertexIndex(x, y), getVertexIndex(x + 1, y)));         // oben\r
163         newFace.springs.push(new Spring(vertices, getVertexIndex(x, y), getVertexIndex(x, y + 1)));         // links\r
164         newFace.springs.push(new Spring(vertices, getVertexIndex(x, y), getVertexIndex(x + 1, y + 1)));     // oben links  -> unten rechts diagonal\r
165         newFace.springs.push(new Spring(vertices, getVertexIndex(x + 1, y), getVertexIndex(x, y + 1)));     // oben rechts -> unten links diagonal\r
166         newFace.springs.push(new Spring(vertices, getVertexIndex(x + 1, y), getVertexIndex(x + 1, y + 1))); // rechts\r
167         newFace.springs.push(new Spring(vertices, getVertexIndex(x, y + 1), getVertexIndex(x + 1, y + 1))); // unten\r
168 \r
169         faces.push(newFace);\r
170       }\r
171     }\r
172 \r
173     /**\r
174      * call createExplicit\r
175      * with generated vertices and faces\r
176      */\r
177     this.createExplicit(vertices, faces);\r
178 \r
179     /**\r
180      * hand cloth from left and right upper corners\r
181      */\r
182     this.vertexRigidness[0] = true;\r
183     this.vertexRigidness[numPointsWidth-1] = true;\r
184   }\r
185 \r
186   /**\r
187    * Generate THREE JS Geometry\r
188    * (list of vertices and list of indices representing triangles)\r
189    * and calculate the weight of each face and split it between\r
190    * surrounding vertices\r
191    * @param {Array<Vector3>} vertices \r
192    * @param {Array<Face>} faces \r
193    */\r
194   createExplicit(vertices, faces) {\r
195 \r
196     /**\r
197      * Copy vertices and initialize vertex weights to 0\r
198      */\r
199     for (let i in vertices) {\r
200       this.geometry.vertices.push(vertices[i].clone());\r
201       this.previousPositions.push(vertices[i].clone());\r
202       // this.geometry.vertices.push(vertices[i]);\r
203       // this.previousPositions.push(vertices[i]);\r
204       this.vertexWeights.push(0);\r
205       this.vertexRigidness.push(false);\r
206     }\r
207     /**\r
208      * copy faces,\r
209      * generate two triangles per face,\r
210      * calculate weight of face as its area\r
211      * and split between the 4 vertices\r
212      */\r
213     for (let i in faces) {\r
214       let face = faces[i];\r
215 \r
216       /** copy faces to class member */\r
217       this.faces.push(face);\r
218 \r
219       /** generate triangles */\r
220       this.geometry.faces.push(new THREE.Face3(\r
221         face.a, face.b, face.c\r
222       ));\r
223       this.geometry.faces.push(new THREE.Face3(\r
224         face.c, face.b, face.d\r
225       ));\r
226 \r
227       /**\r
228        * calculate area of face as combined area of\r
229        * its two composing triangles\r
230        */\r
231       let xLength = vectorLength(this.geometry.vertices[face.b], this.geometry.vertices[face.a]);\r
232       let yLength = vectorLength(this.geometry.vertices[face.c], this.geometry.vertices[face.a]);\r
233       let weight = xLength * yLength / 2;\r
234 \r
235       xLength = vectorLength(this.geometry.vertices[face.b], this.geometry.vertices[face.d]);\r
236       yLength = vectorLength(this.geometry.vertices[face.c], this.geometry.vertices[face.d]);\r
237       weight += xLength * yLength / 2;\r
238 \r
239       /**\r
240        * split weight equally between four surrounding vertices\r
241        */\r
242       this.vertexWeights[face.a] += weight / 4;\r
243       this.vertexWeights[face.b] += weight / 4;\r
244       this.vertexWeights[face.c] += weight / 4;\r
245       this.vertexWeights[face.d] += weight / 4;\r
246     }\r
247 \r
248     /**\r
249      * let THREE JS compute bounding sphere around generated mesh\r
250      * needed for View Frustum Culling internally\r
251      */\r
252     this.geometry.computeBoundingSphere();\r
253     this.geometry.computeFaceNormals();\r
254   }\r
255 \r
256   /**\r
257    * generate a debug mesh for visualizing\r
258    * vertices and springs of the cloth\r
259    * and add it to scene for rendering\r
260    * @param {Scene} scene - Scene to add Debug Mesh to\r
261    */\r
262   createDebugMesh(scene) {\r
263     /**\r
264      * helper function to generate a single line\r
265      * between two Vertices with a given color\r
266      * @param {Vector3} from \r
267      * @param {Vector3} to \r
268      * @param {number} color \r
269      */\r
270     function addLine(from, to, color) {\r
271       let geometry = new THREE.Geometry();\r
272       geometry.vertices.push(from);\r
273       geometry.vertices.push(to);\r
274       let material = new THREE.LineBasicMaterial({ color: color, linewidth: 10 });\r
275       let line = new THREE.Line(geometry, material);\r
276       line.renderOrder = 1;\r
277       scene.add(line);\r
278     }\r
279     /**\r
280      * helper function to generate a small sphere\r
281      * at a given Vertex Position with color\r
282      * @param {Vector3} point \r
283      * @param {number} color \r
284      */\r
285     function addPoint(point, color) {\r
286       const geometry = new THREE.SphereGeometry(0.05, 32, 32);\r
287       const material = new THREE.MeshBasicMaterial({ color: color });\r
288       const sphere = new THREE.Mesh(geometry, material);\r
289       sphere.position.set(point.x, point.y, point.z);\r
290       scene.add(sphere);\r
291     }\r
292 \r
293     let lineColor = 0x000000;\r
294     let pointColor = 0xff00000;\r
295 \r
296     /**\r
297      * generate one line for each of the 6 springs\r
298      * and one point for each of the 4 vertices\r
299      * for all of the faces\r
300      */\r
301     for (let i in this.faces) {\r
302       let face = this.faces[i];\r
303       addLine(this.geometry.vertices[face.a], this.geometry.vertices[face.b], lineColor);\r
304       addLine(this.geometry.vertices[face.a], this.geometry.vertices[face.c], lineColor);\r
305       addLine(this.geometry.vertices[face.a], this.geometry.vertices[face.d], lineColor);\r
306       addLine(this.geometry.vertices[face.b], this.geometry.vertices[face.c], lineColor);\r
307       addLine(this.geometry.vertices[face.b], this.geometry.vertices[face.d], lineColor);\r
308       addLine(this.geometry.vertices[face.c], this.geometry.vertices[face.d], lineColor);\r
309 \r
310       addPoint(this.geometry.vertices[face.a], pointColor);\r
311       addPoint(this.geometry.vertices[face.b], pointColor);\r
312       addPoint(this.geometry.vertices[face.c], pointColor);\r
313       addPoint(this.geometry.vertices[face.d], pointColor);\r
314     }\r
315   }\r
316 \r
317   previousPositions = [];\r
318   time = 0;\r
319   /**\r
320    * \r
321    * @param {number} dt time in seconds since last frame\r
322    */\r
323   simulate(dt) {\r
324     for (let i in this.geometry.vertices) {\r
325       let acceleration = this.getAcceleration(i, dt);\r
326 \r
327       //acceleration.clampLength(0, 10);\r
328 \r
329       if (Math.abs(acceleration.length()) <= 10e-4) {\r
330         acceleration.set(0, 0, 0);\r
331       }\r
332  \r
333       let currentPosition = this.verlet(this.geometry.vertices[i].clone(), this.previousPositions[i].clone(), acceleration, dt);\r
334       //let currentPosition = this.euler(this.geometry.vertices[i], acceleration, dt);\r
335      \r
336       this.previousPositions[i].copy(this.geometry.vertices[i]);\r
337       this.geometry.vertices[i].copy(currentPosition);\r
338     }\r
339     //console.log(this.getAcceleration(1, dt));\r
340     \r
341     this.time += dt;\r
342 \r
343     for (let face of this.faces) {\r
344       for (let spring of face.springs) {\r
345         spring.update(this.geometry.vertices);\r
346       }\r
347     }\r
348 \r
349     /**\r
350      * let THREE JS compute bounding sphere around generated mesh\r
351      * needed for View Frustum Culling internally\r
352      */\r
353 \r
354     this.geometry.verticesNeedUpdate = true;\r
355     this.geometry.elementsNeedUpdate = true;\r
356     this.geometry.computeBoundingSphere();\r
357     this.geometry.computeFaceNormals();\r
358 \r
359   }\r
360 \r
361 \r
362 \r
363 /**\r
364  * Equation of motion for each vertex which represents the acceleration \r
365  * @param {number} vertexIndex The index of the current vertex whose acceleration should be calculated\r
366  *  @param {number} dt The time passed since last frame\r
367  */\r
368 getAcceleration(vertexIndex, dt) {\r
369   if (this.vertexRigidness[vertexIndex])\r
370     return new THREE.Vector3(0, 0, 0);\r
371 \r
372   let vertex = this.geometry.vertices[vertexIndex];\r
373 \r
374   // Mass of vertex\r
375   let M = this.vertexWeights[vertexIndex];\r
376   // constant gravity\r
377   let g = new THREE.Vector3(0, -9.8, 0);\r
378   // stiffness\r
379   let k = 1000;\r
380 \r
381   // Wind vector\r
382   let fWind = new THREE.Vector3(\r
383     Math.sin(vertex.x * vertex.y * this.time),\r
384     Math.cos(vertex.z * this.time),\r
385     Math.sin(Math.cos(5 * vertex.x * vertex.y * vertex.z))\r
386   );\r
387 \r
388   /**\r
389    * constant determined by the properties of the surrounding fluids (air)\r
390    * achievement of cloth effects through try out\r
391    * */\r
392   let a = 0.1;\r
393   \r
394   let velocity = new THREE.Vector3(\r
395     (this.previousPositions[vertexIndex].x - vertex.x) / dt,\r
396     (this.previousPositions[vertexIndex].y - vertex.y) / dt,\r
397     (this.previousPositions[vertexIndex].z - vertex.z) / dt\r
398   );\r
399 \r
400   //console.log(velocity, vertex, this.previousPositions[vertexIndex]);\r
401 \r
402   let fAirResistance = velocity.multiply(velocity).multiplyScalar(-a);\r
403   \r
404   let springSum = new THREE.Vector3(0, 0, 0);\r
405 \r
406   // Get the bounding springs and add them to the needed springs\r
407   // TODO: optimize\r
408 \r
409   const numPointsX = this.numPointsWidth;\r
410   const numPointsY = this.numPointsHeight;\r
411   const numFacesX = numPointsX - 1;\r
412   const numFacesY = numPointsY - 1;\r
413 \r
414   function getFaceIndex(x, y) {\r
415     return y * numFacesX + x;\r
416   }\r
417 \r
418   let indexX = vertexIndex % numPointsX;\r
419   let indexY = Math.floor(vertexIndex / numPointsX);\r
420 \r
421   let springs = [];\r
422 \r
423   // 0  oben\r
424   // 1  links\r
425   // 2  oben links  -> unten rechts diagonal\r
426   // 3  oben rechts -> unten links diagonal\r
427   // 4  rechts\r
428   // 5  unten\r
429 \r
430   let ul = indexX > 0 && indexY < numPointsY - 1;\r
431   let ur = indexX < numPointsX - 1 && indexY < numPointsY - 1;\r
432   let ol = indexX > 0 && indexY > 0;\r
433   let or = indexX < numPointsX - 1 && indexY > 0;\r
434 \r
435   if (ul) {\r
436     let faceUL = this.faces[getFaceIndex(indexX - 1, indexY)];\r
437     springs.push(faceUL.springs[3]);\r
438     if (!ol)\r
439       springs.push(faceUL.springs[0]);\r
440     springs.push(faceUL.springs[4]);\r
441   }\r
442   if (ur) {\r
443     let faceUR = this.faces[getFaceIndex(indexX, indexY)];\r
444     springs.push(faceUR.springs[2]);\r
445     if (!or)\r
446       springs.push(faceUR.springs[0]);\r
447     if (!ul)\r
448       springs.push(faceUR.springs[1]);\r
449   }\r
450   if (ol) {\r
451     let faceOL = this.faces[getFaceIndex(indexX - 1, indexY - 1)];\r
452     springs.push(faceOL.springs[2]);\r
453     springs.push(faceOL.springs[4]);\r
454     springs.push(faceOL.springs[5]);\r
455   }\r
456   if (or) {\r
457     let faceOR = this.faces[getFaceIndex(indexX , indexY - 1)];\r
458     springs.push(faceOR.springs[3]);\r
459     if (!ol)\r
460       springs.push(faceOR.springs[1]);\r
461     springs.push(faceOR.springs[5]);\r
462   }\r
463 \r
464   for (let spring of springs) {\r
465     let springDirection = spring.getDirection(this.geometry.vertices);\r
466 \r
467     if (spring.index1 == vertexIndex)\r
468       springDirection.multiplyScalar(-1);\r
469 \r
470     springSum.add(springDirection.multiplyScalar(k * (spring.restLength - spring.currentLength)));\r
471   }\r
472   \r
473   let result = new THREE.Vector3(1, 1, 1);\r
474 \r
475   let temp = result.multiplyScalar(M).multiply(g).add(fWind).add(fAirResistance).clone();\r
476   result.sub(springSum);\r
477   document.getElementById("Output").innerText = "SpringSum: " + Math.floor(springSum.y) + "\nTemp: " + Math.floor(temp.y);\r
478 \r
479   return result;\r
480 }\r
481 \r
482 /**\r
483  * The Verlet algorithm as an integrator \r
484  * to get the next position of a vertex  \r
485  * @param {Vector3} currentPosition \r
486  * @param {Vector3} previousPosition \r
487  * @param {Vector3} acceleration \r
488  * @param {number} passedTime The delta time since last frame\r
489  */\r
490 verlet(currentPosition, previousPosition, acceleration, passedTime) {\r
491   // verlet algorithm\r
492   // next position = 2 * current Position - previous position + acceleration * (passed time)^2\r
493   // acceleration (dv/dt) = F(net)\r
494   // Dependency for one vertex: gravity, fluids/air, springs\r
495   const DRAG = 0.97;\r
496   let nextPosition = new THREE.Vector3(\r
497     (currentPosition.x - previousPosition.x) * DRAG + currentPosition.x + acceleration.x * (passedTime * passedTime),\r
498     (currentPosition.y - previousPosition.y) * DRAG + currentPosition.y + acceleration.y * (passedTime * passedTime),\r
499     (currentPosition.z - previousPosition.z) * DRAG + currentPosition.z + acceleration.z * (passedTime * passedTime),\r
500   );\r
501 \r
502   // let nextPosition = new THREE.Vector3(\r
503   //   (2 * currentPosition.x) - previousPosition.x + acceleration.x * (passedTime * passedTime),\r
504   //   (2 * currentPosition.y) - previousPosition.y + acceleration.y * (passedTime * passedTime),\r
505   //   (2 * currentPosition.z) - previousPosition.z + acceleration.z * (passedTime * passedTime),\r
506   // );\r
507 \r
508   return nextPosition;\r
509 }\r
510 \r
511 euler(currentPosition, acceleration, passedTime) {\r
512   let nextPosition = new THREE.Vector3(\r
513     currentPosition.x + acceleration.x * passedTime,\r
514     currentPosition.y + acceleration.y * passedTime,\r
515     currentPosition.z + acceleration.z * passedTime,\r
516   );\r
517 \r
518   return nextPosition;\r
519 }\r
520 \r
521 wind(intersects) {\r
522   let intersect = intersects[0];\r
523   this.geometry.vertices[intersect.face.a].z -= 0.05;\r
524   this.geometry.vertices[intersect.face.b].z -= 0.05;\r
525   this.geometry.vertices[intersect.face.c].z -= 0.05;\r
526 }\r
527 \r
528 }\r
529 \r