#include "random.h" #include "planet.h" static void putpixel(struct SDL_Surface *screen, const int x, const int y, const unsigned char r, const unsigned char g, const unsigned char b) { int offset = y * screen->pitch + x * 4; unsigned char *buf = screen->pixels; buf[offset++] = b; buf[offset++] = g; buf[offset] = r; } void init_planet(const SDL_Surface *screen, struct planet *p) { p->speed.x = 0; p->speed.y = 0; p->pos.x = get_random() % screen->w; p->pos.y = get_random() % screen->h; p->mass = get_random() % 1000 + 100; p->r = get_random() % 256; p->g = get_random() % 256; p->b = get_random() % 256; } void draw_planet(SDL_Surface *screen, struct planet *p) { if (p->pos.x < screen->w && p->pos.y < screen->h && p->pos.x >= 0 && p->pos.y >= 0) putpixel(screen, p->pos.x, p->pos.y, p->r, p->g, p->b); } void gravitize_planets(struct planet *a, struct planet *b, const double time) { struct vector distance, sum; double dist, f, acc; vector_sub(&a->pos, &b->pos, &distance); dist = vector_abs(&distance); vector_div(&distance, dist, &distance); f = a->mass * b->mass / (dist * dist + 5) * time; acc = f / b->mass; vector_scale(&distance, acc, &sum); vector_add(&b->speed, &sum, &b->speed); acc = f / a->mass; vector_scale(&distance, acc, &sum); vector_sub(&a->speed, &sum, &a->speed); } void move_planet(struct planet *p, const double time) { struct vector tmp; vector_scale(&p->speed, time, &tmp); vector_add(&p->pos, &tmp, &p->pos); } void print_planet(const struct planet *p) { printf("pos: (%f.%f), speed: (%f.%f), mass: %f\n", p->pos.x, p->pos.y, p->speed.x, p->speed.y, p->mass); }