Monday, February 13, 2012

Virtual Texturing. Rage.

    Id Software and John Carmack have created a really new way in using unlimited textures in CG, but they hasted for year or two because current generation of graphics hardware have not enough on chip memory to make use VT approach well. Stop! Why we need lots of on chip video memory? The main idea of VT is to minimize requirements for video memory by providing ability to use a magnitude more textures than before. Lets try understand why it's so.
    In theory VT always consumes constant memory footprint, more over ideally when other sub-systems parameters like hard drive and memory latency and bandwidth will be very well, VT needs only additional texture with dimension equal to the back buffer size. But current (and future also) generation of hardware is not ideal and has limitations, so VT needs overcome them by using page (tile) of pixels instead of single pixel to minimize latency and using indirection table to access the right page. VT is very similar in base idea to the virtual memory system for operating systems. That all makes VT using much more bigger texture (even textures) which is usually 4-16 times bigger than the initial theoretical assumption.
    I'm lucky to have Nvidia 590 GTX graphics card (with 3Gb of video memory) on my work and as a real passion graphics programmer the first thing what I did was run Rage and change size of the page table from 4k to 16k. And guess what? the bothering texture popping has gone. Now I don't see any texture loading and switching between fallback texture to needed LOD at all. That is why I said that Carmack  hasted  for year or two. Currently 590 GTX is high-end graphics card with the price about 800$, but over the year it'll be usual middle-end video card.
     P.S. Anyone who is interesting in virtual texturing technique (theory and implementation) I'm very recommending this blog http://sandervanrossen.blogspot.com/

Friday, February 3, 2012

Grass coloring(tinting).

    Often in game engines is used an approach when grass type (geometry or texture type) is chosen based on the landscape type. For example on the road we don’t want any grass at all because they can’t grow there, but for meadow we want a lot of very dense grass. This can be achieved with grass masking, but often we need not only binary value about need we grass or not but some variations. Another example grass with different textures to make grass and landscape belong each other. For this case we also need grass masking texture with values which indicate the kind of grass. This technique is not a new and it has been widely used for a long time in industry, but often we can see intersection between grass geometry and landscape geometry (look at the images below) even when we implemented this technique. This may happen when grass masking texture is not big enough or when grass geometry is relatively big (for choosing flora type we use only central point of this geometry, but geometry may be big enough to overlap neighborhoods areas with different materials) or when we have landscape with very rapid environment type transition. This issue happens always but in one games this is not a big issue and in another may make the final picture unbalanced.
      
    Here I try to explain how we can achieve this picture with relatively small performance overhead.
    As always the main idea is very simple. To make grass and landscape belong each other what we need to do is tint grass with the landscape color in the bottom-up direction. There are different methods for doing this (I know at least three) but the common stuff in all of them is access a texture which represents a color of the ground under the grass. Means we have to prepare this specific texture before we start grass rendering.
Ok let’s imagine that we have this texture before grass drawing. What we need to do with it.
    Look at the image here on the left I drew typical flora geometry (a quad) which consist of two triangles (front view). Red points represent bottom vertices of the flora, blue points up vertices. On the right is flora geometry (side view) with the different slope against the landscape. For each vertex of the grass geometry we need to add an additional attribute with represents tint position (in object space) and the blend factor for doing right tinting (in the simplest case for bottom vertices it will be 1.0f and for the up vertices 0.0f).
    Now I shortly explain each of these three techniques:
  •  For each grass chunk you have to find landscape textures under it. If you landscape uses blend textures for correct blending different layer’s textures you have to do the same calculation of the final color in the grass pixels shader. Yes, this may be expensive task. So think twice before doing it.
  •  Render landscape and all needed for grass coloring stuff into the texture with camera looking top-down and with orthogonal projection. Then use this texture in the grass pixel shader. This may me less expensive on the CPU side, but may introduce some artifacts. (of course it very depends on the engine capabilities)
  •  Do grass rendering as the last part of the rendering. Make copy of the already filled back-buffer. Then use this back-buffer copy as a texture for coloring in the grass pixel shader.
    I prefer the third method because of its simplicity and efficiency on both CPU and GPU sides. In the vertex shader we calculate clips space position of the tint position and in the pixels shader we just sample back buffer with these calculated coordinates then we blend grass color with this sampled color by the tint blend factor. It’s very simple and efficient. And we don't have any additional work on the CPU side except that we need to send into the pixel shader back-buffer copy.
    Someone may ask why not just blend grass color with the back-buffer color with standard hardware blending. The answer is simple because it’s not right if you will try to look through the flora you will notice that we blend bottom part of the grass with incorrect color because it may be located far away from the bottom part of the grass itself.

Friday, January 20, 2012

Sample Distribution Shadow Maps

Correct choosing space for doing calculation on the incoming data is very important thing. Sometimes it can give you significant performance increase or memory reduction gain. There a lot of different examples of these smartly selected spaces:
  •  Frustum culling may be performed in the clip space instead of the world space. This simple moving provides significant performance boost because we can minimize calculation operation count and reuse some extended instruction of CPU like SSE.
  •  Deferred shadows techniques allows save performance by not doing expensive filtering calculation on the long distance splits and at the same time allows save memory by doing the shadow resolving process consecutively for each individual split (reusing the same shadow map more times during a frame). This becomes available because we've moved calculation from the world space to the screen space.
  • Deferred shading and its different variations can also save a lot of performance by reduction overdraw effect to zero. Again this becomes available by moving from world space (or object space lighting calculation) to just screen space.
The list may be continued and I’m sure that you also can give some another examples.

Recently I’ve read paper about Sample Distribution Shadow Maps (SDSM) technique which tries to improve the shadow mapping quality. But it does that in very ingenious way. Authors of this technique use clip space of the light to select reuse useful area as much as possible. Their work based on the Cascaded Shadow Map (CSM) technique. But instead of manually selecting partition scheme for the camera frustum, like Parallel Split Shadow Mapping (PSSM) technique does, they use information about shadow sample distribution in the light clip space.
On the image you can see shadow sample distribution (orange) in light clips space and smart bounds(red, green, yellow, blue respectively) selection for each individual split.
 So by doing this they can greatly reduce AABB’s size of the needed for drawing into desired shadow map objects. This gives opportunity not only being rid of manually selecting split scheme parameters but significantly improve using of useful area of each individual shadow map and often even improve performance because AABB of visible object for drawing into  the shadow map is usually smaller. More over algorithm can skip occluded object from the drawing into the shadow map, because pixels in this shadow map are not needed during the shadow resolving process.

Of course there are some drawbacks:
  •  shadow edge shimmering because shadow’s volume changes every frame. But authors say that this is not a problem because with the tighter shadow volume and in fact with much more intelligent shadow space usage they can achieve almost sub-pixel quality along the whole view frustum.  
  •  Unfortunately this technique makes impossible using CPU frustum culling without overhead on the CPU <-> GPU sync. But I think with help of fully hardware frustum and occlusion culling (like this) it will be almost solved.

Tuesday, November 1, 2011

Software occlusion culling trip. Part I: Packing the luggage.

          Occlusion culling in computer graphics especially in games becomes more and more important in several last years because the complexity of virtual worlds grows very quickly. Often in games are used much more complex materials with very heavy shading cost. But traditional hardware occlusion culling (HOC) which uses the extremely efficient and scalable GPUs power often becomes a bottleneck in the current games because rendering itself uses a lot of GPU power and often GPU’s more utilized than CPU (especially multicore CPU) and any additional work on GPU, not directly related to the rendering itself, may cause relatively big drops in the frame rate. So developers have started finding some way how to use occlusion culling because it helps cull a lot of invisible objects from rendering without worrying about GPU overworking.There is some “solution” called software occlusion culling (SOC) with difference in which kind of processing power is used. SOC is very similar to HOC by principle, but SOC  uses CPU for making decision about is desired object visible or not. In age where CPUs continue increasing the core number it seems not so bad idea, because SOC itself is very suitable for parallelization and to utilize all the power of modern CPUs. To be precise SOC has several another drawbacks and it isn’t single solution for the occlusion culling. There are some techniques which precomputes static scene and then uses this precomputed data to quickly answer the question “Which objects are visible from current point of view?” But they work well only with almost the static (often indoor) environment and only with a very few number of dynamic objects in the scene. So if you want to have both the occlusion culling and the relatively dynamic (potentially destructible) environment SOC is the only one suitable approach.
 
            That theme has been always very interesting for me and during this cycle of posts I want to implement software occlusion culling step by step. I know that this technique is not novel and these are examples where this technique was successfully commercially implemented and works (Frostbite 2 engine), but I’m interesting in taking experience in many areas around this technique. What areas are related to the SOC: software rasterization, SIMD instructions optimizations, and multithreading support and of course C++.

            The first step on our trip will be understading how the OC (HOC in particular) algorithm works and why HOC becomes less suitable for the heavy GPU usage games. OC is a very good optimization for virtual worlds with heavy number of virtual objects and with the relatively small amount of the entire world visible at any given time from the current camera point of view. OC algorithm consists of two basic conceptions: occluder objects and occluded objects. Occluder objects are renderable objects which hide another object behind themself. Not all objects are good occluders. Good occluders are for example walls, big buildings and so on. In other worlds everything big enough that can hind a lot of another objects. Occluded objects are object which were occluded from rendering because they are located totally behind an occluder object. As we can see OC is not need to be performed with some kind of object rendering it may be even fully analytically, means be fully performed by some mathematical equation. For example PVS (Potentially Visible Set, it is one kind of the OC algorithms) uses analytical approach while HOC and SOC use so named numerical approach. Look at the image below to understand the roles of occluder objects (red color) and occluded objects (black color).  The green triangle is camera view frustum if we are looking along XOZ plane. As we can see occluder objects can significantly reduce visible objects count if OC is enabled.

            Now we will try to answer the question “Why does HOC become less suitable approach for heavy GPU usage games?” The answer is hidden in the basic principle how CPU and GPU work together. Most of the time they work independently and asynchronously. That means that CPU is just supplier of the work for the consumer GPU. During the rendering CPU just calls GAPI (Graphics API) function to do something, the graphic's card driver collects these commands in its internal command buffer and time to time flushes this command buffer to the GPU for execution. There is no implicit synchronization between CPU and GPU during the typical usage, even Present() GAPI function is also asynchronous, and it is an usual driver buffer command as many other. But there are some exceptions where synchronization is necessary. One of the cases when we try to retrieve data back from GPU or we ask GPU to return some query result synchronously.

            Let’s talk a little about query mechanism in modern GPUs. There are a lot of different queries, detailed description about most of them you can find in the official documentation DirectX or OpenGL standard paper. For HOC we are interesting in the one specific kind of the queries named occlusion query. What is it? Occlusion query helps us to answer the question “How many pixels of a rendered object were rendered” Before rendering some geometry we ask GAPI to get us occlusion query, then we render out geometry, and after that we ask GAPI to get us the result about how many pixels were rendered. Notice that third step, when we ask GAPI to return us the result, may be either synchronous or asynchronous. Often used synchronous or some kind of synchronous where the query is asynchronous itself but we ask GAPI about the result in the infinite loop. To understand why the synchronization CPU and GPU is really bad idea, when we retrieve results of an occlusion query let’s look at the image below. Here we illustrate driver command buffer, where green rectangles are usual GPU command like SetTexture, DrawPrimitive and so on, two red rectangles are respectively acquire an occlusion query and retrieve results for this query and the blue rectangle between two red rectangles is DrawPrimitive command for which we want to get the number of the rendered pixels.

As you can see on the image our CPU is slightly ahead over the GPU, means CPU has produced more operations then GPU can do right now, but CPU doesn't wait while GPU is executing these commands, it just continue to write command in the command buffer as usual and it even doesn’t guess that GPU currently is really busy and can’t perform all these commands immediately. But what happens when we acquire an occlusion query and are waiting for the results. We manually make CPU to wait until GPU hasn’t done its works. It means that now CPU waits GPU until the red vertical line. And if we have a lot of these queries, that may significantly drop overall performance.  Don’t forget also about an additional work for the GPU introduced by the drawing occluder geometry and tested geometry of the occluded objects.

Now we know the answers on both questions. Let’s think about how SOC can help us in that situation. In the last several years CPUs have increased their core number relatively quickly and now it’s typical that gamer’s PC has a CPU with 4 and more cores. Unfortunately PC game developers are not so much experienced in multicore programming as our colleagues from console world, where Xbox 360 and PS3 have 4-6 general use cell processors. On the PC a typical game engine uses only 2 threads (but there are some exceptions of course and often most advanced game studios try to implement much more advanced multithreading): the first one is the entry point of the game where the main command flow is executed and the second one is so named background tasks thread, usually for loading content in background to be sure that we don’t interrupt main thread and don't cause short-time fps drop . But CPU utilization is not uniform for these threads, while main thread utilizes almost 100% of one CPU core; second thread uses usually 20-40% of CPU core power. So typically we use only less than 70% power of the dual core processor, 35% for the quad core and only 15% for eight cores. That shows us that we have a lot of unused processing power which we can use to improve our game and make it even better. As I mentioned earlier SOC is very suitable for parallel processing, so we can relatively easily use this processing power to accelerate OC algorithm. More over as well as we will do occlusion culling fully on the CPU we have to not see any negative influence of CPU-GPU synchronization.

So let’s think about what we need to implement a fairly good SOC. We will do this step by step and will describe common principles. Well that is the list of steps to achieve our goal:
·         Simple software rasterization algorithm.
·         Simple single-threaded software occlusion culling algorithm.
·         SIMD optimization of software rasterization and culling algorithm.
·         Job system to effectively parallel SOC.
·         Some automated tool to generate occluder geometry from the rendering geometry without artist’s part.

That sounds not very hard but as always devil is in the details.

Antialiasing techniques. Part II: Image based antialiasing techniques.

        I’m too late with this part. I’ve even started writing it but was really busy at work and at my pet project. About a month ago I’ve found a really cool introduction to existing image based antialiasing techniques and a lot of papers. So I decided to not describe them here by myself and just post here links to these papers: http://iryoku.com/aacourse/