r/cprogramming • u/NazgulResebo • 57m ago
Coding a Moiré Fractal with C, Raylib and GLSL
I created a simple moiré fractal using C, raylib and GLSL shaders.
The idea is quite simple: start with two nearby centers and generate concentric circles around each one, gradually increasing their radius.
Then, using the radius as input to a sin function, I generate alternating light and dark values. By applying this to the colors, the two circle patterns interact and produce the characteristic moiré effect.
Complete coding session:
Source code:
https://github.com/FractalCodeRicardo/hangover-programming/tree/main/moire-shaders
C / Raylib
#include <raylib.h>
#define size 800
float time = 0.0;
int main() {
InitWindow(size, size, "Moire Circles");
Shader shader = LoadShader(0, "moire.glsl");
int timeLoc = GetShaderLocation(shader, "time");
while (!WindowShouldClose()) {
time = GetTime();
SetShaderValue(shader, timeLoc, &time, SHADER_UNIFORM_FLOAT);
BeginDrawing();
BeginShaderMode(shader);
DrawRectangle(0, 0, size, size, BLACK);
EndShaderMode();
EndDrawing();
}
CloseWindow();
}
Glsl
#version 330
out vec4 color;
uniform float time;
void main() {
vec2 uv = gl_FragCoord.xy / 800;
uv = uv - 0.5;
float a = 30;
vec2 center1 = vec2(0.1, 0.0);
vec2 center2 = vec2(-0.1, 0.0);
float d1 = distance(center1, uv);
float d2 = distance(center2, uv);
vec4 color1 = vec4(
0.0 * sin(a * time*d1),
0.8 * sin(a * time*d1),
0.8 * sin(a * time*d1),
1
);
vec4 color2 = vec4(
1 * sin(a * time*d2),
0.2 * sin(a * time*d2),
1 * sin(a * time*d2),
1
);
color = mix(color1, color2, 0.5);
}AI Disclaimer:
I did not use AI to code the fractal.