1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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);
}
|