c8/srcs/graphics.c

122 lines
3.3 KiB
C

#include "graphics.h"
#include <SDL2/SDL.h>
#include <stdint.h>
#include <stdio.h>
#include "chip8.h"
int graphics_init(t_display *display)
{
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
fprintf(stderr, "SDL2 could not initiallize! e=%s\n", SDL_GetError());
return (1);
}
display->window = SDL_CreateWindow("c8",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
SCREEN_WIDTH * SCALE,
SCREEN_HEIGHT * SCALE,
SDL_WINDOW_SHOWN);
if (!display->window)
{
fprintf(stderr, "Window could not be created! e=%s\n", SDL_GetError());
return (1);
}
display->renderer = SDL_CreateRenderer(display->window, -1, SDL_RENDERER_ACCELERATED);
if (!display->renderer)
{
fprintf(stderr, "Renderer could not be created! e=%s\n", SDL_GetError());
return (1);
}
display->texture = SDL_CreateTexture(display->renderer, SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING,
SCREEN_WIDTH,
SCREEN_HEIGHT);
if (!display->texture)
{
fprintf(stderr, "Texture could not be created! e=%s\n", SDL_GetError());
return (1);
}
return (0);
}
void graphics_render(t_chip8 *emu)
{
for (int i = 0; i < SCREEN_WIDTH * SCREEN_HEIGHT; i++)
{
uint8_t pixel = emu->memory.screen[i];
emu->display.pixels[i] = pixel ? 0xFFFFFFFF : 0xFF000000;
}
SDL_UpdateTexture(emu->display.texture, NULL, emu->display.pixels, SCREEN_WIDTH * sizeof(uint32_t));
SDL_RenderClear(emu->display.renderer);
SDL_RenderCopy(emu->display.renderer, emu->display.texture, NULL, NULL);
SDL_RenderPresent(emu->display.renderer);
}
void graphics_cleanup(t_display *display)
{
SDL_DestroyTexture(display->texture);
SDL_DestroyRenderer(display->renderer);
SDL_DestroyWindow(display->window);
SDL_Quit();
}
void graphics_draw_sprite(t_chip8 *emu, uint8_t x, uint8_t y, uint8_t n)
{
uint8_t pixel;
uint16_t sprite_address = emu->i;
uint8_t collision = 0;
for (int row = 0; row < n; row++)
{
pixel = emu->memory.memory[sprite_address + row];
for (int col = 0; col < 8; col++)
{
if ((pixel & (0x80 >> col)) != 0)
{
uint16_t screen_x = (x + col) % SCREEN_WIDTH;
uint16_t screen_y = (y + row) % SCREEN_HEIGHT;
if (emu->memory.screen[screen_y * SCREEN_WIDTH + screen_x] == 1)
{
collision = 1;
}
emu->memory.screen[screen_y * SCREEN_WIDTH + screen_x] ^= 1;
}
}
}
emu->v[0xF] = collision;
}
int graphics_display_ready()
{
SDL_Event event;
while (1)
{
while (SDL_PollEvent(&event) != 0)
{
if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_SHOWN)
{
return 1;
}
// Check for window close event
if (event.type == SDL_QUIT)
{
return 0;
}
}
SDL_Delay(10);
}
}