-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollisionBox.cpp
More file actions
1181 lines (1051 loc) · 38.3 KB
/
CollisionBox.cpp
File metadata and controls
1181 lines (1051 loc) · 38.3 KB
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***********************************************************************
CollisionBox - Class to represent a rectangular box containing spheres
of a fixed radius interacting by fully elastic collisions.
Copyright (c) 2005-2020 Oliver Kreylos
This file is part of the Virtual Wind Tunnel package.
The Virtual Wind Tunnel package is free software; you can redistribute
it and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
The Virtual Wind Tunnel package is distributed in the hope that it will
be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along
with the Virtual Wind Tunnel package; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***********************************************************************/
#define COLLISIONBOX_IMPLEMENTATION
#include "CollisionBox.h"
#include <iostream>
#include <Misc/SizedTypes.h>
#include <IO/File.h>
#include <Math/Math.h>
/* Set to 1 to use a second-order Runge-Kutta solver: */
#define SECOND_ORDER_INTEGRATION 1
/*****************************
Methods of class CollisionBox:
*****************************/
template <class ScalarParam,int dimensionParam>
inline
void
CollisionBox<ScalarParam,dimensionParam>::queueSphereCollisions(
typename CollisionBox<ScalarParam,dimensionParam>::Scalar timeStep,
typename CollisionBox<ScalarParam,dimensionParam>::CollisionQueue& collisionQueue)
{
/* Calculate the spherical obstacle's position at the end of this time step: */
Point newSpherePosition=spherePosition+sphereVelocity*(timeStep-sphereTimeStamp);
Vector wallNormal;
Scalar collisionTime=timeStep;
for(int dim=0;dim<dimension;++dim)
{
/* Check if the spherical obstacle leaves the domain: */
if(newSpherePosition[dim]<boundaries.min[dim]+sphereRadius)
{
/* Calculate the event time: */
Scalar ct=(boundaries.min[dim]+sphereRadius-spherePosition[dim])/sphereVelocity[dim]+sphereTimeStamp;
if(ct>sphereTimeStamp&&collisionTime>ct)
{
wallNormal=Vector::zero;
wallNormal[dim]=Scalar(1);
collisionTime=ct;
}
}
else if(newSpherePosition[dim]>boundaries.max[dim]-sphereRadius)
{
/* Calculate the event time: */
Scalar ct=(boundaries.max[dim]-sphereRadius-spherePosition[dim])/sphereVelocity[dim]+sphereTimeStamp;
if(ct>sphereTimeStamp&&collisionTime>ct)
{
wallNormal=Vector::zero;
wallNormal[dim]=Scalar(-1);
collisionTime=ct;
}
}
}
if(collisionTime<timeStep)
collisionQueue.insert(CollisionEvent(collisionTime,sphereTimeStamp,wallNormal));
}
template <class ScalarParam,int dimensionParam>
inline
void
CollisionBox<ScalarParam,dimensionParam>::queueCollisionsInCell(
typename CollisionBox<ScalarParam,dimensionParam>::GridCell* cell,
typename CollisionBox<ScalarParam,dimensionParam>::Particle* particle1,
typename CollisionBox<ScalarParam,dimensionParam>::Scalar timeStep,
bool symmetric,
typename CollisionBox<ScalarParam,dimensionParam>::Particle* otherParticle,
typename CollisionBox<ScalarParam,dimensionParam>::CollisionQueue& collisionQueue)
{
/* Calculate all intersections between two particles: */
for(Particle* particle2=cell->particlesHead;particle2!=0;particle2=particle2->cellSucc)
if(particle2!=particle1&&particle2!=otherParticle&&(symmetric||particle2>particle1))
{
/* Calculate any possible intersection time between the two particles: */
Vector d=particle1->position-particle2->position;
d-=particle1->velocity*particle1->timeStamp;
d+=particle2->velocity*particle2->timeStamp;
Vector vd=particle1->velocity-particle2->velocity;
Scalar vd2=Geometry::sqr(vd);
if(vd2>Scalar(0)) // Are the two particles' velocities different?
{
/* Solve the quadratic equation determining possible collisions: */
Scalar ph=(d*vd)/vd2;
Scalar q=(Geometry::sqr(d)-Scalar(4)*particleRadius2)/vd2;
Scalar det=Math::sqr(ph)-q;
if(det>=Scalar(0)) // Are there any solutions?
{
/* Calculate the first solution (only that can be valid): */
Scalar collisionTime=-ph-Math::sqrt(det);
/* If the collision is valid, i.e., occurs past the last update of both particles, queue it: */
if(collisionTime>particle1->timeStamp&&collisionTime>particle2->timeStamp&&collisionTime<=timeStep)
collisionQueue.insert(CollisionEvent(collisionTime,particle1,particle2));
}
}
}
}
template <class ScalarParam,int dimensionParam>
inline
void
CollisionBox<ScalarParam,dimensionParam>::queueCellChanges(
typename CollisionBox<ScalarParam,dimensionParam>::Particle* particle,
const typename CollisionBox<ScalarParam,dimensionParam>::Point& newPosition,
typename CollisionBox<ScalarParam,dimensionParam>::Scalar timeStep,
typename CollisionBox<ScalarParam,dimensionParam>::CollisionQueue& collisionQueue)
{
/* Check for crossing of any cell borders: */
GridCell* cell=particle->cell;
Scalar cellChangeTime=timeStep;
int cellChangeDirection=-1;
for(int i=0;i<dimension;++i)
{
if(newPosition[i]<cell->boundaries.min[i])
{
Scalar collisionTime=particle->timeStamp+(cell->boundaries.min[i]-particle->position[i])/particle->velocity[i];
if(cellChangeTime>collisionTime)
{
cellChangeTime=collisionTime;
cellChangeDirection=2*i+0;
}
}
else if(newPosition[i]>cell->boundaries.max[i])
{
Scalar collisionTime=particle->timeStamp+(cell->boundaries.max[i]-particle->position[i])/particle->velocity[i];
if(cellChangeTime>collisionTime)
{
cellChangeTime=collisionTime;
cellChangeDirection=2*i+1;
}
}
}
if(cellChangeDirection>=0)
collisionQueue.insert(CollisionEvent(cellChangeTime,particle,cellChangeDirection));
}
template <class ScalarParam,int dimensionParam>
inline
void
CollisionBox<ScalarParam,dimensionParam>::queueCollisions(
typename CollisionBox<ScalarParam,dimensionParam>::Particle* particle1,
typename CollisionBox<ScalarParam,dimensionParam>::Scalar timeStep,
bool symmetric,
typename CollisionBox<ScalarParam,dimensionParam>::Particle* otherParticle,
typename CollisionBox<ScalarParam,dimensionParam>::CollisionQueue& collisionQueue)
{
/* Calculate the particle's position at the end of this time step: */
Point newPosition=particle1->position+particle1->velocity*(timeStep-particle1->timeStamp);
/* Check for crossing of cell borders: */
queueCellChanges(particle1,newPosition,timeStep,collisionQueue);
/* Check for collisions with any of the collision box's walls: */
for(int i=0;i<dimension;++i)
{
if(newPosition[i]<boundaries.min[i]+particleRadius)
{
Scalar collisionTime=particle1->timeStamp+(boundaries.min[i]+particleRadius-particle1->position[i])/particle1->velocity[i];
if(collisionTime<particle1->timeStamp)
collisionTime=particle1->timeStamp;
else if(collisionTime>timeStep)
collisionTime=timeStep;
Vector wallNormal=Vector::zero;
wallNormal[i]=Scalar(1);
collisionQueue.insert(CollisionEvent(collisionTime,particle1,wallNormal));
}
else if(newPosition[i]>boundaries.max[i]-particleRadius)
{
Scalar collisionTime=particle1->timeStamp+(boundaries.max[i]-particleRadius-particle1->position[i])/particle1->velocity[i];
if(collisionTime<particle1->timeStamp)
collisionTime=particle1->timeStamp;
else if(collisionTime>timeStep)
collisionTime=timeStep;
Vector wallNormal=Vector::zero;
wallNormal[i]=Scalar(-1);
collisionQueue.insert(CollisionEvent(collisionTime,particle1,wallNormal));
}
}
/* Check for collision with the spherical obstacle: */
Vector d=particle1->position-spherePosition;
d-=particle1->velocity*particle1->timeStamp;
d+=sphereVelocity*sphereTimeStamp;
Vector vd=particle1->velocity-sphereVelocity;
Scalar vd2=Geometry::sqr(vd);
if(vd2>Scalar(0)) // Are the particle's and the sphere's velocities different?
{
Scalar collisionTime(0);
/* Check if the particle is inside or outside the sphere: */
Scalar d2=d.sqr();
if(d2>=sphereRadius2)
{
/* Solve the quadratic equation determining possible collisions: */
Scalar ph=(d*vd)/vd2;
Scalar q=(d2-Math::sqr(sphereRadius+particleRadius))/vd2;
Scalar det=Math::sqr(ph)-q;
if(det>=Scalar(0)) // Are there any solutions?
{
/* Calculate the first solution (only that can be valid): */
collisionTime=-ph-Math::sqrt(det);
}
}
else
{
/* Solve the quadratic equation determining possible collisions: */
Scalar ph=(d*vd)/vd2;
Scalar q=(d2-Math::sqr(sphereRadius-particleRadius))/vd2;
Scalar det=Math::sqr(ph)-q;
if(det>=Scalar(0)) // Are there any solutions?
{
/* Calculate the second solution (only that can be valid): */
collisionTime=-ph+Math::sqrt(det);
}
}
/* If the collision is valid, i.e., occurs past the last update of both the particle and the sphere, queue it: */
if(collisionTime>particle1->timeStamp&&collisionTime>sphereTimeStamp&&collisionTime<=timeStep)
{
/* Check if the sphere is open: */
if(sphereOpen)
{
/* Calculate the collision offset: */
d+=(particle1->velocity-sphereVelocity)*collisionTime;
if(d[1]>=Scalar(0)||Math::abs(d[0])>=sphereRadius*Scalar(0.075))
collisionQueue.insert(CollisionEvent(collisionTime,particle1,sphereTimeStamp));
}
else
collisionQueue.insert(CollisionEvent(collisionTime,particle1,sphereTimeStamp));
}
}
/* Check for collisions with any other particle: */
GridCell* baseCell=particle1->cell;
for(int i=0;i<numNeighbors;++i)
{
GridCell* cell=baseCell+neighborOffsets[i];
queueCollisionsInCell(cell,particle1,timeStep,symmetric,otherParticle,collisionQueue);
}
}
template <class ScalarParam,int dimensionParam>
inline
void
CollisionBox<ScalarParam,dimensionParam>::queueCollisionsOnCellChange(
typename CollisionBox<ScalarParam,dimensionParam>::Particle* particle,
typename CollisionBox<ScalarParam,dimensionParam>::Scalar timeStep,
int cellChangeDirection,
typename CollisionBox<ScalarParam,dimensionParam>::CollisionQueue& collisionQueue)
{
/* Calculate the particle's position at the end of this time step: */
Point newPosition=particle->position+particle->velocity*(timeStep-particle->timeStamp);
/* Check for crossing of cell borders: */
queueCellChanges(particle,newPosition,timeStep,collisionQueue);
/* Check for collision with any other particle: */
GridCell* baseCell=particle->cell;
for(int i=0;i<numNeighbors;++i)
if(cellChangeMasks[i]&(1<<cellChangeDirection))
{
GridCell* cell=baseCell+neighborOffsets[i];
queueCollisionsInCell(cell,particle,timeStep,true,0,collisionQueue);
}
}
template <class ScalarParam,int dimensionParam>
inline
void
CollisionBox<ScalarParam,dimensionParam>::queueCollisionsWithSphere(
typename CollisionBox<ScalarParam,dimensionParam>::Scalar timeStep,
typename CollisionBox<ScalarParam,dimensionParam>::CollisionQueue& collisionQueue)
{
/* Check all particles: */
for(typename ParticleList::iterator pIt=particles.begin();pIt!=particles.end();++pIt)
{
/* Check for collision with the spherical obstacle: */
Vector d=pIt->position-spherePosition;
d-=pIt->velocity*pIt->timeStamp;
d+=sphereVelocity*sphereTimeStamp;
Vector vd=pIt->velocity-sphereVelocity;
Scalar vd2=Geometry::sqr(vd);
if(vd2>Scalar(0)) // Are the particle's and the sphere's velocities different?
{
Scalar collisionTime(0);
/* Check if the particle is inside or outside the sphere: */
Scalar d2=d.sqr();
if(d2>=sphereRadius2)
{
/* Solve the quadratic equation determining possible collisions: */
Scalar ph=(d*vd)/vd2;
Scalar q=(d2-Math::sqr(sphereRadius+particleRadius))/vd2;
Scalar det=Math::sqr(ph)-q;
if(det>=Scalar(0)) // Are there any solutions?
{
/* Calculate the first solution (only that can be valid): */
collisionTime=-ph-Math::sqrt(det);
}
}
else
{
/* Solve the quadratic equation determining possible collisions: */
Scalar ph=(d*vd)/vd2;
Scalar q=(d2-Math::sqr(sphereRadius-particleRadius))/vd2;
Scalar det=Math::sqr(ph)-q;
if(det>=Scalar(0)) // Are there any solutions?
{
/* Calculate the second solution (only that can be valid): */
collisionTime=-ph+Math::sqrt(det);
}
}
/* If the collision is valid, i.e., occurs past the last update of both the particle and the sphere, queue it: */
if(collisionTime>pIt->timeStamp&&collisionTime>sphereTimeStamp&&collisionTime<=timeStep)
{
/* Check if the sphere is open: */
if(sphereOpen)
{
/* Calculate the collision offset: */
d+=(pIt->velocity-sphereVelocity)*collisionTime;
if(d[1]>=Scalar(0)||Math::abs(d[0])>=sphereRadius*Scalar(0.075))
collisionQueue.insert(CollisionEvent(collisionTime,&*pIt,sphereTimeStamp));
}
else
collisionQueue.insert(CollisionEvent(collisionTime,&*pIt,sphereTimeStamp));
}
}
}
}
#if HOLD_ENERGY
template <class ScalarParam,int dimensionParam>
inline
void
CollisionBox<ScalarParam,dimensionParam>::updateTotalEnergy(
void)
{
/* Calculate the sum of the kinetic and potential energies of all particles: */
#if CENTRAL_GRAVITY
Scalar g=gravity.mag()*sphereRadius2;
#endif
kineticEnergy=Scalar(0);
potentialEnergy=Scalar(0);
for(typename ParticleList::const_iterator pIt=particles.begin();pIt!=particles.end();++pIt)
{
/* Accumulate the particle's kinetic energy: */
kineticEnergy+=pIt->velocity.sqr();
/* Accumulate the particle's potential energy: */
#if CENTRAL_GRAVITY
Scalar r=Geometry::dist(spherePosition,pIt->position);
potentialEnergy+=g*(Scalar(1)/sphereRadius-Scalar(1)/r);
#else
potentialEnergy-=pIt->position*gravity;
#endif
}
kineticEnergy*=Scalar(0.5);
}
#endif
template <class ScalarParam,int dimensionParam>
inline
CollisionBox<ScalarParam,dimensionParam>::CollisionBox(
const typename CollisionBox<ScalarParam,dimensionParam>::Box& sBoundaries,
typename CollisionBox<ScalarParam,dimensionParam>::Scalar sParticleRadius,
typename CollisionBox<ScalarParam,dimensionParam>::Scalar sSphereRadius)
:boundaries(sBoundaries),
numNeighbors(0),neighborOffsets(0),cellChangeMasks(0),
particleRadius(sParticleRadius),particleRadius2(Math::sqr(particleRadius)),
gravity(Vector::zero),
attenuation(1),
numParticles(0),
spherePosition(Point::origin),
sphereVelocity(Vector::zero),
sphereOpen(false),
sphereRadius(sSphereRadius),sphereRadius2(Math::sqr(sphereRadius)),
invSphereMass(0),sphereTimeStamp(0),
particleVelocityFactor(2),sphereVelocityFactor(0)
#if ACCUMULATE_PRESSURE
,
numPressureSlots(0),pressureSlotSize(0),pressureSlots(0),pressureTime(0)
#endif
#if HOLD_ENERGY
,
kineticEnergy(0),potentialEnergy(0)
#endif
{
/* Calculate optimal number of cells and cell sizes: */
Index numOuterCells;
for(int i=0;i<dimension;++i)
{
numCells[i]=int(Math::floor(boundaries.getSize(i)/(particleRadius*Scalar(2.5))));
cellSize[i]=boundaries.getSize(i)/Scalar(numCells[i]);
numOuterCells[i]=numCells[i]+2; // Create a layer of "ghost cells" in all directions
}
/* Create the cell array: */
cells.resize(numOuterCells);
for(Index index(0);index[0]<numOuterCells[0];cells.preInc(index))
{
/* Initialize the cell: */
Point min,max;
for(int i=0;i<dimension;++i)
{
min[i]=boundaries.min[i]+cellSize[i]*Scalar(index[i]-1);
max[i]=boundaries.min[i]+cellSize[i]*Scalar(index[i]-0);
}
cells(index).boundaries=Box(min,max);
cells(index).particlesHead=0;
cells(index).particlesTail=0;
}
/* Initialize the direct neighbor offsets: */
for(int i=0;i<dimension;++i)
{
directNeighborOffsets[2*i+0]=-cells.getIncrement(i);
directNeighborOffsets[2*i+1]=cells.getIncrement(i);
}
/* Initialize the neighbor array: */
numNeighbors=1;
for(int i=0;i<dimension;++i)
numNeighbors*=3;
neighborOffsets=new ssize_t[numNeighbors];
cellChangeMasks=new int[numNeighbors];
Index minBound;
Index maxBound;
for(int i=0;i<dimension;++i)
{
minBound[i]=-1;
maxBound[i]=2;
}
int neighborIndex=0;
for(Index index=minBound;index[0]<maxBound[0];index.preInc(minBound,maxBound),++neighborIndex)
{
neighborOffsets[neighborIndex]=0;
cellChangeMasks[neighborIndex]=0x0;
for(int i=0;i<dimension;++i)
{
neighborOffsets[neighborIndex]+=cells.getIncrement(i)*index[i];
if(index[i]==-1)
cellChangeMasks[neighborIndex]|=1<<(2*i+0);
else if(index[i]==1)
cellChangeMasks[neighborIndex]|=1<<(2*i+1);
}
}
/* Position the spherical obstacle: */
spherePosition[0]=boundaries.min[0]-sphereRadius-Scalar(10);
for(int i=1;i<dimension;++i)
spherePosition[i]=Math::div2(boundaries.min[i]+boundaries.max[i]);
// sphereVelocity[0]=Scalar(5);
}
template <class ScalarParam,int dimensionParam>
inline
CollisionBox<ScalarParam,dimensionParam>::CollisionBox(
IO::File& file)
:neighborOffsets(0),cellChangeMasks(0)
#if ACCUMULATE_PRESSURE
,
numPressureSlots(0),pressureSlotSize(0),pressureSlots(0),pressureTime(0)
#endif
{
/* Read the collision box vector space dimension and scalar type for compatibility checks: */
int fileDimension=file.read<Misc::UInt32>();
size_t fileScalarSize=file.read<Misc::UInt32>();
if(fileDimension!=dimension||fileScalarSize!=sizeof(Scalar))
throw std::runtime_error("CollisionBox::CollisionBox: File has incompatible format");
/* Read the collision box boundaries: */
file.read(boundaries.min.getComponents(),dimension);
file.read(boundaries.max.getComponents(),dimension);
/* Read the cell size and number of cells: */
file.read(cellSize.getComponents(),dimension);
file.read(numCells,dimension);
#if 0
/* Grow the box vertically: */
numCells[1]*=2;
boundaries.max[1]=boundaries.min[1]+(boundaries.max[1]-boundaries.min[1])*Scalar(2);
#endif
/* Create the cell array: */
Index numOuterCells;
for(int i=0;i<dimension;++i)
numOuterCells[i]=numCells[i]+2;
cells.resize(numOuterCells);
for(Index index(0);index[0]<numOuterCells[0];cells.preInc(index))
{
/* Initialize the cell: */
Point min,max;
for(int i=0;i<dimension;++i)
{
min[i]=boundaries.min[i]+cellSize[i]*Scalar(index[i]-1);
max[i]=boundaries.min[i]+cellSize[i]*Scalar(index[i]-0);
}
cells(index).boundaries=Box(min,max);
cells(index).particlesHead=0;
cells(index).particlesTail=0;
}
/* Initialize the direct neighbor offsets: */
for(int i=0;i<dimension;++i)
{
directNeighborOffsets[2*i+0]=-cells.getIncrement(i);
directNeighborOffsets[2*i+1]=cells.getIncrement(i);
}
/* Initialize the neighbor array: */
numNeighbors=1;
for(int i=0;i<dimension;++i)
numNeighbors*=3;
neighborOffsets=new ssize_t[numNeighbors];
cellChangeMasks=new int[numNeighbors];
Index minBound;
Index maxBound;
for(int i=0;i<dimension;++i)
{
minBound[i]=-1;
maxBound[i]=2;
}
int neighborIndex=0;
for(Index index=minBound;index[0]<maxBound[0];index.preInc(minBound,maxBound),++neighborIndex)
{
neighborOffsets[neighborIndex]=0;
cellChangeMasks[neighborIndex]=0x0;
for(int i=0;i<dimension;++i)
{
neighborOffsets[neighborIndex]+=cells.getIncrement(i)*index[i];
if(index[i]==-1)
cellChangeMasks[neighborIndex]|=1<<(2*i+0);
else if(index[i]==1)
cellChangeMasks[neighborIndex]|=1<<(2*i+1);
}
}
/* Read simulation parameters: */
file.read(particleRadius);
particleRadius2=Math::sqr(particleRadius);
file.read(gravity.getComponents(),dimension);
file.read(attenuation);
/* Read the state of the spherical obstacle: */
file.read(spherePosition.getComponents(),dimension);
file.read(sphereVelocity.getComponents(),dimension);
file.read(sphereRadius);
sphereRadius2=Math::sqr(sphereRadius);
sphereOpen=file.read<Misc::UInt8>()!=0;
file.read(invSphereMass);
particleVelocityFactor=Scalar(2)/(invSphereMass+Scalar(1));
sphereVelocityFactor=(Scalar(2)*invSphereMass)/(invSphereMass+Scalar(1));
sphereTimeStamp=Scalar(0);
/* Read the states of all particles: */
size_t fileNumParticles=size_t(file.read<Misc::UInt32>());
// std::cout<<"Reading "<<fileNumParticles<<" particles"<<std::endl;
for(size_t i=0;i<fileNumParticles;++i)
{
Point pos;
file.read(pos.getComponents(),dimension);
Vector vel;
file.read(vel.getComponents(),dimension);
if(!addParticle(pos,vel))
std::cout<<"Warning: Unable to add particle from state file"<<std::endl;
}
#if HOLD_ENERGY
/* Calculate the particle system's initial total energy: */
updateTotalEnergy();
#endif
}
template <class ScalarParam,int dimensionParam>
inline
CollisionBox<ScalarParam,dimensionParam>::~CollisionBox(
void)
{
delete[] neighborOffsets;
delete[] cellChangeMasks;
#if ACCUMULATE_PRESSURE
delete[] pressureSlots;
#endif
}
template <class ScalarParam,int dimensionParam>
inline
void
CollisionBox<ScalarParam,dimensionParam>::setAttenuation(
typename CollisionBox<ScalarParam,dimensionParam>::Scalar newAttenuation)
{
attenuation=newAttenuation;
}
template <class ScalarParam,int dimensionParam>
inline
void
CollisionBox<ScalarParam,dimensionParam>::setGravity(
const typename CollisionBox<ScalarParam,dimensionParam>::Vector& newGravity)
{
gravity=newGravity;
}
template <class ScalarParam,int dimensionParam>
inline
bool
CollisionBox<ScalarParam,dimensionParam>::addParticle(
const typename CollisionBox<ScalarParam,dimensionParam>::Point& newPosition,
const typename CollisionBox<ScalarParam,dimensionParam>::Vector& newVelocity,
bool sphereSolid)
{
/* Find the cell containing the new particle: */
Point newP=newPosition;
Index cellIndex;
for(int i=0;i<dimension;++i)
{
if(newP[i]<boundaries.min[i]+particleRadius)
newP[i]=boundaries.min[i]+particleRadius;
else if(newP[i]>boundaries.max[i]-particleRadius)
newP[i]=boundaries.max[i]-particleRadius;
cellIndex[i]=int(Math::floor((newP[i]-boundaries.min[i])/cellSize[i]))+1;
}
GridCell* cell=cells.getAddress(cellIndex);
/* Check if there is room to add the new particle: */
for(int i=0;i<numNeighbors;++i)
{
GridCell* neighborCell=cell+neighborOffsets[i];
for(Particle* pPtr=neighborCell->particlesHead;pPtr!=0;pPtr=pPtr->cellSucc)
{
Scalar dist2=Geometry::sqrDist(pPtr->position,newP);
if(dist2<=Scalar(4)*particleRadius2)
return false; // Could not add the particle
}
}
/* Check if the particle overlaps the sphere: */
Scalar sphereDist2=Geometry::sqrDist(newPosition,spherePosition);
if(sphereDist2<=Math::sqr(sphereRadius+particleRadius)&&(sphereSolid||sphereDist2>=Math::sqr(sphereRadius+particleRadius)))
return false; // Could not add the particle
/* Add a new particle to the particle list: */
particles.push_back(Particle());
Particle& p=particles.back();
/* Initialize the new particle: */
p.position=newPosition;
p.velocity=newVelocity;
p.timeStamp=Scalar(0);
cell->addParticle(&p);
#if HOLD_ENERGY
/* Accumulate the new particle's kinetic energy: */
kineticEnergy+=Scalar(0.5)*p.velocity.sqr();
/* Accumulate the new particle's potential energy: */
#if CENTRAL_GRAVITY
Scalar g=gravity.mag()*sphereRadius2;
Scalar r=Geometry::dist(spherePosition,p.position);
potentialEnergy+=g*(Scalar(1)/sphereRadius-Scalar(1)/r);
#else
potentialEnergy-=pIt->position*gravity;
#endif
#endif
++numParticles;
return true; // Particle succesfully added
}
template <class ScalarParam,int dimensionParam>
inline
void
CollisionBox<ScalarParam,dimensionParam>::setSphere(
const typename CollisionBox<ScalarParam,dimensionParam>::Point& newPosition)
{
/* Set the sphere's position and reset its velocity: */
spherePosition=newPosition;
sphereVelocity=Vector::zero;
}
template <class ScalarParam,int dimensionParam>
inline
void
CollisionBox<ScalarParam,dimensionParam>::moveSphere(
const typename CollisionBox<ScalarParam,dimensionParam>::Point& newPosition,
typename CollisionBox<ScalarParam,dimensionParam>::Scalar timeStep)
{
/* Calculate the sphere's velocity for this time step: */
sphereVelocity=(newPosition-spherePosition)/timeStep;
}
template <class ScalarParam,int dimensionParam>
inline
void
CollisionBox<ScalarParam,dimensionParam>::setSphereOpen(
bool newSphereOpen)
{
sphereOpen=newSphereOpen;
}
template <class ScalarParam,int dimensionParam>
inline
void
CollisionBox<ScalarParam,dimensionParam>::setInverseSphereMass(
typename CollisionBox<ScalarParam,dimensionParam>::Scalar newInvSphereMass)
{
/* Set the inverse sphere mass: */
invSphereMass=newInvSphereMass;
/* Update the particle and sphere collision velocity factors: */
particleVelocityFactor=Scalar(2)/(invSphereMass+Scalar(1));
sphereVelocityFactor=(Scalar(2)*invSphereMass)/(invSphereMass+Scalar(1));
}
template <class ScalarParam,int dimensionParam>
inline
void
CollisionBox<ScalarParam,dimensionParam>::simulate(
typename CollisionBox<ScalarParam,dimensionParam>::Scalar timeStep)
{
/* Pre-compute acceleration constants: */
#if SECOND_ORDER_INTEGRATION
Scalar timeStepH=Math::div2(timeStep);
#endif
#if CENTRAL_GRAVITY
Scalar g=gravity.mag()*sphereRadius2; // Set g to the gravitational acceleration on the sphere's surface, for simplicity
#else // !CENTRAL_GRAVITY
#if SECOND_ORDER_INTEGRATION
Vector dv=gravity*timeStepH; // Velocity change in the first and second half time step due to gravity
#else // !SECOND_ORDER_INTEGRATION
Vector dv=gravity*timeStep; // Velocity change in this time step due to gravity
#endif
#endif
#if CENTRAL_GRAVITY
/* Calculate each particle's acceleration: */
for(typename ParticleList::iterator pIt=particles.begin();pIt!=particles.end();++pIt)
{
/* Calculate acceleration at particle's current position: */
Vector gDir=spherePosition-pIt->position;
Scalar gd2=gDir.sqr();
#if SECOND_ORDER_INTEGRATION
/* Calculate half-step acceleration at particle's current position: */
Vector a=gDir*(timeStepH*g/(gd2*Math::sqrt(gd2)));
/* Calculate particle's half-step position: */
Point p1=pIt->position+pIt->velocity*timeStepH;
/* Calculate acceleration at particle's half-step position: */
Vector gDir1=spherePosition-p1;
Scalar gd12=gDir1.sqr();
Vector a1=gDir1*(timeStep*g/(gd12*Math::sqrt(gd12)));
/* Calculate particle's full-step velocity: */
pIt->velocity+=a;
/* Store the full-step acceleration for later: */
pIt->dv=a1-a;
#else // !SECOND_ORDER_INTEGRATION
/* Calculate acceleration at particle's current position: */
pIt->dv=gDir*(timeStep*g/(gd2*Math::sqrt(gd2)));
#endif
}
#elif SECOND_ORDER_INTEGRATION
/* Calculate each particle's full-step velocity: */
for(typename ParticleList::iterator pIt=particles.begin();pIt!=particles.end();++pIt)
pIt->velocity+=dv;
#endif
/* Initialize the collision queue: */
CollisionQueue collisionQueue(numParticles*dimension);
for(typename ParticleList::iterator pIt=particles.begin();pIt!=particles.end();++pIt)
queueCollisions(&(*pIt),timeStep,false,0,collisionQueue);
if(invSphereMass!=Scalar(0))
queueSphereCollisions(timeStep,collisionQueue);
/* Update all particles' positions and handle all collisions: */
while(!collisionQueue.isEmpty())
{
/* Get the next collision from the queue: */
CollisionEvent nc=collisionQueue.getSmallest();
collisionQueue.removeSmallest();
/* Handle the collision if it is still valid: */
switch(nc.collisionType)
{
case CollisionEvent::SphereWallCollision:
if(sphereTimeStamp==nc.timeStamp1)
{
/* Bounce the spherical obstacle off the wall: */
spherePosition+=sphereVelocity*(nc.collisionTime-nc.timeStamp1);
sphereTimeStamp=nc.collisionTime;
Vector dv=(Scalar(2)*(nc.wallNormal*sphereVelocity))*nc.wallNormal;
sphereVelocity-=dv;
/* Re-calculate all collisions of the spherical obstacle: */
queueCollisionsWithSphere(timeStep,collisionQueue);
queueSphereCollisions(timeStep,collisionQueue);
}
break;
case CollisionEvent::CellChange:
if(nc.particle1->timeStamp==nc.timeStamp1)
{
/* Let the particle cross into the next grid cell: */
GridCell* cell=nc.particle1->cell;
cell->removeParticle(nc.particle1);
cell+=directNeighborOffsets[nc.cellChangeDirection];
cell->addParticle(nc.particle1);
/* Re-calculate all the particle's collisions: */
queueCollisionsOnCellChange(nc.particle1,timeStep,nc.cellChangeDirection,collisionQueue);
}
break;
case CollisionEvent::WallCollision:
if(nc.particle1->timeStamp==nc.timeStamp1)
{
/* Bounce the particle off the wall: */
nc.particle1->position+=nc.particle1->velocity*(nc.collisionTime-nc.timeStamp1);
nc.particle1->timeStamp=nc.collisionTime;
#if 1
Vector dv=(Scalar(2)*(nc.wallNormal*nc.particle1->velocity))*nc.wallNormal;
nc.particle1->velocity-=dv;
#else
/* Create convection by making the floor "hot" and the ceiling "cold": */
Vector dv=(nc.wallNormal*nc.particle1->velocity)*nc.wallNormal;
nc.particle1->velocity-=dv;
if(nc.wallNormal[1]<Scalar(0))
nc.particle1->velocity-=dv*Scalar(0.1);
else if(nc.wallNormal[1]>Scalar(0))
nc.particle1->velocity-=dv*Scalar(1.05);
else
nc.particle1->velocity-=dv;
#endif
#if ACCUMULATE_PRESSURE
if(numPressureSlots>0&&nc.wallNormal[1]==Scalar(0))
{
/* Accumulate pressure: */
unsigned int psIndex=(unsigned int)(Math::floor(nc.particle1->position[1]/pressureSlotSize));
if(nc.wallNormal[0]>Scalar(0))
pressureSlots[psIndex*2+0]-=dv[0];
else
pressureSlots[psIndex*2+1]+=dv[0];
}
#endif
/* Re-calculate all the particle's collisions: */
queueCollisions(nc.particle1,timeStep,true,0,collisionQueue);
}
break;
case CollisionEvent::SphereCollision:
if(nc.particle1->timeStamp==nc.timeStamp1&&sphereTimeStamp==nc.timeStamp2)
{
/* Bounce the particle off the sphere: */
nc.particle1->position+=nc.particle1->velocity*(nc.collisionTime-nc.timeStamp1);
nc.particle1->timeStamp=nc.collisionTime;
Point sp=spherePosition+sphereVelocity*(nc.collisionTime-nc.timeStamp2);
Vector d=sp-nc.particle1->position;
Scalar dLen2=Geometry::sqr(d);
Vector v1=d*((nc.particle1->velocity*d)/dLen2);
Vector v2=d*((sphereVelocity*d)/dLen2);
nc.particle1->velocity+=(v2-v1)*particleVelocityFactor;
/* Re-calculate all collisions of the particle: */
queueCollisions(nc.particle1,timeStep,true,0,collisionQueue);
if(invSphereMass>Scalar(0))
{
/* Update the position and velocity of the spherical obstacle: */
spherePosition=sp;
sphereTimeStamp=nc.collisionTime;
sphereVelocity+=(v1-v2)*sphereVelocityFactor;
/* Re-calculate all collisions of the spherical obstacle: */
queueCollisionsWithSphere(timeStep,collisionQueue);
queueSphereCollisions(timeStep,collisionQueue);
}
}
break;
case CollisionEvent::ParticleCollision:
if(nc.particle1->timeStamp==nc.timeStamp1&&nc.particle2->timeStamp==nc.timeStamp2)
{
/* Bounce the two particles off each other: */
nc.particle1->position+=nc.particle1->velocity*(nc.collisionTime-nc.timeStamp1);
nc.particle1->timeStamp=nc.collisionTime;
nc.particle2->position+=nc.particle2->velocity*(nc.collisionTime-nc.timeStamp2);
nc.particle2->timeStamp=nc.collisionTime;
Vector d=nc.particle2->position-nc.particle1->position;
Scalar dLen2=Geometry::sqr(d);
Vector v1=d*((nc.particle1->velocity*d)/dLen2);
Vector v2=d*((nc.particle2->velocity*d)/dLen2);
Vector dv=v2-v1;
nc.particle1->velocity+=dv;
nc.particle2->velocity-=dv;
/* Re-calculate all collisions of both particles: */
queueCollisions(nc.particle1,timeStep,true,nc.particle2,collisionQueue);
queueCollisions(nc.particle2,timeStep,true,nc.particle1,collisionQueue);
}
break;
}
}
/* Update all particles to the end of the timestep: */
if(attenuation!=Scalar(1))
{
Scalar att=Math::pow(attenuation,timeStep); // Scale attenuation factor for this time step
for(typename ParticleList::iterator pIt=particles.begin();pIt!=particles.end();++pIt)
{
/* Move the particle to the end of the time step: */
pIt->position+=pIt->velocity*(timeStep-pIt->timeStamp);
pIt->timeStamp=Scalar(0);
/* Update the particle's velocity: */
#if CENTRAL_GRAVITY
/* Apply the previously calculated velocity delta: */
pIt->velocity+=pIt->dv;
#else // !CENTRAL_GRAVITY
/* Apply the constant velocity delta: */
pIt->velocity+=dv;
#endif
/* Attenuate the particle's velocity: */
// pIt->velocity*=att;
}
}
else
{
for(typename ParticleList::iterator pIt=particles.begin();pIt!=particles.end();++pIt)
{
/* Move the particle to the end of the time step: */
pIt->position+=pIt->velocity*(timeStep-pIt->timeStamp);
pIt->timeStamp=Scalar(0);
/* Update the particle's velocity: */
#if CENTRAL_GRAVITY
/* Apply the previously calculated velocity delta: */
pIt->velocity+=pIt->dv;
#else // !CENTRAL_GRAVITY
/* Apply the constant velocity delta: */
pIt->velocity+=dv;
#endif
}
}
/* Update the collision sphere to the end of the time step: */
spherePosition+=sphereVelocity*(timeStep-sphereTimeStamp);
#if !CENTRAL_GRAVITY
if(invSphereMass!=Scalar(0))
sphereVelocity+=dv;
#endif
sphereTimeStamp=Scalar(0);