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
    平野義久
  • НаукаНаука

Комментарии • 123

  • @sudolea
    @sudolea Год назад +10

    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 !

  • @hellishbrogaming3643
    @hellishbrogaming3643 2 года назад +39

    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]))

    • @nzuckman
      @nzuckman 2 года назад +1

      omg bless you

    • @remot1
      @remot1 Год назад +2

      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*
      *[!] --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- [!]*

  • @justinlua4848
    @justinlua4848 2 года назад +4

    This is the only tutorial I've seen so far that animated the matrix multiplication. That makes so much more sense now.

  • @brickolo_
    @brickolo_ Год назад +1

    I love how you got L's theme playing in the background lol, great tutorial

  • @jonasstrabel
    @jonasstrabel 2 года назад +2

    Nice Video! Learned a lot while being entertained!

  • @nio8739
    @nio8739 3 года назад +5

    freaking awesome dude!

  • @halfsine
    @halfsine Год назад +16

    uhhhhhhhhhhhhhhhhh mine generates a plane????? task failed succesfully

  • @xixixitsme
    @xixixitsme Год назад +1

    this is art, congratulations!

  • @cgiscript415
    @cgiscript415 Год назад +2

    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.

  • @atharvsharma2539
    @atharvsharma2539 3 года назад +10

    this is underated

  • @curcumin417
    @curcumin417 3 месяца назад

    Awesome tutorial!

  • @tsukigva6130
    @tsukigva6130 3 года назад +8

    amazing video! learned a lot from it

  • @maynermoran
    @maynermoran 9 месяцев назад

    De aquí va a salir mi tesis gracias ❤

  • @user-zq9vq7nl8b
    @user-zq9vq7nl8b 3 дня назад

    amazing! its so easy! thx!

  • @0x49
    @0x49 3 года назад +4

    I LOVE YOU!!! 😍

  • @user-ur1ee5qx5x
    @user-ur1ee5qx5x 3 года назад +2

    amazing
    thank you for video

  • @hezziacGames
    @hezziacGames 7 месяцев назад

    Great to code along simple to follow as well as learned a few things... and i got a spinning cube on my computer 😎

  • @user-so1qk2sy3h
    @user-so1qk2sy3h Год назад

    Hi! Your video is really helpfull, ty!!!

  • @Dileuven
    @Dileuven Год назад

    I like that death note theme song in the background, makes it feel so dramatic.

  • @kaklikcontapessoal129
    @kaklikcontapessoal129 2 года назад +13

    good video.teaches how to apply texture and apply a Z position and camera position and camera rotation

  • @vinnn8694
    @vinnn8694 Год назад +1

    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.

    • @vinnn8694
      @vinnn8694 Год назад

      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.

    • @Sycro11
      @Sycro11 2 месяца назад

      @@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.

  • @RenderingUser
    @RenderingUser Год назад +1

    man started this video like the monogatari series

  • @9Lights
    @9Lights Год назад

    Wah! Your videos are too good for 385 subscribers. Thanks lot for the video tho.

  • @_doofiis7420
    @_doofiis7420 2 года назад

    Nice use of the deathnote ost

  • @elmondo.
    @elmondo. 2 года назад

    Thank for sharing

  • @commissarofpublicsafety
    @commissarofpublicsafety Год назад

    This is godly

  • @nikolastamenkovic7069
    @nikolastamenkovic7069 Год назад +3

    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.

  • @peeper2070
    @peeper2070 8 месяцев назад +1

    Unexpected death note. Very unexpected.

  • @cock_sauce8336
    @cock_sauce8336 2 года назад

    The "set caption" piece killed me

  • @theguy2887
    @theguy2887 2 года назад +1

    i loved it!!! show to everybodyhow to make an first person!!! it will be awolsome.

  • @ejskshrvhshsbdbdbddhdh3yej11
    @ejskshrvhshsbdbdbddhdh3yej11 2 года назад

    thank you bro

  • @westonkomar3767
    @westonkomar3767 2 года назад

    Thank you

  • @01bit
    @01bit Год назад

    Thanks!!!!

  • @tashadurrahman
    @tashadurrahman Год назад

    Oh man... you got the Death note music in the background

  • @SaferSephy
    @SaferSephy 11 месяцев назад

    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

  • @hasninabedali9149
    @hasninabedali9149 Год назад

    the into says it all

  • @havitjustimagine134
    @havitjustimagine134 3 года назад +2

    This is insine ! 👍

  • @tonytony-hz1cg
    @tonytony-hz1cg 3 года назад

    You bloody bastard 😭 thank you bro it's for my project 😭 😭 😭 😭 😭 😭 😭 😭 😭

  • @harigopaladamus9481
    @harigopaladamus9481 4 месяца назад

    bro entered the matrix 💀

  • @64-bit63
    @64-bit63 2 года назад +1

    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))

  • @kevinquintana3085
    @kevinquintana3085 Год назад

    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)...

  • @linuslim3841
    @linuslim3841 Год назад +7

    Could you map textures on the cube?

  • @tiktoks4579
    @tiktoks4579 11 месяцев назад

    it's cute

  • @renejr2006
    @renejr2006 8 месяцев назад

    any idea how i can connect points to a 4d square using the p in range

  • @devfromthefuture506
    @devfromthefuture506 3 года назад +2

    🙏

  • @cheeseburgerinvr
    @cheeseburgerinvr 5 месяцев назад

    That intro makes me scared already
    I knew this was a bad idea.

  • @programm_mister9692
    @programm_mister9692 6 месяцев назад +1

    Good job bro, How to a make a frustum projection?

  • @ziyadcodes
    @ziyadcodes 2 года назад +1

    How do I make it so that the line on the front appears over the line on the back?

  • @ravethefox
    @ravethefox 2 года назад

    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

    • @ravethefox
      @ravethefox 2 года назад +1

      Nvm i think its just an optical illusion

  • @ranveerdev4514
    @ranveerdev4514 10 месяцев назад

    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.

  • @eagle_2712
    @eagle_2712 3 года назад +4

    incredible!! btw where did you get this cursor

    • @pythonista_333
      @pythonista_333  2 года назад +1

      it's the default dmz white from ubuntu

    • @ajarivas72
      @ajarivas72 2 месяца назад

      @@pythonista_333
      Arigato

  • @tonin8499
    @tonin8499 2 года назад

    Hi ! Great video, worked like a charm :) But I have a question : why is the order of the points so important ?

    • @atharvsharma2539
      @atharvsharma2539 2 года назад

      Because the order matters for multiplication of matrices (in this case are (x , y , z) cordinates

    • @tonin8499
      @tonin8499 2 года назад

      @@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

    • @dhpshow9277
      @dhpshow9277 Год назад +4

      @@tonin8499 because the order decides what dots get a line drawn in between then

  • @oracuda
    @oracuda Год назад +1

    "how to make a 3d projection": shows orthographic projection

  • @dynast7550
    @dynast7550 Год назад

    how do u get that cursor?

  • @person10103
    @person10103 2 месяца назад

    is there a way to fill every face of the cube?

  • @spozniony5499
    @spozniony5499 3 года назад

    Wow and try make pyramid in the next video

    • @dhpshow9277
      @dhpshow9277 Год назад

      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]))

  • @prod_guzz
    @prod_guzz Год назад

    can u make a texture tutorial?

  • @mohmedahmed6696
    @mohmedahmed6696 2 года назад

    Hi thanks for the video can i snap mouse to any point and get its x, y and z coordinates?

    • @pythonista_333
      @pythonista_333  2 года назад +1

      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

    • @dhpshow9277
      @dhpshow9277 Год назад +1

      maybe get the x and y coordinates then do every thing you do to place dots in reverse

  • @weversonch
    @weversonch 2 года назад

    I wrote in javascript and the object shrinks in size. :(

  • @SquirtingBlood
    @SquirtingBlood 5 месяцев назад

    when will there be new videos?(

  • @erickcampos6651
    @erickcampos6651 2 года назад

    the only thing I really didn't like was the music at minute 6:10. It was like The Omen's soundtrack.

  • @simplyjemelah8276
    @simplyjemelah8276 Год назад

    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)

  • @musicandlength
    @musicandlength Год назад +1

    I am kira

  • @burhanyasir4614
    @burhanyasir4614 8 месяцев назад

    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

  • @ohnocoder
    @ohnocoder 2 года назад

    Why subtitles are blocked????!!!!?1!!!!!!111!/1?!/!?!!?

  • @MarlandoCrosdale
    @MarlandoCrosdale 2 года назад +3

    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.

    • @1alexandermichael
      @1alexandermichael 2 года назад

      this video requires a basic understanding of linear algebra

    • @yongamamkolokotho9904
      @yongamamkolokotho9904 2 года назад

      Watch a video by coding train on projection 3d he explains it.

    • @pythonista_333
      @pythonista_333  2 года назад +1

      sorry about that ;(
      check out the coding train's video, im sure he can explain it better

  • @ddoshostingeryeah9185
    @ddoshostingeryeah9185 3 года назад

    What type projection is this?
    Ortogonal or what?

  • @itzmeB2
    @itzmeB2 3 года назад +4

    Is there anyway I can add textures to it?

    • @pythonista_333
      @pythonista_333  3 года назад +3

      well, that's a good question

    • @brainloading5543
      @brainloading5543 3 года назад +1

      You'd have to draw lines between the main lines

    • @itzmeB2
      @itzmeB2 3 года назад +1

      @@brainloading5543 what about points?

    • @brainloading5543
      @brainloading5543 3 года назад +1

      @@itzmeB2 wdym?

    • @itzmeB2
      @itzmeB2 3 года назад +1

      @@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

  • @srblender5327
    @srblender5327 2 месяца назад

    i am comverting the code to work with geometry dash triggers XD

  • @joshuac5233
    @joshuac5233 3 года назад +1

    Can you add sides on this cube?

    • @pythonista_333
      @pythonista_333  3 года назад +2

      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

    • @joshuac5233
      @joshuac5233 3 года назад

      @@pythonista_333 thank you ^^

    • @charliegregg5691
      @charliegregg5691 2 года назад +1

      @@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.

  • @chiranthchiranthmb2996
    @chiranthchiranthmb2996 2 года назад

    Do I hear death note baground

  • @tonin8499
    @tonin8499 2 года назад +1

    does anyone know, or has a link on how to draw the faces ? thx :)

    • @jeas29
      @jeas29 2 года назад +1

      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.

    • @tonin8499
      @tonin8499 2 года назад

      @@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...

    • @timdoring8571
      @timdoring8571 11 месяцев назад

      @@tonin8499 Hey I have the exact same problem, did you find a solution in the meantime?

    • @tonin8499
      @tonin8499 11 месяцев назад +1

      @@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

    • @timdoring8571
      @timdoring8571 11 месяцев назад +1

      @@tonin8499 thanks for the quick reply! I'll get on it now :)

  • @carlosazuaje8381
    @carlosazuaje8381 2 года назад

    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?

    • @fumano2679
      @fumano2679 2 года назад +1

      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 :)

    • @dhpshow9277
      @dhpshow9277 Год назад

      [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

  • @sandiguha
    @sandiguha Год назад

    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?

  • @samyakmarathe3434
    @samyakmarathe3434 2 года назад

    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

    • @pythonista_333
      @pythonista_333  2 года назад +2

      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 :)

    • @samyakmarathe3434
      @samyakmarathe3434 2 года назад +1

      @@pythonista_333 all the best

  • @sergiopuccini
    @sergiopuccini Год назад

    Wat about projection in perspective ? %(((((

  • @coolmanthecool603
    @coolmanthecool603 4 месяца назад

    Why are you using python for this?

  • @Arium_games_YT
    @Arium_games_YT 5 месяцев назад

    Ugh not again I made Minecraft i was trying to make a cube

  • @legendrags
    @legendrags Год назад

    Nice vid but WHY ON HELL DID U TEACH US ON LIGHT MODE
    DO U WANT TO BLIND US!?!?

  • @WahranRai
    @WahranRai Месяц назад

    Why mixing with pygame !
    Just use numpy , your array multiplication (projection) and matplotlib to draw the figure.
    Keep it simple and stupid !

    • @pythonista_333
      @pythonista_333  29 дней назад

      You're right! But pygame would give more views lol

  • @brycepersello5331
    @brycepersello5331 2 года назад

    music annoying

  • @cyklop1977
    @cyklop1977 6 дней назад

    Thx

  • @bueno_excelente
    @bueno_excelente Год назад

    Good job, now enter Z depth. Filling of polygons by scaline, and shading. There we will congratulate you, newbie

  • @jasonboyd782
    @jasonboyd782 Год назад

    I can't stand stammering and stuttering speech, it drives me crazy.