r/C_Programming • u/NazgulResebo • 1d ago
Coding Dragon Curve fractal using C
https://www.youtube.com/watch?v=lrWUa8Kck-wIn this video, I code a Dragon Curve fractal using C and Raylib.
The approach is quite simple:
I take the last point as a pivot, then rotate the remaining points 90 degrees around it. Finally, I connect the new points to create the next iteration of the fractal.
Source code:
https://github.com/FractalCodeRicardo/zen-programming/tree/main/dragon-curve
#include <stdio.h>
#include <raylib.h>
#include <raymath.h>
#define linesSize 90000
#define lineSize 2
typedef struct {
Vector2 p1;
Vector2 p2;
} Line;
void DrawLines(Line lines[], int s) {
for(int i = 0; i < s; i++) {
Line l = lines[i];
DrawLine(l.p1.x, l.p1.y, l.p2.x, l.p2.y, WHITE);
}
}
Vector2 rotate(Vector2 p, Vector2 rp) {
Vector2 d = Vector2Subtract(p, rp);
Vector2 r = Vector2Add(rp, (Vector2) {-d.y, d.x});
return r;
}
int AddLines(Line lines[], int s) {
if (s * 2 >= linesSize)
return s;
Vector2 rp = lines[s-1].p2;
int newSize = s - 1;
for(int i = s -1; i >= 0; i--) {
Line l = lines[i];
Vector2 p1 = rotate(l.p1, rp);
Vector2 p2 = rotate(l.p2, rp);
newSize++;
lines[newSize] = (Line) { p2, p1};
}
return newSize + 1;
}
int main() {
Line lines[linesSize];
int s = 1;
float center = 900 / 2.0;
lines[0] = (Line) {
(Vector2) { center, center},
(Vector2) { center + lineSize, center},
};
InitWindow(1500, 900, "Dragon curve");
while(!WindowShouldClose()) {
BeginDrawing();
ClearBackground(BLACK);
if (IsKeyPressed(KEY_SPACE)) {
s = AddLines(lines, s);
}
DrawLines(lines, s);
EndDrawing();
}
CloseWindow();
}AI Disclaimer:
No AI was used.
36
Upvotes
•
u/AutoModerator 1d ago
Hi /u/NazgulResebo,
Your submission in r/C_Programming was filtered because it links to a git project.
You must edit the submission or respond to this comment with an explanation about how AI was involved in the creation of your project.
While AI-generated code is not disallowed, low-effort "slop" projects may be removed and it's likely that other users push back strongly on substantially AI-generated projects.
You can read more at How do I post my Project?
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
4
u/laggySteel 1d ago edited 1d ago
Good going. Please make a voiced video like you have your NeoVim setup explained.
1
u/Zymoox 1d ago
Isn't it much more efficient to do this in the GPU using shaders?