Project Rembrandt: Difference between revisions

Jump to navigation Jump to search
m
(Revert unreadable font)
m (→‎Status (07/2014): obsolete due to Compositor)
(82 intermediate revisions by 12 users not shown)
Line 1: Line 1:
{{WIP}}
== Why the name? ==
== Why this name ? ==
{{Wikipedia|Rembrandt}} was a dutch painter living in the 17th century, famous as one of the master of {{Wikipedia|chiaroscuro}}.
[http://en.wikipedia.org/wiki/Rembrandt Rembrandt] was a dutch painter living in the 17th century, famous as one of the master of [http://en.wikipedia.org/wiki/Chiaroscuro chiaroscuro].


This project is about changing the way [[FlightGear]] renders lights, [[shadows]] and shades, and aims at making Rembrandt painting style possible in FG.
This project is about changing the way [[FlightGear]] renders lights, [[shadows]] and shades, and aims at making Rembrandt painting style possible in FG.
{{forum|47|Effects & Shaders}}


== What is it ? ==
== What is it ? ==
{{FGCquote
  |Deferred {{=}} rendering a geometry pass into the geometry (g-)buffer which holds positions, normals, materials, then doing all operations (texel, light, ...) in fragment passes on that buffer (or any others).<br/>
<br/>
Forward {{=}} (usually) rendering part of the shading (typically ambient and diffuse light) per vertex, extrapolate all quantities  which are declared as varying across triangles and hand them via rasterizer to the fragment shader which does the rest
  |{{cite web |url=http://forum.flightgear.org/viewtopic.php?p=221222#p221222
    |title=<nowiki>Re: Orbital Makes the Sky Black</nowiki>
    |author=<nowiki>Thorsten</nowiki>
    |date=<nowiki>Sun Oct 19</nowiki>
  }}
}}
The idea driving the project is to implement [http://en.wikipedia.org/wiki/Deferred_shading deferred rendering] inside FlightGear.
The idea driving the project is to implement [http://en.wikipedia.org/wiki/Deferred_shading deferred rendering] inside FlightGear.
From the beginning FlightGear had a forward renderer that tries to render all properties of an object in one pass (shading, lighting, fog, ...), making it difficult to render more sophisticated shading  
From the beginning FlightGear had a forward renderer that tries to render all properties of an object in one pass (shading, lighting, fog, ...), making it difficult to render more sophisticated shading  
Line 23: Line 35:
:*<u>Ambient pass</u>: the diffuse buffer is modulated with the ambient color of the scene and is drawn as a screen-aligned textured quad
:*<u>Ambient pass</u>: the diffuse buffer is modulated with the ambient color of the scene and is drawn as a screen-aligned textured quad
:*<u>Sunlight pass</u>: a second screen aligned quad is drawn and a shader computes the view position of every pixel to compute its diffuse and specular color, using the normal stored in the first stage. The resulting color is blended with the previous pass. Shadows are computed here by comparing the position of the pixel with the position of the light occluder stored in the shadow map.
:*<u>Sunlight pass</u>: a second screen aligned quad is drawn and a shader computes the view position of every pixel to compute its diffuse and specular color, using the normal stored in the first stage. The resulting color is blended with the previous pass. Shadows are computed here by comparing the position of the pixel with the position of the light occluder stored in the shadow map.
:*<u>Fog pass</u>: a new screen aligned quad is draw and the position of the pixel is computed to evaluate the amount of fog the pixel has. The fog color is blended with the result of the previous stage.
:*<u>Additional light pass</u>: the scene graph will be traversed another time to display light volumes (cone or frusta for spot lights, sphere for omni-directional lights) and their shader will add the light contributed by the source only on pixels receiving light.
:*<u>Additional light pass</u>: the scene graph will be traversed another time to display light volumes (cone or frusta for spot lights, sphere for omni-directional lights) and their shader will add the light contributed by the source only on pixels receiving light.
:*<u>Fog pass</u>: a new screen aligned quad is draw and the position of the pixel is computed to evaluate the amount of fog the pixel has. The fog color is blended with the result of the previous stage.
:*<u>Transparent objects pass</u>: transparent objects (and clouds) are finally rendered using classical method.
:*<u>Transparent objects pass</u>: transparent objects (and clouds) are finally rendered using classical method.


Line 34: Line 46:
In FG, we end the rendering pipeline by displaying the [[Menubar|GUI]] and the [[HUD]].
In FG, we end the rendering pipeline by displaying the [[Menubar|GUI]] and the [[HUD]].


All these stages are more precisely described if this [http://bat710.univ-lyon1.fr/~jciehl/Public/educ/GAMA/2007/Deferred_Shading_Tutorial_SBGAMES2005.pdf tutorial] that is the basis of the current code, with some addition and modifications.
All these stages are more precisely described in this [http://bat710.univ-lyon1.fr/~jciehl/Public/educ/GAMA/2007/Deferred_Shading_Tutorial_SBGAMES2005.pdf tutorial] that is the basis of the current code, with some addition and modifications.
 
C++ developers interested in learning more about how Rembrandt works, will want to look at these initial $FG_SRC commits (note that the viewer related sources are now to be found in $FG_SRC/Viewer):
* 94e3ae4c675463c358071e1d9da8de583cf56e15
* 6b008126b5fd99c38778c6293c15f9721a4fa509
* 64e3e98069fb2310311687b9f099b338b8b375a5
* bb16463d631a8d87310a54a573966eb1cca813e6


== Caveats ==
== Caveats ==
Deferred rendering is not capable to display transparent. For the moment, clouds are renderer separately and should be lit and shaded by their own. Transparent surfaces are alpha-tested and not blended. They would have to be drawn in their own bin over the composited image.
Deferred rendering is not able to display transparency. For the moment, clouds are rendered separately and should be lit and shaded by their own. Transparent surfaces are alpha-tested and not blended. They would have to be drawn in their own bin over the composited image.


It also don't fit with depth partitioning because the depth buffer should be kept to retain the view space position, so for the moment, z-fighting is quite visible. Depth partitioning with non overlapping depth range might be the solution and should be experimented at one point.
It also doesn't fit with depth partitioning because the depth buffer should be kept to retain the view space position, so for the moment, z-fighting is quite visible. Depth partitioning with non overlapping depth range might be the solution and should be experimented at one point.


The glow pass can make certain MFD (that use emissive color) unreadable because blurred. Should be treated as transparent.
The glow pass can make certain MFDs (that use emissive color) unreadable because of blurring. Should be treated as transparent.


== Implementation ==
== Implementation ==
=== Repositories ===
=== Repositories ===
Initial source code and data are available in gitorious repositories :
The code is in the main branch of the [[FlightGear and Git|official repository]]. Any other location is not maintained anymore.
:https://gitorious.org/~fredb/fg/fredbs-simgear
:https://gitorious.org/~fredb/fg/fredbs-flightgear
:https://gitorious.org/~fredb/fg/fredbs-fgdata
The code and data are in <tt>project/rembrandt</tt> branches but are '''not updated anymore'''.
 
'''Work is now done in the main Flightgear repositories.'''
 
<span style="color:red;font-size:1.5em;font-weight:bold">The code is not yet optimized</span><br /> and may put the graphic card under pressure.


=== Rendering of transparent surfaces ===
=== Rendering of transparent surfaces ===
Line 69: Line 79:
If you are seeing error messages during startup or FlightGear doesn't start up properly, it's probably because you don't have enough free video memory. Reduce the size of the shadow map in preferences.xml by locating  
If you are seeing error messages during startup or FlightGear doesn't start up properly, it's probably because you don't have enough free video memory. Reduce the size of the shadow map in preferences.xml by locating  


<pre>
<syntaxhighlight lang="xml">
<map-size type="int">8192</map-size>
<map-size type="int">8192</map-size>
</pre>
</syntaxhighlight>


And put 4096 or 2048 instead.
And put 4096 or 2048 instead.
You can also use a startup parameter: --prop:/sim/rendering/shadows/map-size=2048
You can also use a startup parameter <code>--prop:/sim/rendering/shadows/map-size=2048</code>
 
=== Configurable pipeline ===
The Rembrandt renderer uses an XML file to setup its pipeline for each viewport described in the camera group. This file describes the way the intermediary buffers are setup and how the different rendering stages are sequenced. The general outline of a pipeline file is as follow :
 
<syntaxhighlight lang="xml">
<?xml version="1.0" encoding="utf-8"?>
<PropertyList>
<!-- BUFFERS -->
<buffer>
<!-- First buffer definition -->
</buffer>
<buffer>
<!-- nth buffer definition -->
</buffer>
<!-- STAGES -->
<stage>
<!-- First stage definition -->
</stage>
<stage>
<!-- nth stage definition -->
</stage>
</PropertyList>
</syntaxhighlight>
 
==== Buffers ====
A buffer is a texture used as a storage area in the GPU. It's size is usually a multiple of the screen size, but fixed size is supported (typical for shadow map). The description of a buffer is described below :
 
<syntaxhighlight lang="xml">
<buffer>
<name>buffer-name</name>
<internal-format>rgba8</internal-format> <!-- rgb8, rgba8, rgb16, rgba16, rg16, depth-component24, depth-component32 or OpenGL hex value -->
<source-format>rgba</source-format> <!-- rg, rgb, rgba, depth-component or OpenGL hex value -->
<source-type>unsigned-byte</source-type> <!-- unsigned-byte, unsigned-short, unsigned-int, float or OpenGL hex value -->
<width>screen</width> <!-- screen, value or <property>/a/width/property</property> -->
<height>screen</height> <!-- screen, value or <property>/a/height/property</property> -->
<scale-factor>1.0</scale-factor>
<wrap-mode>clamp-to-border</wrap-mode> <!-- clamp, clamp-to-border, clamp-to-edge, mirror, repeat or OpenGL hex value -->
<!-- optional, for shadow map -->
<shadow-comparison>true</shadow-comparison>
<!-- optional condition -->
<condition>
<!-- Valid boolean expression -->
</condition>
</buffer>
</syntaxhighlight>
 
==== Stages ====
A stage is an unit of rendering to a group of buffer. Most stages are predefined and their type is not free. When a type is not specified, the name is used. Stage types are :
{| class="wikitable"
!align="left"| Stage type
!align="left"| Purpose
|-
|geometry
|The geometry stage initialize most of the buffers and works on the real objects and geometry. Transparent objects are set aside and will be used untouched in the lighting stage. Other opaque geometry is rendered with the standard effects that do the hard work to put sensible data in the buffers.
|-
|shadow
|In this stage, the geometry is rendered in the normal map from the perspective of the sun.
|-
|lighting
|This stage uses the buffers filled by the previous stages to light every pixel of the scene. The result is rendered in another buffer to allow post effects.
|-
|fullscreen
|Stages of this type are used to alter the whole scene or transform data from a particular buffer.
|-
|display
|Final rendering of the scene to the screen or the texture defined in the camera group.
|}


=== Configurable pipeline ideas ===
A stage description is outlined below :
<syntaxhighlight lang="xml">
<stage>
<name>stage-name</name>
<type>stage-type</type> <!-- optional if name is one of the predefined type except fullscreen -->
<order-num>-1</order-num>
<effect>Effects/fullscreen-effect</effect> <!-- only if type == fullscreen -->
<needs-du-dv>true</needs-du-dv> <!-- only if type == fullscreen -->
<scale-factor>0.25</scale-factor> <!-- only if type == fullscreen -->
 
<!-- optional condition -->
<condition>
<!-- Valid boolean expression -->
</condition>
 
<attachment>
<!-- First attachment definition -->
</attachment>
<attachment>
<!-- Nth attachment definition -->
</attachment>
 
<!-- Passes only for the lighting stage -->
<pass>
<!-- First pass definition -->
</pass>
<pass>
<!-- Nth pass definition -->
</pass>
</stage>
</syntaxhighlight>
Stages render in buffers (except for the display stage). Attachments describe which buffers are affected by each stage.
 
===== Attachments =====
Attachment describe bindings between buffer and attachment point :
<syntaxhighlight lang="xml">
<attachment>
<component>color0</component> <!-- depth, stencil, packed-depth-stencil, color0, color1, color2 or color3 -->
<buffer>buffer-name</buffer>
<!-- optional condition -->
<condition>
<!-- Valid boolean expression -->
</condition>
</attachment>
</syntaxhighlight>
 
===== Passes =====
Passes are only available in the <tt>lighting</tt> stage. Three kind of stage are allowed :
 
{| class="wikitable"
!align="left"| Pass type
!align="left"| Purpose
|-
|sky-clouds
|Renders the skydome, sun, moon, planet, stars and clouds
|-
|lights
|Renders additional spot and point lights
|-
|fullscreen
|Fullscreen pass analog to a fullscreen stage except that it renders in the buffers attached to the lighting stage
|}
A pass is defined like below :
<syntaxhighlight lang="xml">
<pass>
<name>pass-name</name>
<type>pass-type</type> <!-- optional if name is one of the predefined type except fullscreen -->
<order-num>-1</order-num>
<effect>Effects/fullscreen-effect</effect> <!-- only if type == fullscreen -->
 
<!-- optional condition -->
<condition>
<!-- Valid boolean expression -->
</condition>
</pass>
</syntaxhighlight>
 
A typical lighting stage is a succession of 5 passes :
# <tt>sky-clouds</tt> pass
# <tt>fullscreen</tt> pass for ambient light
# <tt>fullscreen</tt> pass for sun light (and shadows)
# <tt>lights</tt> pass
# <tt>fullscreen</tt> pass for fog
 
Each effect attached to the fullscreen passes define the way blending is done between the pass and the previous accumulation of render.
 
 
=== C++ implementation ===
 
On the C++ side, Rembrandt is set up in those steps:
 
* ''buildRenderingPipeline()'' is the last common function between forward rendering and deferred rendering. That's the point of start for specific deferred stuff. In this function we call  ''buildDeferredPipeline()''
** ''buildDeferredPipeline()'' is just a wrapper for ''buildCameraFromRenderingPipeline()''
*** ''buildCameraFromRenderingPipeline()'' is where we initialize all buffers and create all the stages found in ''Effects/default-pipeline.xml'' with the call to ''buildBuffers()'' and ''buildStage()''
**** ''buildBuffers()'' is where we ask to build each buffer with the call to ''buildDeferredBuffer()''
***** ''buildDeferredBuffer()'' create a 2D texture
**** ''buildStage()'' is where we ask to build each camera depending on the type of the stage (geometry, lighting, shadow, fullscreen, display) with the call to ''buildDeferred*Camera()'' (where * is the stage type)
***** ''buildDeferred*Camera()''is where we build the camera, for each camera we attach the required buffers with the call to ''buildAttachments()''.
****** ''buildDeferredGeometryCamera()'' c.f [http://wiki.flightgear.org/Project_Rembrandt#What_is_it_.3F What is it ?]
****** ''buildDeferredShadowCamera()'' c.f [http://wiki.flightgear.org/Project_Rembrandt#What_is_it_.3F What is it ?]
****** ''buildDeferredLightingCamera()'' Only for the lighting camera (''buildDeferredLightingCamera()'') we have to build passes who is called with ''buildPass()'' c.f [http://wiki.flightgear.org/Project_Rembrandt#What_is_it_.3F What is it ?]
****** ''buildDeferredFullscreenCamera()'' c.f [http://wiki.flightgear.org/Project_Rembrandt#What_is_it_.3F What is it ?]
****** ''buildDeferredDisplayCamera()'' c.f [http://wiki.flightgear.org/Project_Rembrandt#What_is_it_.3F What is it ?]


== Running Flightgear with Rembrandt ==
== Running Flightgear with Rembrandt ==
[[File:Rembrandt dialog.png|thumb|270px|Rembrandt dialog]]
The Rembrandt renderer is now integrated in the main repository but needs to be enabled to run. There are two ways to enable it (only one is needed!):
* <code>--enable-rembrandt</code> (when using [[FGRun]], you may add this behind the <tt>FG_EXECUTABLE</tt> on the first page).
* <code>--prop:/sim/rendering/rembrandt/enabled=true</code> (with FGRun this can be added via <tt>Advanced > Properties</tt> on the last page, but only the <code>/sim/rendering/rembrandt/enabled=true</code> part).


The Rembrandt renderer is now integrated in the main repository but needs to be enabled to run. Use the <tt>--enable-rembrandt</tt> option to start Flightgear with this new renderer.
The <tt>View > Rendering Options > Rembrandt Options</tt> dialog allows you to toggle and adjust the various features that Rembrandt offers.


Rembrandt is quite demanding in GPU resources and may fail to run with the default options. The more frequent symptom is an OSG message in the console :
Rembrandt is quite demanding in GPU resources and may fail to run with the default options. The more frequent symptom is an OSG message in the console :
Line 87: Line 271:
  Warning: RenderStage::runCameraSetUp(State&) Pbuffer does not support multiple color outputs.
  Warning: RenderStage::runCameraSetUp(State&) Pbuffer does not support multiple color outputs.


Some card also exhibit messages like this :
The ssao effect provided in v2.8.0 may generate these messages, more often on Mac :


glLinkProgram "" FAILED
<pre>
Program "" infolog:
FRAGMENT glCompileShader "/Users/xxxx/Desktop/FlightGear.app/Contents/Resources/../Resources/data/Shaders/ssao.frag" FAILED
Fragment info
FRAGMENT Shader "/Users/xxxx/Desktop/FlightGear.app/Contents/Resources/../Resources/data/Shaders/ssao.frag" infolog:
-------------
ERROR: 0:20: 'array of 2-component vector of float' : constructor not supported for type
0(37) : error C6013: Only arrays of texcoords may be indexed in this profile, and only with a loop index variable
ERROR: 0:20: 'array of 2-component vector of float' : no matching overloaded function found
0(36) : error C6013: Only arrays of texcoords may be indexed in this profile, and only with a loop index variable
ERROR: 0:20: 'const 2-component vector of float' : cannot declare arrays of this type
0(35) : error C6013: Only arrays of texcoords may be indexed in this profile, and only with a loop index variable
ERROR: 0:20: 'v' : redefinition
0(34) : error C6013: Only arrays of texcoords may be indexed in this profile, and only with a loop index variable
ERROR: 0:55: 'reflect' : no matching overloaded function found
ERROR: 0:55: '=' :  cannot convert from 'float' to '2-component vector of float'
 
glLinkProgram "" FAILED
Program "" infolog:
ERROR: One or more attached shaders not successfully compiled
</pre>
In that case, disable ambient occlusion with the command :
<tt>--prop:/sim/rendering/rembrandt/ambient-occlusion-buffers=false</tt>


There is a number of additional options that can help to avoid these problems :
There is a number of additional options that can help to avoid these problems :


{| class="wikitable"
{| class="wikitable"
|<tt>--prop:/sim/rendering/use-color-for-depth=true</tt>
|<tt>--prop:/sim/rendering/rembrandt/use-color-for-depth=true</tt>
|Some old NVidia cards, such as 7600GT, don't give enough resolution for depth and that result in "fog curtains" at few meters from the viewer. One trick is to encode depth in another texture and get the proper value afterward. This option enables that.
|Some old NVidia cards, such as 7600GT, don't give enough resolution for depth and that result in "fog curtains" at few meters from the viewer. One trick is to encode depth in another texture and get the proper value afterward. This option enables that.
|-
|-
|<tt>--prop:/sim/rendering/shadows/enabled=false</tt>
|<tt>--prop:/sim/rendering/shadows/enabled=false</tt>
|Disable shadows altogether. This setting is changeable at runtime in the rendering option dialog.
|Disable shadows altogether.
|-
|-
|<tt>--prop:/sim/rendering/shadows/num-cascades=1</tt>
|<tt>--prop:/sim/rendering/shadows/num-cascades=1</tt>
|Avoid the "error C6013" message on old cards at the cost of resolution in the cockpit. Set <tt>/sim/rendering/shadows/cascade-far-m[0]</tt> to change the shadow map range. The more the range, the less the resolution (default value is 5 meters)
|Set <tt>/sim/rendering/shadows/cascade-far-m[0]</tt> to change the shadow map range. The more the range, the less the resolution (default value is 5 meters)
|-
|-
|<tt>--prop:/sim/rendering/shadows/map-size=<power-of-two></tt>
|<tt>--prop:/sim/rendering/shadows/map-size=<power-of-two></tt>
Line 120: Line 312:
|Set the shadow map cascade range for each cascade. Default values are 5m, 50m, 500m and 5000m for 4 cascades.
|Set the shadow map cascade range for each cascade. Default values are 5m, 50m, 500m and 5000m for 4 cascades.
|-
|-
|<del><tt>--prop:/sim/rendering/no-16bit-buffer=true</tt></del>
|<tt>--prop:/sim/rendering/rembrandt/no-16bit-buffer=false</tt>
|<del>Some earlier card don't support 16 bit 2-components textures (RG16 internal format), or as a framebuffer object attachment when mixed with 8bit 4-components buffers</del>
|By default, Rembrandt uses 8 bit buffers for normals (so the property is set to true by default). This may create banding artifacts on specular highlights. If it's unacceptable and the GPU supports it, set to false to have better precision for normals and effects relying on normal direction.
Rembrandt no longer use 16bit buffers. This may create banding effects on specular highlights at greater zoom ratio.
|}
|}


Line 144: Line 335:
|<tt>mat4</tt>
|<tt>mat4</tt>
|In fullscreen pass only, projection matrix inverse used to transform the screen position to view direction
|In fullscreen pass only, projection matrix inverse used to transform the screen position to view direction
|-
|<tt>fg_CameraPositionCart</tt>
|<tt>vec3</tt>
|Position of the camera in world space, expressed in cartesian coordinates
|-
|<tt>fg_CameraPositionGeod</tt>
|<tt>vec3</tt>
|Position of the camera in world space, expressed in geodesic coordinates (longitude in radians, latitude in radians, elevation in meters)
|-
|-
|<tt>fg_SunAmbientColor</tt>
|<tt>fg_SunAmbientColor</tt>
Line 235: Line 434:
For material shaders, it is necessary to provide both <tt>gbuffer-functions.frag</tt> and <tt>gbuffer-encode.frag</tt> in the effect file, like this :
For material shaders, it is necessary to provide both <tt>gbuffer-functions.frag</tt> and <tt>gbuffer-encode.frag</tt> in the effect file, like this :


<pre >
<syntaxhighlight lang="xml">
<program>
<program>
<vertex-shader>Shaders/ubershader.vert</vertex-shader>
<vertex-shader>Shaders/ubershader.vert</vertex-shader>
Line 242: Line 441:
<fragment-shader>Shaders/gbuffer-encode.frag</fragment-shader>
<fragment-shader>Shaders/gbuffer-encode.frag</fragment-shader>
</program>
</program>
</pre>
</syntaxhighlight>


For fullscreen passes shaders, only <tt>gbuffer-functions.frag</tt> should be provided, like this :
For fullscreen passes shaders, only <tt>gbuffer-functions.frag</tt> should be provided, like this :


<pre >
<syntaxhighlight lang="xml">
<program>
<program>
<vertex-shader>Shaders/sunlight.vert</vertex-shader>
<vertex-shader>Shaders/sunlight.vert</vertex-shader>
Line 252: Line 451:
<fragment-shader>Shaders/gbuffer-functions.frag</fragment-shader>
<fragment-shader>Shaders/gbuffer-functions.frag</fragment-shader>
</program>
</program>
</pre>
</syntaxhighlight>


In the main function of the shader, the functions referenced need to be declared first. With no #include files, the whole function prototype needs to be typed :
In the main function of the shader, the functions referenced need to be declared first. With no #include files, the whole function prototype needs to be typed :
<pre>
<syntaxhighlight lang="glsl">
void encode_gbuffer(vec3 normal, vec3 color, int mId, float specular, float shininess, float emission, float depth);
void encode_gbuffer(vec3 normal, vec3 color, int mId, float specular, float shininess, float emission, float depth);


Line 271: Line 470:
     encode_gbuffer(normal, color, mId, specular, shininess, emission, depth);
     encode_gbuffer(normal, color, mId, specular, shininess, emission, depth);
}
}
</pre>
</syntaxhighlight>


=== Geometry Stage ===
=== Geometry Stage ===
Line 346: Line 545:
* Rembrandt has strict needs with shaders => shaders need to be adjusted to comply with the new framework otherwise the view will be plain wrong
* Rembrandt has strict needs with shaders => shaders need to be adjusted to comply with the new framework otherwise the view will be plain wrong
* Rembrandt can't do transparent surfaces => transparent surface need to be properly registered to render them with the classical path
* Rembrandt can't do transparent surfaces => transparent surface need to be properly registered to render them with the classical path
Once your aircraft has been ported, please modify its wiki page and add this symbol to it:
[[File:Rembrandtready.png]].
For a list of converted aircraft, please see [http://forum.flightgear.org/viewtopic.php?f=4&t=17536#p166346].


=== Registering all translucent surfaces ===
=== Registering all translucent surfaces ===
Line 356: Line 560:
   <object-name>TheObject</object-name>
   <object-name>TheObject</object-name>
  </effect>
  </effect>
'''Beware: <Effect> only works on real objects, not on groups of objects or animations.'''


If opaque surface need to have special effect, for example to apply bump mapping, this effect should use the "RenderBin" bin, or the rendering hint set to "opaque", and the G-buffer needs to be initialized correctly in the Geometry stage.
If opaque surface need to have special effect, for example to apply bump mapping, this effect should use the "RenderBin" bin, or the rendering hint set to "opaque", and the G-buffer needs to be initialized correctly in the Geometry stage.
A surface that uses the [[ALS technical notes#ALS glass effect|ALS glass effect]] does not need to be separately registered for Rembrandt, this is done automatically.
=== Making sure that all geometry will cast shadow ===
To limit the amount of geometry rendered in the shadow map, and also to reduce artifacts (shadow acne), only faces not facing the sun are casting shadows. The test is made using the normal orientation. That means that double-sided polygons, or mesh that are not closed, will be transparent to light at certain sun angles. To avoid that, modelers can either :
* ensure that the object is always in the shadow of another objects,
* close their mesh, or,
* double polygons with the normal set to the opposite.


=== Adding lights to a model ===
=== Adding lights to a model ===
Line 372: Line 587:
{|cellpadding=10|
{|cellpadding=10|
|valign=top|
|valign=top|
<pre>
<syntaxhighlight lang="xml">
<animation>
<animation>
   <type>light</type>
   <type>light</type>
Line 428: Line 643:
   <far-m>39</far-m>
   <far-m>39</far-m>
  </animation>
  </animation>
</pre>
</syntaxhighlight>
|valign=top|
|valign=top|
{| class="wikitable" cellpadding="3"
{| class="wikitable" cellpadding="3"
Line 468: Line 683:
|-
|-
|<tt>attenuation</tt>
|<tt>attenuation</tt>
|Three element vector. <c> element is the constant factor, <l> element is the linear factor and <q> element is the quadratic factor.<br />
|Three element vector. <c> element is the constant factor, <l> element is the linear factor and &lt;q&gt; element is the quadratic factor.<br />
Attenuation of color at distance d is [[File:Spotlight_attenuation.png]]
Attenuation of color at distance d is [[File:Spotlight_attenuation.png]]
|-
|-
Line 488: Line 703:
{|cellpadding=10|
{|cellpadding=10|
|valign=top|
|valign=top|
<pre>
<syntaxhighlight lang="xml">
<animation>
<animation>
   <type>light</type>
   <type>light</type>
Line 537: Line 752:
   <far-m>39</far-m>
   <far-m>39</far-m>
  </animation>
  </animation>
</pre>
</syntaxhighlight>
|valign=top|
|valign=top|
{| class="wikitable" cellpadding="3"
{| class="wikitable" cellpadding="3"
Line 585: Line 800:
|}
|}


== Initial TODO List ==
==== Performance and compatibility considerations ====
Every light on screen is equivalent for the GPU of redrawing the light volume with a shader, without z buffer culling. So each light comes with a cost, that is small taken individually but noticeable when a lot of them are visible. That cost also increase with the size of the light volume.
 
Beside that, it is wise to allow a model to work with the classical renderer that know nothing about lights and would render light volumes like other geometry. So a good practice is to complement each light animation with a select animation checking :
*if Rembrandt is enabled
*if the user selected quality match with the purpose of the light
*if the light should be on or off according to the other parameters of the simulation (position of the sun, position of switch, presence of power, ...)
 
A quality property is created to reflect the user preferences about quality vs performance concerning lights, and a proper slider is added to the shader dialog.
[[File:Fgfs-shaders-with-light.jpg|thumb|Light quality slider]]
The propery to use is :
/sim/rendering/shaders/lights
The quality slider sets its range from 0 (no lights) to 4 (all lights on). Simple airport lamp post appears at 1. Few bridge lamps at 2, all simple bridge lamp at 3 and more involved one at 4.
 
Example:
<syntaxhighlight lang="xml">
<animation>
  <type>light</type>
  <light-type>spot</light-type>
  <name>LightSource</name>
  <object-name>LightVolume</object-name>
  ...
</animation>
 
<animation>
  <type>select</type>
  <!-- Select the named animation -->
  <object-name>LightSource</object-name>
  <condition>
      <and>
        <!-- Rembrandt enabled ? -->
        <property>/sim/rendering/rembrandt/enabled</property>
        <!-- Quality ok ? -->
        <greater-than>
            <property>/sim/rendering/shaders/lights</property>
            <value>3.0</value>
        </greater-than>
        <!-- Simulation conditions ? -->
        <greater-than>
            <property>/sim/time/sun-angle-rad</property>
            <value>1.57</value>
        </greater-than>
      </and>
  </condition>
</animation>
 
</syntaxhighlight>
 
=== Tutorials ===
[[User:F-JJTH|F-JJTH]] compiled his experience and the one acquired by the PAF team converting aircraft in {{fr}} [http://equipe-flightgear.forumactif.com/t1034-howto-adapter-un-appareil-pour-rembrandt this tutorial],
 
== TODO List ==
 
=== Mac Issues ===
More and more Apple/Mac users are reporting issues related to running Rembrandt [http://forum.flightgear.org/search.php?st=0&sk=t&sd=d&sr=posts&keywords=rembrandt+mac].
 
Looking at the Mac GPU specs, it isn't clear if the Mac/ATI hardware/driver is generally insufficient, it should seem possible to run a customized Rembrandt setup with acceptable frame rates at 15-35 fps (assuming everything else being disabled for starters).
 
GLSL compilers have varying quality and especially the Mac (ATI/AMD) GLSL compilers are known to have issues with more sophisticated/nested constructs, so that it may help to reduce complexity of GLSL statements by splitting them up, instead of using nested anonymous vectors or functions (fatal error C9999: Nested functions, aborting!) for example.
 
So, the specific issue on Mac is some shaders being miscompiled, so the frame-rates are particularly bad, since the driver is hitting (slow) error paths. Certainly some Rembrandt-related shades fail to compile, though whether or not these are optional or required ones, isn't clear (Fred?). Some users reported that the errors and problems after upgrading their OS from OsX, 10.6.8 to  OSX 10.8.2 (Mountain Lion) [http://forum.flightgear.org/viewtopic.php?f=47&t=19070&p=177106&hilit=rembrandt+mac#p177106] or OS Snow Leopard (10.6. to Mountain Lion (10.8.2), downloaded XQuartz 2.7.4 [http://forum.flightgear.org/viewtopic.php?f=21&t=19000&p=177570&hilit=rembrandt+mac#p176972].
 
The shader errors would suggest that certain GLSL constructs are not supported by the ATI/AMD glsl compiler - this seems to be a known issue: [https://groups.google.com/forum/?fromgroups=#!topic/comp.graphics.api.opengl/H_FLQCQE1i4] To address this, one would need to port the corresponding shaders - like just was done to get rid of the constructs that caused errors on old GeForce 7x generation hardware. It seems the hardware is not the problem, but the driver being way out of date. I find the fact that it's the Cg compiler and not a native glsl compiler that returns the errors very strange.
 
Another FG 2.10 user on MacPro 3.2 GHz Quad-Core Xeon, 8GB RAM, MacOS X 10.6.8. ATI Radeon HD 5870 (gl-vendor:ATI Technologies Inc., gl-version:2.1 ATI-1.6.36 gl-renderer:ATI Radeon HD 5870 OpenGL Engine, gl-shading-language-version:1.20) report said "Rembrandt is still unusable on my Mac. One frame every 4-5 seconds and it looks weird."[http://forum.flightgear.org/viewtopic.php?f=68&t=18839&p=175737&hilit=rembrandt+mac#p175684]
 
It's also worth noting that a number of FG 2.8 users reported that Rembrandt would still work for them using the 2.8 binary, unlike the 2.10 binary on Mac OSX version 10.7.5 on an iMac (AMD Radeon HD Graphics with 512MB) [http://forum.flightgear.org/viewtopic.php?f=21&t=19000&hilit=rembrandt+mac#p176460]. So the issue seems to occur largely in combination with older Mac OS versions and newer FG versions (>=2.8+) [http://forum.flightgear.org/viewtopic.php?f=4&t=19396&hilit=rembrandt+mac#p179456].
 
It appears it is the Rembrandt lighting causing issues while in non rembrandt mode with older Mac OS + FG 2.8 and better. On other OS setups, the rembrandt lighting gets ignored when rembrandt is turned off, but not in this case. Both lighting modes are present and creating the weird light cone effects [http://forum.flightgear.org/viewtopic.php?f=4&t=19396&hilit=rembrandt+mac&start=15#p179655].
 
If there are any console messages (like warnings or errors) shown, that would be helpful to know. A number of rembrandt related changes got fixed by Fred like this. Obviously, it is difficult for shader developers to troubleshoot shader related issues that they cannot reproduce with their own hardware.
 
Rembrandt is being largely developed by a single Windows/Nvidia-based developer, so it gets very little testing and debugging on different platforms, especially Mac/ATI (AMD) - so as a Mac user, your safest bet is probably providing lots of feedback via the forums (or preferably the issue tracker), FredB (the Rembrandt developer) is generally pretty responsive and appreciates all helpful feedback. Obviously, it helps being able to build from source, and being able to provide detailed troubleshooting reports.
 
These things are hard to debug/troubleshoot without having access to a corresponding system that exhibits the problem, which is why I suggested earlier to provide lots of Mac/Rembrandt-related feedback via the issue tracker, i.e. GLSL errors/warnings and anything else that could be useful.
 
If you have you ever tried to debug an issue that doesn't cause errors on your computer, you'll understand that it's damn difficult in the first place. Most developers don't own a Mac, and are not going to spend 1000$ or so just to have one more computer to test things on, and we don't know of anyone who buys computers for the whole purpose of testing FG on more platforms.
 
So as a rule we can try to pin down and solve such issues if, and only if, we get a decent bug report with tons of relevant background info and the possibility to ask follow-up questions. Remember, fixing such issues involves essentially working blind - it is trying to figure out why code that runs pefectly fine on your own computer might have issues on other computers and any traditional bug-hunting technique essentially fails.
 
Posting a screenshot of the issue is nice, but tells little more than that it exists. It's completely impossible to turn that into any action developer-side. The underlying shader code has probably a combined 1000 lines, any of which could be problematic.
 
Overall, the Rembrandt situation is most likely to improve the more feedback is provided by end users with different hardware/software configurations, Fred has fixed quite a number of shader related issues in the past, so it's largely a matter of time, and obviously the quality of feedback, provided by end-users like yourself.
 
And just in case: Note that GLSL shaders are not really compiled/built by developers (unlike the actual fgfs binary), but on an invididual basis by your GPU/graphics drivers, which happens transparently in the background, each time fgfs is started. Basically, a GLSL shader is a snippet of "source code" that is passed on to your GPU driver, which in turn compiles it down into hardware-specific instructions for your particular hardware.
 
From a troubleshooting perspective, it would be REALLY helpful if Mac users with the corresponding hardware and knowledge could come up with extremely downstripped test cases, that either show the problem, or which no longer show the problem as significantly. Disabling other shader-based features will definitely go a long way here, because many other GLSL features have not yet been explicitly ported to support Rembrandt.
In other words, you should preferably disable random building, advanced light scattern, advanced weather etc - and only really use the most basic settings to have an easily reproducable test case.
 
To get this started, you can customize the "zero eye candy" profile and enable Rembrandt using shader level 1: [[Howto:Debugging_FlightGear_Crashes#Minimal_Rembrandt_Startup_Profile]]
 
Some Mac folks have recently reported some success, it may be a good idea to search the forum for details, see for example:
 
* http://forum.flightgear.org/viewtopic.php?f=21&t=19000&p=177570&hilit=rembrandt+mac#p176972
 
{{cquote|I'm seeing regular crashes here from ALS and Rembrandt, but that's nothing new.<ref>{{cite web |url=http://www.mail-archive.com/flightgear-devel@lists.sourceforge.net/msg40024.html|title=<nowiki>Re: [Flightgear-devel] 2.10.1</nowiki>|author=Vivian Meazza|date=Fri, 03 May 2013 10:16:13 -0700}}</ref>|Vivian Meazza}}
 
{{cquote|With an AMD Radeon HD 5670 using free radeon driver I've never seen performance of more than 15fps with Rembrandt and if I turn shadow details up so they don't look crappy I get about 3-4fps.<ref>{{cite web |url=http://www.mail-archive.com/flightgear-devel@lists.sourceforge.net/msg40293.html|title=<nowiki>Re: [Flightgear-devel] reminder: entering feature freeze now</nowiki>|author=Stefan Seifert|date=Thu, 20 Jun 2013 10:10:56 -0700}}</ref>|Stefan Seifert}}
 
{{cquote|with a i3770K and a GTX670, I get some hit from ALS (10-30%) but Rembrandt instantly drops me to 20fps, and < 10fps I use an aircraft I actually want to fly (777 or Citation) and go to any major airport (EGKK, EHAM, EDDM, EDDF, EGLC, VHHH)
 
This is at 2560x1600, but on the 670 I would be highly surprised if I'm fill-rate limited, given that AA is off, and the general suboptimal size of our
primitive batches.
 
Emilian has explained on IRC this might be due to the out-of-the-box / default config for Rembrandt being highly suboptimal, which I didn't yet evaluate, I would be delighted to have it more usable.<ref>{{cite web |url=http://www.mail-archive.com/flightgear-devel@lists.sourceforge.net/msg40298.html|title=<nowiki>Re: [Flightgear-devel] reminder: entering feature freeze now</nowiki>|author=James Turner|date=Thu, 20 Jun 2013 13:29:47 -0700}}</ref>|James Turner}}
 
{{cquote|The Apple OpenGL renderer is a rather interesting beast - it's a clean-room front-end to the drivers, one of aspect of which means it is the only true 'Core Profile' 3.x renderer in wide use. (As opposed to the Ati and Nvidia Core profile drivers, which are simple the compat ones with some checks removed, I have been told). Of course FG is hence limited to 2.1 on Mac since we're a long way from Core profile support in the main code.
 
This does however mean it produces different GLSL compile issues, and different bugs in general, from the same hardware on other platforms.
 
(The renderer backend does of course come from the vendors, but OpenGL.framework always comes from Apple - it's not like Linux where your
libGL.so comes, at least potentially, from your hardware vendor)<ref>{{cite web |url=http://www.mail-archive.com/flightgear-devel@lists.sourceforge.net/msg40083.html|title=<nowiki>Re: [Flightgear-devel] Shader compile failure</nowiki>|author=James Turner|date=Sat, 11 May 2013 06:53:32 -0700}}</ref>|James Turner}}
 
{{cquote|concerning the larger issue of different rendering pipelines / approaches, my opinion is, and remains, that the long-term solution is separate viewer codebases - while a plethora would be bad, we would already benefit from a 'fixed-function, no shaders' renderer codebase distinct from a Rembrandt renderer and modern, forward-rendering OpenGL 3.x pipeline. This needs the viewer to be cleanly split out from the simulation backend, via HLA, which is exactly what Mathias (and soon, myself) are working towards, but slowly.<ref>{{cite web |url=http://www.mail-archive.com/flightgear-devel@lists.sourceforge.net/msg39922.html|title=<nowiki>Re: [Flightgear-devel] Atmospheric Light Scattering</nowiki>|author=James Turner|date=Thu, 25 Apr 2013 08:09:08 -0700}}</ref>|James Turner}}
 
{{cquote|Like you and Thorsten, I see a very significant drop (50%) in frame-rate with Rembrandt, even without most the nice features such as shadows which has put me off using it.  I had thought it was just because my box is now underpowered (the march of technology....) but it sounds like other are
seeing similar issues and it would be worth some further investigation.<ref>{{cite web |url=http://www.mail-archive.com/flightgear-devel@lists.sourceforge.net/msg40304.html|title=<nowiki>Re: [Flightgear-devel] reminder: entering feature freeze now</nowiki>|author=Stuart Buchanan|date=Fri, 21 Jun 2013 01:40:15 -0700}}</ref>|Stuart Buchanan}}
 
=== Completed tasks ===
*Fix shadow rendering when using multi threading in OSG
*Fix shadow rendering when using multi threading in OSG
*<del>Implement Cascaded Shadow Map (need to be optimized - frustum calculation and night</del>)
*Implement Cascaded Shadow Map (need to be optimized - frustum calculation and night)
*Honor <noshadow> animation directive
*Honor 'noshadow' animation (done)
*See what happens with glow in fog
*See what happens with glow in fog : unknown landclass creates white patches in the emission buffer - scenery generation problem
*Test multi-screen
*Test multi-screen (mostly done)
*Restore splashscreen
*Restore splashscreen
*<del>Draw transparent objects with forward rendering (may need to capture the transparent bin from the geometry stage and move it in the display stage)</del> (OK - needs model contribution)
*Draw transparent objects with forward rendering (may need to capture the transparent bin from the geometry stage and move it in the display stage) (OK - needs model contribution)
*<del>Add spotlights as animations (nearly finished)</del>
*Add spotlights as animations (nearly finished)
*<del>find a solution for ambient and emissive color of material (may need an additional buffer)</del>
*find a solution for ambient and emissive color of material (may need an additional buffer)
*implement strength of glow (in the emissive buffer alpha channel)
*Provide a shader for transparent objects that could render to the emissive buffer too (using MRT) not doable. Light pass can't use MRT
*Use stencil buffer to limit light range(no - done in light shader)
**needed for cockpit light to implement fake shadows and avoid lighting the runway from the cabin through the airframe
*Use effect system instead of hard-coded shaders
*Add new animation to link a light source to a model (need to provide point light animation duplicating spot light) (done)
*Tidy up the architecture (done)
*Global strength of glow or ambient occlusion via slider in rendering dialog
*Fix dim-factor in multiplayer mode (done)
*Design and implement a configurable pipeline (done)
*Document rendering pipeline configuration file format (done)
*Fix fog on clouds
 
=== Near term tasks ===
*Convert existing shaders to deferred rendering
*Avoid to redraw opaque objects in the light pass. Involve OSG node mask not properly initialized.
*take care of particles and precipitation
*Fix shadow matrices in multi-screen
*Fix Lights in multi screen (seems same problem than shadows. Forgot a 1/w factor ?)
*Implement lightfield shader
*Add some kind of fog to lights
*Restore depth partitioning using depth ranges
*Move effect of cloud coverage from water shader to sunlight shader
*Allow light masks using textures
*Use stencil double-sided operations to limit the depth of light volumes. Use depth clamp to ensure front faces are always rendered even if the camera is enclosed in the light volume.
 
=== Long term ideas (unsorted) ===
*Use a separate list of light volumes to avoid traversing the scenegraph again (with transparency problems). Find out how we can detect unloading of models.
*implement volumetric effects by extending lights to arbitrary shaders. Should enable to implement heat haze effect and real wake waves.
*implement strength of glow (in the emissive buffer alpha channel) - use a Poisson-disk distribution to implement variable size blur
**provide levels 0 to 5 - we are currently at level 5
**provide levels 0 to 5 - we are currently at level 5
**level 0 should be ok for MFDs that are currenly unreadable because blurred
**level 0 should be ok for MFDs that are currenly unreadable because blurred
*Provide a shader for transparent objects that could render to the emissive buffer too (using MRT)
*Modify shadows to allow multiple casters (limited list)
*<del>Use stencil buffer to limit light range</del>(no - done in light shader)
**needed for cockpit light to implement fake shadows and avoid lighting the runway from the cabin through the airframe
*Use effect system instead of hard-coded shaders (mostly done)
*Convert existing shaders to deferred rendering
**Modify shadows to allow multiple casters (limited list)
**Implement a priority list of light sources, based on priority and distance from the viewer
**Implement a priority list of light sources, based on priority and distance from the viewer
**<del>Add new animation to link a light source to a model</del> (need to provide point light animation duplicating spot light)
*Tidy up the architecture
*Restore depth partitioning using depth ranges
*Restore stereo and other options currently available in CameraGroup
*Restore stereo and other options currently available in CameraGroup
*Implement quality vs performance user control
*Implement quality vs performance user control
== "Merge in next" TODO List ==
*Design and implement a configurable pipeline
*Implement lightfield shader


== Gallery ==
== Gallery ==
{{#ev:youtube|PXHhtQb5yzc}} {{#ev:youtube|peEzEapavkg}} {{#ev:youtube|RIetPh8iJXk}} {{#ev:youtube|oaNFrxgQY1c}} {{#ev:youtube|8xGzy12hlis}} {{#ev:youtube|ZyuHBlm3xXU}} {{#ev:youtube|RgH9GZRukOI}} {{#ev:youtube|UQvbHnBkpaM}} {{#ev:youtube|v02phoOqWHE}}{{#ev:youtube|dlSo4sBa7Nk}}
{{#ev:youtube|PXHhtQb5yzc}} {{#ev:youtube|peEzEapavkg}} {{#ev:youtube|RIetPh8iJXk}} {{#ev:youtube|oaNFrxgQY1c}} {{#ev:youtube|8xGzy12hlis}} {{#ev:youtube|ZyuHBlm3xXU}} {{#ev:youtube|RgH9GZRukOI}} {{#ev:youtube|UQvbHnBkpaM}} {{#ev:youtube|v02phoOqWHE}}{{#ev:youtube|dlSo4sBa7Nk}}


== Model modification log ==
== Appendix ==
;c172p
:Add an effect to the propeller disk (object Propeller.Fast) to put it in a transparent bin
;Models/Airport/apt-light.xml & Models/Airport/apt-light-ba.ac
:Add a spot light animation and a light volume
;Scenery/Objects/w130n30/w123n37/942050.stg
:Change KSFO_light.xml to apt-light.xml
;Aircraft/followme/Models/followme.xml & .ac
:Add light volumes and spotlight animations for headlights
 
== Effect/Shader modification log ==
;Default shaders
:render to the G-buffer
;Urban effect
:render to the G-buffer
;Spot light effect
:new effect to render spot lights from the animation file
;model-transparent
:new effect to classify transparent surfaces (those that are not bound to the glass shader or other shader that use explicitly the transparent bin )
 
{{Appendix|all|
{{Appendix|all|
* {{cite web |url=http://http.download.nvidia.com/developer/presentations/2004/6800_Leagues/6800_Leagues_Deferred_Shading.pdf |title=Deferred Shading |author=Shawn Hargreaves and Mark Harris }}
* {{cite web |url=http://http.download.nvidia.com/developer/presentations/2004/6800_Leagues/6800_Leagues_Deferred_Shading.pdf |title=Deferred Shading |author=Shawn Hargreaves and Mark Harris }}
Line 649: Line 979:
* {{cite web |url=http://aras-p.info/texts/CompactNormalStorage.html |title=Compact Normal Storage for small g-buffers |author=Aras Pranckevičius |date=4 August 2009 |accessdate=12 April 2012 }}
* {{cite web |url=http://aras-p.info/texts/CompactNormalStorage.html |title=Compact Normal Storage for small g-buffers |author=Aras Pranckevičius |date=4 August 2009 |accessdate=12 April 2012 }}
* {{cite web |url=http://the-witness.net/news/2010/03/graphics-tech-shadow-maps-part-1/ |title=Graphics Tech: Shadow Maps (part 1) |author=Jonathan Blow |date=3 March 2010 |accessdate=13 April 2012 }}
* {{cite web |url=http://the-witness.net/news/2010/03/graphics-tech-shadow-maps-part-1/ |title=Graphics Tech: Shadow Maps (part 1) |author=Jonathan Blow |date=3 March 2010 |accessdate=13 April 2012 }}
* {{cite web |url=http://directtovideo.wordpress.com/2009/11/13/deferred-rendering-in-frameranger/ |title=deferred rendering in frameranger. |author=Matt Swoboda |date=13 November 2009 |accessdate=8 July 2012 }}
* {{cite web |url=http://publications.dice.se/publications.asp?show_category=yes&which_category=Rendering |author=DICE |title=Publications on rendering |accessdate=15 August 2012 }}
* {{cite web |url=http://advances.realtimerendering.com/s2012/Epic/The%20Technology%20Behind%20the%20Elemental%20Demo%2016x9.pptx |author=Martin Mittring |title=The Technology behind the Unreal Engine 4 Elemental Demo |accessdate=15 September 2012 }}
}}
}}
<references/>


[[Category:Shader development]]
[[Category:Shader development]]
[[Category:Core development projects]]
[[Category:Core development projects]]
[[fr:Projet Rembrandt]]

Navigation menu