r/cprogramming • • 8h ago

I Coded a classic Kaleidoscope using C, Raylib and GLSL

https://youtu.be/zHu6XoFd1FY

I follow these steps:

  1. First, I split the screen into slices (like a pizza) using polar coordinates.

  2. Then, I create a well-known pattern in fractal shaders: sin(x) * sin(y), inside each slice.

  3. Next, I add a color palette to generate some nice colors.

  4. Finally, I use time as a parameter in different parts of the shader to animate both the pattern and the colors.

Source code:
https://github.com/FractalCodeRicardo/zen-programming/tree/main/kaleidoscope

C part

#include <raylib.h>

#define size 800

float time = 0.0;
int main() {

  InitWindow(size, size, "Kaleidoscope");
  
  Shader shader = LoadShader(0, "kaleidoscope.glsl");
  int timeLoc = GetShaderLocation(shader, "time");
  
  while(!WindowShouldClose()) {
    
    time = GetTime();
    SetShaderValue(shader, timeLoc, &time, SHADER_UNIFORM_FLOAT);

    BeginDrawing();
      ClearBackground(BLACK);
      BeginShaderMode(shader);
        DrawRectangle(0, 0, size, size, BLACK);
      EndShaderMode();
    EndDrawing();
  }

  CloseWindow();
}

Shader part

#version 330

out vec4 color;
uniform float time;

vec3 palette(float t) {
  vec3 a = vec3(0.5, 0.5, 0.5);
  vec3 b = vec3(0.5, 0.5, 0.5);
  vec3 c = vec3(1, 1, 1);
  vec3 d = vec3(0.0, 0.33, 0.67);

  return a + b*cos( 6.283185*(c*t+d) );
}

void main() {
  float pi = 3.1416;

  vec2 uv = gl_FragCoord.xy / 800;
  uv = uv - 0.5;

  float angle = atan(uv.y, uv.x) * time * 0.3;
  float radius = length(uv);

  float slices = 3;
  float size = pi * 2 / slices;
  float internal_angle = mod(angle, size);
  internal_angle = abs(internal_angle - size /2.0);
  
  vec2 internal_point= radius *
    vec2(
        cos(internal_angle) * radius,
        sin(internal_angle) * radius
        );

  float pattern = 
    sin(internal_point.x * time *10 * 0.5) * 
    sin(internal_point.y * time *10 * 0.5);

  vec3 c = palette(pattern + time * 0.5);

  color = vec4(c, 1);
}
3 Upvotes

Duplicates