Create a 3D Cube Structure for GDI+

Conspicuously absent from the .NET Framework and GDI+ are three-dimensional (3D) shapes. Sure, you can draw lines, ellipses, rectangles, arcs, Bezier curves, and polygons, but things as obvious as spheres and cubes are absent. A sphere is a circle with volume, and a cube is a rectangle with a z-dimension or a depth. Unfortunately, 3D primitive shapes just don't exist.

Recently, when working at a logistics company, I was asked if we could render loads as 3D images, showing the load as various stacks of bins and pallets. Such an implementation would permit suppliers, carriers, dockworkers, and plants to visualize what was in a particular shipment. With all of the shippers in the world, this seems like it would be a common enough problem. Unfortunately, to do this you have to write your own primitives or leap up to something more advanced like DirectX 9. What I decided to do was experiment with GDI+ and implement a 3D cube primitive to determine how much work was involved in capturing the graphics aspect of this problem. This article more or less describes the results.

Defining the Cube Structure

A 3D cube, for the purposes of this example, has height, width, and depth values. When each of the six sides of the primitive has the same dimension as the others, you have a cube. Additionally, the graphics primitive needs to know about its Cartesian location, and the ability to divine the center of the cube also seems useful. The result is six rectangles connected along their respective edges.

An additional objective was that the cube be "renderable" using GDI+. This meant that the class or structure had to work with one of the GDI+ draw methods. Graphics.DrawPolygon turned out to be an option. However, imitating the implementation of the Rectangle structure, defining the 3D Cube as a structure, using the Rectangle structure as a pattern, and emulating the style of properties and fields of the Rectangle structure in my Cube structure seemed like a practical choice.

Defining Cube Fields and Properties

Following the Rectangle structure defined in the System.Drawing namespace, I added location, height, width, depth, center, path, and rotateX and rotateY fields. Location and center were defined as point structures; a point is a single X,Y Cartesian pair. Location represents the upper-left corner of the cube. Height, depth, and width are self-explanatory; these were defined as integers. Path was defined as a GraphicsPath, which is more or less an array of points. RotateX and rotateY are enumerated types representing the aspect ratio. These values are used to create a horizontal left, right, or center, and vertical up, down, or center viewpoint perspective. Collectively, rotateX and rotateY help give the illusion of viewing the cube from different angles.

You can define the project as a Class Library and add a reference to the System.Drawing.dll assembly. If you include the necessary Imports statement and the members mentioned thus far, your structure could be implemented as shown in Listing 1.

Listing 1: Defining the enumerations and fields for the Cube structure

To avoid getting lost, note that you will be adding code to the Cube structure, thereby growing the structure and the code in each successive listing until you have all of the code in the final listing.

Note: Using camel-cased names for fields and Pascal-cased names for properties (for example, location and Location) won't work in VB.NET because it is case insensitive. I prefer to use an F-prefix to mean field because it is easy and not as atrocious as m_, mvar_, or str_. Also, even though a language like C# is case sensitive, using case to distinguish members is not CLS compliant. This means that cross-language use of such classes may cause problems, and tools such as FxCop (http://www.gotdotnet.com/team/fxcop/) will report an error in your code due to such usage. Whichever convention you use, try to be consistent.

The next thing you need to do is add the symmetric properties for your fields. Convention fields are always private, and properties are the public means by which you permit consumers to change a field's value in a constrained way. Listing 2 shows the Cube Structure with the associated properties and a few extra convenience properties whose values are derived from the previously defined fields.

Listing 2: The Cube structure with properties

Imports System
Imports System.Drawing
Imports System.Drawing.Drawing2D
Public Enum RotateHorizontal
Left = -1
Center = 0
Right = 1
End Enum
Public Enum RotateVertical
Up = -1
Center = 0
Down = 1
End Enum
Public Enum CubeSides
Left
Right
Top
Bottom
Front
Back
End Enum
Public Structure Cube
Private FLocation As Point
Private FHeight As Integer
Private FWidth As Integer
Private FDepth As Integer
Private FCenter As Point
Private FPath As GraphicsPath
Private FRotateX As RotateHorizontal
Private FRotateY As RotateVertical
Public Property Location() As Point
Get
Return FLocation
End Get
Set(ByVal Value As Point)
FLocation = Value
End Set
End Property
Public Property Height() As Integer
Get
Return FHeight
End Get
Set(ByVal Value As Integer)
FHeight = Value
End Set
End Property
Public Property Width() As Integer
Get
Return FWidth
End Get
Set(ByVal Value As Integer)
FWidth = Value
End Set
End Property
Public Property Depth() As Integer
Get
Return FDepth
End Get
Set(ByVal Value As Integer)
FDepth = Value
End Set
End Property
Public Property Center() As Point
Get
Return FCenter
End Get
Set(ByVal Value As Point)
FCenter = Value
End Set
End Property
Public ReadOnly Property Path() As GraphicsPath
Get
Return FPath
End Get
End Property
Public Property RotateX() As RotateHorizontal
Get
Return FRotateX
End Get
Set(ByVal Value As RotateHorizontal)
FRotateX = Value
End Set
End Property
Public Property RotateY() As RotateVertical
Get
Return FRotateY
End Get
Set(ByVal Value As RotateVertical)
FRotateY = Value
End Set
End Property
Public ReadOnly Property X() As Integer
Get
Return FLocation.X
End Get
End Property
Public ReadOnly Property Y() As Integer
Get
Return FLocation.Y
End Get
End Property
'Return the rectangle that bounds the entire polygon
'representing the cube
Public ReadOnly Property BoundsRect() As Rectangle
Get
If (FPath Is Nothing) Then
Return New Rectangle(0, 0, 0, 0)
Else
Dim r As RectangleF = Path.GetBounds()
' Implicit conversion from single to integer,
' really only available in VB
Return New Rectangle(r.X, r.Y, r.Width, r.Height)
End If
End Get
End Property
Public Property Size() As CubeSize
Get
Return New CubeSize(FWidth, FHeight, FDepth)
End Get
Set(ByVal Value As CubeSize)
FWidth = Value.Width
FHeight = Value.Height
FDepth = Value.Depth
End Set
End Property
Public ReadOnly Property Item(ByVal index As CubeSides) _
As Point()
Get
Select Case index
Case CubeSides.Back
Return Back
Case CubeSides.Front
Return Front
Case CubeSides.Left
Return Left
Case CubeSides.Right
Return Right
Case CubeSides.Top
Return Top
Case CubeSides.Bottom
Return Bottom
Case Else
Return Front
End Select
End Get
End Property
Public ReadOnly Property Top() As Point()
Get
' TODO: Need to implement behavior here
Return New Point() {}
' Return GetTop(location, height, width, depth,
' rotateX, rotateY)
End Get
End Property
Public ReadOnly Property Bottom() As Point()
Get
' TODO: Need to implement behavior here
Return New Point() {}
' Return GetBottom(location, height, width, depth,
' rotateX, rotateY)
End Get
End Property
Public ReadOnly Property Left() As Point()
Get
' TODO: Need to implement behavior here
Return New Point() {}
' Return GetLeft(location, height, width, depth,
' rotateX, rotateY)
End Get
End Property
Public ReadOnly Property Right() As Point()
Get
' TODO: Need to implement behavior here
Return New Point() {}
' Return GetRight(location, height, width, depth,
' rotateX, rotateY)
End Get
End Property
Public ReadOnly Property Front() As Point()
Get
' TODO: Need to implement behavior here
Return New Point() {}
' Return GetFront(location, height, width, depth,
' rotateX, rotateY)
End Get
End Property
Public ReadOnly Property Back() As Point()
Get
' TODO: Need to implement behavior here
Return New Point() {}
' Return GetBack(location, height, width, depth,
' rotateX, rotateY)
End Get
End Property
End Structure

I added an enumeration (CubeSides) so I could refer to the sides of a cube by name. I defined a property indexer to return an array of points representing a specific size, added a property that returns the enclosing bounds of the cube by getting the bounds of a GraphicsPath object, and defined read-only properties representing each side. I stubbed out these properties in terms of as yet unimplemented methods.

Create a 3D Cube Structure for GDI+

Implementing Behaviors

At this point, the bulk of the remaining work is the implementation of constructors and methods for calculating the points needed to describe the sides of a cube. For the most part, I used the constructors to initialize fields, and the side-drawing code is very similar for each of the sides. The most difficult part is the meticulous arithmetic necessary to ensure that all of the edges match. Listing 3 contains the remaining code (including the code already provided) for the Cube structure.

Create a 3D Cube Structure for GDI+

The complete listing is just over 400 lines of code. Rather than cover every single line, I will leave it to you to explore. However, some small changes and points of interest—as well as some interesting GDI+ elements—are worth showcasing. Let's start with the changes:

Most of the property setters have a call to the new method, Changed. Changed reconstructs the GraphicsPath object by calling ConstructPath.

A couple of the constructors (Sub New methods) provide default values for the FRotateX and FRotateY fields. In a class, you could use field initializers like Private FRotateX As RotateHorizontal = RotateHorizontal.Right, but initializers are permitted only on constants in structures.

Now, let's examine the GDI+ features you use to implement the cube:

Using Point: The Point structure contains two integers representing a two-dimensional location in a Cartesian plane, most notably the real estate represented by your monitor's screen. In conjunction with using Point, you defined CubeSize as a structure with a height, width, and depth. When combined with a Point, you can visualize a cube shape.

Using Rectangle: Rectangle is a GDI+ structure that represents a two-dimensional rectangle with four corners. If you take six equally sized rectangles and join them at the edges, you can generate a cube.

Both Point and Rectangle have integer fields and properties. GDI+ defines PointF and RectangleF, which use floating-point numbers. If you desired to be as consistent with GDI+ as possible, you could define a structure (CubeF) that uses floating-point numbers for X, Y, Width, Height, and Depth, as well.

Using GraphicsPath: A GraphicsPath is an open or closed path of points. Sort of like the children's game Connect the Dots, the GraphicsPath represents the dots and GDI+ knows how to connect the dots. Because GDI+ doesn't currently define a Cube primitive, you can define your cube as a collection of points expressed as a GraphicsPath and use GDI+ to connect those dots.

Calculating the Center: Some of the features I found it useful to define include the ability to calculate the 3D center. In two dimensions, the horizontal center is X + Width/2 and the vertical center is Y + Height/2. For a cube, you need to account for the Z axis, or depth.

To approximate the center, each of the constructors adds half the depth multiplied by the number that represents that vertex's aspect ratio. Another means is to request the bounding rectangle for the GraphicsPath and then calculate the center in the usual way. Experiment with my implementation or try using the bounding rectangle to see which means of calculating the center yields the best result.

Constructing the GraphicsPath: A direct way of defining the GraphicsPath was to visualize each face of the cube as a rectangle comprised of lines. All of these lines were then added to a single instance of a GraphicsPath object. (Perhaps a professional game programmer could devise a better algorithm, but this one seems practical.) In ConstructPath, GetBack, GetFront, GetTop, GetBottom, GetRight, and GetLeft are each called and the results are added to an instance of the GraphicsPath object, which is in turn assigned to the field FPath.

As mentioned previously, no method in the Graphics class is named DrawCube, but one is named DrawPath. While consistent with the Cube's progenitor Rectangle, your Cube does not draw itself. Consumers of the Cube can use Graphics.DrawPath, getting the job done with the GraphicsPath object returned by GetCube.

Rendering the Cube with GDI+

Rendering the cube is easy. All you need to do is construct an instance of a Cube structure, pass in the constructor's required arguments, obtain a Graphics object, and call DrawPath, passing the GraphicsPath that represents the Cube. If you want the cube to be present and updated each time a form was repainted, for example, place the call to DrawPath in the Form's OnPaint event handler. Listing 4 demonstrates.

The Pens class is a predefined class with shared instances of Pens. (The Pens class has some great colors. One of mine is AliceBlue.) Figure 1 shows the output from Listing 4.

Figure 1: Output from the Cube Primitive

With a little bit of effort and ingenuity, you can make a simple game sort of like the children's Spyrograph from the 60s. Give it a try. (Hint: Assign a matrix randomly rotated between 0° and 360° to the Graphics object's Transform property, rotating the cube at its center.) Figure 2 shows a sample output from my solution.

Figure 2: Rotate the Cube at Its Center Using a Matrix Object, the Matrix.RotateAt Method, and the Transform Property of the Graphics Class

Graphics Are Easy with GDI+

Graphics are just plain fun. Without graphics we wouldn't have cool software like video games. While it may be very challenging to write today's advanced games from Graphics primitives like the Cube example, this is how such games got started. Modern video games use tools like the DirectX 9 SDK and pre-existing libraries that work with advanced primitives like sprites and wire-framing.

However, you can write visually powerful business solutions using graphics primitives and GDI+. GDI+ makes graphics programming easier than ever. Unfortunately for beginners, some things are easy to do and others require that you to write a couple of hundred lines of code.

Biography

Paul Kimmel is the VB Today columnist, has written several books on .NET programming, and is a software architect. You may contact him at pkimmel@softconcepts.com if you need assistance or are interested in joining the Lansing Area .NET Users Group (glugnet.org).

Top White Papers and Webcasts

Data integrity and ultra-high performance dictate the success and growth of many companies.
One of these companies is BridgePay Network Solutions, a recently launched and rapidly growing financial services organization that allows merchants around the world to process millions of daily credit card transactions. Due to the nature of their business, their IT team needed to strike the perfect balance between meeting regulatory-mandated data security measures with the lowest possible levels of latency and …

How Red Hat Enterprise Linux shrinks total cost of ownership (TCO) compared to Windows
IT organizations face the constant challenge of juggling two almost opposing priorities: continuously delivering business-critical application services while keeping IT expenses in line with budget constraints. The primary function of IT departments is to supply core infrastructure and applications to attract new business, generate revenue, and facilitate profitability - and IT managers strive to meet this goal in spite of …