-
Notifications
You must be signed in to change notification settings - Fork 7
/
RigidSolidChain.html
480 lines (422 loc) · 12.6 KB
/
RigidSolidChain.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HTML5 Physics simulation</title>
<script type="text/javascript">
var pi = 3.14159265359;
var console = []
//Vector class + math
function Vector(x,y) { this.x = x; this.y = y; }
function addV(a,b) { return new Vector(a.x+b.x, a.y+b.y); }
function subV(a,b) { return new Vector(a.x-b.x, a.y-b.y); }
function mulV(a,k) { return new Vector(a.x*k, a.y *k); }
function dotV(a,b) { return a.x*b.x+a.y*b.y; }
function crossKV(k,v) { return new Vector(-v.y*k, v.x *k); }
function crossVV(a,b) { return a.x*b.y-a.y*b.x; }
function norm2V(a) { return dotV(a,a); }
function lengthV(a) { return Math.sqrt(norm2V(a,a)); }
function norm2(a) { return mulV(a, 1.0/lengthV(a)); }
function RotV(a, v) { return new Vector(Math.cos(a)*v.x - Math.sin(a)*v.y, Math.sin(a)*v.x+Math.cos(a)*v.y); }
function InvRotV(a, v) { return new Vector(Math.cos(a)*v.x + Math.sin(a)*v.y, -Math.sin(a)*v.x+Math.cos(a)*v.y); }
// Frame of reference
function Frame(x, y, r) { this.x = x; this.y = y; this.r = r; }
function FrameV(v, r) { this.x = v.x; this.y = v.y; this.r = r; }
function addF(a,b) { return new Frame(a.x+b.x, a.y+b.y, a.r+b.r); }
function subF(a,b) { return new Frame(a.x-b.x, a.y-b.y, a.r-b.r); }
function mulF(a,k) { return new Frame(a.x*k, a.y*k, a.r*k); }
function dotF(a,b) { return a.x*b.x+a.y*b.y+a.r*b.r; }
function TransFV(f,p) { return addV(new Vector(f.x, f.y), RotV(f.r, p) ); }
function InvTransFV(f,p) { return addV(InvRotV(f.r, p), new Vector(f.x, f.y) ); }
function getPosF(f) { return new Vector(f.x, f.y); }
// velocities, positions and radius
function State(p, v, b, M, I) { this.p = p; this.v = v; this.b = b; this.M=M; this.I = I; }
function getVelS(f, p) { return addV( f.v, crossKV( f.v.r, subV(p,f.p) ) ); }
function getPosS(f, p) { return TransFV( f.p, p ); }
var States = [];
var intergrationStep = 1./240;
//drawing helpers
function drawSphere(context, p, radius, color)
{
context.beginPath();
context.fillStyle=color;
context.arc(p.x,p.y,radius,0,Math.PI*2,true);
context.closePath();
context.fill();
}
function drawCross(context, p, radius, color)
{
drawLine( addV(p, new Vector(-1/5,0)),addV(p, new Vector(1/5,0)));
drawLine( addV(p, new Vector(0,-1/5)),addV(p, new Vector(0,1/5)));
}
function drawPoly(context, state, color)
{
for(var i=0;i<state.b.length-1;i++)
{
var p1 = TransFV(state.p, state.b[i]);
var p2 = TransFV(state.p, state.b[i+1]);
drawLine(p1,p2);
}
var p1 = TransFV(state.p, state.b[state.b.length-1]);
var p2 = TransFV(state.p, state.b[0]);
drawLine(p1,p2);
}
function drawLine( p1,p2)
{
context.beginPath();
context.fillStyle="#ff0000";
context.moveTo(p1.x*30,p1.y*30);
context.lineTo(p2.x*30,p2.y*30);
context.stroke();
}
//
//multiply 2 matrices made out of vectors
//
function MulMatFF(m1, m2)
{
var O = [];
for(var j=0;j<m1.length;j++)
{
O[j]=[];
for(var i=0;i<m2[0].length;i++)
{
var tmp=0;
for(var k=0;k<m1[i].length;k++)
{
tmp += dotF(m1[j][k], m2[k][i]);
}
O[j][i] = tmp;
}
}
return O;
}
//
//multiply 2 matrices made out of vectors
//
function MulMatSF(s, f)
{
var O = [];
for(var j=0;j<f.length;j++)
{
O[j]=[];
for(var i=0;i<f[0].length;i++)
{
O[j][i] = new FrameV( mulV(f[j][i], s[j].M), f[j][i].r*s[j].I);
}
}
return O;
}
//
// multiply 2 matrices made out of scalars
//
function MulMatKK(m1, m2)
{
var O = [];
for(var j=0;j<m1.length;j++)
{
O[j]=[];
for(var i=0;i<m2[0].length;i++)
{
var tmp=0;
for(var k=0;k<m1[i].length;k++)
{
tmp += (m1[j][k] * m2[k][i]);
}
O[j][i] = tmp;
}
}
return O;
}
//
// multiply 2 matrices, one made out of vectors and the other made out of scalars
//
function MulMatFK(m1, m2)
{
var O = [];
for(var j=0;j<m1.length;j++)
{
O[j]=[];
for(var i=0;i<m2[0].length;i++)
{
var tmp= new Frame(0,0,0);
for(var k=0;k<m1[i].length;k++)
{
tmp = addF(mulF(m1[j][k], m2[k][i]), tmp);
}
O[j][i] = tmp;
}
}
return O;
}
//
// addV 2 matrices made out of scalars
//
function addVMatKK(m1, m2)
{
var O = [];
for(var j=0;j<m1.length;j++)
{
O[j]=[];
for(var i=0;i<m1[0].length;i++)
{
O[j][i] = m1[j][i] + m2[j][i];
}
}
return O;
}
//
// Transpose matrix
//
function TransposeMat(m)
{
var O = [];
for(var j=0;j<m[0].length;j++)
{
O[j]=[];
for(var i=0;i<m.length;i++)
{
O[j][i] = m[i][j];
}
}
return O;
}
//
// Get Jtranspose * lambda
//
function GetMinvJtlambda(J, Minv, velT, bias)
{
var JvelT = MulMatFF(J, velT);
if (bias!=undefined)
JvelT = addVMatKK(JvelT, bias);
var Jt = TransposeMat(J);
var MinvJt = MulMatSF(Minv, Jt);
var JJt = MulMatFF(J, MinvJt );
var invJJt = invertMat( JJt );
var lambda = MulMatKK( invJJt, JvelT);
var Jtlambda = MulMatFK( Jt, lambda);
var MinvJtlambda = MulMatSF(Minv, Jtlambda);
return MinvJtlambda;
}
//
// Distance constraint, note how the jacobian is a small matrix
// Inputs:
// bodyA, bodyB: particle index
//
function DistanceConstraint(bodyA, Pa, bodyB, Pb)
{
// compute jacobian---------
var J = []
var PaPb = subV(Pb, Pa);
var PbPa = subV(Pa, Pb);
var Ca = getPosF(States[bodyA].p);
var Cb = getPosF(States[bodyB].p);
var CaPa = subV(Pa, Ca);
var CbPb = subV(Pb, Cb);
var Wa = -crossVV(CaPa, PaPb);
var Wb = crossVV(CbPb, PaPb);
J[0] = [ new FrameV(mulV(mulV(PaPb,-1),2), 2*Wa), new FrameV(mulV(PaPb,2), 2*Wb) ];
// compute vels--------------
var vel = [[ States[bodyA].v, States[bodyB].v ]];
var velT = TransposeMat(vel);
// compute bias---------------
var betaoverh = .5/intergrationStep;
var C = dotV(PaPb, PaPb);
// if the constraint is zero (is met) then bail out, the jacobian is zero and
// obviously it wont have an inverse
if (C<= 1e-15)
return;
var bias = [[betaoverh * C]];
//just the diagonal matrix -----
var Minv = [ States[bodyA], States[bodyB] ];
// solver-----------------------
var MinvJtlambda = GetMinvJtlambda(J, Minv, velT, bias)
// update speeds-----------------
States[bodyA].v = subF(States[bodyA].v, MinvJtlambda[0][0]);
States[bodyB].v = subF(States[bodyB].v, MinvJtlambda[1][0]);
}
//
// Integrate step
//
function integrate(t)
{
for(var i=0;i<States.length;i++)
{
States[i].p = addF(States[i].p ,mulF(States[i].v, t));
//States.v[i] = mulV(States.v[i], .98);
}
}
function SimulationLoop()
{
// render chain
{
context= myCanvas.getContext('2d');
context.clearRect(0,0,600,600);
for(var i=0;i<States.length;i++)
{
drawPoly(context, States[i], "#ff0000");
}
}
// apply gravity
for(var i=1;i<States.length;i++)
States[i].v.y+=9.8/10;
// compute tentative velocities
integrate(intergrationStep);
// apply constraints
var iterations = 4;
for(var iter=0;iter<iterations;iter++)
{
for(var i=0;i<States.length-1;i++)
{
var Pa = getPosS( States[i], States[i].b[3]);
var Pb = getPosS( States[i+1], States[i+1].b[0]);
DistanceConstraint(i, Pa, i+1, Pb)
}
}
}
function init()
{
var cubeVerts = [
new Vector(-1,-1),
new Vector(1,-1),
new Vector(1,1),
new Vector(0, 1),
new Vector(-1,1)
];
var linkVerts = [ new Vector(0, -0.5), new Vector(-0.1, -0.3), new Vector(-0.1, 0.3), new Vector(0, 0.5), new Vector(0.1, 0.3), new Vector(0.1, -0.3)];
// create top hook
var p = new Frame(10,0, 0*pi/180);
var v = new Frame(0,0, 0);
States.push( new State(p, v, cubeVerts, 0, 0) );
// create chain
for(var i=0;i<15;i++)
{
var l = Math.sqrt(.5)
var p = new Frame(10+i*l + l*.5,1+i*l + l*.5, -45*pi/180);
var v = new Frame(0,0, 0);
States.push( new State(p, v, linkVerts, 5, 5) );
}
setInterval(SimulationLoop,10);
}
//
// Inverts a matrix (taken from http://blog.acipo.com/matrix-inversion-in-javascript/)
//
function invertMat(M){
// I use Guassian Elimination to calculate the inverse:
// (1) 'augment' the matrix (left) by the identity (on the right)
// (2) Turn the matrix on the left into the identity by elemetry row ops
// (3) The matrix on the right is the inverse (was the identity matrix)
// There are 3 elemtary row ops: (I combine b and c in my code)
// (a) Swap 2 rows
// (b) Multiply a row by a scalar
// (c) addV 2 rows
//if the matrix isn't square: exit (error)
if(M.length !== M[0].length){return;}
//create the identity matrix (I), and a copy (C) of the original
var i=0, ii=0, j=0, dim=M.length, e=0, t=0;
var I = [], C = [];
for(i=0; i<dim; i+=1){
// Create the row
I[I.length]=[];
C[C.length]=[];
for(j=0; j<dim; j+=1){
//if we're on the diagonal, put a 1 (for identity)
if(i==j){ I[i][j] = 1; }
else{ I[i][j] = 0; }
// Also, make the copy of the original
C[i][j] = M[i][j];
}
}
// Perform elementary row operations
for(i=0; i<dim; i+=1){
// get the element e on the diagonal
e = C[i][i];
// if we have a 0 on the diagonal (we'll need to swap with a lower row)
if(e==0){
//look through every row below the i'th row
for(ii=i+1; ii<dim; ii+=1){
//if the ii'th row has a non-0 in the i'th col
if(C[ii][i] != 0){
//it would make the diagonal have a non-0 so swap it
for(j=0; j<dim; j++){
e = C[i][j]; //temp store i'th row
C[i][j] = C[ii][j];//replace i'th row by ii'th
C[ii][j] = e; //repace ii'th by temp
e = I[i][j]; //temp store i'th row
I[i][j] = I[ii][j];//replace i'th row by ii'th
I[ii][j] = e; //repace ii'th by temp
}
//don't bother checking other rows since we've swapped
break;
}
}
//get the new diagonal
e = C[i][i];
//if it's still 0, not invertable (error)
if(e==0){return}
}
// Scale this row down by e (so we have a 1 on the diagonal)
for(j=0; j<dim; j++){
C[i][j] = C[i][j]/e; //apply to original matrix
I[i][j] = I[i][j]/e; //apply to identity
}
// subVtract this row (scaled appropriately for each row) from ALL of
// the other rows so that there will be 0's in this column in the
// rows above and below this one
for(ii=0; ii<dim; ii++){
// Only apply to other rows (we want a 1 on the diagonal)
if(ii==i){continue;}
// We want to change this element to 0
e = C[ii][i];
// subVtract (the row above(or below) scaled by e) from (the
// current row) but start at the i'th column and assume all the
// stuff left of diagonal is 0 (which it should be if we made this
// algorithm correctly)
for(j=0; j<dim; j++){
C[ii][j] -= e*C[i][j]; //apply to original matrix
I[ii][j] -= e*I[i][j]; //apply to identity
}
}
}
//we've done all operations, C should be the identity
//matrix I should be the inverse:
return I;
}
</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-3425939-7', 'auto');
ga('send', 'pageview');
</script>
<style type="text/css">
<!--
body { background-color:#ededed; font:norm2al 12px/18px Arial, Helvetica, sans-serif; }
h1 { display:block; width:600px; margin:20px auto; paddVing-bottom:20px; font:norm2al 24px/30px Georgia, "Times New Roman", Times, serif; color:#333; text-shadow: 1px 2px 3px #ccc; border-bottom:1px solid #cbcbcb; }
#container { width:600px; margin:0 auto; }
#myCanvas { background:#fff; border:1px solid #cbcbcb; }
#nav { display:block; width:100%; text-align:center; }
#nav li { display:block; font-weight:bold; line-height:21px; text-shadow:1px 1px 1px #fff; width:100px; height:21px; paddVing:5px; margin:0 10px; background:#e0e0e0; border:1px solid #ccc; -moz-border-radius:4px;-webkit-border-radius:4px; border-radius:4px; float:left; }
#nav li a { color:#000; display:block; text-decoration:none; width:100%; height:100%; }
-->
</style>
</head>
<body onload="init()">
<h1>Rigid solid chain (sequential solver)</h1>
<div id="container">
<canvas id="myCanvas" width="600" height="600"></canvas>
<div id="text"></div>
<h2>Intro</h2>
This is a quick exercise to learn how constraints work in a physics simulator. This sample is using equality constraints for the joints</br>
</br>
This physics simulator is heavily based on Erin Catto's GDC2009 talk.</br>
</br>
</br>
<h2>Contact/Questions:</h2>
<my_github_account_username>[email protected]$.
</br>
</br>
</div>
</body>
</html>