<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Robotic Pandas</title>
	<atom:link href="http://mcdirmid.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://mcdirmid.wordpress.com</link>
	<description>On abstractions for building next generation user interfaces</description>
	<lastBuildDate>Wed, 28 Dec 2011 19:53:07 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='mcdirmid.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://0.gravatar.com/blavatar/2d09bdacd2a2f4ae9b6fadd519554760?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Robotic Pandas</title>
		<link>http://mcdirmid.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://mcdirmid.wordpress.com/osd.xml" title="Robotic Pandas" />
	<atom:link rel='hub' href='http://mcdirmid.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Designing a GPU-oriented geometry abstraction &#8211; Part Three</title>
		<link>http://mcdirmid.wordpress.com/2009/11/24/designing-a-gpu-oriented-geometry-abstraction-part-three/</link>
		<comments>http://mcdirmid.wordpress.com/2009/11/24/designing-a-gpu-oriented-geometry-abstraction-part-three/#comments</comments>
		<pubDate>Tue, 24 Nov 2009 03:03:43 +0000</pubDate>
		<dc:creator>mcdirmid</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://mcdirmid.wordpress.com/2009/11/24/designing-a-gpu-oriented-geometry-abstraction-part-three/</guid>
		<description><![CDATA[In this post, I want to propose an geometry abstraction along with an example on how it works. But first I’ll clarify the goals of the abstraction: Should support functional composition and transformation. This basically means that it will support operations like a + b where a and b are geometry values and the result [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mcdirmid.wordpress.com&amp;blog=8484952&amp;post=95&amp;subd=mcdirmid&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post, I want to propose an geometry abstraction along with an example on how it works. But first I’ll clarify the goals of the abstraction:</p>
<ul>
<li>Should support functional composition and transformation. This basically means that it will support operations like <em><strong>a </strong>+<strong> b </strong></em>where <strong><em>a</em></strong> and <strong><em>b</em></strong> are geometry values and the result is a geometry value or <strong><em>f</em></strong>(<strong><em>a</em></strong>) where <strong><em>f</em></strong> is a pure function from geometry value to geometry value.</li>
<li>A geometry value can be rendered by one call without any other companion values.</li>
<li>Very limited magic and hard coded properties. Only properties relevant for rendering, vertex position, pixel color, and topology, are semi-magical in that a render call will look for them. All other properties and all calculations, such as those that specify layout or apply lighting, are non-magical and expressed explicitly by manipulating/transforming geometry values.</li>
</ul>
<p>The above goals ensure that the abstraction is easy to use and that we can easily modularize geometry-building code using standard in-language constructs such as procedures, objects, or functions (including high-order functions). Now, let’s introduce the abstraction via an example using a neutral syntax:</p>
<p><span id="more-95"></span></p>
<pre class="code">// recipe for face
// create topology with 4 vertices and 2 primitives
face = new_topology&lt;D3&gt;(4, 2);
// set indices of topology primitives to (0,1,2) and (0,2,3)
// per_primitive creates a function applied to all primitives by their integer id.
face = set_indices(face, per_primitive(id =&gt; (0, 1+id, 2+id)));</pre>
<p>The above code defines a face as a primitive triangle topology (D3 = 3 points) with four vertices and two triangles. The code then defines an index buffer that differs according to primitive ids (per_primitive…). As a result, there are two primitives formed from vertices (0,1,2) and (0,2,3). Now we define the spatial properties of a face:</p>
<pre class="code">// set vertex positions to 0:(-1,-1,0), 1:(-1,+1,0), 2:(+1,+1,0), 3:(+1,-1,0)
// per_vertex creates a function applied to all vertices by their vertex id.
face = make_position(face, per_vertex(id =&gt; (id/2*2-1,(id+1)%4/2*2-1,0)));
// face texture coordinates are similar to its positions, except in 2D and from 0,0 to 1,1.
face = make_texcoord(face, per_pixel((face.position.xy + 1) / 2));
// make face normal, just point it along the -z axis.
face = make_normal(face, (0,0,-1));
// give face a transform, initially this transform is identity.
face = make_transform(face, identity);</pre>
<p>Positions are defined per vertex using a formula over vertex ids, which could have also been expressed as a table indexed by vertex ids if we wanted (formulas are more compact). Texture coordinates are defined according to the 2D position and shifted so that they are from (0,0) to (1,1) rather than (-1,-1) to (+1,+1). Additionally, texture coordinates are defined on a per-pixel basis, so that expressions that depend on them are never interpolated a the pixel shader. One normal is defined for the face and used as the normal for all of the face’s vertices and pixels. Finally, the face is given a matrix transform property with an initial value of the identity matrix. This call also ensures that the position and normal of the face are transformed appropriately according to the transformation matrix (normal transformation will ignore the matrix’s translation components). Now to form a cube from the face:</p>
<pre class="code">// duplicate the face 6 times to create a cube.
cube = duplicate(6, face);
// each face is translated out to (0,0,-1) and rotated according to its id
// note: we use open gl row major transform matrices, so prepend the matrices.
// transforms update position and normals,
// for normals the translate component is ignored when the transform is applied, of course.
// face 0 is rotated 0.0pi around (0,1,0)
// face 1 is rotated 0.5pi around (1,0,0)
// face 2 is rotated 0.5pi around (0,1,0)
// face 3 is rotated 1.0pi around (1,0,0)
// face 4 is rotated 1.5pi around (0,1,0)
// face 5 is rotated 1.5pi around (1,0,0)
cube = prepend_transform(cube, per_duplicate1(id =&gt;
  rotate((0+id%2,1-id%2,0), (i/3+(id%3).Min(1))*.5pi) * translate(0,0,-1));</pre>
<p>The first statement duplicates the face six times to form the beginnings of a cube. The next statement prepends a transform that translates/rotates the position and normal of each face according to its ID, which is simply its duplicate ID. Now…we have a complete cube! Incidentally, we could just encapsulate all of this code into a simple make_cube function, or better yet, just use the cube value as a prototype anytime we need a cube value. Continuing on, we color and light the cube:</p>
<pre class="code">// makes the cube ready for rendering by giving it a color
// property, color is initially transparent
cube = make_color(cube, transparent);
// prepare cube for lighting, causes color to be computed via lighting equations.
cube = prepare_lighting(cube);
// prepare materials.
cube = add_material(cube, specular(power=3));
cube = add_material(cube, diffuse(knob=100%,ambient=100%));
// set color of cube according to face id, so each face has a different color.
cube = set_material_color(cube, per_duplicate1(id =&gt; color_table[id]));
// light cube with an ambient light at 50% of white.
lights = ambient_light(color = .5 * white);
// directional light 50% white at a weird angle
lights = add_light(lights, directional_light(color = .5*white, direction = (-.5,-.5,+1)));
// spot light 50% white directed straight on.
lights = add_light(lights, spot_light(color = .5*white, direction=(0,0,+1),
                                      position=(0,0,-10),outer=4dg, inner=2dg));
// set the lights for this cube, same lights can be applied to other geometries.
cube = apply_lights(cube, lights);</pre>
<p>This code adds a color property to the cube (before it had none!) allowing it to be rendered, or for our purposes, prepared for lighting. The prepare_lighting call adds a bunch of properties related to lighting as well as ensuring that the cube’s color is now computed via a lighting algorithm (configured by lighting properties). The next line’s adds diffuse and specular materials to the cube, set a material color for each face, and creates lights to light the cube. The lights value is used to light the cube geometry value but could also be applied light other geometry values in the same scene.</p>
<p>Stepping back, lighting is a fairly complicated algorithm and there are many different was to do it. For this reason, lighting is not built into the geometry abstraction, all of the lighting related functions (prepare_lighting, apply_lights, add_material) are all explicitly defined outside of the geometry abstraction and alternative lighting schemes can be defined in the same way. To finish up the rendering:</p>
<pre class="code">// rotation provided by world matrix, can be updated via user input.
cube = prepend_transform(cube, world);
// finally, a camera...
camera = perspective_camera(position = (0,0,-4), fov = .25pi);
cube = apply_camera(cube, camera);
// we get a cube, multi color faces, lit with three lights.
render(cube);</pre>
<p>The world matrix provides for rotation and scaling, which will trickle down to the matrix that is used to transform face normal’s and vertex positions. A camera is created and then applied to the cube to provide for standard 3D view and projection matrices, and finally the cube is rendered. As a bonus, let’s apply <a href="http://en.wikipedia.org/wiki/Normal_mapping" target="_blank">normal mapping</a> to the cube faces by updating the normal of each face to include the results of a texture lookup:</p>
<pre class="code">map = convert_to_normal_map(folded_paper_texture);
// extract normals from textures
// per-pixel texture coordinates to sample per-pixel normals.
cube = set_normal(cube, map[cube.texcoord]).rotate(cube.normal.angle_between((0,0,-1)));</pre>
<p>Finally, you might get something like this:</p>
<p><a href="http://mcdirmid.files.wordpress.com/2009/11/image.png"><img style="display:inline;border:0;" title="image" src="http://mcdirmid.files.wordpress.com/2009/11/image_thumb.png?w=244&#038;h=244" border="0" alt="image" width="244" height="244" /></a></p>
<p>I haven’t implemented this geometry abstraction yet, so the above rendering was developed from the way Bling is today.</p>
<p>In the above code, we are building up the type of the geometry value along with its structure. The type of the value indicates what transformations the geometry value supports (e.g., setting an existing property’s value) and prevents invalid transformations from occurring (e.g., applying normal-based lighting without specifying a normal!). However, I’m not aware of any static type system that allows us to mix and match independent types, so I’ll probably implement this through dynamic typing in C#.</p>
<p>Another issue that I need to address in more detail is that of what value one is referring to during a transformation. There is the value embedded in the value we are building from and the final value after the value is completed and when it undergoes processing (obtained from an implicit self parameter). In the above code, we mostly use the former semantics, but some operations obviously depend on the latter semantics; e.g., the normal I refer to in a lighting calculation is the final transformed version of the normal and not the current normal of a lighting calculation. Ah, kind of a headache.</p>
<p>I promised to talk about geometry shading in my last post, but it will have to wait. Basically, the constituent values used to build up a geometry value are not necessarily constants and can be dynamic values from the external environment; e.g., a slider thumb’s state, a texture sample, or a noise value. When the cube value is processed, if a dynamic value is encountered that affects the topology of the geometry, then a geometry shader is needed. We’ll still have to add some operations to transform the topology (possibly with a different primitive type) and to “step” the geometry when obvious state is involved. I’ll definitely talk about this next time.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mcdirmid.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mcdirmid.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mcdirmid.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mcdirmid.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mcdirmid.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mcdirmid.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mcdirmid.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mcdirmid.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mcdirmid.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mcdirmid.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mcdirmid.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mcdirmid.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mcdirmid.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mcdirmid.wordpress.com/95/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mcdirmid.wordpress.com&amp;blog=8484952&amp;post=95&amp;subd=mcdirmid&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mcdirmid.wordpress.com/2009/11/24/designing-a-gpu-oriented-geometry-abstraction-part-three/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6829d6ae4bda3a38255a96637b944a5a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mcdirmid</media:title>
		</media:content>

		<media:content url="http://mcdirmid.files.wordpress.com/2009/11/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Designing a GPU-oriented geometry abstraction &#8211; Part Two.</title>
		<link>http://mcdirmid.wordpress.com/2009/11/23/designing-a-gpu-oriented-geometry-abstraction-part-two/</link>
		<comments>http://mcdirmid.wordpress.com/2009/11/23/designing-a-gpu-oriented-geometry-abstraction-part-two/#comments</comments>
		<pubDate>Mon, 23 Nov 2009 03:19:52 +0000</pubDate>
		<dc:creator>mcdirmid</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://mcdirmid.wordpress.com/2009/11/23/designing-a-gpu-oriented-geometry-abstraction-part-two/</guid>
		<description><![CDATA[My last post described the problem of crafting an appropriate geometry abstraction for Bling. Bling previously solved the code problem for vertex and pixel shading, but lacked decent geometry input abstractions as well as an abstraction that supported geometry shading. The last post proposes giving geometry its own abstraction, but I was a bit hesitant [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mcdirmid.wordpress.com&amp;blog=8484952&amp;post=91&amp;subd=mcdirmid&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>My last post described the problem of crafting an appropriate geometry abstraction for Bling. Bling previously solved the code problem for vertex and pixel shading, but lacked decent geometry input abstractions as well as an abstraction that supported geometry shading. The last post proposes giving geometry its own abstraction, but I was a bit hesitant in including properties within the geometry, which leads to either a problem of flexibility or static safety. I think its time to back up a bit and describe the abstractions that are relevant to a traditional programmable rendering pipeline:</p>
<ul>
<li><strong><em><span id="more-91"></span>Pixels </em></strong>as children of geometric primitives. The position of a pixel is fixed and a pixel shader only specifies each pixel’s color and optional depth. It often makes sense to have other properties beyond color and depth at the pixel level for better shading computations; e.g., a normal that is computed on a per-pixel basis via a <a href="http://en.wikipedia.org/wiki/Parametric_surface" target="_blank">parametric equation</a> or via <a href="http://en.wikipedia.org/wiki/Normal_mapping" target="_blank">normal mapping</a>. Other properties can be accessed from previous vertex and geometry shading phases, where interpolation is used to determine the value of the property from the value of the property in the enclosing primitive’s vertices. Quality improves when properties are computed on a per-pixel basis rather than interpolated; e.g., consider <a href="http://en.wikipedia.org/wiki/Phong_shading" target="_blank">Phong</a> vs. <a href="http://en.wikipedia.org/wiki/Gouraud_shading" target="_blank">Gouraud</a> shading.</li>
<li><strong><em>Vertices</em></strong> as used to define primitives. A vertex shader specifies the position of each vertex, and will compute per-vertex properties that are later used in later geometry and pixel shading.</li>
<li><strong><em>Primitives</em></strong> that are used to form complete topologies. A primitive is either of a point, line, or triangle topology, with triangle being the primitive that most commonly reaches the rendering stage. A primitive is defined by multiple vertices, and encloses multiple pixels. Geometry shading works as a primitive translator, where one primitive can be translated into zero or more primitives of possibly a different topology. Primitives created during geometry shading are defined by specifying their vertices.</li>
<li>A <strong><em>topology</em></strong> as a collection of primitives. Its initial definition is as a set of vertices, a topology for the vertices, and optionally an index buffer to allow for arbitrary vertex sharing between primitives, or an implicit adjacency relationship with explicit breaks.</li>
<li>A <strong><em>geometry</em></strong> as a topology + vertex layout properties. Geometry shading updates both vertex topology and properties, hence it is modifying the entire geometry. Technically, geometry does not include pixel color, which is more of a skin around the geometry, but we can throw pixel color into a geometry abstraction for completeness, although a term like object might be more appropriate to describe geometry + skin.</li>
</ul>
<p>At the end of the day, only three properties need to be explicitly specified during shading to accommodate rendering: a geometry as a topology of vertices to form primitives, a position for each vertex, and a color for each pixel in each primitive.</p>
<p>What we are looking for in a geometry abstraction is to allow a single value <strong><em>g</em></strong> that can by itself undergo rendering (e.g., <em>render</em>(<strong><em>g</em></strong>)) where the pixel, vertex, and geometry shader can all be inferred by the composition of <strong><em>g</em></strong>. As a value, <strong><em>g</em></strong> explicitly encodes everything needed for shader generation and is formed through pure functional programming techniques that include composition and transformation. To meet the rendering requirement, <strong><em>g</em></strong> not only carries around a formula that defines vertex topology, but also the formula for each vertex’s position and the formula for each pixel’s color. These formulas in turn can depend on secondary properties that are subject to transformations that are applied to the geometry or state defined outside of the geometry; e.g., a slider’s thumb position.</p>
<p>As described in the last post, we can define an abstraction for geometry that supports composition, duplication, and transformation. Ideally, rendering could then involve forming a geometry in a clean functional way through multiple compositions and transformations, and passing the resulting geometry into a render command. Transformations not only include modifying the layout of the geometry by rotating, scaling, and translating it, but also applying color and lighting to the geometry and the pixels contained within it, or whatever else is required for a complete rendering specification. Lighting could even be applied to the constituent parts of a geometry before they are composed. The various properties needed to make this possible include thinks like diffuse, specular, glass, and refractive materials as well as additional non-geometry constituents such as directional, ambient, and spot lights. Essentially, the geometry would then become a mini-<a href="http://en.wikipedia.org/wiki/Scene_graph" target="_blank">scene graph</a>.</p>
<p>Scene graphs are common in retained graphics APIs such as <a href="http://blogs.msdn.com/wpf3d/" target="_blank">WPF 3D</a> and <a href="http://java.sun.com/javase/technologies/desktop/java3d/" target="_blank">Java 3D</a>. Basically, a scene graph is a graph of the elements that affect scene rendering, and then becomes the basis for what is shown on the screen. Since we are only interested in what can be efficiently rendered in a shader pipeline, we have to keep the graph nodes mostly homogeneous: duplicating and transforming a geometry in the graph is fine, but composing completely different geometries with different lighting schemes is probably not going to work in the context of one rendering call (instead, render the geometries in separate rendering calls).</p>
<p>The primary difference then with my previous geometry abstraction is that this new geometry embeds properties and transformations at every level of composition. A level in a geometric composition can omit or duplicate properties from a higher level, and transformations (e.g., lighting or layout) should input a property from the lowest level that it exists in the geometry that the transformation is attached to; e.g., a normal property at the pixel level is preferred from a normal property at the vertex level as it is more accurate for lighting computations. The problem with this approach is that we can lose static typing: a property might not exist at any level, then what? Right now I’m willing to live with dynamic checking since it will occur relatively early in Bling when code is generated at application startup.</p>
<p>That’s it for now. Geometry shading will fall out of transformations that cannot be resolved statically. I’ll talk about this in my next post.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mcdirmid.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mcdirmid.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mcdirmid.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mcdirmid.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mcdirmid.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mcdirmid.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mcdirmid.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mcdirmid.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mcdirmid.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mcdirmid.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mcdirmid.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mcdirmid.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mcdirmid.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mcdirmid.wordpress.com/91/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mcdirmid.wordpress.com&amp;blog=8484952&amp;post=91&amp;subd=mcdirmid&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mcdirmid.wordpress.com/2009/11/23/designing-a-gpu-oriented-geometry-abstraction-part-two/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6829d6ae4bda3a38255a96637b944a5a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mcdirmid</media:title>
		</media:content>
	</item>
		<item>
		<title>Designing a GPU-oriented geometry abstraction &#8211; Part One.</title>
		<link>http://mcdirmid.wordpress.com/2009/11/20/designing-a-gpu-oriented-geometry-abstraction-part-one/</link>
		<comments>http://mcdirmid.wordpress.com/2009/11/20/designing-a-gpu-oriented-geometry-abstraction-part-one/#comments</comments>
		<pubDate>Fri, 20 Nov 2009 04:43:51 +0000</pubDate>
		<dc:creator>mcdirmid</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://mcdirmid.wordpress.com/2009/11/20/designing-a-gpu-oriented-geometry-abstraction-part-one/</guid>
		<description><![CDATA[One the inputs of rendering via programmable shading on a modern graphics card is a collection of vertices associated with some per-vertex properties used in shader computations. When programming the GPU, this collection of vertices is commonly abstracted as a vertex buffer, which is essentially just a bag of bytes. The collection of vertices describes [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mcdirmid.wordpress.com&amp;blog=8484952&amp;post=89&amp;subd=mcdirmid&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>One the inputs of rendering via programmable shading on a modern graphics card is a collection of vertices associated with some per-vertex properties used in shader computations. When programming the GPU, this collection of vertices is commonly abstracted as a vertex buffer, which is essentially just a bag of bytes. The collection of vertices describes a primitive point, line, or triangle topology along with an optional index buffer (if triangle) that describes vertex sharing.  Again, the abstractions for describing these topologies are very weak and essentially amount to flags and arrays, although we can informally describe to the vertex buffer plus its primitive topology description as a <em><strong>geometry</strong></em>. Each vertex first individually undergoes processing in a vertex shader, and then (optionally) per-primitive (point, line, or triangle) in a <em>geometry shader</em> where a new geometry can be specified with fewer or more vertices or even a completely different topology. After vertex and geometry shading, the position of each vertex must be specified. Finally, each pixel of the rasterized primitive is processed by a pixel shader to determine its color. This is a simplification, the GPU supports other features such as instancing, where we reuse the vertex buffer multiple times in a single rendering, and geometry shader stream out, where we save the result of vertex/geometry shading for later re-use.</p>
<p><span id="more-89"></span></p>
<p><a href="http://bling.codeplex.com/" target="_blank">Bling</a> does a good job of abstracting vertices and pixels: in Bling shader code one value represents both the vertex and pixel, where the vertex position and pixel color are specified with respect to this value. Bling infers whether the code is referring to a vertex or pixel based on a simple dependency analysis: we are referring to a pixel whenever we refer to anything that is only available in the pixel shader, otherwise we are referring to a vertex and the computation result (if used in the pixel shader) will be interpolated based on the analogous results in the primitive’s other vertices. However, Bling’s vertex/pixel abstraction breaks down when dealing with geometry: the input of a a rendering is simply the vertex count and primitive data and Bling has no high-level geometry abstraction. Bling’s lack of a geometry abstraction prevents geometries from being manipulated, composed, and constructed at a high-level, and prevents geometry shaders from being expressed at all unless shader partitioning is expressed explicitly. And this is a pity because geometry shaders can do so many cool things such as dynamically forming fur, hair, feathers, sparkles, blobs, and so on. We definitely need to make manipulating geometries easier.</p>
<p>So here is my new realization: give geometries their own abstraction in Bling, defined as one of the following:</p>
<ul>
<li>The atomic case is a a collection of adjacent primitives. Actually, the only things that need to be specified for this primitive geometry is the number of vertices, vertex adjacency (if more than one primitive is defined), and primitive topology. Vertex properties such as positions and normals are not included as they will be inferred via dependency analysis within the shader. Examples: the face of a cube (four vertices to define two triangles) or the result of sampling a <a href="http://en.wikipedia.org/wiki/Parametric_surface" target="_blank">parametric surface</a> such as a sphere.</li>
<li>A <strong>composition</strong> of two different geometries (gn = g0 + g1). The geometries composed must be of the same primitive topology. Example: we could compose a face with a four simple triangles to form a pyramid.</li>
<li>A <strong>duplication</strong> of the same geometry N times (gn = N * g0). We define this separately from geometry composition as it could correspond (but might not depending on efficiency) to geometry instancing in the GPU API. For duplication to be meaningful, each duplicated geometry will always undergo a transformation based on the duplication index. Example: a face is duplicated four times to form a cube, or duplicating a cube N times to do some crude voxel rendering.</li>
<li>A <strong>transformation</strong> of one geometry’s properties (gn = f(g0)). This is a bit difficult to define since there is no explicit common set of vertex properties, and indeed a vertex might not need a normal or even a position if it is not going to be rendered. However, the most common transformations will be on the position and normal, as the geometry is translated, scaled, and rotated. Example: rotating a face in 6 different ways to represent each face of a cube.</li>
</ul>
<p>The benefit of this approach is immediately apparent: depending on our need we can define geometries mathematically or load them from a mesh. As properties aren’t included explicitly in the geometry, we can mix and match separate geometries as long as they share the same topology. We can then synthesize the index buffer (if needed) automatically, removing this burden from the user, and infer where geometry instancing occurs.</p>
<p>Unfortunately, vertex properties are more difficult to specify. Before, each vertex had one vertex ID and an optional instance ID, which we would use to compute the vertex’s position and pixel’s color. These could then be used as indexes into a table (in the case of a mesh) to lookup initial values for properties like position and normal, or they could be used in more rich computations; e.g., computing a per-pixel normal from the derivative of a parametric surface. At any rate, we inferred what properties to include in the vertex buffer in a way that allowed an expressed computation to span the CPU and GPU, which is a very good feature from an optimization and reuse perspective.  Now if we allow geometries to be composed, duplicated, and transformed, vertex addressing obviously becomes much more difficult when inferring properties. There are few directions that we could go in to solve this problem:</p>
<ol>
<li>We could assign an ID to a vertex based on the order that it was defined in a composition, but often vertex properties are defined relative to their geometries, and such a scheme would basically ruin reuse of code of that computes properties for a certain composed geometry.</li>
<li>We could come up with some hierarchical Id scheme. However, vertices are generally thrown all together (in the vertex shader at least), and as such it would be very difficult to reason about vertices whose IDs are not homogenous.</li>
<li>The other obvious option is to embed properties in geometries, which would solve the geometry reuse problem but then would tie geometries down to a common set of properties that they had to share in order to be combined. Yet this might be reasonable if the set of per-vertex properties are relatively fixed and it was easy to deal with exceptions easily. Whatever properties are declared do not necessarily correspond to what properties go in the vertex buffer; e.g., the position and normal properties of a sampled parametric surface can refer to dynamic CPU-only values (such as a slider’s position), where inference would synthesize the vertex buffer accordingly to include only static values. I’m still thinking about this problem but I guess I’m working in the direction of somehow re-introducing per-vertex properties, although I might have to throw away dynamic typing to make it work in C#’s type system (hopefully, generics will be enough).</li>
</ol>
<p>Any solution that I come with has to play friendly with geometry shaders, which have the ability transform geometries based on dynamic information. I’ll get into this with my next post.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mcdirmid.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mcdirmid.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mcdirmid.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mcdirmid.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mcdirmid.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mcdirmid.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mcdirmid.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mcdirmid.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mcdirmid.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mcdirmid.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mcdirmid.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mcdirmid.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mcdirmid.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mcdirmid.wordpress.com/89/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mcdirmid.wordpress.com&amp;blog=8484952&amp;post=89&amp;subd=mcdirmid&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mcdirmid.wordpress.com/2009/11/20/designing-a-gpu-oriented-geometry-abstraction-part-one/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6829d6ae4bda3a38255a96637b944a5a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mcdirmid</media:title>
		</media:content>
	</item>
		<item>
		<title>Swizzling in C# via Bling</title>
		<link>http://mcdirmid.wordpress.com/2009/10/30/swizzling-in-c-via-bling/</link>
		<comments>http://mcdirmid.wordpress.com/2009/10/30/swizzling-in-c-via-bling/#comments</comments>
		<pubDate>Fri, 30 Oct 2009 04:08:20 +0000</pubDate>
		<dc:creator>mcdirmid</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://mcdirmid.wordpress.com/2009/10/30/swizzling-in-c-via-bling/</guid>
		<description><![CDATA[Swizzling is a GPU-supported operation that allows you to cheaply reorganize and repeat elements of a vector during an operation. Given its efficiency, it is very important to support swizzling in a language that targets GPUs. HLSL has special syntax where any scalar or vector can be swizzled; e.g., p.xyz takes a vector4 and returns [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mcdirmid.wordpress.com&amp;blog=8484952&amp;post=88&amp;subd=mcdirmid&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Swizzling is a GPU-supported operation that allows you to cheaply reorganize and repeat elements of a vector during an operation. Given its efficiency, it is very important to support swizzling in a language that targets GPUs. HLSL has special syntax where any scalar or vector can be swizzled; e.g., p.xyz takes a vector4 and returns its first 3 elements as a vector3, p.zyx reverses these elements, and p.xxy repeats the first element twice then pairs the result with the second element. Through C# extension methods, we can define some common swizzle combinations (e.g., xyz and zyx), but with repeated elements and considering vectors of size 4 (the max that is supported by GPUs), we’d have to define way too many extension methods to be complete. Rather, I’ve defined a few overloaded extensible extension methods where the swizzle indices are indicated as type parameters; e.g., considered swizzled quaternion transformation in C#:
<pre class="code"><span style="color:#2b91af;">Double3Bl m = -q.XYZ().Square;
m = m.Sw&lt;Y,X,X&gt;() + m.Sw&lt;Z,Z,Y&gt;();

Double3Bl n = q.W * q.XYZ();
Double3Bl r = q.Sw&lt;X,X,Y&gt;() * q.Sw&lt;Y,Z,Z&gt;();
Double3Bl t = r.Sw&lt;X,Z,Y&gt;() - n.Sw&lt;Z,X,Y&gt;();
Double3Bl u = n.Sw&lt;Y,Z,X&gt;() + r.Sw&lt;Y,X,Z&gt;();
Double3Bl p = argB;
Double3Bl v = m * p.XYZ() + t * p.YZX() + u * p.ZXY();
</span><span style="color:blue;">return 2d * v + p.XYZ();
</pre>
<p><a href="http://11011.net/software/vspaste"></a></span></p>
<p>Sometimes we use extension methods (e.g., XYZ()), and sometimes we use the Sw method, which is slightly more verbose but still reasonably concise. For type safety, we define the X, Y, Z, and W classes so that X &lt;: Y &lt;: Z &lt;: W, then if the target is a 4 vector, the type parameter bounds for all the swizzle parameters is W , while if it’s a 2 vector, the type parameter bounds for all the swizzle parameters is Y, disallowing Z and W. The X, Y, Z, and W classes can then be instantiated as type parameters to determine the index they represent. </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mcdirmid.wordpress.com/88/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mcdirmid.wordpress.com/88/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mcdirmid.wordpress.com/88/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mcdirmid.wordpress.com/88/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mcdirmid.wordpress.com/88/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mcdirmid.wordpress.com/88/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mcdirmid.wordpress.com/88/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mcdirmid.wordpress.com/88/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mcdirmid.wordpress.com/88/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mcdirmid.wordpress.com/88/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mcdirmid.wordpress.com/88/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mcdirmid.wordpress.com/88/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mcdirmid.wordpress.com/88/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mcdirmid.wordpress.com/88/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mcdirmid.wordpress.com&amp;blog=8484952&amp;post=88&amp;subd=mcdirmid&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mcdirmid.wordpress.com/2009/10/30/swizzling-in-c-via-bling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6829d6ae4bda3a38255a96637b944a5a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mcdirmid</media:title>
		</media:content>
	</item>
		<item>
		<title>Announcing Bling 3.1!</title>
		<link>http://mcdirmid.wordpress.com/2009/10/27/announcing-bling-3-1/</link>
		<comments>http://mcdirmid.wordpress.com/2009/10/27/announcing-bling-3-1/#comments</comments>
		<pubDate>Tue, 27 Oct 2009 06:59:26 +0000</pubDate>
		<dc:creator>mcdirmid</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://mcdirmid.wordpress.com/2009/10/27/announcing-bling-3-1/</guid>
		<description><![CDATA[I’d like to announce a new version of Bling (http://bling.codeplex.com/) with maturing experimental support for retained and programmable 3D graphics. On the one hand, we have immediate-mode programmable graphics in Direct3D, which is flexible and fast but is more difficult to program. On the other hand, we have retained mode graphics in WPF 3D, which [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mcdirmid.wordpress.com&amp;blog=8484952&amp;post=84&amp;subd=mcdirmid&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I’d like to announce a new version of Bling (<a href="http://bling.codeplex.com/">http://bling.codeplex.com/</a>) with maturing experimental support for <strong>retained and programmable</strong> 3D graphics. On the one hand, we have immediate-mode programmable graphics in Direct3D, which is flexible and fast but is more difficult to program. On the other hand, we have retained mode graphics in WPF 3D, which is easier to program but is less flexible and not as fast as straight Direct3D. Bling is a side project that experiments with something in between the two: the ease of programming that a retained graphics model provides with the flexibility and performance that comes with the ability to express custom pixel and vertex shaders.  Bling is built on top of Direct3D via the <a href="http://code.msdn.microsoft.com/WindowsAPICodePack">WindowsAPI Code pack</a>, the <a href="http://dlr.codeplex.com">DLR</a>, and WPF.</p>
<p>Long description/example for those that are interested:<span id="more-84"></span></p>
<p>In Bling, 3D programmers are expressed by the programmer in pure C# code rather than HLSL code—at run-time the C#-encoded shaders are dynamically translated into HLSL code that is then compiled into DirectX 10 shaders. Shader bodies can directly refer to dependency properties, which are translated into uniform slots (aka global parameters) that are maintained via efficient dynamically generated CLR code (via the DLR). A simple complete example that uses a camera but no lighting:</p>
<pre class="code"><span style="color:black;">CameraZ = </span><span style="color:blue;">new </span><span style="color:#2b91af;">LabelSliderBl</span><span style="color:black;">(</span><span style="color:blue;">this</span><span style="color:black;">) { LabelName = </span><span style="color:#a31515;">"Z"</span><span style="color:black;">, Minimum = -40d, Maximum = +10d, Value = -4d, };
RotateX = </span><span style="color:blue;">new </span><span style="color:#2b91af;">LabelSliderBl</span><span style="color:black;">(</span><span style="color:blue;">this</span><span style="color:black;">) { LabelName = </span><span style="color:#a31515;">"RotateX"</span><span style="color:black;">, Minimum = 0d, Maximum = 2d, Value = .9d, };
RotateY = </span><span style="color:blue;">new </span><span style="color:#2b91af;">LabelSliderBl</span><span style="color:black;">(</span><span style="color:blue;">this</span><span style="color:black;">) { LabelName = </span><span style="color:#a31515;">"RotateY"</span><span style="color:black;">, Minimum = 0d, Maximum = 2d, Value = .9d, };
</span><span style="color:#2b91af;">CubeTopology </span><span style="color:black;">Cube = </span><span style="color:blue;">new </span><span style="color:#2b91af;">CubeTopology</span><span style="color:black;">();
</span><span style="color:#2b91af;">Point3DBl </span><span style="color:black;">WorldCenter = </span><span style="color:blue;">new </span><span style="color:#2b91af;">Point3DBl</span><span style="color:black;">(0, 0, 0);
</span><span style="color:#2b91af;">Point3DBl </span><span style="color:black;">CameraPosition = WorldCenter + </span><span style="color:blue;">new </span><span style="color:#2b91af;">Point3DBl</span><span style="color:black;">(0, 0, CameraZ.Value);
</span><span style="color:#2b91af;">PerspectiveCameraCl </span><span style="color:black;">Camera = </span><span style="color:blue;">new </span><span style="color:#2b91af;">PerspectiveCameraCl</span><span style="color:black;">() { Position = CameraPosition, };
</span><span style="color:#2b91af;">ColorBl</span><span style="color:black;">[] FaceColors = </span><span style="color:blue;">new </span><span style="color:#2b91af;">ColorBl</span><span style="color:black;">[] {
 </span><span style="color:#2b91af;">Colors</span><span style="color:black;">.Red, </span><span style="color:#2b91af;">Colors</span><span style="color:black;">.LightGreen,
 </span><span style="color:#2b91af;">Colors</span><span style="color:black;">.Blue, </span><span style="color:#2b91af;">Colors</span><span style="color:black;">.Yellow,
 </span><span style="color:#2b91af;">Colors</span><span style="color:black;">.Purple, </span><span style="color:#2b91af;">Colors</span><span style="color:black;">.Salmon,
};
Device.Render(Cube.Count, 16, (</span><span style="color:#2b91af;">IntBl </span><span style="color:black;">n, </span><span style="color:#2b91af;">IntBl </span><span style="color:black;">m, </span><span style="color:#2b91af;">IVertex </span><span style="color:black;">vertex) =&gt; {
 </span><span style="color:#2b91af;">QuaternionBl </span><span style="color:black;">qx = </span><span style="color:blue;">new </span><span style="color:#2b91af;">QuaternionBl</span><span style="color:black;">(</span><span style="color:blue;">new </span><span style="color:#2b91af;">Point3DBl</span><span style="color:black;">(1, 0, 0), RotateX.Value.PI());
 </span><span style="color:#2b91af;">QuaternionBl </span><span style="color:black;">qy = </span><span style="color:blue;">new </span><span style="color:#2b91af;">QuaternionBl</span><span style="color:black;">(</span><span style="color:blue;">new </span><span style="color:#2b91af;">Point3DBl</span><span style="color:black;">(0, 1, 0), RotateY.Value.PI());
 </span><span style="color:#2b91af;">PointBl </span><span style="color:black;">mxy = </span><span style="color:blue;">new </span><span style="color:#2b91af;">PointBl</span><span style="color:black;">(m % 4, m / 4);
 mxy = (mxy / 4d) - (.5 + .25) / 2d;
 vertex.Position =
(Camera * mxy.InsertZ(0).Translate() * .1.Bl().XXX().Scale() * (qx * qy).Matrix).Transform(Cube[n]);
 vertex.Color = FaceColors.Table(n / 4);
}, Cube.IndexBuffer);
</span></pre>
<p>The example defines 3 sliders (Z, RotateX, RotateY) with Slider-like Value dependency properties, these properties are then referred to in the Device.Render call to define the position of each vertex in a cube (defined through a utility cube topology class), where Z drives the perspective camera’s Z position while RotateX and RotateY are used to define rotations around the X and Y axis respectively. The cube is instanced 16 times, where n is the vertex ID and m is the instance ID. As with other shader-based programming models, all the logic for rendering is specified directly in the shader; e.g., the effects of the camera must be multiplied into the position computation.</p>
<p><a href="http://mcdirmid.files.wordpress.com/2009/10/clip_image001.jpg"><img style="display:inline;border-width:0;" title="clip_image001" src="http://mcdirmid.files.wordpress.com/2009/10/clip_image001_thumb.jpg?w=209&#038;h=244" border="0" alt="clip_image001" width="209" height="244" /></a> <a href="http://mcdirmid.files.wordpress.com/2009/10/clip_image002.jpg"><img style="display:inline;border-width:0;" title="clip_image002" src="http://mcdirmid.files.wordpress.com/2009/10/clip_image002_thumb.jpg?w=210&#038;h=244" border="0" alt="clip_image002" width="210" height="244" /></a></p>
<p>This approach has full support for WPF dependency property capabilities, including WPF-based animation. Partitioning shader computations between pixel and vertex shaders is also inferred, with the principle that computation occurs in the vertex shader  as possible unless the programmer specifies otherwise. For example, consider the following code with a spotlight where all lighting computations are done in the vertex shader:</p>
<pre class="code"><span style="color:blue;">var </span><span style="color:black;">Slider = </span><span style="color:blue;">new </span><span style="color:#2b91af;">LabelSliderBl</span><span style="color:black;">(</span><span style="color:blue;">this</span><span style="color:black;">) {
 Minimum = -.1, Maximum = +.1, Value = 0, LabelName = </span><span style="color:#a31515;">"Light"</span><span style="color:black;">,
};
</span><span style="color:#2b91af;">LightBl </span><span style="color:black;">light = </span><span style="color:blue;">new </span><span style="color:#2b91af;">SpotLightBl</span><span style="color:black;">() {
 Direction = (</span><span style="color:blue;">new </span><span style="color:#2b91af;">Point3DBl</span><span style="color:black;">(Slider.Value, Slider.Value, +1)).Normalize,
 Color = </span><span style="color:#2b91af;">Colors</span><span style="color:black;">.White,
 Position = </span><span style="color:blue;">new </span><span style="color:#2b91af;">Point3DBl</span><span style="color:black;">(0, 0, -2.5),
 InnerConeAngle = 2.ToDegrees(),
 OuterConeAngle = 4.ToDegrees(),
};
</span><span style="color:#2b91af;">MaterialCl </span><span style="color:black;">diffuse = </span><span style="color:blue;">new </span><span style="color:#2b91af;">DiffuseMaterialCl</span><span style="color:black;">() {
Factor = .5,
Ambient = { Factor = .5 }
};
Device.Render(Cube.Count, DIM * DIM, (</span><span style="color:#2b91af;">IntBl </span><span style="color:black;">n, </span><span style="color:#2b91af;">IntBl </span><span style="color:black;">m, </span><span style="color:#2b91af;">IVertex </span><span style="color:black;">vertex) =&gt; {
</span><span style="color:#2b91af;">Point3DBl </span><span style="color:black;">WorldPos;
… /* ellided position computations */
 Vertex.Color = diffuse.ApplyLights(light + </span><span style="color:blue;">new </span><span style="color:#2b91af;">AmbientLightBl</span><span style="color:black;">() { Color = </span><span style="color:#2b91af;">Colors</span><span style="color:black;">.White }).
 ApplyAt(WorldPos, normal, CameraPosition).ForColor(clr);
}, Cube.IndexBuffer);
</span></pre>
<p>Result:</p>
<p><a href="http://mcdirmid.files.wordpress.com/2009/10/clip_image003.jpg"><img style="display:inline;border-width:0;" title="clip_image003" src="http://mcdirmid.files.wordpress.com/2009/10/clip_image003_thumb.jpg?w=215&#038;h=156" border="0" alt="clip_image003" width="215" height="156" /></a></p>
<p>For better quality, we can force the lighting computation down into the pixel shader by specifying that world positions are computed on a per-pixel basis:</p>
<pre class="code"><span style="color:black;">Device.Render(Cube.Count, DIM * DIM, (</span><span style="color:#2b91af;">IntBl </span><span style="color:black;">n, </span><span style="color:#2b91af;">IntBl </span><span style="color:black;">m, </span><span style="color:#2b91af;">IVertex </span><span style="color:black;">vertex) =&gt; {
</span><span style="color:#2b91af;">Point3DBl </span><span style="color:black;">WorldPos;
… /* ellided position computations */
 Vertex.Color = diffuse.ApplyLights(light + </span><span style="color:blue;">new </span><span style="color:#2b91af;">AmbientLightBl</span><span style="color:black;">() { Color = </span><span style="color:#2b91af;">Colors</span><span style="color:black;">.White }).
 ApplyAt(WorldPos.PerPixel(), normal, CameraPosition).ForColor(clr);
}, Cube.IndexBuffer);
</span></pre>
<pre class="code">The result is an improvement in quality if you look closely:</pre>
<p><a href="http://mcdirmid.files.wordpress.com/2009/10/clip_image004.jpg"><img style="display:inline;border-width:0;" title="clip_image004" src="http://mcdirmid.files.wordpress.com/2009/10/clip_image004_thumb.jpg?w=126&#038;h=107" border="0" alt="clip_image004" width="126" height="107" /></a></p>
<p>Other nice features:</p>
<p>· An explicit signature mode where uniforms, vertex, pixel, and geometry shaders are specified directly as annotated C# interfaces. This mode gives the user more control without requirement too much boiler plate, and is also the only way we can currently express DX10 geometry shading.</p>
<p>· Render target textures, ability to specify multiple render out passes, e.g., for simulating heat diffusion:</p>
<p>· Camera, light, and material model based on WPF 3D, with enhancements (e.g., a glass material).</p>
<p>· Meta-programming of shader trees to do things like automatically compute the derivative of an expression or automatically compute the upper bound of vertices that could be produced by a geometry shader.</p>
<p>· Lots of graphic utility classes to ease the expression of shaders and hide the math; e.g., one line of code to normal map a texture onto a parametric surface.</p>
<p>· DX10/WPF airspace issues addressed by overlay window.</p>
<p>Caveats:</p>
<p>· Right now Bling is only meant for prototypes and experiments, and not meant for production use; e.g., no DX resource management has been implemented. Bling is an effective way of rapidly exploring design ideas, which are then produced using a more established/involved technology (e.g., Direct3D).</p>
<p>· No XP support (DX10), textures won’t work on pre-SP3 Vista.</p>
<p>· Even though Bling’s retained model is based on WPF dependency properties, there is no support for anything like XAML.</p>
<p>· No way to host WPF content in DX10.</p>
<p>A download of Bling 3.1 is available on <a href="http://bling.codeplex.com">Codeplex</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mcdirmid.wordpress.com/84/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mcdirmid.wordpress.com/84/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mcdirmid.wordpress.com/84/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mcdirmid.wordpress.com/84/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mcdirmid.wordpress.com/84/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mcdirmid.wordpress.com/84/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mcdirmid.wordpress.com/84/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mcdirmid.wordpress.com/84/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mcdirmid.wordpress.com/84/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mcdirmid.wordpress.com/84/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mcdirmid.wordpress.com/84/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mcdirmid.wordpress.com/84/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mcdirmid.wordpress.com/84/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mcdirmid.wordpress.com/84/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mcdirmid.wordpress.com&amp;blog=8484952&amp;post=84&amp;subd=mcdirmid&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mcdirmid.wordpress.com/2009/10/27/announcing-bling-3-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6829d6ae4bda3a38255a96637b944a5a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mcdirmid</media:title>
		</media:content>

		<media:content url="http://mcdirmid.files.wordpress.com/2009/10/clip_image001_thumb.jpg" medium="image">
			<media:title type="html">clip_image001</media:title>
		</media:content>

		<media:content url="http://mcdirmid.files.wordpress.com/2009/10/clip_image002_thumb.jpg" medium="image">
			<media:title type="html">clip_image002</media:title>
		</media:content>

		<media:content url="http://mcdirmid.files.wordpress.com/2009/10/clip_image003_thumb.jpg" medium="image">
			<media:title type="html">clip_image003</media:title>
		</media:content>

		<media:content url="http://mcdirmid.files.wordpress.com/2009/10/clip_image004_thumb.jpg" medium="image">
			<media:title type="html">clip_image004</media:title>
		</media:content>
	</item>
		<item>
		<title>What is a programmable abstraction?</title>
		<link>http://mcdirmid.wordpress.com/2009/07/30/what-is-a-programmable-abstraction/</link>
		<comments>http://mcdirmid.wordpress.com/2009/07/30/what-is-a-programmable-abstraction/#comments</comments>
		<pubDate>Thu, 30 Jul 2009 04:47:41 +0000</pubDate>
		<dc:creator>mcdirmid</dc:creator>
				<category><![CDATA[Bling]]></category>
		<category><![CDATA[abstraction]]></category>

		<guid isPermaLink="false">http://mcdirmid.wordpress.com/2009/07/30/what-is-a-programmable-abstraction/</guid>
		<description><![CDATA[In a recent blog post I described the principles behind Bling’s design. The primary principle is preferring programmable over fixed abstractions. But I feel that my definition of a programmable abstraction is so far unsatisfactory and undeveloped. To converge on a better definition, let’s first start at the beginning and discuss abstraction. The process of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mcdirmid.wordpress.com&amp;blog=8484952&amp;post=73&amp;subd=mcdirmid&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In a recent blog post I described the principles behind Bling’s design. The primary principle is preferring <strong>programmable</strong> over <strong>fixed</strong> abstractions. But I feel that my definition of a <em>programmable abstraction</em> is so far unsatisfactory and undeveloped. To converge on a better definition, let’s first start at the beginning and discuss abstraction. </p>
<p> <span id="more-73"></span>
<p>The process of <em><a href="http://en.wikipedia.org/wiki/Abstraction_(computer_science)" target="_blank">abstraction</a></em> (verb) is that of hiding details so that one can focus on fewer concepts at a time. An abstraction (noun) then is a hider of details. A <a href="http://en.wikipedia.org/wiki/Programming_language" target="_blank">programming language</a> provides various <a href="http://en.wikipedia.org/wiki/Language_primitive" target="_blank">primitives</a> for constructing custom abstractions, such as procedures, classes, functions, properties, or rules—let’s refer to these as <em>abstraction primitives</em> to distinguish them from <em>computation primitives</em>, which are used to build up computations that use or are hidden by abstractions. Using abstraction primitives, a <a href="http://en.wikipedia.org/wiki/Library_(computer_science)" target="_blank">library</a> then define and implement an <a href="http://en.wikipedia.org/wiki/API" target="_blank">API</a> as a set of abstractions that permit access to some kind of service. Of course, real life is often more complex: one or more languages can be involved in the definition of a library (e.g., WPF and C#, Visual Basic, XAML, and HLSL), while libraries will often be built from or to interoperate with abstractions from other libraries.&#160; </p>
<p>Libraries are increasingly defined as <a href="http://en.wikipedia.org/wiki/Software_framework" target="_blank">frameworks</a> that provide heavy large-grained abstractions for assembling systems in specific domains; for example consider a web framework (<a href="http://rubyonrails.org/" target="_blank">Ruby on Rails</a>) or an IDE framework (<a href="http://www.eclipse.org" target="_blank">Eclipse</a>). Programmers customize a framework’s abstractions from the top-down according to their needs and assemble them together according to a rigid <a href="http://en.wikipedia.org/wiki/Software_architecture" target="_blank">architecture</a>. The trade off of using a frameworks includes the learning curve of the framework’s abstractions and architecture, as well as a sacrifice in flexibility where the framework becomes difficult or impossible to program outside of its intended purpose. </p>
<p>I am going to refer to framework abstractions as <em>fixed abstractions </em>because they are analogous to abstractions used to program a GPU through a fixed-function graphics pipeline as opposed to the abstractions used to program a GPU through a programmable pipeline. In the past, GPUs encoded in hardware only various fixed functions to manipulate vertices, light pixels, and so on. To program the GPU, the programmer manipulated various abstractions that represent fixed GPU functions through an API such as DirectX or OpenGL. As with a framework, these fixed-function APIs allowed for some customization of abstractions from the top-down, come with rigid architectures, and sacrifice flexibility in what they can express. </p>
<p>For the reason of flexibility alone, fixed-function pipelines are being rapidly replaced programmable pipelines that have the ability to express arbitrary custom effects through small programs known as <a href="http://en.wikipedia.org/wiki/Shader" target="_blank">shaders</a>, which run directly on the GPU. The programmable pipeline completely supersedes the fixed-function pipeline.&#160; For example, whereas a specific kind of light (e.g., spotlight) and material (e.g., specular) are fixed abstractions that would be customized and installed in a fixed-function pipeline, now it is merely sufficient to take the position of the vertex or pixel being shaded and return a color! At first glance, such an API seems a lot harder to use in simple cases where well non-custom understood lighting is being used, but then such cases can rely on reusable procedures that package up the lighting math. Beyond dramatically increased flexibility, the programmable pipeline approach also has a better learning curve as their are only a few lightweight abstractions to learn with virtually no architecture. For an excellent write up what the move from fixed-function to programmable pipelines means, see <a href="http://arstechnica.com/gaming/news/2008/09/gpu-sweeney-interview.ars" target="_blank">Tim Sweeney’s Ars interview on the subject</a>. </p>
<p>What do programmable pipelines and shaders have to do with software libraries and frameworks? They hint at an alternative to frameworks: rather design a library with many large-grained abstractions (fixed functions) that programmers customize down to what they want, instead we could design a library with a few small-grained versatile abstractions (shaders) that programmers then build up to what they want. We refer to the latter as <strong>programmable abstractions</strong>, which are smaller and more generally used than fixed abstractions. Large-grained reuse then comes from assembling the programmable abstractions together and packaging them up through language-level abstraction primitives (e.g., procedures). Programmable abstractions are not a new concept: they underpin many libraries, especially those built in functional programming languages. Additionally, programmable abstractions can be promoted to language-level abstractions with <a href="http://en.wikipedia.org/wiki/Domain-specific_language" target="_blank">domain-specific languages</a> (e.g., <a href="http://en.wikipedia.org/wiki/Anonymous_pipe" target="_blank">pipes</a> in <a href="http://en.wikipedia.org/wiki/Unix_shell" target="_blank">shell script</a>), where the key to defining a good DSL is to base it on versatile programmable abstractions rather than fixed abstractions. I feel that a term for such abstractions is needed because of the confusion surrounding languages, frameworks, libraries, DSLs, and something in between (highly versatile libraries that are not quite DSLs). </p>
<p>I’m not exactly sure what the threshold between a programmable abstraction and a fixed abstraction is, it might not be very clear cut. Also, the benefits of programmable abstractions are negated if excessive amounts of boilerplate are needed to use them, languages can go a long way in eliminating this boilerplate and making programmable abstractions more feasible (e.g., see express tree lifting in LINQ). To be continued, in the next part I’ll provide some concrete examples of differences between fixed and programmable abstractions. </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mcdirmid.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mcdirmid.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mcdirmid.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mcdirmid.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mcdirmid.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mcdirmid.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mcdirmid.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mcdirmid.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mcdirmid.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mcdirmid.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mcdirmid.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mcdirmid.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mcdirmid.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mcdirmid.wordpress.com/73/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mcdirmid.wordpress.com&amp;blog=8484952&amp;post=73&amp;subd=mcdirmid&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mcdirmid.wordpress.com/2009/07/30/what-is-a-programmable-abstraction/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6829d6ae4bda3a38255a96637b944a5a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mcdirmid</media:title>
		</media:content>
	</item>
		<item>
		<title>Announcing Bling 3!</title>
		<link>http://mcdirmid.wordpress.com/2009/07/27/announcing-bling-3/</link>
		<comments>http://mcdirmid.wordpress.com/2009/07/27/announcing-bling-3/#comments</comments>
		<pubDate>Mon, 27 Jul 2009 03:38:18 +0000</pubDate>
		<dc:creator>mcdirmid</dc:creator>
				<category><![CDATA[Bling]]></category>

		<guid isPermaLink="false">http://mcdirmid.wordpress.com/2009/07/27/announcing-bling-3/</guid>
		<description><![CDATA[I’d like to announce a newly rewritten release of Bling with many improvements and exciting new features. Bling is a novel experiment in how WPF/UI programming can be enhanced via a lightweight domain-specific language hosted completely within C#. Bling basically changes the meaning of statements and expressions to do more that is otherwise possible with [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mcdirmid.wordpress.com&amp;blog=8484952&amp;post=63&amp;subd=mcdirmid&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I’d like to announce a newly rewritten <a href="http://bling.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=30598">release</a> of <a href="http://bling.codeplex.com/">Bling</a> with many improvements and exciting new features. Bling is a novel experiment in how WPF/UI programming can be enhanced via a lightweight domain-specific language hosted completely within C#. Bling basically changes the meaning of statements and expressions to do more that is otherwise possible with normal values in C#; e.g., a + b no longer means add the value of “a” to the value of “b,” but rather it creates tree that we can then transform into a databinding relationship, HLSL code, and so on. We exploit this to reduce or completely UI boilerplate code; e.g., no more value converters, no more HLSL code, no more C# shader classes, etc…Bling 3 goes farther with this style of programming through the addition of lifted functions (so f(a) also creates a tree!). For more details, see my <a href="http://mcdirmid.wordpress.com/">blog</a>.</p>
<p><span id="more-63"></span>New features in Bling 3.0:</p>
<ul>
<li>Improved support for multiple forms in lighting in pixel shaders reusing WPF3D abstractions when possible. Now a lighting effect can be added to a widget by specifying a WPF3D light, a material (similar to but not a WPF3D material), a normal map and/or a height map loaded from a texture (some kinds of lights require an eye position). Lighting effects can be combined via addition. WPF shader examples:</li>
</ul>
<p><a href="http://mcdirmid.files.wordpress.com/2009/07/clip_image002.jpg"><img style="display:inline;border-width:0;" title="clip_image002" src="http://mcdirmid.files.wordpress.com/2009/07/clip_image002_thumb.jpg?w=147&#038;h=133" border="0" alt="clip_image002" width="147" height="133" /></a> <a href="http://mcdirmid.files.wordpress.com/2009/07/clip_image004.jpg"><img style="display:inline;border-width:0;" title="clip_image004" src="http://mcdirmid.files.wordpress.com/2009/07/clip_image004_thumb.jpg?w=156&#038;h=134" border="0" alt="clip_image004" width="156" height="134" /></a><a href="http://mcdirmid.files.wordpress.com/2009/07/clip_image006.jpg"><img style="display:inline;border-width:0;" title="clip_image006" src="http://mcdirmid.files.wordpress.com/2009/07/clip_image006_thumb.jpg?w=133&#038;h=137" border="0" alt="clip_image006" width="133" height="137" /></a> <a href="http://mcdirmid.files.wordpress.com/2009/07/clip_image008.jpg"><img style="display:inline;border-width:0;" title="clip_image008" src="http://mcdirmid.files.wordpress.com/2009/07/clip_image008_thumb.jpg?w=135&#038;h=135" border="0" alt="clip_image008" width="135" height="135" /></a></p>
<ol>
<li>Normal mapped diffuse material + red specular material point light effect.</li>
<li>Glass material + point light effect (also normal mapped).</li>
<li>Diffraction material + point light effect (again normal mapped).</li>
<li>Diffuse material + point light effect with parametric normals (computed vs. loaded from an image).</li>
</ol>
<ul>
<li>Pixel-level transition abstractions that support composition. Example:</li>
</ul>
<p><a href="http://mcdirmid.files.wordpress.com/2009/07/clip_image009.png"><img style="display:inline;border-width:0;" title="clip_image009" src="http://mcdirmid.files.wordpress.com/2009/07/clip_image009_thumb.png?w=244&#038;h=163" border="0" alt="clip_image009" width="244" height="163" /></a></p>
<p>Intermediate progress of a ripple + sin transition composed via Min (take the min color from each transition’s result, where start and end are the same).</p>
<ul>
<li>Hacked prototype-quality WPF-friendly web browser that supports transformations and pixel shader effects. Browser will refresh every 100 milliseconds, so flash animations will work if a bit choppy. Link clicking is supported, but not keyboard input (need more interop code). Example:</li>
</ul>
<p><a href="http://mcdirmid.files.wordpress.com/2009/07/clip_image0111.jpg"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="clip_image011" src="http://mcdirmid.files.wordpress.com/2009/07/clip_image011_thumb1.jpg?w=469&#038;h=178" border="0" alt="clip_image011" width="469" height="178" /></a></p>
<p>Paper normal mapped browser navigated to Bling’s codeplex page.</p>
<ul>
<li>Simplified physics engine (more examples in the future).</li>
<li>Initial experimental support for DirectX 10, focusing right now on parametric surfaces. DirectX compositions look very much like Bling WPF pixel shaders and can refer directly to WPF dependency properties (just like a WPF pixel shader can). Example:</li>
</ul>
<p><a href="http://mcdirmid.files.wordpress.com/2009/07/clip_image013.jpg"><img style="display:inline;border-width:0;" title="clip_image013" src="http://mcdirmid.files.wordpress.com/2009/07/clip_image013_thumb.jpg?w=176&#038;h=147" border="0" alt="clip_image013" width="176" height="147" /></a> <a href="http://mcdirmid.files.wordpress.com/2009/07/clip_image015.jpg"><img style="display:inline;border-width:0;" title="clip_image015" src="http://mcdirmid.files.wordpress.com/2009/07/clip_image015_thumb.jpg?w=154&#038;h=148" border="0" alt="clip_image015" width="154" height="148" /></a> <a href="http://mcdirmid.files.wordpress.com/2009/07/clip_image017.jpg"><img style="display:inline;border-width:0;" title="clip_image017" src="http://mcdirmid.files.wordpress.com/2009/07/clip_image017_thumb.jpg?w=154&#038;h=149" border="0" alt="clip_image017" width="154" height="149" /></a> <a href="http://mcdirmid.files.wordpress.com/2009/07/clip_image019.jpg"><img style="display:inline;border-width:0;" title="clip_image019" src="http://mcdirmid.files.wordpress.com/2009/07/clip_image019_thumb.jpg?w=146&#038;h=146" border="0" alt="clip_image019" width="146" height="146" /></a></p>
<p><a href="http://mcdirmid.files.wordpress.com/2009/07/clip_image021.jpg"><img style="display:inline;border-width:0;" title="clip_image021" src="http://mcdirmid.files.wordpress.com/2009/07/clip_image021_thumb.jpg?w=244&#038;h=124" border="0" alt="clip_image021" width="244" height="124" /></a></p>
<ol>
<li>A sphere, no distortion</li>
<li>A sphere + a egg crate distortion</li>
<li>(2) with more magnitude</li>
<li>(3) with more frequency</li>
<li>(4) with less magnitude + the WPF sliders that are controlling it all.</li>
</ol>
<p>Caveats:</p>
<ul>
<li>Bling 3 is not backwards compatible with the previous version of Bling. Existing code requires porting.</li>
</ul>
<p>ToDo:</p>
<ul>
<li>Work on DirectX abstractions (right now we just have a start).</li>
<li>Would like to support Silverlight 3.</li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mcdirmid.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mcdirmid.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mcdirmid.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mcdirmid.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mcdirmid.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mcdirmid.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mcdirmid.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mcdirmid.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mcdirmid.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mcdirmid.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mcdirmid.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mcdirmid.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mcdirmid.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mcdirmid.wordpress.com/63/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mcdirmid.wordpress.com&amp;blog=8484952&amp;post=63&amp;subd=mcdirmid&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mcdirmid.wordpress.com/2009/07/27/announcing-bling-3/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6829d6ae4bda3a38255a96637b944a5a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mcdirmid</media:title>
		</media:content>

		<media:content url="http://mcdirmid.files.wordpress.com/2009/07/clip_image002_thumb.jpg" medium="image">
			<media:title type="html">clip_image002</media:title>
		</media:content>

		<media:content url="http://mcdirmid.files.wordpress.com/2009/07/clip_image004_thumb.jpg" medium="image">
			<media:title type="html">clip_image004</media:title>
		</media:content>

		<media:content url="http://mcdirmid.files.wordpress.com/2009/07/clip_image006_thumb.jpg" medium="image">
			<media:title type="html">clip_image006</media:title>
		</media:content>

		<media:content url="http://mcdirmid.files.wordpress.com/2009/07/clip_image008_thumb.jpg" medium="image">
			<media:title type="html">clip_image008</media:title>
		</media:content>

		<media:content url="http://mcdirmid.files.wordpress.com/2009/07/clip_image009_thumb.png" medium="image">
			<media:title type="html">clip_image009</media:title>
		</media:content>

		<media:content url="http://mcdirmid.files.wordpress.com/2009/07/clip_image011_thumb1.jpg" medium="image">
			<media:title type="html">clip_image011</media:title>
		</media:content>

		<media:content url="http://mcdirmid.files.wordpress.com/2009/07/clip_image013_thumb.jpg" medium="image">
			<media:title type="html">clip_image013</media:title>
		</media:content>

		<media:content url="http://mcdirmid.files.wordpress.com/2009/07/clip_image015_thumb.jpg" medium="image">
			<media:title type="html">clip_image015</media:title>
		</media:content>

		<media:content url="http://mcdirmid.files.wordpress.com/2009/07/clip_image017_thumb.jpg" medium="image">
			<media:title type="html">clip_image017</media:title>
		</media:content>

		<media:content url="http://mcdirmid.files.wordpress.com/2009/07/clip_image019_thumb.jpg" medium="image">
			<media:title type="html">clip_image019</media:title>
		</media:content>

		<media:content url="http://mcdirmid.files.wordpress.com/2009/07/clip_image021_thumb.jpg" medium="image">
			<media:title type="html">clip_image021</media:title>
		</media:content>
	</item>
		<item>
		<title>A web browser suitable for Harry Potter in WPF!</title>
		<link>http://mcdirmid.wordpress.com/2009/07/27/a-web-browser-suitable-for-harry-potter-in-wpf/</link>
		<comments>http://mcdirmid.wordpress.com/2009/07/27/a-web-browser-suitable-for-harry-potter-in-wpf/#comments</comments>
		<pubDate>Mon, 27 Jul 2009 02:01:14 +0000</pubDate>
		<dc:creator>mcdirmid</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://mcdirmid.wordpress.com/2009/07/27/a-web-browser-suitable-for-harry-potter-in-wpf/</guid>
		<description><![CDATA[Daily Prophet eat your heart out! Here is a prototype web browser we threw together in Bling: We (myself, my intern lighting-export Li SiYu, and a former intern Wang Chao who worked on the browser part) started with code from Chris Cavanagh&#8217;s Blog to render a background IE instance into a WPF writeable bitmap, which [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mcdirmid.wordpress.com&amp;blog=8484952&amp;post=40&amp;subd=mcdirmid&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Daily_Prophet#The_Daily_Prophet" target="_blank">Daily Prophet</a> eat your heart out! Here is a prototype web browser we threw together in <a href="http://bling.codeplex.com/" target="_blank">Bling</a>:</p>
<p><a href="http://mcdirmid.files.wordpress.com/2009/07/image3.png"><img style="display:inline;border-width:0;" title="image" src="http://mcdirmid.files.wordpress.com/2009/07/image_thumb3.png?w=563&#038;h=310" border="0" alt="image" width="563" height="310" /></a></p>
<p><span id="more-40"></span>We (myself, my intern lighting-export Li SiYu, and a former intern Wang Chao who worked on the browser part) started with code from <a href="http://chriscavanagh.wordpress.com/2008/09/04/youcube/">Chris Cavanagh&#8217;s Blog</a> to render a background IE instance into a WPF writeable bitmap, which we optimized using some sample code from <a href="http://channel9.msdn.com/tags/David+Teitlebaum/" target="_blank">David Teitlebaum</a>. The advantage of this approach is that a writeable bitmap is a first class entity in WPF and so can be transformed and distorted, whereas a standard WPF web browser doesn’t support these features due to airspace issues. The disadvantage of our approach is that its a big hack suitable only for playing around (e.g., in the above pic) and we can only update the browser about once every 100 milliseconds, so videos and Flash are extremely choppy (but still very lively!).</p>
<p>The web browser content is projected onto a <a href="http://en.wikipedia.org/wiki/Diffuse_reflection" target="_blank">diffuse</a> material that is lit by a point light. We bind the point light’s position to the mouse so the lighting changes dynamically with user interaction. The height of the light is bound to the slider beneath the address bar. This code sets up the lighting:</p>
<pre class="code"><span style="color:#2b91af;">ThumbBl </span>LightXY = <span style="color:blue;">new </span><span style="color:#2b91af;">ThumbBl</span>();
<span style="color:#2b91af;">Action </span>UpdateLightXY = <span style="color:#2b91af;">PointBl</span>.Assign(LightXY, canvas.MousePosition);
<span style="color:blue;">this</span>.MouseMove += (xx, yy) =&gt; UpdateLightXY();
<span style="color:#2b91af;">Lighting </span>lighting = <span style="color:blue;">new </span><span style="color:#2b91af;">DiffuseMaterialCl</span>().Apply(<span style="color:blue;">new </span><span style="color:#2b91af;">PointLightBl</span>() {
  Position = <span style="color:blue;">new </span><span style="color:#2b91af;">Point3DBl</span>(LightXY, HeightOfLight),
  Color = <span style="color:#2b91af;">Colors</span>.White,
});</pre>
<p>This code mostly involves databinding, except for tracking the mouse position, which we do manually. The “Apply” method of material exercises basic lighting equations according to the specified light (diffuse material + point light in our case) to create a lighting result. The lighting code for a diffuse material is encoded in Bling is something like this:</p>
<pre class="code"><span style="color:#2b91af;">Point3DBl </span>Dir = LightSource.DirectionToPosition(Position);
<span style="color:#2b91af;">DoubleBl </span>Dis = Dir.Length;
Dir = Dir.Normalize;
LightingResult = ((LightSource.Color.ScRGB * Dir.Dot(Normal).Max(0) *
  LightSource.UseAttenuation(Dir, Dis))) * Input.ScRGB;</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>Lights are distinguished by their direction (constant for a directional light, difference between position being shaded and light position for point light) and their <a href="http://en.wikipedia.org/wiki/Attenuation" target="_blank">attenuation</a> (a bit more math).</p>
<p>We apply the lighting result to the canvas containing the browser via <a href="http://en.wikipedia.org/wiki/Normal_mapping" target="_blank">normal mapping</a>, which uses pre-baked texture to add depth and naturalness to the surface being lit. The textures used here make the browser look like it is printed on slightly folded paper! The texture scrolls as the scrollbar is used to scroll browser content, though not at the same magnitude. Code:</p>
<pre class="code"><span style="color:#2b91af;">Texture </span>HeightField = <span style="color:blue;">new </span><span style="color:#2b91af;">ImageBrushBl</span>(HeightImage);
<span style="color:#2b91af;">Texture </span>NormalMap = <span style="color:blue;">new </span><span style="color:#2b91af;">ImageBrushBl</span>(NormalImage);
HeightField = HeightField.Distort(uv =&gt; <span style="color:blue;">new </span><span style="color:#2b91af;">PointBl</span>(uv.X, (uv.Y + scrollBar.Value).Frac));
NormalMap =     NormalMap.Distort(uv =&gt; <span style="color:blue;">new </span><span style="color:#2b91af;">PointBl</span>(uv.X, (uv.Y + scrollBar.Value).Frac));
canvas.Effect.Custom = lighting.Apply((<span style="color:#2b91af;">HeightField</span>)HeightField, (<span style="color:#2b91af;">NormalMap</span>)NormalMap,
                              canvas.Size.AddZ(0.015d), canvas.CenterSize.AddZ(100d));</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Textures in WPF are brushes, so we load our normal mapping files (HeightImage and NormalImage) as image brushes. We distort the resulting textures by shifting them vertically by the scrollbar’s value, which are then converted into proper texture coordinates via Frac (an <a href="http://msdn.microsoft.com/en-us/library/bb509611(VS.85).aspx" target="_blank">HLSL</a> intrinsic defined as Math.Abs(Math.Round(n))). We then explicitly coerce the two textures into a height field and normal map respectively, for use in normal mapping. These explicit coercions convert the textures according to a popular normal map and height field texture representations (<a href="http://www.crazybump.com/" target="_blank">Crazy Bump</a> and various Photoshop normal mapping plugins). The other two arguments used for normal mapping are the 3D size of the canvas and the eye position we want to use. The code for normal mapping is as follows:</p>
<pre class="code"><span style="color:blue;">public </span><span style="color:#2b91af;">PixelEffect </span>Apply(<span style="color:#2b91af;">HeightField </span>Heights, <span style="color:#2b91af;">NormalMap </span>Normals, <span style="color:#2b91af;">Point3DBl </span>Size, <span style="color:#2b91af;">Point3DBl </span>Eye) {
  <span style="color:blue;">return new </span><span style="color:#2b91af;">PixelEffect</span>(input =&gt; <span style="color:blue;">new </span><span style="color:#2b91af;">Texture</span>(UV =&gt; {
    <span style="color:#2b91af;">Point3DBl </span>Position = <span style="color:blue;">new </span><span style="color:#2b91af;">Point3DBl</span>(UV * Size.XY(), Heights[UV] * Size.Z);
    <span style="color:blue;">var </span>eyeDir = (Eye - Position).Normalize;
    <span style="color:blue;">var </span>UV0 = UV + eyeDir.XY() * Heights[UV] * Size.Z;
    <span style="color:blue;">return this</span>[Position, Normals[UV0], Eye][input, UV0];
  }));
}</pre>
<p>A pixel effect is simply a texture-to-texture function that is suitable for use as a pixel shader. A texture is defined as a point-to-color function that can be loaded from a file (as we did with HeightField and NormalMap) but can also be defined programmatically, which is what we are doing here. The math for the resulting texture is beyond the scope of this blog post but is not very difficult: basically we extract heights and normals from the height field and normal map according to the current texture coordinate UV, adjust them for the 3D size of our target, and bias UV by using an eye direction and the current height.  This is then plugged into our lighting result, which in turn is used to compute the resulting pixel from the input texture and the biased texture coordinate. Video:</p>
<span style="text-align:center; display: block;"><a href="http://mcdirmid.wordpress.com/2009/07/27/a-web-browser-suitable-for-harry-potter-in-wpf/"><img src="http://img.youtube.com/vi/Z941XGJi2eg/2.jpg" alt="" /></a></span>
<p>This effect will work for any WPF application, not just our browser, notice the text field at the top, the slider below that, and the scrollbar tot he side, which are all WPF widgets!</p>
<p>The code for this sample is available in the <a href="http://bling.codeplex.com/" target="_blank">Bling 3 distribution</a>, which will hopefully be released soon!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mcdirmid.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mcdirmid.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mcdirmid.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mcdirmid.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mcdirmid.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mcdirmid.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mcdirmid.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mcdirmid.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mcdirmid.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mcdirmid.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mcdirmid.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mcdirmid.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mcdirmid.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mcdirmid.wordpress.com/40/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mcdirmid.wordpress.com&amp;blog=8484952&amp;post=40&amp;subd=mcdirmid&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mcdirmid.wordpress.com/2009/07/27/a-web-browser-suitable-for-harry-potter-in-wpf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6829d6ae4bda3a38255a96637b944a5a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mcdirmid</media:title>
		</media:content>

		<media:content url="http://mcdirmid.files.wordpress.com/2009/07/image_thumb3.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Bling Manifesto</title>
		<link>http://mcdirmid.wordpress.com/2009/07/22/bling-manifesto/</link>
		<comments>http://mcdirmid.wordpress.com/2009/07/22/bling-manifesto/#comments</comments>
		<pubDate>Wed, 22 Jul 2009 03:53:30 +0000</pubDate>
		<dc:creator>mcdirmid</dc:creator>
				<category><![CDATA[Bling]]></category>

		<guid isPermaLink="false">http://mcdirmid.wordpress.com/2009/07/22/bling-manifesto/</guid>
		<description><![CDATA[User interfaces toolkits are becoming increasingly complicated through frameworks with rigid architectures and numerous high-level abstractions that must be customized down to meet application requirements. In contrast, modern low-level 3D graphics toolkits are moving en masse away from similar fixed function APIs to flexible programmable shader models. For example, rather than call a point light [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mcdirmid.wordpress.com&amp;blog=8484952&amp;post=36&amp;subd=mcdirmid&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>User interfaces toolkits are becoming increasingly complicated through frameworks with rigid architectures and numerous high-level abstractions that must be customized down to meet application requirements. In contrast, modern low-level 3D graphics toolkits are moving en masse away from similar fixed function APIs to flexible programmable shader models. For example, rather than call a point light on diffuse material fixed function, one would instead encode the math for this operation in a shader. Custom forms of lighting are easily expressed through new math. Can similar model work for user interfaces? Consider layouts: a few fixed kinds of panels (stack, flow, etc…) can be configured and composed to implement various kinds of layouts. The number of fixed layouts combined with their customization options make such APIs very complicated and difficult to learn and use. However, the ability to express layout math can accommodate any kind of layout, and since the layout is being expressed as math their are no customization options to learn and use. This brings us to the first principle of Bling’s design: <strong>to optimize for flexibility and simplicity, support bottom up construction of “programmable” abstractions as opposed to the top-down customization of high-level fixed abstractions.</strong></p>
<p>The drawback of such <em>programmable abstractions</em> is convenience and repetition—no one wants to reinvent the wheel while inventing an effectively round wheel requires complex processes. Consider implementing a custom layout algorithm in WPF, boilerplate make expressing programmable layouts difficult and repetitive: one must define a new panel, define minimum, maximum, and preferred sizes, and deal manually with layout changing events. Later on, this panel can only be reused in its entirety: parts of the algorithm must be re-implemented in a new panel. Likewise, boilerplate in Direct3D makes it difficult to setup even simple scenes, while boilerplate to interface with shaders prevents the modularization of lighting math that can run either on the CPU or GPU. The solution to the boilerplate problem is to eliminate boilerplate. For example in expressing layouts, convenient and concise databinding to arbitrary expressions makes it practical to encode arbitrary layout constraints that automatically react to dynamic changes. Likewise, the direct expression of shader code regardless of whether on the CPU or GPU allows for the modularization of lighting code into simple functions. This brings us to the second principle of Bling’s design: <strong>avoid inconvenience and repetition through boilerplate-hiding abstractions such as those concerning databinding or function composition. </strong>Code can then simply be organized into methods or functions.<strong> </strong></p>
<p>Other Bling principles:</p>
<ul>
<li><strong>To reduce confusion and keep the API as small and simple as possible, avoid redundant abstractions</strong>. For example, Bling does not support WPF storyboards because they overlap with databinding and explicit clocks to synchronize animations. Likewise, styles and triggers are easily replaced with constraints expressed via databinding.</li>
<li><strong>Focus on math</strong>. Almost everything in UI is math heavy, be it layout, animation, gradient blending, lighting, or physics.  Therefore it makes a lot of sense to optimize our abstractions for the expression and modularization of math. Bling includes an extensive math library, support for composite tuple, matrix, and function operations, simple algebraic solving, and symbolic derivation.</li>
<li><strong>Programmer friendliness through reasonable defaults. </strong>The days when a rectangle does not show up on the screen because the programmer forgot to set a stroke or color should be over! For programmer friendliness, Bling strives to ensure that all properties have default values, which then cause something noticeable to happen on the screen.</li>
<li><strong>Avoid abstraction performance penalty through dynamic code generation</strong>. Layers of abstraction can be expensive in performance critical parts of a UI, such as in layout, lighting, animation, or physics. This expense can be eliminated by using abstraction-heavy code to generate unabstracted code at run-time. Furthermore, code can be generated to run on GPUs as well as CPUs, leading to even greater performance improvements while isolating programmers from the otherwise inconveniences of GPU programming.</li>
<li><strong>To support code generation and symbolic analysis, manipulate expression trees, not values.</strong> Bling is like LINQ in that it is based on manipulating expression trees. Various tricks such as the use of operator overloading allows expression tree compositions to resemble comparable operations on values; e.g., a + b can form an addition tree node with a and b sub-trees.</li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mcdirmid.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mcdirmid.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mcdirmid.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mcdirmid.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mcdirmid.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mcdirmid.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mcdirmid.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mcdirmid.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mcdirmid.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mcdirmid.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mcdirmid.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mcdirmid.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mcdirmid.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mcdirmid.wordpress.com/36/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mcdirmid.wordpress.com&amp;blog=8484952&amp;post=36&amp;subd=mcdirmid&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mcdirmid.wordpress.com/2009/07/22/bling-manifesto/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6829d6ae4bda3a38255a96637b944a5a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mcdirmid</media:title>
		</media:content>
	</item>
		<item>
		<title>Fun(ctional) graphics in C#!</title>
		<link>http://mcdirmid.wordpress.com/2009/07/20/functional-graphics-in-c/</link>
		<comments>http://mcdirmid.wordpress.com/2009/07/20/functional-graphics-in-c/#comments</comments>
		<pubDate>Mon, 20 Jul 2009 04:09:26 +0000</pubDate>
		<dc:creator>mcdirmid</dc:creator>
				<category><![CDATA[Bling]]></category>

		<guid isPermaLink="false">http://mcdirmid.wordpress.com/2009/07/20/functional-graphics-in-c/</guid>
		<description><![CDATA[Graphics programming often involves customizing and combining well known techniques as mathematic formulas and algorithms related to geometry, lighting, physics, and so on. For performance and architecture reasons, realizing these formulas in a real programming involves drastic transformations that results in code that is hard to read and write. For example, multiple graphics techniques are [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mcdirmid.wordpress.com&amp;blog=8484952&amp;post=34&amp;subd=mcdirmid&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Graphics programming often involves customizing and combining well known techniques as mathematic formulas and algorithms related to geometry, lighting, physics, and so on. For performance and architecture reasons, realizing these formulas in a real programming involves drastic transformations that results in code that is hard to read and write. For example, multiple graphics techniques are encoded into low-level pixel and vertex shader code in way that renders them unrecognizable.</p>
<p>One solution is to encode graphic techniques in a high-level functional programming language, where functions allow us to effectively represent, combine, and manipulate graphic techniques. Take for example lighting computations that can be represented as a function <strong>Position3D –&gt; Normal3D –&gt; InputColor –&gt; ResultColor</strong>, which can then be combined via addition: take two lighting computations <strong><em>l1</em></strong> and <strong><em>l2</em></strong>, where a succinct <strong><em>l1</em></strong> + <strong><em>l2</em></strong> expands to p –&gt; n –&gt; c –&gt; <strong><em>l1</em></strong>(p)(n)(c) + <strong><em>l2</em></strong>(p)(n)(c). As graphics is math-intensive, it benefits dramatically from function representations.</p>
<p>Unfortunately, their are a couple of drawbacks to this approach. First, the execution of a functional program is drastically slower than imperative code. However, as most graphics computations are moving to GPUs via memory-restricted shader code, this problem can be solved by generating shader code from functional programs. Such is the approach taken by <a href="http://conal.net/" target="_blank">Conal Elliott</a>’s Haskell-hosted <a href="http://conal.net/Vertigo/">Vertigo</a> library done at MSR. In Vertigo, geometries can be expressed as <a href="http://en.wikipedia.org/wiki/Parametric_surface" target="_blank">parametric surfaces</a>, <a href="http://en.wikipedia.org/wiki/Surface_normal" target="_blank">surface normals</a> for lighting are computed via symbolic differentiation. The second drawback is more one of familiarity: the techniques seem to require abandoning our existing mainstream languages and tools for dramatically different and less familiar languages such as Haskell. However, while functional programming definitely benefits from functional languages, functional programming techniques can definitely be applied in more familiar languages. As a mainstream language, C# even provides a lambda construct to support programmers who want to dabble in functional programming; e.g., by using <a href="http://en.wikipedia.org/wiki/Linq" target="_blank">LINQ</a> to query databases.</p>
<p><span id="more-34"></span>I’m implementing a functional graphics library in <a href="http://bling.codeplex.com/" target="_blank">Bling</a> for C#. Bling supports the creation and composition of expression trees as seemingly normal C# expressions, allowing us to easily compose code in a high level language and then ship the result to the GPU as a vertex or pixel shader. This allows us, among other things, to support a style of programming very similar to how Vertigo is used in Haskell. For example, consider the definition of a sphere parametric surface in Bling:</p>
<pre class="code"><span style="color:blue;">public static readonly </span><span style="color:#2b91af;">PSurface </span>Sphere = <span style="color:blue;">new </span><span style="color:#2b91af;">PSurface</span>((<span style="color:#2b91af;">PointBl </span>p) =&gt; {
  <span style="color:#2b91af;">PointBl </span>sin = p.SinU;
  <span style="color:#2b91af;">PointBl </span>cos = p.CosU;
  <span style="color:blue;">return new </span><span style="color:#2b91af;">Point3DBl</span>(sin[0] * cos[1], sin[0] * sin[1], cos[0]);
});</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>PSurface is a wrapper around a function from PointBl to Point3DBl, which are wrapper types around point (R2) and 3D point (R3) expression trees. SinU and CosU define scaled sine and cosine values over points between [0,0] and [1,1] by using the coordinates as percentage for 2PI angles. Rendering a sphere in Bling is simply a matter of creating some light and defining how many vertices we want to sample in the resulting vertex buffer:</p>
<pre class="code"><span style="color:#2b91af;">PSurface </span>Surface = <span style="color:#2b91af;">Geometries</span>.Sphere;
<span style="color:#2b91af;">DirectionalLightBl </span>dirLight = <span style="color:blue;">new </span><span style="color:#2b91af;">DirectionalLightBl</span>() {
  Direction = <span style="color:blue;">new </span><span style="color:#2b91af;">Point3DBl</span>(0, 0, 1),
  Color = <span style="color:#2b91af;">Colors</span>.White,
};
<span style="color:#2b91af;">ParametricKeys </span>SurfaceKeys = <span style="color:blue;">new </span><span style="color:#2b91af;">ParametricKeys</span>(200, 200);
Device.Render(SurfaceKeys, (<span style="color:#2b91af;">IntBl </span>n, <span style="color:#2b91af;">PointBl </span>uv, <span style="color:#2b91af;">IVertex </span>vertex) =&gt; {
  vertex.Position = (Surface * (world * view * project))[uv]; ;
  <span style="color:#2b91af;">Point3DBl</span><span style="color:blue;"> </span>norm = (<span style="color:#2b91af;">Point3DBl</span>)(Surface.Normals[uv] * world).Normalize;
  <span style="color:#2b91af;">Point3DBl </span>usePosition = (<span style="color:#2b91af;">Point3DBl</span>)((Surface[uv] * (world)));
  vertex.Color = dirLight.Diffuse()[usePosition, norm](n.SelectColor());
});</pre>
<p>where world, view, and project are standard 4&#215;4 matrices used in translating position in 3D scenes. This code creates a directional light coming from the bottom (reused from WPF 3D no less!) and defines a set of surface keys over 200 by 200 vertices, meaning 40,000 vertices are sampled in the rendered sphere. The light is applied to the sphere in a render function using a world transformed position of each vertex along with a world transformed normal that is automatically computed via the derivative of the parametric surface. The color for each vertex is selected based on the vertex index, leading to a nice spiral pattern in the sphere that also gives us an idea of vertex topology. Here is the result:</p>
<p><a href="http://mcdirmid.files.wordpress.com/2009/07/image.png"><img style="display:inline;border-width:0;" title="image" src="http://mcdirmid.files.wordpress.com/2009/07/image_thumb.png?w=244&#038;h=220" border="0" alt="image" width="244" height="220" /></a></p>
<p>As described in the <a href="http://conal.net/papers/Vertigo/" target="_blank">Vertigo paper</a>, interesting geometries can also be formed from surfaces via displacement by height fields. Copying the examples in the vertigo paper, consider an eggcrate height field that whose definition in Bling has a simple structure similar to sphere:</p>
<pre class="code"><span style="color:blue;">public static readonly </span><span style="color:#2b91af;">HeightField </span>EggCrate = <span style="color:blue;">new </span><span style="color:#2b91af;">HeightField</span>((<span style="color:#2b91af;">PointBl </span>p) =&gt; {
  p = p.SinCosU;
  <span style="color:blue;">return </span>p.X * p.Y;
});</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The displacement method on surfaces is then defined as follows:</p>
<pre class="code"><span style="color:blue;">public </span><span style="color:#2b91af;">PSurface </span>Displace(<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">PointBl</span>, <span style="color:#2b91af;">DoubleBl</span>&gt; HeightField) {
  <span style="color:blue;">return new </span><span style="color:#2b91af;">PSurface</span>((<span style="color:#2b91af;">PointBl</span> p) =&gt;
    <span style="color:blue;">this</span>[p] + Normals[p] * HeightField(p));
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>As with lighting computations, surface normals are used to determine the proper direction in which to apply the height field. We can then apply the egg crate height field to a sphere as follows:</p>
<pre class="code"><span style="color:#2b91af;">PSurface </span>Surface = <span style="color:#2b91af;">Geometries</span>.Sphere.
  Displace((<span style="color:#2b91af;">Geometries</span>.EggCrate.Frequency(20d).Magnitude(sliderZ.Value * .5)));</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The frequency and magnitude of a height field are adjusted via methods that have one line implementations (again, this is described in the Vertigo paper). One twist is that we control the magnitude by a slider (Z), which is a standard WPF slider with a value dependency property. Now, by moving the slider up, the sphere becomes deformed via the egg crate height field:</p>
<p><a href="http://mcdirmid.files.wordpress.com/2009/07/image1.png"><img style="display:inline;border-width:0;" title="image" src="http://mcdirmid.files.wordpress.com/2009/07/image_thumb1.png?w=208&#038;h=244" border="0" alt="image" width="208" height="244" /></a></p>
<p>Moving the slider even farther up, the sphere becomes spiky:</p>
<p><a href="http://mcdirmid.files.wordpress.com/2009/07/image2.png"><img style="display:inline;border-width:0;" title="image" src="http://mcdirmid.files.wordpress.com/2009/07/image_thumb2.png?w=227&#038;h=244" border="0" alt="image" width="227" height="244" /></a></p>
<p>The change in deformation occurs in real time, so we see a smooth animation as the sphere becomes deformed.</p>
<p>Bling will automatically determine what code executes outside of the shader in the form of either uniforms (per-shader external variables) or vertex buffers (per-vertex data). Bling will also determine what code runs in pixel shaders vs. vertex shaders, and will automatically generate vertex input and output structures to accommodate communication between the two kinds of shaders. Bling will also generate code to handle update uniforms and vertex buffers during rendering, requiring absolutely no boilerplate code on behalf of the programmer. Instead, the programmer can just focus on what graphics techniques they want to use, without needing to worry about adapting them to fit on the underlying graphics architecture. For the above example, here is the HLSL code that Bling generates, which is then rendered using Direct3D 10:</p>
<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:00d280bb-aaf4-4702-b383-eb9916c75cd7" class="wlWriterEditableSmartContent" style="width:750px;display:block;float:none;margin-left:auto;margin-right:auto;padding:5px;">
<div style="border:#000080 1px solid;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background:#ddd;max-height:300px;overflow:scroll;padding:0;">
<ol style="background:#ffffff;white-space:wrap;margin:0 0 0 35px;">
<li> float U0;</li>
<li> float4x4 U1;</li>
<li> float4x4 U2;</li>
<li> float3 U3;</li>
<li> float3 U4;</li>
<li> struct VS_Input {</li>
<li> float P0 : POSITION;</li>
<li> float3 P1 : POSITION1;</li>
<li> float3 P2 : POSITION2;</li>
<li> float P3 : NORMAL;</li>
<li> float3 P4 : NORMAL1;</li>
<li> float3 P5 : NORMAL2;</li>
<li> float P6 : NORMAL3;</li>
<li> float3 P7 : NORMAL4;</li>
<li> float3 P8 : NORMAL5;</li>
<li> float4 P9 : COLOR;</li>
<li> };</li>
<li> struct VS_Output {</li>
<li> float4 Pos : SV_Position;</li>
<li> float4 P0 : COLOR;</li>
<li> };</li>
<li> VS_Output VS(VS_Input input) {</li>
<li> VS_Output output = (VS_Output) 0;</li>
<li> float t0_0 = (U0 * input.P0);</li>
<li> float3 t0_1 = t0_0.xxx;</li>
<li> float3 t0_2 = (input.P1 * t0_1);</li>
<li> float3 t0_3 = (input.P2 + t0_2);</li>
<li> float3 t0_4 = t0_3.xyz;</li>
<li> float4 t0_5 = float4(t0_4, 1);</li>
<li> float4 t0_6 = t0_5;</li>
<li> float4 t0_7 = mul(t0_6, U1);</li>
<li> float4 t0_8 = t0_7;</li>
<li> float3 t0_9 = t0_8.xyz;</li>
<li> float3 t0_10 = t0_8.w.xxx;</li>
<li> float3 t0_11 = (t0_9 / t0_10);</li>
<li> float4 t0_12 = float4(t0_11, 1);</li>
<li> float t0_13 = (U0 * input.P3);</li>
<li> float3 t0_14 = t0_13.xxx;</li>
<li> float3 t0_15 = (input.P1 * t0_14);</li>
<li> float3 t0_16 = (t0_1 * input.P4);</li>
<li> float3 t0_17 = (t0_15 + t0_16);</li>
<li> float3 t0_18 = (input.P5 + t0_17);</li>
<li> float3x1 t0_19 = float3x1(t0_18.x, t0_18.y, t0_18.z);</li>
<li> float3 t0_20 = t0_19;</li>
<li> float t0_21 = (U0 * input.P6);</li>
<li> float3 t0_22 = t0_21.xxx;</li>
<li> float3 t0_23 = (input.P1 * t0_22);</li>
<li> float3 t0_24 = (t0_1 * input.P7);</li>
<li> float3 t0_25 = (t0_23 + t0_24);</li>
<li> float3 t0_26 = (input.P8 + t0_25);</li>
<li> float3x1 t0_27 = float3x1(t0_26.x, t0_26.y, t0_26.z);</li>
<li> float3 t0_28 = t0_27;</li>
<li> float3 t0_29 = cross(t0_20, t0_28);</li>
<li> float3 t0_30 = normalize(t0_29);</li>
<li> float3 t0_31 = t0_30.xyz;</li>
<li> float4 t0_32 = float4(t0_31, 1);</li>
<li> float4 t0_33 = t0_32;</li>
<li> float4 t0_34 = mul(t0_33, U2);</li>
<li> float4 t0_35 = t0_34;</li>
<li> float4 t0_36 = normalize(t0_35);</li>
<li> float3 t0_37 = t0_36.xyz;</li>
<li> float3 t0_38 = t0_36.w.xxx;</li>
<li> float3 t0_39 = (t0_37 / t0_38);</li>
<li> float t0_40 = dot(U3, t0_39);</li>
<li> float t0_41 = max(t0_40, 0);</li>
<li> float3 t0_42 = t0_41.xxx;</li>
<li> float3 t0_43 = (U4 * t0_42);</li>
<li> float4 t0_44 = float4(t0_43, 1);</li>
<li> float4 t0_45 = (t0_44 * input.P9);</li>
<li> output.Pos = t0_12;</li>
<li> output.P0 = t0_45;</li>
<li> return output;</li>
<li> }</li>
<li> float4 PS(VS_Output input) : SV_Target {</li>
<li> float4 retV;</li>
<li> retV = input.P0;</li>
<li> return retV;</li>
<li> }</li>
<li> technique10 Render {</li>
<li> pass P0 {</li>
<li> SetVertexShader( CompileShader( vs_4_0, VS() ) );</li>
<li> SetGeometryShader(NULL);</li>
<li> SetPixelShader(CompileShader(ps_4_0, PS()));</li>
<li> }</li>
<li> }</li>
</ol>
</div>
</div>
</div>
<p>Since the code is auto-generated, it is not very pretty, but it doesn’t have to be. I still need to work on the conversion process to minimize the number of vertex parameters passed in as input, as these are limited to 16 and can easily be exhausted when more external values (e.g., sliders) are added to parameterize geometry and lighting.</p>
<p>The code for this example is currently available in our codeplex SVN repository at <a title="https://bling.svn.codeplex.com/svn/Bling3" href="https://bling.svn.codeplex.com/svn/Bling3">https://bling.svn.codeplex.com/svn/Bling3</a>, and I’m currently working on cleaning things up for a new release of Bling (titled Bling 3) that will support rich UI construction in WPF and preliminary support for DirectX 10 (sorry XP users!) as described in this post.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mcdirmid.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mcdirmid.wordpress.com/34/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mcdirmid.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mcdirmid.wordpress.com/34/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mcdirmid.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mcdirmid.wordpress.com/34/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mcdirmid.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mcdirmid.wordpress.com/34/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mcdirmid.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mcdirmid.wordpress.com/34/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mcdirmid.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mcdirmid.wordpress.com/34/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mcdirmid.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mcdirmid.wordpress.com/34/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mcdirmid.wordpress.com&amp;blog=8484952&amp;post=34&amp;subd=mcdirmid&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mcdirmid.wordpress.com/2009/07/20/functional-graphics-in-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6829d6ae4bda3a38255a96637b944a5a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mcdirmid</media:title>
		</media:content>

		<media:content url="http://mcdirmid.files.wordpress.com/2009/07/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://mcdirmid.files.wordpress.com/2009/07/image_thumb1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://mcdirmid.files.wordpress.com/2009/07/image_thumb2.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
	</channel>
</rss>
