USING PYTHON PROGRAMMING IN COMPUTER GRAPHICS
Shoykulov Sh.K.
Senior Lecturer, department of Applied Mathematics, faculty of Computer sciences, Karshi State
university, Karshi, Republic of Uzbekistan https://doi.org/10.5281/zenodo.13926022
Abstract. This article discusses using Python programming in computer graphics.
Keywords: data science, Python programming, computer graphics, machine learning, PyGame, 3D modeling, animation programming, visualization, artificial intelligence, high-level programming language, simulation, Web development, OpenGL, virtual reality, visual effects, object-oriented programming, graphic processing, game development, data analysis, algorithm.
Introduction. A programming language or computer language is used to develop programs, scripts, or other sets of instructions for computers. The growing demand for programming languages makes Python one of the required programming languages. Python is an extremely popular and most in-demand programming language across the globe. Python has applications in the field of data science or big data. Due to the growing demand for Python, job seekers are enthusiastic about learning the language and acquiring skills in this language [1].
Python is a high-level, interpreted programming language based on general principles. Python works as a bridge between web developers and data analysis. Python programming languages often provide the best opportunity to take introductory courses in data science and machine learning process. Python is of great importance for learning developers, data scientists, software engineers as it is the most versatile and object-oriented program. One of the best goals of learning Python is to apply it to various projects. Python is used for data science, scientific and mathematical computing, Web development, basic game development, computer graphics, etc [2].
Methods and materials.
Choosing Python gives us the following advantages:
• Python code is simpler, easier to read, write, and debug.
• It is less verbose and benefits from a large and intuitive set of built-in functions (tuples, lists, dictionaries, arrays, etc.)
• In particular, Python constructs such as generators, lists, and dictionaries that is a great way to reduce simple object construction loops to a single readable line of code, or to create iterators that don't clutter the code.
• Well-written Python code can already be quite fast, and most of the inner-loop tasks of interest for these practical problems are executed on the GPU anyway, once properly initialized.
• Python has great wrappers for OpenGL and windowing libraries that have an interface very similar to their C counterpart. This means that everything you learn about writing Python code maps directly to the C API [3].
Animators use programs like MAYA, 3DSMAX, BLENDER, HOUDINI, CINEMA 4D to do their work, not a programming language. Animation involves performing repetitive tasks like copying buildings to model a city, moving some objects a certain distance and resting at another distance, etc. This is usually done with a scripting language. PYTHON is such a popular scripting language and most animation programs support it. With this bundle of work, you can reduce the execution of certain tasks several times. Instead of routine copying of elements or creating typical
effects. All this can be done thanks to Python. More advanced specialists can already not only perform basic functionality but also make various simulations and effects. Users working with 3D data know very well the importance of Python computer graphics. The high Python language is mainly used in:
• Visualization
• Virtual reality
• Photorealistic images
• Simulation creation
• Visual effects creation
• 3D modeling and sculpting
• And games
It serves functionally where tools are used to handle 3D. Modules used like CG and cri types make it easy to store a 3D scene in memory. This is only possible thanks to Python.
Python plays an important role in Artificial Intelligence (AI) unlike other programming languages due to the following reasons:
• It provides a free platform that gives users a popular choice with the least adjustments required in the necessary coding.
• It plays a constructive role in advanced computing as Numpy is used in scientific computing and Pybrain in machine learning [8].
Python has made a revolutionary step as the most widely used language in recent times. Creating a website in Python means that users have to create a coding process and execute it quickly on the server. Those who are interested in using Python based web development should learn programming and the basics of this language. Before taking on any real project, you should have some experience with the programming language [4]. Results and discussions.
Let's look at an example of using Python in computer graphics. We use Python and the PyGame library as a basis for outputting graphics. This set can be very easily output to the screen, make animation, etc. without being distracted by technical details of implementation. In Python, you can draw geometric shapes, patterns, create animation, draw graphs defined by mathematical calculations, and even create elements in a computer game. To work, you need to install additional modules or use built-in ones. This requires connecting some modules. For example, the Graph graphics module is connected in the first line: from graph import*
For error-free operation of this module, you first need to download the graph.ru modules
file.
Example. Create a window for outputting graphics, and also create an infinite loop reproducing an animation frame displayed on the screen - the so-called game loop. Code:
import pygame SX = 800 SY = 800 pygame.init()
screen = pygame.display.set_mode((SX, SY)) running = True
while running:
for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Main part pygame.display.flipO pygame.quit()
First, let's take graphic effects, so that it is both as simple and as beautiful as possible. To implement this, we create a graphic effect called a "screen saver". This is a small program that demonstrates a simple animation and runs on a timer when the user has not pressed any keys or touched the mouse.
On cathode-ray tubes, such programs helped prevent the phosphor from burning out inside the kinescope. If you display a static image with a minimum of changes on the monitor screen for a long time, you can get the effect that the phosphor applied to the inner side of the kinescope evaporated due to overheating in certain points and left traces that did not disappear even when the monitor power was turned off. That is, the image remained as if burned on the monitor. By the way, LCD monitors and plasma panels, etc. are subject to this effect. To prevent this effect, when the user was inactive for a long time, a screensaver program was launched that updated the screen and displayed something changing, not giving a chance to burn out individual parts of the screen. Useful functionality combines an aesthetic component, the monitor displays something pleasing to the eye. For example, one of such programs was a demonstration of the starry sky, where individual stars simply blinked. But flying through the stars looked even more beautiful. There are several examples of such software products as "Star Battle" in Norton Commander, Star Flight in Dos Navigator, Starfield Simulation in Windows 3.11, etc. [4].
To continue the example, we create a Windows 3.11 screensaver program and try to make it with minor improvements. In the animation of the program, we see a certain number of stars that are moving. The stars are approaching, gradually increasing their brightness. The stars are scattered evenly relative to the center of the screen. To begin with, we will fix the total number of stars that are simultaneously displayed on the screen.
Let this be the constant NumStar and to begin with, we will process 100 stars. We will store the stars in a regular mutable list. Each star has some characteristics, and we will write them down in this list. We need to know the coordinates of each star in space, in three-dimensional space, these will be the coordinates X, Y, Z. Here Z will be the depth of the screen, the greater it is, the further the star is. We need to know the characteristic of the star's color, that is, the brightness. The color value will be inversely proportional to the distance to the star: Stars [[x1, y1, z1, color1], [x2, y2, z2, color2], etc.]
When a star flies, it gradually moves along all three coordinates X, Y, Z, and will eventually fly out of the screen. A star can fall out of the field of view if it exceeds the coordinates on the window plane along X or Y and goes into negative coordinates along the Z axis. At this point, you need to make a new star instead of this star, so as not to process values that we will not see. To do this, reset all the properties of the star to their initial values.
To make the stars fly evenly relative to the center of the screen, the center of the window will be the center of the coordinate system and does not coincide with the coordinates provided by PyGame, and this is replaced. For uniform random scattering of star coordinates across the window
plane, the width and height of the window are known (these are SX and SY), so the new coordinates are obtained as:
X = random.randint(0, SX) - SX // 2
Y = random.randint(0, SY) - SY // 2
The X and Y coordinates are ready. The Z coordinate is set more simply, each new star appears at the maximum distance. For simplicity of calculations, let the maximum screen depth be Z = 256. The color of the new star will not be visible at first, color = 0. As the star approaches along the Z axis, its brightness will increase. And increase from 0 to 255. The algorithm scheme is as follows:
• clear the screen;
• display the stars;
• calculate new coordinates;
• repeat.
To display a star in screen coordinates, we need to convert 3D coordinates to 2D, and preferably in a perspective projection.
Perspective projection is when a certain point is needed to construct the projection - the center of the projection, from which a ray emerges that intersects the object for which the projection is constructed and a certain plane on which the object is projected. This method allows you to display an object on a plane taking into account its perspective distortions, i.e. the distant parts will be smaller than the near ones.
The figure shows a star in coordinates X, Y, Z. We consider only two axes Y and Z, for the X and Z axis everything will be completely similar. The projection center will be located at the origin of coordinates. A virtual ray comes out of the projection center, which intersects the star and then intersects the plane of the screen, on which the star will be displayed in 2D form (the Z axis will no longer be here).
This can be compared to a flashlight shining from a central point and the star casting a shadow on the wall. The point on the screen will have coordinates Xs, Ys, Zs. Since the Y and Z axes are considered, X is not taken into account. Let's calculate the Ys coordinate.
Let's place the display plane at the farthest point of our virtual field along the Z axis, at coordinate 256. As a result, we will obtain formulas for calculating the screen coordinates of our stars on the plane. We slightly modified the center of coordinates, compared to what PyGame offers, we need to bring the obtained coordinates to the PyGame coordinate system.
Xs = ((X * 256) / Z) + coordinate of the center of the screen by X
Ys = ((Y * 256) / Z) + coordinate of the center of the screen by Y
As a result, when the star moves to the center of coordinates along the Z axis, it will move up along the Y axis, and the effect of the stars scattering from the center of the screen will occur. Let's make all the stars move at the same speed. We'll choose the speed experimentally, we got it
equal to 0.08, for slow and beautiful movement of the stars. In the cycle, for each star we decrease its Z coordinate and recalculate X and Y. If the Z coordinate has become less than or equal to 0 or the star has flown out of any of the side borders of the screen by X or Y, then we generate a new star, instead of the old one. Simultaneously with decreasing the Z coordinate, we increase the color value of the star, so that as it approaches, the brightness increases. Experimentally, the brightness increment, for the most pleasant picture, we take the step = 0.15. The final code will be as follows: import pygame import random SX = 800 SY = 800 pygame.init()
screen = pygame.display.set_mode((SX, SY)) running = True
NumStar = 100 # number of stars speed = 0.08 # Speed of stars stars = [] # List containing stars
# X-coordinates, Y-coordinates of stars, # Z range of star, color
# Function of star generation. def new_star():
star = [random.randint(0, SX) - SX // 2, random.randint(0, SY) - SY // 2, 256, 0] return star
for i in range (0, NumStar): # Fill the list with stars.
stars.append(new_star())
while running:
for event in pygame.event.get(): if event.type == pygame.QUIT: running = False
screen.fill((0, 0, 0)) # Clear the screen
x = y = 0
for i in range (0, NumStar): # Loop through all stars. s = stars[i] # star characteristics from the list
# current star coordinates x = s[0] * 256 / s[2]
y = s[1] * 256 / s[2]
s[2] -= speed # Change its Z coordinate
# If the coordinates go beyond the screen, generate a new star.
if s[2] <= 0 or x <= -SX // 2 or x >= SX // 2 or y <= -SY // 2 or y >= SY // 2: s = new_star()
if s[3] < 256: # If the color has not reached maximum brightness, increase the color. s[3] += 0.15
if s[3] >= 256: # If the color suddenly becomes larger than the permissible value, set it to
255
s[3] = 255
stars[i] = s # Place the star back into the list of stars.
# Display the star on the screen.
x = round(s[0] * 256 / s[2]) + SX // 2
y = round(s[1] * 256 / s[2]) + SY // 2
pygame.draw.circle(screen, (s[3], s[3], s[3]), (x, y), 3)
pygame.display.flip()
pygame.quit()
We get an analogue of the screen saver in Python. This algorithm and graphic effect is one of the simplest, but contains some interesting mathematics and geometric transformations.
Conclusions. This paper examined the Python programming language and its application in various fields, including data science, machine learning, animation, and computer graphics. It was shown that Python is a universal programming language that is easy to use, has a high level of code readability, and has wide library support, making it one of the most popular programming languages in the world.
One of the key advantages of Python is its ability to integrate with various tools and technologies, such as libraries for processing 3D graphics and animation. The language is actively used in animation programs and simulations, which greatly simplifies the implementation of routine tasks and increases the productivity of developers. An example of this is the creation of a simple screensaver demonstrating the starry sky using the PyGame library.
Based on the conducted research, it can be concluded that Python is not only a language convenient for novice developers, but also a powerful tool for solving complex problems in areas such as data visualization, machine learning, and animation creation. Further research and development can be aimed at expanding Python's capabilities in the area of high-performance computing and integration with GPUs, which will further improve its efficiency when working with large amounts of data and creating complex simulations. We have discussed the main reasons for the emergence of the Python programming language. These approaches should be enough to understand Python in all its aspects. Python supports both functional and structured programs. It is also compatible with any platform of other programming languages. Therefore, it is considered a universal language.
REFERENCES
1. Shoyqulov Sh. Q. Methods for plotting function graphs in computers using backend and frontend internet technologies. European Scholar Journal (ESJ). Vol. 2 No. 6, June 2021, ISSN: 2660-5562. P.161-165, https://scholarzest.com/index.php/ esj/article/view/964/826
2. Shoyqulov Sh. Q., Bozorov A. A. Methods for graphing functions in computers using Web technologies. Journal of Information Computational Science. Journal Vol. 1 Issue 1, JUNE 2021. Urgench., https://www.sciencepublish.org/index.php/ics/article/view/79
3. Shoyqulov Sh. Q. Wonderful multimedia - applying in areas outside of teaching. "Innovations in technology and science education" scientific journal, Volume #2, issue#7, Publication: february 2023, p. 700-708, SJIF-5.305, ISSN 2181-371X, https://humoscience.com/index.php/itse/index
4. Sh.Q. Shoyqulov. (2021). Methods for plotting function graphs in computers using backend and frontend internet technologies. European Scholar Journal, 2(6), 161-165. Retrieved from https://scholarzest.com/index.php/esj/article/view/964
5. Sh.Q. Shoyqulov, A. M. Shukurov. Propagation of Non-Stationary Waves Of Transverse Displacement from a Spherical Cavity in an Elastic Half-Space.
6. International Journal of Advanced Research in Science, Engineering and Technology. 1329113299. Vol. 7, Issue 4 , April 2020. http://www.ijarset.com/upload/2020/april/13-shshovqulov-02-1.pdf
7. Shoyqulov Sh. Q., Bozorov A. A. Methods for plotting function graphs in computers using modern software and programming languages. ACADEMICIA: An International Multidisciplinary Research Journal. 321-329. 2021, Volume : 11, Issue : 6. ISSN : 2249-7137. DOI : 10.5958/2249-7137.2021.01619.0. Online published on 22 July, 2021.
8. Bozorov Abdumannon, & Shoyqulov Shodmonkul Qudratovich. (2022). MULTIMEDIA SURVEILLANCE CAMERAS AND THEIR FEATURES IN USING. Open Access Repository, 9(10), 29-34. https://doi.org/10.17605/OSF.IO/4EV75
9. Bozorov Abdumannon, Nodirbek Abdulkhayev, Shoyqulov Shodmonkul Qudratovich. (2022). Modern technologies of virtual reality- a new multimedia opportunities. eurasian journal of mathematical theory and computer sciences, 2(11), 85-90. https://doi.org/10.5281/zenodo.7251370
10. Qudratovich, S. S. (2022). The Role and Possibilities of Multimedia Technologies in Education. International Journal of Discoveries and Innovations in Applied Sciences, 2(3), 72-78. Retrieved from http://openaccessjournals.eu/index.php/ijdias/article/view/1148