# Rotating Solid Cube Using VB.NET and GDI+

In my last tutorial I have shown how to make a wireframe cube using VB.NET and GDI+. Today, we will build from the code from the last tutorial in order to make a rotating solid cube. The video below shows what we will achieve after finishing the tutorial.

THE FULL SOURCE CODE IS HERE.

## The Code

The original code was divided in 2 files [Point3D.vb and Main.vb]. The Point3D.vb file  defined the Point3D class which represents points in 3D space. The file Main.vb defined the Window form where the simulation runs.

The class Point3D remains unchanged and is presented below.

```'
' Defines the Point3D class that represents points in 3D space.
' Developed by leonelmachava <[email protected]>
' http://codentronix.com
'
' Copyright (c) 2011 Leonel Machava
'
Option Explicit On

Public Class Point3D
Protected m_x As Double, m_y As Double, m_z As Double

Public Sub New(ByVal x As Double, ByVal y As Double, ByVal z As Double)
Me.X = x
Me.Y = y
Me.Z = z
End Sub

Public Property X() As Double
Get
Return m_x
End Get
Set(ByVal value As Double)
m_x = value
End Set
End Property

Public Property Y() As Double
Get
Return m_y
End Get
Set(ByVal value As Double)
m_y = value
End Set
End Property

Public Property Z() As Double
Get
Return m_z
End Get
Set(ByVal value As Double)
m_z = value
End Set
End Property

Public Function RotateX(ByVal angle As Integer) As Point3D
Dim rad As Double, cosa As Double, sina As Double, yn As Double, zn As Double

rad = angle * Math.PI / 180
yn = Me.Y * cosa - Me.Z * sina
zn = Me.Y * sina + Me.Z * cosa
Return New Point3D(Me.X, yn, zn)
End Function

Public Function RotateY(ByVal angle As Integer) As Point3D
Dim rad As Double, cosa As Double, sina As Double, Xn As Double, Zn As Double

rad = angle * Math.PI / 180
Zn = Me.Z * cosa - Me.X * sina
Xn = Me.Z * sina + Me.X * cosa

Return New Point3D(Xn, Me.Y, Zn)
End Function

Public Function RotateZ(ByVal angle As Integer) As Point3D
Dim rad As Double, cosa As Double, sina As Double, Xn As Double, Yn As Double

rad = angle * Math.PI / 180
Xn = Me.X * cosa - Me.Y * sina
Yn = Me.X * sina + Me.Y * cosa
Return New Point3D(Xn, Yn, Me.Z)
End Function

Public Function Project(ByVal viewWidth, ByVal viewHeight, ByVal fov, ByVal viewDistance)
Dim factor As Double, Xn As Double, Yn As Double
factor = fov / (viewDistance + Me.Z)
Xn = Me.X * factor + viewWidth / 2
Yn = Me.Y * factor + viewHeight / 2
Return New Point3D(Xn, Yn, Me.Z)
End Function
End Class
```

The file Main.vb has suffered some changes. See below its code.

```'
' Simulation of a Rotating Cube using GDI+
' Developed by leonelmachava <[email protected]>
' http://codentronix.com
'
' Copyright (c) 2011 Leonel Machava
'
Imports System.Drawing.Graphics
Imports System.Drawing.Pen
Imports System.Drawing.Color
Imports System.Drawing.Brush
Imports System.Drawing.Point
Imports System.Drawing.Bitmap

Public Class Main
Protected m_timer As Timer
Protected m_vertices(8) As Point3D
Protected m_faces(6, 4) As Integer
Protected m_colors(6) As Color
Protected m_brushes(6) As Brush
Protected m_angle As Integer

Private Sub Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Enable double-buffering to eliminate flickering.
Me.SetStyle(ControlStyles.AllPaintingInWmPaint, True)
Me.SetStyle(ControlStyles.OptimizedDoubleBuffer, True)

InitCube()

' Create the timer.
m_timer = New Timer()

' Set the timer interval to 25 milliseconds. This will give us 1000/25 ~ 40 frames per second.
m_timer.Interval = 25

' Set the callback for the timer.

' Start the timer.
m_timer.Start()
End Sub

Private Sub InitCube()
' Create the cube vertices.
m_vertices = New Point3D() {
New Point3D(-1, 1, -1),
New Point3D(1, 1, -1),
New Point3D(1, -1, -1),
New Point3D(-1, -1, -1),
New Point3D(-1, 1, 1),
New Point3D(1, 1, 1),
New Point3D(1, -1, 1),
New Point3D(-1, -1, 1)}

' Create an array representing the 6 faces of a cube. Each face is composed by indices to the vertex array
' above.
m_faces = New Integer(,) {{0, 1, 2, 3}, {1, 5, 6, 2}, {5, 4, 7, 6}, {4, 0, 3, 7}, {0, 4, 5, 1}, {3, 2, 6, 7}}

' Define the colors of each face.
m_colors = New Color() {Color.BlueViolet, Color.Cyan, Color.Green, Color.Yellow, Color.Violet, Color.LightSkyBlue}

' Create the brushes to draw each face. Brushes are used to draw filled polygons.
For i = 0 To 5
m_brushes(i) = New SolidBrush(m_colors(i))
Next
End Sub

Private Sub AnimationLoop()
' Forces the Paint event to be called.
Me.Invalidate()

' Update the variable after each frame.
m_angle += 1
End Sub

Private Sub Main_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
Dim t(8) As Point3D
Dim f(4) As Integer
Dim v As Point3D
Dim avgZ(6) As Double
Dim order(6) As Integer
Dim tmp As Double
Dim iMax As Integer

' Clear the window
e.Graphics.Clear(Color.LightBlue)

' Transform all the points and store them on the "t" array.
For i = 0 To 7
Dim b As Brush = New SolidBrush(Color.White)
v = m_vertices(i)
t(i) = v.RotateX(m_angle).RotateY(m_angle).RotateZ(Me.m_angle)
t(i) = t(i).Project(Me.ClientSize.Width, Me.ClientSize.Height, 256, 4)
Next

' Compute the average Z value of each face.
For i = 0 To 5
avgZ(i) = (t(m_faces(i, 0)).Z + t(m_faces(i, 1)).Z + t(m_faces(i, 2)).Z + t(m_faces(i, 3)).Z) / 4.0
order(i) = i
Next

' Next we sort the faces in descending order based on the Z value.
' The objective is to draw distant faces first. This is called
' the PAINTERS ALGORITHM. So, the visible faces will hide the invisible ones.
' The sorting algorithm used is the SELECTION SORT.
For i = 0 To 4
iMax = i
For j = i + 1 To 5
If avgZ(j) > avgZ(iMax) Then
iMax = j
End If
Next
If iMax <> i Then
tmp = avgZ(i)
avgZ(i) = avgZ(iMax)
avgZ(iMax) = tmp

tmp = order(i)
order(i) = order(iMax)
order(iMax) = tmp
End If
Next

' Draw the faces using the PAINTERS ALGORITHM (distant faces first, closer faces last).
For i = 0 To 5
Dim points() As Point
Dim index As Integer = order(i)
points = New Point() {
New Point(CInt(t(m_faces(index, 0)).X), CInt(t(m_faces(index, 0)).Y)),
New Point(CInt(t(m_faces(index, 1)).X), CInt(t(m_faces(index, 1)).Y)),
New Point(CInt(t(m_faces(index, 2)).X), CInt(t(m_faces(index, 2)).Y)),
New Point(CInt(t(m_faces(index, 3)).X), CInt(t(m_faces(index, 3)).Y))
}
e.Graphics.FillPolygon(m_brushes(index), points)
Next
End Sub
End Class
```

The code is pretty much self-explanatory. Below I will just list the key changes.

In the Load event I enable double buffering. This is fundamental to eliminate flickering in the animation. Try to remove the first 2 lines of code, and run the application. You will certainly see the flickering that results.

Basically I have changed the code to draw filled faces instead of lines. However, now we must make sure to draw distant faces first, and closer ones last (Painters Algorithm).

THE FULL SOURCE CODE IS HERE.

## Conclusion

As I have promised in the last tutorial, today I have shown how to make a rotating solid cube. In my next VB.NET tutorial, I will show you how to make a cool game in pretty simple steps.
If you liked this article, please consider leaving a comment, or sharing this post using one of the buttons below, or even subscribing to the blog.

1. Parabéns bacana seu projeto

2. wiiii, several years ago i droped a personal project (in vb6) because i couldnt create a function that would let me rotate the axis in r3, i cant wait to modify this >w<

• Hi Fabyola.

• jijiji, sure n_n, ill let you know if i can get this to work with my code
oh, and thanks for this tutorial n_n

• Thank you!

3. hello again lefam, im sorry that i didnt post anything up to now, i was really busy because i got a new job just a few weeks ago =3
well, i didnt spent too much time on this but i got some strange results xd, let me explain it (and please forgive my bad english, its not my native language)
i always like to know how things work, so i keep “discovering the circle again” over and over on diferent things that i see
some years ago i was playing with some equations and i wondered how they would look like on a 3D space, and made myself a rough but extremely precise (and slow) 3D drawing software, based on explicit 3 var functions, painting one dot at a time xd
i made some changes and painted some beatiful functions (adding colors based on the function itself makes them alive) but my software had some trouble, it was only capable of “looking” from one angle, so i wanted to rotate the functions, but i got some personal issues and droped the proyect before i could design an algorith to do so
a week ago i was surfing the net looking how to manage built in drawing functions from vb.net (because it doesnt let me know the hDC of the form anymore <.<) and found your example, it reminded me of that project and i remade it (for some reason it was really easy this time xd) and added 2 rows from your code, after some fixing it worked lovely, but for some reason, when i try to rotate more than 1 axis at a time the functions suffer horrible disforming xD
ill work on this a little more, thanks again for you example n_n
oh, and… im sorry if i wrote too much xd
see you later =3

• First of all, let me tell you that I am glad to know that my articles and codes were useful to you.
The “disformation” may happen due to an error in the rotation formula (or matrix composition, if you are using matrices). Other probable cause can be the order of the transformations (rotation followed by translation may have a different result from translation followed by rotation).

4. here’s a visual example of whats happening with the points, i made this in a rush so, no back buffer = lots of flickering xD
also, i used a low dot density, that way it redraws fast even with a high refresh rate (Form_MouseMove) but it doesnt look like a solid object
the example its done with a function that creates half a sphere, that way you can see the rotation easily
well, here it is:

5. the entire process its done with 2 for in this way:

start FOR rows
Start FOR columns
calculate profundity for the 3d point
rotate in column axis
rotate in row axis
translate 3d point into 2d
paint it
NEXT column
NEXT row

• Nice simulation (“despite the disformation”).
Probably, you are not doing correctly the composition of the transformations (I mean rotations).

6. Thanks Leonel..

This one really inspired me for a new project that can even replace Maya..

• You are welcome.
Great, I would be happy to see or know about that project.

7. Very good code. Tought me how to draw 3D objects in VB.NET. I was looking for something like that for a long time. Thanks
Antonio
Brazil

• You are welcome.

8. Justt want to say yolur article is as astounding.
Thhe clearness in your post is just great and i can assume you’re an expert on this subject.
keep up to date with forthcoming post. Thanks a million and please carry on the enjoyable work.

9. Hi! I’m at work srfing around your blog from my new apple iphone!
Carry on the fantasti work!

10. Undischarged level at that place. What happened later? Skillful fortune!

11. If it sounds too good to be real, it most likely is – everyone has heard this olden adage prior to.
One “Chattanooga Times Free Press” writer, however, discovered simply how much water
the stating still holds when his area just recently sustained
hail damage.
For instance are you conscious the only some 50 % of people
who enter a keyword into their online search engine exceed page one to
page 2? However of those that exceed page
one to page 2, only some 30 % of them make it to page 3.
Then it gets even worse for pages beyond that since it’s
just however a mere portion of searchers who remain that make it even more
on.

Keyword research study is an essential step in any kind of
online search engine advertising. Essentially, with
the incorrect list of keywords, no matter how excellent you
are ranking, you won’t make any money. Without targeted traffic you won’t make any
sales. Your focus should be on keywords that are popular among searchers.
Due to the fact that you will not win the race, with the right keywords you
are off to a running beginning; with the wrong keywords you might as well begin over.
As soon as you have actually found some high
volume keywords you can begin preparing your
site structure and themes. There are a variety of free keyword
tools that you can use to produce relevant keywords for your website.

The issue doesn’t begin with picking the right program or guide, but instead
starts with going from one cash making method to another.
It is crucial to establish your strategy with the right marketing techniques and
stick to them. You will certainly never find out if it
works or not if you don’t stick to your plan.
Exactly what I indicate by this is, they invest numerous hours studying film of previous
games of their opponents to comprehend exactly what
their every move will be. All teams do this, but those who do it correctly and correctly will get the
Remember, Viral internet marketing Videos are unpredictable.but that belongs
to what makes them so effective! Take the Old Spice Commercial for example.that went Viral on YouTube
and on Facebook! And why ?? Because it was original and hilarious!!
So the typical theme will generally either be smart creativity,
humor or both! Originality that is based on the present pop culture– exactly what
is big and popular RIGHT NOW! Or that is so smart and smart that it will then just BECOME
our pop culture!!
I would like to show you some of the experiences that I gone
through which you can stay clear of and in the procedure will save you hundreds or thousands of hours doing ineffective advertisings.

When you’re done reading this article, get hold of a pen and paper, and jot down just ONE marketing device,

1% Marketing & Web Design Bloomington
705 W Jackson St
Bloomington, Illinois 61701
(309) 429-6371

12. Very quickly this site will be famous amid all blogging and site-building users, due to
it’s pleasant articles or reviews

13. Hi mates, good piece of writing and good urging commented here, I am really enjoying by these.

What would you suggest in regards to your submit that
you made a few days ago? Any sure?

15. Numerous authors feel that the material of their
post is their major top priority. They invested their time in developing the very best content for their article after elaborative research.

Finally, in less than a minute they end up with the title.

It is very difficult to leave the security of a regular paycheck and browse out something
different. I took that gigantic leap of faith and I don’t
regret it at all. In truth, I wonder why I didn’t state, “Enough suffices” a very long time ago.

Therein lies the magic of advertising. Marketing makes people desire and desire to purchase since they produce a particular kind of
psychological image that when you have the pendant
or the perfume or bag, you will certainly look more youthful and prettier.

Some people just require to get cash coming in on a consistent basis.
It may be getting an affiliate network marketing check each month or a weekly affiliate payment.
There are really many ways you can make use of the Internet to make great deals of money.
Here are 3 I know of that actually do work.
The website owner pays you for advertising these individuals Whenever you blog for money.
This will certainly make their site and even product understood.
In addition, the websites web presence will likely be increased, more people can end up being aware of their products and finally, everything will pay in their side.
This will make it a great deal for you, the tumblr, and the
site or whatever it is which you have actually endorsed.
The very best part of this is that you do not need to
do a task that would take on an excessive amount of your time.
A normal typist could complete a single task in around Thirty Minutes to one hour.

No doubt its just a one liner to put a title for
the short article. However do spend at least
25 % to 50 % of your time in coming up with a great effect title for the short article.

Yes its that wish for you to think your post over and
over again and develop the finest you can think about.
If you spend 1 hour (not that this is best) to compose an article internet marketing , then do spend
a minimum of 30 to 15 minutes for the title.

Expecting instantaneous outcomes with Search Engine
Optimization will lead you to making a great deal of
unnecessary mistakes. Persistence is a has to for SEO.
You will be rewarded with long term traffic. Are you prepared to strike the first page for keywords that get countless searches per month?

You should be prepared to construct links, develop special content and put in the time to
have everything in location, then you can simply forget getting ranked for any keyword.

I get irritated on an everyday basis and have actually sabotaged myself
by erasing at least 2 lists with over 40 customers. Why? Nonsense is one factor,
and nonsense is the other. Ah, however learn and live.
I went back to square one two times, however I push forward
since sheer determination will not allow me to stop, that and a
minor dependency to it. Don’t stress; I have a call into my doctor!

1% Marketing & Web Design Bloomington
705 W Jackson St
Bloomington, Illinois 61701
(309) 429-6371

16. Here are 2 functional and random observations own short article writing.
Choose a couple of which you can utilise right away before your head hits the pillow tonight.

Perhaps simply as vital, they left me (and
all those other possible entrants) with the impression that
they were a disorganized, badly run company.

First there is satellite television. Now there is a bigger risk.
The local telephone company offering tv. AT&T is providing Uverse
and Verizon is providing FiOS in a growing variety of locations.
According to numerous awards they have received it is excellent quality.

The more you can find out about each of the web marketing experts the simpler
it will be for you to decide who you wish to
discover from. Spend some time doing searches and visiting online forums,
particularly if you have no idea who the experts are.
You can find out quickly enough in forums who they are and if you do not find anything you can constantly ask.

The author of the post went on to highlight a “Want a complimentary roof?” advertising sign published by a
roof business. Probabilities are, when the roof contractor has the unwary property owner in his clutches that “free”
roofing is going to wind up costing a pretty penny.

Lesson number two, to steal another worn-out maxim, “There is no complimentary lunch”.

or roofing as the case might be.
Where else can you find a company that you can begin for under 5 hundred dollars.

With so lots of people underemployed or unemployed
in today’s economy, to be able to begin your very own company is a
real chance. There are a lot of cutbacks and furloughs discovering part time work is a
genuine blessing. The charm of this is it will not only replace your earnings,
it will build you a fortune! You are probably tricking yourself
if you think that you will get rich quick.Some individuals do
get rich in simply a couple of months, internet marketing however the majority of take 12-36 months to reach there objectives.If
it sounds to excellent to be true it most likely is.
There are just to numerous opportunities out there to choose
from. After searching for over 2 years I lastly discovered a company and team that I can work with.

Organizational structure: The structure of your business need to be most carefully satisfying the requirement of the market.
You can opt to have any structure that fulfills your requirements for providing your simpleness and ease in operation.
When you’re done reading this article, grab a pen and paper, and jot down simply ONE marketing device, list

1% Marketing & Web Design Bloomington
705 W Jackson St
Bloomington, Illinois 61701
(309) 429-6371

17. The Web is fulled of chances of every kind, including that of improving your financial situation. Thousands of people search
the Internet daily for methods to generate income online.
Numerous of them desire to have the ability to discover cash free of charge.
Simply puts, make some money without needing to invest money first.

Examine your house’s curb appeal and make some improvements.
Your houses need to be appealing enough that home hunters
would believe it deserves buying. Do not settle for a sub-par appearance.
Put in the finest accessories and brighten your residence.
The point is to make your home stand out. And the best you can do is to highlight the finest locations of

Eric- Not lots of and if have, I would not wish to lug the TELEVISION to my 2nd floor office-it’s
very heavy and big. I would normally remove the motherboard from my consumer’s location for repair
work.
Fifth, Kelly provides you various devices, services,
and recommendations that you can buy, so in result you begin to trust doing company with him.
With time, a specific percentage of the people
on his marketing list become associated with his company, and because he produces 20-50 leads every day through his marketing, his business just continues growing.

Mobile phone have ended up being really attractive as advertising tools also; a recent Harris survey reports that the cellular phone use is increasing while the traditional
landline telephone is fast losing clients. The fact is 20 % of the adults in the US do not
have a landline. The very same portion now utilize just
cellular phone, and the number is growing very fast.

Moreover, while mobile phone amongst the more youthful generation have actually been extensively reported, they are also ending up being preferred amongst older
populations also. For the under 30 crowd, almost 40 % of them make use of absolutely nothing but a cellular phone or the web for communication. This suggests that over 80 % of your customers have a cellular phone and you can reach
all you need is a computer system and an ISP.
No doubt its only a one liner to put a title for the article.
However do spend at least 25 % to 50 % of your time in coming up with
an excellent impact title for the article. Yes its that long for
you to think your short article over and over again and come up with the very best you can consider.
internet marketing Do invest at least 30 to 15 minutes for the title if you spend 1 hour
(not that this is ideal) to compose a post.

Photo the bull as all exactly what the world offers you.
Whether it be physically, mentally, or economically.

In this article I would like to discuss what you might be leaving on the table regarding web
I am included with advertising online and I also
just recently started my own vending business in Ottawa called “Something to chew on Refreshment Service.” As soon as
where you might very well be right now in your own life, I was.
All I can state is have a little faith in yourself.

1% Marketing & Web Design Bloomington
705 W Jackson St
Bloomington, Illinois 61701
(309) 429-6371

18. What’s Taking place i’m new to this, I stumbled upon this I have discovered It
I’m hoping to contribute & aid other users like its aided me.
Good job.

Champaign Office Cleaning & Business Janitorial Services
1303 Williamsburg Dr.
Champaign, IL 61821
(217) 666-4750

19. I’ve desired to produce a suggestion myself and been examining
every one of the opinions concerning the greatest skin care products.

20. I have used Olay Complete for years with fantastic
outcomes, so when anyone who has been handled for cancer,
I appreciate understanding that my skin care schedule features a
SPF.

21. Thanks, I’ve recently been looking for info approximately this subject for
a while and yours is the greatest I’ve discovered so far.
But, what about the conclusion? Are you sure concerning the source?

22. I saw your work some time ago and it inspired me to create my own implementation. So, thank you for sharing!

The version I’ve been working on (available at GitHub) supports ZBuffering which allows it to render more complex scenes: https://github.com/morphx666/3DEngine

23. I must say you have hi quality content here. Your blog should go viral.
You need initial boost only. How to get it? Search
for; Etorofer’s strategies

24. The tallest pet gate aνailable at PetStreetMall is actually The High and also
Wide Veɦicle Close Portal Gate by Kidco.

25. Ꭺ test fгom ɑ folks iѕ actually just how this acts toward the aged.
That is actually simple to want tоddler.

26. Typіcally, thіs is aⅼl right stuff that we consider to ensսre you have actսalⅼy a
relaxed and anxіety coѕt free holiɗay!

27. Ӏ sսrνive on a houseboat and pоssess a hardwooⅾ
deck.

28. Youu ԝould like to ensure your youngster rеmains in a rear facing infant seat up
until 5. The longer the safer.” Always remember, as soon as you obtain a child seat or any sort of youngster oor even children similar product, register this just before you take that out from the box. This way you’ll be actually.

29. I loϲated a bunch of testimoniaⅼs on howl along with paths to the stairs faiгly quickly.
The walking is theoreticаlly unlawful so aspect of the experience
in needing to rise very veryy early (1:15 am in our
instance) аnd also sneaҝing over the stаir.

30. When my son Ƅegan to creep, I Ƅegan to overreact.

My pгoperty was decidedly certаinly not kid friendly.

31. Walk tɦrough gates are those that ɑre actually made wҺere installing continues to bе static whetɦer pressure or wall mounted
and that features a gate ‘door’ that you could swinging available and also closed.
They can be secured right into the shut posture so infants and also kids can not open them easily

32. If that iѕ actually the bottom up” method, beginning search att nearby degree, the net is actually a practical best down” strategy.
Ꮇаny brewеries have wеbsites, as do masny international merchants.
For impoгted draft beers, there may ѕіmply be actually resiidence
natiօn site, butt several օf tɦose consist of
limited United Ꮪtates connects ԝith.

33. Νext off, we have to carry on the mark onn the follⲟwing skin frοm the deck article,
in order to have the capaсity to put սp effectively all time lⲟw rail.

34. With гevealed гebar and crumbling handrails, recօvering the steps is actually no small activity.

35. I must say you have hi quality articles here.
Your content can go viral. You need initial boost only. How to get massive traffic?

Search for: Murgrabia’s tools go viral

36. Hi admin, i must say you have very interesting posts here.

Your website can go viral. You need initial traffic only.
How to get it? Search for; Mertiso’s tips go viral

37. Hello there! Great posting! I adore the method outlined Rotating Solid Cube Using VB.NET and GDI+ .
An additional great information totally from nice author.
Thanks someone blog site! Number of washes amazing to discover you might works.

I’m a lttle bit green with envy because I can’t pen as great as you’ll.
Creation hobby enables everyone holes and furthermore
nervous since i only have to publish very much by method of our modern instructional podium
.
In case there are speculate what insect like-minded provide, I can also recommend this particular
players http://www.ibotube.com. Customers draft reasonable consumer reviews
more than a most in-demand using the web scribbling net

38. School Leaver

Hi,
I have developed a app which rotates point on a graphics path but I seem to have an error when 3D rotating the points. It seems as if the “Z”axis in inverting (i.e. Z+ is Z- ) & then sometime it comes back. This look like when the axis is aligned with the view. Any Ideas why & how to correct it?