Last active
April 24, 2024 22:08
-
-
Save FernandoAiresCastello/9d1d2cc23ebd6c8f841dbed2d7b10455 to your computer and use it in GitHub Desktop.
Functions to dynamically draw individual pixels in C using SDL2. Is this the fastest way? Is this the simplest way? Is it the most elegant way? You'll be the judge.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <stdbool.h> | |
#include <SDL.h> | |
typedef int rgb; | |
#define SCR_W 360 | |
#define SCR_H 200 | |
#define BUFLEN SCR_W * SCR_H * sizeof(rgb) | |
#define WND_ZOOM 3 | |
#define WND_W SCR_W * WND_ZOOM | |
#define WND_H SCR_H * WND_ZOOM | |
SDL_Window* wnd = NULL; | |
SDL_Renderer* rend = NULL; | |
SDL_Texture* tex = NULL; | |
rgb scrbuf[BUFLEN] = { 0 }; | |
bool fullscreen = false; | |
void open_window(const char* title) | |
{ | |
SDL_SetHint(SDL_HINT_RENDER_DRIVER, "direct3d"); | |
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "nearest"); | |
fullscreen = false; | |
wnd = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WND_W, WND_H, fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0); | |
rend = SDL_CreateRenderer(wnd, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE); | |
tex = SDL_CreateTexture(rend, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, SCR_W, SCR_H); | |
SDL_SetRenderDrawBlendMode(rend, SDL_BLENDMODE_NONE); | |
SDL_SetTextureBlendMode(tex, SDL_BLENDMODE_NONE); | |
SDL_RenderSetLogicalSize(rend, SCR_W, SCR_H); | |
SDL_SetWindowPosition(wnd, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); | |
SDL_RaiseWindow(wnd); | |
} | |
void update_window() | |
{ | |
static int pitch; | |
static void* pixels; | |
SDL_LockTexture(tex, NULL, &pixels, &pitch); | |
SDL_memcpy(pixels, scrbuf, BUFLEN); | |
SDL_UnlockTexture(tex); | |
SDL_RenderCopy(rend, tex, NULL, NULL); | |
SDL_RenderPresent(rend); | |
} | |
void set_pixel(int x, int y, rgb color) | |
{ | |
if (x >= 0 && y >= 0 && x < SCR_W && y < SCR_H) { | |
scrbuf[y * SCR_W + x] = color; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment