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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#include "Headers/Terrain.h"
#include "Headers/TerrainDescriptor.h"

#include "Core/Headers/ParamHandler.h"
#include "Quadtree/Headers/Quadtree.h"
#include "Managers/Headers/SceneManager.h"
#include "Geometry/Material/Headers/Material.h"
#include "Geometry/Shapes/Headers/Predefined/Quad3D.h"

#include "Hardware/Video/Headers/RenderStateBlock.h"
#include "Hardware/Video/Buffers/VertexBufferObject/Headers/VertexBufferObject.h"

#define COORD(x,y,w)	((y)*(w)+(x))

bool Terrain::unload(){
	SAFE_DELETE(_terrainQuadtree);
	SAFE_DELETE(_groundVBO);
	SAFE_DELETE(_terrainRenderState);
	SAFE_DELETE(_terrainDepthRenderState);
	SAFE_DELETE(_terrainReflectionRenderState);
	SAFE_DELETE(_veg);

	assert(!_terrainTextures.empty());
	for_each(TerrainTextureMap::value_type& it, _terrainTextures){
		if(it.second != NULL){///Remember kids, alpha channel is optional ;) -Ionut
			RemoveResource(it.second);
		}
	}
	_terrainTextures.clear();

	return SceneNode::unload();
}

/// Visual resources must be loaded in the rendering thread to gain acces to the current graphic context
void Terrain::loadVisualResources(){

	_alphaTexturePresent = (_terrainTextures[TERRAIN_TEXTURE_ALPHA] != NULL);
	
	//Generate a render state
	RenderStateBlockDescriptor terrainDesc;
	terrainDesc.setCullMode(CULL_MODE_CW);
    terrainDesc.setZReadWrite(true,true);
    terrainDesc.setBlend(false);
	_terrainRenderState = GFX_DEVICE.createStateBlock(terrainDesc);
	terrainDesc.setCullMode(CULL_MODE_CW);
	_terrainReflectionRenderState = GFX_DEVICE.createStateBlock(terrainDesc);
    //Generate a shadow render state
    terrainDesc.setCullMode(CULL_MODE_CCW);
    _terrainDepthRenderState = GFX_DEVICE.createStateBlock(terrainDesc);
	//For now, terrain doesn't cast shadows
	//getSceneNodeRenderState().addToDrawExclusionMask(DEPTH_STAGE);
}

bool Terrain::loadThreadedResources(TerrainDescriptor* const terrain){
	///Terrain dimensions:
	///    |-----------------------|        /\						      /\
	///    |          /\           |         |					         /  \
 	///    |          |            |         |					    /\__/    \
	///    |          |            | _terrainHeightScaleFactor  /\   /          \__/\___
	///    |<-_terrainScaleFactor->|         |				 |  --/                   \
	///    |          |            |         |                /                          \
	///    |          |            |         |              |-                            \
	///    |          |            |         \/            /_______________________________\
	///    |_________\/____________|

	_terrainHeightScaleFactor = terrain->getScale().y;

	_groundVBO = GFX_DEVICE.newVBO(TRIANGLE_STRIP);
    _groundVBO->useHWIndices(false);//<Use custom LOD indices;
	_groundVBO->useLargeIndices(true);//<32bit indices
	const vectorImpl<vec3<F32> >& normalData	= _groundVBO->getNormal();
	const vectorImpl<vec3<F32> >& tangentData	= _groundVBO->getTangent();

	ImageTools::ImageData img;
	img.create(terrain->getVariable("heightmap"));
	///data will be destroyed when img gets out of scope
	const U8* data = img.data();

	_terrainWidth = img.dimensions().width;
	_terrainHeight = img.dimensions().height;

	D_PRINT_FN(Locale::get("TERRAIN_INFO"),_terrainWidth, _terrainHeight);
	assert(data);
	U32 heightmapWidth  = _terrainWidth;
	U32 heightmapHeight = _terrainHeight;

	if(_terrainWidth%2==0)	_terrainWidth++;
	if(_terrainHeight%2==0)	_terrainHeight++;

	_groundVBO->resizePositionCount(_terrainWidth*_terrainHeight);
	_groundVBO->resizeNormalCount(_terrainWidth*_terrainHeight);
	_groundVBO->resizeTangentCount(_terrainWidth*_terrainHeight);

    _boundingBox.set(vec3<F32>(-_terrainWidth/2,  0.0f, -_terrainHeight/2),
					 vec3<F32>( _terrainWidth/2, 40.0f,  _terrainHeight/2));
	_boundingBox.Translate(terrain->getPosition());
	_boundingBox.Multiply(vec3<F32>(terrain->getScale().x,1,terrain->getScale().x));
	_boundingBox.MultiplyMax(vec3<F32>(1,_terrainHeightScaleFactor,1));

	const vec3<F32> bMin = _boundingBox.getMin();
	const vec3<F32> bMax = _boundingBox.getMax();

	vec3<F32> vertexData;
	for(U32 j=0; j < _terrainHeight; j++) {
		for(U32 i=0; i < _terrainWidth; i++) {
			U32 idxHM = COORD(i,j,_terrainWidth);

			vertexData.x = bMin.x + ((F32)i) * (bMax.x - bMin.x)/(_terrainWidth-1);
			vertexData.z = bMin.z + ((F32)j) * (bMax.z - bMin.z)/(_terrainHeight-1);

			U32 idxIMG = COORD(	i<heightmapWidth? i : i-1, j<heightmapHeight? j : j-1,	heightmapWidth);

			F32 h = (F32)(data[idxIMG*img.bpp() + 0] + data[idxIMG*img.bpp() + 1] + data[idxIMG*img.bpp() + 2])/3.0f;

			vertexData.y = (bMin.y + ((F32)h) * (bMax.y - bMin.y)/(255)) * _terrainHeightScaleFactor;
			_groundVBO->modifyPositionValue(idxHM,vertexData);
		}
	}

	U32 offset = 2;
	vec3<F32> vU, vV, vUV;
	for(U32 j=offset; j < _terrainHeight-offset; j++) {
		for(U32 i=offset; i < _terrainWidth-offset; i++) {
			U32 idx = COORD(i,j,_terrainWidth);

			vU.set(_groundVBO->getPosition(COORD(i+offset, j+0, _terrainWidth)) -  _groundVBO->getPosition(COORD(i-offset, j+0, _terrainWidth)));
			vV.set(_groundVBO->getPosition(COORD(i+0, j+offset, _terrainWidth)) -  _groundVBO->getPosition(COORD(i+0, j-offset, _terrainWidth)));
			vUV.cross(vV,vU); vUV.normalize();
			_groundVBO->modifyNormalValue(idx,vUV);
			vU = -vU; vU.normalize();
			_groundVBO->modifyTangentValue(idx,vU);
		}
	}

	for(U32 j=0; j < offset; j++) {
		for(U32 i=0; i < _terrainWidth; i++) {
			U32 idx0 = COORD(i,	j,		_terrainWidth);
			U32 idx1 = COORD(i,	offset,	_terrainWidth);

			_groundVBO->modifyNormalValue(idx0, normalData[idx1]);
			_groundVBO->modifyTangentValue(idx0,tangentData[idx1]);

			idx0 = COORD(i,	_terrainHeight-1-j,		 _terrainWidth);
			idx1 = COORD(i,	_terrainHeight-1-offset, _terrainWidth);

			_groundVBO->modifyNormalValue(idx0,normalData[idx1]);
			_groundVBO->modifyTangentValue(idx0,tangentData[idx1]);
		}
	}

	for(U32 i=0; i < offset; i++) {
		for(U32 j=0; j < _terrainHeight; j++) {
			U32 idx0 = COORD(i,		    j,	_terrainWidth);
			U32 idx1 = COORD(offset,	j,	_terrainWidth);

			_groundVBO->modifyNormalValue(idx0,normalData[idx1]);
			_groundVBO->modifyTangentValue(idx0,normalData[idx1]);

			idx0 = COORD(_terrainWidth-1-i,		 j,	_terrainWidth);
			idx1 = COORD(_terrainWidth-1-offset, j,	_terrainWidth);

			_groundVBO->modifyNormalValue(idx0,normalData[idx1]);
			_groundVBO->modifyTangentValue(idx0,normalData[idx1]);
		}
	}
	//Terrain dimensions
	vec2<U32> terrainDim(_terrainWidth, _terrainHeight);
	//Use primitive restart for each strip
	_groundVBO->setIndicesDelimiter(TERRAIN_STRIP_RESTART_INDEX);
	_terrainQuadtree->setParentShaderProgram(getMaterial()->getShaderProgram());
    _terrainQuadtree->setParentVBO(_groundVBO);
	_terrainQuadtree->Build(_boundingBox, terrainDim, terrain->getChunkSize(), _groundVBO);

	ResourceDescriptor infinitePlane("infinitePlane");
	infinitePlane.setFlag(true); //No default material
	_plane = CreateResource<Quad3D>(infinitePlane);
	F32 depth = GET_ACTIVE_SCENE()->state().getWaterDepth();
	F32 height = GET_ACTIVE_SCENE()->state().getWaterLevel()- depth;
	_farPlane = 2.0f * ParamHandler::getInstance().getParam<F32>("runtime.zFar");
    _plane->setCorner(Quad3D::TOP_LEFT, vec3<F32>(   -_farPlane, height, -_farPlane));
	_plane->setCorner(Quad3D::TOP_RIGHT, vec3<F32>(   _farPlane, height, -_farPlane));
	_plane->setCorner(Quad3D::BOTTOM_LEFT, vec3<F32>(-_farPlane, height,  _farPlane));
	_plane->setCorner(Quad3D::BOTTOM_RIGHT, vec3<F32>(_farPlane, height,  _farPlane));

	_plane->getSceneNodeRenderState().setDrawState(false);
    _diffuseUVScale = terrain->getDiffuseScale();
    _normalMapUVScale = terrain->getNormalMapScale();
	return true;
}

void Terrain::postLoad(SceneGraphNode* const sgn){
	if(getState() != RES_LOADED) {
		sgn->setActive(false);
	}
	_node = sgn;

	_groundVBO->Create();
	_planeSGN = _node->addNode(_plane);
	_plane->computeBoundingBox(_planeSGN);
	_plane->renderInstance()->preDraw(true);
	_planeSGN->setActive(false);
	_planeTransform = _planeSGN->getTransform();
	_plane->renderInstance()->transform(_planeTransform);
	computeBoundingBox(_node);
	ShaderProgram* s = getMaterial()->getShaderProgram();
	
	s->Uniform("detail_scale",  _normalMapUVScale);
    s->Uniform("diffuse_scale", _diffuseUVScale);
	s->Uniform("bbox_min", _boundingBox.getMin());
	s->Uniform("bbox_diff", _boundingBox.getMax() - _boundingBox.getMin());
	s->Uniform("_waterHeight", GET_ACTIVE_SCENE()->state().getWaterLevel());
	s->Uniform("dvd_lightCount", 1);
	s->UniformTexture("texDiffuseMap", 0);
	s->UniformTexture("texNormalHeightMap", 1);
	s->UniformTexture("texWaterCaustics", 2);
	s->UniformTexture("texBlend0", 3);
	s->UniformTexture("texBlend1", 4);
	s->UniformTexture("texBlend2", 5);
	if(_alphaTexturePresent) s->UniformTexture("texBlend3",6);

	_groundVBO->setShaderProgram(s);
}

bool Terrain::computeBoundingBox(SceneGraphNode* const sgn){
	///The terrain's final bounding box is the QuadTree's root bounding box
	///Compute the QuadTree boundingboxes and get the root BB
	_boundingBox = _terrainQuadtree->computeBoundingBox(_groundVBO->getPosition());
	///Inform the scenegraph of our new BB
	sgn->getBoundingBox() = _boundingBox;
	return  SceneNode::computeBoundingBox(sgn);
}

void Terrain::initializeVegetation(TerrainDescriptor* const terrain,SceneGraphNode* const terrainSGN) {
	vectorImpl<Texture2D*> grass;
	ResourceDescriptor grassBillboard1("Grass Billboard 1");
	grassBillboard1.setResourceLocation(terrain->getVariable("grassBillboard1"));
	ResourceDescriptor grassBillboard2("Grass Billboard 2");
	grassBillboard2.setResourceLocation(terrain->getVariable("grassBillboard2"));
	ResourceDescriptor grassBillboard3("Grass Billboard 3");
	grassBillboard3.setResourceLocation(terrain->getVariable("grassBillboard3"));
	//ResourceDescriptor grassBillboard4("Grass Billboard 4");
	//grassBillboard4.setResourceLocation(terrain->getVariable("grassBillboard4"));
	grass.push_back(CreateResource<Texture2D>(grassBillboard1));
	grass.push_back(CreateResource<Texture2D>(grassBillboard2));
	grass.push_back(CreateResource<Texture2D>(grassBillboard3));
	//grass.push_back(CreateResource<Texture2D>(grassBillboard4));
	addVegetation(New Vegetation(3, terrain->getGrassDensity(),
			                        terrain->getGrassScale(),
								    terrain->getTreeDensity(),
									terrain->getTreeScale(),
									terrain->getVariable("grassMap"),
									grass),
				  "grass");
	toggleVegetation(true);
	 _veg->initialize(_grassShader,this,terrainSGN);
}

void Terrain::addTexture(TerrainTextureUsage channel, Texture2D* const texture) {
	assert(texture != NULL);
	std::pair<TerrainTextureMap::iterator, bool > result;
	//Try and add it to the map
	result = _terrainTextures.insert(std::make_pair(channel,texture));
	//If we had a collision (same name?)
	if(!result.second){
		if((result.first)->second){
			UNREGISTER_TRACKED_DEPENDENCY(dynamic_cast<TrackedObject*>((result.first)->second));
			RemoveResource((result.first)->second);
		}
		//And add this one instead
		(result.first)->second = texture;
	}
	REGISTER_TRACKED_DEPENDENCY(dynamic_cast<TrackedObject*>(texture));
}

Commits for Divide-Framework/trunk/Source Code/Environment/Terrain/TerrainLoader.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]]

167 Diff Diff k1ngp1n picture k1ngp1n Mon 22 Jul, 2013 16:14:32 +0000

[Ionut] [[BR]]
- Changed triangle list creation for terrain (reference: http://3dgep.com/?p=1116#The_Terrain_Class) [[BR]]
- NavMesh creation now works properly for terrain [[BR]]

162 Diff Diff k1ngp1n picture k1ngp1n Mon 15 Jul, 2013 19:14:45 +0000

[Ionut] [[BR]]
- Improved terrain rendering a lot by using OpenGL’s primitive restart feature. Now terrain is rendered in n-draw calls where n is the number of terrain chunks in the quadtree (main scene has 4 chunks per terrain). [[BR]]
- Some terrain nav mesh generation code fixed. Still not 100% working [[BR]]

154 Diff Diff k1ngp1n picture k1ngp1n Sun 23 Jun, 2013 23:39:07 +0000

[Ionut] [[BR]]
- Changed math computation for: Matrix multiplication, Normal and Tangent calculation, Quaternion to Matrix conversion and more [[BR]]
- Removed useless UBO classes and extended the functionality of the base UBO class [[BR]]
- Changed lighting shaders to be more streamlined [[BR]]
- Added full shader based fog [[BR]]
— Added per-scene optional fog settings [[BR]]
- Re-enabled sorting by shader program for Mesh Delegate Bin (was set to Front to Back for debugging purposes and forgotten there) [[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 Diff Diff 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]]

122 Diff Diff k1ngp1n picture k1ngp1n Mon 11 Jun, 2012 14:39:08 +0000

[Ionut] [[BR]]
-Restructured “Hardware” folder to match the rest of the projects header-separation pattern [[BR]]

121 Diff Diff k1ngp1n picture k1ngp1n Sun 10 Jun, 2012 16:40:45 +0000

[Ionut] [[BR]]
-Added basic localization support [[BR]]
-Added cross-platform INI parsing [[BR]]
-Moved ReCast+Detour to LIBS folder [[BR]]

117 k1ngp1n picture k1ngp1n Tue 05 Jun, 2012 17:30:40 +0000

[Ionut] [[BR]]
-Separated responsibilities between “Application” and “Kernel” [[BR]]
--“Application” handles data such as window dimensions, logs, “ParamHandler” etc [[BR]]
--“Kernel” handles the main loop, SFX, GFX, physics, sceneManager etc updates [[BR]]
---“Kernel” is now a “Core” component [[BR]]
-Reduced coupling between some classes by passing more info via parameters rather than relying on singleton access [[BR]]
--Ex: eyePos in “Terrain”,“Water” and “Trigger” classes is now passed as a "vec3<F32>" on render call rather than querying “CameraManager” [[BR]]
-Reworked “GLWrapper” shutdown routine [[BR]]
Singleton witch hunt [[BR]]
-“Kernel” is no longer a singleton and it’s initialized on application startup in the “Application” class[[BR]]
-“CameraManager” is no longer a singleton and it’s instantiated in the kernel [[BR]]