]> git.lizzy.rs Git - dungeon_game.git/blob - plugins/game/game.c
adcb59abf5e56746983fa0d3fcc42a3ddd95af01
[dungeon_game.git] / plugins / game / game.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <assert.h>
5 #include <ctype.h>
6 #include <signal.h>
7 #include <termios.h>
8 #include <math.h>
9 #include <pthread.h>
10 #include <string.h>
11 #include "game.h"
12
13 /* Shared variables */
14
15 struct color black = {0};
16
17 struct material wall;
18 struct material air;
19 struct material outside;
20
21 struct node map[MAP_WIDTH][MAP_HEIGHT];
22
23 struct list *entities = & (struct list) {
24         .element = &player,
25         .next = NULL,
26 };
27
28 /* Private variables */
29
30 struct entity *entity_collision_map[MAP_WIDTH][MAP_HEIGHT] = {{NULL}};
31
32 static bool running = true;
33 static double damage_overlay = 0.0;
34 static struct color damage_overlay_color;
35
36 static struct list *air_functions = NULL;
37 static struct input_handler *input_handlers[256] = {NULL};
38 static struct entity *render_entities[LIGHT * 2 + 1][LIGHT * 2 + 1];
39 static struct list *render_components = NULL;
40 static struct list *globalsteps = NULL;
41
42 /* Helper functions */
43
44 struct color get_color(const char *str)
45 {
46         unsigned int r, g, b;
47         sscanf(str, "#%2x%2x%2x", &r, &g, &b);
48         return (struct color) {r, g, b};
49 }
50
51 void set_color(struct color color, bool bg)
52 {
53         printf("\e[%u;2;%u;%u;%um", bg ? 48 : 38, color.r, color.g, color.b);
54 }
55
56 void light_color(struct color *color, double light)
57 {
58         color->r *= light;
59         color->g *= light;
60         color->b *= light;
61 }
62
63 void mix_color(struct color *color, struct color other, double ratio)
64 {
65         double ratio_total = ratio + 1;
66
67         color->r = (color->r + other.r * ratio) / ratio_total;
68         color->g = (color->g + other.g * ratio) / ratio_total;
69         color->b = (color->b + other.b * ratio) / ratio_total;
70 }
71
72 void dir_to_xy(enum direction dir, int *x, int *y)
73 {
74         switch (dir) {
75                 case UP:
76                         (*y)--;
77                         break;
78                 case LEFT:
79                         (*x)--;
80                         break;
81                 case DOWN:
82                         (*y)++;
83                         break;
84                 case RIGHT:
85                         (*x)++;
86                         break;
87         }
88 }
89
90 struct list *add_element(struct list *list, void *element)
91 {
92         struct list **ptr;
93
94         for (ptr = &list; *ptr != NULL; ptr = &(*ptr)->next)
95                 ;
96
97         *ptr = malloc(sizeof(struct list));
98         (*ptr)->element = element;
99         (*ptr)->next = NULL;
100
101         return list;
102 }
103
104 int clamp(int v, int min, int max)
105 {
106         return v < min ? min : v > max ? max : v;
107 }
108
109 int max(int a, int b)
110 {
111         return a > b ? a : b;
112 }
113
114 int min(int a, int b)
115 {
116         return a < b ? a : b;
117 }
118
119 void *make_buffer(void *ptr, size_t size)
120 {
121         void *buf = malloc(size);
122         memcpy(buf, ptr, size);
123
124         return buf;
125 }
126
127 double calculate_dtime(struct timespec from, struct timespec to)
128 {
129         return (double) (to.tv_sec - from.tv_sec) + (double) (to.tv_nsec - from.tv_nsec) / 1000000000.0;
130 }
131
132 static struct
133 {
134         int number;
135         const char *symbol;
136 } roman_ct[13] = {
137         {1000, "M"},
138         {900, "CM"},
139         {500, "D"},
140         {400, "CD"},
141         {100, "C"},
142         {90, "XC"},
143         {50, "L"},
144         {40, "XL"},
145         {10, "X"},
146         {9, "IX"},
147         {5, "V"},
148         {4, "IV"},
149         {1, "I"}
150 };
151
152 void get_roman_numeral(int number, char **ptr, size_t *len)
153 {
154         *ptr = NULL;
155         *len = 0;
156
157         for (int i = 0; i < 13; i++) {
158                 while (number >= roman_ct[i].number) {
159                         number -= roman_ct[i].number;
160                         size_t old_len = *len;
161                         *len += 1 + i % 2;
162                         *ptr = realloc(*ptr, *len + 1);
163                         strcpy(*ptr + old_len, roman_ct[i].symbol);
164                 }
165         }
166 }
167
168 /* Game-related utility functions */
169
170 void quit()
171 {
172         running = false;
173 }
174
175 bool player_dead()
176 {
177         return player.health <= 0;
178 }
179
180 /* Map functions */
181
182 struct node get_node(int x, int y)
183 {
184         return is_outside(x, y) ? (struct node) {&outside} : map[x][y];
185 }
186
187 bool is_outside(int x, int y)
188 {
189         return x >= MAP_WIDTH || x < 0 || y >= MAP_HEIGHT || y < 0;
190 }
191
192 bool is_solid(int x, int y)
193 {
194         return get_node(x, y).material->solid;
195 }
196
197 /* Entity functions */
198
199 bool spawn(struct entity def, int x, int y, void *data)
200 {
201         if (is_solid(x, y))
202                 return false;
203
204         if (def.collide_with_entities && entity_collision_map[x][y])
205                 return false;
206
207         def.x = x;
208         def.y = y;
209
210         struct entity *entity = malloc(sizeof(struct entity));
211         *entity = def;
212
213         add_element(entities, entity);
214
215         if (entity->collide_with_entities)
216                 entity_collision_map[x][y] = entity;
217
218         if (entity->on_spawn)
219                 entity->on_spawn(entity, data);
220
221         return true;
222 }
223
224 bool move(struct entity *entity, int xoff, int yoff)
225 {
226         int x, y;
227
228         x = entity->x + xoff;
229         y = entity->y + yoff;
230
231         if (is_solid(x, y)) {
232                 if (entity->on_collide)
233                         entity->on_collide(entity, x, y);
234                 return false;
235         } else if (entity->collide_with_entities && entity_collision_map[x][y]) {
236                 if (entity->on_collide_with_entity)
237                         entity->on_collide_with_entity(entity, entity_collision_map[x][y]);
238                 return false;
239         } else {
240                 entity_collision_map[entity->x][entity->y] = NULL;
241                 entity->x = x;
242                 entity->y = y;
243                 entity_collision_map[entity->x][entity->y] = entity;
244                 return true;
245         }
246 }
247
248 void add_health(struct entity *entity, int health)
249 {
250         bool was_alive = entity->health > 0;
251
252         entity->health += health;
253
254         if (health < 0 && entity->on_damage)
255                 entity->on_damage(entity, -health);
256
257         if (entity->health > entity->max_health)
258                 entity->health = entity->max_health;
259         else if (entity->health <= 0 && was_alive && entity->on_death)
260                 entity->on_death(entity);
261 }
262
263 /* Register callback functions */
264
265 void register_air_function(struct generator_function func)
266 {
267         air_functions = add_element(air_functions, make_buffer(&func, sizeof(struct generator_function)));
268 }
269
270 void register_input_handler(unsigned char c, struct input_handler handler)
271 {
272         if (input_handlers[c])
273                 return;
274
275         input_handlers[c] = make_buffer(&handler, sizeof(struct input_handler));
276 }
277
278 void register_render_component(void (*callback)(struct winsize ws))
279 {
280         render_components = add_element(render_components, callback);
281 };
282
283 void register_globalstep(struct globalstep step)
284 {
285         globalsteps = add_element(globalsteps, make_buffer(&step, sizeof(struct globalstep)));
286 }
287
288 /* Player */
289
290 static void player_death(struct entity *self)
291 {
292         self->texture = "☠ ";
293 }
294
295 static void player_damage(struct entity *self, int damage)
296 {
297         damage_overlay += (double) damage * 0.5;
298 }
299
300 struct entity player = {
301         .name = "player",
302         .x = MAP_WIDTH / 2,
303         .y = MAP_HEIGHT / 2,
304         .color = {0},
305         .use_color = false,
306         .texture = "🙂",
307         .remove = false,
308         .meta = NULL,
309         .health = 10,
310         .max_health = 10,
311         .collide_with_entities = true,
312
313         .on_step = NULL,
314         .on_collide = NULL,
315         .on_collide_with_entity = NULL,
316         .on_spawn = NULL,
317         .on_remove = NULL,
318         .on_death = &player_death,
319         .on_damage = &player_damage,
320 };
321
322 /* Mapgen */
323
324 static void mapgen_set_air(int x, int y, enum mg_context ctx)
325 {
326         if (is_outside(x, y))
327                 return;
328
329         if (map[x][y].material == &air)
330                 return;
331
332         map[x][y] = (struct node) {&air};
333
334         for (struct list *ptr = air_functions; ptr != NULL; ptr = ptr->next) {
335                 struct generator_function *func = ptr->element;
336
337                 if (rand() % func->chance == 0)
338                         func->callback(x, y, ctx);
339         }
340 }
341
342 static void generate_room(int origin_x, int origin_y)
343 {
344         int left = 5 + rand() % 10;
345         int right = 5 + rand() % 10;
346
347         int up = 0;
348         int down = 0;
349
350         for (int x = -left; x <= right; x++) {
351                 if (x < 0) {
352                         up += rand() % 2;
353                         down += rand() % 2;
354                 } else {
355                         up -= rand() % 2;
356                         down -= rand() % 2;
357                 }
358
359                 for (int y = -up; y <= down; y++)
360                         mapgen_set_air(origin_x + x, origin_y + y, MG_CTX_ROOM);
361         }
362 }
363
364 static bool check_direction(int x, int y, enum direction dir)
365 {
366         if (dir % 2 == 0)
367                 return is_solid(x + 1, y) && is_solid(x - 1, y) && (is_solid(x, y + 1) || rand() % 3 > 1) && (is_solid(x, y - 1) || rand() % 3 > 1);
368         else
369                 return is_solid(x, y + 1) && is_solid(x, y - 1) && (is_solid(x + 1, y) || rand() % 3 > 1) && (is_solid(x - 1, y) || rand() % 3 > 1);
370 }
371
372 static void generate_corridor(int lx, int ly, enum direction ldir)
373 {
374         if (is_outside(lx, ly))
375                 return;
376
377         if (rand() % 200 == 0) {
378                 generate_room(lx, ly);
379                 return;
380         }
381
382         mapgen_set_air(lx, ly, MG_CTX_CORRIDOR);
383
384         int x, y;
385
386         enum direction dir;
387         enum direction ret = (ldir + 2) % 4;
388
389         int limit = 50;
390
391         do {
392                 x = lx;
393                 y = ly;
394
395                 if (rand() % 3 > 1)
396                         dir = ldir;
397                 else
398                         dir = rand() % 4;
399
400                 dir_to_xy(dir, &x, &y);
401         } while (dir == ret || (! check_direction(x, y, dir) && --limit));
402
403         if (limit)
404                 generate_corridor(x, y, dir);
405
406         if (rand() % 20 == 0)
407                 generate_corridor(lx, ly, ldir);
408 }
409
410 static void generate_corridor_random(int x, int y)
411 {
412         enum direction dir = rand() % 4;
413
414         generate_corridor(x, y, dir);
415         generate_corridor(x, y, (dir + 2) % 4);
416 }
417
418 /* Rendering */
419
420 static bool render_color(struct color color, double light, bool bg, bool use_color)
421 {
422         if (light <= 0.0) {
423                 set_color(black, bg);
424                 return false;
425         } else if (use_color) {
426                 if (damage_overlay > 0.0)
427                         mix_color(&color, damage_overlay_color, damage_overlay * 2.0);
428
429                 light_color(&color, light);
430
431                 set_color(color, bg);
432                 return true;
433         } else {
434                 return true;
435         }
436 }
437
438 static void render_map(struct winsize ws)
439 {
440         int cols = ws.ws_col / 2 - LIGHT * 2;
441         int rows = ws.ws_row / 2 - LIGHT;
442
443         int cols_left = ws.ws_col - cols - (LIGHT * 2 + 1) * 2;
444         int rows_left = ws.ws_row - rows - (LIGHT * 2 + 1);
445
446         for (int i = 0; i < rows; i++)
447                 for (int i = 0; i < ws.ws_col; i++)
448                         printf(" ");
449
450         for (int y = -LIGHT; y <= LIGHT; y++) {
451                 for (int i = 0; i < cols; i++)
452                         printf(" ");
453
454                 for (int x = -LIGHT; x <= LIGHT; x++) {
455                         int map_x, map_y;
456
457                         map_x = x + player.x;
458                         map_y = y + player.y;
459
460                         struct node node = get_node(map_x, map_y);
461
462                         double dist = sqrt(x * x + y * y);
463                         double light = 1.0 - (double) dist / (double) LIGHT;
464
465                         render_color(node.material->color, light, true, true);
466
467                         struct entity *entity = render_entities[x + LIGHT][y + LIGHT];
468                         render_entities[x + LIGHT][y + LIGHT] = NULL;
469
470                         if (entity && render_color(entity->color, light, false, entity->use_color))
471                                 printf("%s", entity->texture);
472                         else
473                                 printf("  ");
474                 }
475
476                 set_color(black, true);
477
478                 for (int i = 0; i < cols_left; i++)
479                         printf(" ");
480         }
481
482         for (int i = 0; i < rows_left; i++)
483                 for (int i = 0; i < ws.ws_col; i++)
484                         printf(" ");
485 }
486
487 static void render()
488 {
489         printf("\e[2J");
490
491         struct winsize ws;
492         ioctl(STDIN_FILENO, TIOCGWINSZ, &ws);
493
494         for (struct list *ptr = render_components; ptr != NULL; ptr = ptr->next) {
495                 printf("\e[0m\e[0;0H");
496                 set_color(black, true);
497
498                 ((void (*)(struct winsize ws)) ptr->element)(ws);
499         }
500
501         fflush(stdout);
502 }
503
504 /* Input */
505
506 static void handle_interrupt(int signal)
507 {
508         quit();
509 }
510
511 static void handle_input(unsigned char c)
512 {
513         struct input_handler *handler = input_handlers[c];
514
515         if (handler && (handler->run_if_dead || ! player_dead()))
516                 handler->callback();
517 }
518
519 static void *input_thread(void *unused)
520 {
521         while (running)
522                 handle_input(tolower(fgetc(stdin)));
523
524         return NULL;
525 }
526
527 /* Main Game */
528
529 void game()
530 {
531         struct sigaction sa;
532         sa.sa_handler = &handle_interrupt;
533         sigaction(SIGINT, &sa, NULL);
534
535         generate_corridor_random(player.x, player.y);
536
537         for (int i = 0; i < 50; i++)
538                 generate_corridor_random(rand() % MAP_WIDTH, rand() % MAP_HEIGHT);
539
540         struct termios oldtio, newtio;
541         tcgetattr(STDIN_FILENO, &oldtio);
542         newtio = oldtio;
543         newtio.c_lflag &= ~(ICANON | ECHO);
544         tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
545
546         printf("\e[?1049h\e[?25l");
547
548         pthread_t input_thread_id;
549         pthread_create(&input_thread_id, NULL, &input_thread, NULL);
550
551         struct timespec ts, ts_old;
552         clock_gettime(CLOCK_REALTIME, &ts_old);
553
554         while (running) {
555                 clock_gettime(CLOCK_REALTIME, &ts);
556                 double dtime = calculate_dtime(ts_old, ts);
557                 ts_old = ts;
558
559                 bool dead = player_dead();
560
561                 for (struct list *ptr = globalsteps; ptr != NULL; ptr = ptr->next) {
562                         struct globalstep *step = ptr->element;
563
564                         if (step->run_if_dead || ! dead)
565                                 step->callback(dtime);
566                 }
567
568                 if (! dead && damage_overlay > 0.0) {
569                         damage_overlay -= dtime;
570
571                         if (damage_overlay < 0.0)
572                                 damage_overlay = 0.0;
573                 }
574
575                 for (struct list **ptr = &entities; *ptr != NULL; ) {
576                         struct entity *entity = (*ptr)->element;
577
578                         if (entity->remove) {
579                                 assert(entity != &player);
580                                 struct list *next = (*ptr)->next;
581
582                                 if (entity->on_remove)
583                                         entity->on_remove(entity);
584
585                                 if (entity->meta)
586                                         free(entity->meta);
587
588                                 if (entity->collide_with_entities)
589                                         entity_collision_map[entity->x][entity->y] = NULL;
590
591                                 free(entity);
592                                 free(*ptr);
593
594                                 *ptr = next;
595                                 continue;
596                         }
597
598                         int dx, dy;
599
600                         dx = entity->x - player.x;
601                         dy = entity->y - player.y;
602
603                         bool visible = abs(dx) <= LIGHT && abs(dy) <= LIGHT;
604
605                         if (visible)
606                                 render_entities[dx + LIGHT][dy + LIGHT] = entity;
607
608                         if (! dead && entity->on_step)
609                                 entity->on_step(entity, (struct entity_step_data) {
610                                         .dtime = dtime,
611                                         .visible = visible,
612                                         .dx = dx,
613                                         .dy = dy,
614                                 });
615
616                         ptr = &(*ptr)->next;
617                 }
618
619                 render();
620
621                 // there is no such thing as glfwSwapBuffers, so we just wait 1 / 60 seconds to prevent artifacts
622                 usleep(1000000 / 60);
623         }
624
625         printf("\e[?1049l\e[?25h");
626         tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
627 }
628
629 /* Initializer function */
630
631 __attribute__ ((constructor)) static void init()
632 {
633         srand(time(0));
634
635         wall = (struct material) {
636                 .solid = true,
637                 .color = get_color("#5B2F00"),
638         };
639
640         air = (struct material) {
641                 .solid = false,
642                 .color = get_color("#FFE027"),
643         };
644
645         outside = (struct material) {
646                 .solid = true,
647                 .color = black,
648         };
649
650         entity_collision_map[player.x][player.y] = &player;
651
652         for (int x = 0; x < MAP_WIDTH; x++)
653                 for (int y = 0; y < MAP_HEIGHT; y++)
654                         map[x][y] = (struct node) {&wall};
655
656         register_input_handler('q', (struct input_handler) {
657                 .run_if_dead = true,
658                 .callback = &quit,
659         });
660
661         register_render_component(&render_map);
662
663         damage_overlay_color = get_color("#F20000");
664 }
665
666 /* Use later */
667
668 /*
669 get_box_char(is_solid(x, y - 1), is_solid(x, y + 1), is_solid(x - 1, y), is_solid(x + 1, y));
670
671 const char *get_box_char(bool up, bool down, bool left, bool right)
672 {
673         if (left && right && ! up && ! down)
674                 return "\u2501\u2501";
675         else if (up && down && ! right && ! left)
676                 return "\u2503 ";
677         else if (down && right && ! up && ! left)
678                 return "\u250F\u2501";
679         else if (down && left && ! up && ! right)
680                 return "\u2513 ";
681         else if (up && right && ! down && ! left)
682                 return "\u2517\u2501";
683         else if (up && left && ! down && ! right)
684                 return "\u251B ";
685         else if (up && down && right && ! left)
686                 return "\u2523\u2501";
687         else if (up && down && left && ! right)
688                 return "\u252B ";
689         else if (down && left && right && ! up)
690                 return "\u2533\u2501";
691         else if (up && left && right && ! down)
692                 return "\u253B\u2501";
693         else if (up && down && left && right)
694                 return "\u254b\u2501";
695         else if (left && ! up && ! down && ! right)
696                 return "\u2578 ";
697         else if (up && ! down && ! left && ! right)
698                 return "\u2579 ";
699         else if (right && ! up && ! down && ! left)
700                 return "\u257A\u2501";
701         else if (down && ! up && ! left && ! right)
702                 return "\u257B ";
703         else if (! up && ! down && ! left && ! right)
704                 return "\u25AA ";
705         else
706                 return "??";
707 }
708 */