free web page hit counter
🛡️
Copyright Notice: This video is officially sourced and embedded from YouTube. For all copyright inquiries, reports, or removals, please contact YouTube's legal team here.
Daniel Hirsch

Daniel Hirsch

0 subscribers

⏱ 👁 508,638 views

Coding Ray Tracing in C

Video Overview & Insights

A first attempt coding raytracing in C. And it actually worked. I am surprised of the little math we needed. Just some basic line drawing (which I struggled with more than I'd like to admit). But then it worked out!

“

https://hirschdaniel.gumroad.com/l/c-programming
Guys, I did it - I created a C programming video course!!

It’s called No-nonsense C Programming. It teaches you exactly how to code C like I do, with a clear, structured learning path.

— @HirschDaniel

✘ My No-Nonsense C Programming Course: https://hirschdaniel.gumroad.com/l/c-programming

✘ Get my full dev environment and color scheme: https://hirschdaniel.gumroad.com/l/daniel-terminal

“

53:33 you are wondering how to calculate m from the angle and the answer is just there: m=tan(angle)

— @JulesvanPhil

✘ Get Proton VPN to stay anonymous online: https://go.getproton.me/SH27Q

✘ Get ALL my YouTube projects' source code: https://hirschdaniel.gumroad.com/l/sourcecode

“

Sorry, I'm not entirely through the whole video, but I can't help but imagine the rays, instead of originating from the center of the circle, to originate from many points around the radius/perimeter of the circle, and each point shoots a fan of rays in a 180 deg. spread, from tangent to tangent and in between (perhaps 6 rays from each point), and this way, you get a much more realistic light since the outer edge of the light circle is where the shadow lines should point at, not the center of the light circle. SUPER video. Thanks very much!

— @TroyNiemeier

✘ Exclusive Content on Patreon (& Get all Projects as Source Code):

https://www.patreon.com/HirschDaniel

“

raw doggin C in VIM... based

— @Greg-g1f4h

✘ Learn to Code:

https://app.codecrafters.io/join?via=danieldeer

“

Hello here is how i dit it :

#include <stdio.h>
#include <math.h>
#include <SDL2/SDL.h>


#define WIDTH 1200
#define HEIGHT 900
#define WHITE 0xffffff
#define BLACK 0x000000
#define RAY_COLOR 0xdbb407


// ------------------------ STRUCTS -------------------------------


typedef struct Circle
{
double x;
double y;
double radius;
} Circle;


typedef struct Ray
{
double ox, oy;
double dx, dy;
} Ray;


// ------------------------ METHODS -------------------------------

Circle* initializeCircle(double x, double y, double radius)
{

Circle* circle1 = malloc(sizeof(Circle));

circle1->x=x;
circle1->y=y;
circle1->radius=radius;

return circle1;
}

void drawCircle(SDL_Surface* surface, Circle* circle, int color)
{
for (int y = -circle->radius; y <= circle->radius; y++)
{
int x = (int)sqrt(circle->radius * circle->radius - y * y);

SDL_Rect ligne = {circle->x - x, circle->y + y, 2*x, 1};
SDL_FillRect(surface, &ligne, color);
}
}

double intersectCircle(Ray* ray, Circle* circle)
{
double fx = ray->ox - circle->x;
double fy = ray->oy - circle->y;

double a = ray->dx * ray->dx + ray->dy * ray->dy;
double b = 2 * (fx * ray->dx + fy * ray->dy);
double c = fx*fx + fy*fy - circle->radius * circle->radius;

double discriminant = b*b - 4*a*c;

if (discriminant < 0)
return -1;

return (-b - sqrt(discriminant)) / (2*a);
}

// ------------------------ MAIN -------------------------------

int main(void)
{
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window = SDL_CreateWindow("Raytracing", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WIDTH, HEIGHT, 0);
SDL_Surface* surface = SDL_GetWindowSurface(window);

Circle* circlePlanet = initializeCircle(800, 430, 100);
Circle* circleSol = initializeCircle(300, 550, 50);
SDL_Rect eraser = {0, 0, WIDTH, HEIGHT};

int simulation_running = 1;
SDL_Event event;
while (simulation_running)
{
while(SDL_PollEvent(&event))
{
if(event.type == SDL_QUIT)
{
simulation_running = 0;
}
if(event.type == SDL_MOUSEMOTION && event.motion.state != 0)
{
circleSol->x = event.motion.x;
circleSol->y = event.motion.y;
}
}
SDL_FillRect(surface, &eraser, BLACK);


// ------------- RAY DRAWING ---------------

for (int py = 0; py < HEIGHT; py++)
{
for (int px = 0; px < WIDTH; px++)
{
Ray ray = {px, py, circleSol->x - px, circleSol->y - py};
double len = sqrt(ray.dx*ray.dx + ray.dy*ray.dy);
ray.dx /= len;
ray.dy /= len;

double t = intersectCircle(&ray, circlePlanet);

Uint32 color;
if (t > 0 && t < len)
color = BLACK;
else
color = RAY_COLOR;

SDL_Rect pixel = {px, py, 1, 1};
SDL_FillRect(surface, &pixel, color);
}
}


drawCircle(surface, circleSol, WHITE);
drawCircle(surface, circlePlanet, WHITE);


SDL_UpdateWindowSurface(window);
SDL_Delay(10);

}

free(circlePlanet);
free(circleSol);

}

— @nathanrichard5361

A BIG thanks goes out to my "Dev Supporter"-level Patreon nr.bln.

“

you know when a guy isnt being that honest when he puts sin and cos the wrong way round on purpose.

— @magnuswootton6181

More User Perspectives

@

hmmm
very good video

@AadityaChauhan-g5n
@

proxy chain code and kernel hook?

@thehighestme
@

Great video Great explanation Great coder

@jayrathore5964
@

for the angle problem, my approach would be looping over x and y individually, given the length of a ray is a combination of how far it goes on x and on y, which is constant, you can just loop over x, and each iteration increase the x amount and decrease the y amount of that angle, since their sum accounts into 1 at all times, or at least their absolute [ ] value does

@CybernetonPL
@

Nice

@ProgrammingHeadache
@

Who hurt you?

@evamariarabinalnogueras3306
@

it is imazing it s give me absolute motivation to do coding

@saidbenyaich03
@

Cool video. I was able to follow along and duplicate what you were doing!.
FYI. . .
I got it to look pretty cool with 1.35 instead of 5

double blur_size = 1.35 * RAY_THICKNESS;

@donaldrussell-tx3873
@

Bro, I love you and your videos! Can you give me some advice?
Right now I’m studying from Stephen Prata’s book and doing the exercises, but I really want to start writing something cool already. Still, I know I should finish the book first.

@atatutititaya
@

1:27:36 Avg guy's reaction after coding out something in Pure Shit C

@CodeWithAmash
@

Couldn't stop laughing when you said "you get my point" as you just fumbled with the most common mistake on mspaint

@randokaratajev2617
@

bounce time

@Lunaisded
@

I think the blur issue is caused by the rendering order: you're drawing a blur, then a ray, then another blur, and so on. This means the blur from newer rays is being drawn on top of previous rays. I haven't tested it though, so it's just a theory.

@Zolenfik
@

what is the name of this theme ? it's so smooth with almost white letter

@cobbminh3811
@

i appreciate for your work man

@mezoxy
@

1:15:50 🤣🤣🤣
Don't be so hard on yourself. You're the absolute best

@uCodes880
@

GGs
This man in an inspiration.


I was yelling sin and cosine to resolve the y and x value from a given angle 🤣

The best thing is you figured it out yourself, while I know it from classes I took a while ago

@uCodes880
@

For me with an IQ of 157 this is easy. I came up with an algorithm while watching him fumble around: Create an imaginary isosceles triangle (which is actually the 2D projection of a 3D cone onto the xy plane) with the right angle offset (proportionally given the similarity in shape between the triangles) to the left of the light source (since all points in the light source will emit light, it is not good enough to just use x and y for the origin of the light source). You then scale the size of the object circle onto the backdrop (here the right wall) based on the same projection relationship mentioned above and erase all the "light pixels" from that area. All other pixels should be illuminated.

@SwedishNiceGuy
@

1:11:57 i'm literally shouting sin and cos at my screen !

@Alex-cs7bd
@

Hey dude! Where are you writing the codes? I never saw this environment. But i want this. Plz help

@blackguy-o3q
@

I would love to see this kinda video in streaming format

@LaSaloVat
@

I think you can fill screen with light except the target ball and use some method to introduce the shadow instead. That would solve the problem of divergent rays and the gaps that form between them. But thats not raytracing though...

@vibin.v
@

36:15 could've just set it to 0 and it would've worked.
and there's an sdl function that clears the screen with the last selected draw color but i guess it just draws a rectangle under the hood.

@SwirX
@

Amazingly entertaining video, somehow its more fun watching other people do projects since you don't get as frustrated and can skip forwards lol

@rogumann838
@

привет подскажи свое IDE, и операционную систему в чем работаешь? и ты используешь только язык С или еще можно на С++????

@Kogot7779
@

how to use vim on windows?

@Someone-j1b5s
@

Finally ray tracing that I can run on my PC

@CodeAndChill-Vids
@

Drawing the ray as a 3x3 rect at X, Y and drawing the 5x5 blur at the same X and Y.. that's why. Add an offset.. Nice video

@QcQc-m
@

Daniel which is your processor!? Because I was struggling with what looks like a infinite looping, but after 3h I discover that my PC can handle with more than 20 rays!!

@gabrielvinicius4563
@

What do you think about drawing the rays in the following way: for loop 1 for determining the angle for the ray, for loop 2 for determining when the ray hits one of the walls/corners of the window (and a separate method for hitting the other circle ofc). Then, you draw one pixel per one iteration of for loop 2 until you hit a wall/corner for both directions of the ray measured from the mid point of the movable circle, so you draw in a "positive" direction (meaning x += some increment and y += some increment) from the mid point of the movable circle and in a "negative" direction (meaning x -= some decrement and y -= some decrement). You eventually hit a wall/corner for both directions that you need to account for with a conditional to break the loop and then you start over again but with the new angle for a new ray(line) that is created with another increment from loop 1?

@adriankovacs4133
@

This is crazyyy

@sanketff21
@

i don't know why i'm here i'm studying psychology but these are super fun to watch

@nathaliehernandez2683
@

When the circle is inside the shadow_circle, the rays are gone. It can be solved by using circle.x+circle.r*cos(angle), circle.y+circle.r*sin(angle) in generate_rays.
This happened because rays come out from the center of the circle instead of the surface of the circle.

@TheLucky368368
@

this is rasterization
for ray tracing you would march a ray from every pixel on screen toward the light source and choose which color to draw the starting pixel based on which object the ray encountered first

@IXSigmaXI
@

ts raytracing pmo 💔😭 panzoid intro ahh raytracing

@Halo2Veteran
@

Me: struggling to learn C++
People: Coding Ray Tracing in C

@SirFlankBoring
@

good video. But why this editor ? I always use JB IDEs

@quantum-t
@

you're greaaaatttt dude

@MennaJaheen
@

try that in 3d

@AtulTripathi-s1f
@

Technically ray tracing(X) ray casting(O)

@bhluschrean
@

is it just me or pattern of pixels of ray tracing is somewhat similar to lines of magnetic field?you can see it blinking when the source of light is moving.

@Kuro31803
@

bro took 30mins to figure out sine. ouch.

@Blacksoul444
@

I'm relatively new to programming, but it's already a great hobby. It was interesting to watch, even though I use C++ myself, not C. But we're practically related programming-wise. Instead of Vim, I use VS Code. I wanted something more beginner-friendly and not to have to struggle with the editor. I also looked at SDL, but then decided on Raylib. The pure coding is exactly what I'm looking for. And I like it when someone shows the entire process. You often struggle with programming, and it's interesting to see how other people solve problems. And no one should be ashamed of getting stuck sometimes. It's just part of the process, and I know what it's like to get stuck on a problem for hours.

@RealTanne
@

Excellent content! But, why suffer with vim? We are in 2025

@marcoslatchuk8192