OpenGL is a reasonably abstract API for doing 3D graphics.
In the past I did an example of OpenGL using GLUT.
However GLUT is a bit outdated now and a more modern alternative is GLFW.
The example still uses GLEW to setup the OpenGL extensions.
This example is minimal and only uses a vertex shader and a fragment shader to get started with OpenGL.
For an example using tesselation and geometry shaders as well, see my short introduction to OpenGL.
Note that it is important to add code for retrieving error messages (as I have done below) in order to be able to do development of the shaders.
As in my old example, the code draws a coloured triangle on the screen.
// Minimal OpenGL example using GLFW and GLEW#include<math.h>
#include<stdio.h>
#include<GL/glew.h>
#include<GLFW/glfw3.h>// Vertex shader source code:// This shader takes in vertex positions and texture coordinates,// passing them to the fragment shader.constchar*vertexSource="#version 130\n\
in mediump vec3 point;\n\
in mediump vec2 texcoord;\n\
out mediump vec2 UV;\n\
void main()\n\
{\n\
gl_Position = vec4(point, 1);\n\
UV = texcoord;\n\
}";// Fragment shader source code:// This shader samples the color from a texture based on UV coordinates.constchar*fragmentSource="#version 130\n\
in mediump vec2 UV;\n\
out mediump vec3 fragColor;\n\
uniform sampler2D tex;\n\
void main()\n\
{\n\
fragColor = texture(tex, UV).rgb;\n\
}";GLuintvao;// Vertex Array ObjectGLuintvbo;// Vertex Buffer ObjectGLuintidx;// Index Buffer ObjectGLuinttex;// TextureGLuintprogram;// Shader programintwidth=320;// Width of window in pixelsintheight=240;// Height of window in pixels// Function to handle shader compile errorsvoidhandleCompileError(constchar*step,GLuintshader){GLintresult=GL_FALSE;glGetShaderiv(shader,GL_COMPILE_STATUS,&result);if(result==GL_FALSE){charbuffer[1024];glGetShaderInfoLog(shader,1024,NULL,buffer);if(buffer[0])fprintf(stderr,"%s: %s\n",step,buffer);};}// Function to handle shader program link errorsvoidhandleLinkError(constchar*step,GLuintprogram){GLintresult=GL_FALSE;glGetProgramiv(program,GL_LINK_STATUS,&result);if(result==GL_FALSE){charbuffer[1024];glGetProgramInfoLog(program,1024,NULL,buffer);if(buffer[0])fprintf(stderr,"%s: %s\n",step,buffer);};}// Vertex data:// Each vertex has a position (x, y, z) and a texture coordinate (u, v)GLfloatvertices[]={0.5f,0.5f,0.0f,1.0f,1.0f,// Top right-0.5f,0.5f,0.0f,0.0f,1.0f,// Top left-0.5f,-0.5f,0.0f,0.0f,0.0f// Bottom left};// Indices for drawing the triangleunsignedintindices[]={0,1,2};// Texture BGR data for a 2x2 texturefloatpixels[]={0.0f,0.0f,1.0f,0.0f,1.0f,0.0f,1.0f,0.0f,0.0f,1.0f,1.0f,1.0f};intmain(intargc,char**argv){// Initialize GLFW library.glfwInit();// Create a window.GLFWwindow*window=glfwCreateWindow(width,height,"minimal OpenGL example",NULL,NULL);// Set current OpenGL context to window.glfwMakeContextCurrent(window);// Initialize GLEW library.glewInit();glViewport(0,0,width,height);// Compile and check vertex shader.GLuintvertexShader=glCreateShader(GL_VERTEX_SHADER);glShaderSource(vertexShader,1,&vertexSource,NULL);glCompileShader(vertexShader);handleCompileError("Vertex shader",vertexShader);// Compile and check fragment shader.GLuintfragmentShader=glCreateShader(GL_FRAGMENT_SHADER);glShaderSource(fragmentShader,1,&fragmentSource,NULL);glCompileShader(fragmentShader);handleCompileError("Fragment shader",fragmentShader);// Link and check shader program.program=glCreateProgram();glAttachShader(program,vertexShader);glAttachShader(program,fragmentShader);glLinkProgram(program);handleLinkError("Shader program",program);// Create a vertex array object which serves as context for the// vertex buffer object and the index buffer object.glGenVertexArrays(1,&vao);glBindVertexArray(vao);// Initialize vertex buffer object with the vertex data.glGenBuffers(1,&vbo);glBindBuffer(GL_ARRAY_BUFFER,vbo);glBufferData(GL_ARRAY_BUFFER,sizeof(vertices),vertices,GL_STATIC_DRAW);// Initialize the index buffer object with the index data.glGenBuffers(1,&idx);glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,idx);glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(indices),indices,GL_STATIC_DRAW);// Set up layout of vertex buffer object.glVertexAttribPointer(glGetAttribLocation(program,"point"),3,GL_FLOAT,GL_FALSE,5*sizeof(float),(void*)0);glVertexAttribPointer(glGetAttribLocation(program,"texcoord"),2,GL_FLOAT,GL_FALSE,5*sizeof(float),(void*)(3*sizeof(float)));// Enable depth testing using depth buffer.glEnable(GL_DEPTH_TEST);// Switch to the shader program.glUseProgram(program);// Enable the two variables of the vertex buffer layout.glEnableVertexAttribArray(glGetAttribLocation(program,"point"));glEnableVertexAttribArray(glGetAttribLocation(program,"texcoord"));// Initialize texture.glGenTextures(1,&tex);// Bind texture to first slot.glActiveTexture(GL_TEXTURE0);glBindTexture(GL_TEXTURE_2D,tex);// Set uniform texture in shader object to first texture.glUniform1i(glGetUniformLocation(program,"tex"),0);// Load pixel data into texture.glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,2,2,0,GL_BGR,GL_FLOAT,pixels);// Set texture wrapping mode and interpolation modes.glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);// Initialize multiresolution layers.glGenerateMipmap(GL_TEXTURE_2D);// Loop until the user closes the window.while(!glfwWindowShouldClose(window)){// Clear color buffer and depth buffer.glClearColor(0.0f,0.0f,0.0f,0.0f);glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);// Switch to the shader program.glUseProgram(program);// Draw triangle(s).glDrawElements(GL_TRIANGLES,3,GL_UNSIGNED_INT,(void*)0);// Swap front and back buffers.glfwSwapBuffers(window);// Poll for and process events.glfwPollEvents();};// Disable the two shader variables.glDisableVertexAttribArray(glGetAttribLocation(program,"point"));glDisableVertexAttribArray(glGetAttribLocation(program,"texcoord"));// Unbind and delete the texture.glBindTexture(GL_TEXTURE_2D,0);glDeleteTextures(1,&tex);// Unbind and delete the index buffer object.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);glDeleteBuffers(1,&idx);// Unbind and delete the vertex buffer object.glBindBuffer(GL_ARRAY_BUFFER,0);glDeleteBuffers(1,&vbo);// Unbind and delete the vertex array object.glBindVertexArray(0);glDeleteVertexArrays(1,&vao);// Unlink and delete the shader program.glDetachShader(program,vertexShader);glDetachShader(program,fragmentShader);glDeleteProgram(program);glDeleteShader(vertexShader);glDeleteShader(fragmentShader);// Set OpenGL context to NULL.glfwMakeContextCurrent(NULL);// Destroy window.glfwDestroyWindow(window);// Terminate GLFW.glfwTerminate();return0;}
The example uses the widely supported OpenGL version 3.1 (which has the version tag 130).
You can download, compile, and run the example as follows:
In the past I have experimented with sequential impulses to implement constraints (see
part 1,
part 2,
part 3,
part 4,
part 5,
part 6 of my rigid body physics series).
I tried to integrate Runge-Kutta integration with sequential impulses.
However it was difficult to prevent interpenetration of objects.
Also implementing a vehicle with wheels and suspension, where the weight ratio between the vehicle and the wheels was high, required a high number of iterations to stabilise.
Finally stacking of boxes turned out to be unstable.
In the following I have provided a few Jolt physics example programs to demonstrate some capabilities of the physics engine.
Installing Jolt
Jolt Physics is a C++ library built using CMake.
To compile with double precision, I invoked JoltPhysics/Build/cmake_linux_clang_gcc.sh as follows:
cd Build
./cmake_linux_clang_gcc.sh Release g++ -DCMAKE_POSITION_INDEPENDENT_CODE=ON -DDOUBLE_PRECISION=ON \-DDEBUG_RENDERER_IN_DEBUG_AND_RELEASE=OFF -DPROFILER_IN_DEBUG_AND_RELEASE=OFF
A release build with g++ and installation is done as follows:
cd Linux_Release
make -j`nproc`sudo make install
cd ../..
Next you can have a look at JoltPhysics/HelloWorld/HelloWorld.cpp which is a simple example of a sphere bouncing on a floor.
The example shows how to implement the required layers and collision filters (e.g. stationary objects cannot collide with each other).
Make sure to define the Trace variable so you get useful warnings if something goes wrong.
Tumbling object in space
In this section we test the tumbling motion of a cuboid in space.
To compile a C++ program using Jolt, you need to use the same preprocessor definitions which were used to compile Jolt.
If you have set up the Trace function, you will get a warning if the preprocessor definitions do not match.
Here is an example Makefile to compile and link a program with the release build of the Jolt library, GLFW, and GLEW.
The core of the example creates a shape of dimension a×b×c and sets the density to 1000.0.
Furthermore the convex radius used for approximating collision shapes needs to be much smaller than the object dimensions.
The limit for the linear velocity is lifted and most importantly the solution for gyroscopic forces is enabled.
Furthermore linear and angular damping are set to zero.
Finally the body is created, added to the physics system, and the angular velocity is set to an interesting value.
The code snippet is shown below:
In this section we test the falling motion of a stack of cuboids.
Three cuboids are created and the initial positions are staggered in the x direction to get a more interesting result.
Using i = 0, 1, 2 the cuboids are created in the following way:
Furthermore a ground shape is created.
Note that for simplicity I only created one layer.
If the ground was composed of multiple convex objects, a static layer should be created and used.
The double pendulum is created using the HingeConstraintSettings class.
There are two hinges.
One between the base and the upper arm of the pendulum and one between the upper arm and the lower arm.
The physics library also requires initialisation of a vector normal to the hinge axis.
Another test case is a prismatic joint with a suspension constraint.
The prismatic joint is created using the SliderConstraintSettings class.
The suspension is created using a soft distance constraint.
The code snippet is shown below:
Jolt comes with a specialised implementation for simulating wheeled vehicles (there is also even one for tracked vehicles).
The vehicle API allows placing the wheels and adjusting the suspension minimum and maximum length.
One can set the angular damping of the wheels to zero.
Furthermore there are longitudinal and lateral friction curves of the wheels which I haven’t modified.
Finally there is a vehicle controller object for setting motor, steering angle, brakes, and hand brake.
Note that there is a mMinVelocityForRestitution setting.
I.e. if two bodies collide at a velocity below that (default is 1.0 m/s), an inelastic collision will occur.
This is a small example on how to implement an interpreter using Clojure and the Instaparse library.
Dependencies
First we create a deps.edn file to get Rich Hickey’s Clojure, Mark Engelberg’s Instaparse, the Midje test suite by Brian Marick, and my modified version of Max Miorim’s midje-runner:
We also need to create an initial grammar in resources/clj_calculator/calculator.bnf defining a minimal grammar and a regular expression for parsing an integer:
START = <WHITESPACE?> (NUMBER | SUM | DIFF | PROD) <WHITESPACE?>
SUM = NUMBER <WHITESPACE?> <'+'> <WHITESPACE?> NUMBER
DIFF = NUMBER <WHITESPACE?> <'-'> <WHITESPACE?> NUMBER
PROD = NUMBER <WHITESPACE?> <'*'> <WHITESPACE?> NUMBER
NUMBER = #'[-+]?[0-9]+'
WHITESPACE = #'[,\ \t]+'
Transforming syntax trees
Instaparse comes with a useful transformation function for recursively transforming the abstract syntax tree we obtained from parsing.
First we write and run a failing test for transforming a string to an integer:
(facts"Test calculator"(calculate"-42")=>-42)
To pass the test we implement a calculator function which transforms the syntax tree.
Initially it only needs to deal with the nonterminal symbols START and NUMBER:
Obviously we can use the transformation function to also perform the calculations.
Here are the tests for the three possible operations of the parse tree.
A naive implementation using a blind EXPR nonterminal symbol passes the test:
START = <WHITESPACE?> (EXPR | SUM | DIFF | PROD) <WHITESPACE?>
<EXPR> = SUM | DIFF | PROD | NUMBER
SUM = EXPR <WHITESPACE?> <'+'> <WHITESPACE?> EXPR
DIFF = EXPR <WHITESPACE?> <'-'> <WHITESPACE?> EXPR
PROD = EXPR <WHITESPACE?> <'*'> <WHITESPACE?> EXPR
NUMBER = #'[-+]?[0-9]+'
WHITESPACE = #'[,\ \t]+'
However there is a problem with this grammar: It is ambiguous.
The following failing test shows that the parser could generate two different parse trees:
When parsing small strings, this might not be a problem.
However if you use an ambiguous grammar to parse a large file with a syntax error near the end, the resulting combinatorial explosion leads to a long processing time before the parser can return the syntax error.
The good thing is, that Instaparse uses the GLL parsing algorithm, i.e. it can handle a left-recursive grammar to resolve the ambiguity:
START = <WHITESPACE?> (EXPR | SUM | DIFF | PROD) <WHITESPACE?>
<EXPR> = SUM | DIFF | PROD | NUMBER
SUM = EXPR <WHITESPACE?> <'+'> <WHITESPACE?> NUMBER
DIFF = EXPR <WHITESPACE?> <'-'> <WHITESPACE?> NUMBER
PROD = EXPR <WHITESPACE?> <'*'> <WHITESPACE?> NUMBER
NUMBER = #'[-+]?[0-9]+'
WHITESPACE = #'[,\ \t]+'
This grammar is not ambiguous any more and will pass above test.
Grouping using brackets
We might want to use brackets to group expressions and influence the order expressions are applied: