xref: /haiku/src/add-ons/screen_savers/gravity/GravitySource.cpp (revision 820dca4df6c7bf955c46e8f6521b9408f50b2900)
1 /*
2  * Copyright 2012-2013 Tri-Edge AI <triedgeai@gmail.com>
3  * All rights reserved. Distributed under the terms of the MIT license.
4  */
5 
6 
7 #include "GravitySource.h"
8 
9 #include "Particle.h"
10 
11 #include <stdlib.h>
12 
13 
14 #define frand() ((float)rand() / (float)RAND_MAX)
15 
16 
17 GravitySource::GravitySource()
18 {
19 	x = 0.0f;
20 	y = 0.0f;
21 	z = 0.0f;
22 	r = 0.0f;
23 
24 	vx = 0.0f;
25 	vy = 0.0f;
26 	vz = 0.0f;
27 
28 	tx = frand() * 30.0f - 15.0f;
29 	ty = frand() * 30.0f - 15.0f;
30 	tz = frand() * 10.0f - 5.0f;
31 }
32 
33 
34 void
35 GravitySource::Tick()
36 {
37 	float dx = tx - x;
38 	float dy = ty - y;
39 	float dz = tz - z;
40 
41 	float d = dx * dx + dy * dy + dz * dz;
42 
43 	vx += dx * 0.003f;
44 	vy += dy * 0.003f;
45 	vz += dz * 0.003f;
46 
47 	x += vx;
48 	y += vy;
49 	z += vz;
50 
51 	vx *= 0.98f;
52 	vy *= 0.98f;
53 	vz *= 0.98f;
54 
55 	if (dx * dx + dy * dy + dz * dz < 1.0f) {
56 		tx = frand() * 20.0f - 10.0f;
57 		ty = frand() * 20.0f - 10.0f;
58 		tz = frand() * 10.0f - 5.0f;
59 	}
60 
61 	for (int32 i = 0; i < Particle::list->CountItems(); i++) {
62 		Particle* p = (Particle*)Particle::list->ItemAt(i);
63 		dx = x - p->x;
64 		dy = y - p->y;
65 		dz = z - p->z;
66 
67 		d = dx * dx + dy * dy + dz * dz;
68 
69 		p->vx += dx / d * 0.25f;
70 		p->vy += dy / d * 0.25f;
71 		p->vz += dz / d * 0.25f;
72 		p->vr += 1.0f / d;
73 	}
74 }
75