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