💾 Archived View for thingvellir.net › toys › applet › noise.c captured on 2023-01-29 at 02:58:54.

View Raw

More Information

➡️ Next capture (2024-07-09)

-=-=-=-=-=-=-

/* 'noise' wasm applet demo, Ada <sarahsooup@protonmail.com> 2022, CC0-1.0 */
#include <stdint.h>
/*
 * noise section
 */
static inline float hash2(uint32_t x, uint32_t y) {
	x *= 1597334677U;
	y *= 3812015801U;
	return ((x ^ y) * 1597334677U) / (float)0xFFFFFFFF;
}

static inline float grad(float x) { return x * x * (3.0f - 2.0f * x); }
static inline float lerp(float t, float a, float b) {
	return a + t * (b - a);
}

static float noise2(float x, float y) {
	int xi = __builtin_wasm_trunc_s_i32_f32(x);
	int yi = __builtin_wasm_trunc_s_i32_f32(y);

	/* this was going to be value noise but i couldnt figure it out */

	return hash2(xi, yi);
}

static float fbm2(float x, float y) {
	float accum = 0.0f;

	for (int i = 1; i < 6; i++) {
		accum += noise2(x * i, y * i) / 6.0f;
	}

	return accum;
}

/*
 * applet section
 */
static uint32_t ticks = 0;
static uint32_t fb[128 * 128] = {0};

#define IMPORT(name) \
	[[clang::import_module("applet"), clang::import_name(name)]]

IMPORT("log") void ffi_log(const char *ptr, uint32_t len);
IMPORT("set_framerate") void ffi_framerate(uint32_t fps);
IMPORT("quit") void ffi_quit(uint32_t code);
IMPORT("sin") float ffi_sin(float x);
IMPORT("cos") float ffi_cos(float x);

uint32_t *applet_fbptr(void) { return fb; }
uint32_t applet_fbsize(void) { return (128 << 16) | 128; }
void applet_init(void) { ffi_framerate(20); }
void applet_input(uint32_t type, int arg1, int arg2) {}

void applet_render(void) {
	float t = ticks / 30.0f;
	float xt = ffi_sin(t) * 64.0f;
	float yt = ffi_cos(t) * 64.0f;
	for (uint32_t x = 0; x < 128; x++) {
		for (uint32_t y = 0; y < 128; y++) {
			uint32_t pos = (y * 128) + x;
			float fval = fbm2((x + xt) / 16.0f,
			                  (y + yt) / 16.0f);
			uint8_t val = (uint8_t)(fval * 255.0f);
			fb[pos] = (0xFF << 24) | (val << 16) | (val << 8) | val;
		}
	}
	ticks += 1;
}