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
|
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_timer.h>
#include <time.h>
#include <math.h>
#define NUM_BODIES 500
#define PARTSIZE 10
#define WIDTH 512
#define HEIGHT 512
struct body { double x, y, dx, dy; };
typedef struct vec { float x, y; } vector;
struct body B[NUM_BODIES];
void init()
{
srand(time(NULL));
for(int i = 0; i < NUM_BODIES; i++) {
B[i].x = WIDTH/2 + rand() % 20 - 40;
B[i].y = HEIGHT/2 + rand() % 20 - 40;
B[i].dx = rand() % 50 - 100;
B[i].dy = rand() % 50 - 100;
}
}
float geomdist(int i, int j)
{
return sqrt(pow( B[i].x - B[j].x, 2 ) + pow( B[i].y - B[j].y, 2 ));
}
void updatePos() {
for(int i = 0; i < NUM_BODIES; i++) {
B[i].x += B[i].dx;
B[i].y += B[i].dy;
printf("%f %f |", B[i].dx, B[i].dy);
vector mass_centre_vec;
for(int j = 0; j < NUM_BODIES; j++) {
if(i == j) continue;
mass_centre_vec.x += (B[j].x - B[i].x) /geomdist(i, j);
mass_centre_vec.y += (B[j].y - B[i].y) /geomdist(i, j);
}
mass_centre_vec.x /= NUM_BODIES - 1;
mass_centre_vec.y /= NUM_BODIES - 1;
B[i].dx = mass_centre_vec.x;
B[i].dy = mass_centre_vec.y;
}
}
int processEvents(SDL_Window *window)
{
SDL_Event event;
while(SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_WINDOWEVENT_CLOSE:
if(window)
{
SDL_DestroyWindow(window);
window = NULL;
return 1;
}
break;
case SDL_KEYDOWN:
switch(event.key.keysym.sym) {
case SDLK_ESCAPE:
return 1;
}
}
}
return 0;
}
void render(SDL_Renderer *renderer, SDL_Rect particles[NUM_BODIES])
{
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // фон
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255);
for(int i = 0; i < NUM_BODIES; i++) {
particles[i].h = PARTSIZE;
particles[i].w = PARTSIZE;
particles[i].x = B[i].x - PARTSIZE/2;
particles[i].y = B[i].y - PARTSIZE/2;
SDL_RenderDrawRect(renderer, &particles[i]);
}
SDL_RenderPresent(renderer);
}
int main(int argc, char *argv[])
{
SDL_Window *window = NULL;
SDL_Renderer *renderer = NULL;
init();
SDL_Init(SDL_INIT_VIDEO);
SDL_Rect particles[NUM_BODIES];
window = SDL_CreateWindow("Universe simulation",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
WIDTH,
HEIGHT,
0);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
while(1) {
if(processEvents(window) == 1)
break;
render(renderer, particles);
updatePos(renderer);
SDL_Delay(10);
}
return 0;
}
|