/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   init_game.c                                        :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: pblagoje <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2022/05/04 13:58:13 by pblagoje          #+#    #+#             */
/*   Updated: 2022/05/04 13:59:14 by pblagoje         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "cube3d.h"

static void	init_img(t_img *img, void *mlx_ptr, t_win *win)
{
	img->ptr = mlx_new_image(mlx_ptr, win->size_x, win->size_y);
	img->data = mlx_get_data_addr(img->ptr, &img->bpp, &img->szl, &img->ndn);
	img->height = win->size_y;
}

static void	init_raycast(t_rcast *rcast)
{
	double	dist;

	dist = (SCREEN_FOCAL / 2) * M_PI / 180;
	dist = cos(dist) * ((SCREEN_WIDTH / 2) / sin(dist));
	rcast->screen_dist = dist;
	rcast->screen_width = SCREEN_WIDTH;
	rcast->screen_height = SCREEN_HEIGHT;
	rcast->screen_size.start.x = -SCREEN_WIDTH / 2;
	rcast->screen_size.start.y = -dist;
	rcast->screen_size.end.x = SCREEN_WIDTH / 2;
	rcast->screen_size.end.y = -dist;
	rcast->ray.start.x = 0;
	rcast->ray.start.y = 0;
	rcast->ray.end.x = -SCREEN_WIDTH / 2;
	rcast->ray.end.y = -dist;
}

static void	init_plr(t_plr *plr, t_map *map)
{
	plr->exact.x = map->plr_x * CELL + CELL / 2;
	plr->exact.y = map->plr_y * CELL + CELL / 2;
	plr->pos.x = plr->exact.x;
	plr->pos.y = plr->exact.y;
	plr->deg = PLR_ROT;
	plr->rot = 0;
	plr->cosi = 0;
	plr->cosj = 0;
	plr->sini = 0;
	plr->sinj = 0;
	if (map->plr_dir == 'E')
		plr_turn(plr, 90);
	if (map->plr_dir == 'S')
		plr_turn(plr, 180);
	if (map->plr_dir == 'W')
		plr_turn(plr, -90);
}

void	init_game(t_game *game)
{
	init_plr(&(game->plr), &(game->map));
	game->mlx_ptr = mlx_init();
	mb_add(game->mlx_ptr);
	game->win.size_x = SCREEN_WIDTH;
	game->win.size_y = SCREEN_HEIGHT;
	game->win.ptr = mlx_new_window(game->mlx_ptr, game->win.size_x, \
	game->win.size_y, "cube3d");
	init_img(&(game->img), game->mlx_ptr, &game->win);
	init_txtr(&game->txt, game->mlx_ptr);
	ft_bzero(&game->k_hook, sizeof(game->k_hook));
	init_raycast(&(game->rcast));
	game->rcast.cell = game->map.cell;
}
