Following the announcement made today on the scene on MIX 2011 I’ve prepared an example for the purpose of showing the new powerful 3D available in the beta bits. Remembering ancient days when I enjoyed myself writing small programs to plot 3D functions on the screen of my Amiga 500, I decided to follow again this path and put together a few lines of code to draw the sample functions in Silverlight (so this pairs with the fractals experiments made in occasion of MIX 2009).
Drawing 3D scenes in Silverlight is not so intuitive as it is in WPF due the fact that the API exposed by the plugin is on a lower level than the WPF one. The team choosed to implement an API that is very close to the XNA framework one. So to create objects in 3D space you have to deal with lot of triangles, vertex and pixel shaders and other exotic stuff. Nonetheless, once you understand the way the thing works the results don’t delude you.
Basically to create a 3D scene you have to put in the markup a special element named DrawingSurface. This element is able to render a 3D set. Every time it surface needs to be rendered it raises an OnDraw event passing to the handler and instance of a GraphicsDevice that is useful to actually draw the scene on the surface. In the example a class named Scene is used to setup the 3D environment (camera, viewing direction and elements in the scene) do inside the OnDraw event the Scene’s Draw method is called to perform the draw.
Inside the Scene class every element draw itself. In my case the scene is populated only by FunctionPlot class that contains the function to draw and receives some parameters. During the rendering is is possible to apply some transformation matrices that apply rotation, translation and scaling.
The drawing of the function is probably the simplest thing. While the x and y coordinates run on the plane the vertexs of a square are build. The area of every square is divided in two triangles.
A detailed explanation of how the 3D pipeline works is out of the scope of this article and should take an huge number of posts, not few lines. For now I give you the code I wrote for this example and I hope you appreciate like me the beautiful images that it creates.
Download: SLPG.3D.zip (256kb)