How to generate basic Perlin noise with SDL3 and stb_perlin in C

1 Answer

0 votes
#include <stdio.h>

// #define STB_PERLIN_IMPLEMENTATION
#include "stb_perlin.h"

#include <SDL3/SDL.h>

#define WIDTH 800
#define HEIGHT 600

int main(int argc, char* argv[]) {
    if (!SDL_Init(SDL_INIT_VIDEO)) {
        SDL_Log("Couldn't initialize SDL: %s", SDL_GetError());
        return SDL_APP_FAILURE;
    }

    // Create SDL window and renderer
    SDL_Window* window = SDL_CreateWindow("SDL3  Perlin noise", WIDTH, HEIGHT, SDL_WINDOW_OPENGL);
    if (window == NULL) {
        printf("SDL_CreateWindow Error: %s\n", SDL_GetError());
        SDL_Quit();
        return 1;
    }
    
    SDL_Renderer* renderer = SDL_CreateRenderer(window, NULL);

    if (renderer == NULL) {
        SDL_DestroyWindow(window);
        printf("SDL_CreateRenderer Error: %s\n", SDL_GetError());
        SDL_Quit();
        return 1;
    }

    // Generate and display Perlin noise
    for (int y = 0; y < HEIGHT; y++) {
        for (int x = 0; x < WIDTH; x++) {
            // Scale coordinates for Perlin noise function
            float nx = x / (float)WIDTH, ny = y / (float)HEIGHT;
            // float stb_perlin_noise3(float x, float y, float z, int x_wrap, int y_wrap, int z_wrap)
            float noiseValue = stb_perlin_noise3(nx * 10, ny * 10, 0, 0, 0, 0);

            // Map noise value to grayscale color
            int color = (int)((noiseValue + 1) * 127.5);

            // Set pixel color
   
            // bool SDL_SetRenderDrawColor(SDL_Renderer *renderer, Uint8 r, Uint8 g, Uint8 b, Uint8 a);
            SDL_SetRenderDrawColor(renderer, color, color, color, 255);

            // SDL_RenderPoint(SDL_Renderer * renderer, float x, float y);
            SDL_RenderPoint(renderer, (float)x, (float)y);
        }
    }

    // Present the renderer
    SDL_RenderPresent(renderer);

    // Wait for 2 seconds before closing
    SDL_Delay(2000);

    // Clean up and quit SDL
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;
}



/*
run:


*/

 



answered Jan 24, 2025 by avibootz
edited Jan 26, 2025 by avibootz
...