How to make a 3D projection in Python | Rendering a cube in 2D! (No OpenGL)
HTML-код
- Опубликовано: 18 мар 2021
- This is a tutorial that shows how to make a 3D projection using python and pygame.
This is a way of projecting 3D dimensions to 2D.
In this video we will project a cube :O
If I said something wrong, forgive me, because english is not my native language :P
#python #computergraphics #pygame #3D #gamedev
---
Source code: github.com/Magoninho/3D-proje...
---
Songs used:
We Are The Champions
Queen
Lのテーマ
タニウチヒデキ
Low of Solipsism Ⅱ
平野義久
Semblance of Dualism
平野義久 Наука
Perfect in its simplicity. Thank you for this video, and for showing the way how to do matrix multiplication in Python (still not the language of my preference however) ! After looking for some theory, this was the perfect "next-step"-hit !
here is a fun way to avoid copy pasting in the beginning :)
points = []
for x in (-1, 1):
for y in (-1, 1):
for z in (-1, 1):
points.append(np.matrix([x, y, z]))
omg bless you
WIDTH = 100
HEIGHT = 100
LENGTH = 100
points = []
for x in range(-1, WIDTH, WIDTH):
for y in range(-1, WIDTH, WIDTH):
for z in range(-1, WIDTH, WIDTH):
points.append(np.matrix([[x], [y], [z]]))
*Matrices so you dont have to copy, even tho I made mine a lil different.*
*_Projection & Rotation_*
projectionMatrix = np.matrix([
[1, 0, 0],
[0, 1, 0],
])
def Rx(angle):
return np.matrix([
[1, 0, 0],
[0, math.cos(angle), -math.sin(angle)],
[0, math.sin(angle), math.cos(angle)]
])
def Ry(angle):
return np.matrix([
[math.cos(angle), 0, math.sin(angle)],
[0, 1, 0],
[-math.sin(angle), 0, math.cos(angle)]
])
def Rz(angle):
return np.matrix([
[math.cos(angle), -math.sin(angle), 0],
[math.sin(angle), math.cos(angle), 0],
[0, 0, 1]
])
*[!] --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- [!]*
*You dont have to use np.dot(), you can use the @, matrix multiplication operator.*
*Example: Matrix1 @ Matrix2*
*[!] --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- [!]*
This is the only tutorial I've seen so far that animated the matrix multiplication. That makes so much more sense now.
I love how you got L's theme playing in the background lol, great tutorial
Nice Video! Learned a lot while being entertained!
freaking awesome dude!
uhhhhhhhhhhhhhhhhh mine generates a plane????? task failed succesfully
this is art, congratulations!
I just cant find the right words to explain how i am appreciate this. Man i spent weeks to understand 3d projection and because my math background is weak i just disappointed and stopped to try. But God finally sent you to me :) Thanks man, this is awesome explanation for aliens to 3d(like me). Also thanks again for funny presentation.
this is underated
Awesome tutorial!
amazing video! learned a lot from it
De aquí va a salir mi tesis gracias ❤
amazing! its so easy! thx!
I LOVE YOU!!! 😍
amazing
thank you for video
Great to code along simple to follow as well as learned a few things... and i got a spinning cube on my computer 😎
Hi! Your video is really helpfull, ty!!!
I like that death note theme song in the background, makes it feel so dramatic.
good video.teaches how to apply texture and apply a Z position and camera position and camera rotation
Thanks a lot, this was perfect for me as i could understand it and change it to my own needs.
I used it to create a Hexagon viewed from an x-axis angle.
Now I want to try making a game-grid for pygame from this.
Although, I guess I will run into a problem. I am not sure what the right words are, but i guess i need orthographic perspective to get rid of the depth skewing? If anyone can help me with this, leave a comment pls :) Meanwhile I will try to figure it out myself.
@@vinnn8694 im a bit late but orthographic projection is a completely different thing and the whole purpose of using perspective projection is to see depth and majority of games use it. orthographic projection is mainly used for things like engineering where they dont want this depth.
man started this video like the monogatari series
Wah! Your videos are too good for 385 subscribers. Thanks lot for the video tho.
Nice use of the deathnote ost
Thank for sharing
This is godly
Great tutorial!
My piece of mind on the "bracket" issue". In order to multiply matrices, number of columns of matrix on the left needs to be equal to the number of rows of the matrix on the right.
The projection matrix (P) is 3x3 matrix.
M1 = [x, y, z] is 1x3 matrix.
M2 = [[x]],[y],[z]] is 3x1 matrix. (It doesn't look so intuitive when there's only one element per row)
P x M1 -> not possible
P x M2 -> possible
M2 = (M1) transposed
So, even though you solved problem using reshape, I think that more accurate way is to use matrix transposition here. I've yet to start learning numpy, but i'm sure there is a function numpy.transpose() or something along those lines.
Unexpected death note. Very unexpected.
The "set caption" piece killed me
i loved it!!! show to everybodyhow to make an first person!!! it will be awolsome.
thank you bro
Thank you
Thanks!!!!
Oh man... you got the Death note music in the background
to solve the issue with matrix multiplication you have to match up the shapes in terms of mn * nm. Easiest to do this here is to transpose the point vertex with .T
the into says it all
This is insine ! 👍
You bloody bastard 😭 thank you bro it's for my project 😭 😭 😭 😭 😭 😭 😭 😭 😭
bro entered the matrix 💀
You can do this on pydroid it works and i verified it (pydroid has diffrent interpretations of window you also gotta screen = display.set_mode((0,0))
Man that's what I needed, an actual tutorial on drawing points and lines using a not so bloated library in a good language (fck java) in structured programming (fck classes), not to simple or starting from the ground and not too complex or starting with OpenGL (vulkan gives me nightmares)...
Could you map textures on the cube?
it's cute
any idea how i can connect points to a 4d square using the p in range
🙏
That intro makes me scared already
I knew this was a bad idea.
Good job bro, How to a make a frustum projection?
How do I make it so that the line on the front appears over the line on the back?
i dont know if its my additions but i tested the code you uploaded and edited the cube to have a new point at 0,0,-1. i added the ability to control the rotation and scale. ive found that if when you start the program and rotate it in the x axis the point will be on the closest side of the cube to the camera while if you rotate it in the y axis it will be on the far side of the cube
edit: sometimes both axis give the same result when starting the program and sometimes its the opposite
Nvm i think its just an optical illusion
hi sir it is really good tutorial, can you tell me that how can we use arroy of other OBJ and then render that. Please reply me soon.
incredible!! btw where did you get this cursor
it's the default dmz white from ubuntu
@@pythonista_333
Arigato
Hi ! Great video, worked like a charm :) But I have a question : why is the order of the points so important ?
Because the order matters for multiplication of matrices (in this case are (x , y , z) cordinates
@@atharvsharma2539 Yes, you're right about multiplying the points with the rotation/projection matrixes, but what about the order of the points relative to one another ? He says the order in which the points are defined matters,at 9:00, but that, I don't get why
@@tonin8499 because the order decides what dots get a line drawn in between then
"how to make a 3d projection": shows orthographic projection
how do u get that cursor?
is there a way to fill every face of the cube?
Wow and try make pyramid in the next video
Just use this
points = []
# all the cube vertices
points.append(np.matrix([0, -1, 0]))
points.append(np.matrix([0, -1, 0]))
points.append(np.matrix([1, 1, 1]))
points.append(np.matrix([-1, 1, 1]))
points.append(np.matrix([0, -1, 0]))
points.append(np.matrix([0, -1, 0]))
points.append(np.matrix([1, 1, -1]))
points.append(np.matrix([-1, 1, -1]))
can u make a texture tutorial?
Hi thanks for the video can i snap mouse to any point and get its x, y and z coordinates?
I'm sure you can get the X and Y, but I'm not sure for the Z axis. I've used orthogonal projection, perhaps in perspective projection you can get the Z axis somehow
maybe get the x and y coordinates then do every thing you do to place dots in reverse
I wrote in javascript and the object shrinks in size. :(
when will there be new videos?(
the only thing I really didn't like was the music at minute 6:10. It was like The Omen's soundtrack.
hi I got this error with the code
Traceback (most recent call last):
File "C:/Users/Jemelah/AppData/Local/Programs/Python/Python310/cube1.py", line 1, in
import pygame
File "C:\Users/Jemelah/AppData/Local/Programs/Python/Python310\pygame.py", line 10, in
pygame.display.set_caption("3D projection in pygame!")
AttributeError: partially initialized module 'pygame' has no attribute 'display' (most likely due to a circular import)
I am kira
thee shape problem you were having on which you spent a lot of time researching it could be fixed by just adding the [0,0,0] at the end of the projection matrix. That's how I fixed it. And by the way the projection matrix is useless
Why subtitles are blocked????!!!!?1!!!!!!111!/1?!/!?!!?
This was a really fun video and I enjoyed most of it, my only problem was that your approach on teaching wasn't what I was expecting, meaning you didn't explain everything. So a complete beginner or someone who had little to no knowledge of matrix or perspective would have been completely lost.
this video requires a basic understanding of linear algebra
Watch a video by coding train on projection 3d he explains it.
sorry about that ;(
check out the coding train's video, im sure he can explain it better
What type projection is this?
Ortogonal or what?
it's an orthographic projection
Is there anyway I can add textures to it?
well, that's a good question
You'd have to draw lines between the main lines
@@brainloading5543 what about points?
@@itzmeB2 wdym?
@@brainloading5543 can't u like get a points 3d position with the method in this video? Then u can just assign a color to that point and have textures
i am comverting the code to work with geometry dash triggers XD
Can you add sides on this cube?
you can use the pygame.draw.polygon to draw the sides. The problem is that, in this kind of projection, there is no sense of depth. This is something that I need to figure out. Probably One Lone Coder explains it
@@pythonista_333 thank you ^^
@@pythonista_333
x*=z/math.tan(fov[0]/2)
y*=z/math.tan(fov[1]/2)
z=(z-ncp)/(fcp-ncp)*2-1)
perspective projection into unit cube (if point in veiw it will be inside -1,-1,-1 to 1,1,1. screen x and y are x and y of new point)
You may have already found this but I'll share it anyway.
Do I hear death note baground
does anyone know, or has a link on how to draw the faces ? thx :)
I think it's possible if you connect the points with polygons instead of lines. Then, you can set the color you want for the polygons. I don't know Pygame very well but I think there's a function to draw polygons.
@@jeas29 thank you, yes you are right, pygame.draw.poly(surface,color,position_list). But my main concern is that, by doing so, they are going to overlap. I would like each face to be drawn only if it's on the front...
@@tonin8499 Hey I have the exact same problem, did you find a solution in the meantime?
@@timdoring8571 oh hi haha, yes I did, you have two solutions (at least) : the painter's algorithm or per pixel rendering. Per pixel might be a bit overkill in this case, I'd suggest starting with painter's algorithm, it needs way less computing power. You basically have all your faces, you sort them by distance to the camera (you can average a point in the middle of the face for that), then draw them furthest to closest. But it's an approximation, you often get overlapping problems (that you won't have with per pixel). You also will get overdraw (drawing faces in top of each other), so the problem I pointed out previously about not wanting to draw hidden faces isn't solved. Still a good solution though. You can also choose to automatically subdivide large faces into several smaller faces to limit the size of artefacts.
en.m.wikipedia.org/wiki/Painter%27s_algorithm
I'd be glad to help you further if needed :), good luck, let me know if you managed to do what you wanted
@@tonin8499 thanks for the quick reply! I'll get on it now :)
Someone can help me to understood how he create a cube using arrays of [1, 0, -1]? I mean, Can I do that with all the geomety shapes? Any article or concepts to read?
yes, 1,0,-1 are the coordinates of a point and so every point has 3 different values. it doesnt which shape basically. minecraft is good example how these coordinates work :)
[1,1,1] = [X,Y,Z] then the array is for each coordinate he makes a dot. After he just connects the dots and its a cube
Hi I make games with pygame. I want to meet more people who fiddles with pygame and game developement. Is there any group or hub you can suggest me please?
If someone find it hard, try watching linear algebra series. In that way u can create this without even watching this video, like I did
nice, idk linear algebra, but i think i learned something with this project. If I go to university someday, I will study linear algebra for sure :)
@@pythonista_333 all the best
Wat about projection in perspective ? %(((((
Why are you using python for this?
Ugh not again I made Minecraft i was trying to make a cube
Nice vid but WHY ON HELL DID U TEACH US ON LIGHT MODE
DO U WANT TO BLIND US!?!?
Why mixing with pygame !
Just use numpy , your array multiplication (projection) and matplotlib to draw the figure.
Keep it simple and stupid !
You're right! But pygame would give more views lol
music annoying
Thx
Good job, now enter Z depth. Filling of polygons by scaline, and shading. There we will congratulate you, newbie
I can't stand stammering and stuttering speech, it drives me crazy.