Monday, November 15, 2010

Drawing shapes in mental mill

This post should have been originally part of a much much longer entry, but it turned out to be way too elaborate, so I will start very small. The post today is all about drawing simple geometric shapes in mental mill, using the texture space as a coordinate sytem.

"So why would I ever want to do that!?" you may ask next. This is a good and valid question. It will become more obvious when I have one of my next blog entries ready that implements a simple 2 dimensional ray marcher in a shader. For now, just assume that you would like to render simple geometric shapes such as spheres and squares.

Rendering procedural 2D shapes in a shader
In a shader you can't just say "Draw a line from A to B" - this is because a shader is executed when the triangles and lines are being rasterized, so a shader can not issue drawing calls. But the shader has access to certain information that is passed along like texture coordinates, surface normal etc.
If we want a shader to draw procedural shapes, we need to change the process of generating procedural shapes. Instead of asking our program to draw something (which we can not do) we ask it instead: Is the (current) pixel that we are about to display near the line? If yes, it will receive the line color, otherwise we will use some background color.


Here we will use the texture coordinates as our coordinate system. This is also perfect to inspect in mental mill on the 'plane' geometry. Check out the shader code here.


This shader provides some control over the size and the position of the circle.

Rendering an outlined circle
However, we can change our shader to render a circle with a line. We do this by testing how far the current point is away from the boundary of the circle. If it is within a given range, we apply a smoothstep function which outputs a value from 0 to 1 when the length varies betwen 0 and "line_width".


The result of the shader can be seen here:

This is just the beginning. In the next post I will show how to render lines and squares, so stay tuned for more! Feel free to ask questions if you need more explanations. Shade safe and have a nice day! :)

No comments:

Post a Comment