Banjo API 1.1.0-alpha
Low-level C99 game development API
Loading...
Searching...
No Matches
physics_particle.c
Go to the documentation of this file.
1
19
20#include <banjo/app.h>
21#include <banjo/main.h>
22#include <banjo/assert.h>
23#include <banjo/bitmap.h>
24#include <banjo/draw.h>
25#include <banjo/event.h>
26#include <banjo/log.h>
27#include <banjo/mat.h>
28#include <banjo/physics.h>
29#include <banjo/physics_2d.h>
30#include <banjo/pixel.h>
31#include <banjo/system.h>
32#include <banjo/time.h>
33#include <banjo/vec.h>
34#include <banjo/window.h>
35
36#include <stdlib.h>
37#include <time.h>
38
39#define SCREEN_WIDTH 800
40#define SCREEN_HEIGHT 600
41#define CANVAS_WIDTH SCREEN_WIDTH
42#define CANVAS_HEIGHT SCREEN_HEIGHT
43
44#define FB_PIXEL_MODE BJ_PIXEL_MODE_XRGB8888
45
48
49static void on_draw(struct bj_window*, struct bj_render_target*,
50 const struct bj_rect*, void*);
51
52// Physics constants for the solar system simulation.
53// G_SUN: gravitational constant (tuned for visual appeal, not realistic)
54// SOFTENING: prevents infinite forces when particles get very close
55// Masses: relative to Earth (Jupiter is 317.8× Earth's mass)
56#define G_SUN BJ_F(120.0)
57#define SOFTENING BJ_F(6.0)
58#define M_SUN BJ_F(1000.0)
59#define M_MERCURY BJ_F(0.055)
60#define M_VENUS BJ_F(0.815)
61#define M_EARTH BJ_F(1.0)
62#define M_MARS BJ_F(0.107)
63#define M_JUPITER BJ_F(317.8)
64
65// bj_particle_2d contains: position, velocity, forces, inverse_mass, damping
66// Forces accumulate during a frame, then bj_step_particle_2d() integrates them
67// into velocity and position changes.
68typedef struct {
71 uint32_t color;
72} planet_t;
73
74#define N_PLANETS 5
77
78#define N_ASTEROIDS 800
81
82static void update_projection() {
83 bj_mat3 ortho, viewport;
85 bj_mat3_set_viewport(&viewport, 0.f, 0.f, SCREEN_WIDTH, SCREEN_HEIGHT);
86 bj_mat3_mul(&projection, &viewport, &ortho);
87}
88
89// Calculate stable orbital velocity for a circular orbit with softening.
90// For realistic orbits, velocity must balance gravitational force.
91// Formula: v = sqrt(G*M*r² / (r² + eps²)^1.5)
92// Without this, planets would either spiral in or fly away.
94 const bj_real r2 = r*r;
95 const bj_real denom = bj_pow(r2 + eps*eps, BJ_F(1.5));
96 return (denom > BJ_FZERO) ? bj_sqrt( (G*M) * r2 / denom ) : BJ_FZERO;
97}
98
99static void init_sun() {
100 sun.damping = BJ_F(1.0);
101 sun.inverse_mass = BJ_F(1.0) / M_SUN;
102}
103
104// Initialise a planet in a stable circular orbit.
105// Setting up particles: configure position, velocity, mass, damping.
106// - Position: place at orbital radius r, angle phase
107// - Velocity: perpendicular to position vector, magnitude = orbital speed
108// - Mass: stored as inverse_mass for efficiency (F = a / inverse_mass)
109// - Damping: 1.0 = no damping (perfect conservation of energy)
110static void init_planet(planet_t* p, bj_real r, bj_real mass, uint32_t color, bj_real draw_r, bj_real phase) {
111 const bj_real a = phase;
112 p->body.position.x = r * bj_cos(a);
113 p->body.position.y = r * bj_sin(a);
114
116 p->body.velocity.x = -v * bj_sin(a);
117 p->body.velocity.y = v * bj_cos(a);
118
120 p->body.damping = BJ_F(1.0);
121 p->body.inverse_mass = BJ_F(1.0) / mass;
122
123 p->radius = draw_r;
124 p->color = color;
125}
126
127static void init_asteroids() {
129 for (size_t i = 0; i < N_ASTEROIDS; ++i) {
130 const bj_real rmin = BJ_F(190.0), rmax = BJ_F(260.0);
131 const bj_real t = (bj_real)rand() / (bj_real)RAND_MAX;
132 const bj_real u = (bj_real)rand() / (bj_real)RAND_MAX;
133 const bj_real r = rmin + (rmax - rmin) * t;
134 const bj_real a = BJ_TAU * u;
135
136 asteroids[i].position.x = r * bj_cos(a);
137 asteroids[i].position.y = r * bj_sin(a);
138
140 asteroids[i].velocity.x = -v * bj_sin(a);
141 asteroids[i].velocity.y = v * bj_cos(a);
142
143 asteroids[i].forces = BJ_VEC2_ZERO;
144 asteroids[i].damping = BJ_F(1.0);
145 asteroids[i].inverse_mass = 1.0;
146 }
147}
148
149static void initialize() {
150 init_sun();
151
152 uint32_t col_mercury = bj_pack_pixel_rgb(FB_PIXEL_MODE, 0xC8, 0xC8, 0xC8);
153 uint32_t col_venus = bj_pack_pixel_rgb(FB_PIXEL_MODE, 0xD4, 0xA3, 0x58);
154 uint32_t col_earth = bj_pack_pixel_rgb(FB_PIXEL_MODE, 0x30, 0xA0, 0xFF);
155 uint32_t col_mars = bj_pack_pixel_rgb(FB_PIXEL_MODE, 0xD0, 0x50, 0x30);
156 uint32_t col_jupiter = bj_pack_pixel_rgb(FB_PIXEL_MODE, 0xD2, 0xB4, 0x8C);
157
158 init_planet(&planets[0], BJ_F(60.0), M_MERCURY, col_mercury, BJ_F(2.0), BJ_F(0.0));
159 init_planet(&planets[1], BJ_F(90.0), M_VENUS, col_venus, BJ_F(3.0), BJ_F(1.2));
160 init_planet(&planets[2], BJ_F(130.0), M_EARTH, col_earth, BJ_F(3.2), BJ_F(2.0));
161 init_planet(&planets[3], BJ_F(170.0), M_MARS, col_mars, BJ_F(2.6), BJ_F(2.6));
162 init_planet(&planets[4], BJ_F(260.0), M_JUPITER, col_jupiter, BJ_F(6.0), BJ_F(0.8));
163
165}
166
167// The particle physics loop: apply forces, then integrate. Called from
168// fixed_step so dt is constant (1 / fixed_step_rate); the simulation
169// timestep is configured to 1/120 s in main() to keep the integrator
170// stable for this gravity setup.
171//
172// 1. bj_apply_point_gravity_softened_2d(): Accumulates gravitational force
173// into particle.forces based on distance and masses. Softening prevents
174// infinite forces when particles are very close.
175//
176// 2. bj_step_particle_2d(): Integrates accumulated forces:
177// - acceleration = forces * inverse_mass
178// - velocity += acceleration * dt (with damping)
179// - position += velocity * dt
180// - forces = zero (ready for next frame)
181//
182// This pattern allows multiple forces (gravity, wind, springs) to combine
183// naturally. Each force function just adds to particle.forces, then step
184// integrates them all at once.
185static void physics(bj_real dt) {
186 for (size_t i = 0; i < N_PLANETS; ++i) {
188 bj_step_particle_2d(&planets[i].body, dt);
189 }
190 for (size_t i = 0; i < N_ASTEROIDS; ++i) {
193 }
194}
195
196static void draw(bj_bitmap* framebuffer) {
197 bj_clear_bitmap(framebuffer);
198
199 const uint32_t col_sun = bj_pack_pixel_rgb(FB_PIXEL_MODE, 0xFF, 0xCC, 0x44);
200
201 bj_vec3 c = { sun.position.x, sun.position.y, BJ_F(1.0) };
203 bj_draw_filled_circle(framebuffer, pc.x, pc.y, BJ_F(10.0), col_sun);
204
205 for (size_t i = 0; i < N_PLANETS; ++i) {
206 c.x = planets[i].body.position.x; c.y = planets[i].body.position.y;
208 bj_draw_filled_circle(framebuffer, pc.x, pc.y, planets[i].radius, planets[i].color);
209 }
210
211 for (size_t i = 0; i < N_ASTEROIDS; ++i) {
212 c.x = asteroids[i].position.x; c.y = asteroids[i].position.y;
214 bj_put_pixel(framebuffer, (int)pc.x, (int)pc.y, asteroid_color);
215 }
216}
217
218static void* setup(struct bj_app* app, void* init_data) {
219 (void)init_data;
220
221 bj_set_fixed_step_rate(app, 120);
222
223 srand((unsigned)time(NULL));
224
225 if (!bj_begin(BJ_VIDEO_SYSTEM, 0)) {
226 bj_quit_app(app, 1);
227 return 0;
228 }
229
230 window = bj_create_window("2D Solar System + Asteroids", 100, 100, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0);
231
234
236 initialize();
237 return 0;
238}
239
240static void on_draw(
241 struct bj_window* w,
242 struct bj_render_target* target,
243 const struct bj_rect* dirty,
244 void* user_data
245) {
246 (void)w; (void)dirty; (void)user_data;
248}
249
250// Particle physics is integrated in fixed_step so the orbits are stable
251// regardless of how often step gets to fire. The 120 Hz rate set in main
252// keeps dt = 1/120 s, matching what the integrator was already clamping
253// to under the old variable-rate model.
254//
255// Particles vs Kinematics choice:
256// - Use particles when forces change (orbiting bodies, springs, interactions)
257// - Use kinematics when acceleration is constant (projectiles with gravity only)
258// Here, gravity direction/magnitude changes as planets orbit, so particles are needed.
259static void fixed_step(struct bj_app* app, struct bj_tick_info tick, void* user_data) {
260 (void)app; (void)user_data;
261 physics(tick.delta);
262}
263
264static void step(struct bj_app* app, struct bj_tick_info tick, void* user_data) {
265 (void)tick; (void)user_data;
268
270 bj_quit_app(app, 0);
271 }
272}
273
274static void teardown(struct bj_app* app, void* user_data) {
275 (void)user_data;
277 bj_end();
278}
279
280int main(int argc, char* argv[]) {
281 (void)argc; (void)argv;
283}
Application lifecycle: callback-driven setup, step, and teardown.
Assertion facility for Banjo API.
static void step(struct bj_app *app, struct bj_tick_info tick, void *user_data)
Definition audio_pcm.c:142
static void teardown(struct bj_app *app, void *user_data)
Definition audio_pcm.c:168
static void * setup(struct bj_app *app, void *init_data)
Definition audio_pcm.c:107
Header file for Bitmap type.
static void on_draw(struct bj_window *w, struct bj_render_target *target, const struct bj_rect *dirty, void *user_data)
Definition bitmap_blit.c:32
bj_window * window
Definition bitmap_blit.c:24
Header file for Bitmap drawing functions.
void draw(bj_bitmap *bmp)
Definition drawing_2d.c:135
Sytem event management API.
bj_real delta
Definition app.h:108
int bj_run_app(bj_app_setup_fn setup, bj_app_step_fn step, bj_app_fixed_step_fn fixed_step, bj_app_teardown_fn teardown, void *init_data)
Drive the application lifecycle.
void bj_set_fixed_step_rate(struct bj_app *app, int hz)
Configure the fixed-step rate (in Hz) for app.
void bj_quit_app(struct bj_app *app, int exit_code)
Signal the given application to exit on the next iteration.
Timing snapshot handed to the step and fixed-step callbacks.
Definition app.h:107
void bj_clear_bitmap(struct bj_bitmap *bitmap)
Fills the entire bitmap with the clear colour.
void bj_put_pixel(struct bj_bitmap *bitmap, size_t x, size_t y, uint32_t value)
Change the pixel colour at given coordinate.
struct bj_render_target bj_render_target
Definition api.h:369
struct bj_bitmap bj_bitmap
Definition api.h:340
struct bj_window bj_window
Definition api.h:384
void bj_draw_filled_circle(struct bj_bitmap *bitmap, int cx, int cy, int radius, uint32_t color)
Draw a filled circle onto a bitmap.
void bj_dispatch_events(void)
Poll and dispatch all pending events.
void bj_close_on_escape(struct bj_window *window, const struct bj_key_event *event, void *user_data)
Handle the ESC key to close a window.
bj_key_callback_fn bj_set_key_callback(bj_key_callback_fn callback, void *user_data)
Set the global callback for keyboard key events.
bj_real x
X component.
Definition vec.h:58
bj_real x
X component.
Definition vec.h:71
bj_real y
Y component.
Definition vec.h:59
bj_real y
Y component.
Definition vec.h:72
#define BJ_TAU
TAU in the selected bj_real precision.
Definition math.h:117
static struct bj_vec3 bj_mat3_transform_vec3(const struct bj_mat3 *restrict M, struct bj_vec3 v)
Multiply a 3×3 matrix by a 3D vector: r = M * v.
Definition mat.h:264
static void bj_mat3_set_viewport(struct bj_mat3 *restrict M, bj_real x, bj_real y, bj_real w, bj_real h)
Build a 2D viewport transform into a 3×3 matrix.
Definition mat.h:550
static void bj_mat3_set_ortho(struct bj_mat3 *restrict M, bj_real l, bj_real r, bj_real b, bj_real t)
Build a 2D orthographic projection into a 3×3 matrix.
Definition mat.h:523
#define BJ_VEC2_ZERO
Zero 2D vector literal {0, 0}.
Definition vec.h:63
#define bj_sin
Sine.
Definition math.h:250
#define BJ_FZERO
Zero constant in bj_real.
Definition math.h:93
#define bj_pow
Power.
Definition math.h:248
#define bj_cos
Cosine.
Definition math.h:241
#define BJ_F(x)
Literal suffix helper for bj_real when float is selected.
Definition math.h:82
#define bj_sqrt
Square root.
Definition math.h:251
float bj_real
Selected real type for float configuration.
Definition math.h:80
static void bj_mat3_mul(struct bj_mat3 *restrict out, const struct bj_mat3 *restrict A, const struct bj_mat3 *restrict B)
Matrix product: out = A * B.
Definition mat.h:238
3×3 column-major matrix.
Definition mat.h:75
Axis-aligned rectangle: a top-left corner plus a width and height.
Definition rect.h:33
3D vector of bj_real components.
Definition vec.h:70
struct bj_vec2 position
Definition physics_2d.h:101
bj_real damping
Definition physics_2d.h:105
struct bj_vec2 velocity
Definition physics_2d.h:102
struct bj_vec2 forces
Definition physics_2d.h:104
bj_real inverse_mass
Definition physics_2d.h:106
void bj_step_particle_2d(struct bj_particle_2d *particle, bj_real dt)
Semi-implicit Euler step for a particle.
void bj_apply_point_gravity_softened_2d(struct bj_particle_2d *restrict particle_from, const struct bj_particle_2d *restrict particle_to, const bj_real gravity_factor, const bj_real epsilon)
Apply softened point gravity to avoid singularities at small r.
2D point mass state and physical properties.
Definition physics_2d.h:100
uint32_t bj_pack_pixel_rgb(enum bj_pixel_mode mode, uint8_t red, uint8_t green, uint8_t blue)
Packs red, green, and blue components into one opaque pixel value.
bj_bool bj_begin(int systems, struct bj_error **error)
Initialises the system.
void bj_end(void)
De-initialises the system.
@ BJ_VIDEO_SYSTEM
Definition system.h:81
static void bj_invalidate_window(struct bj_window *window)
Mark the whole window as needing a repaint.
Definition window.h:513
bj_bool bj_window_should_close(struct bj_window *window)
Report whether a window's close flag is set.
struct bj_window * bj_create_window(const char *title, uint16_t x, uint16_t y, uint16_t width, uint16_t height, uint8_t flags, struct bj_error **error)
Create a window with the given attributes.
void bj_set_window_draw_callback(struct bj_window *window, bj_window_draw_fn fn, void *user_data)
Register the redraw callback for window.
struct bj_bitmap * bj_render_target_bitmap(struct bj_render_target *target)
Reach the software framebuffer behind a render target.
void bj_destroy_window(struct bj_window *window)
Destroy a window and release its resources.
static void fixed_step(struct bj_app *app, struct bj_tick_info tick, void *ud)
Logging utility functions.
Portable main() replacement with platform-aware entry shim.
Matrix types and operations for 2D and 3D transforms.
Physics helpers (SI units, but dimensionally consistent with any unit system).
Physics helpers (SI units, but dimensionally consistent with any unit system).
#define SCREEN_WIDTH
#define SCREEN_HEIGHT
#define FB_PIXEL_MODE
static void update_projection()
#define M_VENUS
uint32_t color
#define M_EARTH
bj_particle_2d body
static void init_planet(planet_t *p, bj_real r, bj_real mass, uint32_t color, bj_real draw_r, bj_real phase)
#define N_PLANETS
#define N_ASTEROIDS
bj_real radius
uint32_t asteroid_color
#define M_MARS
bj_particle_2d sun
planet_t planets[5]
#define M_JUPITER
static void init_sun()
static void init_asteroids()
#define SOFTENING
#define CANVAS_WIDTH
static bj_real orbital_speed_soft(bj_real G, bj_real M, bj_real r, bj_real eps)
bj_particle_2d asteroids[800]
static void initialize()
#define CANVAS_HEIGHT
#define M_SUN
#define M_MERCURY
bj_mat3 projection
static void physics(bj_real dt)
#define G_SUN
Header file for general pixel manipulation facilities.
Header file for system interactions.
int main(void)
Header file for time manipulation utilities.
Fixed-size vector types (2D, 3D, 4D) and inline operations.
Header file for bj_window type.