app.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. /* Copyright (C) 2023 Salvatore Sanfilippo -- All Rights Reserved
  2. * See the LICENSE file for information about the license. */
  3. #include <furi.h>
  4. #include <furi_hal.h>
  5. #include <input/input.h>
  6. #include <gui/gui.h>
  7. #include <stdlib.h>
  8. #include <gui/gui.h>
  9. #include <gui/view_dispatcher.h>
  10. #include <gui/scene_manager.h>
  11. #include <math.h>
  12. #define TAG "Asteroids" // Used for logging
  13. #define DEBUG_MSG 1
  14. #define SCREEN_XRES 128
  15. #define SCREEN_YRES 64
  16. #ifndef PI
  17. #define PI 3.14159265358979f
  18. #endif
  19. /* ============================ Data structures ============================= */
  20. typedef struct Ship {
  21. float x, /* Ship x position. */
  22. y, /* Ship y position. */
  23. vx, /* x velocity. */
  24. vy, /* y velocity. */
  25. rot; /* Current rotation. 2*PI full ortation. */
  26. } Ship;
  27. typedef struct Bullet {
  28. float x, y, vx, vy; /* Fields like in ship. */
  29. uint32_t ttl; /* Time to live, in ticks. */
  30. } Bullet;
  31. typedef struct Asteroid {
  32. float x, y, vx, vy, rot, /* Fields like ship. */
  33. rot_speed, /* Angular velocity (rot speed and sense). */
  34. size; /* Asteroid size. */
  35. uint8_t shape_seed; /* Seed to give random shape. */
  36. } Asteroid;
  37. #define MAXBUL 10 /* Max bullets on the screen. */
  38. #define MAXAST 8 /* Max asteroids on the screen. */
  39. typedef struct AsteroidsApp {
  40. /* GUI */
  41. Gui *gui;
  42. ViewPort *view_port; /* We just use a raw viewport and we render
  43. everything into the low level canvas. */
  44. FuriMessageQueue *event_queue; /* Keypress events go here. */
  45. /* Game state. */
  46. int running; /* Once false exists the app. */
  47. uint32_t ticks; /* Game ticks. Increments at each refresh. */
  48. /* Ship state. */
  49. struct Ship ship;
  50. /* Bullets state. */
  51. struct Bullet bullets[MAXBUL]; /* Each bullet state. */
  52. int bullets_num; /* Active bullets. */
  53. uint32_t last_bullet_tick; /* Tick the last bullet was fired. */
  54. /* Asteroids state. */
  55. Asteroid asteroids[MAXAST]; /* Each asteroid state. */
  56. int asteroids_num; /* Active asteroids. */
  57. uint32_t pressed[InputKeyMAX]; /* pressed[id] is true if pressed.
  58. Each array item contains the time
  59. in milliseconds the key was pressed. */
  60. bool fire; /* Short press detected: fire a bullet. */
  61. } AsteroidsApp;
  62. /* ============================ 2D drawing ================================== */
  63. /* This structure represents a polygon of at most POLY_MAX points.
  64. * The function draw_poly() is able to render it on the screen, rotated
  65. * by the amount specified. */
  66. #define POLY_MAX 8
  67. typedef struct Poly {
  68. float x[POLY_MAX];
  69. float y[POLY_MAX];
  70. uint32_t points; /* Number of points actually populated. */
  71. } Poly;
  72. /* Define the polygons we use. */
  73. Poly ShipPoly = {
  74. {-3, 0, 3},
  75. {-3, 6, -3},
  76. 3
  77. };
  78. /* Rotate the point of the poligon 'poly' and store the new rotated
  79. * polygon in 'rot'. The polygon is rotated by an angle 'a', with
  80. * center at 0,0. */
  81. void rotate_poly(Poly *rot, Poly *poly, float a) {
  82. /* We want to compute sin(a) and cos(a) only one time
  83. * for every point to rotate. It's a slow operation. */
  84. float sin_a = (float)sin(a);
  85. float cos_a = (float)cos(a);
  86. for (uint32_t j = 0; j < poly->points; j++) {
  87. rot->x[j] = poly->x[j]*cos_a - poly->y[j]*sin_a;
  88. rot->y[j] = poly->y[j]*cos_a + poly->x[j]*sin_a;
  89. }
  90. rot->points = poly->points;
  91. }
  92. /* This is an 8 bit LFSR we use to generate a predictable and fast
  93. * pseudorandom sequence of numbers, to give a different shape to
  94. * each asteroid. */
  95. void lfsr_next(unsigned char *prev) {
  96. unsigned char lsb = *prev & 1;
  97. *prev = *prev >> 1;
  98. if (lsb == 1) *prev ^= 0b11000111;
  99. *prev ^= *prev<<7; /* Mix things a bit more. */
  100. }
  101. /* Render the polygon 'poly' at x,y, rotated by the specified angle. */
  102. void draw_poly(Canvas *const canvas, Poly *poly, uint8_t x, uint8_t y, float a)
  103. {
  104. Poly rot;
  105. rotate_poly(&rot,poly,a);
  106. canvas_set_color(canvas, ColorBlack);
  107. for (uint32_t j = 0; j < rot.points; j++) {
  108. uint32_t a = j;
  109. uint32_t b = j+1;
  110. if (b == rot.points) b = 0;
  111. canvas_draw_line(canvas,x+rot.x[a],y+rot.y[a],
  112. x+rot.x[b],y+rot.y[b]);
  113. }
  114. }
  115. /* A bullet is just a + pixels pattern. A single pixel is not
  116. * visible enough. */
  117. void draw_bullet(Canvas *const canvas, Bullet *b) {
  118. canvas_draw_dot(canvas,b->x-1,b->y);
  119. canvas_draw_dot(canvas,b->x+1,b->y);
  120. canvas_draw_dot(canvas,b->x,b->y);
  121. canvas_draw_dot(canvas,b->x,b->y-1);
  122. canvas_draw_dot(canvas,b->x,b->y+1);
  123. }
  124. /* Draw an asteroid. The asteroid shapes is computed on the fly and
  125. * is not stored in a permanent shape structure. In order to generate
  126. * the shape, we use an initial fixed shape that we resize according
  127. * to the asteroid size, perturbate according to the asteroid shape
  128. * seed, and finally draw it rotated of the right amount. */
  129. void draw_asteroid(Canvas *const canvas, Asteroid *ast) {
  130. Poly ap;
  131. /* Start with what is kinda of a circle. Note that this could be
  132. * stored into a template and copied here, to avoid computing
  133. * sin() / cos(). But the Flipper can handle it without problems. */
  134. uint8_t r = ast->shape_seed;
  135. for (int j = 0; j < 8; j++) {
  136. float a = (PI*2)/8*j;
  137. /* Before generating the point, to make the shape unique generate
  138. * a random factor between .7 and 1.3 to scale the distance from
  139. * the center. However this asteroid should have its unique shape
  140. * that remains always the same, so we use a predictable PRNG
  141. * implemented by an 8 bit shift register. */
  142. lfsr_next(&r);
  143. float scaling = .7+((float)r/255*.6);
  144. ap.x[j] = (float)sin(a) * ast->size * scaling;
  145. ap.y[j] = (float)cos(a) * ast->size * scaling;
  146. }
  147. ap.points = 8;
  148. draw_poly(canvas,&ap,ast->x,ast->y,ast->rot);
  149. }
  150. /* Given the current position, update it according to the velocity and
  151. * wrap it back to the other side if the object went over the screen. */
  152. void update_pos_by_velocity(float *x, float *y, float vx, float vy) {
  153. /* Return back from one side to the other of the screen. */
  154. *x += vx;
  155. *y += vy;
  156. if (*x >= SCREEN_XRES) *x = 0;
  157. else if (*x < 0) *x = SCREEN_XRES-1;
  158. if (*y >= SCREEN_YRES) *y = 0;
  159. else if (*y < 0) *y = SCREEN_YRES-1;
  160. }
  161. /* Render the current game screen. */
  162. void render_callback(Canvas *const canvas, void *ctx) {
  163. AsteroidsApp *app = ctx;
  164. /* Clear screen. */
  165. canvas_set_color(canvas, ColorWhite);
  166. canvas_draw_box(canvas, 0, 0, 127, 63);
  167. /* Draw ship, asteroids, bullets. */
  168. draw_poly(canvas,&ShipPoly,app->ship.x,app->ship.y,app->ship.rot);
  169. for (int j = 0; j < app->bullets_num; j++)
  170. draw_bullet(canvas,&app->bullets[j]);
  171. for (int j = 0; j < app->asteroids_num; j++)
  172. draw_asteroid(canvas,&app->asteroids[j]);
  173. }
  174. /* ============================ Game logic ================================== */
  175. float distance(float x1, float y1, float x2, float y2) {
  176. float dx = x1-x2;
  177. float dy = y1-y2;
  178. return sqrt(dx*dx+dy*dy);
  179. }
  180. /* Detect a collision between the object at x1,y1 of radius r1 and
  181. * the object at x2, y2 of radius r2. A factor < 1 will make the
  182. * function detect the collision even if the objects are yet not
  183. * relly touching, while a factor > 1 will make it detect the collision
  184. * only after they are a bit overlapping. It basically is used to
  185. * rescale the distance.
  186. *
  187. * Note that in this simplified 2D world, objects are all considered
  188. * spheres (this is why this function only takes the radius). This
  189. * is, after all, kinda accurate for asteroids, for bullets, and
  190. * even for the ship "core" itself. */
  191. bool detect_collision(float x1, float y1, float r1,
  192. float x2, float y2, float r2,
  193. float factor)
  194. {
  195. /* The objects are colliding if the distance between object 1 and 2
  196. * is smaller than the sum of the two radiuses r1 and r2.
  197. * So it would be like: sqrt((x1-x2)^2+(y1-y2)^2) < r1+r2.
  198. * However we can avoid computing the sqrt (which is slow) by
  199. * squaring the second term and removing the square root, making
  200. * the comparison like this:
  201. *
  202. * (x1-x2)^2+(y1-y2)^2 < (r1+r2)^2. */
  203. float dx = (x1-x2)*factor;
  204. float dy = (y1-y2)*factor;
  205. float rsum = r1+r2;
  206. return dx*dx+dy*dy < rsum*rsum;
  207. }
  208. /* Create a new bullet headed in the same direction of the ship. */
  209. void ship_fire_bullet(AsteroidsApp *app) {
  210. if (app->bullets_num == MAXBUL) return;
  211. Bullet *b = &app->bullets[app->bullets_num];
  212. b->x = app->ship.x;
  213. b->y = app->ship.y;
  214. b->vx = -sin(app->ship.rot);
  215. b->vy = cos(app->ship.rot);
  216. /* Ship should fire from its head, not in the middle. */
  217. b->x += b->vx*5;
  218. b->y += b->vy*5;
  219. /* Give the bullet some velocity (for now the vector is just
  220. * normalized to 1). */
  221. b->vx *= 2;
  222. b->vy *= 2;
  223. /* It's more realistic if we add the velocity vector of the
  224. * ship, too. Otherwise if the ship is going fast the bullets
  225. * will be slower, which is not how the world works. */
  226. b->vx += app->ship.vx;
  227. b->vy += app->ship.vy;
  228. b->ttl = 50; /* The bullet will disappear after N ticks. */
  229. app->bullets_num++;
  230. }
  231. /* Remove the specified bullet by id (index in the array). */
  232. void remove_bullet(AsteroidsApp *app, int bid) {
  233. /* Replace the top bullet with the empty space left
  234. * by the removal of this bullet. This way we always take the
  235. * array dense, which is an advantage when looping. */
  236. int n = --app->bullets_num;
  237. if (n && bid != n) app->bullets[bid] = app->bullets[n];
  238. }
  239. /* Create a new asteroid, away from the ship. */
  240. void add_asteroid(AsteroidsApp *app) {
  241. if (app->asteroids_num == MAXAST) return;
  242. float size = 4+rand()%15;
  243. float min_distance = 20;
  244. float x,y;
  245. do {
  246. x = rand() % SCREEN_XRES;
  247. y = rand() % SCREEN_YRES;
  248. } while(distance(app->ship.x,app->ship.y,x,y) < min_distance+size);
  249. Asteroid *a = &app->asteroids[app->asteroids_num++];
  250. a->x = x;
  251. a->y = y;
  252. a->vx = ((float)rand()/RAND_MAX);
  253. a->vy = ((float)rand()/RAND_MAX);
  254. a->size = size;
  255. a->rot = 0;
  256. a->rot_speed = ((float)rand()/RAND_MAX)/10;
  257. if (app->ticks & 1) a->rot_speed = -(a->rot_speed);
  258. a->shape_seed = rand() & 255;
  259. }
  260. /* Remove the specified asteroid by id (index in the array). */
  261. void remove_asteroid(AsteroidsApp *app, int id) {
  262. /* Replace the top asteroid with the empty space left
  263. * by the removal of this one. This way we always take the
  264. * array dense, which is an advantage when looping. */
  265. int n = --app->asteroids_num;
  266. if (n && id != n) app->asteroids[id] = app->asteroids[n];
  267. }
  268. /* This is the main game execution function, called 10 times for
  269. * second (with the Flipper screen latency, an higher FPS does not
  270. * make sense). In this function we update the position of objects based
  271. * on velocity. Detect collisions. Update the score and so forth.
  272. *
  273. * Each time this function is called, app->tick is incremented. */
  274. void game_tick(void *ctx) {
  275. AsteroidsApp *app = ctx;
  276. /* Handle keypresses. */
  277. if (app->pressed[InputKeyLeft]) app->ship.rot -= .35;
  278. if (app->pressed[InputKeyRight]) app->ship.rot += .35;
  279. if (app->pressed[InputKeyOk]) {
  280. app->ship.vx -= 0.35*(float)sin(app->ship.rot);
  281. app->ship.vy += 0.35*(float)cos(app->ship.rot);
  282. }
  283. /* Fire a bullet if needed. app->fire is set in
  284. * asteroids_update_keypress_state() since depends on exact
  285. * pressure timing. */
  286. if (app->fire) {
  287. ship_fire_bullet(app);
  288. app->fire = false;
  289. }
  290. /* Update ship position according to its velocity. */
  291. update_pos_by_velocity(&app->ship.x,&app->ship.y,app->ship.vx,app->ship.vy);
  292. /* Update bullets position. */
  293. for (int j = 0; j < app->bullets_num; j++) {
  294. update_pos_by_velocity(&app->bullets[j].x,&app->bullets[j].y,
  295. app->bullets[j].vx,app->bullets[j].vy);
  296. if (--app->bullets[j].ttl == 0) {
  297. remove_bullet(app,j);
  298. j--; /* Process this bullet index again: the removal will
  299. fill it with the top bullet to take the array dense. */
  300. }
  301. }
  302. /* Update asteroids position. */
  303. for (int j = 0; j < app->asteroids_num; j++) {
  304. update_pos_by_velocity(&app->asteroids[j].x,&app->asteroids[j].y,
  305. app->asteroids[j].vx,app->asteroids[j].vy);
  306. app->asteroids[j].rot += app->asteroids[j].rot_speed;
  307. if (app->asteroids[j].rot < 0) app->asteroids[j].rot = 2*PI;
  308. else if (app->asteroids[j].rot > 2*PI) app->asteroids[j].rot = 0;
  309. }
  310. /* Detect collision between bullet and asteroid. */
  311. for (int j = 0; j < app->bullets_num; j++) {
  312. Bullet *b = &app->bullets[j];
  313. for (int i = 0; i < app->asteroids_num; i++) {
  314. Asteroid *a = &app->asteroids[i];
  315. if (detect_collision(a->x, a->y, a->size,
  316. b->x, b->y, 1, 1))
  317. {
  318. remove_asteroid(app,i);
  319. remove_bullet(app,j);
  320. /* The bullet no longer exist. Break the loop.
  321. * However we want to start processing from the
  322. * same bullet index, since now it is used by
  323. * another bullet (see remove_bullet()). */
  324. j--; /* Scan this j value again. */
  325. break;
  326. }
  327. }
  328. }
  329. /* From time to time, create a new asteroid. The more asteroids
  330. * already on the screen, the smaller probability of creating
  331. * a new one. */
  332. if (app->asteroids_num == 0 ||
  333. (random() % 5000) < (30/(1+app->asteroids_num)))
  334. {
  335. add_asteroid(app);
  336. }
  337. app->ticks++;
  338. view_port_update(app->view_port);
  339. }
  340. /* ======================== Flipper specific code =========================== */
  341. /* Here all we do is putting the events into the queue that will be handled
  342. * in the while() loop of the app entry point function. */
  343. void input_callback(InputEvent* input_event, void* ctx)
  344. {
  345. AsteroidsApp *app = ctx;
  346. furi_message_queue_put(app->event_queue,input_event,FuriWaitForever);
  347. }
  348. /* Allocate the application state and initialize a number of stuff.
  349. * This is called in the entry point to create the application state. */
  350. AsteroidsApp* asteroids_app_alloc() {
  351. AsteroidsApp *app = malloc(sizeof(AsteroidsApp));
  352. app->gui = furi_record_open(RECORD_GUI);
  353. app->view_port = view_port_alloc();
  354. view_port_draw_callback_set(app->view_port, render_callback, app);
  355. view_port_input_callback_set(app->view_port, input_callback, app);
  356. gui_add_view_port(app->gui, app->view_port, GuiLayerFullscreen);
  357. app->event_queue = furi_message_queue_alloc(8, sizeof(InputEvent));
  358. app->running = 1;
  359. app->ticks = 0;
  360. app->ship.x = SCREEN_XRES / 2;
  361. app->ship.y = SCREEN_YRES / 2;
  362. app->ship.rot = PI; /* Start headed towards top. */
  363. app->ship.vx = 0;
  364. app->ship.vy = 0;
  365. app->bullets_num = 0;
  366. app->last_bullet_tick = 0;
  367. app->asteroids_num = 0;
  368. memset(app->pressed,0,sizeof(app->pressed));
  369. return app;
  370. }
  371. /* Free what the application allocated. It is not clear to me if the
  372. * Flipper OS, once the application exits, will be able to reclaim space
  373. * even if we forget to free something here. */
  374. void asteroids_app_free(AsteroidsApp *app) {
  375. furi_assert(app);
  376. // View related.
  377. view_port_enabled_set(app->view_port, false);
  378. gui_remove_view_port(app->gui, app->view_port);
  379. view_port_free(app->view_port);
  380. furi_record_close(RECORD_GUI);
  381. furi_message_queue_free(app->event_queue);
  382. app->gui = NULL;
  383. free(app);
  384. }
  385. /* Handle keys interaction. */
  386. void asteroids_update_keypress_state(AsteroidsApp *app, InputEvent input) {
  387. if (input.type == InputTypePress) {
  388. app->pressed[input.key] = furi_get_tick();
  389. } else if (input.type == InputTypeRelease) {
  390. uint32_t dur = furi_get_tick() - app->pressed[input.key];
  391. app->pressed[input.key] = 0;
  392. if (dur < 200 && input.key == InputKeyOk) app->fire = true;
  393. }
  394. }
  395. int32_t asteroids_app_entry(void* p) {
  396. UNUSED(p);
  397. AsteroidsApp *app = asteroids_app_alloc();
  398. /* Create a timer. We do data analysis in the callback. */
  399. FuriTimer *timer = furi_timer_alloc(game_tick, FuriTimerTypePeriodic, app);
  400. furi_timer_start(timer, furi_kernel_get_tick_frequency() / 10);
  401. /* This is the main event loop: here we get the events that are pushed
  402. * in the queue by input_callback(), and process them one after the
  403. * other. The timeout is 100 milliseconds, so if not input is received
  404. * before such time, we exit the queue_get() function and call
  405. * view_port_update() in order to refresh our screen content. */
  406. InputEvent input;
  407. while(app->running) {
  408. FuriStatus qstat = furi_message_queue_get(app->event_queue, &input, 100);
  409. if (qstat == FuriStatusOk) {
  410. if (DEBUG_MSG) FURI_LOG_E(TAG, "Main Loop - Input: type %d key %u",
  411. input.type, input.key);
  412. /* Handle navigation here. Then handle view-specific inputs
  413. * in the view specific handling function. */
  414. if (input.type == InputTypeShort &&
  415. input.key == InputKeyBack)
  416. {
  417. app->running = 0;
  418. } else {
  419. asteroids_update_keypress_state(app,input);
  420. }
  421. } else {
  422. /* Useful to understand if the app is still alive when it
  423. * does not respond because of bugs. */
  424. if (DEBUG_MSG) {
  425. static int c = 0; c++;
  426. if (!(c % 20)) FURI_LOG_E(TAG, "Loop timeout");
  427. }
  428. }
  429. }
  430. furi_timer_free(timer);
  431. asteroids_app_free(app);
  432. return 0;
  433. }