2010-11-20

Starting out with 3D #2 (F - L)

This section builds on #1, which can be found here.

Face
Simply put, the shape of which a 3D object has been extruded. The front or back of an extruded object. Any of the polygons which makes up it’s boundaries.

Fall off
The way in which the intensity of a light diminishes with the distance from its source. In the real world, this is calculated by the inverse square law, which states that the intensity is inversely proportional to the square of the distance. In other words, the further the light, the darker the object. Real world examples would be the sun, a light, etc.

Forward Kinetics (FK)
A character animation technique for controlling the motion of bones in a chain. For example, the limbs. The opposite of this is inverse kinetics. (See further down)

Global Illumination
A type of rendering that computes all the possible light interactions between surfaces in a given scene.
Grime(Dirt) map
2D images applied to a particular channel of material. When the image is projected across the surface of an object, it breaks up the channels flat, even value, creating realistic variations.

Hard Body Dynamics
Also known as rigged body dynamics. It simulates the physical behaviour of rigged object that do not deform on collision.

Hardware Rendering
Renders a preview of a 3D scene providing real-time feedback. To make this possible it removes certain processor-intensive effects such as volumetrics, shadowing and realistic refraction.

Hierarchy
The relationship of the sub objects within a model or scene to one another. Sub-objects may exist as
parents, children or independents. A parent object controls the motion of all child objects linked to it. The motion of a child object does not affect its parent.

Interpolation
When a 3D package calculates the in between position between two keyframes.

Inverse Kinematics (IK)
Inverse Kinematics is a character animation technique in which the end bone of a chain is
assigned a goal object. When the goal object moves, the bone moves with it, dragging the rest of the chain behind it. For example, when moving a hand up, the whole arm moves up with it. The reverse is Forward Kinematics.

Joints
Points between the bones in a character rig.

Keyframe
An image used as a reference point for animation. An image is set up at a certain time in an animation and a later time and have the computer calculate all the frames between the two reference images. (See Interpolation)

Lathing
A modeling technique in which a two-dimensional profile is duplicated in rotation around a reference axis. The duplicates then join up to create a continuous three-dimensional
surface. Lathing is particularly useful for creating objects with rotational axes of symmetry, such as plates, glasses, vases or wheels.



Lofting
A technique in which a continuous three-dimensional surface is created by selecting and joining multiple two-dimensional cross sections or profiles. You basically have a “path” and an “object” the object will follow the path.


Low Poly Modeling
When creating a simplified model with a low polygon amount for realtime use, such as games. A few years ago anything with a polygon count of 512 and under was considered low poly. Today, anything well over a few thousand can still be rendered in realtime.

In part 3 I am going through the words between M and P.

Project "HoT MetaL JaZz" - Part 3

In our last episode, we demonstrated how to draw images to our canvas. Now we will dig deeper into the HTML5 Canvas drawing methods by looking at the path-drawing methods, and learn how to scale images.

Drawing straight lines is easy. We start with [context].beginPath(), plot our paths, apply a stroke and/or fill, then call [context].closePath() to finish up. For example, to draw a simple triangle, you could use code like the following. Open gamecore.js, and replace your current draw() method with the following:

GameCore.prototype.draw = function() {
  this.bufferContext.fillStyle = "rgb(0, 0, 0)";
  this.bufferContext.fillRect(0,
                              0,
                              this.bufferCanvasWidth,
                              this.bufferCanvasHeight);

  this.bufferContext.beginPath();
  this.bufferContext.moveTo(100, 100);
  this.bufferContext.lineTo(200, 100);
  this.bufferContext.lineTo(100, 200);
  this.bufferContext.lineTo(100, 100);

  this.bufferContext.fillStyle = "rgb(127, 127, 127)";
  this.bufferContext.fill();
  this.bufferContext.strokeStyle = "rgb(255, 255, 255)";
  this.bufferContext.stroke();
  this.bufferContext.closePath();

  this.primaryContext.clearRect(0,
                                0,
                                this.primaryCanvasWidth,
                                this.primaryCanvasHeight);

  this.primaryContext.drawImage(this.bufferCanvas,
                                0,
                                0,
                                this.primaryCanvasWidth,
                                this.primaryCanvasHeight);

  setTimeout("game.draw()", this.frameSpeed);
}

The first difference is in the first line - we set the fillStyle to black explicitly, to ensure that we always get a black fill since we'll be changing the context's fillStyle in this example.

Then comes the call, [context].beginPath(). This simple call is used to indicate that we are starting to plot a path. After that, we use [context].moveTo() to move our "cursor" to the indicated X/Y coordinate, without plotting any paths. Three lines calling [context].lineTo() plot the path for a triangular shape. We set our fillStyle to gray, call [context].fill(), and this fills our triangle shape with the color gray. We then set our strokeStyle to white, and call [context].stroke() to draw the lines between points. A call to [context].closePath() lets the context know that this path is complete.

Of course, we can draw curves fairly easily, too. We can draw a triangle that looks "pinched", with each side bending inward toward the center of the shape. To do this, we replace our [context].lineTo() calls with the following:

this.bufferContext.quadraticCurveTo(125, 125, 200, 100);
this.bufferContext.quadraticCurveTo(125, 125, 100, 200);
this.bufferContext.quadraticCurveTo(125, 125, 100, 100);

Look out, those are some sharp points on that triangle!

Quadratic curves are simple: The first two arguments define the coordinate to which the middle of the line will be "pulled", and the second pair of arguments define that start and end points of the path.

Of course, bezier curves are no problem for us, either. Change the code for drawing your triangle to the following:

this.bufferContext.bezierCurveTo(250,  50,  50,  50, 200, 100);
this.bufferContext.bezierCurveTo(125, 275, 275, 125, 100, 200);
this.bufferContext.bezierCurveTo( 50,  50,  50, 250, 100, 100);

The main difference between quadratic curves and bezier curves are that quadratic curves have one "pull" point, while bezier curves have two. Once you master these curves, you can make some very intriquing designs.

As a side note, you can assign an image as a fillStyle for a path. Doing so is quite simple, involving a call to [context].createPattern(). The function takes two arguments: The first is the image you want to use, and the second is a string that determines the pattern of repetition. Valid values for this argument are "repeat", "repeat-x", "repeat-y", and "no-repeat".

There are some other path-plotting functions: arcTo(float x1, float y1, float x2, float y2, float radius); and arc(float x, float y, float radius, float startAngle, float endAngle, boolean anticlockwise). Experiment with these to learn how to create things like pie charts, etc. Oh, and don't forget the rect(float x, float y, float width, float height) function!

Before we move on to scaling our game canvas, let's touch on one last detail about paths - there is a function, [context].isPointInPath(float x, float y) that will tell you whether the specified point is contained within the path you are currently plotting. It returns true if the point is contained within the path, false if otherwise. Use this for collision detection against complex shapes.

Now that you have a good understanding of paths, we can move on to something a little different. Let's say you want to scale your game canvas to fit the size of the browser window. Furthermore, you want to scale the image with the canvas, so that players with bigger screens see the same amount of view area, just stretched to fit.

If that's something you're interested in, you're in luck - it's pretty easy to do this, so let's get to work on that. Firstly, go back to your skeleton HTML file. We will generally leave this alone for the most part, but there are times where it will need a slight tweak. In the <body> tag, add the following attribute shown in boldface:

<body onload="startGame();" onresize="game.resize();">

This makes the browser call our GameCore's .resize() function, which is:

GameCore.prototype.resize = function() {
  var winInnerWidth = window.innerWidth;
  var winInnerHeight = window.innerHeight;

  this.primaryCanvas.width = winInnerWidth;
  this.primaryCanvas.height = winInnerHeight;

  this.primaryCanvasWidth = this.primaryCanvas.width;
  this.primaryCanvasHeight = this.primaryCanvas.height;
}

This function simply resizes the primary canvas, without touching the buffer canvas. Thus, we can keep the same amount of data on-screen independent of the size of the game's primary canvas. The buffer just "stretches" to the size of the primary canvas.

Remember that this function is called whenever the window is resized, so you may want to add an extra call to the GameCore.resize() method at the end of your GameCore.init() method, just before the call to GameCore.loadData().

Here's an exercise: Add a minimum and maximum size to which the primary canvas will scale. For extra credit, have the primary canvas retain its original aspect ratio. Hint: The aspect ratio would be the canvas width divided by the canvas height.

That about does it for laying the groundwork. In the next section, we'll begin to take what we've learned to help us build a simple framework for our game. In the meantime, there's a really nice "HTML5 Canvas Cheat Sheet" you should definitely check out.

Until next time, have fun!

Project "HoT MetaL JaZz" - Part 2

In the previous installment of this series, we added code to our project that showed us how to draw text to our canvas and manipulate it a bit. Now, we will learn more about the drawing functions within the HTML5 canvas element, including image-drawing capabilities.

Let us begin this exercise by modifying our base template for HTML5 games. Everything will be similar to the skeleton presented in Part 0 of our series, except that we will have a separate file for our game scripts.

The new skeleton code is as follows:


<head>
  <title>HoT MetaL JaZz - Rev.2</title>

  <script src="gamecore.js"></script>

  <script>
    var game;
    function startGame() {
      game = new GameCore(document.getElementById("gamecanvas"),
                          document.getElementById("backbuffer"),
                          30);
    }
  </script>

  <style type="text/css">
    body { margin: 0 auto; text-align: center; }
  </style>
</head>

<body onload="startGame();">
  <canvas id="gamecanvas" width="300" height="300"></canvas>
  <canvas id="backbuffer" width="300" height="300" style="display:none;"></canvas>
</body>


Save the code into a plain text file, with a file name ending with ".html". This simple HTML file will allow us to write as much game code as we want without touching the "front-end" HTML file, with the exception of adding new script file definition in the <head> area.

This skeleton code works with the script file "gamecore.js". To add this file, create a new, empty text file to the same folder as your HTML file, and name it "gamecore.js". We will use this new file to store the "core" scripts for our game.

We will define a GameCore class in gamecore.js. Its constructor will simply take a primary canvas, a buffer canvas, and a "desired" framerate as arguments. It will then store references to the canvas elements and do a few other basic setup tasks. Then, it will automatically call a function to initialize the game. Take the following code:


function GameCore(primaryCanvas, bufferCanvas, desiredFramerate) {
  this.primaryCanvas = primaryCanvas;
  this.primaryContext;
  this.bufferCanvas = bufferCanvas;
  this.bufferContext;

  //store the width and height of each canvas to reduce
  //the overhead involved in individual queries to canvas elements
  this.primaryCanvasWidth = primaryCanvas.width;
  this.primaryCanvasHeight = primaryCanvas.height;
  this.bufferCanvasWidth = bufferCanvas.width;
  this.bufferCanvasHeight = bufferCanvas.height;

  //To get a framerate of N frames per second, divide 1000 by N
  this.frameSpeed = 1000 / desiredFramerate;

  this.images = new Array();

  this.init();
}


As you can see, there isn't much going on here that we haven't covered. After we reference the Canvas objects and make variables to store the context for each canvas, we store the width and height of each. We have a "frameSpeed" variable, which sets a timeout between refreshes - timeouts are measured in milliseconds (1/1000th of a second), so we get our actual frames-per-second delay by dividing 1000 by our desiredFramerate. The desiredFramerate should be a reasonable value - no more than 60, but in practice, about 30. Then we create a new array to store the images we will use for this example.

At the end of the GameCore constructor, we make a call to the init() function of our GameCore object. For now, our GameCore.init() function looks like this:


GameCore.prototype.init = function() {
  if (this.primaryCanvas.getContext) {
    this.primaryContext = this.primaryCanvas.getContext("2d");
    this.primaryContext.clearRect(0,
                                  0,
                                  this.primaryCanvasWidth,
                                  this.primaryCanvasHeight);
  }

  if (this.bufferCanvas.getContext) {
    this.bufferContext = this.bufferCanvas.getContext("2d");
    this.bufferContext.clearRect(0,
                                 0,
                                 this.bufferCanvasWidth,
                                 this.bufferCanvasHeight);
  }

  this.loadData();
}


We simply set up the references to the context of our primary and buffer canvases here. We use the variables in which we stored each canvas's width and height, to avoid any unnecessary overhead from calling the canvas properties directly. Once this has been done, the GameCore.loadData() function is called. This function is defined as such:


GameCore.prototype.loadData = function() {
  var testImage = new Image();
  testImage.src = "sprite.png";
  this.images.push(testImage);

  this.draw();
}


For the purpose of our demonstration, we define the loadData() function to create a new Image object, set it to point to an image named "sprite.png", and then add the image to our GameCore.images array. Once that is done, we are ready to start the game. Our GameCore.draw() function looks like this:


GameCore.prototype.draw = function() {
  this.bufferContext.fillRect(0,
                              0,
                              this.bufferCanvasWidth,
                              this.bufferCanvasHeight);


  for (currImage = 0; currImage < this.images.length; currImage++) {
    if (this.images[currImage].complete) {
      this.bufferContext.drawImage(this.images[currImage],
                                   this.bufferCanvasWidth / 2,
                                   this.bufferCanvasHeight / 2);
    }
  }


  this.primaryContext.clearRect(0,
                                0,
                                this.primaryCanvasWidth,
                                this.primaryCanvasHeight);

  this.primaryContext.drawImage(this.bufferCanvas,
                                0,
                                0,
                                this.primaryCanvasWidth,
                                this.primaryCanvasHeight);

  setTimeout("game.draw()", this.frameSpeed);
}


This function begins by filling the backbuffer with a solid black rectangle (remember, the default fillStyle is black). We then iterate through all the images in our demo (currently, just one) to make sure they have completely loaded. If the image is finished loading, we draw the image to the center of our backbuffer using the context.drawImage(...) function. Here, we put our image as the first argument, and the X/Y coordinate at which to place the image.

Once we have iterated through all our images, we clear the primary context, and then "flip" our backbuffer onto it using the drawImage() function. This time, we call the drawImage() function with five arguments: The image, the X/Y coordinates, and the width/height of the image to draw. We then set a timeout for redrawing the canvas.

To test this out, we will need our "sprite.png" image file in our game directory. If you don't feel like making your own, here is the one I used in writing this article:



When you open the page, you should see your sprite image appear near the center of the canvas. It is off-center a bit, because the image is drawn starting from the top-left. In other words, the top-left of the image is in the center of the canvas!

Later, we will give suggestions for easily drawing images from their center, rather than their top-left corners. For now, though, let's go into detail on the drawImage() function.

The drawImage() function template looks like this:

drawImage(Object image, float dx, float dy, float dw, float dh)

Where image can be an HTML image, HTML canvas, or HTML video element. dx/dy indicate the origin of drawing (i.e. the top-left corner of where to draw). dw/dh are optional arguments, and indicate how much of the image to draw. In other words, if our image is 300x300, and only want to draw half of that image, we would call drawImage() as such:

[context].drawImage(myImage, 0, 0, 150, 150);

If dw/dh are not defined, the entire image will be drawn.

There is also an alternate way to use drawImage() that allows you to draw a specific portion of an image to a context. We will go over this method later in this series.

The next time we dive into Project "HoT MetaL JaZz", we will go over some of the advanced path functions built into the HTML5 canvas element, and also learn how to dynamically scale our game to fit the player's browser window. It will be an extremely exciting ride, so don't miss it!

Starting out with 3D #1 (A - E)

With each technological advancement a few new words are invented. For example a Hard drive, an Operating System, Application software, PDF, etc.  All those were words that you wouldn’t find anywhere a hundred years ago. 3D is no exception. There are hundreds of new words and terms you should learn before you can think of going into 3D.

First off, you should know that 3D is a space that has height, width and depth. 2D only has height and width.

Note: Not only should you know 3D terms before you can tackle 3D, make sure you know your 2D terms to! Such as channel, animation, co-ordinate system etc.

Due to the massive amount of words that was invented for 3D, this topic was split into several parts, I also only included the important ones, things you will be using a lot, or things I think will be much more popular in the future. At the end of the series, you can find a downloadable PDF file with all the words neatly summed up.

#1 (A – E)
#2 (F – L)
#3 (M – P)
#4 (Q – T)
#5 (U – Z)

Bone
Much like a human bone organ, a bone in a 3D scene is placed “inside” of the skeleton of the model. When the bone in the skeleton is moved, it reacts on the mesh, making the mesh move, thus deforming the model to fit into the skeleton.

Boolean
In 3D, a Boolean is an object that is created by merging two new objects via mathematical operators. The two objects may be subtracted, merged or intersected to form a new object. See screenshot below of me using the Boolean technique on two cubes.


Bounding Box
The smallest possible regular shaped block that encloses an object.
 

Why would this be useful? This really does speed up a lot of maths, for example with collision detection. Instead of checking collision with hundreds of points on the model, a simple box is created.

This is also a rendering technique (See DirectX article), in which programmers check if the bounding box has any effect on the final image. If not, the object is not rendered. This saves your computer a lot of trouble and speeds up gameplay.

Bump Map
Bump mapping is a technique used to modify a 3D object based on a 2D, black and white image. When projected on the surface of a model, parts of the surface which has lighter, or white colors are raised, darker colors are lowered. This is simply a rendering effect and can make a big difference on the end effect. The actual model is not actually edited. (See Displacement map).


A clean sphere on the left, with a bump map in the middle, placed over the sphere will generate the result on the right.

Camera
A virtual viewpoint in 3D space. A camera represents the viewers eye. Everything you see on the screen of a game, is making use of a camera. A camera can move, rotate, zoom, etc. Whatever to suit the programmers need.

Camera Mapping

A technique by which geometry matching the size and perspective of objects shown within a still image is constructed, and the original image mapped back onto those objects. This permits limited camera movement around the picture, giving the illusion of a 3D environment from a 2D image.

Camera Path
The given path in 3D space in which the camera will move in a 3D scene. For example, when starting a game, some games give you a quick preview of the level. That preview you see is the image from a camera which is moving in a path.

Camera Tracking
A visual-effects technique that allows the insertion of computer graphics into other footage with correct position, scale, orientation, and motion relative to the photographed objects in the shot.

Caustics
A piece of intense illumination caused by the refraction of light through a transparent object or the
reflection of light from a reflective surface. This is not easy to achieve, in mathematics, this effect would have a formula similar to this:
 
Luckily none of us have to worry about that. The 3D package worries about that. It does all you need. Only recently have computers be able to create this effect in a 3D environment. A common example is that reflective shine on a swimming pool on a hot sunny day.

CGI
CGI stands for computer generated imagery. This is really simple. An image created or manipulated with the help of a computer. This is used in a lot of forms, but mostly in 3D. Probably because 3D is created from scratch and not like photographs being manipulated.

Character Animation
A sub section of animation that deals with the simulation of movements of living creatures. Usually before this can be done the model has to be rigged. (See part 4).

CV
CV stands for control vertex(See part 5). Which is a control point used to manipulate a NURBS(See part 3) curve.

Displacement Map
Similar to a Bump map, but a Displacement map modifies the actual underlining geometry and is not just a rendering effect.

DoF
Stands for Depth of Field. The depth of field of a specific lens is the range of acceptable focus in front of and behind the primary focus setting. It is a function not only of the specific lens used but
also of the distance from the lens to the primary focal plane, and of the chosen aperture. Larger apertures will narrow the depth of field, smaller apertures will increase it.


Extrusion
A modeling technique in which a 2D outline is duplicated outwards along a linear path. Example of extruding a flat plane.


This concludes the first section of our 3D terminology. Stay tuned, number 2 is coming soon!

2010-11-19

Tech Roundup: Digital Audio

Are you a musician who doesn't know much about technology? Or perhaps a techie who simply needs some information on available technologies involving music production and sound? If so, then this article will give you a break-down of the major technologies involved in computer audio.

DAW
Let us start with the big picture. A DAW (Digital Audio Workstation) is the heart and soul of the digital studio. They typically process, record, and mix sound; as well as give you the ability to use different plug-ins. Examples of DAW software include:

Steinberg Cubase - http://www.steinberg.net/
Propellerhead Record Reason Duo - http://www.propellerheads.se/
Energy-XT -  http://www.energy-xt.com/
Cakewalk SONAR - http://www.cakewalk.com/products/SONAR/
Ableton Live - http://www.ableton.com/
Pro Tools - http://www.avid.com/US/resources/digi-orientation/


MIDI

A common format used in composing music, MIDI (Musical Instrument Data Interface) actually doesn't contain any sound data. Instead, it uses instructions to interact with devices or software. MIDI is a standard "language" used by software and hardware to talk and interact with one another. For example, a MIDI file on your computer sends instructions to your MIDI player software to tell it which notes to hit, when to release notes, how much velocity to use when hitting a note, and so on.


Loops

Loops are short "chunks" of music - such as a drum pattern - that can be used to form a baseline for a song. These can come in multiple varieties: Some are divided into separate beats and can be quantized and matched to a beat; while others are simply a single sound file. Common loop formats include:

WAV - A standard, uncompressed sound file.
Acidized WAV - Similar to a wav, but "sliced" into segments that can be adjusted for tempo.
REX Loop - One of the most common loop formats. This format was engineered by the creators of Propellerhead Reason and Record.
Apple Loop - A loop format used in Apple software, such as Garageband and Logic.


Samples

Samples are small sound files that represent a note played from an instrument or other source. These sounds can be used individually, but are often packaged into sample "libraries" that include many related samples. Some of these libraries can be used in conjunction with MIDI data to change the sound. The most common of these is SoundFont; a format created by E-mu Systems, Inc. that includes sampled sounds arranged in categories called "banks". SoundFonts are commonly used to render "enhanced" MIDI music.


Plug-ins

Plug-ins include virtual instruments and effects that "plug in" to your DAW to enhance and shape your sound. These can be anything from reverbs, distortion effects, overdrive effects, and vocoders. They can also be instruments such as synthesizers and sample-based sound engines. Plug-in standards include:

VST - Designed by Steinberg, VSTs are programs that are loaded into a DAW as effects processors and the like.
VSTi - Similar to VST, but generally contain sampled sounds from one or more musical instruments.
RTAS - This format was developed by DigiDesign and Avid.
AU - Apple's own plug-in standard.


Putting it all together

It can be daunting putting together the right combination of software for music production. After all, not all DAW software will use all plug-in formats, loop formats, or even sample formats. It is important to keep in mind a few things as you shop for digital audio tools:

Compatibility. Do the formats supported by your DAW match the formats of the loops, samples, and plug-ins you want to use?
Copy-Protection. Do you have to buy any extra copy-protection hardware, such as a dongle?
Performance. Will your computer be able to handle the overhead of the software and all effects/instruments you plan on using?

If you are seriously considering moving over to the digital music standard, it will pay off to be patient, do your research, and learn the ins and outs of each piece of software in which you are interested. It may take some time to settle on something that fits your needs - and budget - but knowing what you're looking for is the first step in making the leap.