app.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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. #define GAME_START_LIVES 3
  17. #define TTLBUL 30 /* Bullet time to live, in ticks. */
  18. #define MAXBUL 5 /* Max bullets on the screen. */
  19. #define MAXAST 32 /* Max asteroids on the screen. */
  20. #define SHIP_HIT_ANIMATION_LEN 15
  21. #ifndef PI
  22. #define PI 3.14159265358979f
  23. #endif
  24. /* ============================ Data structures ============================= */
  25. typedef struct Ship {
  26. float x, /* Ship x position. */
  27. y, /* Ship y position. */
  28. vx, /* x velocity. */
  29. vy, /* y velocity. */
  30. rot; /* Current rotation. 2*PI full ortation. */
  31. } Ship;
  32. typedef struct Bullet {
  33. float x, y, vx, vy; /* Fields like in ship. */
  34. uint32_t ttl; /* Time to live, in ticks. */
  35. } Bullet;
  36. typedef struct Asteroid {
  37. float x, y, vx, vy, rot, /* Fields like ship. */
  38. rot_speed, /* Angular velocity (rot speed and sense). */
  39. size; /* Asteroid size. */
  40. uint8_t shape_seed; /* Seed to give random shape. */
  41. } Asteroid;
  42. typedef struct AsteroidsApp {
  43. /* GUI */
  44. Gui* gui;
  45. ViewPort* view_port; /* We just use a raw viewport and we render
  46. everything into the low level canvas. */
  47. FuriMessageQueue* event_queue; /* Keypress events go here. */
  48. /* Game state. */
  49. int running; /* Once false exists the app. */
  50. bool gameover; /* Gameover status. */
  51. uint32_t ticks; /* Game ticks. Increments at each refresh. */
  52. uint32_t score; /* Game score. */
  53. uint32_t lives; /* Number of lives in the current game. */
  54. uint32_t ship_hit; /* When non zero, the ship was hit by an asteroid
  55. and we need to show an animation as long as
  56. its value is non-zero (and decrease it's value
  57. at each tick of animation). */
  58. /* Ship state. */
  59. struct Ship ship;
  60. /* Bullets state. */
  61. struct Bullet bullets[MAXBUL]; /* Each bullet state. */
  62. int bullets_num; /* Active bullets. */
  63. uint32_t last_bullet_tick; /* Tick the last bullet was fired. */
  64. /* Asteroids state. */
  65. Asteroid asteroids[MAXAST]; /* Each asteroid state. */
  66. int asteroids_num; /* Active asteroids. */
  67. uint32_t pressed[InputKeyMAX]; /* pressed[id] is true if pressed.
  68. Each array item contains the time
  69. in milliseconds the key was pressed. */
  70. bool fire; /* Short press detected: fire a bullet. */
  71. } AsteroidsApp;
  72. /* ============================== Prototyeps ================================ */
  73. // Only functions called before their definition are here.
  74. void restart_game_after_gameover(AsteroidsApp* app);
  75. uint32_t key_pressed_time(AsteroidsApp* app, InputKey key);
  76. /* ============================ 2D drawing ================================== */
  77. /* This structure represents a polygon of at most POLY_MAX points.
  78. * The function draw_poly() is able to render it on the screen, rotated
  79. * by the amount specified. */
  80. #define POLY_MAX 8
  81. typedef struct Poly {
  82. float x[POLY_MAX];
  83. float y[POLY_MAX];
  84. uint32_t points; /* Number of points actually populated. */
  85. } Poly;
  86. /* Define the polygons we use. */
  87. Poly ShipPoly = {{-3, 0, 3}, {-3, 6, -3}, 3};
  88. /* Rotate the point of the poligon 'poly' and store the new rotated
  89. * polygon in 'rot'. The polygon is rotated by an angle 'a', with
  90. * center at 0,0. */
  91. void rotate_poly(Poly* rot, Poly* poly, float a) {
  92. /* We want to compute sin(a) and cos(a) only one time
  93. * for every point to rotate. It's a slow operation. */
  94. float sin_a = (float)sin(a);
  95. float cos_a = (float)cos(a);
  96. for(uint32_t j = 0; j < poly->points; j++) {
  97. rot->x[j] = poly->x[j] * cos_a - poly->y[j] * sin_a;
  98. rot->y[j] = poly->y[j] * cos_a + poly->x[j] * sin_a;
  99. }
  100. rot->points = poly->points;
  101. }
  102. /* This is an 8 bit LFSR we use to generate a predictable and fast
  103. * pseudorandom sequence of numbers, to give a different shape to
  104. * each asteroid. */
  105. void lfsr_next(unsigned char* prev) {
  106. unsigned char lsb = *prev & 1;
  107. *prev = *prev >> 1;
  108. if(lsb == 1) *prev ^= 0b11000111;
  109. *prev ^= *prev << 7; /* Mix things a bit more. */
  110. }
  111. /* Render the polygon 'poly' at x,y, rotated by the specified angle. */
  112. void draw_poly(Canvas* const canvas, Poly* poly, uint8_t x, uint8_t y, float a) {
  113. Poly rot;
  114. rotate_poly(&rot, poly, a);
  115. canvas_set_color(canvas, ColorBlack);
  116. for(uint32_t j = 0; j < rot.points; j++) {
  117. uint32_t a = j;
  118. uint32_t b = j + 1;
  119. if(b == rot.points) b = 0;
  120. canvas_draw_line(canvas, x + rot.x[a], y + rot.y[a], x + rot.x[b], y + rot.y[b]);
  121. }
  122. }
  123. /* A bullet is just a + pixels pattern. A single pixel is not
  124. * visible enough. */
  125. void draw_bullet(Canvas* const canvas, Bullet* b) {
  126. canvas_draw_dot(canvas, b->x - 1, b->y);
  127. canvas_draw_dot(canvas, b->x + 1, b->y);
  128. canvas_draw_dot(canvas, b->x, b->y);
  129. canvas_draw_dot(canvas, b->x, b->y - 1);
  130. canvas_draw_dot(canvas, b->x, b->y + 1);
  131. }
  132. /* Draw an asteroid. The asteroid shapes is computed on the fly and
  133. * is not stored in a permanent shape structure. In order to generate
  134. * the shape, we use an initial fixed shape that we resize according
  135. * to the asteroid size, perturbate according to the asteroid shape
  136. * seed, and finally draw it rotated of the right amount. */
  137. void draw_asteroid(Canvas* const canvas, Asteroid* ast) {
  138. Poly ap;
  139. /* Start with what is kinda of a circle. Note that this could be
  140. * stored into a template and copied here, to avoid computing
  141. * sin() / cos(). But the Flipper can handle it without problems. */
  142. uint8_t r = ast->shape_seed;
  143. for(int j = 0; j < 8; j++) {
  144. float a = (PI * 2) / 8 * j;
  145. /* Before generating the point, to make the shape unique generate
  146. * a random factor between .7 and 1.3 to scale the distance from
  147. * the center. However this asteroid should have its unique shape
  148. * that remains always the same, so we use a predictable PRNG
  149. * implemented by an 8 bit shift register. */
  150. lfsr_next(&r);
  151. float scaling = .7 + ((float)r / 255 * .6);
  152. ap.x[j] = (float)sin(a) * ast->size * scaling;
  153. ap.y[j] = (float)cos(a) * ast->size * scaling;
  154. }
  155. ap.points = 8;
  156. draw_poly(canvas, &ap, ast->x, ast->y, ast->rot);
  157. }
  158. /* Draw small ships in the top-right part of the screen, one for
  159. * each left live. */
  160. void draw_left_lives(Canvas* const canvas, AsteroidsApp* app) {
  161. int lives = app->lives;
  162. int x = SCREEN_XRES - 5;
  163. Poly mini_ship = {{-2, 0, 2}, {-2, 4, -2}, 3};
  164. while(lives--) {
  165. draw_poly(canvas, &mini_ship, x, 6, PI);
  166. x -= 6;
  167. }
  168. }
  169. /* Given the current position, update it according to the velocity and
  170. * wrap it back to the other side if the object went over the screen. */
  171. void update_pos_by_velocity(float* x, float* y, float vx, float vy) {
  172. /* Return back from one side to the other of the screen. */
  173. *x += vx;
  174. *y += vy;
  175. if(*x >= SCREEN_XRES)
  176. *x = 0;
  177. else if(*x < 0)
  178. *x = SCREEN_XRES - 1;
  179. if(*y >= SCREEN_YRES)
  180. *y = 0;
  181. else if(*y < 0)
  182. *y = SCREEN_YRES - 1;
  183. }
  184. /* Render the current game screen. */
  185. void render_callback(Canvas* const canvas, void* ctx) {
  186. AsteroidsApp* app = ctx;
  187. /* Clear screen. */
  188. canvas_set_color(canvas, ColorWhite);
  189. canvas_draw_box(canvas, 0, 0, SCREEN_XRES - 1, SCREEN_YRES - 1);
  190. /* Draw score. */
  191. canvas_set_color(canvas, ColorBlack);
  192. canvas_set_font(canvas, FontSecondary);
  193. char score[32];
  194. snprintf(score, sizeof(score), "%lu", app->score);
  195. canvas_draw_str(canvas, 0, 8, score);
  196. /* Draw left ships. */
  197. draw_left_lives(canvas, app);
  198. /* Draw ship, asteroids, bullets. */
  199. draw_poly(canvas, &ShipPoly, app->ship.x, app->ship.y, app->ship.rot);
  200. for(int j = 0; j < app->bullets_num; j++) draw_bullet(canvas, &app->bullets[j]);
  201. for(int j = 0; j < app->asteroids_num; j++) draw_asteroid(canvas, &app->asteroids[j]);
  202. /* Game over text. */
  203. if(app->gameover) {
  204. canvas_set_color(canvas, ColorBlack);
  205. canvas_set_font(canvas, FontPrimary);
  206. canvas_draw_str(canvas, 28, 35, "GAME OVER");
  207. canvas_set_font(canvas, FontSecondary);
  208. canvas_draw_str(canvas, 25, 50, "Press OK to restart");
  209. }
  210. }
  211. /* ============================ Game logic ================================== */
  212. float distance(float x1, float y1, float x2, float y2) {
  213. float dx = x1 - x2;
  214. float dy = y1 - y2;
  215. return sqrt(dx * dx + dy * dy);
  216. }
  217. /* Detect a collision between the object at x1,y1 of radius r1 and
  218. * the object at x2, y2 of radius r2. A factor < 1 will make the
  219. * function detect the collision even if the objects are yet not
  220. * relly touching, while a factor > 1 will make it detect the collision
  221. * only after they are a bit overlapping. It basically is used to
  222. * rescale the distance.
  223. *
  224. * Note that in this simplified 2D world, objects are all considered
  225. * spheres (this is why this function only takes the radius). This
  226. * is, after all, kinda accurate for asteroids, for bullets, and
  227. * even for the ship "core" itself. */
  228. bool objects_are_colliding(float x1, float y1, float r1, float x2, float y2, float r2, float factor) {
  229. /* The objects are colliding if the distance between object 1 and 2
  230. * is smaller than the sum of the two radiuses r1 and r2.
  231. * So it would be like: sqrt((x1-x2)^2+(y1-y2)^2) < r1+r2.
  232. * However we can avoid computing the sqrt (which is slow) by
  233. * squaring the second term and removing the square root, making
  234. * the comparison like this:
  235. *
  236. * (x1-x2)^2+(y1-y2)^2 < (r1+r2)^2. */
  237. float dx = (x1 - x2) * factor;
  238. float dy = (y1 - y2) * factor;
  239. float rsum = r1 + r2;
  240. return dx * dx + dy * dy < rsum * rsum;
  241. }
  242. /* Create a new bullet headed in the same direction of the ship. */
  243. void ship_fire_bullet(AsteroidsApp* app) {
  244. if(app->bullets_num == MAXBUL) return;
  245. Bullet* b = &app->bullets[app->bullets_num];
  246. b->x = app->ship.x;
  247. b->y = app->ship.y;
  248. b->vx = -sin(app->ship.rot);
  249. b->vy = cos(app->ship.rot);
  250. /* Ship should fire from its head, not in the middle. */
  251. b->x += b->vx * 5;
  252. b->y += b->vy * 5;
  253. /* Give the bullet some velocity (for now the vector is just
  254. * normalized to 1). */
  255. b->vx *= 3;
  256. b->vy *= 3;
  257. /* It's more realistic if we add the velocity vector of the
  258. * ship, too. Otherwise if the ship is going fast the bullets
  259. * will be slower, which is not how the world works. */
  260. b->vx += app->ship.vx;
  261. b->vy += app->ship.vy;
  262. b->ttl = TTLBUL; /* The bullet will disappear after N ticks. */
  263. app->bullets_num++;
  264. }
  265. /* Remove the specified bullet by id (index in the array). */
  266. void remove_bullet(AsteroidsApp* app, int bid) {
  267. /* Replace the top bullet with the empty space left
  268. * by the removal of this bullet. This way we always take the
  269. * array dense, which is an advantage when looping. */
  270. int n = --app->bullets_num;
  271. if(n && bid != n) app->bullets[bid] = app->bullets[n];
  272. }
  273. /* Create a new asteroid, away from the ship. Return the
  274. * pointer to the asteroid object, so that the caller can change
  275. * certain things of the asteroid if needed. */
  276. Asteroid* add_asteroid(AsteroidsApp* app) {
  277. if(app->asteroids_num == MAXAST) return NULL;
  278. float size = 4 + rand() % 15;
  279. float min_distance = 20;
  280. float x, y;
  281. do {
  282. x = rand() % SCREEN_XRES;
  283. y = rand() % SCREEN_YRES;
  284. } while(distance(app->ship.x, app->ship.y, x, y) < min_distance + size);
  285. Asteroid* a = &app->asteroids[app->asteroids_num++];
  286. a->x = x;
  287. a->y = y;
  288. a->vx = 2 * (-.5 + ((float)rand() / RAND_MAX));
  289. a->vy = 2 * (-.5 + ((float)rand() / RAND_MAX));
  290. a->size = size;
  291. a->rot = 0;
  292. a->rot_speed = ((float)rand() / RAND_MAX) / 10;
  293. if(app->ticks & 1) a->rot_speed = -(a->rot_speed);
  294. a->shape_seed = rand() & 255;
  295. return a;
  296. }
  297. /* Remove the specified asteroid by id (index in the array). */
  298. void remove_asteroid(AsteroidsApp* app, int id) {
  299. /* Replace the top asteroid with the empty space left
  300. * by the removal of this one. This way we always take the
  301. * array dense, which is an advantage when looping. */
  302. int n = --app->asteroids_num;
  303. if(n && id != n) app->asteroids[id] = app->asteroids[n];
  304. }
  305. /* Called when an asteroid was reached by a bullet. The asteroid
  306. * hit is the one with the specified 'id'. */
  307. void asteroid_was_hit(AsteroidsApp* app, int id) {
  308. float sizelimit = 6; // Smaller than that polverize in one shot.
  309. Asteroid* a = &app->asteroids[id];
  310. /* Asteroid is large enough to break into fragments. */
  311. float size = a->size;
  312. float x = a->x, y = a->y;
  313. remove_asteroid(app, id);
  314. if(size > sizelimit) {
  315. int max_fragments = size / sizelimit;
  316. int fragments = 2 + rand() % max_fragments;
  317. float newsize = size / fragments;
  318. if(newsize < 2) newsize = 2;
  319. for(int j = 0; j < fragments; j++) {
  320. a = add_asteroid(app);
  321. if(a == NULL) break; // Too many asteroids on screen.
  322. a->x = x + -(size / 2) + rand() % (int)newsize;
  323. a->y = y + -(size / 2) + rand() % (int)newsize;
  324. a->size = newsize;
  325. }
  326. } else {
  327. app->score++;
  328. }
  329. }
  330. /* Set gameover state. When in game-over mode, the game displays a gameover
  331. * text with a background of many asteroids floating around. */
  332. void game_over(AsteroidsApp* app) {
  333. restart_game_after_gameover(app);
  334. app->gameover = true;
  335. int asteroids = 8;
  336. while(asteroids-- && add_asteroid(app) != NULL)
  337. ;
  338. }
  339. /* Function called when a collision between the asteroid and the
  340. * ship is detected. */
  341. void ship_was_hit(AsteroidsApp* app) {
  342. app->ship_hit = SHIP_HIT_ANIMATION_LEN;
  343. if(app->lives) {
  344. app->lives--;
  345. } else {
  346. game_over(app);
  347. }
  348. }
  349. /* Restart game after the ship is hit. Will reset the ship position, bullets
  350. * and asteroids to restart the game. */
  351. void restart_game(AsteroidsApp* app) {
  352. app->ship.x = SCREEN_XRES / 2;
  353. app->ship.y = SCREEN_YRES / 2;
  354. app->ship.rot = PI; /* Start headed towards top. */
  355. app->ship.vx = 0;
  356. app->ship.vy = 0;
  357. app->bullets_num = 0;
  358. app->last_bullet_tick = 0;
  359. app->asteroids_num = 0;
  360. }
  361. /* Called after gameover to restart the game. This function
  362. * also calls restart_game(). */
  363. void restart_game_after_gameover(AsteroidsApp* app) {
  364. app->gameover = false;
  365. app->ticks = 0;
  366. app->score = 0;
  367. app->ship_hit = 0;
  368. app->lives = GAME_START_LIVES;
  369. restart_game(app);
  370. }
  371. /* Move bullets. */
  372. void update_bullets_position(AsteroidsApp* app) {
  373. for(int j = 0; j < app->bullets_num; j++) {
  374. update_pos_by_velocity(
  375. &app->bullets[j].x, &app->bullets[j].y, app->bullets[j].vx, app->bullets[j].vy);
  376. if(--app->bullets[j].ttl == 0) {
  377. remove_bullet(app, j);
  378. j--; /* Process this bullet index again: the removal will
  379. fill it with the top bullet to take the array dense. */
  380. }
  381. }
  382. }
  383. /* Move asteroids. */
  384. void update_asteroids_position(AsteroidsApp* app) {
  385. for(int j = 0; j < app->asteroids_num; j++) {
  386. update_pos_by_velocity(
  387. &app->asteroids[j].x, &app->asteroids[j].y, app->asteroids[j].vx, app->asteroids[j].vy);
  388. app->asteroids[j].rot += app->asteroids[j].rot_speed;
  389. if(app->asteroids[j].rot < 0)
  390. app->asteroids[j].rot = 2 * PI;
  391. else if(app->asteroids[j].rot > 2 * PI)
  392. app->asteroids[j].rot = 0;
  393. }
  394. }
  395. /* Collision detection and game state update based on collisions. */
  396. void detect_collisions(AsteroidsApp* app) {
  397. /* Detect collision between bullet and asteroid. */
  398. for(int j = 0; j < app->bullets_num; j++) {
  399. Bullet* b = &app->bullets[j];
  400. for(int i = 0; i < app->asteroids_num; i++) {
  401. Asteroid* a = &app->asteroids[i];
  402. if(objects_are_colliding(a->x, a->y, a->size, b->x, b->y, 1.5, 1)) {
  403. asteroid_was_hit(app, i);
  404. remove_bullet(app, j);
  405. /* The bullet no longer exist. Break the loop.
  406. * However we want to start processing from the
  407. * same bullet index, since now it is used by
  408. * another bullet (see remove_bullet()). */
  409. j--; /* Scan this j value again. */
  410. break;
  411. }
  412. }
  413. }
  414. /* Detect collision between ship and asteroid. */
  415. for(int j = 0; j < app->asteroids_num; j++) {
  416. Asteroid* a = &app->asteroids[j];
  417. if(objects_are_colliding(a->x, a->y, a->size, app->ship.x, app->ship.y, 4, 1)) {
  418. ship_was_hit(app);
  419. break;
  420. }
  421. }
  422. }
  423. /* This is the main game execution function, called 10 times for
  424. * second (with the Flipper screen latency, an higher FPS does not
  425. * make sense). In this function we update the position of objects based
  426. * on velocity. Detect collisions. Update the score and so forth.
  427. *
  428. * Each time this function is called, app->tick is incremented. */
  429. void game_tick(void* ctx) {
  430. AsteroidsApp* app = ctx;
  431. /* There are two special screens:
  432. *
  433. * 1. Ship was hit, we frozen the game as long as ship_hit isn't zero
  434. * again, and show an animation of a rotating ship. */
  435. if(app->ship_hit) {
  436. app->ship.rot += 0.5;
  437. app->ship_hit--;
  438. view_port_update(app->view_port);
  439. if(app->ship_hit == 0) {
  440. restart_game(app);
  441. }
  442. return;
  443. } else if(app->gameover) {
  444. /* 2. Game over. We need to update only background asteroids. In this
  445. * state the game just displays a GAME OVER text with the floating
  446. * asteroids in backgroud. */
  447. if(key_pressed_time(app, InputKeyOk) > 100) {
  448. restart_game_after_gameover(app);
  449. }
  450. update_asteroids_position(app);
  451. view_port_update(app->view_port);
  452. return;
  453. }
  454. /* Handle keypresses. */
  455. if(app->pressed[InputKeyLeft]) app->ship.rot -= .35;
  456. if(app->pressed[InputKeyRight]) app->ship.rot += .35;
  457. if(app->pressed[InputKeyUp]) {
  458. app->ship.vx -= 0.5 * (float)sin(app->ship.rot);
  459. app->ship.vy += 0.5 * (float)cos(app->ship.rot);
  460. } else if(app->pressed[InputKeyDown]) {
  461. app->ship.vx *= 0.75;
  462. app->ship.vy *= 0.75;
  463. }
  464. /* Fire a bullet if needed. app->fire is set in
  465. * asteroids_update_keypress_state() since depends on exact
  466. * pressure timing. */
  467. if(app->fire) {
  468. uint32_t bullet_min_period = 200; // In milliseconds
  469. uint32_t now = furi_get_tick();
  470. if(now - app->last_bullet_tick >= bullet_min_period) {
  471. ship_fire_bullet(app);
  472. app->last_bullet_tick = now;
  473. }
  474. app->fire = false;
  475. }
  476. /* Update positions and detect collisions. */
  477. update_pos_by_velocity(&app->ship.x, &app->ship.y, app->ship.vx, app->ship.vy);
  478. update_bullets_position(app);
  479. update_asteroids_position(app);
  480. detect_collisions(app);
  481. /* From time to time, create a new asteroid. The more asteroids
  482. * already on the screen, the smaller probability of creating
  483. * a new one. */
  484. if(app->asteroids_num == 0 || (random() % 5000) < (30 / (1 + app->asteroids_num))) {
  485. add_asteroid(app);
  486. }
  487. app->ticks++;
  488. view_port_update(app->view_port);
  489. }
  490. /* ======================== Flipper specific code =========================== */
  491. /* Here all we do is putting the events into the queue that will be handled
  492. * in the while() loop of the app entry point function. */
  493. void input_callback(InputEvent* input_event, void* ctx) {
  494. AsteroidsApp* app = ctx;
  495. furi_message_queue_put(app->event_queue, input_event, FuriWaitForever);
  496. }
  497. /* Allocate the application state and initialize a number of stuff.
  498. * This is called in the entry point to create the application state. */
  499. AsteroidsApp* asteroids_app_alloc() {
  500. AsteroidsApp* app = malloc(sizeof(AsteroidsApp));
  501. app->gui = furi_record_open(RECORD_GUI);
  502. app->view_port = view_port_alloc();
  503. view_port_draw_callback_set(app->view_port, render_callback, app);
  504. view_port_input_callback_set(app->view_port, input_callback, app);
  505. gui_add_view_port(app->gui, app->view_port, GuiLayerFullscreen);
  506. app->event_queue = furi_message_queue_alloc(8, sizeof(InputEvent));
  507. app->running = 1; /* Turns 0 when back is pressed. */
  508. restart_game_after_gameover(app);
  509. memset(app->pressed, 0, sizeof(app->pressed));
  510. return app;
  511. }
  512. /* Free what the application allocated. It is not clear to me if the
  513. * Flipper OS, once the application exits, will be able to reclaim space
  514. * even if we forget to free something here. */
  515. void asteroids_app_free(AsteroidsApp* app) {
  516. furi_assert(app);
  517. // View related.
  518. view_port_enabled_set(app->view_port, false);
  519. gui_remove_view_port(app->gui, app->view_port);
  520. view_port_free(app->view_port);
  521. furi_record_close(RECORD_GUI);
  522. furi_message_queue_free(app->event_queue);
  523. app->gui = NULL;
  524. free(app);
  525. }
  526. /* Return the time in milliseconds the specified key is continuously
  527. * pressed. Or 0 if it is not pressed. */
  528. uint32_t key_pressed_time(AsteroidsApp* app, InputKey key) {
  529. return app->pressed[key] == 0 ? 0 : furi_get_tick() - app->pressed[key];
  530. }
  531. /* Handle keys interaction. */
  532. void asteroids_update_keypress_state(AsteroidsApp* app, InputEvent input) {
  533. // Allow Rapid fire
  534. if(input.key == InputKeyOk) {
  535. app->fire = true;
  536. }
  537. if(input.type == InputTypePress) {
  538. app->pressed[input.key] = furi_get_tick();
  539. } else if(input.type == InputTypeRelease) {
  540. app->pressed[input.key] = 0;
  541. }
  542. }
  543. int32_t asteroids_app_entry(void* p) {
  544. UNUSED(p);
  545. AsteroidsApp* app = asteroids_app_alloc();
  546. /* Create a timer. We do data analysis in the callback. */
  547. FuriTimer* timer = furi_timer_alloc(game_tick, FuriTimerTypePeriodic, app);
  548. furi_timer_start(timer, furi_kernel_get_tick_frequency() / 10);
  549. /* This is the main event loop: here we get the events that are pushed
  550. * in the queue by input_callback(), and process them one after the
  551. * other. */
  552. InputEvent input;
  553. while(app->running) {
  554. FuriStatus qstat = furi_message_queue_get(app->event_queue, &input, 100);
  555. if(qstat == FuriStatusOk) {
  556. if(DEBUG_MSG)
  557. FURI_LOG_E(TAG, "Main Loop - Input: type %d key %u", input.type, input.key);
  558. /* Handle navigation here. Then handle view-specific inputs
  559. * in the view specific handling function. */
  560. if(input.type == InputTypeShort && input.key == InputKeyBack) {
  561. app->running = 0;
  562. } else {
  563. asteroids_update_keypress_state(app, input);
  564. }
  565. } else {
  566. /* Useful to understand if the app is still alive when it
  567. * does not respond because of bugs. */
  568. if(DEBUG_MSG) {
  569. static int c = 0;
  570. c++;
  571. if(!(c % 20)) FURI_LOG_E(TAG, "Loop timeout");
  572. }
  573. }
  574. }
  575. furi_timer_free(timer);
  576. asteroids_app_free(app);
  577. return 0;
  578. }