event.c
1 /* ************************************************************************** */ 2 /* */ 3 /* ::: :::::::: */ 4 /* event.c :+: :+: :+: */ 5 /* +:+ +:+ +:+ */ 6 /* By: omougel <omougel@student.42lyon.fr> +#+ +:+ +#+ */ 7 /* +#+#+#+#+#+ +#+ */ 8 /* Created: 2024/07/29 15:19:32 by omougel #+# #+# */ 9 /* Updated: 2024/10/25 14:37:40 by ll-hotel ### ########.fr */ 10 /* */ 11 /* ************************************************************************** */ 12 13 #include "cub3D.h" 14 #include "mlx.h" 15 #include <stdbool.h> 16 #include <unistd.h> 17 #include <X11/keysym.h> 18 #include <X11/X.h> 19 20 static int keypress_hook(int keysym, t_cube *cube); 21 static int keyrelease_hook(int keysym, t_cube *cube); 22 static int loop_hook(t_cube *cube); 23 24 void cube_loop(t_cube *cube) 25 { 26 mlx_do_sync(cube->mlx.ptr); 27 mlx_do_key_autorepeaton(cube->mlx.ptr); 28 mlx_loop_hook(cube->mlx.ptr, loop_hook, cube); 29 mlx_hook(cube->mlx.win, KeyPress, KeyPressMask, keypress_hook, cube); 30 mlx_hook(cube->mlx.win, KeyRelease, KeyReleaseMask, keyrelease_hook, cube); 31 mlx_hook(cube->mlx.win, DestroyNotify, 0, mlx_loop_end, cube->mlx.ptr); 32 mlx_mouse_hook(cube->mlx.win, mouse_handler, cube); 33 mlx_loop(cube->mlx.ptr); 34 } 35 36 static int keypress_hook(int keysym, t_cube *cube) 37 { 38 if (keysym == XK_Escape) 39 return (mlx_loop_end(cube->mlx.ptr)); 40 else if ((keysym == XK_Left || keysym == XK_Right) 41 && !cube->player.use_pointer) 42 cube->player.turning = (keysym == XK_Left) - (keysym == XK_Right); 43 else if (keysym == XK_w || keysym == XK_s) 44 cube->player.walking = (keysym == XK_w) - (keysym == XK_s); 45 else if (keysym == 'a' || keysym == 'd') 46 cube->player.strafing = (keysym == 'a') - (keysym == 'd'); 47 return (0); 48 } 49 50 static int loop_hook(t_cube *cube) 51 { 52 if (cube->player.moving) 53 { 54 move_player(cube, &cube->player); 55 cube_render(cube); 56 } 57 return (0); 58 } 59 60 static int keyrelease_hook(int keysym, t_cube *cube) 61 { 62 if ((keysym == XK_Left || keysym == XK_Right) && !cube->player.use_pointer) 63 cube->player.turning = 0; 64 else if (keysym == 'w' || keysym == 's') 65 cube->player.walking = 0; 66 else if (keysym == 'a' || keysym == 'd') 67 cube->player.strafing = 0; 68 return (0); 69 }