Skip to main content

Core Structures

Cub3D uses two primary structures defined in cub3.h to manage game state and texture data.

t_map Structure

The t_map structure is the central data container that holds all game state, configuration, and runtime data:
cub3.h (lines 79-162)
typedef struct s_map
{
    char        *northtexture;
    char        *southtexture;
    char        *westtexture;
    char        *easttexture;
    char        *floorcolor;
    char        *ceilingcolor;
    int         floor_color;
    int         ceiling_color;
    char        map[500][500];
    char        *path;
    char        **final_map;
    char        **toflood_map;
    char        **spaceless_map;
    int         map_height;
    int         map_width;

    // Input state
    int         key_a;
    int         key_w;
    int         key_s;
    int         key_d;
    int         key_left;
    int         key_right;
    int         wall_dir;

    // Player position
    int         x;
    int         y;
    double      xx;
    double      yy;
    double      new_x;
    double      new_y;
    int         map_x;
    int         map_y;
    int         d;
    int         end;

    // Raycasting variables
    int         speed;
    int         line_height;
    int         side;
    int         step_y;
    int         step_x;

    // Ray direction and camera
    double      wall_x;
    double      ray_dir_x;
    double      ray_dir_y;
    double      delta_dist_x;
    double      delta_dist_y;
    double      side_dist_x;
    double      side_dist_y;
    double      dir_x;
    double      dir_y;
    double      ray_y;
    double      ray_x;
    double      plane_x;
    double      plane_y;
    double      camera_x;
    double      starting_angle;

    int         column;
    int         row;

    // MiniLibX graphics
    void        *mlx_ptr;
    void        *win_ptr;
    void        *img_ptr;
    char        *pixel_ptr;
    int         bpp;
    int         line_length;
    int         endian;
    char        *name;
    
    // Texture data
    t_texture   tex_north;
    t_texture   tex_south;
    t_texture   tex_east;
    t_texture   tex_west;
    t_texture   *current_tex;
} t_map;

Field Categories

FieldTypeDescription
northtexturechar*Path to north wall texture (e.g., ”./textures/north.xpm”)
southtexturechar*Path to south wall texture
westtexturechar*Path to west wall texture
easttexturechar*Path to east wall texture
floorcolorchar*Floor color as string (e.g., “220,100,0”)
ceilingcolorchar*Ceiling color as string
floor_colorintFloor color as packed RGB integer
ceiling_colorintCeiling color as packed RGB integer
pathchar*Path to the .cub map file
namechar*Map name extracted from filename (used as window title)
FieldTypeDescription
map[500][500]charStatic buffer for initial map parsing
final_mapchar**Dynamically allocated final map used during gameplay
toflood_mapchar**Copy of map used for flood fill validation
spaceless_mapchar**Map variant without spaces (unused in current implementation)
map_heightintNot used (see row instead)
map_widthintNot used (see column instead)
rowintNumber of rows in the map
columnintNumber of columns in the map
The map uses ‘1’ for walls, ‘0’ for empty space, and ‘N’/‘S’/‘E’/‘W’ for the player starting position and orientation.
FieldTypeDescription
key_wint1 if W key pressed (move forward), 0 otherwise
key_sint1 if S key pressed (move backward), 0 otherwise
key_aint1 if A key pressed (strafe left), 0 otherwise
key_dint1 if D key pressed (strafe right), 0 otherwise
key_leftint1 if Left Arrow pressed (rotate left), 0 otherwise
key_rightint1 if Right Arrow pressed (rotate right), 0 otherwise
wall_dirintWall direction (unused in current implementation)
Key states are set to 1 on key press and 0 on key release, enabling smooth continuous movement.
FieldTypeDescription
xintInitial player grid X position (row in map)
yintInitial player grid Y position (column in map)
xxdoubleCurrent player X position in pixels
yydoubleCurrent player Y position in pixels
new_xdoubleProposed new X position (for collision detection)
new_ydoubleProposed new Y position (for collision detection)
map_xintCurrent grid cell X (updated during DDA)
map_yintCurrent grid cell Y (updated during DDA)
speedintMovement speed in pixels per frame (set to 1)
Variable naming is inconsistent: x and y are grid coordinates, while xx and yy are pixel coordinates. The transformation is: xx = y * SIZE + SIZE/2 and yy = x * SIZE + SIZE/2.
FieldTypeDescription
ray_dir_xdoubleX component of current ray direction vector
ray_dir_ydoubleY component of current ray direction vector
delta_dist_xdoubleDistance ray travels to cross one X-axis grid cell
delta_dist_ydoubleDistance ray travels to cross one Y-axis grid cell
side_dist_xdoubleDistance from ray origin to next vertical grid line
side_dist_ydoubleDistance from ray origin to next horizontal grid line
step_xintDirection to step in X (-1 or +1)
step_yintDirection to step in Y (-1 or +1)
sideintWhich wall face was hit (0=vertical, 1=horizontal)
line_heightintHeight of wall slice to draw (inversely proportional to distance)
wall_xdoubleExact X or Y coordinate where ray hit wall (for texture mapping)
dintTexture Y offset calculation variable
endintBottom pixel of wall slice
See the DDA Algorithm page for detailed explanations.
FieldTypeDescription
dir_xdoubleX component of camera direction (forward vector)
dir_ydoubleY component of camera direction (forward vector)
plane_xdoubleX component of camera plane (perpendicular to direction)
plane_ydoubleY component of camera plane (perpendicular to direction)
starting_angledoublePlayer’s current angle in radians [0, 2π]
camera_xdoubleCurrent camera space X coordinate for ray being cast
ray_xdoubleUnused
ray_ydoubleUnused
Calculated by set_player_dir_and_plane():
dir_x = cos(starting_angle);
dir_y = sin(starting_angle);
plane_x = -dir_y * 0.66;  // Perpendicular, 66% magnitude for FOV
plane_y = dir_x * 0.66;
FieldTypeDescription
mlx_ptrvoid*MiniLibX connection pointer (from mlx_init())
win_ptrvoid*Window pointer (from mlx_new_window())
img_ptrvoid*Image buffer pointer (from mlx_new_image())
pixel_ptrchar*Direct pixel data pointer (from mlx_get_data_addr())
bppintBits per pixel (typically 32)
line_lengthintBytes per screen row (WIDTH * bpp / 8)
endianintEndianness flag (0=little-endian, 1=big-endian)
FieldTypeDescription
tex_northt_textureNorth wall texture data
tex_southt_textureSouth wall texture data
tex_eastt_textureEast wall texture data
tex_westt_textureWest wall texture data
current_text_texture*Pointer to currently selected texture for drawing
Set by select_texture() based on side and ray_dir.

t_texture Structure

Holds texture image data loaded from XPM files:
cub3.h (lines 68-77)
typedef struct s_texture
{
    void    *img_ptr;
    char    *data;
    int     width;
    int     height;
    int     bpp;
    int     line_len;
    int     endian;
} t_texture;

Field Descriptions

FieldTypeDescription
img_ptrvoid*MiniLibX image pointer (from mlx_xpm_file_to_image())
datachar*Raw pixel data buffer (from mlx_get_data_addr())
widthintTexture width in pixels
heightintTexture height in pixels
bppintBits per pixel
line_lenintBytes per texture row
endianintEndianness (0=little, 1=big)

Texture Loading

main.c (lines 29-41)
void	load_texture(t_map *mapa, t_texture *tex, char *path)
{
	tex->img_ptr = mlx_xpm_file_to_image(mapa->mlx_ptr, path,
			&tex->width, &tex->height);
	if (!tex->img_ptr)
	{
		perror("Error cargando textura");
		freeall(mapa);
		exit(1);
	}
	tex->data = mlx_get_data_addr(tex->img_ptr, &tex->bpp,
			&tex->line_len, &tex->endian);
}

Texture Sampling

During rendering, pixels are sampled from data using:
drawing.c (lines 26-27)
offset = tex_y * mapa->current_tex->line_len + tex_x * (mapa->current_tex->bpp / 8);
color = *(int *)(mapa->current_tex->data + offset);
Where:
  • tex_x = horizontal position in texture [0, width)
  • tex_y = vertical position in texture [0, height)
  • offset = byte offset into pixel data array
Textures must be in XPM format. The engine does not perform any filtering or mipmapping - pixels are sampled directly.

Configuration Constants

Defined in cub3.h (lines 24-66):

Display Constants

#define WIDTH 1732
#define HEIGHT 1000
#define SIZE 30
#define POV 1.17
ConstantValueUsage
WIDTH1732Screen/window width in pixels
HEIGHT1000Screen/window height in pixels
SIZE30Grid cell size (affects map scale and collision)
POV1.17Point-of-view constant (unused in current implementation)

Mathematical Constants

#define PI 3.14159265358979323846
Used for angle calculations and trigonometry.

Color Constants

#define RED 0xFF0000
#define GREEN 0xFF00
#define WHITE 0xFFFFFF
#define BLACK 0x000000
#define YELLOW 0xFFFF00
Colors are stored as 32-bit integers in format 0x00RRGGBB. Hardcoded colors in drawing.c:
  • Ceiling: 0x87CEEB (sky blue)
  • Floor: 0x444444 (dark gray)

Key Code Constants

#define W 119
#define A 97
#define S 115
#define D 100
ASCII codes for WASD movement keys. The actual implementation uses X11 key symbols (e.g., XK_w) from <X11/keysym.h>.

Minimap Constants (Unused)

#define MINIMAP_SIZE 0.2f
#define MINIMAP_X 8
#define MINIMAP_Y 4
These are defined but not used in the current implementation.

Error Message Macros

Extensive error messages defined as string literals:
#define ARGERROR "Debes introducir dos argumentos por terminal\n"
#define ARGERROR2 "Argumento vacio, especifica un mapa\n"
#define ARGERROR3 "El mapa tiene que acabar en .cub\n"
Used with the msg() utility:
void msg(int fd, char *str)  // Writes string to file descriptor

Memory Layout Considerations

Large Stack Allocation: The map[500][500] array in t_map allocates 250KB on the stack. This is acceptable for most systems but could cause stack overflow if t_map is allocated on a thread with small stack size.

Memory Ownership

  • Texture paths: Dynamically allocated with ft_strdup(), freed by freeall()
  • Map arrays: final_map and toflood_map are dynamically allocated with ft_calloc(), freed by freeme()
  • Texture data: Managed by MiniLibX, freed with mlx_destroy_image()
  • MiniLibX context: Freed with mlx_destroy_window(), mlx_destroy_display(), and free(mlx_ptr)

Typical Memory Usage

ComponentApproximate Size
t_map structure~250KB (mostly the static map buffer)
Screen framebuffer~6.7MB (1732×1000×4 bytes)
Four texturesVaries (e.g., 4×64×64×4 = 64KB for 64x64 textures)
Map arraysDepends on map size (row count × column count)
Total~257MB + map data
The actual memory usage is much smaller than the theoretical maximum since the 500×500 map buffer is rarely fully utilized.