3D graphics have become an important part of every aspect of design nowadays. From game development, to web development, to animations, to data representation, it can be found everywhere. Because of this, it would be great to have an graphics engine in python, an easy to work with language, to develop other projects with. All the code in this article and more can be found in my github repository: https://github.com/hnhaefliger.
In this article, we will be working using python3 and its standard library. To begin, we will create a new .py file and import tkinter, the gui library and math, for geometric functions such as sine and cosine:
The next step is to create our engine class and initialise the display window:
So lets walk through this code. We are creating a class called ‘Engine’, which will initialise with a height, a width, a distance, a scale, points and triangles. We will ignore the last two for now. The height and width represent the size of the window we create in pixels, the distance represents the distance between the viewer and the object and the scale is the size of the object we generate. We then create a new Tk window and give it the name “3D Graphics”. Finally we create a canvas in that window, on which we can draw our shapes.
If we look at a 3D coordinate, it has the shape of (X, Y, Z), however, we can only display a point in 2D space, that is why we need to write a function in our class to flatten the coordinates:
This code uses two formulas to generate x and y coordinates from 3D x,y,z coordinates using the distance and scale of the object.
Next, we write a function to draw a triangle between 3 points, this is the method generally used in 3D graphics as it enables us to link points with a single shape.
This code creates a triangle between three points on our canvas using the create_polygon method. Now we can draw our cube:
If we say that our self.points array contains a list of the coordinates of the cube’s vertices and the self.triangles array a list of points to link we can see that this code creates our 2D coordinates from our points and then links them with the triangle. Now we can test our program like below:
And we should get an output like this:
Which is our cube.
To summarise, we managed to create an engine which, from a set of 3D points creates a displayable model. In a future article, we will discuss how to play with different simple animations such as rotations on our cube.
If you check out my github repository, you will find sets of coordinates you can use to generate models like the ones below:
Since writing this article, I have made significant changes to my code, however, the core functionality is still the same.