sprstk/examples/basic.cpp
2025-08-06 13:14:35 -04:00

127 lines
2.4 KiB
C++

#include <sprstk/sprstk.h>
#include <simplexnoise1234.h>
#include <cmath>
namespace
{
constexpr int SIZE = 256;
double octaves(SimplexNoise1234& simplex, double x, double y, int layers, double persistence, double frequency)
{
double ampl = 1;
double maxval = 0;
double val = 0;
for (int i = 0; i < layers; i++)
{
val += simplex.noise(x * frequency, y * frequency) * ampl;
maxval += ampl;
ampl *= persistence;
frequency *= 2;
}
return val / maxval;
}
uint8_t data[SIZE * SIZE];
double ease(double n)
{
return pow(n, 1.5);
}
uint32_t color(uint8_t r, uint8_t g, uint8_t b, uint8_t a)
{
return (r << 24) | (g << 16) | (b << 8) | a;
}
int pick_pal(uint8_t height)
{
if (height > 20) { return 0; }
if (height > 8) { return 1; }
return 2;
}
void init(sprstk* instance, void* userdata)
{
sprstk_palette pal = {};
for (int i = 0; i < 24; i++)
{
uint8_t val = 0x33 / (12 - i / 2.0f) + 0x33;
pal.colors[i] = color(val, val, val, 0x7F);
}
for (int i = 24; i < 32; i++)
{
uint8_t val = 0x55 / (16 - i / 2.0f) + 0xAA;
pal.colors[i] = color(val, val, val, 0x7F);
}
sprstk_set_palette(instance, 0, &pal);
for (int i = 0; i < 16; i++)
{
pal.colors[i] = color(0x70 / (5.0f - i / 4.0f), 0x35 / (5.0f - i / 4.0f), 0, 0x7F);
}
for (int i = 16; i < 32; i++)
{
pal.colors[i] = color(0x05 / (8.5f - i / 2.5f) + 0x15, 0x40 / (8.5f - i / 2.5f) + 0x0, 0, 0x7F);
}
sprstk_set_palette(instance, 1, &pal);
for (int i = 0; i < 8; i++)
{
pal.colors[i] = color(0x20 / (8 - i) + 0x20, 0x40 / (8 - i) + 0x40, 0x90 / (8 - i) + 0x40, 0x7F);
}
sprstk_set_palette(instance, 2, &pal);
sprstk_set_scale(instance, 0.4f);
SimplexNoise1234 simplex;
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
double value = octaves(simplex, i, j, 6, 0.4, 1.0 / 128.0);
data[i + j * SIZE] = 28 * ease((value + 1) / 2) + 3;
}
}
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
sprstk_put(instance, i - SIZE / 2, j - SIZE / 2, data[i + SIZE * j], pick_pal(data[i + SIZE * j]));
}
}
}
void update(sprstk* instance, float dt, float* userdata)
{
*userdata += dt / 2;
sprstk_set_angle(instance, *userdata);
}
}
int main()
{
float data = 0;
sprstk* instance = sprstk_new({.init = init, .update = (sprstk_update_fn)update}, &data);
sprstk_run(instance);
sprstk_stop(instance);
return 0;
}