giovedì 31 dicembre 2015

Day 111: Little improvements to batch shadow

Today I had the revelation that the shadows cannot work with my new batch.
That's because the batch uses the shaders of the models, while tha shadow must use the same shader for everything...this requires to use the old batch, there's no way around it. I did a few changes to make it a little simpler and faster, because it will never change, so it doesn't need to be versatile.

Lighting however will work pretty well with the new batch I think, because the models will be the bounding boxes of the lights, and each one of them will have a user defined shader.
Right now it is not even using a batch, it draws each model with a single draw call, so everything will require quite a bit of refactoring, but it should work in the end.

mercoledì 30 dicembre 2015

Day 110: Upgrading the last scene

Today I finished once and for all to upgrade all the game-side code.
I updated the last scene, the most complex one, and everything is working fine with the new geometry shader system.
I found out that every resource must be defined as a New pointer in the header file of the scene. Most of them were now declared in the start function, but out of scope they become dangling with the new way of doing things, and garbage is sent to the shader. For this reason this simple declaration rule must be followed carefully.

In the next days I'll have to decide how to handle shadows and ligthing shaders. The idea is to use the same batch for all three, however the shadow shader will not be accessible from the game, because I don't think that it needs to be modified... it will eventually expose a few uniforms, like shadow thinckness or shadow fading, and the rest will be shared among all shadows.

EDIT:
In the evening I had a little more time and I did a few things I was planning to do for a while.
First I made a system to recognize which parts of shaders are loaded (for example if the geometry shader is used or not), which I was manually doing right now.
Then I created a shader folder in the game and moved the geometry shaders in there, because now it's a user job. However the folder in the engine remains, to contain a list of standard shaders, which I'll maybe do in the future.

In the picture I tweaked a little with the second geometry shader. The particles change color randomly each frame (from purple to blue), and at the same time the lerp over time from black to the random color. This would not be possible with the standar shader.


martedì 29 dicembre 2015

Day 109: Fixes

Today I wanted to do for lights shaders the same I did for geometry shaders.
But since the engine right now is actually working correctly (i expected that whis would happen only at the end of the whole process), I decided to take a breath and fix a few things.

First I decided to convert all the scenes to the new system, because only the one I was using for testing was working. By doing that I noticed a problem with the normal maps, which i didn't notice in the firework scene because I was using flat materials. (flat = not interacting with light).

It was a little bug inside the batch, and as you can see in the picture, now the light is correctly reflected if I use non-flat materials. 

Then I noticed a crash when quitting the game...apparently there is something wrong in the destruction of singleton classes...I managed to fix it, but I'm not really sure yet why it wasn't working before. Probably in the future I'll remove all the singletons though, I really don't like how they integrate with the engine.


lunedì 28 dicembre 2015

Day 108: Vertex attributes abstraction

Today I jumped right into the shadow/lights shaders, in order to make them work with the same batch as the other ones. However I immediatly noticed the first problem: they send less vertex attributes...just the position, instead of position,uvs, normals and tangent.

In the ryno engine the shader has ~4 types of data: vertices attributes, instance attributes, temporary uniforms and global uniforms. The latter 3 are now automatically handled, however I didn't do it for the vertices, because they are consistent when rendering geometry, and I manually specified them.

However in my goal of an olistic system that handles all the shaders with a single batch class, I needed to take care of that as well. I decided to just use a big macro-vertex struct, and then send only the attributes found in the shader. If an attribute is called "in_Position", "in_Uv", "in_Tangent" or "in_Normal", the batch sends data to the shader by sampling the vertex struct.

This works well with the geometry shader, however i'll probably need to tweaks a few things to make it work with meshes that use a different vertex format, but it shouldn't take long.

domenica 27 dicembre 2015

Day 107: Multiple shaders!

Finally I managed to complete the automatization of the batch for geometry shaders. It shouldn't take that much to completely remove the other batches, and make a single, general purpose batch to handle multiple shaders of multiple types.

Today I started by adding the concept of a "global uniform", which is a uniform tht has the same value for all the instances. For example, in a single frame, every model has the same uniform for the camera matrix, so the info can be stored in the shader instead of the material. The global uniforms must be declared as "g_Name", so the system can recognized them, and must be set through the shader instead of the material.

Then I made a switch to send uniforms to the shader according to the type. This was the last step to have an "abstract" batch. So I created a second geometry shader, and the batch take care of them both. The DeferredRenderer class doesn't have a geometry shader, but simply call the render function on the batch. And it also send the same uniforms to all the shaders in that batch (namely the camera matrices).

Ideally the lighting shader will do the same, but send different uniforms.

The system will be hable to handle whatever shader, the only requirement is that the uniforms used by the deferred renderer class are present.

In the picture, the bottom right emitter has a different shader for the particles material. It takes another uniform (the time), and the resulting color is white multiplied by the sin of the time, to give a "pulsating" effect. This could be emulated with the particle material itself, but the difference behind it is substantial.

This also works with different attributes (and in different numbers)


giovedì 24 dicembre 2015

Day 106: Automatic batching, another step

Today I continued to automatize the batching process. I'm almost at the point where the batch will become identical for whaterver shader I will decide to use, and that is the goal, so that I will be able to build custom shader and just use them with the same batch.

I did really a lot of stuff today, I'm actually having troubles remembering what I did, and if i did it today. Most of the time was spent fixing bugs and scratching my head, because it's a very delicate work, and each change I make is potentially critical.

Now the system is finally able to automatically divide the models into batches. Before I had a sorting algorithm, where the ">" function was manually defined to suit the default shader. Now the ">" function used by the sorting actually compares the uniforms from the two models, and so it is valid for whathever shader.

The performance is not bad, they fps are slightly lower than before, but there is a reason for that: among the uniforms are also the View matrix and the ViewProjection matrix, so they are compared as well. However they are 100% identical among all the materials. When (and if)  everything will be working, I'll introduce a way to declare "global uniforms", which are set to the shader itself, instead of the model. This will reduce the duplication of data and the time used by the sorting algorithm.

In the picture you can se 4 emitters, each one of them spawns particle with a different mesh and texture/normal map. The drawcalls are 4, which is exactly what should be expected.



mercoledì 23 dicembre 2015

Day 105: Huge changes

Today I continued my work on the automatization of shaders and materials.
In the end I managed to make both attributes and uniforms completely "dynamic".

Attributes:
Each material has a chunk of memory. When calling:

material->add_attr(name,value)

the value is inserted at the right position in the chunk. The position is retrieved from the shader class, which holds all the info about the attributes after the query to the gpu shader.

Uniforms:
Since uniforms don't require to be store in a contiguous chunk of memory, each material holds a map of uniforms built by getting infos from the shader class about the uniforms.
In the batch class only those materials with the same uniforms are drawn togheter.

The system still has lots of problems, and tomorrow i'll try and fix most of them. For example I need to write a function that sort the materials based on their uniforms (to be used in the batch class), and the whole system now only works with a single, mock shader I'm using to test everything. However for the first time, I'm actually seeing that this could be possible to achieve

martedì 22 dicembre 2015

Day 104: Unpacking a color

Well, today i decided that  i really dont like the idea of passing data through the attributes names, so i decided to chose another solution...basically i pack data on the cpu, send them as floats to the shaders, and unpack them there.

I tried it on the color, which is the only attributes using bytes, and it works well, a single int32 is passed for all four channels.

I lost a huge amount of time due to a stupid and counterintuitive opengl function, but now luckily i got it working fine

lunedì 21 dicembre 2015

Day 103: Get data from shaders

The engine so far supports a single shader, and does not have a material system.
Adding the support for multiple materials/shaders at this point is a titanic task, because:
1) The engine is developed around the current system, and everything must be changed
2) The engine uses instancing, which add a level of complexity (usually there are attributes and uniforms, with instancing we have attributes, instance attributes with the divisor and uniform).
3) The shaders are more complex "thanks" o the deferred rendering
3) I don't want to force the developer to manually add the attributes/uniforms in c++, so I want to automatize the system to automatically recognize attributes/uniforms.

This is really an huge amount of work, and I'm not even sure that I will be able to get everything done... I have a lot of confusion in mind because, while I know how the single features in the engine work, the big picture is quite blurry, and its pretty painful to think about all the consequences that this big rebuilding will have.

Today I wrote a function to get info about the attributes in the current shader. GLSL stores everything as a 4 byte value (not really true, just to get the idea), there are no shorts or bytes.
So if I query for the type of a color, I get that each component is a GL_FLOAT...which is not ideal because I used to pass just 4 bytes, which where then converted in the gpu. So there is litterally no clean way to tell if something should be a vector of floats or it could be stored in bytes.

Since I really want to save that extra bandwidth, I decided to give a convention to the attributes names in the shader: 
- the first letter of the name is the type (f, b, s, i)
- the second letter tells if the attribute is a number, a vector or a matrix (n, v, m)
- the third letter is a number representing the size of the vector/matrix

This is not a clean solution, but it's the only way to pass useful informations from the gpu to the cpu that I know of. With this system I can send bytes instead of floats when, for example, needing a color.

venerdì 18 dicembre 2015

Day 102: Fixed copy constructors

Ok, I managed to fix the bug I had yesterday...it was quite stupid but it took me an awfully long time because I was not searching for it where I should have. However this allowed me to find a few problems in several copy constructors, that could have brought to other problems in the future.

Now the  copy constructor of the emitter finally works, and the problem with this was its complexity: each emitter is owner of a vector of particles, which cannot be copied, but should be reinstantiated, so it needed a few tweaks to work correctly, both if used before the emitter initialization or after.

In the picture I created a gameobject with an emitter, and then I just duplicated the game object 3 times (which also copies the emitter component in it). Then I just replaced the update lambda that manages the updates of the particles to have different colors, while in the bottom left one I also modified the creation lambda to spawn different colors from the beginning.


giovedì 17 dicembre 2015

Day 102: Annoying bug

Today I improved a little the emitter class, because its copy constructor was buggy. Now it almost works, but I've this strange annoying bug... Basically the particles are changed in color, but the change is somehow delayed...
It's difficult to explain, but it is really, really strange, one of the most strange bugs I've ever experienced, and I wasn't able to fix it today, I hope to do it tomorrow

mercoledì 16 dicembre 2015

Day 101: Scenes manager improvements

Today I did a few things to improve the user-friendlyness of the scenes manager.

First I created a file in the game folder where you can associate a name to each class:

SceneManager::add_scene("myscene");

If you want to use a scene in the editor, it must be declared there, more or less like in Unity.
This allows to change scene by name, which is way better than what I was doing until now.
In the meanwhile I also fixed a bad bug that made the game crash if no object is rendered, which never occurred until now.

Finally I added e \setscene command to the internal console (picture), so I can easily switch scene instead of cycling to all of them.


martedì 15 dicembre 2015

Day 100: 100!

Well, I managed to reach 100 days!
I didn't expect that, and I'm pretty satisfied with it... the engine has quite a lot of features, and I really learned a ton of stuff, which is the most important thing.

Today I just did a little of refactoring, and created 2 scenes to test the scene management system (and the memory allocators).
One bad thing I noticed is that the particle engine has a bad deallocation time with really high numbers of particles (picture), because each one of them must also deallocate its components, since a particle is a gameobject. The same problem is avoided in creation, because the components are created runtime when the particle is used, so the load time is diluted between multiple frames.

Tomorrow I'd like to implement a system that associates a string name to each scene, so that they can be created by name, maybe also through the shell command line. Right now they are manually created through the game, which is not really ideal.




lunedì 14 dicembre 2015

Day 99: Stack and Pool allocator

Today I finished all the allocators I had in mind.

The stack allocator prepares a huge chunck of memory, and each object is allocated on top of it. Deallocating an object does nothing, the only way to remove an object from the top is calling the pop method. The actual deallocation is called when the stack pointer is set back to zero.
It's important to notice that the destructor of an object is still called, so if you really want to destroy an object, a hole in the memory will be left, but this is an obvious downside in stack allocators.

The Pool allocator is not a "global" allocator like the stack allocator and the mallocator. You can create multiple pools, and each one of them can be allocated using other allocators.
To test it out I allocated on the Stack Allocator a pool of Particle3D used by the particle emitter.

To wrap things up I gave a complete set of debug messages to each allocator, and they can be activated or deactivated with a preprocessor directive.

domenica 13 dicembre 2015

Day 98: Mallocator

Today I did quite a lot of stuff.

I created a Mallocator, which is a custom allocator which works exacly like malloc, but hides the implementation details. I refactored the whole engine to instantiate objects with it, and this required a lot of tweaks to make the interface looks nice. Before I had:

go = new GameObject();

now i have

go.create(mallocator);

Now everything is working, copyconstructors and destructors included.

While doing this I noticed a few things that were not good in the engine, like a bad management of the emitter components inside the gameobject, and the fact that the game has one camera for all the scenes. I modified them both, so noew the emitter behaves like any other component, and each scene has its own camera.

Finally I changed the TextureManager to keep track of which textures are lifetime objects and which are not, and it's reset method is now working correctly.

I didn't profile it yet, but now I'm quite confident that everything works like it should, and even if I'll find leaks they should be easy to fix.

The system now allows me to create other allocators pretty easily, like a stack allocator, which is what i'll do next.
The only downside is that it uses lots of template classes and functions, which leads to very bad error messages.

sabato 12 dicembre 2015

Day 97: GUIObject and scenes improvements

Today I continued to improve the scene management system.

To really test it under the worst conditions I decided to convert the complex scene I used in the last weeks/months to the new pointer system. Thankfully I tought of looking a little into operator overloading, and it turns out that overriding the "=" operator it is possible to assign pointers to smart pointers, making the interface to them identical to normal pointers.

So the conversion of the scene went quite smoothly for the most part, however:

- The emitters were a little problematic during destruction, because the particles didn't go away,but thanks to the smart pointers i fixed that

- The Text and Sprite classes were not going away, because they are not component of a GameObject. So I created a GUIObject, which is an aggregator of components exaclty like the GameObject, but for the GUI. It is not perfect and badly integrated, and should be refactored if the GUI will be expanded, but for now it does its job.

So, now everything is working, but I've not checked yet if there is some leaking of memory, or if the destructors of the various managers are doing exaclty their job. Tomorrow I'll check that with some memory profiler, and the next step is the introduction of custom allocators.

In the picture on the left the "big" scene, on the right the "little" scene created after the "big" one, and with no traces of objects from it.


venerdì 11 dicembre 2015

Day 96: Scenes 2

Today I managed to make everything work, and it was quite a painful job, but I learned tons of stuff on how memory works in c++, when destructors are called, how are called and so on.

The solution I adopted is the use of a typed custom pointer called New. Each object is created through this pointer. Each gameobject is therefore created as a New ptr, and so each of his components. However references to these objects are passed around the engine by their true pointer.

Now, when a scene is switched, the old one is deleted. Each New ptr calls its destructor, and the job is done.

To thest this out I removed most of the stuff from the scene, and I just left there the skybox, a cone mesh and a directional light. In scene 2 everything is identical, except that the second cube is thinner and a little on the right.  As you can see from the picture the switching works perfectly: the old mesh is no more visible (that you can't see, sorry)and the light has the same intensity (which means that there aren't two of them).

The last thing that needs to be done is to reset correclty all the managers in the game: audio, textures, meshes and so on, being careful to not reset lifetime resources. And now that I have a custom pointer I could probably add support for others allocators as well.




giovedì 10 dicembre 2015

Day 95: Scenes

In these days I tried to figure out how to correctly handle memory, but in the end I found out that I just had an enormous confusion about that because I never really studied in depth how cpp handles that... One of the things that I learned is that I shouldn't try to create and destruct an object with an allocator, I should just allocate memory, and the destruction should be done with custom pointers:  instead of instantiating new objects, I should create special pointers with a destructor that holds the pointers to the data.

Now that this is clear, I understood that I can just create my scene system WITHOUT the stack allocator, and I don't even need to keep track of the objects, they will eventually be detroyed when the special pointer goes out of scope.

I will implement the special allocators, but only once I get this working with mallocs and frees.

Today I wrote the entire scene management cycle, and the ways that the game uses to change scene.

To test it out I created two scenes, identical except for a cone which is one of them. I switch between them by calling a function defined in the main game class. The switching is done correctly, and the start, update and handle_inputs are correctly called.

As you can see from the picture, since I've not created the special pointers yet, all the previously created geometry are still visible in the scene. I'll hopefully fix that tomorrow.




martedì 8 dicembre 2015

Day 94: Reference allocator and new constructors

Today I implemented the reference allocator for resources that are going to be freed sooner or later.

I also created an Allocator class with an alloc method that takes one enum parameter. Depending on this parameter the resource is allocated with one of the two different allocators I've implemented so far.

The problem with this is that it's really ugly to call somethin like:

Obj* new_obj = nullptr;
Allocator::alloc(&new_obj, STACK_TEMP);

each time an object is created. So I overloaded the "new" constructor of the instantiable classes to allocate memory at a custom address obtained with the allocators instead of a malloc. The code looks like this:

Obj* new_obj = new (STACK_TEMP) Obj();

which is exacly like a normal constructor, but specifies where to get the memory for the allocation.
I'm not happy with copy constructors though, because they often call copy constructors on each pointer inside the class, and there is no way to tell where to allocate memory for these. Right now I'm passing the enum as a parameter, so you can chose where to store all the dependent pointers, but this is both ugly and doesn't allow you to differentiate between different pointers:

Obj* new_obj = new (STACK_TEMP) Obj(old_obj, STACK_TEMP);


lunedì 7 dicembre 2015

Day 93: Double-stack allocator

Today I decided that I really don't like how I was going to handle memory yesterday. I left a few destructors, for example in the AudioManager or TextureManager classes, because they rely on libraries that allocate memory outside my control.

But for everything else I decided to use a double-stack allocator, instead of keeping a reference for each instanitated object. The idea is that a single chunk of memory is preallocated, and each new object is created on top of one of the two extremities of the chunk.

The resources used by the engine are pushed from the bottom, the resource of a scene from the top. When changing scene it is sufficient to reset the stack pointer to the top, while leaving the engine stack pointer where it is...

Pro:
- No mallocs, just one allocation
- Very easy to erase all the allocated objects without keeping references
- Easy to implement
- Neat division between temporary and persistent resources

Cons:
- It is a stack, so it is not possible to remove an allocated object if it is not on the top

Overall I think that the pros are quite interesting, because most resources are kept until the end of a scene. But I will also add a PoolAllocator and GeneralPurposeAllocator: the first will handle lots of identical objects, the second one will simply malloc those objects that really need to be deallocated sooner or later, and will keep pointers to those. It will be up to the developer which one to use in each case,  but I'll provide a simple interface.

Today I implemented the Double-Stack allocator.

domenica 6 dicembre 2015

Day 92: Destructors

Today I decided to start working on a scene management system.

This requires me to handle the memory correcly when I'm switching scenes, and the amount of things I need to change in order to achieve this is pretty huge...

Today I started by modifying a few classes, for example the audio manager, the profiler and the texture manager. Each one of them now has a reset method that removes everything unnecessary, including gpu memory in case of the texture manager.

The first big problem was the MeshManager, because some of the meshes are loaded by the engine, and should not be freed. So I created a little hacky system to understand if a mesh is for the engine or not without storing the information in the mesh itself.

Now I need to proceed with the most difficult part, which is deleting everything created from within the game. I need to keep track of models, emitters, lights and so on, basically everything I created until now... Deleting only the GameObjects is not an option, even if the components are recursively deleted, because some components could not be attached to anything.

So I guess that for each instantiable class I ever created I will add a static field which holds a list of pointers to the instances, and then I'll just call a Free on each element.

Calling free on a gameobject is usally a bad practice, because all the pointers it holds will not be freed, however if every model, every light and every other thing are also freed, this SHOULD not be a problem.

In absence or more clever ideas, I'll proceed down this road

sabato 5 dicembre 2015

Day 91: Perlin Noise

Today I decided to dig a little deeper in mesh generation, and I wrote a class to generate Perlin noise values for realistic terrain generation (actually I just converted a C# class, because it's a simple but boring straightforward piece of code, and I didn't want to spend to much time on it once I got the idea of how it works).

With the perlin noise class I modified the example I posted two days ago. Instead of picking random values for the height of the terrain, now they are sampled from the perlin texture (not really a texture, the values are dinamically generated).

As you can see from the picture the terrain looks way more natural, and close vertices have similar height values.

To simulate even more realistic terrains, the perlin function is called multiple times, and each time the frequency doubles and the height halves, to get the effect of little bumps and irregularities on the surface of the bigger bumbs....this is difficult to see on the picture, because there are not enough vertices and I used a very low value for the eight of the second perlin function.



giovedì 3 dicembre 2015

Day 90: Mesh Generation

Today I Implemented a MeshBuilder class, which allows to create meshes from scratch. This was possible thanks to the changes I made yesterday to the loading system of the meshes.

The  class allows to create new vertices, to modify their pos, uvs and normals, and it also provides two functions, add_triangle and add_quads to map indices on newly created vertices.

There are also two more important functions: generate_normals and generate_tangents.

The first one can be called if the normals are not manually specified, and it creates them automatically for each triangle. The second one should be always called, because tangents are not added manually, but built from uvs and normals.

That's about it, I started by creating a simple quad, and then I created a bumpy plane to replace the floor of the house i'm always using to test the engine. As you can see from the picture the lighting is correct, thanks to normals and tangent generation, as well as positions as uvs.

Shadows are also correctly casted (except for some moire pattern due to low precision), because the mesh, once created, acts as every other mesh.





mercoledì 2 dicembre 2015

Day 89: Indexed meshes

Until now I used to load meshes into a single vertex buffer object. This is bad for performances, because more data need to be sent to the gpu, while an indexed mesh allow to use a single vertex multiple times.

Another big advantage of indexed meshes is the fact that they are easier to read and manually modify, allowing procedural mesh generation.

So today I refactored everything mesh-related, starting from the loading of the mesh, which now produces a vertex array and an index array.

Then I modified all the batches, both 2D and 3D to use the new indexed mesh. Now everything is working and maybe I gained a little fps in all of this, but the real win is the possibility to easily access the mesh data.

Tomorrow I'll try to write a mesh_builder class to procedurally generate meshes. 

giovedì 5 novembre 2015

venerdì 30 ottobre 2015

Day 87: Emitters of Emitters

Today I drastically refactored the particle engine, and now each emitter features a GenericMap and 3 lamdas (setup, spawn and particle_update).
By dividing the code in the three lambdas and passing data around with the GenericMap it is possible to build whatever kind of stuff inside the particle engine.
The system is not incredibly immediate if you don't know how it works, mainly because it is built in a very unconventional way, but now it is very well organized and give complete freedom to the game programmer.
For example, I created fireworks with the following emitters:

EMITTER 1:
Lambda creation: Setup yellow spheres, and attach to them EMITTER 2
Lambda spawn: Create the spheres and reset them to the original position/color
Lamda particle update: Move them and scale them up. When they are near their deaths make them invisible and tell EMITTER 2 to activate itself to simulate the explosion of the secondary firework.

EMITTER 2:
Lambda creation: Setup red cubes
Lambda spawn: Create the cubes and reset them to the position of the sphere
Lambda particle update: Move them to simulate the explosion



giovedì 29 ottobre 2015

Day 86: GenericMap

Today I managed to do something pretty interesting, but only partially related to the engine.
I noticed that I often needed to pass different data types from the emitter to the particles, and there is no way to know what will be used inside the lambdas. It is then impossible to decide which parameters to give the particle.
So i decided to write a generic map, which can accept all kinds of data, and you can add them and retrieve them with a string id.
To do so I used void pointers ant templates, and now I have a functioning class that can also be used for other things.
In the picture, instead of making global the cone mesh so that it can be accessed from the lambda, I just added it to the map inside the emitter lambda, and each particle retrieves it inside its lambda and use it to change shape after a certain amount of time.
I also did other little improvements to the engine, for example I added static colors in the color class, so that now I can just type ColorRGBA::red instead of creating it every time.




mercoledì 28 ottobre 2015

Day 85: Math library and Dust

Today I continued to improve the particle system.
First I made a math library, which is something I was willing to do for a lot of time. That's because the cpp one (STL) is pretty limited, and I also wanted a few functions that work with vectors or colors.
I made it as a class and gave it multiple Lerp and RandomRange functions, which are useful in lots of situations, and also in particle systems.

After that I tried to use the emitter to generate a completly different effect: atmospheric dust.
To do so I needed to program the emitter to emit all the particles at the beginning, and in a wide range of different locations. They are also randomly rotated and deformed, to look less like cubes.
The single particle now moves randomly around very slowly.
The performance is quite ok, not great because I used cubes, and every one of them is a whole gameobject (which also cast shadows), while something like dust should be done in a more optimized way.
However I decided to trade performance for customizability in this particle engine, so that is fine.

In the picture you can see the little particles (which actually looks nicer thanks to the bad compression) and there is also a particle very close to the camera which shows how the model is rotated/deformed.


martedì 27 ottobre 2015

Day 84: Lambdas

Today I refactored and perfected the logical division between data, particles and emitters. This was not so easy, because it is not always clear if some property should be assigned to the particle, to the emitter or neither of them.
For example I completly removed the "number_of_particles_per_second" field, which is standard in basically every particle system I know of, because now the control over it is given through the lambda emitter.
In the picture you can see an emitter where:

1) The particle lambda change the color from green to blue, move the particle of a constant speed  and if the lifetime of the particle is greater than 0.6, then the mesh is changed to a sphere

2) The emitter lambda spawns particles in a direction included in a 180 degrees field, and olso reset the mesh to a cube.

By using the two lambdas the possibilities are quite endless. It is also possible to switch them on the fly, even though in that case one must be careful to make them really independent.


lunedì 26 ottobre 2015

Day 83: 3D Emitter

Today I noticed that porting the 2D emitter in 3D is an enormous task.
That's because I need to rewrite the 2D rendering, I need to rotate sprites so that they face the camera and so on, really an annoying work and even if i manage to do that, there are still problems with transparency and the ability to cast shadows.
So I decided to just do a 3D emitter, which cannot spawn as many particles as the 2D one, but there are tons of pros, because I'm going to implement it in a very customizable way.

The idea behind this emitter is:
1) Particles ARE game_objects. So they can have all the components they like, something not supported by unity and (if i remember correctly) the standard classes of unreal engine.
2) The behaviour of a single particle is dictated by a lambda function
3) The particles are spawned by the emitter with another lambda function

The incredible power of doing it this way, is that each particle can have all the components of a game object. This include shadow mapping, specular and diffuse lighting, light emission, and eventually physics in the future. Oh, and since the Emitter is a component, a single particle could emit particles as well.
The behaviours are dictated by lambdas, so that the game programmer can just assing two different functions instead of changing the whole class.
Right now I built the skeleton of everything, except the emitter lambda, which is a little harder.

In the picture are spawned ~10.000 little cubes, with textures, mapping and shadows enabled, and the fps are ~30, which is pretty nice for such a complex emitter.


domenica 25 ottobre 2015

Day 82: Particle System

I took a little pause from the engine both for school reasons and for the disappointment with the GJK algorithm which i just can't fix.
So today I decided to start anew with a particle system. I already implemented something like that for an old 2D engine, and back there everything was really easy, now it is quite complex for multiple reasons:
1) In 3D the particles must always face the camera, which is something not supported by the GUI sprites
2) Transparency doesn't work with deferred rendering, so I'm not really sure that something like smoke will ever be possible to implement without some trick I don't know yet. Full transparecny could be supported though, which is the most important thing.
3) Mesh particle systems would be a nice future add to the engine, because they work perfectly with deferred rendering, and potentially I could create parcicles that emit lights, respond to  collisions (if I will ever have a collision system) or even cast shadows. Of course I won't be able to spawn millions of those ones though.

Right now I just implemented a simple emitter in camera view, it needs tons of optimizations and refactoring, and then I'll try to port it in 3D, which will probably take some time.


lunedì 5 ottobre 2015

Day 81: Other convex collisions

Today I played with the convex colliders I implemented yesterday, and added a cone collider.
As always the collision behaves strngely, sometimes it seems correct, some other times not...
When the collision occurs, the collision is always detected, but it is sometimes detected even if not colliding, and there is no way for a physics engine to tell whether the check was right or not...
I don't really know how to fix this, I'll keep working on it


domenica 4 ottobre 2015

Day 80: Convex Colliders

Today I decided to implement something I wanted to add AFTER making the GJK work.
But since I've been stuck on it for more than a week, I decided to implement this now, because it could also help to debug the GJK.
I'm talking about arbitrary convex mesh colliders.
To do so I added a function to the MeshManager class to load simplified models, beacause the only interesting property is the position of a vertex.
Then I created a ConvexCollider class with the relative support function, and did a general refactoring on the other colliders as well.
I tried to load a cube mesh to see if the behaviour is the same as the AABB collider.
Here is what I observed:

1) AABB-Convex -> works
2) Convex-Convex -> works
3) Convex-Sphere -> Exactly as AABB-Sphere there are false positives....however they occurs in a way slightly different than before, so the bug I'm struggling to find behaves differently depending on how the AABB is implemented, as AABB or as a convex cube.

Except for the last point, which is not what should happen so it doesn't really count, I would say that the AABB and ConvexCube are functionally identical, and other meshes should work as well (not tried yet).



sabato 3 ottobre 2015

Day 79: Problems with GJK

It's been a few days since I wrote the GJK algorithm, but somehow I'm not having progresses, it still have false positive collisions.
The 2D is now correct, but the 3D is still faulty, and all the implementations I found online are identical to mine, so I'm not sure of where the problem lies...

domenica 27 settembre 2015

Day 78: 3D GJK

Today I finished my implementation of GJK, and now it works in 3D.
In the pictues there are 4 white objects and a textured sphere. The white objects are emitting light only if they are colliding with the textured sphere, so the big right cube is the only one who is not lighting the scene.
However a major problem is still there: collisions between  boxes and spheres are not correct, while box-box and sphere-sphere collisions are.
This is surprising, because I wrote the algorithm from scratch, while following a different source to check if I was not missing something...but even if the code is completly different, the problem remains...
I'm starting to think that the problem doesn't lie in the algorithm, but I'm also positive that the support functions I wrote are correct as well, so I'm not really sure on how to proceed.
Tomorrow I'll probably add a GenericConvexCollider, and see if it behave correctly.


giovedì 24 settembre 2015

Day 77: AABB collisions

Today I introduced a new kind of colliders, the Axis Aligned Bounding Boxes, which are just unoriented cubes, like the ones in the picture.
They have a little problem when the X or the Y values of the two colliders are identical, and I'll try and fix it as soon as I can, but except for that minor problem they work perfectly.

But, unexpectedly, the collision between AABB and spheres is not what I expected...it is a little off, basically it happens when the two colliders are still a little distant, like the big cube and the sphere in the picture ...I'm not sure if this is normal and GJK don't support collisions between eterogeneous colliders, but I think that it should, and so maybe something is wrong in my implementation

mercoledì 23 settembre 2015

Day 76: GJK

In the last few days I started studying how to implement collisions.
This is actually way more difficult and time consuming than I imagined, especially considering that the colliders can also be convex objects, and not just spheres or cubes.
So I started studying collisions, which is the basis for any physics engine.
Instead of implementing everything with simple colliders, I decided to go directly to the algorithm for convex colliders, which is the GJK.
It is quite complex, especially in 3D, but it has a great advantage: it can check collisions between any kind of shape that can answer to the question: "Which is the farthest point I have in the given direction?"
So It is possible to check collisions between a mesh and an ellipse curve  for example.
Also, for convex meshes, it is faster than the SAT method.
In the picture I implemented it in just two dimension, and I used sphere colliders.
The three external spheres check collisions with the central one, and the left one is yellow because it is not colliding.
Tomorrow I'll add AABB colliders as well, and i'll try to make them collide between each other.
Extending the algorithm to 3D is pretty annoying and error prone, I expect it to  be hard, I'll try to do it soon


lunedì 21 settembre 2015

Day 75: Composite pattern

Today I wanted to add simple colliders to the GameObjects...However they would require a transform, and the GameObjects class already have transform informations...so does ligths, so I decided to do a big refactoring to create a system similar to the Unity one.
A GameObjects is the root object, and its behaviour is defined by its components, as in a slightly simplified composite pattern.
The refactoring took a lot of time, because lots of classes were dependent on lights or models information, while now they are dependent only on GameObjects.
Now each GameObject has 5 components: a Transform, a Model, and the three types of lights.
None of these, except the Transform, is mandatory. An object could choose to have it or not.
Directional lights are now multiple like point and spot lights, while before I could only have one.
In the picture there is an example of how the system is still working exacly like before.
I moved the boundaries of the physics to match the walls positions.
Hopefully the next screen of the engine will be exactly identical, but with real collisions with AABBs (Axis aligned bounding boxes).
The RigidBody class will be a component of the GameObject as well. If missing, the object will not interact with the physics simulation.


domenica 20 settembre 2015

Day 74: Installer

Today I studied physics simulations because I need to better understand what I'm going to do, so I didn't actually wrote any code.
However I downloaded a plugin for Visual Studio called Visual Studio Installer, and with it I managed to create a working installer for the engine, because right now it was working only inside visual studio.
It was a bit problematic due to absolute and relative paths problems, but in the end I made it work.

giovedì 17 settembre 2015

Day 73: The limits of physics simulations

Today I experienced the hard way a problem about physics in a discrete time context.

Tweaking a few values of the drag formula I noticed that with certain values the ball was behaving unexpectedly. With other values its position was rapidly growing to infinite.
After quite a lot of time trying to understand what was wrong, I realized it was not fault of the formula, but of the fact that physics is processed only 60 times for second.

Let's say that a ball is travelling very fast inside water. The water applies a resistance force which is very high at the beginning, and gets softer with the ball losing speed.
If this happens in less than a frame, the force is calculated at the beginning, and it will be so high, that it will actually invert the speed of the ball, which is not the desired effect.
The force will be calculated again the next frame, but the damage will already be done.
The values of the speed were something like this (in m/s):

20 → -30 → 90 → -900 → 500000 → - INF → INF

These values shows that the drag force is so intense that it will actually invert the speed, and make it even more intense. This generates a sort of pong effect, and v will tend to infinite.
Thanks to these numbers I realized the problem, and actually there is not a real solution, except to avoid using "risky" values, or bring to 120 the fps of the physics simulation.
These methods don't solve the problem, but makes it less easy to happen.

Since I was stuck on this problem for quite some time, I just added a few things to the engine: lateral bouncing and a debug tail that changes color depending on how much time before the object passed from that point (as can be seen in the picture).


mercoledì 16 settembre 2015

Day 72: Weight and Drag forces

Today I started working on physics.
This seems to be a very hard thing to implement efficiently, and I don't know if I will ever attempt to implement complex physics and collisions with irregular objects, so for now I'll start to implement the easier things, and gradually add new features.

Today I defined two classes, a WeightForce and a DragForce class.
These holds the important data to calculate the correspondent force (for example in WeightForce is stored a 3d acceleration and the mass of the object).
With these two classes I managed to implement a simple gravity system that uses a gravity weight force and an air drag force.

I also added a very useful debug tool: every 5 frames a red low-poly sphere is instanced in the position of the object.
This allows to follow the path of the object in a nice visual way (as you can see in the image).

Finally I added a few commands to the shell to make physics debugging easier: a pause method that leave the camera active, the automatic pause when shell is active, the command "\r" to restart the simulation, and so on.

lunedì 14 settembre 2015

Day 71: Reorganization

Today I finally decided to divide the headers, the souce files and the shaders in subfolders, because of their growing number.
Now everything is more organized, and in the process I also removed a couple of old classes I forgot to delete weeks ago because I didn't see them in the general disorder.

domenica 13 settembre 2015

Day 70: Improvements to Shell and Log

Today I finished to fix a few bugs I had in the Log class.
Then I added a lot of commands to the shell, and they also helped me to add a few features to the engine.
For example I decided to make a slow motion command. So I added to the TimeManager a delta_time and a slow_motion_factor.
By tweaking the second value it is possible to make the game slower or faster, and I used the delta time to make movements fps-independent (which I had forgotten till today).
I also added a pause command to freeze everything except the shell, I added commands to handle music and sound effects and a few other stuff.

I also found a bad bug in  light directions:
I was using a lookat view matrix with vec3(0,1,0) as the up vector. For most situation this was fine, but I noticed that when lights were pointing upwards or downwards, the shadows were disappearing.
This is because having a forward and up vector in the same direction was generating some bad math error. So I replaced it with one of the vectors perpendicular to the forward one, and everything was solved.
The shell proved to be extremely useful to debug this problem, I was able to remove other lights, check immediatly if the shadows were properly activated and so on.


sabato 12 settembre 2015

Day 69: Log console

Today I added a few commands to the shell, then I proceeded to implement a Log console, which is basically an output console on top of the shell.
I managed to make everything work, and I can also scroll up and down to see older output messages, and so on.
It is not perfect yet, but it does the job.
The shell can control the log as well, for example by changing it color, and with the tab key it is possible to enable or disable them.
In the picture I redirected the fps output I was printing on the windows prompt directly to the Log console, and it works perfectly.
Tomorrow I'll probably try to solve the little problems I have left behind.


venerdì 11 settembre 2015

Day 68: Control rendering with the shell

Today I added lots of commands to enable/disable the different rendering steps.
This was easy for the most part, but a few steps were actually not indepent.
For example I couldn't disable the shadows, because in the light pass the shadow information is read and processed. So I needed to do a few adjustments, for examples I added an uniform to the light shaders to disable shadow processing.
Another example of a problematic command was the disabling of HUD, because the shell is actually part of the gui.

In the picture are show a few commands to disable, in this order, hud sprites (but not texts), directional shadows, spot lights and skybox.
Using \x instead of \nox enables the rendering steps back again.

Probably the next thing I'm gonna do is an output shell, on top of the input shell.
This will be useful to output messages directly there instead of the windows terminal.
I will also probably add a function to pause the game (except the shell).


giovedì 10 settembre 2015

Day 67: Shell

Today I implemented a working shell to input commands to the game.
It was surprisingly easy, free of errors and bugs, and a very satisfying job.

First I managed to create the background of the shell, then I added 15 lines of text on it, and I spent a few hours adding multiple features:

- Reading text instead of button signals thanks to a SDL 2.0 feature
- Tab to show/hide the shell
- Enter to scroll the lines like in a standard bash
- Read commands when '\' is read, and stop reading when ' ' is read.
- Read parameters after a command, it works for both string and int parameters
- Different error messages (if argument is missing or is different, the message is not the same)
- Multiple commands on the same line

Except the last point which was a bit tricky, everything went pretty smootly and I don't think there are bugs until now.

In the picture there are a few examples of commands I implemented:

-\hide: same thing as the tab key, really not that useful
-\shellcolor: changes the color of the shell text, accept 3 ints
-\echo: output the string argument as is

In the next days I'll add other features, and add commands to actually control the game.



mercoledì 9 settembre 2015

Day 66: Fonts

Today I finally made fonts work, and all the problems were due to bad conversions between different units of measure.
In the end I managed to make them work, but  I was not satisfied, I wanted to make them easy to adapt to the screen.
So I added an anchor system like the one for sprites, and I also made so that the text is correctly aligned to the border it is anchored to...much like the "align text" in Word.
I also added a new parameter called Depth to both the sprites and the text. It allows to decide in which "depth plane" the image will be, so that it is possible to decide what will be rendered in front of the other stuff.
It supports alpha, but only 0% or 100% alpha, which means that 10 overlapping sprites with 10% alpha and different colors will NOT blend as expected, but a text in front of a sprite, or vice versa, will be nicely blend.

Edit:
In the evening I managed to precalculate and preallocate all the memory used by the text glyphs, so now it avoids multiple allocations.
Faster and does not require to free memory, which is always good, it just needs to resize the memory every frame.


martedì 8 settembre 2015

Day 65: Fonts and problems

Today I spent a lot of times trying to read .ttf fonts and use them.
The idea is read them inside a opengl texture, then draw them by sampling the correct uv-range from the texture.
I've had a lot of problems, and I wasn't able to finish the work, I'll continue tomorrow.

lunedì 7 settembre 2015

Day 64: Perfected GUI

Today was another very positive day, and I made a lot of improvements to the engine.

I started by refactoring the the PointLight, DirectionalLight, PointLight, GameObject and Sprite.
They all had in common the lack of a global list to track their presence.
After the refactoring you can just create an object, and the engine will know it's there and will be able to render it and so on.

I also moved the batches logic to the deferred renderer class, so that now in the main game class everything is clean and details independent.

After that I proceeded to improve the GUI I've written yesterday.

First I've written an anchoring system, which is something that is often missing in game engines and I find very useful.
As you can see from the image, I just placed 4 sprites at the coordinates (0,0), (0,1), (1,0) and (1,1), and by changing the anchoring point they are easily placed inside the screen.

Then I solved the ratio problem by dividing ratio and size.
The sprite has a default ratio (obtained from the image itself), and setting the size to, for example, (100,100), will make the image 100 times bigger, but with respect for the original ratio.
It is possible to set the ration to 1, and the image will be exactly 100x100


domenica 6 settembre 2015

Day 63: GUI

Today I've written an enormous amount of code, mainly because somehow I didn't stumble in any stupid problem.
I started by creating a Sprite class, with the correct info to handle a 2D image.
Then I wrote a 2D batch to optimize the drawing of sprites (like I did for 3D stuff).
After that I proceeded to write a couple of shaders to render the 2D image on screen, and I added a method to my deferred rendered to draw with those shaders everything inside the batch.
I had a few troubles in blending the HUD on top of the 3D scene because of a pretty bad bug I never found till today, and I fixed that as well.
Once I got that working I needed to tweak a few parameters, implement the system to generate a 2D model matrix, fix a few other bugs, replaced the PNGLoading library, and now the system is working.
The coordinate system is quite good, but the scaling system is not, tomorrow I'll make it ratio-independent.
I also need to add an automatic system to add automatically to the batches the objects in the scene. Right now it is manually done, and it feels very unnecessary.
I'll probably refactor that as well.


sabato 5 settembre 2015

Day 62: 3D graphic recap

Today I will officially stop to work on 3D graphic, for the moment at least .
I'll soon start to implement the (2D) GUI of the engine, because I decided I want to be able to draw a HUD, write output on screen, maybe even implement a custom console.
Before that I wanted to give a proper conclusion to the work I've done till today, so I built a little, nice environnement to replace the random stuff I had on screen.
It was useful to test again the lights and of course I want something nice rendered on screen if I'm not gonna change it for quite some time.
I also added copy constructor for lights in the process

Since this is the end of this part of the engine, I'll recap the main features I implemented, which are visible in the image for the most part:

*At the four corners there are 4 point lights, and each one of them has a diffuse component, and a very high specular component. They also cast shadows.

*The four spheres around the lights are flat color (non lit) and they don't influence shadow casting. It needed a few extra work, but it allowed me to create bulb lights

*At the top there is a spotlight, with the same properties of the point ligths (shadows, specular and diffuse color etc)

*On top there is a sphere that casts the directional light shadow

*In the background there is the skybox

*Everything is based on deferred rendering, which is nice for performances but made everything a little more difficult, and prevented me from using transparency and anti-aliasing, which I would really like to have.




venerdì 4 settembre 2015

Day 61: Problems with buttons mapping

Today I had little times, I just tried a few things and I noticed a problem with the button mapping of the controller...but I think the problem is SDL.
The keys are correctly read by windows, and the joystick is correctly read by games and stuff, but in SDL the enum values for each button are somehow swapped...if that is the prblem there is little I can do, I have to remap manually each SDL code to its true value...very, very annoying

giovedì 3 settembre 2015

Day 60: Copy constructors

Today I wanted to build something with the engine, like a little house, just to show the potentiality of the system...the big problem I faced, is that for each object I needed to set everything up from scratch. For every block on screen i had to write a lot of code, and the only difference was the position ad maybe the size...so I decided to allow the engine to copy objects, so that  i can make a copy and modify just the different parts.
It required the use of copy constructors, which do this process allowing to also duplicate the eventual pointed values inside the copied object.
The system is fine, and i can copy model and game objects. I think i'll extend it to light also, and maybe I'll write a common interface called iCopyable, but there are a few tricky things to handle, so I'll leave it for last.
In the picture I just imported an horrible model to test everything on a more complex environnement, and indeed the shadows were a little messy and i needed to change a few settings of the bias.


mercoledì 2 settembre 2015

Day 59: Game Controller

Today I decided to configure the engine to work with a game controller.
Thankfully my ps4 controller is very easy to configure on a PC compared to the old ps3 dualshock, so I started very easily.
I had to configure SDL to read data from the controller, and then I needed to manually program a lot of things: button mapping, dead zones of the analogs, mapping from analog valus to the range [-1;1] and so on.
In the end I managed to give to the controller all the feature already used by the mouse: control the camera over the screen with rotations and movement, issue commands with buttons and so on.
I had litterally no problems today, everything went smooth and the system is perfect for now.
I will probably add in the future a few features, like a buffer to stabilize the joystick movement (sampling the last three values to avoid imprecise movements), but for now i'm happy with it.

martedì 1 settembre 2015

Day 58: Huge refactoring

Today I made a substanctial refactoring.
I started by moving the MainGame class to the game, and I left to it just the base stuff a game programmer should implement, moving the rest to the super class.

I also moved all the glsl program initialization to the deferred renderer, because unitl now it was handled by lights, main game and deferred renderer, making the situation pretty messy.
Everything seems to work exactly like before.
Probably tomorrow or in the next days I'll add a few classes to the Game project and make something with the engine, just for fun and to test that everything is fine.

lunedì 31 agosto 2015

Day 56 & 57: Bugs and faulty drivers

In these two days I noticed a bad bug in the spot lights bounding box.

While I was trying to fix it, I updated the nVidia drivers, and everything stopped working. It was partially fault of the drivers, but this also allowed me to find a bad bug in the spot lights.

Today I also fixed the rotation bug,which was due to a bad usage of pitch and yaw, and now everything should be fine. In the next days I'll continue to refactor the game and the engine both.

sabato 29 agosto 2015

Day 55: Engine and Game

Today I spent a lot of time on a substanctial refactoring.
Now, instead of a single project, I have a RynoEngine library project, and a Game project that uses its functionalities.
I lost a lot of time on a problem with the lights, and it turned out it was just a driver problem.

Then I tested a bit the engine and  I noticed there is a pretty bad bug on the rotation of the lights, but I'm not seeing a way to fix it for now.

mercoledì 26 agosto 2015

Day 54: No more Lights

Today I finally finished the lighting system.

I Found out that the bug I had yesterday was due to the stencil buffer. I wasn't able to solve it, and so, since I read online that very often it actually makes performances worse, I remove it for good.

Then I implemented the bounding boxes for spot lights. They rotate and they grow in width depending on the cutoff value. In the picture there is an example of a bounding box perfectly aligned with its light. This allows to draw way less pixels for each spot light.

With this, I declared finished all my work on lights.


martedì 25 agosto 2015

Day 53: Rotations

Today I started by trying to change the bounding box of the spotlighs to a rotating pyramid.
Sadly I noticed a bug I have somewhere: the bounding boxes are rendered with missing faces, like a culling problem or a depth problem, or a model loading problem.
This happens only to models without uvs (which are the ones I use for boxing purposes).
For sphere boxes this leads to no problem, because the faces are so many that everything is covered by the model anyway, but for a cube or a cone, I get whole areas of light cut off.
I'll try to fix it tomorrow and finally finish this lighting stuff.

This evening I decided that it's very bad to declare light directions via a vector, so I left to the user the possibility to pass pitch and yaw in degrees, and then I convert them internally to a vec3 representing the direction.

In the picture I placed the three different lights supported by the engine. From left to right: point, directional and point light shadows.
Tomorrow I'll try to fix the problem, and implement the rotating bounding box, after that, no more lighting.


lunedì 24 agosto 2015

Day 52: Spot lights

Today I wrote a lot of stuff.

I started by creating everything needed for the spot lights, by duplicating the point light classes (and shaders) already there.

In the meanwhile I also refactored a bit the Point light and Directional light classes.

Then I implemented all the different things that are different in spot lights compared to the other kinds of lights.

The main problem I had (and actually still have) is how to set the field of view of the spot light...apparently it is not the angle,but  the arccos of the angle, for reasons that are still unknown to me...So in the end I used this method, but, with very narrow fileds (close to 0), the arccos tends to infinite, so i manually set a value of the fov for these values, because the resulting shadows were messy...
Oh and I cannot use field higher then 90 degrees, but 90 is quite a lot anywhay for spot lights.
I don't know if there are better solutions, but now everything works fine, and I don't want to lose my sleep over it.

One last thing to do, not even really necessary, is to change the bounding box of the spot lights.
Right now they uses the same spherical box of the point_lights, but with this method a lot of space inside the sphere is rendered for no reason.
I should use a parallelepiped / cone and rotate it in the direction pointed by the light.


domenica 23 agosto 2015

Day 51: Nothing special

I had really little time today, so I just set up a few things to start working on spot ligths.

sabato 22 agosto 2015

Day 50: Geometry shader

Today I decided to do one last thing on my point shadows.
I read  online that, instead of rendering 6 times to the six faces, you can just render the scene one time, and then use a geometry shader to render the 6 images to the 6 correct faces of the cube.

I guess this is quite faster, because you don't need to bind/unbind 6 textures from the depth_attachment, but the main reason why i liked the idea, is because i never used geometry shaders, and it was time to learn.

Everything went pretty smoothly, no problems at all!

Then I refactored the shader class to handles geometry shaders more nicely, and realized I could just remove all the .meta files I had till today, and all the "binding attribute" step, which is another nice polish of the engine.

So, actually nothing new, but a very positive day. In the picture i just toyed around a little with the shadows.


venerdì 21 agosto 2015

Day 49: Cubemap shadows in depth buffer

Today I decided to move the cubemap for the shadows from the color buffer to the depth buffer.

That's because you don't really need 32 bits for storing the depth, and only the depth buffer allows you to have 16 bit values.

To do so I had to tweak a few things, for example I needed to remap the distance between fragment and light to the interval [0;1], because the depth buffer can only accept those buffers.

In the end everything was unexpectedly working in less then an hour, which is a relief after the last week. Now I'll stop working on point light shadows, and probably I will add spotlights (with the relative shadows), and then stop working on graphic stuff for a while, and move to other aspects of the engine.

In the picture I have 9 dynamic lights (10 with the directional light) casting lots of shadows from 121 parallelepipeds. It runs at 50 fps, which is quite good on my card I guess, considering that each light requires 6 renderings.
I doesn't surprise me that even in modern games there are just a few lights on screen in the same moment, and not all of them are shadow casting.


giovedì 20 agosto 2015

Day 48: 3D shadows: It's finally over

After a terribly frustrating week I finally found the bug:

An angle in degrees instead of radiants...

That happens, and of course I immediatly tought of that, one week ago, but the documentation of the function was wrong, and asked for a DEGREE angle...

Well, I'm still angry with that, but now everything is fine, and in the picture you can see five lights and the five shadows casted by the lit surfaces.


mercoledì 19 agosto 2015

Day 47: Problems with shadow maps

I'm stuck again, this time trying to use the values in the cubemap to render the shadows.

I can read the cubemap, and display some oddly shaped shadows, so the problem lies somewhere in the shader, I cannot see where yet.

martedì 18 agosto 2015

Day 46: Writing to cubemap

Finally, after a few painful days, I managed to proceed with the multipass shadows.
The main problem was that i was using a cubemap too large, and so a black screen was rendered. This made me lose two days of work, it was really frustrating.

After that I spent quite some time to render exactly what i wanted, but now everything is fine.

In the picture on the left there is the usual rendering (horribly modified because I was using colors to debug the scene), and on the right there are 6 little images:

the top two are back and front X faces, the middle ones back and front Y and the bottom one back and front Z (referred to a point light I placed on the scene).

The next step will be to sample this cubemap inside my point light shader, which will be similar to what I already do with the directional shader (for the most part).


domenica 16 agosto 2015

Day 44, 45: Cubemap shadow nightmare

I'm having a really hard time with the shadow maps for point lights.
I wrote the code for it, but somehow it does not render anything, I really have no clue how to proceed.
I have in my mind pretty clearly how the process work, i guess there is some OpenGl error that i'm not seeing which is dragging everything down...
Tomorrow I'll probably continue to work on this, i hope things will be better

venerdì 14 agosto 2015

Day 43: Fix and refactoring

Today I finally managed to fix all those things that were annoying me, and while the engine does just a few new things since yesterday, it's been one of the most productive days I recently had.

First I decided to move the shadow rendering on a new FBO, and leave the deferred rendering on the other one. It's not clear if this is more convenient than using one buffer for everything, but anywhay, it's a nice, logical division.

Then I finally fixed the problem with the depth texture, and now the shadow map is saved in the depth buffer, and uses only 16 bits, cutting the bandwidth in half.

Then i noticed that the engine didn't support objects that doesn't cast shadows, and to do so i had to change from scratch the Batch3D.
Actually I divided it in two, one for geometry rendering, the other for shadow rendering, and both inherits from an abstract one. This will  probably be useful when i'll need to write a 2D batch to render a GUI.

In the picture you can se a big shadow-casting pillar, and a circle of non shadow-casting spheres (with point lights inside them).

giovedì 13 agosto 2015

Day 42: Problems

Before implementing the mutipass shadow maps for point lights, i wanted to fix an annoying problem i had with the shadow map.

Right now the shadow map is stored inside a color channel, which is more expensive than the depth buffer, soo i tried everything to use it instead, but it just won't work...

Tomorrow i'll create a new framebuffer from scratch and use it for shadow rendering, maybe with its depth buffer i'll manage to make it work

mercoledì 12 agosto 2015

Day 41: CPU Profiler

It's been two weeks since my last post because I went to holiday and the update to windows 10 destroyed my pc. Now everything is fine, and I set up the visual studio enironemment from scratch, adding a useful plugin to integrate SVN into the ide.

I noticed that the game is pretty slow to start, something around 3 seconds, so i wrote a CPU profiler to identify the bottleneck. (i also tried the GPU profiler i already wrote, but i found out, not surprisingly, that the times are not correct for CPU).

It came out that mesh loading is a very fast operation, while texture loading takes up a whole second. But the real problem is the cubemap, because of it's high resolution, which takes 2 seconds to load.

For now I'm gonna ignore these problems, probably with uncompressed formats the loading time would be faster, but with a large memory use.

However the cpu profiler is pretty nice and will be very useful in the future.

In the next days (or weeks probably) I would like to implement spotlights, perspective shadow maps and volumetric shadows for the point lights, and then take a pause from the graphic stuff, and maybe work on something new, like a simple GUI or maybe some basic physics engine.