Subversion Repository Public Repository

Divide-Framework

This repository has no backups
This repository's network speed is throttled to 100KB/sec

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
#include "Headers/ParallelSplitShadowMaps.h"

#include "Scenes/Headers/SceneState.h"
#include "Core/Headers/ParamHandler.h"
#include "Rendering/Lighting/Headers/Light.h"
#include "Hardware/Video/Headers/GFXDevice.h"
#include "Rendering/Camera/Headers/Camera.h"
#include "Rendering/Headers/Frustum.h"
#include "Managers/Headers/SceneManager.h"
#include "Geometry/Shapes/Headers/Predefined/Quad3D.h"
#include "Hardware/Video/Buffers/PixelBufferObject/Headers/PixelBufferObject.h"

#define JITTER_SIZE  16

PSShadowMaps::PSShadowMaps(Light* light) : ShadowMap(light)
{
	_maxResolution = 0;
	_resolutionFactor = ParamHandler::getInstance().getParam<U8>("rendering.shadowResolutionFactor");
	CLAMP<F32>(_resolutionFactor,0.001f, 1.0f);
	PRINT_FN(Locale::get("LIGHT_CREATE_SHADOW_FBO"), light->getId(), "PSSM");
	///Initialize the FBO's with a variable resolution
	PRINT_FN(Locale::get("LIGHT_INIT_SHADOW_FBO"), _light->getId());

	ResourceDescriptor shadowPreviewShader("fboPreview.Layered");
	_previewDepthMapShader = CreateResource<ShaderProgram>(shadowPreviewShader);

	std::stringstream ss;
	ss << "Light " << (U32)light->getId() << " viewport ";
	ResourceDescriptor mrt(ss.str());
	mrt.setFlag(true); //No default Material;
	_renderQuad = CreateResource<Quad3D>(mrt);
    _renderQuad->setCustomShader(_previewDepthMapShader);
	_renderQuad->renderInstance()->draw2D(true);
	_jitterTexture = GFX_DEVICE.newPBO(PBO_TEXTURE_3D);

	createJitterTexture(JITTER_SIZE,8,8);

	_depthMap = GFX_DEVICE.newFBO(FBO_2D_ARRAY_DEPTH);
	
	SamplerDescriptor depthMapSampler;
	depthMapSampler.setWrapMode(TEXTURE_CLAMP_TO_EDGE);
	depthMapSampler.toggleMipMaps(false);
	depthMapSampler._useRefCompare = true; //< Use compare function
	depthMapSampler._cmpFunc = CMP_FUNC_LEQUAL; //< Use less or equal
	depthMapSampler._depthCompareMode = INTENSITY;

	TextureDescriptor depthMapDescriptor(TEXTURE_2D_ARRAY,
										 DEPTH_COMPONENT,
										 DEPTH_COMPONENT24,
										 UNSIGNED_BYTE); ///Default filters, LINEAR is OK for this
	depthMapDescriptor.setSampler(depthMapSampler);
	_depthMap->AddAttachment(depthMapDescriptor, TextureDescriptor::Depth);
	_depthMap->toggleColorWrites(false); //<do not draw colors
    _depthMap->toggleDepthBuffer(false); //<do not create a depth buffer
}

void PSShadowMaps::createJitterTexture(I32 size, I32 samples_u, I32 samples_v) {
	_jitterTexture->Create(size, size, samples_u * samples_v / 2, RGBA4, RGBA, UNSIGNED_BYTE);
	U8* data = (U8*)_jitterTexture->Begin();

    for (I32 i = 0; i<size; i++) {
        for (I32 j = 0; j<size; j++) {
            for (I32 k = 0; k<samples_u*samples_v/2; k++) {
                I32 x, y;
                vec4<F32> v;

                x = k % (samples_u / 2);
                y = (samples_v - 1) - k / (samples_u / 2);

                // generate points on a regular samples_u x samples_v rectangular grid
                v[0] = (F32)(x * 2 + 0.5f) / samples_u;
                v[1] = (F32)(y + 0.5f) / samples_v;
                v[2] = (F32)(x * 2 + 1 + 0.5f) / samples_u;
                v[3] = v[1];

                // jitter position
                v[0] += ((F32)rand() * 2 / RAND_MAX - 1) * (0.5f / samples_u);
                v[1] += ((F32)rand() * 2 / RAND_MAX - 1) * (0.5f / samples_v);
                v[2] += ((F32)rand() * 2 / RAND_MAX - 1) * (0.5f / samples_u);
                v[3] += ((F32)rand() * 2 / RAND_MAX - 1) * (0.5f / samples_v);

                // warp to disk
                vec4<F32> d;
                d[0] = sqrtf(v[1]) * cosf(2 * M_PI * v[0]);
                d[1] = sqrtf(v[1]) * sinf(2 * M_PI * v[0]);
                d[2] = sqrtf(v[3]) * cosf(2 * M_PI * v[2]);
                d[3] = sqrtf(v[3]) * sinf(2 * M_PI * v[2]);

                data[(k * size * size + j * size + i) * 4 + 0] = (U8)(d[0] * 127);
                data[(k * size * size + j * size + i) * 4 + 1] = (U8)(d[1] * 127);
                data[(k * size * size + j * size + i) * 4 + 2] = (U8)(d[2] * 127);
                data[(k * size * size + j * size + i) * 4 + 3] = (U8)(d[3] * 127);
            }
        }
    }
	_jitterTexture->End();
}

PSShadowMaps::~PSShadowMaps()
{
	RemoveResource(_previewDepthMapShader);
	RemoveResource(_renderQuad);
	SAFE_DELETE(_jitterTexture);
}

void PSShadowMaps::resolution(U16 resolution, const SceneRenderState& sceneRenderState){
    vec2<F32> zPlanes = Frustum::getInstance().getZPlanes();
    calculateSplitPoints( _light->getShadowMapInfo()->_numSplits, zPlanes.x,zPlanes.y);
    setOptimalAdjustFactor(0, 5);
	setOptimalAdjustFactor(1, 1);
    setOptimalAdjustFactor(2, 0);

	U8 resolutionFactorTemp = sceneRenderState.shadowMapResolutionFactor();
	CLAMP<U8>(resolutionFactorTemp, 1, 4);
	U16 maxResolutionTemp = resolution;
	if(resolutionFactorTemp != _resolutionFactor || _maxResolution != maxResolutionTemp){
		_resolutionFactor = resolutionFactorTemp;
		_maxResolution = maxResolutionTemp;
		//Initialize the FBO's with a variable resolution
		PRINT_FN(Locale::get("LIGHT_INIT_SHADOW_FBO"), _light->getId());
		U16 shadowMapDimension = _maxResolution/_resolutionFactor;
		_depthMap->Create(shadowMapDimension,shadowMapDimension,_numSplits);
		_renderQuad->setDimensions(vec4<F32>(0,0,shadowMapDimension,shadowMapDimension));
	}
	ShadowMap::resolution(resolution,sceneRenderState);
}

void PSShadowMaps::render(const SceneRenderState& renderState, boost::function0<void> sceneRenderFunction){
	//Only if we have a valid callback;
	if(sceneRenderFunction.empty()) {
		ERROR_FN(Locale::get("ERROR_LIGHT_INVALID_SHADOW_CALLBACK"), _light->getId());
		return;
	}
    F32 ortho = GET_ACTIVE_SCENEGRAPH()->getRoot()->getBoundingBox().getWidth() * 0.5f;
	CLAMP<F32>(ortho, 1.0f, (F32)Config::DIRECTIONAL_LIGHT_DISTANCE);
    for(U8 i = 0; i < _numSplits; i++){
        _orthoPerPass[_numSplits - i - 1] = ortho / ((1.0f + i) * (1.0f + i) + i);
    }
	_callback = sceneRenderFunction;
	renderInternal(renderState);
}

void PSShadowMaps::setOptimalAdjustFactor(U8 index, F32 value){
    assert(index < _numSplits);
    if(_optAdjustFactor.size() <= index) _optAdjustFactor.push_back(value);
    else _optAdjustFactor[index] = value;
}

void PSShadowMaps::calculateSplitPoints(U8 splitCount, F32 nearDist, F32 farDist, F32 lambda){
    if (splitCount < 2){
        ERROR_FN(Locale::get("ERROR_LIGHT_INVALID_SPLIT_COUNT"), splitCount);
    }
	_numSplits = splitCount;
    _orthoPerPass.resize(_numSplits);
    _splitPadding = 5;
    _splitPoints.resize(splitCount + 1);
 	_splitPoints[0] = nearDist;
	for (U8 i = 1; i < _numSplits; i++){
	    F32 fraction = (F32)i / (F32)_numSplits;
        F32 splitPoint = lambda * nearDist * std::pow(farDist / nearDist, fraction) +
                         (1.0f - lambda) * (nearDist + fraction * (farDist - nearDist));

		_splitPoints[i] = splitPoint;
	}
	_splitPoints[splitCount] = farDist;
}

void PSShadowMaps::renderInternal(const SceneRenderState& renderState) const {
	Scene* activeScene = GET_ACTIVE_SCENE();
	boost::function0<void> renderFunction = _callback.empty() ? SCENE_GRAPH_UPDATE(activeScene->getSceneGraph()) : _callback;
	GFXDevice& gfx = GFX_DEVICE;
	//Get our eye view
	const vec3<F32>& eyePos = renderState.getCameraConst().getEye();
	//For every depth map
	//Lock our projection matrix so no changes will be permanent during the rest of the frame
    //Lock our model view matrix so no camera transforms will be saved beyond this light's scope
    gfx.lockMatrices();
	//Set the camera to the light's view
	_light->setCameraToLightView(eyePos);
	//bind the associated depth map
	_depthMap->Begin();
	//For each depth pass
	for(U8 i = 0; i < _numSplits; i++){
		//Set the appropriate projection
		_light->renderFromLightView(i, _orthoPerPass[i]);
		_depthMap->DrawToLayer(0,i);
			//draw the scene
			GFX_DEVICE.render(renderFunction, renderState);
	}
	_depthMap->End();
	//get all the required information (light MVP matrix for example)
	//and restore to the proper camera view
	_light->setCameraToSceneView();
	//Undo all modifications to the Projection Matrix
    //Undo all modifications to the ModelView Matrix
	gfx.releaseMatrices();
	//Restore our view frustum
	Frustum::getInstance().Extract(eyePos);
}

void PSShadowMaps::previewShadowMaps(){
    _renderQuad->onDraw(DISPLAY_STAGE);

	_previewDepthMapShader->bind();
	_previewDepthMapShader->UniformTexture("tex",0);
	_depthMap->Bind(0,1);
	GFX_DEVICE.toggle2D(true);
		_previewDepthMapShader->Uniform("layer",0);
		GFX_DEVICE.renderInViewport(vec4<U32>(0,0,128,128),
								    DELEGATE_BIND(&GFXDevice::renderInstance,
									            DELEGATE_REF(GFX_DEVICE),
												DELEGATE_REF(_renderQuad->renderInstance())));
		_previewDepthMapShader->Uniform("layer",1);
		GFX_DEVICE.renderInViewport(vec4<U32>(130,0,128,128),
			                        DELEGATE_BIND(&GFXDevice::renderInstance,
									             DELEGATE_REF(GFX_DEVICE),
												 DELEGATE_REF(_renderQuad->renderInstance())));
		_previewDepthMapShader->Uniform("layer",2);
		GFX_DEVICE.renderInViewport(vec4<U32>(260,0,128,128),
			                        DELEGATE_BIND(&GFXDevice::renderInstance,
									            DELEGATE_REF(GFX_DEVICE),
												DELEGATE_REF(_renderQuad->renderInstance())));
	GFX_DEVICE.toggle2D(false);
	_depthMap->Unbind(0);
}

Commits for Divide-Framework/trunk/Source Code/Rendering/Lighting/ShadowMapping/ParallelSplitShadowMaps.cpp

Diff revisions: vs.
Revision Author Commited Message
168 Diff Diff k1ngp1n picture k1ngp1n Sat 26 Oct, 2013 19:03:21 +0000

- Reworked the Camera class[[BR]]
— Now fully quaternion based [[BR]]
— Basic camera types added but not used yet (third person, first person, orbit) [[BR]]
- Cleaned up Material and Texture handling [[BR]]
- Added clipping plane support [[BR]]
— Similar to OpenGL fixed-function clip planes but fully shader driven [[BR]]
— Added a new class, “Plane”, that helps define clip planes [[BR]]
- Optimized the Singleton class to allow faster “getInstance” calls without performance penalties [[BR]]
-- “createInstance” must be called for each singleton class before usage. Or “gerOrCreateInstance” can be used, which is basically the former “getInstance” implementation [[BR]]
- Improved console logging by changing some heap allocations to stack and removing dependencies on the std::string class [[BR]]
- Added a lot of performance optimizations related to coding standards and redundant calculations [[BR]]
— e.g. Frustum AABB check didn’t need to recompute the AABB points as they were calculated already [[BR]]
— e.g. A vector did not need to be set to 0 on initialization as that is already it’s default state on creation [[BR]]
— e.g. Faster Framerate and Timing calculations by using less member variables that are not needed outsied of calling functions [[BR]]
- The SceneState now contains the SceneRenderState and is passed on to the SceneGraph’s update calls [[BR]]
- Better material export/import to/from XML format [[BR]]
- More bug fixes and cleanups [[BR]]

152 Diff Diff k1ngp1n picture k1ngp1n Thu 20 Jun, 2013 14:23:31 +0000

[Ionut] [[BR]]
- New rendering pipeline (experimental and unstable): [[BR]]
— OpenGL 3.x clean context (glLight commands are still used for now, but UBO support is there, but not used yet) [[BR]]
— Custom matrix stacks and UBO based shader data (UBOs cause some link errors on some nVidia cards)[[BR]]
— Multi-threaded texture loading and shader compilation (mt shader compilation disabled for now. needs more tests) [[BR]]
— VAO rendering is self contained (no more enable/disable calls before a draw request) [[BR]]
— Render instance class used for rendering information [[BR]]
[[BR]]
- New unique ID generation base class: GUIDWrapper. Each class that derives from this, gets an application wide unique id on construction [[BR]]
- Added base code for an in-game editor using CEGUI [[BR]]
- Replaced some mutex locks with lockless data structures or atomic data [[BR]]
- CEGUI 0.8.2, FTGL-GL3 and GLIM 0.4 modified to support GLEW_MX if defined [[BR]]
- Dropped VS2008 support [[BR]]
- Networking library, server framework and ReCast files are now projects inside the Divide Framework solution [[BR]]
- New console command “setFov” that modifies the horizontal FoV value in realtime [[BR]]
- New console command “recompileShader” that reparses shader files, recompiles shaders and relinks shader programs who’s names match or contain the argument string [[BR]]
- New debug utility: axis angle drawn in corner of the screen if needed [[BR]]
- More ‘const’-s pasted around the code, more loop performance tweaks (allocations before a loop, tighter loops, etc), more utility member functions added to various classes [[BR]]

151 Diff Diff k1ngp1n picture k1ngp1n Tue 07 May, 2013 00:00:52 +0000

[Ionut] [[BR]]
- Better ReCast integration [[BR]]
— Any entity can be used as an obstacle in the NavMesh if that’s specified in each scene’s assets.xml file for said entity [[BR]]
— New console command, “createNavMesh”, that passes geometry data to ReCast [[BR]]
-— NavMesh generation is not yet complete [[BR]]
- Better PhysX integration [[BR]]
— Each scene passes data to and gets data from the Physics API better and safer[[BR]]
- Multi-threaded support extended: [[BR]]
— Event class replaced with Task [[BR]]
— Kernel uses a threadpool for scene tasks [[BR]]
— Each task can be added to a different threadpool if needed [[BR]]
— Most critical sections use the new boost::atomic wrapper for thread safety [[BR]]
- Rendering system updated [[BR]]
— VBO’s keep track of the geometry type internally [[BR]]
— Rendering by specific element list is internal to the VBO [[BR]]
— VBO’s can draw a “lite” version that doesn’t send Tangent, BiTangent and TexCoord data for depth rendering (disabled) [[BR]]
- Reflectors now offer a preview of the generated reflective texture if needed [[BR]]
- Buttons are now added and rendered by CEGUI [[BR]]
[[BR]]
Deprecation: [[BR]]
- Removed fixed pipeline material system [[BR]]
- Removed BoundingBox late update system [[BR]]
- Shadow references in the material system are now depth references [[BR]]
[[BR]]
Bug fixes: [[BR]]
- Problematic FBO double bind check removed [[BR]]
- Faster terrain rendering via chunk size selection through each scene’s terrain.xml[[BR]]
- Rendering is paused when the window is minimized [[BR]]
- CEGUI and impostors now render properly in deferred rendering mode [[BR]]
- Fixed various level 4 (VS2008) warnings [[BR]]
- Better state management and cleaning [[BR]]
- Better SceneGraph node management and trasformation/AABB update calls [[BR]]
- AITenisScene has proper collisions now [[BR]]

146 k1ngp1n picture k1ngp1n Wed 10 Apr, 2013 13:20:15 +0000

[Ionut] [[BR]]
*Final LightBranch updates 2/3 : Main trunk merge and build test (VC90, VC100, gDebugger) [[BR]]
-Merged light branch with trunk [[BR]]
-Deleted light branch [[BR]]