water

Hello

It’s been long time since last post, but it wasn’t wasted (i hope so). I fixed a lot of bugs and made few changes that improves performance of engine. Most important upgrade applies to lighting – previously I was clearing screen alpha component for each visible light with glClear(…) then i noticed that this is the bottleneck of lighting system, now I’m just drawing quad with certain dimensions  which set alpha to zero – this approach is faster. Additionally i restrict shadow drawing area to AABB of current light via glScissior(…)  – this helps because shadows were projected to “infinity” (far away of light) what consumes a lot of fillrate.

OK that was not interesting part of work I have done. Let’s look closer on new features (yey) I added.The easiest to  see and most complex is water. To really to talk about it, we must to split it into two planes:

graphics part: which is responsible for general outlook of water so looking wavy and… splashes when something is getting into water or out of water. Splashes are made of particles of which I have mentioned some time ago. Simply – physics part of water reports when, where and how big splash (determined by velocity) should be shown. Splash also is modifying water surface to generate waves on water which are simulated by modified algorithm described in presentation Real Time Fluids in Games (link) by Matthias Müller which general rule goes like this:

[code language=”cpp”]
u[N] – water surface peaks
v[N] – velocity of peaks

for(unsigned int i=1;i<N-1;++i)
{
v[i] +=(u[i-1] + u[i+1])/2 – u[i];
v[i] *= 0.99;
u[i] += v[i] *delta_time;
}
[/code]

when splash occurs i simply add velocity to certain group of vertices, negative velocity when something falls into water, positive otherwise.
– physics part – responsible for applying “fake” buoyancy force. Linear buoyancy itself isn’t hard – just add central force to body. The problem  is with correct rotating body in water which is not so obvious. I was searching  how to do that, i found that is implemented in bullet but it was not enough flexible and complicated (complicated = much lines of code = probably slow 🙂 ) I was looking for something lightweight. I also found that someone implemented buoyancy controller in box2d (see http://personal.boristhebrave.com/project/b2buoyancycontroller and flash demo) but this also was to heavy (computing centroid including rotations). So I came up with my own solution, very approximate btw. It’ based only on AABB of objects so it’s very quick. Most of physics engines uses AABB so i have more than half at the beginning. Next step is to try to minimize object AABB if it is floating on water by applying torque in specific direction. That’s all. As I said,  it has nothing with real buoyancy  but for my purposes it is enough (we all know game programing is art of cheating). Moreover I added new parameter for physics objects which decide if object would sink or float (x<1.f sink ; x>1.f float ; x=1.f stay).

I got some concepts for levels with water… and maybe You have ideas for some puzzles with such mechanics? (yes fluids can also kill like toxic water or immortal lava <pshhhh>).

On video you can see actual state of game / engine. I added some interesting items to this map like trampoline (on the left in beginning) but during video recording I forgot about jumping on it several times to show how it behaves. I collected also new nice textures and climatic ambient sounds that creates climatic scary atmosphere. Of course you should enable full screen for better look.

lighting

Welcome everybody!                                 
Last time I made something for outlook of my game. Previously  I was able to darken environment via manually setting color per each vertex, now besides that, I can also specify global ambient color which is darkening level. Furthermore, it is possible to attach light spot to any object on scene, then every objects that are in certain radius from light are illuminated. Additionally, I implemented shadow casting algorithm basing on this article. But let’s start from the beginning, general recipe for that effect looks pretty simple:

1. Clear screen with ambient color
2. For each lightgradient
     a) set drawing only to alpha channel
     b) remove existing on screen alpha channel
     c) set blending to additive
     d) for each object near light: render shadow using only alpha color
     e) set drawing only to r g b channels
     f) render light only where, there is no shadow
3. copy light-map  existing  on screen to texture
4. clear screen
5. draw scene normally
6. set multiplicative blending ( wherever light-map is black  there will be dark)
7. draw quad with dimensions of  screen textured with light-map
8. bonus:  if emissive light needed draw it again with additive blending

Re 2.f

just draw quad with light gradient texture like image on right, you may also change light color by glColor…

Re 1, 2.b and 4

in opengl we can clear screen by using glClear(GL_COLOR_BUFFER_BIT)  function as long in this case we aren’t using depth and stencil buffers. Additionally  we can set global ambient color via  glClearColor(ambientR,ambientG,ambientB,0.f);  so it will immediately fill screen with wanted color

Re 2.a 2.e

setting true or  false in parameters enables or disables drawing to that channel  glColorMask(red,green,blue,alpha); Re 3 we can copy pixels to texture by using glCopyTexSubImage2D function or… we can skip this point if we previously set rendering directly to texture via FrameBufferObjects (FBO) then we can avoid copping pixels from  screen to texture. It seems to be large optimization, In by case glCopyTexSubImage2D works faster than FBO and everywhere people are writing that it should be slower. I don’t know why this is so. I suspect that it can be because my old integrated graphics card (intel GMA X3100)

Re 2.c 2.f and 6

blend function so the way how existing color of pixel and currently drawing is mixed we can set by glBlendFunc(enum ,enum) it is still bit confusing to me but I understood couple of setups

  • multiplicative: previous color * actual color  = glBlendFunc(GL_DST_COLOR, GL_ZERO)
  • additive: previous color + actual color =  glBlendFunc(GL_ONE, GL_ONE)
  • drawing inversely proportional to amount of alpha =  glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE)

Note: this lighting system was done without any shaders,  only pure OpenGL with fixed pipeline. The essence is to know how to generate light texture and using appropriate blending functions

2.d is most complicated step. It consist in drawing shadows only with alpha set to 1.0. Firstly my must find all overlapping objects with light, I have done that by comparing axis aligned bounding boxes. Then for each vertex in found object we must calculate vector from light, next we perform dot product on it and object edge normal to determine if this vertex is necessary to cast shadow. After that,  draw each found vertex and vertex casted outside light. As performance optimization we can set glScissor test to save some fill rate.

Particle effects

Hello

At the beginning I want to say that approach mentioned here in my earlier post – so creating sequences of frames consisting for full animation of explosion was totally wrong. After creating one explosion animation in ExploTexGen or Particle Illusion, I wanted to have more of these. So simply I started to create another fixed animations. What was th result? TGA files weighing over 2MB each with poor scalability and repeatable look. It wasn’t too efficient way to produce graphics effects. Additionally, I spent a lot of time on creating, exporting and transforming to looping animation.

So, I decided to create my particle system which could create various effects. Firstly I was thinking that I can use Bullet physics engine to simulate particles without collision. But then, I found that Bullet is calculating too much – too much for simple movement with gravitation, without any collision response. So I am calculating trajectory of  particles by myself. Each particle emitter has 20 parameters which determine appearance of spawned particles. most important of them are:

  • size of particle ( more precisely it is side length of textured square )
  • texture – it can be really small, I’m using 8×8 and 16×16 pixels
  • color – RGBA  begin values
  • lifeTime -as the name suggests, it is time after which particle is removed
  • dieTime – time after which particle begins to die, so it’s color and size starts interpolating to dieColor and dieSize
  • frequency – amount of particles

Full options visible on screenshoot.

It can be used for simulating things like:

  • fire
  • smoke
  • wind steams
  • rain, snow
  • explosion
  • blood
  • falling leaves from trees
  • spells, sparks
  • teleports
  • magic areas
  • waterfalls
  • fountains

As well as lot of other things which I can’t now come up with. What is important is that these various effects are produced / simulated in the same way but with different parameters ( so, logic for falling leaves is the same like in simulating fire or gas steam but final effect is totally different). Moreover, the design of new graphical effects is fast as hell. All particle emitters shown in the video bellow were created in less than 15 minutes. Of course everything is integrated in my world editor (new section added)

On video You can see examples of particle emitters and at the end – gas stream which is also forcefield and source of sound

triggers, switches, levers – custom actions

Hello

Last time, I started to make my game more unpredictable. To achieve that i created my internal “script language” which is integrated into my editor and allows me to make custom actions. For now I see many uses, for example :

  • controlling moving platforms
  • opening doors
  • spawning monsters  (yep, monsters are already implemented)
  • changing music, playing suitable sounds ( mystical sound when when entering the room)

How it’s made?

Simply, first in editor I create my level, next i write formula on new script window ( yeah, it will grow to  something like UDK 🙂 ) then I can attach this formula to any object on scene like bottom of switch. After that my chosen object gains new functionality, which is executed every physics update. Especially, typical  trigger checks every update if something collide with it, than if collision occurs, it executes selected action e.g. formula like :

[sourcecode language=”cpp”]
TRIGGER REVERSE OBJ1
[/sourcecode]

mean,  if something touches the object then reverse motor of object which name is “OBJ1″. Of course OBJ1 must have joint with motor enabled, without that nothing will happen. And one more thing is needed to get it to work – object OBJ1 must exist on scene, so we must choose object and name it:

[sourcecode language=”cpp”]
NAME OBJ1
[/sourcecode]

Of course formulas can be combined to give various effects like:

[sourcecode language=”cpp”]
TRIGGER REVERSE OBJ1 REVERSE OBJ2
[/sourcecode]

reverse motor at OBJ1 and reverse motor at OBJ2. This is used in post video – opening horizontal gate
Or something like that:

[sourcecode language=”cpp”]
TRIGGER REVERSE OBJ1 DELAY 300 REVERSE OBJ1
[/sourcecode]

which can mean:  reverse motor at OBJ1 (open door) then wait 5 seconds (300 * physics fixed time-step (1/60 sec) ) then again reverse motor at OBJ1 – close the door. So player have limited time to pass through the door

Switches are made with usage benefits of bullet. Simply capsule-like shape with motor which pushes object in certain direction. Power of motor can be adjusted to the needs. If something is lying on capsule and it’s enough heavy to break power of the motor than it triggers the action. Other type of switch is made with weak motor and it triggers action twice: on collision begin and collision end. The difference of this two switches You can see on video.

Lever is a tricky part.  Every mechanics/logic work beyond eyes of player – lower part of lever  is obscured by non colliding terrain. In fact lever is composed of stick anchored in the middle and the trigger which is waiting for hit. And the only on object which is able to knock it is of course previously mentioned stick.

Especially, trigger doesn’t need to have graphical representation like switch or lever, it can be  also invisible trigger which can create situation like suddenly closed doors after entering new location and played scary sound.


 

 

 

Ps.  Success! first not jerking film!

ropes and ladders

I specialized a new type of object, that allows to stick on it. After physics tick if player wants to catch object, I’m looking on his physics object contact points and simply if there is something to grab – just stick together by adding suitable constraint in right place. When player is sticking something then I unlock his jump possibility, which gives ability to climb. In the video bellow you can see two climbing/sticking models, and as you probably noticed they are not behaving in typical way. I mean specifically that they don’t collide with other objects (especially with player)

in bullet, for turning off collisions per object you can do such things:

  • specify collision group and collision mask while adding object to the world via

[sourcecode language=”cpp”]
btDynamicsWorld::addRigidBody (btRigidBody *body, short group, short mask)
[/sourcecode]

but this is not the way, I use for my ropes, because it prevents collision in very early stage and contact points are not generated for these objects

  • set CF_NO_CONTACT_RESPONSE  flag while constructing body

[sourcecode language=”cpp”]
mBody->setCollisionFlags(mBody->getCollisionFlags() | btCollisionObject::CF_NO_CONTACT_RESPONSE));
[/sourcecode]

contact points will be generated,  so if you don’t need them use previous method because of performance. My sticking objects use this method to let know about ability to grab

Physical sound – how to

update: also available in Polish (slides) Bullet i dźwięki pdf

I decided to create short tutorial about physics based sound. In previous post video you was able to hear my audio. Now I would like to share my short conception with you. Example written in bullet physics engine.

Of course the only way to determine collisions is to search contacts points used by physics engine. But contact points aren’t obvious. We must to check if they meet interesting for us conditions. Currently  I am using two physics sounds:

Impact sound

It should be played when some object hits other object. Typically this is short, loud sound dependent on the materials which objects are made of. Browsing contacts should be done after stepSimulation method defined in collisionWorld class if you have implemented fixed time step physics (see fix-your-timestep article) if you don’t, you can do it using bullet’s internal tick callback.

So you probably want to play “hit” sound when contact point meets this contitions (they work well for me)

  • object really collide with other so contact point distance is less then zero
  • hitting force reaches certain threshold (you must try which is best for you)
  • optionally lifetime of contact point  = 1, so it is just created (I have this condition just in case)

Scratching sound

When some object is sliding on other. It also could depend on objects materials and as extension it can also depend on object sliding velocity (of course if you have such option in your sound library). If greater velocity then sound pitch (frequency) should be greater. Such action will give realism to the sound, like in real world. Here are my conditions for sliding sound effect:

  • length of difference of two object velocity vectors greater than some  small amount (depends on your physics world scaling). Vectors difference is needed to ensure that object is really sliding, this also prevents situation when one object is at rest on another moving object. In this case sliding sound shouldn’t be played, all two object have some velocity, but relatively to each other they aren’t moving and difference of this objects velocities is of course 0
  • contact point distance is less than small value but greater than zero, so one object is located on second

My code example ( magic values works for me, but i have the world scaled by 64 ):

[sourcecode language=”cpp”]
for (int i=0;i< dynamicsWorld->getDispatcher()->getNumManifolds();i++)
{
btPersistentManifold* contactManifold = dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
for(int t=0;tgetNumContacts();++t)
{
auto point=contactManifold->getContactPoint(t);
if(point.getDistance()<-0.5f && point.getLifeTime()==1 && point.getAppliedImpulse()>100.f)
{
//play impact sound
}else
if(((contactManifold->getBody0()->getLinearVelocity()-contactManifold->getBody1()->getLinearVelocity()).length()>4.f) && point.getDistance()<1.5f )
{
//play sliding sound
}
}
}
[/sourcecode]

This easy, short code can really improve audio of your applications. There is still issue – how to play this sounds. I’m using such rules: For impact sound, I’m just playing it on first available channel. For sliding sound I’m using resume / pause method, but You can handle it yourself.

sound, springs, trees and bushes

Ok, at last my game prototype has audio. To achieve that I used SDL_mixer which has quite easy api, and with this wasn’t problem. More difficult part was to determine when certain sound must be played. Of course I am not writing here about trivial cases like player jump, or when player shoots than play “boom” sound. The difficulty is in physics based sounds because of collision ambiguity.  I created two types of physical sound:

  • first is  impact sound e.g.  when box falls to the ground
  • second – sound of scratching e.g. when some object is sliding on ground

All this you can hear on video (sound was recorded little too loud, so there are some defects )

 

 

On the video you can also see upgraded graphics. Adding some plants can really refresh game appearance,  they don’t have physical body they can be displayed behind or before player (hiding places). They are only purely cosmetic aspect.

The last new thing is the spring implemented from bullet physics engine, which may have various frequency of oscillation.

Now I must think about player improvement. I am thinking about creating him legs or feet 🙂

incredible machine

Hello everyone!

Officially I must say that youtube sucks so much.. I moved to vimeo, which is great. Video is put on their site exactly as it is (some jerkiness on video below is from my fault). On the beginning you can see my new feature – forcefields that push objects inside them in chosen direction, here through the “pipe”. On the end, you probably won’t be able to see that (I zoomed out too much) but player is talking(ya, really! he reacted for ball hit). It’s my new target – to create logic-adventure-physics based-platform game with plot.

Terrain destruction vol.3

Finally, physics destruction is completed, I have reduced number of triangles per object to necessary minimum by storing object envelope in it. Than when collision occurs I make geometric difference between ground and explosion vertices, in this example it is simplified circle, but it can be everything (just imagine laser which creates deep but slim holes – great for passing). Final concave polygon is triangulated. Graphics and physics store the same triangles and as far as that’s good for graphics is not as efficient for physics (convex polygons are better)

Another new thing is the animation, created using ExploTexGen. It can generate texture that contains  sequence of smaller images. I only have to manipulate texture coordinates to jump to the correct place – position of the next frame.

Here is video where you can see this news. In middle of film you can see bullet controlled by mouse (I stopped simulation then grabbed it) Ps. youtube screwed my video : (

Terrain destruction vol.2

After long break with posting ( caused by achieving bachelor’s degree – successful btw^^ ) I managed to create various holes in terrain.  Shape of hole can be circle, rectangle, convex polygon, concave also, generally every shape that can be represented by list of vertices. Here you can see circular holes (wire frame view enabled)

[slideshow]

You can see on pics that in some places there are unnecessary triangles. The algorithm is not optimized, it is based only on dividing into smaller triangles:

1.    Find triangles that collide hole shape in certain place ( bullet AABB test)
2.    For each found triangle:

–    A = triangle vertices, B = hole vertices
–    Make polygon difference (complement), output polygon C =A B
–    triangulate C and add to world triangles that we get
–    delete original triangle A

I still need something to merge multiple triangles into one bigger