init: initial commit

This commit is contained in:
2024-11-21 22:22:14 +01:00
commit b5868dfdec
8 changed files with 467 additions and 0 deletions

84
src/main.cpp Normal file
View File

@@ -0,0 +1,84 @@
#include "screen.hpp"
#include "vec.hpp"
#include <cstdio>
#include <swarm.hpp>
#define FPS 60
#define DT (1.0 / FPS)
float f(vec<2> x) {
return (x.x - 49)*(x.x - 49) + (x.y - 13)*(x.y - 13);
}
int
main(int argc, char **argv) {
int iter_count;
if(argc < 2) iter_count = 100;
else sscanf(argv[1], "%d", &iter_count);
Swarm<2> swarm(f);
Screen scr(80, 24);
swarm.add_particle({0, 0}, {7, 3});
swarm.add_particle({4, 1}, {1, 5});
swarm.add_particle({16, 10}, {9, 10});
swarm.add_particle({7, 4}, {4, -3});
swarm.add_particle({14, 1}, {1, 5});
swarm.add_particle({1, 10}, {9, 10});
swarm.add_particle({5, 4}, {5, -3});
swarm.add_particle({4, 6}, {-1, 5});
swarm.add_particle({2, 6}, {9, 0});
swarm.add_particle({7, 7}, {4, -3});
enter_noncanonical_mode();
printf("\e[?1049h");
bool pause = false;
bool frame_step = false;
for(int i = 0; i < iter_count * FPS/4; ++i) {
if(!pause) {
scr.clear();
for(const auto &p : swarm.get_particles()) {
const auto & pos = p.get_position();
scr.at(pos.x, pos.y) = '#';
}
scr.draw();
swarm.move(DT * 4);
if(i % (FPS/4) == (FPS/4)-1)
swarm.step();
}
if(frame_step) {
pause = true;
frame_step = false;
}
struct {char buf[8]; int size;} inbuf = {{}, 0};
inbuf.size = read(STDIN_FILENO, inbuf.buf, 7);
switch (*inbuf.buf) {
case 'q':
goto cleanup;
case ' ':
pause = !pause;
break;
case '.':
pause = false;
frame_step = true;
break;
}
usleep(1000 * 1000 / FPS);
}
cleanup:
printf("\e[?1049l");
enter_canonical_mode();
auto [y, x] = swarm.best();
printf("Best: f(" V2_FMT ") = %.3f", V2_ARG(x), y);
return 0;
}

34
src/screen.cpp Normal file
View File

@@ -0,0 +1,34 @@
#include <cstdio>
#include <cstring>
#include <screen.hpp>
void Screen::resize(std::size_t n) {
w = n; h = 1;
buf = (char *)realloc(buf, n * sizeof(char));
}
void Screen::resize(std::size_t x, std::size_t y) {
w = x; h = y;
buf = (char *)realloc(buf, x * y * sizeof(char));
}
char &Screen::at(std::size_t n) { return buf[n]; }
char &Screen::at(std::size_t x, std::size_t y) {
auto idx = (int)(((y-dy)/sy) * w) + (int)((x-dx)/sx);
if(idx >= w *h) return _dummy;
return buf[idx];
}
void Screen::clear() {
memset(buf, ' ', w*h);
}
void Screen::draw() {
gotoxy(0, 0);
for(int i = 0; i < h; ++i) {
for(int j = 0; j < w; ++j) {
std::fputc(at(j, i), stdout);
}
std::fputc('\n', stdout);
}
}

1
src/swarm.cpp Normal file
View File

@@ -0,0 +1 @@
#include <swarm.hpp>