X-Git-Url: http://git.mutantstargoat.com/user/nuclear/?p=ld42_outofspace;a=blobdiff_plain;f=src%2Fgamescr.cc;h=4bac184a9f8fe7fa8cbeee8d00f9ece739c9ed67;hp=0ae16723bd9bb638e30803ecc69d2ff282146e1b;hb=d0367d9119f81afd77045481b9e53d5a17b89a73;hpb=6206d87eb7b24c04c5675404bdb13e9ace86f2fe diff --git a/src/gamescr.cc b/src/gamescr.cc index 0ae1672..4bac184 100644 --- a/src/gamescr.cc +++ b/src/gamescr.cc @@ -1,24 +1,548 @@ +#include +#include +#include #include "game.h" #include "screen.h" #include "opengl.h" +#include "texture.h" +#include "sdr.h" +#include "mesh.h" +#include "meshgen.h" +#include "goatkit/goatkit.h" + +/* NOTES: + * - whistle hhgg music + * - select objects and center camera on them + * - we need to rely on actual collisions instead of grid occupancy + */ + +struct Particle { + float radius; + float mass; + Vec2 pos; + Vec2 vel; + + float vis_height; + + Particle *next, *prev; +}; + +struct Emitter { + Vec2 pos; + float mass; + float rate, chunk; + float angle, spread; + + float spawn_pending; +}; + +struct Rect { + int x, y; + int width, height; +}; + +struct QuadMesh { + Vec3 *v; + Vec2 *uv; + uint16_t *idx; + + int num_verts, num_idx, num_quads; + + unsigned int vbo_v, vbo_uv, ibo; +}; + +#define SIM_DT 0.016 + +#define GRID_SIZE 2048 +#define GRID_BITS 11 +#define GRID_X(idx) (((idx) >> GRID_BITS) & (GRID_SIZE - 1)) +#define GRID_Y(idx) ((idx) & (GRID_SIZE - 1)) +#define GRID_DELTA ((float)FIELD_SIZE / (float)GRID_SIZE) + +#define FIELD_SIZE 2048 +#define MIN_CAM_DIST 1.0f +#define MAX_CAM_DIST 350.0f + +#define MASS_TO_RADIUS(m) log((m) + 1.0) + +#define CONTRIB_THRES 0.005 +#define CONTRIB_RANGE(m) sqrt((m) / CONTRIB_THRES) + +/* gravitational strength */ +#define GRAV_STR 16.0f + +#define INIT_MASS_BUDGET 600.0f +#define EM_MASS_DEFAULT 100.0f + +static int pos_to_grid_x_noclamp(float x); +static int pos_to_grid_y_noclamp(float y); +static int pos_to_grid(float x, float y); +static Vec2 grid_to_pos(int gx, int gy); + +static void calc_contrib_bounds(const Vec2 &pos, float mass, Rect *rect); +static void add_influence(const Vec2 &pos, float mass, float radius, const Rect &cbox); + +static Vec2 calc_field_grad(int gidx); + +static void destroy_quadmesh(QuadMesh *m); +static void draw_quadmesh(const QuadMesh *m, unsigned int prim = GL_QUADS); +static void gen_quad_plane(QuadMesh *mesh, float width, float height, int usub, int vsub); + +static void spawn_particle(const Vec2 &pos, const Vec2 &vel, float mass); +static void add_particle(Particle *p); +static void remove_particle(Particle *p); +static Particle *alloc_particle(); +void free_particle(Particle *p); + +static bool pause; + +static float grid[GRID_SIZE * GRID_SIZE]; +static Particle *grid_part[GRID_SIZE * GRID_SIZE]; +static Texture *grid_tex; + +static Particle *plist; + +static std::vector emitters; + +static Texture *gvis_tex; // texture tile for visualizing a grid +static unsigned int field_sdr; +static int tess_level = 64; +static float field_scale = 16.0f; + +static QuadMesh field_mesh; + +static Mesh *pmesh; +static unsigned int particle_sdr; + +static Vec2 cam_pos; +static float cam_theta; +static float cam_dist = 100.0f; +static Vec2 *targ_pos = &cam_pos; +static Mat4 view_matrix, proj_matrix; + +static bool wireframe; +static int mouse_x, mouse_y; + +// emitter placement data (filled by event handlers, completed in update) +static bool emit_place_pending; +static Vec2 emit_place_pos; + +static bool placing_emitter; + +static float mass_left; + +// UI +static void ui_handler(goatkit::Widget *w, const goatkit::Event &ev, void *cls); +static int ui_virt_width = 800; +static int ui_virt_height = 600; +static goatkit::Screen *ui; +static goatkit::Button *bn_emitter; +static goatkit::Slider *slider_mass; +static bool mouse_over_ui; + bool GameScreen::init() { + grid_tex = new Texture; + grid_tex->create(GRID_SIZE, GRID_SIZE, TEX_2D, GL_LUMINANCE32F_ARB); + grid_tex->set_anisotropy(glcaps.max_aniso); + + gvis_tex = new Texture; + if(!gvis_tex->load("data/purple_grid.png")) { + return false; + } + gvis_tex->set_anisotropy(glcaps.max_aniso); + + unsigned int vsdr, tcsdr, tesdr, psdr; + + if(!(vsdr = load_vertex_shader("sdr/field.v.glsl")) || + !(tcsdr = load_tessctl_shader("sdr/field.tc.glsl")) || + !(tesdr = load_tesseval_shader("sdr/field.te.glsl")) || + !(psdr = load_pixel_shader("sdr/field.p.glsl"))) { + return false; + } + + if(!(field_sdr = create_program_link(vsdr, tcsdr, tesdr, psdr, 0))) { + return false; + } + set_uniform_int(field_sdr, "gvis_tex", 0); + set_uniform_int(field_sdr, "field_tex", 1); + set_uniform_float(field_sdr, "gvis_scale", FIELD_SIZE / 32.0f); + set_uniform_int(field_sdr, "tess_level", tess_level); + set_uniform_float(field_sdr, "field_scale", field_scale); + + gen_quad_plane(&field_mesh, FIELD_SIZE, FIELD_SIZE, 32, 32); + + pmesh = new Mesh; + gen_geosphere(pmesh, 1.0, 2); + + if(!(particle_sdr = create_program_load("sdr/sph.v.glsl", "sdr/sph.p.glsl"))) { + return false; + } + + mass_left = INIT_MASS_BUDGET; + + ui = new goatkit::Screen; + ui->hide(); + + bn_emitter = new goatkit::Button; + bn_emitter->set_position(5, 5); + bn_emitter->set_size(250, 30); + bn_emitter->set_text("new white hole"); + bn_emitter->set_callback(goatkit::EV_CLICK, ui_handler); + ui->add_widget(bn_emitter); + + slider_mass = new goatkit::Slider; + slider_mass->set_position(300, 5); + slider_mass->set_size(400, 30); + slider_mass->set_continuous_change(false); + slider_mass->set_range(0, mass_left); + slider_mass->set_value(EM_MASS_DEFAULT); + slider_mass->set_callback(goatkit::EV_CHANGE, ui_handler); + ui->add_widget(slider_mass); + + ui->set_visibility_transition(300); + + assert(glGetError() == GL_NO_ERROR); return true; } void GameScreen::destroy() { + free_program(field_sdr); + delete gvis_tex; + delete grid_tex; + destroy_quadmesh(&field_mesh); + delete pmesh; + + delete bn_emitter; +} + +void GameScreen::start() +{ + ui->show(); + slider_mass->hide(); } +void GameScreen::stop() +{ +} + +static void simstep() +{ + if(pause) return; + + // distribute forces + Particle *p = plist; + while(p) { + int num_emitters = emitters.size(); + for(int i=0; ipos - em->pos; + p->vel += dir * em->mass * GRAV_STR * 0.01 / dot(dir, dir) * SIM_DT; + } + + Particle *q = plist; + while(q) { + if(p != q) { + Vec2 dir = q->pos - p->pos; + float accel = GRAV_STR * q->mass / dot(dir, dir); + p->vel += dir * accel * SIM_DT; + } + q = q->next; + } + p = p->next; + } + + // move existing particles + p = plist; + while(p) { + // calculate the field gradient at the particle position + int gidx = pos_to_grid(p->pos.x, p->pos.y); + //Vec2 grad = calc_field_grad(gidx) * GRAV_STR; + + //p->vel += grad * SIM_DT; + p->pos += p->vel * SIM_DT; + + // if it moved outside of the simulation field, remove it + int gx = pos_to_grid_x_noclamp(p->pos.x); + int gy = pos_to_grid_y_noclamp(p->pos.y); + if(gx < 0 || gx >= GRID_SIZE || gy < 0 || gy >= GRID_SIZE) { + Particle *next = p->next; + grid_part[gidx] = 0; + remove_particle(p); + free_particle(p); + p = next; + continue; + } + + // find the grid cell it's moving to + int gidx_next = pos_to_grid(p->pos.x, p->pos.y); + p->vis_height = 0.0f;//-grid[gidx_next] * field_scale; + + if(gidx_next == gidx) { + p = p->next; + continue; + } + + Particle *destp = grid_part[gidx_next]; + if(destp) { + assert(destp != p); + // another particle at the destination, merge them + destp->vel += p->vel; + destp->mass += p->mass; + destp->radius = MASS_TO_RADIUS(destp->mass); + + // ... and remove it + grid_part[gidx] = 0; + Particle *next = p->next; + remove_particle(p); + free_particle(p); + p = next; + } else { + // destination is empty, go there + if(gidx != gidx_next) { + grid_part[gidx] = 0; + grid_part[gidx_next] = p; + } + + p = p->next; + } + } + + // TODO destroy particles which left the simulation field + + // spawn particles + int num_emitters = emitters.size(); + for(int i=0; ispawn_pending += em->rate * SIM_DT; + while(em->spawn_pending >= 1.0f && em->mass > 0.0f) { + Vec2 pvel; // XXX calc eject velocity + + float angle = (float)rand() / (float)RAND_MAX * (M_PI * 2.0); + float emradius = MASS_TO_RADIUS(em->mass); + Vec2 ppos = em->pos + Vec2(cos(angle), sin(angle)) * emradius * 1.00001; + + float pmass = em->chunk > em->mass ? em->mass : em->chunk; + spawn_particle(ppos, pvel, pmass); + em->mass -= pmass; + + em->spawn_pending -= 1.0f; + } + } + + // remove dead emitters + std::vector::iterator it = emitters.begin(); + while(it != emitters.end()) { + Emitter *em = *it; + + if(em->mass <= 0.0f) { + printf("emitter depleted\n"); + it = emitters.erase(it); + delete em; + } else { + it++; + } + } + + // calculate gravitational field - assume field within radius constant: m / r^2 + // first clear the field, and then add contributions + memset(grid, 0, sizeof grid); + + // contribution of emitters + for(int i=0; ipos, em->mass, &cbox); + float emradius = MASS_TO_RADIUS(em->mass); + + add_influence(em->pos, -em->mass, emradius, cbox); + } + + // contribution of particles + p = plist; + while(p) { + Rect cbox; + calc_contrib_bounds(p->pos, p->mass, &cbox); + add_influence(p->pos, p->mass, p->radius, cbox); + p = p->next; + } + + // update texture + assert(glGetError() == GL_NO_ERROR); + grid_tex->bind(); + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, GRID_SIZE, GRID_SIZE, GL_LUMINANCE, + GL_FLOAT, grid); + assert(glGetError() == GL_NO_ERROR); +} + +static void update() +{ + if(placing_emitter) { + float x = (float)mouse_x / (float)win_width; + float y = 1.0f - (float)mouse_y / (float)win_height; + Ray pick_ray = mouse_pick_ray(x, y, view_matrix, proj_matrix); + + float ndotdir = pick_ray.dir.y; + if(fabs(ndotdir) > 1e-6f) { + float ndotpdir = -pick_ray.origin.y; + float t = ndotpdir / ndotdir; + + x = pick_ray.origin.x + pick_ray.dir.x * t; + y = pick_ray.origin.z + pick_ray.dir.z * t; + + if(x >= -FIELD_SIZE / 2 && x < FIELD_SIZE / 2 && + y >= -FIELD_SIZE / 2 && y < FIELD_SIZE / 2) { + emit_place_pos = Vec2(x, y); + } + } + } + + if(emit_place_pending) { + emit_place_pending = false; + Emitter *em = new Emitter; + em->pos = emit_place_pos; + em->mass = slider_mass->get_value(); + em->rate = 10; + em->chunk = 0.001 * em->mass; + em->angle = -1; + em->spread = 0; + em->spawn_pending = 0; + emitters.push_back(em); + + mass_left -= em->mass; + if(mass_left < 0.0f) mass_left = 0.0f; + + Rect cbox; + calc_contrib_bounds(em->pos, em->mass, &cbox); + printf("bounds: %d,%d %dx%d\n", cbox.x, cbox.y, cbox.width, cbox.height); + } + + // update simulation + static float interval; + interval += frame_dt; + if(interval >= SIM_DT) { + interval -= SIM_DT; + simstep(); + assert(glGetError() == GL_NO_ERROR); + } + + // update projection matrix + proj_matrix.perspective(deg_to_rad(60.0f), win_aspect, 0.5, 5000.0); + + // update view matrix + Vec3 targ; + if(targ_pos) { + targ.x = targ_pos->x; + targ.z = targ_pos->y; + } + + float theta = -deg_to_rad(cam_theta); + Vec3 camdir = Vec3(sin(theta) * cam_dist, pow(cam_dist * 0.1, 2.0) + 0.5, cos(theta) * cam_dist); + Vec3 campos = targ + camdir; + + view_matrix.inv_lookat(campos, targ, Vec3(0, 1, 0)); +} void GameScreen::draw() { - glClearColor(1, 0, 0, 1); + update(); + + glClearColor(0.01, 0.01, 0.01, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + glMatrixMode(GL_PROJECTION); + glLoadMatrixf(proj_matrix[0]); + glMatrixMode(GL_MODELVIEW); + glLoadMatrixf(view_matrix[0]); + + // draw gravitational field + if(wireframe) { + glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); + + float amb[] = {0.5, 0.5, 0.5, 1.0}; + glLightModelfv(GL_LIGHT_MODEL_AMBIENT, amb); + } else { + float amb[] = {0.01, 0.01, 0.01, 1.0}; + glLightModelfv(GL_LIGHT_MODEL_AMBIENT, amb); + } + + bind_texture(gvis_tex, 0); + bind_texture(grid_tex, 1); + + glUseProgram(field_sdr); + glPatchParameteri(GL_PATCH_VERTICES, 4); + draw_quadmesh(&field_mesh, GL_PATCHES); + + if(wireframe) { + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + } + + // draw particles + glUseProgram(particle_sdr); + + Particle *p = plist; + while(p) { + int gidx = pos_to_grid(p->pos.x, p->pos.y); + + glPushMatrix(); + glTranslatef(p->pos.x, p->vis_height, p->pos.y); + glScalef(p->radius, p->radius, p->radius); + + pmesh->draw(); + + glPopMatrix(); + p = p->next; + } + + glUseProgram(0); + + // draw emitter placement marker if we are in placement mode + if(placing_emitter && !mouse_over_ui) { + glPushMatrix(); + glTranslatef(emit_place_pos.x, 0, emit_place_pos.y); + + glBegin(GL_LINES); + glColor3f(0, 1, 0); + glVertex3f(0, -1000, 0); + glVertex3f(0, 1000, 0); + glEnd(); + + float s = MASS_TO_RADIUS(slider_mass->get_value()); + if(s < 0.1) s = 0.1; + glScalef(s, s, s); + + glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); + pmesh->draw(); + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + + glPopMatrix(); + } + + // draw the UI + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(0, ui_virt_width, ui_virt_height, 0, -1, 1); + + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + + ui->draw(); + + + assert(glGetError() == GL_NO_ERROR); +} + +void GameScreen::reshape(int x, int y) +{ + ui_virt_width = x; + ui_virt_height = y; + ui->set_size(ui_virt_width, ui_virt_height); } + void GameScreen::keyboard(int key, bool pressed) { if(pressed) { @@ -27,20 +551,390 @@ void GameScreen::keyboard(int key, bool pressed) pop_screen(); break; + case ']': + if(tess_level < glcaps.max_tess_level) { + tess_level++; + printf("tessellation level: %d\n", tess_level); + set_uniform_int(field_sdr, "tess_level", tess_level); + glUseProgram(0); + } + break; + + case '[': + if(tess_level > 1) { + tess_level--; + printf("tessellation level: %d\n", tess_level); + set_uniform_int(field_sdr, "tess_level", tess_level); + glUseProgram(0); + } + break; + + case '=': + field_scale += 0.5; + printf("field scale: %f\n", field_scale); + set_uniform_float(field_sdr, "field_scale", field_scale); + break; + + case '-': + field_scale -= 0.5; + if(field_scale < 0.0f) { + field_scale = 0.0f; + } + printf("field scale: %f\n", field_scale); + set_uniform_float(field_sdr, "field_scale", field_scale); + break; + + case 'w': + wireframe = !wireframe; + break; + + case ' ': + pause = !pause; + break; + default: break; } } } +#define UI_HEIGHT 50 + void GameScreen::mbutton(int bn, bool pressed, int x, int y) { + mouse_x = x; + mouse_y = y; + + mouse_over_ui = y < UI_HEIGHT; + + ui->sysev_mouse_button(bn, pressed, x * ui_virt_width / win_width, + y * ui_virt_height / win_height); + + if(placing_emitter && bn == 0 && pressed && !mouse_over_ui) { + emit_place_pending = true; + placing_emitter = false; + slider_mass->hide(); + } } void GameScreen::mmotion(int x, int y) { + int dx = x - mouse_x; + int dy = y - mouse_y; + mouse_x = x; + mouse_y = y; + + mouse_over_ui = y < UI_HEIGHT; + + ui->sysev_mouse_motion(x * ui_virt_width / win_width, y * ui_virt_height / win_height); + if(ui->get_mouse_grab()) { + return; + } + + if(game_bnstate(0)) { + float pan_speed = pow(cam_dist, 1.5) * 0.00035; // magic + Vec2 dir = rotate(Vec2(dx, dy) * pan_speed, deg_to_rad(cam_theta)); + cam_pos.x -= dir.x; + cam_pos.y -= dir.y; + } + + if(game_bnstate(2)) { + cam_theta += dx * 0.5; + } } void GameScreen::mwheel(int dir, int x, int y) { + cam_dist -= dir * cam_dist * 0.05f; + if(cam_dist <= MIN_CAM_DIST) cam_dist = MIN_CAM_DIST; + if(cam_dist > MAX_CAM_DIST) cam_dist = MAX_CAM_DIST; +} + +static void ui_handler(goatkit::Widget *w, const goatkit::Event &ev, void *cls) +{ + if(w == bn_emitter) { + if(placing_emitter) { + placing_emitter = false; + slider_mass->hide(); + } else { + if(mass_left > 0.0f) { + placing_emitter = true; + slider_mass->set_range(0, mass_left); + slider_mass->set_value(mass_left >= EM_MASS_DEFAULT ? EM_MASS_DEFAULT : mass_left); + slider_mass->show(); + } + } + return; + } + + if(w == slider_mass) { + printf("foo: %f\n", slider_mass->get_value()); + } +} + +static int pos_to_grid_x_noclamp(float x) +{ + return ((x / (float)FIELD_SIZE) + 0.5f) * (float)GRID_SIZE; +} + +static int pos_to_grid_y_noclamp(float y) +{ + return ((y / (float)FIELD_SIZE) + 0.5f) * (float)GRID_SIZE; +} + +static int pos_to_grid(float x, float y) +{ + int gx = pos_to_grid_x_noclamp(x); + int gy = pos_to_grid_y_noclamp(y); + + if(gx < 0) gx = 0; + if(gx >= GRID_SIZE) gx = GRID_SIZE - 1; + if(gy < 0) gy = 0; + if(gy >= GRID_SIZE) gy = GRID_SIZE - 1; + + return (gx << GRID_BITS) | gy; +} + +static Vec2 grid_to_pos(int gx, int gy) +{ + float x = (((float)gx / (float)GRID_SIZE) - 0.5f) * (float)FIELD_SIZE; + float y = (((float)gy / (float)GRID_SIZE) - 0.5f) * (float)FIELD_SIZE; + + return Vec2(x, y); +} + +static void calc_contrib_bounds(const Vec2 &pos, float mass, Rect *rect) +{ + int gidx = pos_to_grid(pos.x, pos.y); + int gx = GRID_X(gidx); + int gy = GRID_Y(gidx); + int maxrange = (int)ceil(CONTRIB_RANGE(mass)); + + int sx = gx - maxrange; + int sy = gy - maxrange; + int ex = gx + maxrange; + int ey = gy + maxrange; + + if(ex > GRID_SIZE) ex = GRID_SIZE; + if(ey > GRID_SIZE) ey = GRID_SIZE; + + rect->x = sx < 0 ? 0 : sx; + rect->y = sy < 0 ? 0 : sy; + rect->width = ex - sx; + rect->height = ey - sy; +} + +static void add_influence(const Vec2 &pos, float mass, float radius, const Rect &cbox) +{ + float *gptr = grid + cbox.y * GRID_SIZE + cbox.x; + Vec2 startpos = grid_to_pos(cbox.x, cbox.y); + + for(int y=0; y= GRID_SIZE ? gx : gx + 1) << GRID_BITS) | gy; + int pidx = ((gx > 0 ? gx - 1 : gx) << GRID_BITS) | gy; + float dfdx = grid[nidx] - grid[pidx]; + + nidx = (gx << GRID_BITS) | (gy + 1 >= GRID_SIZE ? gy : gy + 1); + pidx = (gx << GRID_BITS) | (gy > 0 ? gy - 1 : gy); + float dfdy = grid[nidx] - grid[pidx]; + + return Vec2(dfdx, dfdy); +} + + +// ---- quad mesh operations ---- + +static void destroy_quadmesh(QuadMesh *m) +{ + glDeleteBuffers(1, &m->vbo_v); + glDeleteBuffers(1, &m->vbo_uv); + glDeleteBuffers(1, &m->ibo); + + delete [] m->v; + delete [] m->uv; + delete [] m->idx; +} + +static void draw_quadmesh(const QuadMesh *m, unsigned int prim) +{ + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + + glBindBuffer(GL_ARRAY_BUFFER, m->vbo_v); + glVertexPointer(3, GL_FLOAT, 0, 0); + + glBindBuffer(GL_ARRAY_BUFFER, m->vbo_uv); + glTexCoordPointer(2, GL_FLOAT, 0, 0); + + glBindBuffer(GL_ARRAY_BUFFER, 0); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m->ibo); + glDrawElements(prim, m->num_idx, GL_UNSIGNED_SHORT, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + + glDisableClientState(GL_VERTEX_ARRAY); + glDisableClientState(GL_TEXTURE_COORD_ARRAY); +} + +static void gen_quad_plane(QuadMesh *m, float width, float height, int usub, int vsub) +{ + Vec3 *vptr; + Vec2 *uvptr; + uint16_t *iptr; + + if(usub < 1) usub = 1; + if(vsub < 1) vsub = 1; + + int uverts = usub + 1; + int vverts = vsub + 1; + m->num_verts = uverts * vverts; + m->num_quads = usub * vsub; + m->num_idx = m->num_quads * 4; + + vptr = m->v = new Vec3[m->num_verts]; + uvptr = m->uv = new Vec2[m->num_verts]; + iptr = m->idx = new uint16_t[m->num_idx]; + + float du = 1.0f / (float)usub; + float dv = 1.0f / (float)vsub; + + float u = 0.0f; + for(int i=0; ivbo_v); + glBindBuffer(GL_ARRAY_BUFFER, m->vbo_v); + glBufferData(GL_ARRAY_BUFFER, m->num_verts * 3 * sizeof(float), m->v, GL_STATIC_DRAW); + + glGenBuffers(1, &m->vbo_uv); + glBindBuffer(GL_ARRAY_BUFFER, m->vbo_uv); + glBufferData(GL_ARRAY_BUFFER, m->num_verts * 2 * sizeof(float), m->uv, GL_STATIC_DRAW); + + glGenBuffers(1, &m->ibo); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m->ibo); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, m->num_idx * sizeof(uint16_t), m->idx, GL_STATIC_DRAW); + + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); +} + +static void spawn_particle(const Vec2 &pos, const Vec2 &vel, float mass) +{ + int gidx = pos_to_grid(pos.x, pos.y); + + if(grid_part[gidx]) { + // merge with existing + Particle *p = grid_part[gidx]; + p->vel += vel; + p->mass += mass; + p->radius = MASS_TO_RADIUS(p->mass); + + } else { + Particle *p = alloc_particle(); + p->pos = pos; + p->vel = vel; + p->mass = mass; + p->radius = MASS_TO_RADIUS(mass); + grid_part[gidx] = p; + + add_particle(p); + } +} + +static void add_particle(Particle *p) +{ + if(plist) plist->prev = p; + + p->next = plist; + p->prev = 0; + plist = p; +} + +static void remove_particle(Particle *p) +{ + assert(plist->prev == 0); + + if(plist == p) { + assert(p->prev == 0); + plist = p->next; + } + if(p->prev) { + p->prev->next = p->next; + } + if(p->next) { + p->next->prev = p->prev; + } + p->prev = p->next = 0; +} + +// particle allocator +#define MAX_PFREE_SIZE 256 +static Particle *pfree_list; +static int pfree_size; + +static Particle *alloc_particle() +{ + if(pfree_list) { + Particle *p = pfree_list; + pfree_list = pfree_list->next; + pfree_size--; + return p; + } + + return new Particle; +} + +void free_particle(Particle *p) +{ + if(pfree_size < MAX_PFREE_SIZE) { + p->next = pfree_list; + p->prev = 0; + pfree_list = p; + pfree_size++; + } else { + delete p; + } }