Chapter 10. Advanced 3D Graphics

OpenGL provides a huge amount of flexibility in how objects get rendered, and you can do all kinds of interesting things with light and material. In this chapter, we’re going to look at shaders, which are small programs that give you complete control over how OpenGL should draw your 3D scene. We’ll look at lighting, texturing, bump-mapping, and non-photorealistic rendering.

This chapter builds on beginning and intermediate concepts covered in Chapters 8 and 9, respectively.

Understanding Shaders

Problem

You want to create shader programs, which control how objects are drawn onscreen, so that you can create different kinds of materials.

Solution

A shader is comprised of three elements: a vertex shader, a fragment shader, and a shader program that links the vertex and fragment shaders together. To make a shader, you first write the vertex and fragment shaders, then load them in to OpenGL, and then tell OpenGL when you want to use them.

First, create the vertex shader. Create a file called SimpleVertexShader.vsh, and add it to your project:

uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;

attribute vec3 position;

void main()
{

    // "position" is in model space. We need to convert it to camera space by
    // multiplying it by the modelViewProjection matrix.
    gl_Position = (projectionMatrix* modelViewMatrix) * vec4(position,1.0);
}

Note

When you drag and drop the file into your project, Xcode won’t add it to the list of files that get copied into the app’s ...

Get iOS Game Development Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.