-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathContactConstraints.html
750 lines (628 loc) · 19.9 KB
/
ContactConstraints.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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HTML5 Physics simulation</title>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({ tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]} });
</script>
<script type="text/javascript"
src="https://cdn.rawgit.com/mathjax/MathJax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</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>
<script type="text/javascript">
var pi = 3.14159265359;
//Vector class + math
function Vector(x,y, w) { 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,b) { return new Vector(a.x*b, a.y *b); }
function dotV(a,b) { return a.x*b.x+a.y*b.y; }
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)); }
// velocities, positions and radius
function State(p, v) { this.p = p; this.v = v; }
var States = [];
var r = [];
var intergrationStep = 0.05;
//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 drawLine( p1,p2)
{
context.beginPath();
context.fillStyle="#ff0000";
x = p1.x;
y = p1.y;
context.moveTo(x,y);
x = p2.x;
y = p2.y;
context.lineTo(x,y);
context.stroke();
}
//
//multiply 2 matrices made out of vectors
//
function MulMatVV(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 += dotV(m1[j][k], m2[k][i]);
//tmp += (m1[j][k] * m2[k][i]);
}
O[j][i] = tmp;
}
}
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 += dotV(m1[j][k], m2[k][i]);
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 MulMatVK(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 Vector(0,0);
for(var k=0;k<m1[i].length;k++)
{
//tmp += dotV(m1[j][k], m2[k][i]);
tmp = addV(mulV(m1[j][k], m2[k][i]), tmp);
//tmp += mulV(m2[k][i], m1[j][k]);
}
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 GetJtlambda(J, velT, bias)
{
var JvelT = MulMatVV(J, velT);
if (bias!=undefined)
{
JvelT = addVMatKK(JvelT, bias);
}
var Jt = TransposeMat(J);
var JJt = MulMatVV(J, Jt );
var invJJt = invertMat( JJt );
var lambda = MulMatKK( invJJt, JvelT);
var Jtlambda = MulMatVK( Jt, lambda);
return Jtlambda;
}
//
// Single particle pendulum, not using matrices (since the jacobian is a scalar)
// Inputs:
// body: particle index
// top: coordinates of the top of the chain
//
function PendulumUsingScalars(top, body)
{
//compute jacobian
var J = subV(States[body].p,top);
var Jt = J;
//compute vels
var vel = States[body].v;
var velT = vel;
//compute bias
var bias = undefined;
//solver
var JvelT = dotV(J,velT);
var JJt = dotV(J,Jt);
var invJJt = 1.0/ JJt;
var lambda = (invJJt*JvelT);
var Jtlambda = mulV(Jt, lambda);
//update speeds
States[body].v = subV( States[body].v, Jtlambda);
}
//
// Single particle pendulum, using matrices this time (despite that are not needed, but used to validate our math)
// Inputs:
// body: particle index
// top: coordinates of the top of the chain
//
function SinglePendulum(top, body)
{
//compute jacobian
var J = []
J[0] = [ subV(States[body].p,top) ];
//compute vels
var velT = [ ]
velT[0] = [ States[body].v ];
//compute bias
var distance = 10*10+10*10;
var betaoverh = .2/intergrationStep;
var C = .5*(norm2V(subV(States[body].p, top)) - distance);
var bias = [[]];
bias[0].push( betaoverh * C);
var biasT = TransposeMat(bias);
//solver
var Jtlambda = GetJtlambda(J, velT, bias)
//update speeds
States[body].v = subV(States[body].v, Jtlambda[0][0]);
}
//
// 2 particle pendulum, note how the jacobian becomes a matrix
// Inputs:
// body1, body2: particle index
// top:, coordinates of the top of the chain
//
function DoublePendulum(top, body1, body2)
{
//compute jacobian
var J = []
J[0] = [ subV(States[body1].p, top), new Vector(0,0) ];
J[1] = [ subV(States[body1].p, States[body2].p), subV(States[body2].p, States[body1].p) ];
//compute vels
var vel = [[ States[body1].v, States[body2].v ]];
var velT = TransposeMat(vel);
//compute bias
var bias = undefined;
//solver
var Jtlambda = GetJtlambda(J, velT, bias)
//update speeds
States[body1].v = subV(States[body1].v, Jtlambda[0][0]);
States[body2].v = subV(States[body2].v, Jtlambda[1][0]);
}
//
// 3 particle pendulum, the jacobian starts showing a pattern
// Inputs:
// body1, body2: particle index
// top: coordinates of the top of the chain
//
function TriplePendulum(top, body1, body2, body3)
{
//compute jacobian
var J = []
J[0] = [ subV(States[body1].p,top), new Vector(0,0), new Vector(0,0) ];
J[1] = [ subV(States[body1].p, States.p[body2]), subV(States[body2].p, States[body1].p), new Vector(0,0) ];
J[2] = [ new Vector(0,0), subV(States[body2].p, States[body3].p), subV(States[body3].p, States[body2].p) ];
//compute vels
var vel = [[ States[body1].v, States[body2].v, States[body3].v ]];
var velT = TransposeMat(vel);
//compute bias
var bias = undefined;
//solver
var Jtlambda = GetJtlambda(J, velT, bias)
//update speeds
States[body1].v = subV(States[body1].v, Jtlambda[0][0]);
States[body2].v = subV(States[body2].v, Jtlambda[1][0]);
States.v[body3] = subV(States.v[body3], Jtlambda[2][0]);
}
//
// N particle pendulum, using a loop to generate J.
// Inputs:
// bodies: list of particle index
// top: coordinates of the top of the chain
//
function NPendulum(TopChain, bodies)
{
//compute jacobian
var J = []
for(var j=0;j<bodies.length;j++)
{
J[j] = [];
for(var i=0;i<bodies.length;i++)
{
if (i==0 && j==0)
J[j].push(subV(States.p[bodies[i]], TopChain));
else if (i==j)
J[j].push(subV(States.p[bodies[i]], States.p[bodies[i-1]]));
else if (i==j-1)
J[j].push(subV(States.p[bodies[j-1]], States.p[bodies[j]]));
else
J[j].push(new Vector(0,0));
}
}
//compute vels
var vel = [[]];
for(var i=0;i<bodies.length;i++)
vel[0].push(States.v[bodies[i]]);
var velT = TransposeMat(vel);
//compute bias
var distance = 10*10+10*10;
var betaoverh = .2/intergrationStep;
var bias = [[]];
bias[0].push( betaoverh * .5*(norm2V(subV( States.p[bodies[0]], TopChain)) - distance));
for(var i=1;i<bodies.length;i++)
{
bias[0].push( betaoverh * .5 * (norm2V(subV( States.p[bodies[i-1]], States.p[bodies[i]])) - distance));
}
var biasT = TransposeMat(bias);
//solver
var Jtlambda = GetJtlambda(J, velT, biasT);
//update speeds
for(var i=0;i<bodies.length;i++)
States.v[bodies[i]] = subV(States.v[bodies[i]], Jtlambda[i][0]);
//draw connections
drawLine( TopChain, States.p[bodies[0]])
for(var i=1;i<bodies.length;i++)
drawLine( States.p[bodies[i-1]], States.p[bodies[i]]);
}
//
// Distance constraint, note how the jacobian is a small matrix
// Inputs:
// body1, body2: particle index
//
function DistanceConstraint(body1, body2)
{
//compute jacobian
var J = []
J[0] = [ subV(States[body1].p, States[body2].p), subV(States[body2].p, States[body1].p) ];
//compute vels
var vel = [[ States[body1].v, States[body2].v ]];
var velT = TransposeMat(vel);
//compute bias
var distance = 10*10+10*10;
var betaoverh = .5/intergrationStep;
var C = .5 * (norm2V(subV( States[body1].p, States[body2].p)) - distance);
var bias = [[betaoverh * C]];
//solver
var Jtlambda = GetJtlambda(J, velT, bias)
//update speeds
States[body1].v = subV(States[body1].v, Jtlambda[0][0]);
States[body2].v = subV(States[body2].v, Jtlambda[1][0]);
}
//
// Distance constraint, note how the jacobian is a small matrix
// Inputs:
// body1, body2: particle index
//
function ContactConstraintBallBall(body1, norm2al, body2)
{
//compute jacobian
var J = []
J[0] = [ mulV(norm2al, 1.0), mulV(norm2al, -1.0) ];
//compute vels
var vel = [[ States[body1].v, States[body2].v ]];
var velT = TransposeMat(vel);
//compute bias
var betaoverh = .5/intergrationStep;
var C = dotV(subV(States[body1].p, States[body2].p), norm2al) - (r[body1]+r[body2]);
//bouncy term
var vn = 0;//dotV(subV(States[body1].v, States[body2].v), norm2al);
var bias = [[betaoverh * C + vn]];
//solver
var Jtlambda = GetJtlambda(J, velT, bias)
//update speeds
States[body1].v = subV(States[body1].v, Jtlambda[0][0]);
States[body2].v = subV(States[body2].v, Jtlambda[1][0]);
}
function ContactConstraintBallND(body1, norm2al, depth)
{
if (depth<0)
return;
//compute jacobian
var J = []
J[0] = [ mulV(norm2al, 1.0), mulV(norm2al, -1.0) ];
v2 = new Vector(0,0);
//compute vels
var vel = [[ States[body1].v, v2 ]];
var velT = TransposeMat(vel);
//compute bias
var betaoverh = .5/intergrationStep;
var C = -depth;
//bouncy term
var vn = 0;//dotV(subV(States[body1].v, States[body2].v), norm2al);
var bias = [[betaoverh * C + vn]];
//solver
var Jtlambda = GetJtlambda(J, velT, bias)
//update speeds
States[body1].v = subV(States[body1].v, Jtlambda[0][0]);
}
//
// Integrate step
//
function integrate(t)
{
for(var i=0;i<States.length;i++)
{
States[i].p = addV(States[i].p,mulV(States[i].v,t));
//States.v[i] = mulV(States.v[i], .98);
States[i].v = addV(States[i].v, new Vector(0,.5));
}
}
function ComputeCollsions()
{
var colliders= [];
colliders.pA = [];
colliders.pB = [];
colliders.N = [];
//compute collisions
for(var i=0;i<States.length;i++)
{
for(var j=0;j<i;j++)
{
var rr = (r[i]+r[j]);
var diff = subV(States[i].p, States[j].p);
var d = dotV(diff, diff);
if (d<rr*rr)
{
colliders.pA.push(i);
colliders.pB.push(j);
colliders.N.push( mulV(diff,1.0/Math.sqrt(d) ) );
}
}
}
for(var i=0;i<States.length;i++)
{
if (States[i].p.y+r[i]>300)
{
colliders.pA.push(i);
colliders.pB.push(undefined);
colliders.N.push( new Vector(0,-1) );
}
}
return colliders;
}
var time = 0;
var hammokParticles = []
var redParticles = []
function draw()
{
time++;
contacts = []
//compute tentative velocities
integrate(intergrationStep);
//apply constraints
var iterations = 10;
for(var iter=0;iter<iterations;iter++)
{
var colliders = ComputeCollsions();
for(var i=0;i<colliders.pA.length;i++)
{
if (colliders.pB[i]!=undefined)
{
ContactConstraintBallBall(colliders.pA[i], colliders.N[i], colliders.pB[i])
}
else
{
var pi = colliders.pA[i];
ContactConstraintBallND(pi, colliders.N[i], States.p[pi].y+r[pi]-300);
}
}
var TopChain1 = new Vector(50,100);
var TopChain2 = new Vector(550,100);
SinglePendulum(TopChain1, hammokParticles[0]);
SinglePendulum(TopChain2, hammokParticles[hammokParticles.length-1]);
for(var i=1;i<hammokParticles.length;i++)
{
DistanceConstraint(hammokParticles[i-1], hammokParticles[i]);
}
}
context= myCanvas.getContext('2d');
context.clearRect(0,0,600,300);
//draw chain1
for(var i=0;i<hammokParticles.length;i++)
{
var b=hammokParticles[i];
drawSphere(context, States[b].p, r[b], "#0000ff");
}
//draw chain2
for(var i=0;i<redParticles.length;i++)
{
var b=redParticles[i];
drawSphere(context, States[b].p, r[b], "#ff0000");
}
}
//
// 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;
}
function init()
{
var vv = 40;
// create particles for the hammok
for(var i=0;i<vv;i++)
{
var p = new Vector(50+(i+1)*10,100);
var v = new Vector(0,0);
States.push( new State(p,v) );
r.push(5);
hammokParticles.push(States.length-1)
}
//create some particles
for(var i=0;i<100;i++)
{
var p = new Vector(150,-i*10);
var v = new Vector(0,0);
States.push( new State(p,v) );
r.push(5);
redParticles.push(States.length-1)
var p = new Vector(150+15,-i*10);
var v = new Vector(0,0);
States.push( new State(p, v) );
r.push(5);
redParticles.push(States.length-1)
}
setInterval(draw,10);
}
</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>Contact constraint (sequential solver)</h1>
<div id="container">
<canvas id="myCanvas" width="600" height="300"></canvas>
<h2>Intro</h2>
This is a quick exercise to learn how constraints work in a physics simulator. This sample is using inequality constraints for the contact contacts</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>