summaryrefslogtreecommitdiff
path: root/sily.c
diff options
context:
space:
mode:
Diffstat (limited to 'sily.c')
-rw-r--r--sily.c93
1 files changed, 93 insertions, 0 deletions
diff --git a/sily.c b/sily.c
new file mode 100644
index 0000000..750d491
--- /dev/null
+++ b/sily.c
@@ -0,0 +1,93 @@
+/* ************************************************************************** */
+/* */
+/* ::: :::::::: */
+/* sily.c :+: :+: :+: */
+/* +:+ +:+ +:+ */
+/* By: kdx <kdx @student.42angouleme.fr +#+ +:+ +#+ */
+/* +#+#+#+#+#+ +#+ */
+/* Created: 2022/10/07 04:15:41 by kdx #+# #+# */
+/* Updated: 2022/10/16 01:26:55 by kdx ### ########.fr */
+/* */
+/* ************************************************************************** */
+
+#include "sily.h"
+#include "game.h"
+#include "minilibx/mlx.h"
+#include <X11/X.h>
+#include <stdlib.h>
+
+static int sily_hook_destroy(t_sily *sily)
+{
+ game_destroy(sily->game);
+ exit(0);
+ return (0);
+}
+
+t_err sily_init(t_sily *sily, int width, int height, char *title)
+{
+ ft_bzero(sily, sizeof(*sily));
+ if (width <= 0)
+ return (1 | ft_dprintf(2, "width is < 0\n"));
+ if (height <= 0)
+ return (1 | ft_dprintf(2, "height is < 0\n"));
+ if (title == NULL)
+ return (1 | ft_dprintf(2, "title is NULL\n"));
+ sily->width = width;
+ sily->height = height;
+ sily->ctx = mlx_init();
+ if (sily->ctx == NULL)
+ return (1 | ft_dprintf(2, "mlx_init failed\n"));
+ sily->window = mlx_new_window(sily->ctx, width, height, title);
+ if (sily->window == NULL)
+ return (1 | ft_dprintf(2, "mlx_new_window failed\n"));
+ mlx_expose_hook(sily->window, sily_expose_hook, sily);
+ mlx_key_hook(sily->window, sily_input_release_ev, sily);
+ mlx_hook(sily->window, KeyPress, KeyPressMask, sily_input_press_ev,
+ sily);
+ mlx_hook(sily->window, DestroyNotify, StructureNotifyMask,
+ sily_hook_destroy, sily);
+ mlx_do_key_autorepeatoff(sily->ctx);
+ sily->next_time = sily_get_time();
+ return (0);
+}
+
+void sily_deinit(t_sily *sily)
+{
+ if (sily->ctx != NULL)
+ mlx_loop_end(sily->ctx);
+ if (sily->window != NULL)
+ mlx_destroy_window(sily->ctx, sily->window);
+ if (sily->ctx != NULL)
+ mlx_destroy_display(sily->ctx);
+ free(sily->ctx);
+ ft_bzero(sily, sizeof(*sily));
+}
+
+static int sily_update(t_sily *sily)
+{
+ t_u64 cur_time;
+
+ if (sily->quit)
+ game_destroy(sily->game);
+ else
+ {
+ sily->update(sily);
+ sily->next_time += MIN_DT;
+ sily->draw(sily);
+ cur_time = sily_get_time();
+ if (sily->next_time <= cur_time)
+ sily->next_time = cur_time;
+ else
+ sily_sleep(sily->next_time - cur_time);
+ }
+ sily->tick++;
+ return (0);
+}
+
+void sily_loop(t_sily *sily, void (*u)(t_sily *), void (*d)(t_sily *))
+{
+ mlx_loop_hook(sily->ctx, sily_update, sily);
+ sily->update = u;
+ sily->draw = d;
+ mlx_loop(sily->ctx);
+}