Donut!

25 Nov 2026 10:12
5 views
c 1,862 chars · 79 lines

#include <stdio.h>
#include <math.h>
#include <unistd.h>

#define W 80
#define H 24

int main(void)
{
    float A = 0, B = 0;
    float zbuffer[W * H];
    char output[W * H];

    printf("\033[2J");

    while (1) {
        for (int i = 0; i < W * H; i++) {
            output[i] = ' ';
            zbuffer[i] = 0;
        }

        for (float theta = 0; theta < 6.28; theta += 0.07) {
            for (float phi = 0; phi < 6.28; phi += 0.02) {

                float ct = cos(theta), st = sin(theta);
                float cp = cos(phi), sp = sin(phi);

                float h = ct + 2;
                float D = 1 / (sp * h * sin(A) +
                               st * cos(A) + 5);

                float t = sp * h * cos(A) -
                          st * sin(A);

                int x = W/2 + 30 * D *
                    (cp * h * cos(B) - t * sin(B));

                int y = H/2 + 15 * D *
                    (cp * h * sin(B) + t * cos(B));

                int o = x + W * y;

                int N = 8 * (
                    (sp * st - cp * ct * cos(A)) *
                    cos(B) -
                    cp * ct * sin(A) -
                    sp * st * sin(B)
                );

                if (x >= 0 && x < W &&
                    y >= 0 && y < H && D > zbuffer[o]) {

                    zbuffer[o] = D;

                    char *shades = ".,-~:;=!*#$@";
                    int shade = N > 0 ? N : 0;
                    if (shade > 11) shade = 11;

                    output[o] = shades[shade];
                }
            }
        }

        printf("\033[H");

        for (int i = 0; i < W * H; i++) {
            putchar(i % W ? output[i] : '\n');
        }

        A += 0.04;
        B += 0.02;

        usleep(30000);
    }

    return 0;
}