<?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/"
	>

<channel>
	<title>CreativeApplications.Net &#187; Tutorials</title>
	<atom:link href="http://www.creativeapplications.net/category/tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.creativeapplications.net</link>
	<description>Apps that Inspire..</description>
	<lastBuildDate>Thu, 09 Feb 2012 19:01:16 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Shaders, Geometry, and the Kinect &#8211; Part 1 [Cinder, Tutorials]</title>
		<link>http://www.creativeapplications.net/tutorials/shaders-geometry-and-the-kinect-part-1-cinder-tutorials/</link>
		<comments>http://www.creativeapplications.net/tutorials/shaders-geometry-and-the-kinect-part-1-cinder-tutorials/#comments</comments>
		<pubDate>Thu, 12 Jan 2012 11:45:26 +0000</pubDate>
		<dc:creator>Joshua Noble</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[cinder]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[glsl]]></category>
		<category><![CDATA[gpu]]></category>
		<category><![CDATA[Joshua Noble]]></category>
		<category><![CDATA[kinect]]></category>
		<category><![CDATA[shaders]]></category>
		<category><![CDATA[shading]]></category>
		<category><![CDATA[Stephen Schieberl]]></category>

		<guid isPermaLink="false">http://www.creativeapplications.net/?p=21182</guid>
		<description><![CDATA[By Stephen Schieberl and Joshua Noble We&#8217;ve heard it plenty of times when people are talking about working with the Kinect: &#8220;we&#8217;ll just get the point cloud and turn it a mesh&#8221;. You may have even thought that yourself at some point, &#8220;this is going to be easy&#8221; Well, it&#8217;s actually fairly difficult to do [...]]]></description>
			<content:encoded><![CDATA[<p><strong>By <a href="http://www.bantherewind.com/">Stephen Schieberl</a> and <a href="http://thefactoryfactory.com/">Joshua Noble</a></strong></p>
<p>We&#8217;ve heard it plenty of times when people are talking about working with the Kinect: &#8220;we&#8217;ll just get the point cloud and turn it a mesh&#8221;. You may have even thought that yourself at some point, &#8220;this is going to be easy&#8221; Well, it&#8217;s actually fairly difficult to do and especially difficult to do quickly, because a mesh is a complex object to create and update in realtime. In a mesh of either triangles or quads, each surface needs to be correctly oriented to it&#8217;s neighboring surfaces and to the camera. When working with a point cloud coming from the Kinect you have several thousand points which means several thousand pieces of geometry needing to be created all at once. The typical approach that people use is to just display the points and not worry about trying to make surfaces or shapes out of those points. While this is fine for some projects, we&#8217;d like to see more people dig into making real shapes from their Kinect imagery so we&#8217;re going to show you how to do that in two different ways. This is a fairly advanced tutorial that focuses a little more on theory and implementation rather than a specific toolset. What we&#8217;re going to talk about in this article can be applied to any of the creative coding toolkits, but we&#8217;ll be making projects for Cinder to demonstrate. If you don&#8217;t know anything about Cinder, I suggest you take a look here: http://libcinder.org/ and check it out. With that said, let&#8217;s get into some theory.</p>
<p>Point clouds are big and connecting those points in a 3D shape is slow. We need to make geometry and we need to make it fast, so we&#8217;re going to look at two approaches to using shaders to either generate our geometry and to position the RGB data that we receive from the camera. To do that we’re going to use shaders because they can be faster and they more neatly separate the code that accesses our peripherals, i.e. the Kinect, from the code that creates our geometry and displays the mesh.</p>
<h2>A quick introduction to shaders</h2>
<p>This is a very quick introction to shaders, for more detail there are a lot of resources that you can look at: The Orange Book, Nehe, even glsl.heroku.com/. For now though, we just want to make sure you get the basics: GLSL (Graphics Language Shading Language) is an abbreviation for the official OpenGL Shading Language. GLSL is a high-level programming language that’s similar to C/C++ for several parts of the graphics card. With GLSL, you can code short programs, called shaders, which are executed on the GPU. GLSL can be fairly confusing because graphics card support is a little bit unreliable, i.e. what works on one card may not work on another, and because the differences between versions is significant. However, whether you’re working with GL ES on mobile devices or WebGL, or with full GLSL in a Cinder application, the basics are the same, and an understanding of how the shading pipeline functions will serve you well in any OpenGL platform or with other shading tools like CG, HLSL, or ARB.</p>
<p>Before we get started though, you might want to know what version of GLSL you’re running. This isn’t mandatory, but it is pretty handy. Downloading and running the following: http://www.realtech-vr.com/glview/ will let you know what version of GLSL your computer supports. If you aren’t interested in that, or you already know, feel free to skip that step.</p>
<p>So, first, the basics: a shading language is a special programming language adapted to easily map on shader programming. Those kinds of languages usually have special data types such as color and normal. Because of the various target markets of 3D graphics, different shading languages have been developed: fragment shaders, geometry shaders, vertex shaders. In this article we&#8217;re interested in GLSL. GLSL shaders themselves are just text that is passed to the graphics card drivers for compilation from within an application using the OpenGL API’s entry points. Shaders can be created on the fly from within an application or read in as text files, but they must be sent to the driver in the form of a text string.</p>
<p>There are three fundamental steps in shading: read and modify any vertices, create or modify any geometry, and read and modify any pixel data. The OpenGL shader pipeline looks roughly like this:</p>
<p><img class="alignright size-full wp-image-21188" title="shading" src="http://www.creativeapplications.net/wp-content/uploads/2012/01/shading.png" alt="" width="600" height="573" /></p>
<p>Let&#8217;s break that down a bit.</p>
<h3>Vertex Shaders</h3>
<p>A vertex shader has attributes about a location in space or vertex, which means not only the actual coordinates of that location but also its color, how any textures should be mapped onto it, and how the vertices are modified in the operation. A vertex shader can change the positions of each vertex, the number of lighting computations per vertex, and the color that will be applied to each vertex.</p>
<p>Your application certainly doesn’t need to do all of these operations to use a vertex shader. As you’ll see in the next code example, you don’t need to apply lights to your objects. Even though you don’t need to use all the functionality of the vertex shader, when you create and apply a vertex shader, your program will assume that you’re replacing all the functionality of your other vertex transformations. If you apply changes to particular vertex, the vertex shader will probably change those according to the instructions contained in the vertex shader. When a vertex shader is used, it becomes responsible for replacing all the needed functionality of this stage of the pipeline.</p>
<p>The vertex processor processes each vertex individually and doesn’t store any data about the other vertices that it has already processed or that it will process. It is responsible for at least modifying (or not) the position of the vertex and then writing it to the next shaders, usually transforming the vertex with the ModelView and Projection matrices. It does this by writing to the gl_Position, which is where OpenGL stores the location of the vertex. A vertex processor has access to OpenGL state, so it can perform operations that involve lighting for instance, and use materials, and can even access textures.<br />
So, what does a vertex shader look like? They can be quite simple. Take a look at the following example. It’s a single function that sets the value of each vertex passed to it. To be nice to everyone, no matter what graphics card they’re running, we need to make a small split here, showing two different ways of doing things.</p>
<p><strong>GLSL 1.2</strong></p><pre class="crayon-plain-tag"><code>void main() {
    vec4 v = vec4(gl_Vertex);</code></pre><p>As a quick example, the x position of the vertex is shifted over by 1 pixel:</p><pre class="crayon-plain-tag"><code>v.x += 1;
Now the final position of the vertex is set:
    gl_Position = gl_ModelViewProjectionMatrix * v;
}</code></pre><p><strong>GLSL 1.3+</strong></p><pre class="crayon-plain-tag"><code>uniform mat4 mvp; // this is set for the entire shader, it doesn&rsquo;t change for each point
in vec4 vertexIn; // this is set for each vertex, i.e it changes for each point

void main() {
    v.x += 1.;</code></pre><p><p><p>
Now the final position of the vertex is set:</p><pre class="crayon-plain-tag"><code>gl_Position = mvp * vertexIn;
}</code></pre><p>Here the vertex that is currently being operated on is used to create a new vertex: As a quick example, the x position of the vertex is shifted over by an arbitrary amount. That’s a very simple vertex shader that doesn’t alter your image in any immediately noticeable way, but it does show you how the vertex shader functions. In 1.2 the vertex passed to the shader can be accessed within that method as gl_Vertex, and its final position after the operation can be set using the gl_Position variable:</p>
<h3>Geometry Shader</h3>
<p>A geometry shader can generate new graphics primitives like points, lines, and triangles, from those primitives that were sent to the graphics card from the CPU. This means that you could get a point and turn it into a triangle or even a bunch of triangles, or get a line and turn it into a rectangle, or do real-time extrusion.</p>
<p><img class="alignright size-full wp-image-21189" title="gemo" src="http://www.creativeapplications.net/wp-content/uploads/2012/01/gemo.png" alt="" width="600" height="525" /></p>
<p>Geometry shader programs are executed after the vertex shader and before the fragment shader. As an example, if your oF application creates triangles and passes them to the vertex shader, then your geometry shader will receive one triangle at a time. What you do with those is up to you. You could, for instance, turn each triangle into 2 triangles or add additional points around each triangle. As long as you declare what your geometry shader will be getting in and what it will be churning out, everything will be passed to the fragment shader to be colored in without a problem. A very simple geometry shader looks like this:</p>
<p><strong>GLSL 1.2</strong></p><pre class="crayon-plain-tag"><code>void main() {
  for(int i = 0; I &amp;lt; gl_VerticesIn; ++i) {
     gl_FrontColor = gl_FrontColorIn[i];
     gl_Position = gl_PositionIn[i];
    EmitVertex();
  }
}</code></pre><p><strong>GLSL 1.3+</strong></p><pre class="crayon-plain-tag"><code>in vec4 vertex;
out vec4 color;
void main() {
  for(int i = 0; i &amp;lt; gl_VerticesIn; ++i) {
    gl_Position = gl_PositionIn[i];
    color = vec4( i / 4., 1 - i/4., 0, 1.);
    EmitVertex();
  }
  EmitPrimitive();
}</code></pre><p>The number of vertices being passed in with the gl_VerticesIn variable will be the same as the GL type that you’re using. If you’re using points, it’ll be one. If you’re using quads, it’ll be four. gl_Position is where you want to put the vertex that you’re creating and EmitVertex() is how you say that you’re done with a vertex. EmitPrimitive is how you tell the geometry shader that you’re done with creating geometry all together. The diagram below shows how you would create a quad out of GL_TRIANGLE_STRIP from a GL_POINT. This means that the vertex shader receives a point, manipulates its position, and then passes the coordinates of that point to the geometry shader. The geometry shader then generates the 4 points to create the quad using the received position, calls EmitPrimitive() when the quad is complete, and then passes the data on to the fragment shader.</p>
<h3>Fragment Shader</h3>
<p>The fragment shader is somewhat misleadingly named because what it really allows you to do is to change values assigned to each pixel. The vertex shader operates on the vertices, and the fragment shader operates on the pixels. By the time the fragment shader gets information passed into it by the graphics card, the color of a particular pixel has already been computed and in the fragment shader can be combined with an element like a lighting effecting, a fog effect, or a blur among many other options. The usual end result of this stage per fragment is a color value and a depth for the fragment.</p>
<p>The inputs of this stage are the pixel’s location and the fragment’s depth, whether it will be visible or altered by an effect, and color values.<br />
Just like vertex shaders, fragment shaders must also have a main() function. Just as the vertex shader provides you access to the current vertex using the gl_Vertex variable, the fragment shader provides you access to the current fragment, that is, the fragment that the fragment shader is working with when it is called, using the gl_FragColor variable. Like the gl_vertex, this is a four-dimensional vector that lets you set the RGB and alpha properties of the fragment. In the following example, the color of the fragment is set to a medium gray with full alpha:</p>
<p><strong>GLSL 1.2</strong></p><pre class="crayon-plain-tag"><code>#version 120
void main() {
        gl_FragColor = vec4(0.5, 0.5, 0.5, 1.0);
    }</code></pre><p><strong>GLSL 1.3+</strong></p><pre class="crayon-plain-tag"><code>#version 150
out vec4 color;
void main(void)
{
    color = vec4(1.0, 0.0, 0.0, 1.0);
}</code></pre><p>Notice how each of the channels is set using a floating point number from 0.0 to 1.0. The gl_FragColor is what is passed to the renderer to be displayed on the screen.</p>
<p>What we want is to be able to get a point cloud from the IR camera of the kinect and an RGB image from the RGB camera, to display them you need to assemble them. You can do this on the CPU or you can do it on the GPU, but at some point everything needs to go to the GPU so it can be drawn by the graphics card. Of the types of shaders that we&#8217;re going to focus more on the geometry shader, since our goal is to be able to make a mesh out of the points that we get quickly and in a lightweight way.</p>
<p>Probably the best way to understand this is to dig into some small demos of fun things that you can do when putting together points and shaders.</p>
<p>To save space and to keep you interested, we’re going to just look at the important parts of the applciations that are available for download and closer browsing <a href="https://github.com/joshuajnoble/CAN-Article-Code">here</a>.</p>
<p>The first application is a simple one, to introduce the basics and set the stage for what we’re going to do later on. As you can see in the picture below, we’ve got a control panel that allow you to control the drawing and the result shown behind the control panel.</p>
<p><img class="alignright size-large wp-image-21190" title="01_shape0" src="http://www.creativeapplications.net/wp-content/uploads/2012/01/01_shape0-640x375.png" alt="" width="640" height="375" /></p>
<p>We’re actually doing all the drawing in the geometry shader so we’ll unpack how that’s done. First, the Cinder application .cpp file. The github link is here. Take a look at the loadShaders() method:</p><pre class="crayon-plain-tag"><code>// Find maximum number of output vertices for geometry shader
	int32_t maxGeomOutputVertices;
	glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT, &amp;amp; maxGeomOutputVertices);</code></pre><p>This is important: every graphics card will have a maximum number of vertices that it can output. For most modern cards this is 1024 or even more, but you want to set your shader to output only as many as you need. In this case, since we’re just demonstrating the basics, we’ll go with the max number that the card supports but in practice, you never want to do this. This is passed to the geometry shader when you actually load it onto graphics card. Each programming framework, Processing, WebGL, OF, Cinder, etc, has a slightly different syntax for this, but the basic idea is always the same: load the vertex shader, the fragment shader, and optionally the geometry shader. If you load a geometry shader you need to say what type of OpenGL primitive you’re passing to the geometry shader, what kind of OpenGL primitive you’re outputting, and the number of vertices that you’re going to be outputting. Here’s the cinder implementation that we’re using:</p><pre class="crayon-plain-tag"><code>mShaderPassThru = gl::GlslProg(
	loadResource(RES_SHADER_VERT_150),
	loadResource(RES_SHADER_FRAG_150),
	loadResource(RES_SHADER_GEOM_150),
	GL_POINTS, GL_POINTS, 1); // note: 1 point out

mShaderTransform = gl::GlslProg(
	loadResource(RES_SHADER_VERT_150),
	loadResource(RES_SHADER_FRAG_150),
	loadResource(RES_SHADER_GEOM_150),
	GL_POINTS, GL_TRIANGLE_STRIP, maxGeomOutputVertices
	); // note max points out</code></pre><p><p><p><p><p><p><p><p><p><p>
The draw() method in the first application is quite simple, draw a bunch of points and you’re good to go.</p><pre class="crayon-plain-tag"><code>// Draw points
	mShader.bind();
	glBegin(GL_POINTS);
	for (vector::const_iterator pointIt = mPoints.cbegin(); pointIt != mPoints.cend(); ++pointIt)
		gl::vertex(* pointIt);
	glEnd();
	mShader.unbind();</code></pre><p>Again, that’s Cinder, but actual shader can be used in any programming framework, so let’s dig into that a little bit because the real trick here is making a geometry shader for points.</p><pre class="crayon-plain-tag"><code>#version 120
#extension GL_EXT_geometry_shader4 : enable
#extension GL_EXT_gpu_shader4 : enable 

// Constants to match those in CPP
const int SHAPE_CIRCLE = 2;
const int SHAPE_SQUARE = 1;
const int SHAPE_TRIANGLE = 0;

// Uniforms
uniform float aspect;
uniform int shape;
uniform float size;
uniform bool transform;

// Kernel
void main(void)
{
	// Key on shape
	switch (shape)
	{

		case SHAPE_TRIANGLE:</code></pre><p><p><p><p><p><p><p><p><p><p><p><p>
To draw a triangle, we add the size times the cos and sin of each angle to the original position. After each point is set, we call EmitVertex() to the newly created vertex to the geometry that will be sent to the fragment shader. Be sure to draw counter-clockwise.</p><pre class="crayon-plain-tag"><code>gl_Position = gl_PositionIn[0] + vec4(cos(radians(270.0)) * size, sin(radians(270.0)) * size * aspect, 0.0, 0.0);
		EmitVertex();
		gl_Position = gl_PositionIn[0] + vec4(cos(radians(150.0)) * size, sin(radians(150.0)) * size * aspect, 0.0, 0.0);
		EmitVertex();
		gl_Position = gl_PositionIn[0] + vec4(cos(radians(30.0)) * size, sin(radians(30.0)) * size * aspect, 0.0, 0.0);
		EmitVertex();</code></pre><p>Call EndPrimitive() to close the shape. In this case we don’t strictly need this since we’re only drawing one primitive and the GLSL program can figure out that we’re done making our primitive, but when you have more than one primitive, it’s vitally important to call this whenever you’ve finished one of whatever type of primitive you’re creating.</p><pre class="crayon-plain-tag"><code>EndPrimitive();

		break;
		case SHAPE_SQUARE:</code></pre><p><p><p><p><p><p><p><p><p><p><p><p><p><p>
		To draw a square, we will draw two triangles, just like  above. The two triangles will share vertices, so we&#8217;ll define the vertices in advance.</p>
<pre class="crayon-plain-tag"><code>vec4 vert0 = vec4(cos(radians(315.0)) * size, sin(radians(315.0)) * size * aspect, 0.0, 0.0);
		vec4 vert1 = vec4(cos(radians(225.0)) * size, sin(radians(225.0)) * size * aspect, 0.0, 0.0);
		vec4 vert2 = vec4(cos(radians(135.0)) * size, sin(radians(135.0)) * size * aspect, 0.0, 0.0);
		vec4 vert3 = vec4(cos(radians(45.0)) * size, sin(radians(45.0)) * size * aspect, 0.0, 0.0);

			// Draw the left triangle
			gl_Position = gl_PositionIn[0] + vert0;
			EmitVertex();
			gl_Position = gl_PositionIn[0] + vert1;
			EmitVertex();
			gl_Position = gl_PositionIn[0] + vert3;
			EmitVertex();

			// Close this triangle
			EndPrimitive();

			// And now the right one
			gl_Position = gl_PositionIn[0] + vert3;
			EmitVertex();
			gl_Position = gl_PositionIn[0] + vert1;
			EmitVertex();
			gl_Position = gl_PositionIn[0] + vert2;
			EmitVertex();

			// Close the second triangle to form a quad
			EndPrimitive();

			break;
			case SHAPE_CIRCLE:

			// To draw a circle, we'll iterate through 24
			// segments and form triangles
			float twoPi = 6.283185306;
			float delta = twoPi / 24.0;
			for (float theta = 0.0; theta &amp;lt; twoPi; theta += delta)
			{
					// Draw a triangle to form a wedge of the circle
				gl_Position = gl_PositionIn[0] + vec4(cos(theta) * size, sin(theta) * size * aspect, 0.0, 0.0);
				EmitVertex();
				gl_Position = gl_PositionIn[0];
				EmitVertex();
				gl_Position = gl_PositionIn[0] + vec4(cos(theta + delta) * size, sin(theta + delta) * size * aspect, 0.0, 0.0);
				EmitVertex();
				EndPrimitive();
			}

			break;

		}

	}
}</code></pre><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p>
So that’s pretty interesting, but next let’s make boxes for all those points and then things will get more interesting.</p>
<p><img class="alignright size-large wp-image-21191" title="03_box2" src="http://www.creativeapplications.net/wp-content/uploads/2012/01/03_box2-640x375.jpg" alt="" width="640" height="375" /></p>
<p>Actually, if you’ve done any OpenGL, making a cube using a geometry shader is going to look very familiar since it involves almost the same code as the glVertex() version, only with the addition of EmitVertex() and EmitPrimitive(). First though, we’re going to dig into the Cinder application to show a few new features.</p>
<p>We’re going to use a Vertex Buffer Object to create objects and points that we can work with in the geometry shader. If VBOs aren’t familiar to you and you want to learn more about how to work with them in Cinder, check out http://www.creativeapplications.net/tutorials/guide-to-meshes-in-cinder-cinder-tutorials/</p>
<p>First, set up the mesh using a vbo layout object:</p><pre class="crayon-plain-tag"><code>// Set VBO layout, we use this to set up how the VBO is configured in the GPU memory
	mVboLayout.setStaticIndices();
	mVboLayout.setStaticPositions();

	// Iterate through the grid dimensions
	for (int32_t y = 0; y &amp;lt; mMeshHeight; y++) {
		for (int32_t x = 0; x &amp;lt; mMeshWidth; x++)
		{

			// Set the index of the vertex in the VBO so it is
			// numbered left to right, top to bottom
			mVboIndices.push_back(x + y * mMeshWidth);

			// Set the position of the vertex in world space
			mVboVertices.push_back(Vec3f((float)x - (float)mMeshWidth * 0.5f, (float)y - (float)mMeshHeight * 0.5f, 0.0f));

		}
	}</code></pre><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p>
Now we actually add all the indices and positions to the VBOMesh:</p><pre class="crayon-plain-tag"><code>mVboMesh = gl::VboMesh(mVboVertices.size(), mVboIndices.size(), mVboLayout, GL_POINTS);
	mVboMesh.bufferIndices(mVboIndices);
	mVboMesh.bufferPositions(mVboVertices);</code></pre><p>Normally you do some modificiation of the VBO on the CPU in the update() method, but we’re interested in moving as much of our processing as possible to the GPU, so we’re not doing any of that. We do however need to be able to pass variables into our shader so we can generate the wave and correctly position the view onto the mesh. We do this using Uniforms, which as mentioend eaelir in the article are values passed into the shader on a per shader basis. Not every shader (vertex, geometry, fragment) needs to read them, but they are available for all shaders. Here’s how we pass all the values into the shaders and then draw the VBOMesh:</p><pre class="crayon-plain-tag"><code>// Bind and configure shader
	mShader.bind();
	mShader.uniform(&quot;alpha&quot;, mMeshAlpha);
	mShader.uniform(&quot;amp&quot;, mMeshWaveAmplitude);
	mShader.uniform(&quot;eyePoint&quot;, mEyePoint);
	mShader.uniform(&quot;lightAmbient&quot;, mLightAmbient);
	mShader.uniform(&quot;lightDiffuse&quot;, mLightDiffuse);
	mShader.uniform(&quot;lightPosition&quot;, mLightPosition);
	mShader.uniform(&quot;lightSpecular&quot;, mLightSpecular);
	mShader.uniform(&quot;mvp&quot;, gl::getProjection() * gl::getModelView());
	mShader.uniform(&quot;phase&quot;, mElapsedSeconds);
	mShader.uniform(&quot;rotation&quot;, mBoxRotationSpeed);
	mShader.uniform(&quot;scale&quot;, mMeshScale);
	mShader.uniform(&quot;dimensions&quot;, Vec4f(mBoxDimensions));
	mShader.uniform(&quot;shininess&quot;, mLightShininess);
	mShader.uniform(&quot;speed&quot;, mMeshWaveSpeed);
	mShader.uniform(&quot;transform&quot;, mBoxEnabled);
	mShader.uniform(&quot;uvmix&quot;, mMeshUvMix);
	mShader.uniform(&quot;width&quot;, mMeshWaveWidth);

	// Draw VBO
	gl::draw(mVboMesh);

	// Stop drawing
	mShader.unbind();</code></pre><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p>
Some of these lines are worth annotating a bit further. For instance:</p>
<p>mShader.uniform(&#8220;mvp&#8221;, gl::getProjection() * gl::getModelView());</p>
<p>In previous versions of GLSL, you could access the ModelView matrix through a built in variable. In GLSL 1.5 though you simply pass the matrix in using a uniform. This line:</p>
<p>mShader.uniform(&#8220;eyePoint&#8221;, mEyePoint);</p>
<p>allows us to position our generated geometry to the camera. This is really powerful because all you need is a 3D vector and you can correctly calculate the eye perspective onto a scene, I’m sure you can imagine how this will be very useful when we finally get to the Kinect portion of this tutorial. That eye position is vital, because it&#8217;s how we use the place that you want to look when we generate all the geometry. In the geometry shader you can see how these are all put to use:</p><pre class="crayon-plain-tag"><code>uniform vec4 dimensions;
uniform mat4 mvp;
uniform float rotation;
uniform bool transform;

// Input attributes from the vertex shader
in vec4 vertex[];

// Output attributes
out vec4 normal;
out vec4 position;
out vec2 uv;

// Adds a vertex to the current primitive
void addVertex(vec2 texCoord, vec4 vert, vec4 norm)
{

	// Assign values to output attributes
	normal = norm;
	uv = texCoord;
	position = vert;
	gl_Position = vert;

	// Create vertex
	EmitVertex();

}

// Kernel
void main(void)
{</code></pre><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p>
Now we need to calculate what the position should be based on the view so that we can send that on to the fragment shader.</p><pre class="crayon-plain-tag"><code>position = mvp * vertex[0];

	// Transform point to box
	if (transform)
	{

		// Use Y position for phase
		float angle = vertex[0].y * rotation;</code></pre><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p>
The rotation matrix we&#8217;re making here is what allows us to correctly position each box after twisting it to fit the shape of our wave. If these are a bit fuzzy for you, I find <a href="http://knol.google.com/k/matrices-for-3d-applications-translation-rotation#">this</a> to be an excellent refresher or introduction.</p><pre class="crayon-plain-tag"><code>// Define rotation matrix
		mat4 rotMatrix;
		rotMatrix[0].x = 1.0 + cos(angle);
		rotMatrix[0].y = 1.0 + -sin(angle);
		rotMatrix[0].z = 1.0 + -rotMatrix[0].x;
		rotMatrix[0].w = 0.0;
		rotMatrix[1].x = 1.0 + -rotMatrix[0].z;
		rotMatrix[1].y = 1.0 + -rotMatrix[0].y;
		rotMatrix[1].z = 1.0 + -rotMatrix[0].x;
		rotMatrix[1].w = 0.0;
		rotMatrix[2].x = 0.0;
		rotMatrix[2].y = 0.0;
		rotMatrix[2].z = 1.0;
		rotMatrix[2].w = 0.0;
		rotMatrix[3].x = 0.0;
		rotMatrix[3].y = 0.0;
		rotMatrix[3].z = 0.0;
		rotMatrix[3].w = 1.0;</code></pre><p>Now we need vertices for our box. This can broken down as:<br />
<code>vertex = the view matrix * (our position from the vertex shader + (the size of the box * the corner of the box that we're generating) * the amount that it should be twisted)</code></p><pre class="crayon-plain-tag"><code>// Define vertices
		vec4 vert0 = mvp * (vertex[0] + vec4(dimensions * vec4(-1.0, -1.0, -1.0, 0.0)) * rotMatrix); // 0 ---
		vec4 vert1 = mvp * (vertex[0] + vec4(dimensions * vec4( 1.0, -1.0, -1.0, 0.0)) * rotMatrix); // 1 +--
		vec4 vert2 = mvp * (vertex[0] + vec4(dimensions * vec4(-1.0,  1.0, -1.0, 0.0)) * rotMatrix); // 2 -+-
		vec4 vert3 = mvp * (vertex[0] + vec4(dimensions * vec4( 1.0,  1.0, -1.0, 0.0)) * rotMatrix); // 3 ++-
		vec4 vert4 = mvp * (vertex[0] + vec4(dimensions * vec4(-1.0, -1.0,  1.0, 0.0)) * rotMatrix); // 4 --+
		vec4 vert5 = mvp * (vertex[0] + vec4(dimensions * vec4( 1.0, -1.0,  1.0, 0.0)) * rotMatrix); // 5 +-+
		vec4 vert6 = mvp * (vertex[0] + vec4(dimensions * vec4(-1.0,  1.0,  1.0, 0.0)) * rotMatrix); // 6 -++
		vec4 vert7 = mvp * (vertex[0] + vec4(dimensions * vec4( 1.0,  1.0,  1.0, 0.0)) * rotMatrix); // 7 +++

		// Define normals
		vec4 norm0 = mvp * vec4( 1.0,  0.0,  0.0, 0.0); // Right
		vec4 norm1 = mvp * vec4( 0.0,  1.0,  0.0, 0.0); // Top
		vec4 norm2 = mvp * vec4( 0.0,  0.0,  1.0, 0.0); // Front
		vec4 norm3 = mvp * vec4(-1.0,  0.0,  0.0, 0.0); // Left
		vec4 norm4 = mvp * vec4( 0.0, -1.0,  0.0, 0.0); // Bottom
		vec4 norm5 = mvp * vec4( 0.0,  0.0, -1.0, 0.0); // Back

		// Define UV coordinates
		vec2 uv0 = vec2(0.0, 0.0); // --
		vec2 uv1 = vec2(1.0, 0.0); // +-
		vec2 uv2 = vec2(1.0, 1.0); // ++
		vec2 uv3 = vec2(0.0, 1.0); // -+</code></pre><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p>
Now we get in to simply making the sides of a cube:</p><pre class="crayon-plain-tag"><code>// left
		addVertex(uv1, vert5, norm3);
		addVertex(uv2, vert7, norm3);
		addVertex(uv0, vert4, norm3);
		addVertex(uv3, vert6, norm3);
		EndPrimitive();

		// Right
		addVertex(uv3, vert3, norm0);
		addVertex(uv0, vert1, norm0);
		addVertex(uv2, vert2, norm0);
		addVertex(uv1, vert0, norm0);
		EndPrimitive();

		// Top
		addVertex(uv1, vert7, norm1);
		addVertex(uv2, vert3, norm1);
		addVertex(uv0, vert6, norm1);
		addVertex(uv3, vert2, norm1);
		EndPrimitive();

		// Bottom
		addVertex(uv1, vert1, norm4);
		addVertex(uv2, vert5, norm4);
		addVertex(uv0, vert0, norm4);
		addVertex(uv3, vert4, norm4);
		EndPrimitive();

		// Front
		addVertex(uv2, vert3, norm2);
		addVertex(uv3, vert7, norm2);
		addVertex(uv1, vert1, norm2);
		addVertex(uv0, vert5, norm2);
		EndPrimitive();

		// Back
		addVertex(uv2, vert6, norm5);
		addVertex(uv1, vert2, norm5);
		addVertex(uv3, vert4, norm5);
		addVertex(uv0, vert0, norm5);
		EndPrimitive();

	}
	else
	{

		// Pass-thru
		gl_Position = position;
		EmitVertex();
		EndPrimitive();

	}

}</code></pre><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p>
Now the fragment shader and yes, this seems a bit complex, but is actually fairly simple.</p><pre class="crayon-plain-tag"><code>#version 150

// Uniforms
uniform float alpha;
uniform vec3 eyePoint;
uniform vec4 lightAmbient;
uniform vec4 lightDiffuse;
uniform vec4 lightSpecular;
uniform vec3 lightPosition;
uniform float shininess;
uniform bool transform;
uniform float uvmix;</code></pre><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p>
The geometry shader is outputting a normal, position, and uv coordinate for the fragment shader to use in coloring:</p><pre class="crayon-plain-tag"><code>// Input attributes
in vec4 normal;
in vec4 position;
in vec2 uv;</code></pre><p>And here&#8217;s what is actually output:</p><pre class="crayon-plain-tag"><code>// Output attributes
out vec4 color;

// Kernel
void main(void)
{
	// Transform point to box
	if (transform)
	{

		// Initialize color
		color = vec4(0.0, 0.0, 0.0, 0.0);

		// Normalized eye position
		vec3 eye = normalize(-eyePoint);</code></pre><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p>
Lights are really a light position and a reflection vector. That reflection needs to take the position of the light and normal of the surface into account to look &#8220;right&#8221;, so we normalize the reflected light vector using the reflect() method, which is built into GLSL.</p><pre class="crayon-plain-tag"><code>// Calculate light and reflection positions
		vec3 light = normalize(lightPosition.xyz - position.xyz);
		vec3 reflection = normalize(-reflect(light, normal.xyz));</code></pre><p>This is where what people think of as materials are actually generated: putting together the value of a light, a surface color, and a reflection together mathematically. That becomes the color of our pixel and voila, our geometry is generated and colored correctly to match what we&#8217;d expect from the color of the box and the light shining onto it.</p><pre class="crayon-plain-tag"><code>// Calculate ambient, diffuse, and specular values
		vec4 ambient = lightAmbient;
		vec4 diffuse = clamp(lightDiffuse * max(dot(normal.xyz, light), 0.0), 0.0, 1.0);
		vec4 specular = clamp(lightSpecular * pow(max(dot(reflection, eye), 0.0), 0.3 * shininess), 0.0, 1.0); 

		// Set color from light
		color = ambient + diffuse + specular;

		// Mix with UV map
		color = mix(color, vec4(uv.s, uv.t, 1.0, 1.0), uvmix);

		// Set alpha
		color.a = color.a * alpha;

	}
	else
	{

		// Color point white
		color = vec4(1.0, 1.0, 1.0, 1.0);

	}

}</code></pre><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p>
Here&#8217;s another view of what that looks like:</p>
<p><img class="alignright size-large wp-image-21317" title="03_box0" src="http://www.creativeapplications.net/wp-content/uploads/2012/01/03_box0-640x375.jpg" alt="" width="640" height="375" /></p>
<p>So now you&#8217;ve seen how to make geometry and give it color, we&#8217;re going to let you take a breather and in part 2, generate some geometry from a Kinect point cloud data using these techniques. It&#8217;s gonna be awesome :)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.creativeapplications.net/tutorials/shaders-geometry-and-the-kinect-part-1-cinder-tutorials/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Augmented Reality with Processing [Tutorial, Processing]</title>
		<link>http://www.creativeapplications.net/processing/augmented-reality-with-processing-tutorial-processing/</link>
		<comments>http://www.creativeapplications.net/processing/augmented-reality-with-processing-tutorial-processing/#comments</comments>
		<pubDate>Thu, 22 Dec 2011 13:34:58 +0000</pubDate>
		<dc:creator>Amnon Owed</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[Processing]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[AR]]></category>
		<category><![CDATA[au]]></category>
		<category><![CDATA[augmented reality]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[examples]]></category>
		<category><![CDATA[GSVideo]]></category>
		<category><![CDATA[NyArtoolkit]]></category>
		<category><![CDATA[opensource]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.creativeapplications.net/?p=20933</guid>
		<description><![CDATA[All of the visuals in the above video were created using NyArtoolkit for Processing. NyARToolkit is an augmented reality toolkit built with 100% pure Java. It is derived from ARToolkit-2.72.1. Like Processing itself it’s open source and free! In this tutorial you will learn how to use it to place computer generated imagery correctly onto [...]]]></description>
			<content:encoded><![CDATA[<p><iframe src="http://player.vimeo.com/video/34047128?title=0&amp;byline=0&amp;portrait=0" frameborder="0" width="640" height="360"></iframe></p>
<p>All of the visuals in the above video were created using <a href="http://nyatla.jp/nyartoolkit/wiki/index.php?NyAR4psg.en">NyArtoolkit</a> for Processing. <a href="http://nyatla.jp/nyartoolkit/wiki/index.php?NyAR4psg.en">NyARToolkit</a> is an augmented reality toolkit built with 100% pure Java. It is derived from ARToolkit-2.72.1. Like Processing itself it’s open source and free! In this tutorial you will learn how to use it to place computer generated imagery correctly onto real world footage. To do this in real-time NyArtoolkit uses markers &#8211; black and white images &#8211; to determine the three-dimensional position and orientation in the real world. Most likely you will have seen something like this before, but now you will learn how to do it yourself using freely available software.</p>
<p>All right so let’s start with the general setup. What do you need to get started?</p><p><a href="http://www.creativeapplications.net/processing/augmented-reality-with-processing-tutorial-processing/?utm_source=feed&utm_campaign=rss-mo-more&utm_medium=rss">Continue reading.... Augmented Reality with Processing [Tutorial, Processing]</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.creativeapplications.net/processing/augmented-reality-with-processing-tutorial-processing/feed/</wfw:commentRss>
		<slash:comments>64</slash:comments>
		</item>
		<item>
		<title>EYJAFJALLAJÖKULL [vvvv, Events, Environment, Inspiration]</title>
		<link>http://www.creativeapplications.net/environment/eyjafjallajokull-vvvv-events-environment-inspiration/</link>
		<comments>http://www.creativeapplications.net/environment/eyjafjallajokull-vvvv-events-environment-inspiration/#comments</comments>
		<pubDate>Sun, 18 Dec 2011 21:44:11 +0000</pubDate>
		<dc:creator>Filip</dc:creator>
				<category><![CDATA[Environment]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[Inspiration]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[vvvv]]></category>
		<category><![CDATA[antivj]]></category>
		<category><![CDATA[cinema4d]]></category>
		<category><![CDATA[drawing]]></category>
		<category><![CDATA[graffiti]]></category>
		<category><![CDATA[installation]]></category>
		<category><![CDATA[Joanie Lemercier]]></category>
		<category><![CDATA[landscape]]></category>
		<category><![CDATA[mapping]]></category>
		<category><![CDATA[onedotzero]]></category>
		<category><![CDATA[projection]]></category>
		<category><![CDATA[volcano]]></category>

		<guid isPermaLink="false">http://www.creativeapplications.net/?p=20812</guid>
		<description><![CDATA[Last year, onedotzero approached Joanie Lemercier of AntiVJ to be part of one of their event, a festival they organised at empac, upstate New York, with a selection of screenings, installations and live performances. The installation, now on show at the China Millennium Monument Museum of Digital Arts onedotzero event, has received fantastic feedback and high acclaim. Just as [...]]]></description>
			<content:encoded><![CDATA[<p><iframe src="http://player.vimeo.com/video/32811205?title=0&amp;byline=0&amp;portrait=0" frameborder="0" width="640" height="272"></iframe></p>
<p>Last year, onedotzero approached Joanie Lemercier of AntiVJ to be part of one of their event, a festival they organised at empac, upstate New York, with a selection of screenings, installations and live performances. The installation, now on show at the China Millennium Monument Museum of Digital Arts onedotzero event, has received fantastic feedback and high acclaim. Just as the team published video describing the project (above), we asked Joanie few questions about the installation.</p>
<p>Joanie: The original plan was to fly to empac to do a 3 weeks residency, to develop a new project from scratch, which would involve projection mapping onto objects, a sound track by minimal techno producer Sleeparchive, and potentially a live performance on the day of the opening. As the video explains, the original idea and schedule felt apart when the volcano erupted, and the 3 weeks long residency turned into just 5 days on site, to setup the installation and prepare a live performance&#8230;</p>
<p><a href="http://www.creativeapplications.net/wp-content/uploads/2011/12/test-montagne27_0000.jpg"><img class="alignnone size-medium wp-image-20818" title="test montagne27_0000" src="http://www.creativeapplications.net/wp-content/uploads/2011/12/test-montagne27_0000-320x180.jpg" alt="" width="320" height="180" /></a><a href="http://www.creativeapplications.net/wp-content/uploads/2011/12/test-montagne21_0000.jpg"><img class="alignnone size-medium wp-image-20827" title="test montagne21_0000" src="http://www.creativeapplications.net/wp-content/uploads/2011/12/test-montagne21_0000-320x180.jpg" alt="" width="320" height="180" /></a></p><p><a href="http://www.creativeapplications.net/environment/eyjafjallajokull-vvvv-events-environment-inspiration/?utm_source=feed&utm_campaign=rss-mo-more&utm_medium=rss">Continue reading.... EYJAFJALLAJÖKULL [vvvv, Events, Environment, Inspiration]</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.creativeapplications.net/environment/eyjafjallajokull-vvvv-events-environment-inspiration/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generative Art In HTML5 [Processing, JavaScript, Tutorial]</title>
		<link>http://www.creativeapplications.net/processing/generative-art-in-html5-processing-javascript-tutorial/</link>
		<comments>http://www.creativeapplications.net/processing/generative-art-in-html5-processing-javascript-tutorial/#comments</comments>
		<pubDate>Fri, 09 Sep 2011 18:54:22 +0000</pubDate>
		<dc:creator>Matt Pearson</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Processing]]></category>
		<category><![CDATA[Scripts]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[download]]></category>
		<category><![CDATA[draw]]></category>
		<category><![CDATA[generative]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.creativeapplications.net/?p=18509</guid>
		<description><![CDATA[(A Generative Art Lost Chapter) Through the process of writing Generative Art there were various tangents and miscellaneous-mad-shit that, usually in the name of brevity and clarity, ended up on the cutting room floor. What follows is one such tangent reworked into a brief tutorial. In the week that the Processing 2.0 Beta gets its [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-19155" title="generativehtml501" src="http://www.creativeapplications.net/wp-content/uploads/2011/09/generativehtml501.png" alt="" width="640" height="400" /></p>
<p><strong>(A <em>Generative Art</em> Lost Chapter)</strong></p>
<p>Through the process of writing <em><a href="http://zenbullets.com/book.php" target="_blank">Generative Art</a></em> there were various tangents and miscellaneous-mad-shit that, usually in the name of brevity and clarity, ended up on the cutting room floor. What follows is one such tangent reworked into a brief tutorial. In the week that the <a href="http://code.google.com/p/processing/downloads/list" target="_blank">Processing 2.0 Beta</a> gets its release this would seem an appropriate time to share this on CAN, as it mentions one of P5-2&#8242;s coolest features: publishing to HTML5.</p>
<p>The tutorial is in three sections:</p>
<p><strong>1. <em>&#8220;&#8230; A Practical Guide Using HTML5&#8243;</em></strong></p>
<p>To me, the <em>why</em> is always as important as the <em>how</em>. So first allow me to explain why this is relevant, even though it didn&#8217;t make the book.</p>
<p><strong>2. <em>Processing</em> to <em>JavaScript</em> &#8211; The Ridiculously Easy Way</strong></p>
<p>HTML Canvas for <em>Processing</em> Users. The two minute version.</p>
<p><strong>3. Generative Art in <em>JavaScript</em> &#8211; The Harder, But Still Ridiculously Easy, Way</strong></p>
<p>Cutting out the middle man. How you might get started with nothing but a JavaScript enabled browser to hand.</p><p><a href="http://www.creativeapplications.net/processing/generative-art-in-html5-processing-javascript-tutorial/?utm_source=feed&utm_campaign=rss-mo-more&utm_medium=rss">Continue reading.... Generative Art In HTML5 [Processing, JavaScript, Tutorial]</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.creativeapplications.net/processing/generative-art-in-html5-processing-javascript-tutorial/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Visuals for Sonar Festival + VDMX to Unity3D [Tutorials]</title>
		<link>http://www.creativeapplications.net/mac/visuals-for-sonar-festival-vdmx-to-unity3d-tutorials/</link>
		<comments>http://www.creativeapplications.net/mac/visuals-for-sonar-festival-vdmx-to-unity3d-tutorials/#comments</comments>
		<pubDate>Mon, 22 Aug 2011 14:10:57 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[Mac]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[festival]]></category>
		<category><![CDATA[music]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[sonar]]></category>
		<category><![CDATA[Sound]]></category>
		<category><![CDATA[soundflower]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Unity3D]]></category>
		<category><![CDATA[vdmx]]></category>
		<category><![CDATA[visualizer]]></category>

		<guid isPermaLink="false">http://www.creativeapplications.net/?p=17900</guid>
		<description><![CDATA[Numbers, a record label originating from Glasgow, had the opportunity to showcase artists at this year&#8217;s Sonar Festival in Barcelona. The artists Redinho, Spencer, Deadboy, Jackmaster, and Lory D each had a spot in the set. Adam Rodgers, co-founder of Numbers and Remote-Location approached Thomas Traum, Adam Finlay and myself to create live visuals for the show. We compared a [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.creativeapplications.net/mac/visuals-for-sonar-festival-vdmx-to-unity3d-tutorials/attachment/sonar-15-2/" rel="attachment wp-att-17946"><img src="http://www.creativeapplications.net/wp-content/uploads/2011/07/sonar-151-640x360.jpg" alt="" width="640" height="360" /></a></p>
<p>Numbers, a record label originating from Glasgow, had the opportunity to showcase artists at this year&#8217;s Sonar Festival in Barcelona. The artists Redinho, Spencer, Deadboy, Jackmaster, and Lory D each had a spot in the set.</p>
<p>Adam Rodgers, co-founder of Numbers and Remote-Location approached Thomas Traum, Adam Finlay and myself to create live visuals for the show.</p>
<p>We compared a number of technologies and frameworks&#8211; OpenFrameworks, Cinder, Unity3D, Cocos2d, WebGL, Processing, and good ol&#8217; Flash. Doing something in 3D was a priority, and since we only had a 2-3 week timeline, the decision really came down to what would be the fastest to develop.</p><p><a href="http://www.creativeapplications.net/mac/visuals-for-sonar-festival-vdmx-to-unity3d-tutorials/?utm_source=feed&utm_campaign=rss-mo-more&utm_medium=rss">Continue reading.... Visuals for Sonar Festival + VDMX to Unity3D [Tutorials]</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.creativeapplications.net/mac/visuals-for-sonar-festival-vdmx-to-unity3d-tutorials/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>PING! Augmented Pixel [Tutorials, Games]</title>
		<link>http://www.creativeapplications.net/games/ping-augmented-pixel-tutorials-games/</link>
		<comments>http://www.creativeapplications.net/games/ping-augmented-pixel-tutorials-games/#comments</comments>
		<pubDate>Sun, 07 Aug 2011 20:03:01 +0000</pubDate>
		<dc:creator>Niklas Roy</dc:creator>
				<category><![CDATA[Games]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[ATmega8]]></category>
		<category><![CDATA[augmented]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[camera]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[hardware]]></category>
		<category><![CDATA[Niklas Roy]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[tv]]></category>

		<guid isPermaLink="false">http://www.creativeapplications.net/?p=18336</guid>
		<description><![CDATA[Augmented reality video game &#8211; by Niklas Roy (2011) In the decade where videogames were born, everything virtual looked like rectangular blocks. From today’s perspective, the representation of a tennis court in the earliest videogames is hard to distinguish from a soccer or a basketball field. ‘PING! – Augmented Pixel’ is a seventies style videogame, [...]]]></description>
			<content:encoded><![CDATA[<p>Augmented reality video game &#8211; by Niklas Roy (2011)</p>
<p><iframe src="http://www.youtube.com/embed/eeuaqSEIiTY" frameborder="0" width="640" height="390"></iframe></p>
<p>In the decade where videogames were born, everything virtual looked like rectangular blocks. From today’s perspective, the representation of a tennis court in the earliest videogames is hard to distinguish from a soccer or a basketball field.<br />
‘PING! – Augmented Pixel’ is a seventies style videogame, that adds a layer of digital information and oldschool aesthetics to a video signal: A classic rectangular video game ball moves across a video image. Whenever the ball hits something dark, it bounces off. The game itself has no rules and no goal. Like GTA, it provides a free environment in which anything is possible. And like Sony’s Eyetoy, it uses a video camera as game controller.</p>
<p><a href="http://www.creativeapplications.net/wp-content/uploads/2011/08/ping_screen.jpg"><img class="alignnone size-large wp-image-18338" title="ping_screen" src="http://www.creativeapplications.net/wp-content/uploads/2011/08/ping_screen-640x468.jpg" alt="" width="640" height="468" /></a></p>
<p>What I found interesting when I developed this game, is, that it could have been made already in the seventies. The technology that I used for it is (in a way) similar to what Atari used for the first Pong. It becomes even more awkward, if you think that the electronic components for capturing and evaluating a video signal are cheaper than the rotary game controllers that Atari used. But still, from an economic point of view it makes sense that Eyetoys weren’t the ultimate controllers of thirty-something years ago, as a video camera was probably very hard to afford back in the days.</p>
<p><a href="http://www.creativeapplications.net/wp-content/uploads/2011/08/ping_ok_diagonal.jpg"><img class="alignnone size-large wp-image-18337" title="ping_ok_diagonal" src="http://www.creativeapplications.net/wp-content/uploads/2011/08/ping_ok_diagonal-640x481.jpg" alt="" width="640" height="481" /></a></p>
<p><strong>For those who want to know how it works:</strong></p>
<p>The game is programed with AVR-GCC on an ATmega8 microcontroller that runs with 16MHz. The controller gets basic videosignal synchronisation information from an LM1881 sync separator that triggers two hardware interrupts. One for a new image, the other one for a new line. The controller evaluates the brightness around the pixel (/ball) via its comparator input. Drawing the white image overlay is realized with a simple pull-up resistor in the signal line.</p><p><a href="http://www.creativeapplications.net/games/ping-augmented-pixel-tutorials-games/?utm_source=feed&utm_campaign=rss-mo-more&utm_medium=rss">Continue reading.... PING! Augmented Pixel [Tutorials, Games]</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.creativeapplications.net/games/ping-augmented-pixel-tutorials-games/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Working with Toxiclibs [Processing, Tutorial]</title>
		<link>http://www.creativeapplications.net/processing/working-with-toxiclibs-processing-tutorial/</link>
		<comments>http://www.creativeapplications.net/processing/working-with-toxiclibs-processing-tutorial/#comments</comments>
		<pubDate>Thu, 05 May 2011 21:41:21 +0000</pubDate>
		<dc:creator>Amnon Owed</dc:creator>
				<category><![CDATA[Processing]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[color]]></category>
		<category><![CDATA[colour]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[opensource]]></category>
		<category><![CDATA[particles]]></category>
		<category><![CDATA[physics]]></category>
		<category><![CDATA[springs]]></category>
		<category><![CDATA[toxiclibs]]></category>

		<guid isPermaLink="false">http://www.creativeapplications.net/?p=16361</guid>
		<description><![CDATA[Would you like to create what you see in those videos? Well, read on! Because in this article I will show you how you can do just that using Processing and Toxiclibs. As Processing’s biggest open source collection of libraries, Toxiclibs can assist you in areas like geometry, physics, math and color. With so much [...]]]></description>
			<content:encoded><![CDATA[<p><iframe src="http://player.vimeo.com/video/23319820?title=0&amp;byline=0&amp;portrait=0&amp;autoplay=0" width="640" height="360" frameborder="0"></iframe><iframe src="http://player.vimeo.com/video/22772055?title=0&amp;byline=0&amp;portrait=0&amp;autoplay=0" width="640" height="360" frameborder="0"></iframe></p>
<p>Would you like to create what you see in those videos? Well, read on! Because in this article I will show you how you can do just that using Processing and <a href="http://toxiclibs.org/">Toxiclibs</a>. As Processing’s biggest open source collection of libraries, Toxiclibs can assist you in areas like geometry, physics, math and color. With so much code candy for the taking, the libs can still be a bit daunting for many people, especially Processing beginners. That’s why – in addition to great functionality and documentation – clear and inspiring examples on how to use the library are so important. Fortunately the collection of code examples bundled with the libs is growing steadily. I hope my examples can add to that and be helpful to those learning how to use this wonderful collection of code which is shared and continuously developed by <a href="http://postspectacular.com/" target="_blank">Karsten Schmidt</a>.</p>
<p><a href="http://www.creativeapplications.net/wp-content/uploads/2011/05/Toxiclibs-BreakCircle-by-Amnon-Owed.jpg"><img class="alignnone size-large wp-image-16370" src="http://www.creativeapplications.net/wp-content/uploads/2011/05/Toxiclibs-BreakCircle-by-Amnon-Owed-640x360.jpg" alt="" width="640" height="360" /></a></p>
<p>I’ve already shared the two code examples from the first video on my <a href="http://amnonp5.wordpress.com/" target="_blank">blog</a>. As the video shows these concern creating, picking and dragging polygon shapes (<strong>example 1</strong>) and the destruction of voronoi tesselated circles (<strong>example 2</strong>). The full source code and a more detailed explanation of those two examples can be found <a href="http://amnonp5.wordpress.com/2011/04/23/working-with-toxiclibs/" target="_blank"><strong>HERE</strong></a>. In this follow-up I will share the source code for the two brand new examples you see in the second video. This time I’m venturing a little deeper into the physics capabilities of Toxiclibs, more specifically the <a href="http://toxiclibs.org/docs/verletphysics/toxi/physics2d/VerletSpring2D.html" target="_blank">VerletSpring2D</a> class (<strong>example 3</strong>) and we will explore a whole new area of the libs, namely the color library (<strong>example 4</strong>). All of the examples are commented as much as possible. So by running them and looking through the code, you should be able to understand what’s going on. The rest of this blog post can be considered additional background information ranging from general description to specific pointers. Note (06/05/2011): Karsten came up with some useful suggestions to further improve the code, which of course I was happy to apply. This explains why the visuals when running the code may differ ever so slightly from what you see in the movie.</p>
<p><span style="text-decoration: underline"><strong>Example 3: The Infinite Rope</strong></span></p>
<p><a href="http://www.creativeapplications.net/wp-content/uploads/2011/05/Toxiclibs-Spring2D-v2-by-Amnon-Owed.jpg"><img class="alignnone size-large wp-image-16380" src="http://www.creativeapplications.net/wp-content/uploads/2011/05/Toxiclibs-Spring2D-v2-by-Amnon-Owed-640x360.jpg" alt="" width="640" height="360" /></a></p>
<p>What’s better than a rope? Exactly. An INFINITE rope! This example demonstrates both the creation and efficient removal of particles, springs and behaviors. The three pillars of the physics system. Specifically it uses the <a href="http://toxiclibs.org/docs/verletphysics/toxi/physics2d/VerletSpring2D.html" target="_blank">VerletSpring2D</a> class, which can connect two <a href="http://toxiclibs.org/docs/verletphysics/toxi/physics2d/VerletParticle2D.html" target="_blank">VerletParticles</a> in space. For simplicity it’s kept 2D, but everything with regard to physics in Toxiclibs also has a 3D equivalent. Let me describe the way it works and some of the specific choices and solutions. When the mouse is dragged a new particle is created and connected to the last one, effectively making a digital rope. Release the mouse to start a new rope. Push behavior is added to each particle to make it look a little more realistic. For aesthetic reasons, the color of every segment is determined by the direction of each spring.</p>
<p>The most important part of the sketch however, is the code that removes off-screen objects. This is absolutely imperative to keep things running smoothly. Let me elaborate on two specific aspects with regard to the removeOffscreen() function. First, it’s running backwards through the for loop! This is because we are removing things from the list. Meaning the list is getting shorter while you are going through it. Therefore you need to go backwards to prevent problems and to make sure you cover every item in the list. Second, notice that I remove behavior(i+1) for particle(i). The reason is that the first behavior on the list is the gravity we added in setup(). Therefore the behavior of particle 1 can be found in position 2 of the behavior list and so on.</p>
<pre class="crayon-plain-tag"><code>//  Toxiclibs Code Example: The Infinite Rope
//  by Amnon Owed (05/05/2011)
//  minor refactorings by Karsten Schmidt (06/05/2011)

import processing.opengl.*;

import toxi.physics2d.behaviors.*;
import toxi.physics2d.*;
import toxi.geom.*;
import toxi.color.*;

VerletPhysics2D physics;
VerletParticle2D prev;

int continuous,current; // variables to create a new continuous line on each mouse drag
 
void setup() {
  size(1280,720,OPENGL);
  physics = new VerletPhysics2D();
  // add gravity in positive Y direction
  physics.addBehavior(new GravityBehavior(new Vec2D(0,0.1)));
  // set the stroke weight of the line
  strokeWeight(2);
}
 
void draw() {
  background(255);
  // update all the physics stuff (particles, springs, gravity)
  physics.update();
 
  // draw a line segment for each spring and change the color of it based on the x position
  for(VerletSpring2D s : physics.springs) {
    // map the direction of each spring to a hue
    float currHue=map(s.b.sub(s.a).heading(),-PI,PI,0,1);
    // define a color in HSV and convert into ARGB format (32bit packed integer)
    stroke(TColor.newHSV(currHue,1,1).toARGB());
    line(s.a.x,s.a.y,s.b.x,s.b.y);
  }
 
  // remove stuff that is off the screen to keep things running smoothly ;-)
  removeOffscreen();
}
 
void removeOffscreen() {
  // remove off-screen springs
  for (Iterator&lt;VerletSpring2D&gt; i=physics.springs.iterator(); i.hasNext();) {
    VerletSpring2D s=i.next();
    if (s.a.y &gt; height+100 || s.b.y &gt; height+100) {
      i.remove();
    }
  }
 
  // remove off-screen particles &amp; behaviors
  for (int i=physics.particles.size()-1; i&gt;=0; i--) {
    VerletParticle2D p = physics.particles.get(i);
    if (p.y &gt; height+200) {
      physics.removeParticle(p);
      ParticleBehavior2D b = physics.behaviors.get(i+1);
      physics.removeBehavior(b);
    }
  }
}
 
void mouseDragged() {
  // create a locked (unmovable) particle at the mouse position
  VerletParticle2D p = new VerletParticle2D(mouseX,mouseY);
  p.lock();
  // if there is at least one particle and this is the current continuous line
  if (physics.particles.size() &gt; 0 &amp;&amp; continuous == current) {
    // get the previous particle (aka the last in the list)
    VerletParticle2D prev = physics.particles.get(physics.particles.size()-1);
    // create a spring between the previous and the current particle of length 10 and strength 1
    VerletSpring2D s = new VerletSpring2D(p,prev,10,1);
    // add the spring to the physics system
    physics.addSpring(s);
  } else {
    current = continuous;
  }
  // unlock previous particle
  if (prev!=null) {
    prev.unlock();
  }
  // add the particle to the physics system
  physics.addParticle(p);
  // create a forcefield around this particle with radius 20 and force -1.5 (aka push)
  ParticleBehavior2D b = new AttractionBehavior(p,20,-1.5);
  // add the behavior to the physics system (will be applied to all particles)
  physics.addBehavior(b);
  // make current particle the previous one...
  prev=p;
}
 
void mouseReleased() {
  if (prev!=null) {
    prev.unlock();
  }
  continuous++;
}</code></pre>
<p><span style="text-decoration: underline"><strong>Example 4: NamedColors</strong></span></p>
<p><a href="http://www.creativeapplications.net/wp-content/uploads/2011/05/Toxiclibs-NamedColors-by-Amnon-Owed.jpg"><img class="alignnone size-large wp-image-16373" src="http://www.creativeapplications.net/wp-content/uploads/2011/05/Toxiclibs-NamedColors-by-Amnon-Owed-640x360.jpg" alt="" width="640" height="360" /></a></p>
<p>Aesthetically somewhat similar, but technically completely different, this example is meant to demonstrate how to use <a href="http://toxiclibs.org/docs/colorutils/toxi/color/TColor.html" target="_blank">TColors</a> in general and <a href="http://toxiclibs.org/docs/colorutils/toxi/color/NamedColor.html" target="_blank">NamedColors</a> in particular. If Vec2D/Vec3D is the heart of the geometry lib, then you could say TColor is the heart of the color lib. It’s the basis for much greater possibilities such as color ranges, themes and gradients. But to grasp this part of Toxiclibs, I think it’s best to start with a basic example. For this I chose the NamedColors since they are less abstract than working with numbers alone. In the color portion of Toxiclibs there is a list of 143 NamedColors that you can use. They have names like azure, darkturquoise, lavender, orange and last but not least peachpuff. When working with TColors it’s important to remember that you need to convert them into something that can be used in a Processing fill() or stroke() function. In this example you can see that every time the color is actually used, it’s converted into a packed ARGB int using the toARGB() function.</p>
<p>So let me walk through the sketch real quick. In setup() all the names are loaded into an ArrayList of strings for the purpose of sorting them alphabetically. Running the sketch presents you with the full color palette. I’ve applied some <a href="http://toxiclibs.org/docs/core/toxi/math/ZoomLensInterpolation.html" target="_blank">ZoomLensInterpolation</a> to bring out the selected color (mouseX) and made it move up and down with the user (mouseY). There are some checks to make sure both the name and it’s background are kept within the boundaries of the screen. The right mouse button changes the background color, while the left mouse button creates a colorWorm at the mouse position. Press any key to toggle the palette on/off, the mouse functionality will keep working. The colorWorm is basically a list of up to 25 points, a direction and a certain color. It starts at the mouse position and then moves randomly, adding new points along the way. Since the directional change is limited to 30 degrees, it will generally keep going into a certain direction instead of wriggling around the same spot. To make it a little smoother all the points are loaded into a <a href="http://toxiclibs.org/docs/core/toxi/geom/Spline2D.html" target="_blank">Spline2D</a> which is then subdivided. From the vertices that come out, the line is drawn.</p>
<pre class="crayon-plain-tag"><code>//  Toxiclibs Code Example: NamedColors
//  by Amnon Owed (05/05/2011)
//  minor refactorings by Karsten Schmidt (06/05/2011)

import processing.opengl.*;
import toxi.geom.*;
import toxi.color.*;
import toxi.math.*;

ArrayList &lt;String&gt; names = new ArrayList &lt;String&gt; ();
ArrayList &lt;ColorWorm&gt; worms = new ArrayList &lt;ColorWorm&gt; ();

ZoomLensInterpolation zoomLens = new ZoomLensInterpolation();

boolean showColorPalette = true;
int selectedColorID;

// screen center
Vec2D center;

// background color (readonly colors can't be modified)
ReadonlyTColor bg;

void setup() {
  size(1280, 720, OPENGL);
  center = new Vec2D(width/2, height/2);
  // create a list of all the Toxiclibs NamedColors
  names = NamedColor.getNames();
  // sort it alphabetically
  Collections.sort(names);
  textFont(createFont(&quot;SansSerif&quot;, 28));
  // set zoom lens to a dilating characteristic
  // setting the first parameter to a negative value will create a bundling effect
  zoomLens.setLensStrength(0.45, 1);
  // set the background color to deepskyblue
  bg = NamedColor.getForName(&quot;deepskyblue&quot;);
}

void draw() {
  // convert the bg color into ARGB color format (32bit packed integer)
  background(bg.toARGB());

  // run through all the worms (backwards cause we are also removing some from the list)
  for (Iterator&lt;ColorWorm&gt; i=worms.iterator(); i.hasNext();) {
    ColorWorm w = i.next();
    // if the worm's last point is 'off the screen' remove the worm
    // distanceToSquared() is faster than distanceTo() since it avoids
    // the square root calculation and we don't need precise values here...
    if (w.points.get(0).distanceToSquared(center) &gt; 640000) {
      i.remove();
    } 
    else {
      // otherwise update and display the worm
      w.update();
      w.display();
    }
  }

  // set the zoom location based on the normalized mouseX (0.0 .. 1.0 interval)
  float normX=(float)mouseX / width;
  // interpolate focal point to new mouse position (15% step per frame)
  zoomLens.setLensPos(normX, 0.15);
  // determine the selected color based on mouseX
  // by finding which color area contains mouseX
  float focalX=zoomLens.interpolate(0, width, normX);
  for (int i=0, num=names.size()-1; i&lt;=num; i++) {
    float x=zoomLens.interpolate(0, width, (float)i/num);
    float x2=zoomLens.interpolate(0, width, (float)(i+1)/num);
    // select color if focalX is between x and x2
    if (focalX &gt;= x &amp;&amp; focalX &lt; x2) {
      selectedColorID=i;
      break;
    }
  }

  // toggle the color palette
  if (showColorPalette) {
    drawColorPalette();
  }

  if (mousePressed) {
    // Create worms with the LEFT mouse button
    if (mouseButton == LEFT) {
      Vec2D mouse = new Vec2D(mouseX, mouseY);
      ReadonlyTColor c = NamedColor.getForName(names.get(selectedColorID));
      worms.add(new ColorWorm(mouse, c));
      // Change the background color with the RIGHT or MIDDLE mouse button
    } 
    else {
      bg = NamedColor.getForName(names.get(selectedColorID));
    }
  }
}

// Press ANY key to toggle the color palette
void keyPressed() {
  showColorPalette = !showColorPalette;
}

class ColorWorm {
  List &lt;Vec2D&gt; points = new ArrayList &lt;Vec2D&gt; ();
  Vec2D direction;
  TColor c;

  ColorWorm(Vec2D origin, ReadonlyTColor c) {
    // at the origin point (mouseX,mouseY)
    points.add(origin);
    // create a copy of the readonly color for later manipulation
    this.c = c.copy();
    // create a random direction
    direction = Vec2D.randomVector();
  }

  void update() {
    // every second frame (not too fast, not too slow)
    if (frameCount % 2 == 0) {
      // create a new point given the last point's coordinates
      Vec2D p = points.get(points.size()-1).copy();
      // rotate the direction randomly somewhere between -30 and 30 degrees
      direction.rotate(radians(random(-30, 30)));
      // create a movement vector in that direction with a random magnitude between 15 and 30
      Vec2D move = direction.getNormalizedTo(random(15, 30));
      // move the point in that direction and with that distance
      p.addSelf(move);
      // add the new point to the list
      points.add(p);
    }

    // truncate at 25 points (remove the oldest point)
    while (points.size () &gt; 25) {
      points.remove(0);
    }
  }

  void display() {
    // need at least 3 points to construct a spline
    if (points.size()&gt;2) {
      // create Spline2D from the points
      Spline2D s = new Spline2D(points);
      // subdivide it by 8 into a list of vertices
      List &lt;Vec2D&gt; vertices = s.computeVertices(8);
      noFill();
      strokeWeight(2);
      // draw a line through all the vertices
      beginShape();
      for (int i=0,num=vertices.size()-1; i&lt;=num; i++) {
        Vec2D v = vertices.get(i);
        // the position in the list determines the transparency of the segment
        c.setAlpha(map(i, 0, num, 0, 1));
        // convert the color into ARGB color format (32bit packed integer)
        stroke(c.toARGB());
        vertex(v.x, v.y);
      }
      endShape();
    }
  }
}

void drawColorPalette() {
  noStroke();

  // display all the colors over the width of the screen
  for (int i=0,num=names.size()-1; i&lt;=num; i++) {
    // determine the color swatch's position &amp; width based on
    // it's relative position and the zoom location (mouseX)
    float x = zoomLens.interpolate(0, width, (float)i / num);
    float x2 = zoomLens.interpolate(0, width, (float)(i+1) / num);
    // convert the color into ARGB color format (32bit packed integer)
    fill(NamedColor.getForName(names.get(i)).toARGB());
    // move the colors vertically with mouseY
    rect(x, mouseY-15, x2-x, 30);
  }

  // get the name of the selectedColor
  String name = names.get(selectedColorID);
  float ascent = textAscent();
  float textwidth = textWidth(name);
  // keep the text and it's background fill within screen boundaries
  float x = min(mouseX, width-textwidth-8);
  float y = min(mouseY + 52, height-4);
  // draw a white text background
  fill(255);
  rect(x, y-ascent-4, textwidth+8, ascent+8);
  // draw a black text
  fill(0);
  text(name, x+4, y);
}</code></pre><p>
<p>That concludes this round of code sharing. For all things Toxiclibs go to <a href="http://toxiclibs.org/" target="_blank">toxiclibs.org</a>. A description of how to install contributed libraries for Processing can be found <a href="http://wiki.processing.org/w/How_to_Install_a_Contributed_Library" target="_blank">here</a>. If you would like to know if and how Toxiclibs can help you with your project, but are unsure of where to start, I suggest asking for help in the <a href="http://forum.processing.org/#Home" target="_blank">Processing forum</a>. There are quite a few people over there (including Karsten himself sometimes) who can help you out with advice and maybe even code examples. So good luck and get creative! ;-)</p>
<p><a href="http://www.creativeapplications.net/wp-content/uploads/2011/05/toxiclibscolour01.png"><img class="alignnone size-large wp-image-16385" src="http://www.creativeapplications.net/wp-content/uploads/2011/05/toxiclibscolour01-640x355.png" alt="" width="640" height="355" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.creativeapplications.net/processing/working-with-toxiclibs-processing-tutorial/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>From Processing to the Android Market [Tutorial]</title>
		<link>http://www.creativeapplications.net/android/from-processing-to-the-android-market-tutorial/</link>
		<comments>http://www.creativeapplications.net/android/from-processing-to-the-android-market-tutorial/#comments</comments>
		<pubDate>Wed, 27 Apr 2011 10:08:44 +0000</pubDate>
		<dc:creator>Jerome Saint Clair</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Processing]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[app]]></category>
		<category><![CDATA[OS]]></category>
		<category><![CDATA[publish]]></category>
		<category><![CDATA[sell]]></category>
		<category><![CDATA[sketch]]></category>
		<category><![CDATA[store]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.creativeapplications.net/?p=16108</guid>
		<description><![CDATA[photo by Lei Gao Introduction In this tutorial, you&#8217;ll learn how to sign and publish a Processing/Android sketch to the Android Market. Note that the signing process should be automated and accessible from the PDE quite soon. You can follow this specific issue here and get an alert when the bug is fixed. &#62; Pre-requisites [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.creativeapplications.net/wp-content/uploads/2011/04/processingandroid.jpg"><img class="alignnone size-large wp-image-16219" src="http://www.creativeapplications.net/wp-content/uploads/2011/04/processingandroid-640x385.jpg" alt="" width="640" height="385" /></a><br />
photo by <a href="http://www.flickr.com/photos/whaleforset/5160826809/in/photostream/">Lei Gao</a></p>
<h2>Introduction</h2>
<p><img class="alignleft size-full wp-image-16227" src="http://www.creativeapplications.net/wp-content/uploads/2011/04/AndroidDevelopers.gif" alt="" width="53" height="53" />In this tutorial, you&#8217;ll learn how to sign and publish a Processing/Android sketch to the Android Market.<br />
Note that the signing process should be automated and accessible from the PDE quite soon.<br />
You can follow this specific issue <a href="http://code.google.com/p/processing/issues/detail?id=222">here</a> and get an alert when the bug is fixed.</p>
<p>&gt; Pre-requisites (installation steps are <a href="http://www.creativeapplications.net/android/mobile-app-development-processing-android-tutorial/">covered here</a>):<br />
- Processing 1.5 installed<br />
- Android SDK</p>
<p>&gt; Pre-requisites for Windows users<br />
- Java SE (<a title="Download Java SE" href="http://www.oracle.com/technetwork/java/javase/downloads">http://www.oracle.com/technetwork/java/javase/downloads</a>)<br />
- Ant (<a title="Ant download" href="http://ant.apache.org/manual/install.html">http://ant.apache.org/manual/install.html</a>)</p>
<h2>Step One- Create and export your sketch</h2>
<p>If you haven&#8217;t already, I encourage you to first read Jer Thorp&#8217;s <a href="http://www.creativeapplications.net/android/mobile-app-development-processing-android-tutorial/">introduction to Mobile development using Processing</a> for how to setup your environment and run your first sketch.</p>
<p>Another page worth visiting is the <a href="http://wiki.processing.org/w/Android">Processing for Android Wiki</a></p>
<p>That being said, you can use this sketch as a starting point and modify it to fit your needs.</p>
<p>[sourcecode language="java"]<br />
float radius = 50.0;<br />
float X, Y;<br />
float nX, nY;<br />
int delay = 16;</p>
<p>void setup() {<br />
  size(screenWidth, screenHeight);<br />
  orientation(PORTRAIT);<br />
  background(255);<br />
  X = screenWidth / 2;<br />
  Y = screenHeight /3;<br />
  nX = X;<br />
  nY = Y;<br />
}</p>
<p>void draw() {<br />
  radius = radius + sin( frameCount / 4 );<br />
  X+=(nX-X)/delay;<br />
  Y+=(nY-Y)/delay;<br />
  stroke(0, 50);<br />
  noFill();<br />
  ellipse( X, Y, radius, radius );<br />
}</p>
<p>public boolean surfaceTouchEvent(MotionEvent event) {<br />
  int numPointers = event.getPointerCount();<br />
  if (numPointers == 2) {<br />
    background(255);<br />
  }<br />
  else if (numPointers == 1) {<br />
    int pointerId = event.getPointerId(0);<br />
    nX = event.getX(0);<br />
    nY = event.getY(0);<br />
  }<br />
  return super.surfaceTouchEvent(event);<br />
}</p>
<p>[/sourcecode]</p>
<p>Start Processing, switch to the Android mode, copy the sketch above and save it.</p>
<p>To export your sketck to an Android Project, from the PDE menu, choose File &gt; Export Android Project<br />
This will create a new Project folder named &#8220;android&#8221; at the root level of your sketch.</p>
<h2>Step Two &#8211; Create a key to sign your app</h2>
<p>You&#8217;ll need a private key to sign your app that you can interactively create using the following command where<br />
&#8220;myAndroidKey&#8221; is the name you choose for your key and &#8220;myAndroidKeyAlias&#8221; the alias for this key.</p>
<p>[sourcecode language="bash"]<br />
keytool -genkey -v -keystore myKey.keystore -alias myKeyAlias  -keyalg RSA -validity 10000<br />
[/sourcecode]</p>
<p>After answering a couple of questions, you should end up with a .keystore file.<br />
Make sure you remember the key name and alias as well as the password you choose.<br />
The password will be mandatory if you want to later be able to update your app once published.<br />
This key might be used to sign other apps, so you can copy it somewhere and use it when needed without having to generate a new one each time.</p>
<h2>Step Three &#8211; Configure your project for signing</h2>
<p>Important: each time you export your sketch to an Android Project, if the project already exists, il will be renamed into &#8220;android-timestampsomething&#8221; and a new &#8220;android&#8221; project will replace it. This means that every modifications that you will do below will be lost, unless you copy the modified files to the new Android project or somehow automate this process.</p>
<p>First copy the .keystore file you generated at step two to the root level of your android folder.</p>
<p>To automate the signing and alignment of the app when building for release (you&#8217;ll just be asked for the keystore password), you have to modify the build.properties file and add the following lines (replace the values accordingly):</p>
<p>[sourcecode language="text"]<br />
key.store=myKey.keystore<br />
key.alias=myKeyAlias<br />
[/sourcecode]</p>
<p>Save these changes.</p>
<h2>Step Four &#8211; Modify the AndroidManifest.xml</h2>
<p>Open the AndroidManifest.xml file and set the value of the android:debuggable attribute to false:</p>
<p>[sourcecode language="xml"]<br />
&lt;application android:label=&quot;AndroidSketch&quot;<br />
android:icon=&quot;@drawable/icon&quot;<br />
android:debuggable=&quot;false&quot;&gt;<br />
[/sourcecode]</p>
<p>If required, you can change your app&#8217;s version by modifying the manifest element attributes.<br />
The values are set by default to the following:<br />
android:versionName=&#8221;1.1&#8243; android:versionCode=&#8221;1&#8243;<br />
If you ever update your app, you&#8217;ll have to increment the versionName (1.2  or 2.0) and increment the versionCode (2).<br />
Save these changes.</p>
<h2>Step Five- Customize your app icon</h2>
<p>Processing provides a default icon in 3 different sizes for your app<br />
You can of course replace them with some others of your choice.<br />
They are located in the following folders:</p>
<p>[sourcecode language="text"]<br />
android/res/drawable/icon.png (48&#215;48 pixels)<br />
android/res/drawable-hdpi/icon.png (72&#215;72 pixels)<br />
android/res/drawable/icon.png (36&#215;36 pixels)<br />
[/sourcecode]</p>
<h2>Step Six- Build and sign your app for release</h2>
<p>Now, go to the &#8220;android&#8221; project root and run the following command:</p>
<p>[sourcecode language="bash"]<br />
ant release<br />
[/sourcecode]</p>
<p>Then, enter the password when asked for it.<br />
Make sure you get this message in the end.</p>
<p>[sourcecode language="bash"]BUILD SUCCESSFUL[/sourcecode]</p>
<p>You now have a signed and aligned app in the android/bin folder (ie: myApp-release.apk), ready to be published to the Android Market</p>
<h2>Step Seven &#8211; Upload your app to the Android Market</h2>
<p><img class="alignnone size-full wp-image-16228" src="http://www.creativeapplications.net/wp-content/uploads/2011/04/Screen-shot-2011-04-27-at-11.07.26.png" alt="" width="309" height="55" /></p>
<p>The most painful step (for your wallet) of this tutorial: if not already, you&#8217;ll have to <a href="http://market.android.com/publish/signup">sign up for an Android Developer account</a> for $25.</p>
<p>Once completed, you can <a href="http://market.android.com/publish"> directly publish your app</a>. You&#8217;ll need to provide screenshots, a high resolution application icon and some other information to be published along with your application.</p>
<p><a href="http://www.creativeapplications.net/wp-content/uploads/2011/04/Capture-d’écran-2011-04-26-à-22.35.41.png"><img class="alignnone size-full wp-image-16194" src="http://www.creativeapplications.net/wp-content/uploads/2011/04/Capture-d’écran-2011-04-26-à-22.35.41.png" alt="" width="640" height="320" /></a></p>
<p>You&#8217;re done.</p>
<p>I hope to hear from you very soon with some great Android apps that we can review here.</p>
<p><a href="http://www.creativeapplications.net/wp-content/uploads/2011/04/processingandroid2.jpg"><img class="alignnone size-large wp-image-16223" src="http://www.creativeapplications.net/wp-content/uploads/2011/04/processingandroid2-640x423.jpg" alt="" width="640" height="423" /></a><br />
photo by <a href="http://www.flickr.com/photos/dcuartielles/5574750331/in/photostream/">David Cuartielles</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.creativeapplications.net/android/from-processing-to-the-android-market-tutorial/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Guide to Meshes In Cinder [Cinder, Tutorials]</title>
		<link>http://www.creativeapplications.net/tutorials/guide-to-meshes-in-cinder-cinder-tutorials/</link>
		<comments>http://www.creativeapplications.net/tutorials/guide-to-meshes-in-cinder-cinder-tutorials/#comments</comments>
		<pubDate>Mon, 21 Mar 2011 08:57:06 +0000</pubDate>
		<dc:creator>Joshua Noble</dc:creator>
				<category><![CDATA[cinder]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[3d]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[learning]]></category>
		<category><![CDATA[meshes]]></category>
		<category><![CDATA[polygon]]></category>
		<category><![CDATA[texture]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[vbo]]></category>
		<category><![CDATA[vertex]]></category>

		<guid isPermaLink="false">http://www.creativeapplications.net/?p=15565</guid>
		<description><![CDATA[Introduction Written by Joshua Noble, with images by Robert Hodgin This article is going to cover two things in great detail: vertices and meshes and how they are handled in Cinder. There are a few different names for things that may be new to you in this tutorial which I&#8217;ll lay out for you right at the [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p><em>Written by <a href="http://thefactoryfactory.com/">Joshua Noble</a>, with images by <a href="http://roberthodgin.com/">Robert Hodgin</a></em></p>
<p>This article is going to cover two things in great detail: vertices and meshes and how they are handled in Cinder. There are a few different names for things that may be new to you in this tutorial which I&#8217;ll lay out for you right at the beginning: vertices, mesh, TriMesh, VboMesh, and VBOs. If any of those are already familiar to you and you simply want implementation details on how they work, feel free to skip ahead or around, I won&#8217;t be offended. For those of you who want more background, we&#8217;ll proceed in an orderly fashion.<br />
So, let&#8217;s begin at the beginning: the vertex. In Cinder we use the OpenGL coordinate system which is a right-handed system. Initially the world is oriented at the upper left hand corner of your screen, so the x Axis points right, y Axis points downward, z Axis points into the screen (away from the user). A vertex is a point in geometrical shape, or, a vertex is a point in 3D space that has x, y, and z properties that determine where it is in relation to the 0, 0, 0 point (you can think of this as the center) of the world. For instance, a vertex with the values 100, 100, 100, describes a location 100 pixels to the right on the x axis, down on the y axis, and back on the z axis from the origin of the world in which it is located. In your Cinder application, unless you change it, the world is oriented at the upper left hand corner of your screen. All shapes are the result of the connections between vertices. So, a line is made up of the connections between two vertices, a pyramid is a construction made of the connections between five vertices, a cube is made up of the connections between eight vertices.</p>
<p><a href="http://www.creativeapplications.net/wp-content/uploads/2011/03/line_pyramid_cube.gif"><img class="alignnone size-large wp-image-15566" title="line_pyramid_cube" src="http://www.creativeapplications.net/wp-content/uploads/2011/03/line_pyramid_cube-640x196.gif" alt="" width="640" height="196" /></a></p>
<p>What do these vertices look like in code? Something like this:</p>
<p><code><br />
gl::vertex( Vec3f(300, 100, 0) ); // creates an OpenGL vertex from a Vec3f<br />
</code></p>
<p>Those vertices are passed to your graphics card and your graphics card fill in the spaces in between them in a processing usually called &#8220;the rendering pipeline&#8221;. The rendering pipeline goes more or less like this:<br />
1. Say how you&#8217;re going to connect all the points.<br />
2. Make some points.<br />
3. Say that you&#8217;re done making points.<br />
Saying it in code, and more specficially in Cinder code, looks like this:</p>
<p><code><br />
glBegin(GL_QUAD_STRIP); // start drawing<br />
gl::vertex(Vec3f(20, 20, 0)); // repeated a lot of times with different positions<br />
glEnd(); // stop drawing<br />
</code></p>
<p>You may be thinking: &#8220;I&#8217;ll just make eight vertices and voila: a cube.&#8221; Not so quick. There&#8217;s a hitch and that hitch is that the OpenGL renderer has different ways of connecting the vertices that you pass to it and none are as efficient as to only need eight vertices to create a cube. You&#8217;ve probably seen a version of the following image somewhere before:<br />
<a href="http://www.creativeapplications.net/wp-content/uploads/2011/03/primitives_new.gif"><img class="alignnone size-large wp-image-15567" title="primitives_new" src="http://www.creativeapplications.net/wp-content/uploads/2011/03/primitives_new-640x269.gif" alt="" width="640" height="269" /></a></p>
<p>Creating eight vertices and expecting the GL_QUAD_STRIP to connect them is going to lead to something looking like this:<br />
<a href="http://www.creativeapplications.net/wp-content/uploads/2011/03/incorrect_cube.gif"><img class="alignnone size-large wp-image-15568" title="incorrect_cube" src="http://www.creativeapplications.net/wp-content/uploads/2011/03/incorrect_cube-640x271.gif" alt="" width="640" height="271" /></a></p>
<p>Why is that you ask? Well, first off because we used the GL_QUAD_STRIP but it&#8217;s also because there isn&#8217;t an easy way to tell your graphics card that you want to connect all those points into a cube. Generally you have to create your points to fit the drawing mode that you&#8217;ve selected because of what&#8217;s called &#8220;winding&#8221;. A vertex gets connected to another vertex in the order that the mode does it&#8217;s winding and this means that you might need multiple vertices in a given location to create the shape you want. The cube, for example, requires eighteen vertices, not the eight that you would expect. If you note the order of vertices in the GL chart above you&#8217;ll see that all of them use their vertices slightly differently (in particular you should make note of the GL_TRIANGLE_STRIP example). Drawing a shape requires that you keep track of which drawing mode is being used and which order your vertices are declared in. If you&#8217;re thinking: &#8220;it would be nice if there were an abstraction layer for this&#8221; you&#8217;re thinking right. Enter the mesh, which is really just an abstraction of the vertex and drawing mode that we started with but which has the added bonus of managing the draw order for you. That may seem insignificant at first, but it provides some real benefits when working with complex geometry.</p>
<h2>TriMesh</h2>
<p>The TriMesh represents a series of vertices connected with the same connection algorithm as the GL_TRIANGLE_STRIP. It&#8217;s a convienent way to keep track of multiple complex objects, draw and scale them easily, and manage which vertices create which faces of a model. Let&#8217;s get the simplest example out the way first, drawing a square consisting of two triangles. This requires, as you&#8217;d imagine, four vertices that represent the vertices of each triangle.</p>
<p><code><br />
// Position and Color for the four corners<br />
mesh.appendVertex( Vec3f( 10, 10, 0 ) );<br />
mesh.appendColorRGB( Color( 1, 0, 0 ) );<br />
mesh.appendVertex( Vec3f( 10, 300, 0 ) );<br />
mesh.appendColorRGB( Color( 0, 1, 0 ) );<br />
mesh.appendVertex( Vec3f( 300, 300, 0 ) );<br />
mesh.appendColorRGB( Color( 0, 0, 1 ) );<br />
mesh.appendVertex( Vec3f( 300, 10, 0 ) );<br />
mesh.appendColorRGB( Color( 0, 0, 0 ) );</p>
<p>// Indices for each of the four corners<br />
int vIdx0 = mesh.getNumVertices() - 4;<br />
int vIdx1 = mesh.getNumVertices() - 3;<br />
int vIdx2 = mesh.getNumVertices() - 2;<br />
int vIdx3 = mesh.getNumVertices() - 1;</p>
<p>// Two triangles to create our square<br />
mesh.appendTriangle( vIdx0, vIdx1, vIdx2 );<br />
mesh.appendTriangle( vIdx0, vIdx2, vIdx3 );<br />
</code></p>
<p><a href="http://www.creativeapplications.net/wp-content/uploads/2011/03/sample_squares.jpg"><img class="alignnone size-large wp-image-15569" title="sample_squares" src="http://www.creativeapplications.net/wp-content/uploads/2011/03/sample_squares-640x229.jpg" alt="" width="640" height="229" /></a></p>
<p>So far, so good. Now, let&#8217;s extend that a little further and build something in 3D. A simple cube should suffice to demonstrate how the mesh connects all the vertices that it contains. At first glance, the next block of code (140 lines) might seem daunting, but all we are doing is repeating the previous code block 6 times, once per side. Since each side is comprised of 2 triangles, we draw a total of 12 triangles.<br />
<a href="http://www.creativeapplications.net/wp-content/uploads/2011/03/cubes.jpg"><img class="alignnone size-large wp-image-15570" title="cubes" src="http://www.creativeapplications.net/wp-content/uploads/2011/03/cubes-640x310.jpg" alt="" width="640" height="310" /></a></p>
<p><code><br />
// Create the points of our cube<br />
Vec3f v0(-100,-100,-100);<br />
Vec3f v1( 100,-100,-100);<br />
Vec3f v2( 100, 100,-100);<br />
Vec3f v3(-100, 100,-100);<br />
Vec3f v4(-100,-100, 100);<br />
Vec3f v5( 100,-100, 100);<br />
Vec3f v6( 100, 100, 100);<br />
Vec3f v7(-100, 100, 100);</p>
<p>// Create the colors for each vertex<br />
Color c0( 0, 0, 0 );<br />
Color c1( 1, 0, 0 );<br />
Color c2( 1, 1, 0 );<br />
Color c3( 0, 1, 0 );<br />
Color c4( 0, 0, 1 );<br />
Color c5( 1, 0, 1 );<br />
Color c6( 1, 1, 1 );<br />
Color c7( 0, 1, 1 );</p>
<p>Vec3f faces[6][4] = { /* Vertices for the 6 faces of a cube. */<br />
{v0, v1, v2, v3}, {v3, v2, v6, v7}, {v7, v6, v5, v4},<br />
{v4, v5, v1, v0}, {v5, v6, v2, v1}, {v7, v4, v0, v3} };</p>
<p>Color colors[6][4] = { /* colors for each vertex of the cube. */<br />
{c0, c1, c2, c3}, {c3, c2, c6, c7}, {c7, c6, c5, c4},<br />
{c4, c5, c1, c0}, {c5, c6, c2, c1}, {c7, c4, c0, c3} };</p>
<p>for (int i = 0; i &lt; 6; i++)<br />
{</p>
<p>mesh.appendVertex(faces[i][0]);<br />
mesh.appendColorRGB(colors[i][0]);<br />
mesh.appendVertex(faces[i][1]);<br />
mesh.appendColorRGB(colors[i][1]);<br />
mesh.appendVertex(faces[i][2]);<br />
mesh.appendColorRGB(colors[i][2]);<br />
mesh.appendVertex(faces[i][3]);<br />
mesh.appendColorRGB(colors[i][3]);</p>
<p>int numberVertices = mesh.getNumVertices();</p>
<p>mesh.appendTriangle( numberVertices - 4, numberVertices - 3, numberVertices - 2 );<br />
mesh.appendTriangle( numberVertices - 4, numberVertices - 2, numberVertices - 1 );</p>
<p>}<br />
</code></p>
<p><a href="http://www.creativeapplications.net/wp-content/uploads/2011/03/sample_cube.jpg"><img class="size-full wp-image-15571 alignnone" title="sample_cube" src="http://www.creativeapplications.net/wp-content/uploads/2011/03/sample_cube.jpg" alt="" width="340" height="340" /></a></p>
<p>Accessing the vertices in the TriMesh is a little different than you might imagine it at first, because you can&#8217;t directly access the vertices of the mesh and then alter them. Instead, you make a copy of the vertices using getVertices(), which returns a Vector of the vertices contained by the TriMesh as Vec3f objects and then modifying the values in that vector. To update the vertices in the mesh itself you then need to clear the mesh and append all the vertices again. The same goes for any modifications to the RGB color array as well. Look at the following:</p>
<p><code><br />
void TriMeshSampleApp::update()<br />
{<br />
if( mMesh.getNumVertices() == 0 ) return;</p>
<p>// store all the mesh information</p>
<p>std::vector col = mMesh.getColorsRGB();<br />
std::vector vec = mMesh.getVertices();</p>
<p>int i, j;<br />
i = mMesh.getNumVertices();<br />
j = 0;</p>
<p>mMesh.clear();</p>
<p>// something to add a little movement<br />
float inc = sin( getElapsedSeconds() );</p>
<p>while(j &lt; i)<br />
{<br />
// alter the positions array to get a little dynamism<br />
vec.at(j).x -= inc;<br />
vec.at(j+1).x += inc;<br />
vec.at(j+2).x += inc*2.0f;<br />
vec.at(j+3).x -= inc*2.0f;</p>
<p>// now replace it in the mesh<br />
mMesh.appendVertex( vec.at(j));<br />
mMesh.appendColorRGB( col.at(j) );<br />
mMesh.appendVertex( vec.at(j+1));<br />
mMesh.appendColorRGB( col.at(j+1) );<br />
mMesh.appendVertex( vec.at(j+2));<br />
mMesh.appendColorRGB( col.at(j+2) );<br />
mMesh.appendVertex( vec.at(j+3));<br />
mMesh.appendColorRGB( col.at(j+3) );</p>
<p>int vIdx0 = mMesh.getNumVertices() - 4;<br />
int vIdx1 = mMesh.getNumVertices() - 3;<br />
int vIdx2 = mMesh.getNumVertices() - 2;<br />
int vIdx3 = mMesh.getNumVertices() - 1;</p>
<p>mMesh.appendTriangle( vIdx0, vIdx1, vIdx2 );<br />
mMesh.appendTriangle( vIdx0, vIdx2, vIdx3 );</p>
<p>// go to the next triangle pair<br />
j+=4;<br />
}<br />
}<br />
</code></p>
<p style="text-align: left;">The result?<br />
<a href="http://www.creativeapplications.net/wp-content/uploads/2011/03/sample_cube2.jpg"><img class="size-full wp-image-15572 alignnone" title="sample_cube2" src="http://www.creativeapplications.net/wp-content/uploads/2011/03/sample_cube2.jpg" alt="" width="446" height="360" /></a></p>
<p>Want to use a gl::Texture to texture the cube? Not so difficult. First, you need to set the texture co-ordinates of each vertex in the TriMesh. This requires that you use texture coordinates, not space coordinates or pixel co-ordinates. So, you may think your image is 500 pixels high and 500 pixels wide, but texture co-ordinates say that your texture is 1&#215;1 with what you think of as upper-left corner (0, 0), still being (0, 0), but the bottom-right corner being (1,1). All the values between the 0, 0 and 1,1 points are scalar, meaning that 0.5 will be the midpoint of the image. So if you assign the texture co-ordinate 0.5, 0.5 to a vertex, the middle of the image will appear at that point. The picture below will hopefully help clarify this:<br />
<a href="http://www.creativeapplications.net/wp-content/uploads/2011/03/textures.jpg"><img class="size-large wp-image-15573 alignnone" title="textures" src="http://www.creativeapplications.net/wp-content/uploads/2011/03/textures-640x220.jpg" alt="" width="640" height="220" /></a></p>
<p>So, now, how to put our Trimesh and gl::Texture together? When creating the vertices using the appendVertex() and appendColorRGB() methods, use the appendTexCoord() method to create a texture co-ordinate. This indicates the location in the texture that you want to appear at that location in space:</p>
<p><code><br />
mesh.appendVertex(v0);<br />
mesh.appendColorRGB( Color(1, 0, 0) );<br />
mesh.appendTexCoord(Vec2f(0, 0));<br />
mesh.appendVertex(v1);<br />
mesh.appendColorRGB( Color(0, 0, 1) );<br />
mesh.appendTexCoord(Vec2f(1, 0));<br />
mesh.appendVertex(v2);<br />
mesh.appendColorRGB( Color(1, 0, 0) );<br />
mesh.appendTexCoord(Vec2f(1, 1));<br />
mesh.appendVertex(v3);<br />
mesh.appendColorRGB( Color(0, 1, 0) );<br />
mesh.appendTexCoord(Vec2f(0, 1));<br />
</code></p>
<p>Now, to apply a gl::Texture to this TriMesh, call gl::Texture bind(), draw your TriMesh, and then call gl::Texture unbind() and you&#8217;re done.</p>
<p><code><br />
tex.enableAndBind();<br />
gl::draw(mesh);<br />
tex.unbind();<br />
</code></p>
<p>You can even animate the positions of the texture coordinates by copying, modifying, and then re-appending them in the same way that the vertices and RGB coordinates were updated. But there&#8217;s more to the TriMesh than just a nice way to store all the vertices that you create because, let&#8217;s face it, lining up vertices is a drag and there are better and more fun ways to make vertices, for instance, using a 3d modeling program. To that end, you can import and export OBJ files. So, in my favorite 3d modeling program (the opensource and free one) Blender, I&#8217;ll create a classic platonic solid, the isodecahedron, and then export it as an .obj file:<br />
<a href="http://www.creativeapplications.net/wp-content/uploads/2011/03/icosahedron.jpg"><img class="alignnone size-large wp-image-15574" title="icosahedron" src="http://www.creativeapplications.net/wp-content/uploads/2011/03/icosahedron-640x330.jpg" alt="" width="640" height="330" /></a></p>
<p>Now I can import it using an instance of the ObjLoader class like so:</p>
<p><code><br />
ObjLoader loader( loadResource( SOLID ) );<br />
loader.load( *mesh );<br />
</code></p>
<p>and draw it to the screen by passing it to gl::draw():</p>
<p><code><br />
gl::draw(mesh);<br />
</code></p>
<p>Here it is with some random colors applied to it:<br />
<a href="http://www.creativeapplications.net/wp-content/uploads/2011/03/icosahedrons.jpg"><img class="alignnone size-large wp-image-15575" title="icosahedrons" src="http://www.creativeapplications.net/wp-content/uploads/2011/03/icosahedrons-640x218.jpg" alt="" width="640" height="218" /></a></p>
<p>You can even manipulate it and export it using the TriMesh::writeObject() method:</p>
<p><code><br />
mesh.write( writeFileStream(meshFileName, true); );<br />
</code></p>
<p>Now, if you thought that was all there was to working with meshes in Cinder you would be wrong. As I mentioned earlier, the way that geometry is drawn on the graphics card is by sending points and telling the card how to connect those points. This might remind you a little of how the Textures work in OpenGL: load some data up there, draw it by referring to it using its TextureId. So then, naturally you might wonder, what if we just stored the points on the card? Introducing the Vertex Buffer Object, aka VBO:</p>
<h2>VBO</h2>
<p>A VBO is a way of storing all of the data of vertex data on the graphics card. You&#8217;ve perhaps heard of Vertex Arrays and Display Lists and the VBO is similiar to both of these, but with a few advantages that we&#8217;ll go over very quickly. Vertex Arrays just let you store all the vertex data in an array on the client side, that is, on the CPU side and then send it to the graphics card when you&#8217;re ready to draw it. The downside of that is that you&#8217;re still storing the data on the client side and sending it over to the graphics card. So, instead of making all of our vertex data in what&#8217;s called &#8220;immediate mode&#8221;, which means between a glBegin() and glEnd() pair, you can just store vertex data in an arrays and you can draw geometric primitives by dereferencing the array elements with array indices. The Display List is a similar technique, using an array to store the created geometry, with the crucial difference that a Display List lives solely on the graphics card. This means that once you&#8217;ve created the vertex data for geometry, you can send it the graphics card and draw it simply by referencing the id of the stored data. The downside is that display lists can&#8217;t be modified. Once they&#8217;ve been sent to the card, you need to load them from the card, modify them, and then resend them to the card to see your changes applied. Since one of the conveniences of moving things to the graphics card is reducing the amount of traffic between the graphics card and the rest of your system. The VBO operates quite similarly to the Display List, with the advantage of allowing you to modify the geometry data on the graphics card without downloading all of it at once.</p>
<p>Now, since we&#8217;re focusing on Cinder, we&#8217;ll be focusing on the VboMesh class that Cinder uses to wrap the core OpenGL functionality. When you create a VboMesh, much like in the TriMesh, you need to decide whether the mesh is going to contain color information, texture coordinate information, but, there is another element to the VboMesh: whether the data is dynamic. Thius is particularly important because it determines whether you&#8217;re able to manipulate vertices in the mesh after creating it and it matters because using dynamic data means that the VboMesh will generate two copies of the data: one on the graphics card and one in the memory of your application. So, if you don&#8217;t need to update the data after it&#8217;s been loaded then you you don&#8217;t need to do anything special and if you do want to create dynamic data, you&#8217;ll need to create a gl::VboMesh::Layout object and pass it to the VboMesh. So, for instance, if you want static positions and static colors you would create a Layout object with those properties set on it, declare a VboMesh and then assign it to the result of a call to VboMesh(). This is because the VboMesh, like so many other things in Cinder, is a shared pointer, which means that it has to be created before you can use it, you can return it from a method without problems, and also that you don&#8217;t have to worry about deallocating the VboMesh once you&#8217;ve created it.<br />
Here&#8217;s one of the constructors for the VboMesh:</p>
<p><code><br />
VboMesh( size_t numVertices, size_t numIndices, Layout layout, GLenum primitiveType );<br />
</code></p>
<p>so that would be used like this:</p>
<p><code><br />
gl::VboMesh mesh;<br />
gl::VboMesh::Layout layout;<br />
layout.setStaticPositions();<br />
layout.setStaticColorsRGBA();<br />
mesh = gl::VboMesh( 24, 20, layout, GL_QUADS );<br />
</code></p>
<p>Now, the numVertices and numIndices need a little explanantion. You&#8217;ll recall from the TriMesh that the number of indices and the number of vertices aren&#8217;t directly correlated. You&#8217;ll almost always need to create more indices than vertices because there are more indices than discrete locations required for most geometry, but that depends on what kind of geometry you&#8217;re creating. This brings us to one of the more confusing elements of working with VboMesh::Layout, which is the idea of indices and dynamic indices in particular. The indices set the location of an Vec3f in the order of drawing elements. Remember how in the first example before introducing the TriMesh, you saw how the order that the vertices were created in affected how they were connected the other vertices? Well, the index for a vertex in the VboMesh works much the same way, indicating where the vertex is in relation to the other vertices and how it should be connected to them. In the graphic below the ways to draw a square using GL_QUADS is shown at the top and left and using GL_TRIANGLE_STRIP at the bottom and right.<br />
<a href="http://www.creativeapplications.net/wp-content/uploads/2011/03/vbo_order.png"><img class="alignnone size-large wp-image-15577" title="vbo_order" src="http://www.creativeapplications.net/wp-content/uploads/2011/03/vbo_order-640x325.png" alt="" width="640" height="325" /></a></p>
<p>Cinder always requires that you create the indices for a mesh before you create the positions for that mesh, because conceptually a vertice without a index can&#8217;t be properly integrated into the mesh and vice versa. The two modes of storing positions means that the process for working with VboMeshes that dynamic positions versus those that have static positions is slightly different. We&#8217;ll do the static first:</p>
<p><code><br />
gl::VboMesh::Layout layout;<br />
layout.setStaticIndices();<br />
layout.setDynamicColorsRGBA();<br />
layout.setStaticPositions();</p>
<p>int vertCount = 24;<br />
int quadCount = 6;<br />
mesh = gl::VboMesh(vertCount, quadCount * 4, layout, GL_QUADS);<br />
</code></p>
<p>When you&#8217;re using static positions you can simply assign positions using a vector of Vec3f objects and calling VboMesh::bufferPositions(). So, our VboMesh creation code looks like this, note the indices being assigned before the positions:</p>
<p><code><br />
vector indices;<br />
int i=0;<br />
while(i &lt; 24){<br />
indices.push_back(i);<br />
i++;<br />
}</p>
<p>mesh.bufferIndices(indices);</p>
<p>positions.push_back(Vec3f(100, 200, 1));<br />
positions.push_back(Vec3f( 200, 200, 1));<br />
positions.push_back(Vec3f( 200, 100, 1));<br />
positions.push_back(Vec3f(100, 100, 1));</p>
<p>positions.push_back(Vec3f( 200, 200, 1));<br />
positions.push_back(Vec3f( 200, 200, 100));<br />
positions.push_back(Vec3f( 200, 100, 100));<br />
positions.push_back(Vec3f( 200, 100, 1));</p>
<p>positions.push_back(Vec3f( 200, 200, 100));<br />
positions.push_back(Vec3f(100, 200, 100));<br />
positions.push_back(Vec3f(100, 100, 100));<br />
positions.push_back(Vec3f( 200, 100, 100));</p>
<p>positions.push_back(Vec3f(100, 200, 100));<br />
positions.push_back(Vec3f(100, 200, 1));<br />
positions.push_back(Vec3f(100, 100, 1));<br />
positions.push_back(Vec3f(100, 100, 100));</p>
<p>positions.push_back(Vec3f(100, 200, 100));<br />
positions.push_back(Vec3f( 200, 200, 100));<br />
positions.push_back(Vec3f( 200, 200, 1));<br />
positions.push_back(Vec3f(100, 200, 1));</p>
<p>positions.push_back(Vec3f(100, 100, 100));<br />
positions.push_back(Vec3f( 200, 100, 100));<br />
positions.push_back(Vec3f( 200, 100, 1));<br />
positions.push_back(Vec3f(100, 100, 1));</p>
<p>// now we can buffer positions<br />
mesh.bufferPositions(positions);<br />
</code></p>
<p>This creates the same old boring looking white cube. Until we update the colors. This requires retrieving the color values from the mesh and using an iterator to examine the values, which is a familiar pattern in Cinder. The VertexIter object is created to iterate over all the values in the mesh, you assign to the result of VboMesh::mapVertexBuffer() like so:</p>
<p><code><br />
void VboTutorial::update()<br />
{<br />
float g = sin(getElapsedSeconds());<br />
float b = cos(getElapsedSeconds());<br />
gl::VboMesh::VertexIter iter = mesh.mapVertexBuffer();<br />
for( int x = 0; x &lt; 24; ++x ) {<br />
//positions.at(x) *= 1.001;<br />
iter.setColorRGBA( ColorA( 1 - (g+b/3), g, b, 0.5) );<br />
++iter;<br />
}<br />
}<br />
</code></p>
<p>Dynamic positions are handled in the same way as dynamic colors. To create the dynamic positions for the simple cube in the VboMesh, setting up the VboMesh is going to look familiar, assigning the indices via a vector of uints, but the actual updating of the positions is going to look quite different because you can&#8217;t pass a position values into the VboMesh by using VboMesh::bufferPositions(). Instead, you create an VertexIter to iterate over and modify the positions:</p>
<p><code><br />
void VboTutorialApp::setup()<br />
{<br />
gl::VboMesh::Layout layout;<br />
layout.setStaticIndices();<br />
layout.setDynamicColorsRGBA();<br />
layout.setDynamicPositions();</p>
<p>int vertCount = 24;<br />
int quadCount = 6;<br />
mesh = gl::VboMesh(vertCount, quadCount * 4, layout, GL_QUADS);<br />
vector indices;<br />
int i=0;<br />
while(i &lt; 24){<br />
indices.push_back(i);<br />
i++;<br />
}</p>
<p>mesh.bufferIndices(indices);<br />
}<br />
</code></p>
<p>Note that creating the VboMesh only buffers the indices and not any positions. Creating position data is done via a VertexIter, for instance, in the update() of the application:</p>
<p><code><br />
void VboTutorialApp::update()<br />
{<br />
gl::VboMesh::VertexIter iter = mesh.mapVertexBuffer();<br />
for( int idx = 0; idx &lt; numberOfVertices; ++idx ) {<br />
iter.setPosition( Vec3f( xVal, yVal, zVal) );<br />
++iter;<br />
}<br />
}<br />
</code></p>
<p>The positions are automatically generated to be unit vector values, stored both on the graphics card and in the application memory, When you modify the VertexIter you mark a certain range of data as needing to be uploaded to the graphics card. For those interested in the underlying functionality, this uses the stored local copy of the vertex and index information to pass to glBufferDataARB(). The values are only uploaded to the card when index, color, or position data is modified saving time and space on any draw operation when changes haven&#8217;t been made. This is an important nuance because the idea of keeping records both on the graphics card and in the application memory is used throughout the VboMesh, color data, texture positions, and even indices. If you create dynamic texture positions using either setDynamicTexCoords2d() if you&#8217;re using 2d coordinates or setDynamicTexCoords3d() if you&#8217;re using 3d coordinates, you can reposition a texture on a mesh dynamically. There are some key differences between 2d textures and 3d textures that you can read up more on here . To move a texture around the x axis of the mesh, create a VertexIter and then modify the texture using setTexCoord3d2() or setTexCoord2d2() depending on the texture type that you&#8217;re using. For instance, shifting a 2d texture around:</p>
<p><code><br />
// dynmaically generate our new positions based on a simple sine wave for mesh<br />
gl::VboMesh::VertexIter iter2 = mVboMesh2.mapVertexBuffer();<br />
for( int x = 0; x &lt; VERTICES_X; ++x ) {<br />
for( int z = 0; z &lt; VERTICES_Z; ++z ) {<br />
float height = sin( z / (float)VERTICES_Z * zFreq + x / (float)VERTICES_X * xFreq + offset ) / 5.0f;<br />
iter2.setPosition( Vec3f( x / (float)VERTICES_X, height, z / (float)VERTICES_Z ) + Vec3f( 0, 0.5, 0 ) );<br />
iter.setTexCoord2d2( Vec2f( x / (float)VERTICES_X, z / (float)VERTICES_Z ));<br />
++iter2;<br />
}<br />
}<br />
</code></p>
<p>You can also copy the values from one VboMesh to another, retrieving values from a mesh using the VboMesh::getIndexVbo() to get the indices from a mesh and VboMesh::getStaticVbo() to get the vertex data from the mesh. The VboMesh can be constructed like so assuming that there&#8217;s another VboMesh called otherMesh:</p>
<p><code><br />
mesh = gl::VboMesh( numberVertices, numberQuads * 4, otherMesh.getLayout(), GL_QUADS, &amp;otherMesh.getIndexVbo(), NULL, &amp;otherMesh.getDynamicVbo());<br />
</code></p>
<p>You may be noticing the last two parameters, which are pointers to either the static or dynamic VBO data from the source VBO.</p>
<p><code><br />
VboMesh( size_t numVertices, size_t numIndices, Layout layout, GLenum primitiveType, Vbo *indexBuffer, Vbo *staticBuffer, Vbo *dynamicBuffer );<br />
</code></p>
<p>Which you use will depend on how the source has been created, using the dynamic properties from a source VBO requires that the source has dynamic positionsVBO with dynamic properties. Using the static values from a buffer means copying the values over so that they can be manipulated independently. This means that the target mesh will have the same properties as the source mesh until they are altered. Using the dynamic properties of a mesh means that the target mesh is using the same data as the source and changes to the source will be reflected in the target mesh. This makes it easy to reflect changes across meshes, for instance color effects or textures, but makes your meshes dependent on the source mesh.</p>
<p>For the last trick of interoperation between the mesh types in Cinder, a VboMesh can load a mesh from a TriMesh instance, which means that you can easily import and export an .obj file to a VBO with ease, for instance:</p>
<p><code><br />
ObjLoader loader( loadResource( OBJ_FILE_RESOURCE ));<br />
loader.load(&amp;trimesh);<br />
gl::VboMesh mesh = gl::VboMesh(trimesh);<br />
</code></p>
<p>And that gets you from a modeling tool to a VBO quite painlessly.</p>
<p>As a final demonstration of how much is built into the VBO and mesh handling in Cinder you can easily create normals and set the normals for a VBO using the VertexIter object and its setNormal() method. A normal is simply a vector that&#8217;s perpendicular to the face of a triangle or quad in a mesh or other piece of OpenGL geometry and they&#8217;re quite important if you plan to use lighting of any kind when rendering a TriMesh or VBO to the screen. The normal essentially tells OpenGL how any light is to be reflected off of a particular face. This allows you to create shading, depth, and other real world lighting effects. It&#8217;s also a little out of the scope of this guide, so I&#8217;ll point you to a chapter from OpenGL Programming aka &#8220;The Red Book&#8221; Using the VertexIter allows you set the normal position for each vertex in a VBO (or in a TriMesh for that matter) by iterating through the vertices of the VBO and setting each normal with an appropriate value. The algorithm here was taken from the <a href="http://www.opengl.org/wiki/Calculating_a_Surface_Normal">http://www.opengl.org/wiki/Calculating_a_Surface_Normal</a> OpenGL wiki which explains the algorithm in a little bit greater detail, as well as providing an alternative algorithm.</p>
<p><code><br />
Vec3f v0, v1, v2;</p>
<p>// dynmaically generate our new positions based on a simple sine wave<br />
gl::VboMesh::VertexIter iter = mVboMesh.mapVertexBuffer();<br />
for( int x = 0; x &lt; VERTICES_X; ++x ) {<br />
for( int z = 0; z &lt; VERTICES_Z ; ++z ) {</p>
<p>float height = sin( z / (float)VERTICES_Z * zFreq + x / (float)VERTICES_X * xFreq + offset ) / 2.0f;<br />
if( currentVert == 0) {<br />
v0.set( x / (float)VERTICES_X, height, z / (float)VERTICES_Z );<br />
++currentVert;<br />
} else if ( currentVert == 1) {<br />
v1.set( x / (float)VERTICES_X, height, z / (float)VERTICES_Z );<br />
++currentVert;<br />
} else {</p>
<p>//v3.set( x / (float)VERTICES_X, height, z / (float)VERTICES_Z );<br />
v2.set( x / (float)VERTICES_X, height, z / (float)VERTICES_Z );</p>
<p>Vec3f uu = v2 - v0;<br />
Vec3f vv = v1 - v0;<br />
Vec3f n = uu.cross(vv).normalized();</p>
<p>iter.setPosition(v0);<br />
iter.setNormal(n);<br />
++iter;<br />
iter.setPosition(v1);<br />
iter.setNormal(n);<br />
++iter;<br />
iter.setPosition(v2);<br />
iter.setNormal(n);<br />
++iter;<br />
currentVert = 0;</p>
<p>}<br />
}<br />
}<br />
</code></p>
<p>So hopefully you&#8217;re feeling a little more comfortable not only with creating and manipulating meshes in Cinder, but also with underestanding what some of the underlying mechanics of a mesh and OpenGL geometry are as well. This guide has barely scratched the surface, but it should be enough to get you started. For more information you can check the excellent references at <a href="http://songho.ca/opengl/gl_vbo.html">songho</a> or to the reference for the <a href="http://libcinder.org/docs/v0.8.2/classcinder_1_1_tri_mesh.html">TriMesh</a> and <a href="http://libcinder.org/docs/v0.8.2/classcinder_1_1gl_1_1_vbo_mesh.html">VBO mesh</a>. Have fun, and make something beautiful.</p>
<p>&#8211;</p>
<p><em>Joshua Noble is a writer, designer, and programmer based in Portland, Oregon and New York City. He&#8217;s the author of, most recently, </em><a href="http://www.amazon.com/Programming-Interactivity-Designers-Processing-Openframeworks/dp/0596154143"><em>Programming Interactivity</em></a><em> and the forthcoming book Research for Living.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.creativeapplications.net/tutorials/guide-to-meshes-in-cinder-cinder-tutorials/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Images in Cinder [Tutorials, Cinder]</title>
		<link>http://www.creativeapplications.net/tutorials/images-in-cinder-tutorials-cinder/</link>
		<comments>http://www.creativeapplications.net/tutorials/images-in-cinder-tutorials-cinder/#comments</comments>
		<pubDate>Mon, 13 Dec 2010 11:28:01 +0000</pubDate>
		<dc:creator>Joshua Noble</dc:creator>
				<category><![CDATA[cinder]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[mapping]]></category>
		<category><![CDATA[pixel]]></category>
		<category><![CDATA[surface]]></category>
		<category><![CDATA[texture]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.creativeapplications.net/?p=13741</guid>
		<description><![CDATA[Written by Joshua Noble, with images by Robert Hodgin In this little tutorial we&#8217;re going to follow a path that starts with a file on the filesystem, say a PNG file, and ends with the image being drawn to the screen using OpenGL. [sourcecode language="cpp"] // probably in your App&#8217;s setup() method gl::Texture texture = loadImage( &#34;image.jpg&#34; [...]]]></description>
			<content:encoded><![CDATA[<p><em>Written by <a href="http://thefactoryfactory.com/">Joshua Noble</a>, with images by <a href="http://roberthodgin.com/">Robert Hodgin</a></em></p>
<p>In this little tutorial we&#8217;re going to follow a path that starts with a file on the filesystem, say a PNG file, and ends with the image being drawn to the screen using OpenGL.</p>
<p><img class="alignnone size-large wp-image-13743" title="images_pipeline" src="http://www.creativeapplications.net/wp-content/uploads/2010/12/images_pipeline-640x128.png" alt="" width="640" height="128" /></p>
<p>[sourcecode language="cpp"]<br />
// probably in your App&#8217;s setup() method<br />
gl::Texture texture = loadImage( &quot;image.jpg&quot; );</p>
<p>// and in your App&#8217;s draw()<br />
gl::draw( texture );<br />
[/sourcecode]</p>
<p>Even though that code simply loads and draws an image, there&#8217;s actually quite a lot going on behind the scenes. The first line creates a new OpenGL texture from the result of <a title="Loads an image from the file path path. Optional extension parameter allows specification of a file t..." href="http://libcinder.org/docs/dev/namespacecinder.html#a5091cf493eafbd8741669dfac5188856">loadImage()</a>. This function is used for loading the various image formats Cinder knows about, and can be used to read from files, URLs, resources and other sources, as we&#8217;ll see later. And the second line actually draws the <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a> to your window using OpenGL.</p>
<p>These two lines highlight one of the core characteristics of Cinder&#8217;s design: data, its I/O (Input/Output) and manipulation are carefully separated. Objects and functions are designed for distinct logical points in the process of loading, manipulating, and transferring data. For example, <a title="Loads an image from the file path path. Optional extension parameter allows specification of a file t..." href="http://libcinder.org/docs/dev/namespacecinder.html#a5091cf493eafbd8741669dfac5188856">loadImage()</a> is a standalone function, not a member of <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a>. Similarly, a <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a> doesn&#8217;t draw itself &#8211; it&#8217;s designed to represent image data, but not to manipulate or render it. To draw a <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a>, we use a standalone function as well, <a href="http://libcinder.org/docs/dev/namespacecinder_1_1gl.html#afa0740258a60c37956211e3b843e1dce">gl::draw()</a>. As we explore more of Cinder&#8217;s image capabilities, we&#8217;ll look at some of the power and convenience this division of labor brings.</p>
<p>Continuing this theme of the separation of responsibilities, we introduce the <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> class. This class represents a block of bitmap data on the CPU, just as the <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a> represents a block of bitmap data on the GPU. That&#8217;s all each does and that&#8217;s a good thing. When you want to use a bitmap in OpenGL, you need to load it onto the GPU. Luckily Cinder makes this easy by allowing you to pass the bitmap to an OpenGL Texture by constructing a <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a> directly from a <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a>:</p>
<p>[sourcecode language="cpp"]<br />
Surface mySurface; // initialized elsewhere<br />
gl::Texture texture = gl::Texture( mySurface );<br />
[/sourcecode]</p>
<p>The rest of this article is going to run through a few different topics in greater depth: <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a>s, <a href="http://libcinder.org/docs/dev/classcinder_1_1_channel_t.html">Channel</a>s, I/O, and <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">Texture</a>s, so feel free to skip around in a technologically enhanced fashion or to read along in the time honored &#8220;beginning to end&#8221; fashion.</p>
<h2>Surface</h2>
<p>The <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> comes in two varieties: an 8 bit unsigned integer and 32 bit floating point high dynamic range version. This means each of the color components &#8211; red, green, blue and sometimes alpha &#8211; are represented using either an 8 bit <code>uint8_t</code> or a 32 bit <code>float</code>. These two types are Surface8u and Surface32f, respectively. The majority of the time a Surface8u is just what you need. However if you&#8217;re doing some advanced image processing, or you want to make use of high dynamic range images, Surface32f is your best bet. Also it&#8217;s worth noting <em>Surface</em> is just a convenient synonym for Surface8u &#8211; you can use either name for the class in your code.</p>
<p>The most important thing to recognize about the <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> is where it lives: on the CPU. Any manipulations that you&#8217;d like to do using C++ code (as opposed something like an OpenGL shader), such as filtering, replacing sections of bitmaps, or tweaking values of pixels, should all be performed using a <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a>. You declare a <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> like so:</p>
<p>[sourcecode language="cpp"]<br />
Surface8u regularSurface;  // an empty 8 bit surface<br />
Surface32f hdrSurface;     // an empty 32 bit high dynamic range surface<br />
[/sourcecode]</p>
<p>When you declare a <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> without assigning it or constructing it, it&#8217;s empty. The memory hasn&#8217;t been set aside for it yet and trying to use a<a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> before it&#8217;s been allocated is going to lead to your code throwing an exception. This is akin to trying to sit down before a chair is beneath your hindquarters: best to put something there first. To allocate the memory for a <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> you can call the constructor like so:</p>
<p>[sourcecode language="cpp"]<br />
Surface mySurface( 640, 480, true ); // width, height, alpha?<br />
[/sourcecode]</p>
<p>So what&#8217;s that doing? Simply setting aside memory. <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a>s are contiguous in memory, which means that when you look at an image you see a grid of pixels, but the memory is simply a block of bytes filled with numeric values. In our case above, we&#8217;ve asked for a <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> that is 640 pixels wide, 480 pixels tall, has an alpha channel. It&#8217;s worth noting that not all Surfaces have an alpha channel. Let&#8217;s also look at a slightly different way to allocate a Surface:</p>
<p>[sourcecode language="cpp"]<br />
Surface mySurface( 640, 480, true, SurfaceChannelOrder::RGBA ); // width, height, alpha?, channel order<br />
[/sourcecode]</p>
<p>Here we&#8217;ve asked that the color channels of a pixel be ordered in memory as <code>red-green-blue-alpha</code>. This last parameter is optional (notice that we left it out earlier) and it defaults to something reasonable based on whether you have an alpha channel or not. If we had passed something different like <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_channel_order.html#a94a9743b97a4f08b3ba0224e684a4f77a963397acf16774889e13379dc802c320">SurfaceChannelOrder::BGRA</a> our pixels would be represented in <code>blue-green-red-alpha</code> order in memory instead. Why would we ever want that? Well many graphics APIs &#8211; such as Apple&#8217;s <a href="http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/Introduction/Introduction.html">Quartz</a>, Microsoft&#8217;s <a href="http://msdn.microsoft.com/en-us/library/ms533798(VS.85).aspx">GDI+</a>, <a href="http://cairographics.org/">Cairo</a>, or <a href="http://opencv.willowgarage.com/wiki/">OpenCV</a> prefer or even require that pixels be ordered in a manner other than RGBA. This feature is part of what allows Cinder <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a>s to seamlessly interoperate with these and other APIs.</p>
<p>In the image below, the small area outlined by the white box is blown up on the right hand side to show the red, green and blue values, as well as the alpha, which is depicted as a block of white to indicate that the pixel is 100% opaque (a value of 255).</p>
<p><img class="alignnone size-large wp-image-13748" title="images_gridPixelView" src="http://www.creativeapplications.net/wp-content/uploads/2010/12/images_gridPixelView-640x234.png" alt="" width="640" height="234" /></p>
<p>The application deals with the bitmap data sequentially&#8230;</p>
<p><img class="alignnone size-large wp-image-13752" title="images_byteStrip" src="http://www.creativeapplications.net/wp-content/uploads/2010/12/images_byteStrip-640x10.png" alt="" width="640" height="10" /></p>
<p>&#8230; and stores it in memory as an array of numbers (in this case, bytes).</p>
<p><img class="alignnone size-large wp-image-13753" title="images_byteNumberStrip" src="http://www.creativeapplications.net/wp-content/uploads/2010/12/images_byteNumberStrip-640x13.png" alt="" width="640" height="13" /></p>
<p>The idea to take away is that the <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> is, at its heart, a block of raw data that is interpreted as a rectangular array of pixels. When you&#8217;re creating or working with images, you&#8217;re simply moving numbers around and the <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> is really a collection of methods to help you work with that data more easily.</p>
<p>For advanced users, if you&#8217;re familiar with C++ templates then you&#8217;ll recognize what you see when you open up the <a href="http://libcinder.org/docs/dev/_surface_8h.html">Surface.h</a> file &#8211; the core type is a class <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">SurfaceT</a>, templated on <code>uint8_t</code> or <code>float</code>. However understanding the implementation is definitely not necessary to understand how to use it. Also, as a side note, Cinder supports a 3rd less common <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> type named Surface16u, but not all of Cinder&#8217;s image manipulation code supports it &#8211; it&#8217;s there primarily as an intermediate representation (handy for things like the depth information of the Microsoft Kinect).</p>
<h2>Copying Images</h2>
<p>There are a few different ways to create a new image from the data in another image. First up, using the <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html#a29d86f9b1875c30ac38dfb6447245049">clone()</a> method:</p>
<p>[sourcecode language="cpp"]<br />
newSurface = oldSurface.clone();<br />
[/sourcecode]</p>
<p>This function creates a new <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> with the same dimensions and layout, and then copies all of its pixels into the new <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a>. Let&#8217;s compare that to a simple assignment:</p>
<p>[sourcecode language="cpp"]<br />
newSurface = oldSurface;<br />
[/sourcecode]</p>
<p>This gives us a very different result. While <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html#a29d86f9b1875c30ac38dfb6447245049">clone()</a> allocated a new block of memory and then duplicated the pixels of <em>oldSurface</em>, the assigment statement above causes <em>newSurface</em> to point to the exact same pixels in memory that <em>oldSurface</em> does. Without delving too deep into the topic, this feature is what makes it safe and fast for you to do things like return a <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> as the result of a function, or to create an STL<code>vector&lt;Surface&gt;</code>, for example. In the example above, <em>oldSurface</em> and <em>newSurface</em> are able to safely sort out memory managment between themselves automatically. So if <em>oldSurface</em> goes away, it won&#8217;t take the image data that <em>newSurface</em> is now pointing to with it. However if both<em>oldSurface</em> and <em>newSurface</em> go away, the memory they were sharing is freed for you automatically. Last one out turns off the lights. You&#8217;ll find this design technique used throughout Cinder. If you&#8217;re into the Design Pattern literature, you might know this techique as the <em>handle-body idiom</em>. Or if you are familiar with <code>shared_ptr</code> or other reference-counted pointers, you can think of <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a>, <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a> and many other classes in Cinder as transparent <code>shared_ptr</code>&#8216;s.</p>
<p>We can also copy just a section of a <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> using <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html#a73dda39e47f015905cc43471e7e426d3">copyFrom()</a>. This code copies the left half of <em>oldSurface:</em></p>
<p>[sourcecode language="cpp"]<br />
Surface newSurface( oldSurface.getWidth() / 2, oldSurface.getHeight(), false );<br />
newSurface.copyFrom( oldSurface, newSurface.getBounds() );<br />
[/sourcecode]</p>
<p>That second parameter is an <a href="http://libcinder.org/docs/dev/namespacecinder.html#a157f7d1781706c0affefe6063e9bd24e">Area</a>, Cinder&#8217;s class for representing discrete rectangles, and it specifies the region to copy the pixels from.</p>
<p>You can also load <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a>s from files, using <a title="Loads an image from the file path path. Optional extension parameter allows specification of a file t..." href="http://libcinder.org/docs/dev/namespacecinder.html#a5091cf493eafbd8741669dfac5188856">loadImage()</a>, or construct them from a <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a>:</p>
<p>[sourcecode language="cpp"]<br />
Surface myPicture = loadImage( &quot;myPicture.png&quot; );</p>
<p>gl::Texture myTexture; // initialized elsewhere<br />
Surface fromTex( myTexture );<br />
[/sourcecode]</p>
<p>both of which are discussed in greater detail in the I/O section. These methods are appropriate when you&#8217;re copying big blocks of data. But what if you want to manipulate a single pixel, or even more surgically, a single channel value within a pixel?</p>
<h2>Manipulating Surfaces</h2>
<p>Something that you might want to do with a <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> is walk the pixels, that is, iterate over each RGB value to perform an operation on it. For the sake of a simple example we&#8217;ll invert all the pixels in a <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a>:</p>
<p>[sourcecode language="cpp"]<br />
Surface bitmap( loadImage( &quot;image.jpg&quot; ) );<br />
Area area( 0, 0, 500, 500 );</p>
<p>Surface::Iter iter = surface-&gt;getIter( area );<br />
while( iter.line() ) {<br />
    while( iter.pixel() ) {<br />
        iter.r() = 255 &#8211; iter.r();<br />
        iter.g() = 255 &#8211; iter.g();<br />
        iter.b() = 255 &#8211; iter.b();<br />
    }<br />
}<br />
[/sourcecode]</p>
<p>Here we construct an instance of a helpful class, <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t_1_1_iter.html">Surface::Iter</a>, which is used to iterate the pixels of an <a href="http://libcinder.org/docs/dev/namespacecinder.html#a157f7d1781706c0affefe6063e9bd24e">Area</a> of a <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a>. It is designed to be used in a nested while-loop; the outer loop makes use of the <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t_1_1_iter.html">Iter</a>&#8216;s <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t_1_1_iter.html#a3bd56277eb0c8c7c099ee94e6bf24fb2">line()</a> routine, while the inner loop uses the <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t_1_1_iter.html#ab33eb94a8faf12609993486bb4b32f58">pixel()</a> routine. By using these loops, we can access the red, green, blue and alpha values of each pixel in succession. Another thing you might want to do is manipulate those pixels using the values of other pixels in the bitmap. The iterator helps you with a little syntactic sugar to allow you to access the pixels around the pixel that you&#8217;re currently iterating over. The same way that you can access the red, green, blue or alpha value of the pixel that you want to set using <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t_1_1_iter.html#aa78c1edb138d18eb0920c300c85f9b41">r()</a>, <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t_1_1_iter.html#a08226b88c883505472a2bcd63fc68b1b">g()</a>, <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t_1_1_iter.html#aa3c488554ddb7ce58452dc6490e8b4c8">b()</a>, or <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t_1_1_iter.html#aa52cce049be78f2f0153ee0be2a661c2">a()</a>, you can also get the pixel values with a relative x and y offset using overloaded versions of those same methods.</p>
<p>For instance, in the image below, if the Iter is currently pointing at the pixel labeled <strong>A</strong> in the image, then <code>r(0,-1)</code> will access the red value of the pixel labeled <strong>B</strong>, and <code>r(1,1)</code>, will access the red value of the pixel labeled <strong>C</strong> in the image.</p>
<p style="text-align: center;"><img class="size-full wp-image-13747 aligncenter" title="images_iterator" src="http://www.creativeapplications.net/wp-content/uploads/2010/12/images_iterator.png" alt="" width="445" height="319" /></p>
<p>This saves you the trouble of either using multiple iterators (messy) or maintaining multiple pointers (awful). The <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> does provide<a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html#a862e892ced2cea8d422683ab82915012">getPixel()</a> and <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html#abeef32100150e5748551c074b433f6ab">setPixel()</a> methods to return the <a href="http://libcinder.org/docs/dev/classcinder_1_1_color_t.html">Color</a> of a pixel at a single point, but the accessor methods of <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t_1_1_iter.html">Iter</a> are faster and preferable. As an example, if you wanted to create a twirl effect in an image, you could do something like the following:</p>
<p>[sourcecode language="cpp"]<br />
void TwirlSampleApp::twirl( Surface *surface, Area area, float maxAngle )<br />
{<br />
    // make a clone of the surface<br />
    Surface inputSurface = surface-&gt;clone();</p>
<p>    // we&#8217;ll need to iterate the inputSurface as well as the output surface<br />
    Surface::ConstIter inputIter( inputSurface.getIter() );<br />
    Surface::Iter outputIter( surface-&gt;getIter( area ) );</p>
<p>    float maxDistance = area.getSize().length() / 2;<br />
    Vec2f mid = ( area.getUL() + area.getLR() ) / 2;</p>
<p>    while( inputIter.line() &amp;&amp; outputIter.line() ) {<br />
        while( inputIter.pixel() &amp;&amp; outputIter.pixel() ) {<br />
            Vec2f current = inputIter.getPos() &#8211; mid;<br />
            float r = current.length();<br />
            float twirlAngle = r / maxDistance * maxAngle;<br />
            float angle = atan2( current.y, current.x );<br />
            Vec2f outSample( r * cos( angle + twirlAngle ), r * sin( angle + twirlAngle ) );<br />
            Vec2i out = outSample &#8211; current;</p>
<p>            outputIter.r() = inputIter.rClamped( out.x, out.y );<br />
            outputIter.g() = inputIter.gClamped( out.x, out.y );<br />
            outputIter.b() = inputIter.bClamped( out.x, out.y );<br />
        }<br />
    }<br />
}<br />
[/sourcecode]</p>
<p><img class="alignnone size-large wp-image-13742" title="images_twirl" src="http://www.creativeapplications.net/wp-content/uploads/2010/12/images_twirl-640x154.png" alt="" width="640" height="154" /></p>
<p>Without getting into too much detail, the algorithm converts the coordinates of each pixel into polar coordinates, adds a value to the angle based on how far it is from the center, and then converts this back to rectangular coordinates. One thing to note in that code is the use of rClamped() and friends. Unlike the normal versions, the <em>clamped</em> variants of these accessors are safe to use when you might be illegally accessing pixels that don&#8217;t exist in the bitmap. For example, trying to access the pixel to the left of a row&#8217;s left-most pixel would be illegal normally, but rClamped() will return the red value of the left-most pixel, clamping the x &amp; y coordinates to the boundaries of the image.</p>
<p>You may have noticed that channels in a bitmap get special attention, so much so that they have their own class to help you work with them more easily. Let&#8217;s look at the <a href="http://libcinder.org/docs/dev/classcinder_1_1_channel_t.html">Channel</a> class itself.</p>
<h2>Channel</h2>
<p>You can think of a <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> as a collection of images in its own right &#8211; one for the red, the green, the blue and sometimes alpha. To interact with<a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a>s in that way in Cinder, we can use the <a href="http://libcinder.org/docs/dev/classcinder_1_1_channel_t.html">Channel</a> class. You may be familiar with this view from Photoshop:</p>
<p><img class="alignnone size-large wp-image-13751" title="images_channelPanel" src="http://www.creativeapplications.net/wp-content/uploads/2010/12/images_channelPanel-640x241.jpg" alt="" width="640" height="241" /></p>
<p>A <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> is structured to conceptually replicate this. In the normal cases you don&#8217;t need to interact with individual <a href="http://libcinder.org/docs/dev/classcinder_1_1_channel_t.html">Channel</a>s, but in certain instances it can be very powerful. If you want to create a <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> from a <a href="http://libcinder.org/docs/dev/classcinder_1_1_channel_t.html">Channel</a>, you can just construct it:</p>
<p>[sourcecode language="cpp"]<br />
Surface surface( channel );<br />
[/sourcecode]</p>
<p>You&#8217;ll get a grayscale image automatically because the red, green and blue channels will all be set to the same values as the <a href="http://libcinder.org/docs/dev/classcinder_1_1_channel_t.html">Channel</a> instance passed in. If you want to turn a <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> into a <a href="http://libcinder.org/docs/dev/classcinder_1_1_channel_t.html">Channel</a>, making your color image into a single grayscale channel, you just do the inverse:</p>
<p>[sourcecode language="cpp"]<br />
Channel channel( surface );<br />
[/sourcecode]</p>
<p>In this case a high quality grayscale interpretation is automatically made of your RGB data. We say &#8220;high quality&#8221; because the red, green and blue are weighted to mimick the way your eye perceives luminance (derived from the <a href="http://en.wikipedia.org/wiki/Rec._709">Rec. 709 high definition video spec</a>, for those interested in such things). Using a <a href="http://libcinder.org/docs/dev/classcinder_1_1_channel_t.html">Channel</a> instead of a <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> can also be a smart move when you simply need a lightweight grayscale image, to work with the face detection of OpenCV for example. This saves on both memory and processing time.</p>
<p>You can also mix the 8u and 32f variants of the <a href="http://libcinder.org/docs/dev/classcinder_1_1_channel_t.html">Channel</a> and <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> as well without causing problems:</p>
<p>[sourcecode language="cpp"]<br />
Channel8u myChannel( &#8230; );<br />
Surface32f myHdrSurface( myChannel );<br />
[/sourcecode]</p>
<p>A potential use for the <a href="http://libcinder.org/docs/dev/classcinder_1_1_channel_t.html">Channel</a> would be to do some sort of masking on the CPU, for instance, using the red channel of a <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a> to set the alpha of another <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a>:</p>
<p>[sourcecode language="cpp"]<br />
// only uses the red pixels of the mask Surface<br />
void ChannelDemoApp::surfaceMaskImage( const Surface &amp;mask, Surface *target )<br />
{<br />
    Surface::ConstIter maskIter( mask.getIter() ); // using const because we&#8217;re not modifying it<br />
    Surface::Iter targetIter( target-&gt;getIter() ); // not using const because we are modifying it<br />
    while( maskIter.line() &amp;&amp; targetIter.line() ) { // line by line<br />
        while( maskIter.pixel() &amp;&amp; targetIter.pixel() ) { // pixel by pixel<br />
            float maskValue = maskIter.r() / 255.0f;</p>
<p>            targetIter.r() *= maskValue;<br />
            targetIter.g() *= maskValue;<br />
            targetIter.b() *= maskValue;<br />
        }<br />
    }<br />
}<br />
[/sourcecode]</p>
<p>That could be accelerated and made more general by passing a <a href="http://libcinder.org/docs/dev/classcinder_1_1_channel_t.html">Channel</a> instead of a <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a>:</p>
<p>[sourcecode language="cpp"]<br />
void ChannelDemoApp::channelMaskImage( const Channel &amp;mask, Surface *target )<br />
{<br />
    Channel::ConstIter maskIter = mask.getIter(); // using const because we&#8217;re not modifying it<br />
    Surface::Iter targetIter( target-&gt;getIter() ); // not using const because we are modifying it<br />
    while( maskIter.line() &amp;&amp; targetIter.line() ) { // line by line<br />
        while( maskIter.pixel() &amp;&amp; targetIter.pixel() ) { // pixel by pixel<br />
            float maskValue = maskIter.v() / 255.0f;</p>
<p>            targetIter.r() *= maskValue;<br />
            targetIter.g() *= maskValue;<br />
            targetIter.b() *= maskValue;<br />
        }<br />
    }<br />
}<br />
[/sourcecode]</p>
<p><img class="alignnone size-large wp-image-13746" title="images_mask" src="http://www.creativeapplications.net/wp-content/uploads/2010/12/images_mask-640x159.jpg" alt="" width="640" height="159" /></p>
<p>As a side note, this could be optimized substantially, so don&#8217;t take the above code to be an example of fast image manipulation.</p>
<p>The value of a Channel at any position can be retrieved using the <a href="http://libcinder.org/docs/dev/classcinder_1_1_channel_t_1_1_iter.html#a6646d54aac0be7cea89770ff555b67d9">v()</a> (<em>v</em> for <em>value</em>) function of <a href="http://libcinder.org/docs/dev/classcinder_1_1_channel_t_1_1_iter.html">Channel::Iter</a>. Many of the image processing functions in Cinder can also be used with single channels, allowing you to, for instance, perform an edge detection function using only the blue channel of a <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a>:</p>
<p>[sourcecode language="cpp"]<br />
gl::Texture createEdgeTexture( const Channel &amp;src )<br />
{<br />
    Channel temp( src.getWidth(), src.getHeight() );<br />
    cinder::ip::edgeDetectSobel( src, &amp;temp );<br />
    return gl::Texture( temp );<br />
}<br />
[/sourcecode]</p>
<p>This would be called like so:</p>
<p>[sourcecode language="cpp"]<br />
myTexture = createEdgeTexture( simpleSurface.getChannelBlue() );<br />
[/sourcecode]</p>
<p><img class="alignnone size-large wp-image-13749" title="images_edgeDetect" src="http://www.creativeapplications.net/wp-content/uploads/2010/12/images_edgeDetect-640x237.png" alt="" width="640" height="237" /></p>
<p>In summary, the <a href="http://libcinder.org/docs/dev/classcinder_1_1_channel_t.html">Channel</a> is a lightweight tool for working with a particular color channel from a <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a>, or as a standalone grayscale image. Copying, image processing operations, or other time critical operations that don&#8217;t require all the data from a bitmap are best done with the <a href="http://libcinder.org/docs/dev/classcinder_1_1_channel_t.html">Channel</a>.</p>
<h2>I/O Operations</h2>
<p>Very often you&#8217;ll want to read or write an image file, which is a topic we&#8217;ll explore in this section. In the beginning of this article you saw loading images using the <a title="Loads an image from the file path path. Optional extension parameter allows specification of a file t..." href="http://libcinder.org/docs/dev/namespacecinder.html#a5091cf493eafbd8741669dfac5188856">loadImage()</a> method. This function can be used to load from file paths:</p>
<p>[sourcecode language="cpp"]<br />
loadImage( &quot;data/image.png&quot; );<br />
[/sourcecode]</p>
<p>or, with a slight variation, from a URL:</p>
<p>[sourcecode language="cpp"]<br />
loadImage( loadUrl( &quot;http://site.com/image.png&quot; ) );<br />
[/sourcecode]</p>
<p>We can also use this method to load images stored in resources (described in a <a href="http://libcinder.org/docs/dev/_cinder_resources.html">separate guide</a>):</p>
<p>[sourcecode language="cpp"]<br />
loadImage( loadResource( RES_LOGO_IMAGE ) );<br />
[/sourcecode]</p>
<p>If you look up <a title="Loads an image from the file path path. Optional extension parameter allows specification of a file t..." href="http://libcinder.org/docs/dev/namespacecinder.html#a5091cf493eafbd8741669dfac5188856">loadImage()</a> in the Cinder documentation, you&#8217;ll see it returns an <a href="http://libcinder.org/docs/dev/namespacecinder.html#aca11590d504e68de86f3a57444c2eb70">ImageSourceRef</a>. The way this class (and its cousin, <a href="http://libcinder.org/docs/dev/namespacecinder.html#aa5caf83179f34be27691363934b85afb">ImageTargetRef</a>) work under the hood will be the topic of a future tutorial, but we can benefit from them without understanding their inner workings. In short, an <a href="http://libcinder.org/docs/dev/classcinder_1_1_image_source.html">ImageSource</a> is able to represent any sort of image, even the ones we can&#8217;t manipulate directly using <a href="http://libcinder.org/docs/dev/classcinder_1_1_channel_t.html">Channel</a>s or<a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a>s. You can pass an ImageSourceRef to the constructor of <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a>s, <a href="http://libcinder.org/docs/dev/classcinder_1_1_channel_t.html">Channel</a>s, <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a>s and several other classes like our OpenCV wrapper classes. The power of this design &#8211; a separate class to represent a generic source of an image &#8211; is that a source and its destination can negotiate between themselves to create the best representation. For example, let&#8217;s imagine you have a grayscale 8-bit image stored in a PNG file you&#8217;d like to turn into a <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a>. By using code like the following, you get the most optimal representation:</p>
<p>[sourcecode language="cpp"]<br />
gl::Texture myTexture = loadImage( &quot;grayscale.png&quot; );<br />
[/sourcecode]</p>
<p>OpenGL can store textures in a special grayscale-only mode which saves valuable GPU memory. The <a href="http://libcinder.org/docs/dev/classcinder_1_1_image_source.html">ImageSource</a> which comes back from<a title="Loads an image from the file path path. Optional extension parameter allows specification of a file t..." href="http://libcinder.org/docs/dev/namespacecinder.html#a5091cf493eafbd8741669dfac5188856">loadImage()</a> can tell the constructor of <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a> the things it needs to know to allocate such a representation, and it does so automatically.</p>
<p>And what about the other way around &#8211; writing an image out as a file? As you might have guessed, it&#8217;s done with a function called <a title="Writes imageSource to dataTarget. Optional extension parameter allows specification of a file type..." href="http://libcinder.org/docs/dev/namespacecinder.html#aa665b20560506c98707c15d3fb594c06">writeImage()</a>:</p>
<p>[sourcecode language="cpp"]<br />
writeImage( &quot;/path/to/image.png&quot;, surfaceToBeWritten );<br />
[/sourcecode]</p>
<p>Cinder automatically infers the sort of image you want from the file extension. You can also force the image to be written with a certain format by supplying the extension as a string for the 3rd parameter:</p>
<p>[sourcecode language="cpp"]<br />
writeImage( &quot;/path/to/image_without_extension&quot;, surfaceToBeWritten, &quot;jpg&quot; );<br />
[/sourcecode]</p>
<p>It&#8217;s not just Surfaces that can be saved. For example, you can pass a <a href="http://libcinder.org/docs/dev/classcinder_1_1_channel_t.html">Channel</a> to <a title="Writes imageSource to dataTarget. Optional extension parameter allows specification of a file type..." href="http://libcinder.org/docs/dev/namespacecinder.html#aa665b20560506c98707c15d3fb594c06">writeImage()</a> and the I/O machinery will automatically understand it&#8217;s dealing with grayscale data and will use an optimized variant of say, PNG for you. Or if you pass a Channel32f, <a title="Writes imageSource to dataTarget. Optional extension parameter allows specification of a file type..." href="http://libcinder.org/docs/dev/namespacecinder.html#aa665b20560506c98707c15d3fb594c06">writeImage()</a> will use the 16-bit grayscale mode of PNG to try to preserve as much of your precision as possible. As a fun fact, you can also pass a <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a> to<a title="Writes imageSource to dataTarget. Optional extension parameter allows specification of a file type..." href="http://libcinder.org/docs/dev/namespacecinder.html#aa665b20560506c98707c15d3fb594c06">writeImage()</a>, or you can convert between file formats with code like this:</p>
<p>[sourcecode language="cpp"]<br />
writeImage( &quot;output.png&quot;, loadImage( &quot;input.jpg&quot; ) );<br />
[/sourcecode]</p>
<h2>GL::Texture</h2>
<p>As we&#8217;ve seen, the <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a> represents an image on your graphics card. The class features all the things that you would expect of an OpenGL texture: an ID (sometimes called a <em>name</em> in the OpenGL docs), functions to <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html#acdd83cbd54ac8e923335f5d8a33baba8">bind()</a> and <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html#a452e5ed804782029213f4025e40699fd">unbind()</a>, an <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html#ac7514ae59e1e95a15ee91517dc78054f">update()</a> method to load new data into the Texture, methods to initialize the texture, etc.</p>
<p>There are a few conceptual things to keep in mind when working with a Texture. Fundamentally it&#8217;s just a bitmap object, but your program has handed it off to another piece of hardware, the GPU, which has its own memory and processors. Copying from CPU to GPU (by for example, constructing a <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a> from a <a href="http://libcinder.org/docs/dev/classcinder_1_1_surface_t.html">Surface</a>) is much slower than say, copying from one Surface to another, so you should do this judiciously. However once the image data is on the GPU it&#8217;s ready for any sort of use with OpenGL.</p>
<p>The actual data of a <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a> is stored on the GPU very similarly to the way a Surface stores its bitmap data in memory. You&#8217;ll recall that the Surface provides an iterator that can be used to walk the bitmap data and access the pixel data or channel data at any point. Doing the same in the <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a> is a different matter. As you are likely familiar, modern GPUs implement a fairly rigid multi-stage process known as the &#8220;graphics pipeline&#8221; (discussed in Wikipedia <a href="http://en.wikipedia.org/wiki/Graphics_pipeline">here</a>). If you want to access the pixels of a texture there are a few different techniques that you can use, all of which are a little beyond the scope of this article. The most common and recommendation-worthy would be in a Fragment Shader, which are implemented in Cinder using the <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_glsl_prog.html">gl::GlslProg</a> class.</p>
<p>You&#8217;ve seen how <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a>s are drawn:</p>
<p>[sourcecode language="cpp"]<br />
gl::draw( mProcessedImageTex, getWindowBounds() );<br />
[/sourcecode]</p>
<p>The first parameter is of course the <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">Texture</a> that you want to draw, and the optional second is a <a href="http://libcinder.org/docs/dev/namespacecinder.html#ac60c086a9aa8f5320c96da74cbf20f8b">Rectf</a> that indicates how large and where the texture should be drawn. It&#8217;s important that a <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a> be filled with bitmap data before you try to draw it &#8211; a <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a> can also point to nothing, just as a Surface can. You can populate a <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a> a few different ways, such as by constructing the <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a> from a Surface:</p>
<p>[sourcecode language="cpp"]<br />
texture = gl::Texture( surfaceInstance );<br />
[/sourcecode]</p>
<p>or by initiailizing the Texture with some dummy data:</p>
<p>[sourcecode language="cpp"]<br />
gl::Texture texture(500, 500);<br />
[/sourcecode]</p>
<p>Of course if you just draw this, your program won&#8217;t crash, but you&#8217;ll just see junk data &#8211; whatever random memory happens to be on the graphics card at the moment. Cool if you&#8217;re making glitch art, not if you&#8217;re not.</p>
<p><img class="alignnone size-large wp-image-13754" title="images_buffer" src="http://www.creativeapplications.net/wp-content/uploads/2010/12/images_buffer-640x223.jpg" alt="" width="640" height="223" /></p>
<p>You can also initialize the Texture with a <a href="http://libcinder.org/docs/dev/structcinder_1_1gl_1_1_texture_1_1_format.html">gl::Texture::Format</a> object that contains specs for how to build the Texture. For instance, by default a<a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a> will simply clamp the Texture to its boundaries. If you wanted the texture to repeat, you could pass in a <a href="http://libcinder.org/docs/dev/structcinder_1_1gl_1_1_texture_1_1_format.html">Texture::Format</a> object like so:</p>
<p>[sourcecode language="cpp"]<br />
gl::Texture::Format fmt;<br />
fmt.setWrap( GL_REPEAT );<br />
texture = gl::Texture( someSurface, fmt );<br />
[/sourcecode]</p>
<p>The differences between clamping and repeating can be seen in the image below:<br />
<img class="alignnone size-large wp-image-13750" title="images_clampRepeat" src="http://www.creativeapplications.net/wp-content/uploads/2010/12/images_clampRepeat-640x183.png" alt="" width="640" height="183" /></p>
<p>There are other features that you can set with the Format object too &#8211; mipmapping for instance. What&#8217;s that you may ask? Take a look at the following images:<br />
<img class="alignnone size-large wp-image-13744" title="images_mipmapCompare" src="http://www.creativeapplications.net/wp-content/uploads/2010/12/images_mipmapCompare-640x183.png" alt="" width="640" height="183" /></p>
<p>Notice the edges on the left. As the English say: that&#8217;s not cricket. We want smoothed edges as the <a href="http://libcinder.org/docs/dev/classcinder_1_1gl_1_1_texture.html">gl::Texture</a> itself is scaled down. This is where mipmapping comes in: the GPU can generate multiple copies of Texture data when you create it and that data can be swapped in and out when needed for minification or magnification in your application.</p>
<p>A mipmap is a miniaturized version of the larger bitmap that helps you reduce artifacts when scaling. The smaller the texture is drawn, the smaller the mipmap that the GPU will select. As an example: a texture has a basic size of 256 by 256 pixels, so a mipmap set will be generated with a series of 8 images, each one-fourth the total area of the previous one: 128&#215;128 pixels, 64&#215;64, 32&#215;32, 16&#215;16, 8&#215;8, 4&#215;4, 2&#215;2, 1&#215;1 (a single pixel).</p>
<p style="text-align: center;"><img class="size-full wp-image-13745 aligncenter" title="images_mipmap" src="http://www.creativeapplications.net/wp-content/uploads/2010/12/images_mipmap.png" alt="" width="511" height="256" /></p>
<p>Artifacts are reduced since the mipmap images are effectively already anti-aliased, taking some of the burden off the real-time renderer and potentially improving performance.</p>
<p>[sourcecode language="cpp"]<br />
gl::Texture::Format fmt;<br />
fmt.enableMipmapping( true );<br />
fmt.setMinFilter( GL_LINEAR_MIPMAP_LINEAR );<br />
[/sourcecode]</p>
<p>You&#8217;ll notice we added a call to setMinFilter() to tell it use our mipmap. In general Cinder is designed for you to use the OpenGL constants directly (like <code>GL_LINEAR_MIPMAP_LINEAR</code>) so if these are unfamiliar to you, we&#8217;d recommend you pick up a book like <a href="http://www.opengl.org/documentation/red_book/">The OpenGL Programming Guide</a>.</p>
<p>And that&#8217;s that. As promised: image data from the filesystem, to the CPU, to the graphics card, and finally to your screen. Now go make something and have fun. And thanks to Flickr user Trey Ratcliff, whose <a href="http://www.flickr.com/photos/stuckincustoms/3892139852/">beautiful photograph</a> is used throughout this tutorial.</p>
<p>&#8211;</p>
<p><em>Joshua Noble is a writer, designer, and programmer based in Portland, Oregon and New York City. He&#8217;s the author of, most recently, </em><a href="http://www.amazon.com/Programming-Interactivity-Designers-Processing-Openframeworks/dp/0596154143"><em>Programming Interactivity</em></a><em> and the forthcoming book Research for Living.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.creativeapplications.net/tutorials/images-in-cinder-tutorials-cinder/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>

