Click here to Skip to main content
15,392,858 members
Articles / Desktop Programming / WPF
Posted 27 Mar 2008


136 bookmarked

WPF 3D: Part 1 of n

Rate me:
Please Sign up or sign in to vote.
4.91/5 (48 votes)
27 Mar 2008CPOL6 min read
Excursions and deviations into the dark recesses of my mind.


.NET 3.5 introduced a few new language features; oh and there was that little thing called LINQ. But with all the excitement, sometimes a few things get missed. Such as the new 3D elements that are available to WPF developers in .NET 3.5. This article will discuss the use of some of these new 3D related elements that are now in .NET 3.5.

In order to demonstrate some (yeah, I don't use all of the new elements in the attached demo app), I picked something simple. I decided to have a bunch of 3D meshes within a Viewport3D (3D scene) that could be clicked on to open blog entries. It allow users to switch to three different blogs, my own, Josh Smith's and Karl Shifflett's.

Here is what this article contains:

A Video of the Demo App

Due to the nature of 3D, the only way that I can do the attached demo application any justice is to show you a video which shows it in action. As such, please click on the image below to see a video of the demo application in action:

Image 1

Click the image or here to view the video.

I would recommend waiting until the entire video has streamed and then watch it.

The New .NET 3.5 Elements

There are three new 3D related elements in .NET 3.5, each of which is described below. But in order to understand why these new elements are so cool, you need to go back to .NET 3.0 land. In .NET 3.0, ModelVisual3D elements were simple elements, and ModelVisual3D elements did not support the routed event handling capabilities offered by their 2D counterparts. So when working with 3D elements and wanting to respond to some mouse events or perform hit testing, you had to do it manually. Now this sounds OK, but the only place you could actually carry out hit testing or even listen to routed events was actually on the Viewport3D (3D scene) that contained the various ModelVisual3D elements (3D objects).

This worked something like this:

private void viewport_MouseDown(object sender, MouseButtonEventArgs e)
    Viewport3D viewport = (Viewport3D)sender;
    Point location = e.GetPosition(viewport);
    HitTestResult hitResult = VisualTreeHelper.HitTest(viewport, location);
    if (hitResult != null && hitResult.VisualHit == SOME_VISUAL)
        // Hit the visual.

    RayMeshGeometry3DHitTestResult meshHitResult = 
                   hitResult as RayMeshGeometry3DHitTestResult;
    if (meshHitResult != null && meshHitResult.ModelHit == SOME_MODEL)
        // Hit the model.
    if (meshHitResult != null && meshHitResult.MeshHit == SOME_MESH)

        //do something

Now this isn't that bad for one ModelVisual3D element (3D object). But if you have loads, this just isn't that fun. This is why the new ContainerUIElement3D /ContainerUIElement3D elements are cool. They are proper full blown elements that support input, focus, and events. So we don't have to do code like the above any more; we simply wire up a routed event handler and write the appropriate code in the code-behind. Much better. Let's have a look at these new elements in a bit more detail.


ContainerUIElement3D simply provides a container for ModelUIElement3D objects. ContainerUIElement3D is a ModelUIElement3D object, which provides support for input, focus, and events in 3D. Stealing from MSDN, this is an example with two cube ModelUIElement3D elements within a ContainerUIElement3D. Notice the use of the ContainerUIElement3D MouseDown routed event and the ModelUIElement3D MouseDown routed events. Full fledged events on 3D objects, cool!

        <PerspectiveCamera Position="8,3,0" 
                    LookDirection="-8,-3,0" />

    <!-- The container has the two cubes as its children -->
    <ContainerUIElement3D MouseDown="ContainerMouseDown">
                    <AxisAngleRotation3D x:Name="containerRotation" 
                            Axis="0, 1, 0" Angle="0" />

        <!-- Cube 1 -->
        <ModelUIElement3D MouseDown="Cube1MouseDown">
                <TranslateTransform3D OffsetZ="1.5" />

                <GeometryModel3D Geometry="{StaticResource CubeMesh}">
                           Brush="Blue" />

        <!-- Cube 2 -->
        <ModelUIElement3D MouseDown="Cube2MouseDown">
                <TranslateTransform3D OffsetZ="-1.5" />

                <GeometryModel3D Geometry="{StaticResource CubeMesh}">
                           Brush="Green" />

    <!-- Lights -->
            <PointLight Color="White" Position="3, 10, 4" />


As previously stated, these are new elements that provide rendering of a 3D model that supports input, focus, and events. Using the same example as before, notice the ModelUIElement3D MouseDown routed event:

<!-- Cube 2 -->
    <ModelUIElement3D MouseDown="Cube2MouseDown">
            <TranslateTransform3D OffsetZ="-1.5" />

            <GeometryModel3D Geometry="{StaticResource CubeMesh}">
                    <DiffuseMaterial x:Name="cube2Material" Brush="Green" />


Although the demo application doesn't actually use this, I can say a few words about this new element. Basically, the Viewport2DVisual3D element is an element that can be used within a Viewport3D (3D scene), but hosts an interactive 2D Element, such as a Button. I've taken the following example code straight from MSDN. The following example shows how to place a button, a 2-D object, on a 3-D object. Note that you must set the IsVisualHostMaterial attached property on the material on which you wish to have the 2D visual placed.

    <!-- Button on 3D -->
        <!-- Give the plane a slight rotation -->
                    <AxisAngleRotation3D Angle="40" Axis="0, 1, 0" />

        <!-- The Geometry, Material, and Visual for the Viewport2DVisual3D -->
            <MeshGeometry3D Positions="-1,1,0 -1,-1,0 1,-1,0 1,1,0"
                            TextureCoordinates="0,0 0,1 1,1 1,0" 
                            TriangleIndices="0 1 2 0 2 3"/>

            <DiffuseMaterial Viewport2DVisual3D.IsVisualHostMaterial="True" 

        <Button>Hello, 3D</Button>


Demo App

So what does the attached demo app actually do? Well, it looks like the following diagram when it first starts:

Image 2

Where a number of 3D objects (ModelUIElement3D elements) are shown to represent blog entries. Moving the mouse over one of these individual ModelUIElement3D elements causes them to grow in scale, and when the mouse is moved out, they shrink back to their original size.

This is achieved as follows:

<Tools:TrackballDecorator  >
            <PerspectiveCamera x:Name="camera" Position="-2,2,40" 
            LookDirection="2,-2,-40" FieldOfView="90" />

        <ContainerUIElement3D x:Name="container" />

                <DirectionalLight Color="White" Direction="-1,-1,-1"/>

So this sets up the Viewport3D (3D scene) and does the normal 3D stuff like create a Light and a Camera, but it also sets up a ContainerUIElement3D (container to host other ModelUIElement3D elements).

The only other thing to note here is that I am using a TrackballDecorator decorator element. This is not actually part of the .NET 3.0/3.5 frameworks, but is part of a DLL that the WPF 3D team released, called 3dTools, which is an Open Source CodePlex project located right here.

This TrackballDecorator decorator element allows the user to pan and scroll around the entire Viewport3D (3D scene) in 3D space. It's very cool.

In the code-behind, a number of ModelUIElement3D elements are added which represent the blog entries, where each ModelUIElement3D element uses a tesselate (sphere in my case) MeshGeometry3D mesh. This is done something like this:

this.Resources.Add("sphereMesh", Tesselate.Create(10, 10, 5));
ModelUIElement3D sphere1 = 
  CreateSphere(brushes[1], points3D[0].X, points3D[0].Y, points3D[0].Z);
feedsForShapes.Add(sphere1, feeds[0]);
private ModelUIElement3D CreateSphere(Brush materialBrush, double OffsetX,
        double OffsetY, double OffsetZ)

    ModelUIElement3D sphere3D = new ModelUIElement3D();
    sphere3D.MouseEnter += new MouseEventHandler(Sphere_MouseEnter);
    sphere3D.MouseLeave += new MouseEventHandler(Sphere_MouseLeave);
    sphere3D.MouseDown += new MouseButtonEventHandler(sphere3D_MouseDown);
    GeometryModel3D sphere3D_Geom = new GeometryModel3D(
        this.Resources["sphereMesh"] as MeshGeometry3D,
        new DiffuseMaterial(materialBrush));
    sphere3D.Model = sphere3D_Geom;
    Transform3DGroup transGroup = new Transform3DGroup();
    ScaleTransform3D scaleTrans = new ScaleTransform3D(1, 1, 1);
    TranslateTransform3D translateTrans = 
        new TranslateTransform3D(OffsetX, OffsetY, OffsetZ);
    RotateTransform3D rotateTrans = new RotateTransform3D();
    rotateTrans.Rotation = new AxisAngleRotation3D(new Vector3D(0, 1, 0), 1);
    sphere3D.Transform = transGroup;

    return sphere3D;

The actual blog entries are read using a very simple bit of XLINQ, which is as follows:

public List<feedentry> GetFeedEntries(FeedMember feedMember)
        XElement feeds = XElement.Load(GetFeedUrl(feedMember));
        //check that there is some feed entries
        if (feeds.Element("channel") != null)
            var items = (from f in feeds.Element("channel").Elements("item")
                         select new FeedEntry
                             Link = f.Element("link").Value,
                             Title = f.Element("title").Value
            return items.ToList();
            return null;

    catch(Exception ex)
        System.Diagnostics.Debug.WriteLine(ex.Message + "\r\n");
        return null;

The next section talks a little bit more about how the tesselates are created.

Tesselate Creation

Within WPF, there are no standard meshes that can be used as GeometryModel3D properties. Some times, there are example meshes; for example, DirectX has a well-known teapot. No such luck in WPF. You have to do it manually. The following code shows how you can create a simple square MeshGeometry3D mesh:

<!-- Simple flat, square surface -->
         TriangleIndices="0,1,2    2,3,0"
         TextureCoordinates="0,1 1,1 1,0 0,0"
         Positions="-0.5,-0.5,0     0.5,-0.5,0    0.5,0.5,0    -0.5,0.5,0" />

Perhaps this could do with a little explanation. The Positions property is the position in 3D space X ,Y, Z planes. We can see that if this was mapped out, we would get something like:

Image 3

And the TriangleIndices property is the indices of the triangles that make up GeometryModel3D.Geometry; in this case, a simple square which is made from two separate triangles. This is how 3D works. Let's see these two triangles (basically, triangles are the building blocks of any 3D mesh):

Image 4

But what I wanted for this article was some nice sphere. Or to be more precise, a tessalate.

Tesselation: A tessellation or tiling of the plane is a collection of plane figures that fills the plane with no overlaps and no gaps. One may also speak of tessellations of the parts of the plane or of other surfaces.


But what does that really mean in terms of a 3D mesh? Well, consider the following image:

Image 5

We can see that dividing the sphere into divisions both around (theta) and up from the bottom pole to the top pole (phi), we can create rectangles. And we can treat each rectangle as we did with the above simple square MeshGeometry3D. This would look something like the following figure. We can see the triangles that are forming our mesh.

Image 6

There is a helper class called tesselate in the attached demo project which produces the appropriate MeshGeometry3D; here is the main part of that class:

/// <summary>
/// Tessellates the sphere and returns a MeshGeometry3D representing the 
/// tessellation based on the given parameters
/// </summary>
/// <param name="tDiv">theta Divisions</param>
/// <param name="pDiv">phi divisions</param>
/// <param name="radius">radius</param>
public static MeshGeometry3D Create(int tDiv, int pDiv, double radius)
    double dt = DegToRad(360.0) / tDiv;
    double dp = DegToRad(180.0) / pDiv;

    MeshGeometry3D mesh = new MeshGeometry3D();

    for (int pi = 0; pi <= pDiv; pi++)
        double phi = pi * dp;

        for (int ti = 0; ti <= tDiv; ti++)
            // we want to start the mesh on the x axis
            double theta = ti * dt;

            mesh.Positions.Add(GetPosition(theta, phi, radius));
            mesh.Normals.Add(GetNormal(theta, phi));
            mesh.TextureCoordinates.Add(GetTextureCoordinate(theta, phi));

    for (int pi = 0; pi < pDiv; pi++)
        for (int ti = 0; ti < tDiv; ti++)
            int x0 = ti;
            int x1 = (ti + 1);
            int y0 = pi * (tDiv + 1);
            int y1 = (pi + 1) * (tDiv + 1);

            mesh.TriangleIndices.Add(x0 + y0);
            mesh.TriangleIndices.Add(x0 + y1);
            mesh.TriangleIndices.Add(x1 + y0);

            mesh.TriangleIndices.Add(x1 + y0);
            mesh.TriangleIndices.Add(x0 + y1);
            mesh.TriangleIndices.Add(x1 + y1);

    return mesh;

Can't remember exactly where this code came from, but it was more than likely from the WPF 3D team's blog:


  • 27/03/08: Initial release.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Sacha Barber
Software Developer (Senior)
United Kingdom United Kingdom
I currently hold the following qualifications (amongst others, I also studied Music Technology and Electronics, for my sins)

- MSc (Passed with distinctions), in Information Technology for E-Commerce
- BSc Hons (1st class) in Computer Science & Artificial Intelligence

Both of these at Sussex University UK.


I am lucky enough to have won a few awards for Zany Crazy code articles over the years

  • Microsoft C# MVP 2016
  • Codeproject MVP 2016
  • Microsoft C# MVP 2015
  • Codeproject MVP 2015
  • Microsoft C# MVP 2014
  • Codeproject MVP 2014
  • Microsoft C# MVP 2013
  • Codeproject MVP 2013
  • Microsoft C# MVP 2012
  • Codeproject MVP 2012
  • Microsoft C# MVP 2011
  • Codeproject MVP 2011
  • Microsoft C# MVP 2010
  • Codeproject MVP 2010
  • Microsoft C# MVP 2009
  • Codeproject MVP 2009
  • Microsoft C# MVP 2008
  • Codeproject MVP 2008
  • And numerous codeproject awards which you can see over at my blog

Comments and Discussions

GeneralMy vote of 5 Pin
Azim Zahir15-Jul-12 19:03
MemberAzim Zahir15-Jul-12 19:03 
GeneralThank you for this series Pin
Mazen el Senih4-Apr-12 6:44
professionalMazen el Senih4-Apr-12 6:44 
GeneralLink to video Broken Pin
DaveAuld27-Dec-09 22:03
professionalDaveAuld27-Dec-09 22:03 
GeneralRe: Link to video Broken Pin
Sacha Barber27-Dec-09 22:57
MemberSacha Barber27-Dec-09 22:57 
GeneralRe: Link to video Broken Pin
DaveAuld30-Dec-09 23:28
professionalDaveAuld30-Dec-09 23:28 
GeneralRe: Link to video Broken Pin
Sacha Barber31-Dec-09 0:18
MemberSacha Barber31-Dec-09 0:18 
GeneralNice Article Pin
Razan Paul (Raju)24-Mar-09 23:49
MemberRazan Paul (Raju)24-Mar-09 23:49 
GeneralRe: Nice Article Pin
Sacha Barber25-Mar-09 2:10
MemberSacha Barber25-Mar-09 2:10 
QuestionDo you have example to translate/pan 3D? Pin
wmjcomcn6-Jul-08 19:07
Memberwmjcomcn6-Jul-08 19:07 
AnswerRe: Do you have example to translate/pan 3D? Pin
Sacha Barber7-Jul-08 10:26
MemberSacha Barber7-Jul-08 10:26 
GeneralRe: Do you have example to translate/pan 3D? Pin
wmjcomcn7-Jul-08 18:36
Memberwmjcomcn7-Jul-08 18:36 
GeneralRe: Do you have example to translate/pan 3D? Pin
Sacha Barber8-Jul-08 8:47
MemberSacha Barber8-Jul-08 8:47 
GeneralRe: Do you have example to translate/pan 3D? Pin
wmjcomcn10-Jul-08 20:51
Memberwmjcomcn10-Jul-08 20:51 
GeneralRe: Do you have example to translate/pan 3D? Pin
Sacha Barber10-Jul-08 21:30
MemberSacha Barber10-Jul-08 21:30 
GeneralVery sexy! Pin
Member 13566462-Jun-08 20:10
MemberMember 13566462-Jun-08 20:10 
GeneralRe: Very sexy! Pin
Sacha Barber2-Jun-08 21:47
MemberSacha Barber2-Jun-08 21:47 
GeneralWow I missed it Pin
Rama Krishna Vavilala14-Apr-08 4:52
MemberRama Krishna Vavilala14-Apr-08 4:52 
GeneralRe: Wow I missed it Pin
Sacha Barber14-Apr-08 20:47
MemberSacha Barber14-Apr-08 20:47 
GeneralRe: Wow I missed it Pin
Sacha Barber10-Jun-08 2:05
MemberSacha Barber10-Jun-08 2:05 
GeneralRe: Wow I missed it Pin
Rama Krishna Vavilala10-Jun-08 3:32
MemberRama Krishna Vavilala10-Jun-08 3:32 
GeneralRe: Wow I missed it Pin
Sacha Barber10-Jun-08 3:51
MemberSacha Barber10-Jun-08 3:51 
Generalnice but ... Pin
Icebreaker_2-Apr-08 2:52
MemberIcebreaker_2-Apr-08 2:52 
GeneralRe: nice but ... Pin
Sacha Barber2-Apr-08 3:09
MemberSacha Barber2-Apr-08 3:09 
QuestionWhy not show Viewport2DVisual3D in your demo app? Pin
Dustin Metzgar31-Mar-08 15:58
MemberDustin Metzgar31-Mar-08 15:58 
AnswerRe: Why not show Viewport2DVisual3D in your demo app? Pin
Sacha Barber31-Mar-08 21:28
MemberSacha Barber31-Mar-08 21:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.