-
Notifications
You must be signed in to change notification settings - Fork 32
/
phys.cpp
639 lines (582 loc) · 19.6 KB
/
phys.cpp
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
#include "phys.h"
#include <algorithm>
#include <cmath>
#include <GL/gl.h>
#include <iostream>
#include "render.h"
// W W OOO RRRR L DDDD
// W W O O R RR L D DDD
// W W O O R RR L D DD
// W W O O R RR L D D
// W W O O RRRR L D D
// W W W O O R RR L D D
// W W W O O R R L D DD
// W W W O O R R L D DDD
// W W OOO R R LLLLLLL DDDD
int imin(int a, int b)
{
return a < b ? a : b;
}
int imax(int a, int b)
{
return a > b ? a : b;
}
void phys::world::update(double dt)
{
time += dt;
// Advance simulation for points: (velocity and forces)
for (unsigned int i = 0; i < points.size(); i++)
points[i]->update(dt);
// Iterate the spring relaxation (can tune this parameter, or make it scale automatically depending on free time)
doSprings(dt);
// Check if any springs exceed their breaking strain:
for (std::vector<spring*>::iterator iter = springs.begin(); iter != springs.end();)
{
spring *spr = *iter;
iter++;
if (spr->isBroken()) // have to delete after erasure - else there is a possibility of
delete spr; // other objects accessing a bad pointer during this cleanup
}
// Tell each ship to update all of its water stuff
for (unsigned int i = 0; i < ships.size(); i++)
ships[i]->update(dt);
}
void phys::world::doSprings(double dt)
{
int nchunks = springScheduler.getNThreads();
int springchunk = springs.size() / nchunks + 1;
for (int outiter = 0; outiter < 3; outiter++)
{
for (int iteration = 0; iteration < 8; iteration++)
{
for (int i = springs.size() - 1; i > 0; i -= springchunk)
{
springScheduler.schedule(new springCalculateTask(this, imax(i - springchunk, 0), i));
}
springScheduler.wait();
}
float dampingamount = (1 - pow(0.0, dt)) * 0.5;
for (unsigned int i = 0; i < springs.size(); i++)
springs[i]->damping(dampingamount);
}
}
phys::world::springCalculateTask::springCalculateTask(world *_wld, int _first, int _last)
{
wld = _wld;
first = _first;
last = _last;
}
void phys::world::springCalculateTask::process()
{
for (int i = first; i <= last; i++)
wld->springs[i]->update();
}
phys::world::pointIntegrateTask::pointIntegrateTask(world *_wld, int _first, int _last, float _dt)
{
wld = _wld;
first = _first;
last = _last;
dt = _dt;
}
void phys::world::pointIntegrateTask::process()
{
for (int i = first; i <= last; i++)
{
wld->points[i]->pos += wld->points[i]->force * dt;
wld->points[i]->force = vec2(0, 0);
}
}
void phys::world::render(double left, double right, double bottom, double top)
{
// Draw the ocean floor
renderLand(left, right, bottom, top);
if (quickwaterfix)
renderWater(left, right, bottom, top);
// Draw all the points and springs
for (unsigned int i = 0; i < points.size(); i++)
points[i]->render();
for (unsigned int i = 0; i < springs.size(); i++)
springs[i]->render();
if (!xraymode)
for (unsigned int i = 0; i < ships.size(); i++)
ships[i]->render();
if (showstress)
for (unsigned int i = 0; i < springs.size(); i++)
if (springs[i]->isStressed())
springs[i]->render(true);
if (!quickwaterfix)
renderWater(left, right, bottom, top);
glBegin(GL_LINES);
glLineWidth(1.f);
glEnd();
//buildBVHTree(true, points, collisionTree);
}
void swapf(float &x, float &y)
{
float temp = x;
x = y;
y = temp;
}
float medianOf3(float a, float b, float c)
{
if (a < b)
swapf(a, b);
if (b < c)
swapf(b, c);
if (a < b)
swapf(a, b);
return b;
}
void phys::world::buildBVHTree(bool splitInX, std::vector<point*> &pointlist, BVHNode *thisnode, int depth)
{
int npoints = pointlist.size();
if (npoints)
thisnode->volume = pointlist[0]->getAABB();
for (unsigned int i = 1; i < npoints; i++)
thisnode->volume.extendTo(pointlist[i]->getAABB());
thisnode->volume.render();
if (npoints <= BVHNode::MAX_N_POINTS || depth >= BVHNode::MAX_DEPTH)
{
thisnode->isLeaf = true;
thisnode->pointCount = npoints;
for (int i = 0; i < npoints; i++)
thisnode->points[i] = pointlist[i];
}
else
{
float pivotline = splitInX ?
medianOf3(pointlist[0]->pos.x, pointlist[npoints / 2]->pos.x, pointlist[npoints - 1]->pos.x) :
medianOf3(pointlist[0]->pos.y, pointlist[npoints / 2]->pos.y, pointlist[npoints - 1]->pos.y);
std::vector<point*> listL;
std::vector<point*> listR;
listL.reserve(npoints / 2);
listR.reserve(npoints / 2);
for (int i = 0; i < npoints; i++)
{
if (splitInX ? pointlist[i]->pos.x < pivotline : pointlist[i]->pos.y < pivotline)
listL.push_back(pointlist[i]);
else
listR.push_back(pointlist[i]);
}
buildBVHTree(!splitInX, listL, thisnode->l, depth + 1);
buildBVHTree(!splitInX, listR, thisnode->r, depth + 1);
}
}
void phys::world::renderLand(double left, double right, double bottom, double top)
{
glColor4f(0.5, 0.5, 0.5, 1);
double slicewidth = (right - left) / 200.0;
for (double slicex = left; slicex < right; slicex += slicewidth)
{
glBegin(GL_TRIANGLE_STRIP);
glVertex3f(slicex, oceanfloorheight(slicex), -1);
glVertex3f(slicex + slicewidth, oceanfloorheight(slicex + slicewidth), -1);
glVertex3f(slicex, bottom, -1);
glVertex3f(slicex + slicewidth, bottom, -1);
glEnd();
}
}
void phys::world::renderWater(double left, double right, double bottom, double top)
{
// Cut the water into vertical slices (to get the different heights of waves) and draw it
glColor4f(0, 0.25, 1, 0.5);
double slicewidth = (right - left) / 100.0;
for (double slicex = left; slicex < right; slicex += slicewidth)
{
glBegin(GL_TRIANGLE_STRIP);
glVertex3f(slicex, waterheight(slicex), -1);
glVertex3f(slicex + slicewidth, waterheight(slicex + slicewidth), -1);
glVertex3f(slicex, bottom, -1);
glVertex3f(slicex + slicewidth, bottom, -1);
glEnd();
}
}
float phys::world::oceanfloorheight(float x)
{
/*x += 1024.f;
x = x - 2048.f * floorf(x / 2048.f);
float t = x - floorf(x);
return oceandepthbuffer[(int)floorf(x)] * (1 - t) + oceandepthbuffer[((int)ceilf(x)) % 2048] * t;*/
return (sinf(x * 0.005f) * 10.f + sinf(x * 0.015f) * 6.f - sin(x * 0.0011f) * 45.f) - seadepth;
}
// Function of time and x (though time is constant during the update step, so no need to parameterise it)
float phys::world::waterheight(float x)
{
return (sinf(x * 0.1f + time) * 0.5f + sinf(x * 0.3f - time * 1.1f) * 0.3f) * waveheight;
}
// Destroy all points within a 0.5m radius (could parameterise the radius but...)
void phys::world::destroyAt(vec2f pos)
{
for (std::vector<point*>::iterator iter = points.begin(); iter != points.end();)
{
point *p = *iter;
iter++;
if ((p->pos - pos).length() < 0.5f)
{
delete p; // have to remove reference before deleting, else other cleanup code will use bad memory!
iter--;
}
}
}
// Attract all points to a single position
void phys::world::drawTo(vec2f target)
{
for (std::vector<point*>::iterator iter = points.begin(); iter != points.end(); iter++)
{
vec2f &pos = (*iter)->pos;
vec2f dir = (target - pos);
double magnitude = 50000 / sqrt(0.1 + dir.length());
(*iter)->applyForce(dir.normalise() * magnitude);
}
}
// Copy parameters and set up initial params:
phys::world::world(vec2f _gravity, double _buoyancy, double _strength)
{
time = 0;
gravity = _gravity;
buoyancy = _buoyancy;
strength = _strength;
waterpressure = 0.3;
waveheight = 1.0;
seadepth = 150;
collisionTree = BVHNode::allocateTree();
}
// Destroy everything in the set order
phys::world::~world()
{
// DESTROY THE WORLD??? Y/N
for (unsigned int i = 0; i < springs.size(); i++)
delete springs[i];
springs.clear();
for (unsigned int i = 0; i < points.size(); i++)
delete points[i];
for (unsigned int i = 0; i < ships.size(); i++)
delete ships[i];
}
// PPPP OOO IIIIIII N N TTTTTTT
// P PP O O I NN N T
// P PP O O I N N N T
// P PP O O I N N N T
// PPPP O O I N N N T
// P O O I N N N T
// P O O I N N N T
// P O O I N NN T
// P OOO IIIIIII N N T
// Just copies parameters into relevant fields:
phys::point::point(world *_parent, vec2 _pos, material *_mtl, double _buoyancy)
{
wld = _parent;
wld->points.push_back(this);
pos = _pos;
lastpos = pos;
mtl = _mtl;
buoyancy = _buoyancy;
isLeaking = false;
water = 0;
}
void phys::point::applyForce(vec2f f)
{
force += f;
}
void phys::point::update(double dt)
{
double mass = mtl->mass;
this->applyForce(wld->gravity * (mass * (1 + fmin(water, 1) * wld->buoyancy * buoyancy))); // clamp water to 1, so high pressure areas are not heavier.
// Buoyancy:
if (pos.y < wld->waterheight(pos.x))
this->applyForce(wld->gravity * (-wld->buoyancy * buoyancy * mass));
vec2f newlastpos = pos;
// Water drag:
if (pos.y < wld->waterheight(pos.x))
lastpos += (pos - lastpos) * (1 - pow(0.6, dt));
// Apply verlet integration:
pos += (pos - lastpos) + force * (dt * dt / mass);
// Collision with seafloor:
float floorheight = wld->oceanfloorheight(pos.x);
if (pos.y < floorheight)
{
vec2f dir = vec2f(floorheight - wld->oceanfloorheight(pos.x + 0.01f), 0.01f).normalise(); // -1 / derivative => perpendicular to surface!
pos += dir * (floorheight - pos.y);
}
lastpos = newlastpos;
force = vec2f(0, 0);
}
vec2f phys::point::getPos()
{
return pos;
}
vec3f phys::point::getColour(vec3f basecolour)
{
double wetness = fmin(water, 1) * 0.7;
return basecolour * (1 - wetness) + vec3f(0, 0, 0.8) * wetness;
}
void phys::point::breach()
{
isLeaking = true;
for (std::set<ship::triangle*>::iterator iter = tris.begin(); iter != tris.end();)
{
ship::triangle *t = *iter;
iter++;
delete t;
}
}
void phys::point::render()
{
// Put a blue blob on leaking nodes (was more for debug purposes, but looks better IMO)
if (isLeaking)
{
glColor3f(0, 0, 1);
glBegin(GL_POINTS);
glVertex3f(pos.x, pos.y, -1);
glEnd();
}
}
double phys::point::getPressure()
{
return wld->gravity.length() * fmax(-pos.y, 0) * 0.1; // 0.1 = scaling constant, represents 1/ship width
}
phys::AABB phys::point::getAABB()
{
return phys::AABB(pos - vec2(radius, radius), pos + vec2(radius, radius));
}
phys::point::~point()
{
// get rid of any attached triangles:
breach();
// remove any springs attached to this point:
for (std::vector<spring*>::iterator iter = wld->springs.begin(); iter != wld->springs.end();)
{
spring *spr = *iter;
iter++;
if (spr->a == this || spr->b == this)
{
delete spr;
iter--;
}
}
// remove any references:
for (unsigned int i = 0; i < wld->ships.size(); i++)
wld->ships[i]->points.erase(this);
std::vector<point*>::iterator iter = std::find(wld->points.begin(), wld->points.end(), this);
if (iter != wld->points.end())
wld->points.erase(iter);
}
// SSS PPPP RRRR IIIIIII N N GGGGG
// SS SS P PP R RR I NN N GG
// S P PP R RR I N N N GG
// SS P PP R RR I N N N G
// SSS PPPP RRRR I N N N G
// SS P R RR I N N N G GGGG
// S P R R I N N N GG G
// SS SS P R R I N NN GG GG
// SSS P R R IIIIIII N N GGGG
phys::spring::spring(world *_parent, point *_a, point *_b, material *_mtl, double _length)
{
wld = _parent;
_parent->springs.push_back(this);
a = _a;
b = _b;
if (_length == -1)
length = (a->pos - b->pos).length();
else
length = _length;
mtl = _mtl;
}
phys::spring::~spring()
{
// Used to do more complicated checks, but easier (and better) to make everything leak when it breaks
a->breach();
b->breach();
// Scour out any references to this spring
for (unsigned int i = 0; i < wld->ships.size(); i++)
{
ship *shp = wld->ships[i];
if (shp->adjacentnodes.find(a) != shp->adjacentnodes.end())
shp->adjacentnodes[a].erase(b);
if (shp->adjacentnodes.find(b) != shp->adjacentnodes.end())
shp->adjacentnodes[b].erase(a);
}
std::vector <spring*>::iterator iter = std::find(wld->springs.begin(), wld->springs.end(), this);
if (iter != wld->springs.end())
wld->springs.erase(iter);
}
void phys::spring::update()
{
// Try to space the two points by the equilibrium length (need to iterate to actually achieve this for all points, but it's FAAAAST for each step)
vec2f correction_dir = (b->pos - a->pos);
float currentlength = correction_dir.length();
correction_dir *= (length - currentlength) / (length * (a->mtl->mass + b->mtl->mass) * 0.85); // * 0.8 => 25% overcorrection (stiffer, converges faster)
a->pos -= correction_dir * b->mtl->mass; // if b is heavier, a moves more.
b->pos += correction_dir * a->mtl->mass; // (and vice versa...)
}
void phys::spring::damping(float amount)
{
vec2f springdir = (a->pos - b->pos).normalise();
springdir *= (a->pos - a->lastpos - (b->pos - b->lastpos)).dot(springdir) * amount; // relative velocity spring direction = projected velocity, amount = amount of projected velocity that remains after damping
a->lastpos += springdir;
b->lastpos -= springdir;
}
void phys::spring::render(bool showStress)
{
// If member is heavily stressed, highlight it in red (ignored if world's showstress field is false)
glBegin(GL_LINES);
if (showStress)
glColor3f(1, 0, 0);
else
render::setColour(a->getColour(mtl->colour));
glVertex3f(a->pos.x, a->pos.y, -1);
if (!showStress)
render::setColour(b->getColour(mtl->colour));
glVertex3f(b->pos.x, b->pos.y, -1);
glEnd();
}
bool phys::spring::isStressed()
{
// Check whether strain is more than the word's base strength * this object's relative strength
return (a->pos - b->pos).length() / this->length > 1 + (wld->strength * mtl->strength) * 0.25;
}
bool phys::spring::isBroken()
{
// Check whether strain is more than the word's base strength * this object's relative strength
return (a->pos - b->pos).length() / this->length > 1 + (wld->strength * mtl->strength);
}
// SSS H H IIIIIII PPPP
// SS SS H H I P PP
// S H H I P PP
// SS H H I P PP
// SSS HHHHHHH I PPPP
// SS H H I P
// S H H I P
// SS SS H H I P
// SSS H H IIIIIII P
phys::ship::ship(world *_parent)
{
wld = _parent;
wld->ships.push_back(this);
}
void phys::ship::update(double dt)
{
leakWater(dt);
for (int i = 0; i < 4; i++)
{
gravitateWater(dt);
balancePressure(dt);
}
for (int i = 0; i < 4; i++)
balancePressure(dt);
}
void phys::ship::leakWater(double dt)
{
// Stuff some water into all the leaking nodes, if they're not under too much pressure
for (std::set<point*>::iterator iter = points.begin(); iter != points.end(); iter++)
{
point *p = *iter;
double pressure = p->getPressure();
if (p->isLeaking && p->pos.y < wld->waterheight(p->pos.x) && p->water < 1.5)
{
p->water += dt * wld->waterpressure * (pressure - p->water);
}
}
}
void phys::ship::gravitateWater(double dt)
{
// Water flows into adjacent nodes in a quantity proportional to the cos of angle the beam makes
// against gravity (parallel with gravity => 1 (full flow), perpendicular = 0)
for (std::map<point*, std::set<point*> >::iterator iter = adjacentnodes.begin();
iter != adjacentnodes.end(); iter++)
{
point *a = iter->first;
for (std::set<point*>::iterator second = iter->second.begin(); second != iter->second.end(); second++)
{
point *b = *second;
double cos_theta = (b->pos - a->pos).normalise().dot(wld->gravity.normalise());
if (cos_theta > 0)
{
double correction = std::min(0.5 * cos_theta * dt, a->water); // The 0.5 can be tuned, it's just to stop all the water being stuffed into the first node...
a->water -= correction;
b->water += correction;
}
}
}
}
void phys::ship::balancePressure(double dt)
{
// If there's too much water in this node, try and push it into the others
// (This needs to iterate over multiple frames for pressure waves to spread through water)
for (std::map<point*, std::set<point*> >::iterator iter = adjacentnodes.begin();
iter != adjacentnodes.end(); iter++)
{
point *a = iter->first;
if (a->water < 1) // if water content is not above threshold, no need to force water out
continue;
for (std::set<point*>::iterator second = iter->second.begin(); second != iter->second.end(); second++)
{
point *b = *second;
double correction = (b->water - a->water) * 8 * dt; // can tune this number; value of 1 means will equalise in 1 second.
a->water += correction;
b->water -= correction;
}
}
}
void phys::ship::render()
{
for (std::set<ship::triangle*>::iterator iter = triangles.begin(); iter != triangles.end(); iter++)
{
triangle *t = *iter;
render::triangle(t->a->pos, t->b->pos, t->c->pos,
t->a->getColour(t->a->mtl->colour),
t->b->getColour(t->b->mtl->colour),
t->c->getColour(t->c->mtl->colour));
}
}
phys::ship::~ship()
{
/*for (unsigned int i = 0; i < triangles.size(); i++)
delete triangles[i];*/
}
phys::ship::triangle::triangle(phys::ship *_parent, point *_a, point *_b, point *_c)
{
parent = _parent;
a = _a;
b = _b;
c = _c;
a->tris.insert(this);
b->tris.insert(this);
c->tris.insert(this);
}
phys::ship::triangle::~triangle()
{
parent->triangles.erase(this);
a->tris.erase(this);
b->tris.erase(this);
c->tris.erase(this);
}
phys::AABB::AABB(vec2 _bottomleft, vec2 _topright)
{
bottomleft = _bottomleft;
topright = _topright;
}
void phys::AABB::extendTo(phys::AABB other)
{
if (other.bottomleft.x < bottomleft.x)
bottomleft.x = other.bottomleft.x;
if (other.bottomleft.y < bottomleft.y)
bottomleft.y = other.bottomleft.y;
if (other.topright.x > topright.x)
topright.x = other.topright.x;
if (other.topright.y > topright.y)
topright.y = other.topright.y;
}
void phys::AABB::render()
{
render::box(bottomleft, topright);
}
phys::BVHNode* phys::BVHNode::allocateTree(int depth)
{
if (depth <= 0)
return 0;
BVHNode *thisnode = new BVHNode;
thisnode->l = allocateTree(depth - 1);
thisnode->r = allocateTree(depth - 1);
return thisnode;
}