how to draw a 3d planet
In this article, you volition come across a simple 3D solar organization implementation with OpenGL and C#. In the demo, you lot will larn how OpenGL rotation works and how to rotate a mesh effectually an arbitrary axis. You will as well make apply of the main OpenGL primitives: Point, Line and Triangles.
- Download source code - 1.7 MB
Introduction
This is a 3D solar system implementation with OpenGL and C#. I tried to keep it simple because this demo is only for educational purposes. Information technology contains the sun, the planets, our moon, the planet'southward orbit and some stars. It is programmed in Visual Studio 2008 and I have upgraded it to Visual Studio 2010 without any kind of issue. For this demo, I used the TAO namespace which is an interop between the OpenGL DLL and the .NET Framework. I also used Shadowengine, a small-scale graphic framework developed by me to rid you of the tedium of hard coding the loading of textures, the initialization of the graphic context among others.
A Solar Organization Viewed form a 3D Programmer Point of View
Well, what does a solar arrangement comprise? Planets, Sunday Satellites, the universe, the stars on the background, etc. Equally a 3D programmer, yous should retrieve near how yous will translate those entities to a programming surroundings. For example, the universe is all black. With having a black background, you will solve that trouble. OpenGL already has that part Gl.glClearColor(0, 0, 0, one);//cherry-red green blue blastoff which will set the groundwork color to black. About the stars, they are only bright dots, and then you could make employ of the OpenGL primitives that handle the drawing of points. You can make apply of random functions to generate a lot of stars if you are likewise lazy to place them 1 by one, you just accept to brand sure they don't fall inside the solar system. The planets are merely spheres with textures; they also have orbit and a rotation on its own centrality then you take to keep track of those using variables and update them considering they change over the time. If you don't want to make a sphere in 3D max, you may use OpenGL quadrics considering information technology defines a prepare of basic trigonometric shapes and also defines texture coordinates for them. Satellites are the same as planets, the only difference is that the axis of their rotation is located on a planet not on the sun.
Using the Lawmaking
References in the project include those to ShadowEngine and TAO.OpenGL. I would similar to bespeak out that I don't create a graphic context in a standalone window Like XNA, GLUT, etc. My graphic context is created in a common .NET WinForm. This is very convenient because you can draw 3D content in any window mixing it with 2D components. After, you volition encounter that yous can draw 3D content in nearly whatsoever 2d component. The OpenGL initialization part only needs a valid component handler to start cartoon 3D.
Here is the list of project classes:
Camera.cs
This is a classic FPS (First Person Shooter) camera. The explanation of how a FPS works goes across the scope of this commodity. They piece of work in the following way:
- The mouse is centered on the eye of the screen.
- When the user moves the mouse, a delta X and Delta Y are calculated from the beginning indicate.
- Those Delta X and Delta Y are translated into angles and how the photographic camera it's rotated.
- When you wish to move frontward or astern, the camera will move in the direction in which the angles are pointing.
- You may take a await at
public void Update(int pressedButton)at thephotographic cameraclass to have a better agreement.
MainForm.cs
This class name is cocky explanatory, it is the main and only form of the project. It contains the call to the texture loading, the 3D context initialization, the drawing of the 3D content, among others. It as well handles the user central and mouse input. Because the 3D content requires at to the lowest degree 30 frames per second to be fatigued, I used a timer and placed all the drawing code inside it. One indicate of involvement would be that I commencement a 3D context on a panel, so I tin prepare the panel in any position I want inside the form. Here is the code of the 3D initialization on the project:
hdc = (uint)pnlViewPort.Handle; string error = " "; OpenGLControl.OpenGLInit(ref hdc, pnlViewPort.Width, pnlViewPort.Elevation, ref error);
Here is the lawmaking to load the textures into OpenGL memory:
ContentManager.SetTextureList(" texturas\\"); ContentManager.LoadTextures();
My small-scale engine takes intendance to load all the textures located on that binder, the texture format accustomed is TGA JPG and BMP. The textures may not be NPOT (Non Power Of Ii) and still volition load correctly.
Here is the code that draws all the scenes:
private void tmrPaint_Tick(object sender, EventArgs e) { Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT); solarSystem.Camara.Update(moving); solarSystem.DrawsScene(); Winapi.SwapBuffers(hdc); Gl.glFlush(); }
Planet.cs
A planet contains the following variables:
- Position
- Texture
- Orbit (electric current distance from the sun)
- Current rotation bending
- Current orbit rotation angle
- Current orbit speed
I used OpenGL quadrics to depict the planets sphere. Quadrics are OpenGL predefined shapes to help in minor drawing tasks. Quadrics come, for case, with texture coordinates, so I don't accept to use a 3D editor like 3D Max to correctly apply texture to each planet. In each frame, the planet moves through its orbit according to its orbit speed. Also there is a bool variable called hasMoon to specify if you lot want to draw a moon for that planet. I have but our moon but if you lot like, for example, to draw mars moons Phobos and Deimos, you can apply that code. Some other interesting role that contains the planet grade is the i used to describe its orbit. First, I generate the points with a sin part so I connect them using GL_LINE_STRIP. Hither is the code:
public void DrawOrbit() { Gl.glBegin(Gl.GL_LINE_STRIP); for (int i = 0; i < 361; i++) { Gl.glVertex3f(p.x * (float)Math.Sin(i * Math.PI / 180), 0, p.ten * (bladder)Math.Cos(i * Math.PI / 180)); } Gl.glEnd(); }
Notation that the planets almost always have an elliptical orbit. This is a round orbit. The two angle variables that hold the planets class are used to maintain the rotation of a planet around its centrality and to maintain the rotation around the dominicus.
Satellite.cs
A satellite contains everything that a planet does. The but difference is that its rotation betoken is not the sun but the planet that contains it. So anytime information technology draws, it has to receive the position of its containing planet. You will annotation it on its describe function.
SolarSystem.cs
This is the grade that contains the listing of planets, stars and satellites. It but creates and draws them. The planets are saved into a list and when I call DrawScene() from the principal form, it makes a foreach loop invoking the Describe method on the planets.
Star.cs
This is the grade the draws the stars. The stars are single GL_POINTS which are generated in random positions. This is the office that generates them:
public void CreateStars(int corporeality) { Random r = new Random(); int count = 0; while (count != corporeality) { Position p = default(Position); p.ten = (r.Side by side(110)) * (float)Math.Pw(-ane, r.Next()); p.z = (r.Side by side(110)) * (float)Math.Pow(-1, r.Adjacent()); p.y = (r.Next(110)) * (float)Math.Pow(-1, r.Next()); if (Math.Pow(Math.Pow(p.ten, 2) + Math.Prisoner of war(p.y, 2) + Math.Pow(p.z, 2), i / 3f) > 15) { stars.Add(p); count++; } } }
What this code does is to generate a random point and calculate its altitude to the sun, and if the distance is less that a predefined value, discard the betoken. In this case, the predefined value is twice the radius of the solar system. This operation will be repeated until it reaches the desired amount of stars.
Sun.cs
The sun class is the most simple. It's like the planet class, just it has no orbit. It has only a rotation around its centrality. The sun is drawn at the OpenGL 3D coordinates of (0,0,0).
Points of Interest
In this demo, you larn how OpenGL rotation works and how to rotate a mesh around an arbitrary axis. Also, you will make utilize of the main OpenGL primitives: Point, Line and Triangles. Well, these are all the classes involved in this project. I hope it is useful and that it volition encourage developers to start programming in 3D. Experience costless to play with the code and to enquire any questions you want.
History
- 17th April, 2013: First version of the demo
Source: https://www.codeproject.com/Articles/577259/3D-Solar-System-with-OpenGL-and-Csharp
0 Response to "how to draw a 3d planet"
Enregistrer un commentaire