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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
#include "Headers/glRenderStateBlock.h"
#include "Headers/glImmediateModeEmulation.h"

#include "GUI/Headers/GUI.h"
#include "Core/Headers/Kernel.h"
#include "Core/Headers/ParamHandler.h"
#include "Rendering/Headers/Frustum.h"
#include "Managers/Headers/ShaderManager.h"
#include "Rendering/Lighting/Headers/Light.h"
#include "Hardware/Video/Headers/GFXDevice.h"
#include "Core/Resources/Headers/ResourceCache.h"
#include "Hardware/Video/OpenGL/glsw/Headers/glsw.h"
#include "Shaders/Headers/glUniformBufferObject.h"
#include <glsl/glsl_optimizer.h>
#include <gtc/type_ptr.hpp>

#define FTGL_LIBRARY_STATIC
#include <FTGL/ftgl.h>
#include <CEGUI/CEGUI.h>


#ifdef GLEW_MX
#	ifdef _DEBUG
#		pragma comment(lib, "CEGUIOpenGLRenderer_MX_d.lib")
#		pragma comment(lib, "ftgl_gl3_MX_d.lib")
#		pragma comment(lib, "glew32mxs_d.lib")
#	else //_DEBUG
#		pragma comment(lib, "CEGUIOpenGLRenderer_MX.lib")
#		pragma comment(lib, "ftgl_gl3_MX.lib")
#		pragma comment(lib, "glew32mxs.lib")
#	endif //_DEBUG
#else //GLEW_MX
#	ifdef _DEBUG
#		pragma comment(lib, "CEGUIOpenGLRenderer_d.lib")
#		pragma comment(lib, "ftgl_gl3_d.lib")
#		pragma comment(lib, "glew32s_d.lib")
#	else//_DEBUG
#		pragma comment(lib, "CEGUIOpenGLRenderer.lib")
#		pragma comment(lib, "ftgl_gl3.lib")
#		pragma comment(lib, "glew32s.lib")
#	endif //_DEBUG
#endif //GLEW_MX

glslopt_ctx* GL_API::_GLSLOptContex = NULL;

#ifdef GLEW_MX
///GLEW_MX requirement
static boost::thread_specific_ptr<GLEWContext> _GLEWContextPtr;
GLEWContext * glewGetContext(){ return _GLEWContextPtr.get(); }
#if defined( OS_WINDOWS )
static boost::thread_specific_ptr<WGLEWContext> _WGLEWContextPtr;
WGLEWContext* wglewGetContext(){ return _WGLEWContextPtr.get(); }
#else
static boost::thread_specific_ptr<GLXEWContext> _GLXEWContextPtr;
GLXEWContext* glxewGetContext(){ return _GLXEWContextPtr.get(); }
#endif
#endif//GLEW_MX

namespace Divide{
	namespace GL{
		void initGlew(){
#ifdef GLEW_MX
			GLEWContext * currentGLEWContextsPtr =  _GLEWContextPtr.get();
			if (currentGLEWContextsPtr == NULL)	{
				currentGLEWContextsPtr = New GLEWContext;
				_GLEWContextPtr.reset(currentGLEWContextsPtr);
				ZeroMemory(currentGLEWContextsPtr, sizeof(GLEWContext));
			}
#endif //GLEW_MX
			glewExperimental=TRUE;
			//Everything is set up as needed, so initialize the OpenGL API
			GLuint err = glewInit();
			//Check for errors and print if any (They happen more than anyone thinks)
			//Bad drivers, old video card, corrupt GPU, anything can throw an error
			if (GLEW_OK != err){
				ERROR_FN(Locale::get("ERROR_GFX_DEVICE"),glewGetErrorString(err));
				PRINT_FN(Locale::get("WARN_SWITCH_D3D"));
				PRINT_FN(Locale::get("WARN_APPLICATION_CLOSE"));;
				//No need to continue, as switching to DX should be set before launching the application!
				exit(GLEW_INIT_ERROR);
			}
#ifdef GLEW_MX
	#if defined( OS_WINDOWS )

			WGLEWContext * currentWGLEWContextsPtr =  _WGLEWContextPtr.get();
			if (currentWGLEWContextsPtr == NULL)	{
				currentWGLEWContextsPtr = New WGLEWContext;
				_WGLEWContextPtr.reset(currentWGLEWContextsPtr);
				ZeroMemory(currentWGLEWContextsPtr, sizeof(WGLEWContext));
			}

			err = wglewInit();
			if (GLEW_OK != err){
				ERROR_FN(Locale::get("ERROR_GFX_DEVICE"),glewGetErrorString(err));
				PRINT_FN(Locale::get("WARN_SWITCH_D3D"));
				PRINT_FN(Locale::get("WARN_APPLICATION_CLOSE"));;
				exit(GLEW_INIT_ERROR);
			}
#	else //_WIN32

			GLXEWContext * currentGLXEWContextsPtr =  _GLXEWContextPtr.get();
			if (currentGLXEWContextsPtr == NULL)	{
				currentGLXEWContextsPtr = New GLXEWContext;
				_GLXEWContextPtr.reset(currentGLXEWContextsPtr);
				ZeroMemory(currentGLXEWContextsPtr, sizeof(GLXEWContext));
			}

			err = glxewInit();
			if (GLEW_OK != err){
				ERROR_FN(Locale::get("ERROR_GFX_DEVICE"),glewGetErrorString(err));
				PRINT_FN(Locale::get("WARN_SWITCH_D3D"));
				PRINT_FN(Locale::get("WARN_APPLICATION_CLOSE"));;
				exit(GLEW_INIT_ERROR);
			}
#	endif //_WIN32
#endif //GLEW_MX
		}
	}
}

//Let's try and create a  valid OpenGL context.
GLbyte GL_API::initHardware(const vec2<GLushort>& resolution, I32 argc, char **argv){
	ParamHandler& par = ParamHandler::getInstance();

	glfwSetErrorCallback(Divide::GL::glfw_error_callback);

    if( !glfwInit() )	return GLFW_INIT_ERROR;
	
#ifdef _DEBUG
	glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT,GL_TRUE);
#endif

    Divide::GL::_initStacks();

	//So, if someone selected High detail level, try to use pure 3.x API
	_msaaSamples = par.getParam<U8>("rendering.FSAAsamples",2);
	_useMSAA = (par.getParam<U8>("rendering.FSAAmethod",FS_MSAA) == FS_MSAA ||
				par.getParam<U8>("rendering.FSAAmethod",FS_MSAA) == FS_MSwFXAA);
	
	if(_msaaSamples > 1 && _useMSAA)	glfwWindowHint(GLFW_SAMPLES, _msaaSamples);
	
	if(par.getParam<bool>("runtime.overrideRefreshRate",false)){
		//glfwWindowHint(GLFW_REFRESH_RATE,par.getParam<U8>("runtime.targetRefreshRate",75));
	}

	glfwWindowHint(GLFW_RESIZABLE,par.getParam<bool>("runtime.allowWindowResize",false));
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,3);
	///32Bit RGBA (R8G8B8A8), 24bit Depth, 8bit Stencil
	glfwWindowHint(GLFW_RED_BITS,8);
	glfwWindowHint(GLFW_GREEN_BITS,8);
	glfwWindowHint(GLFW_BLUE_BITS,8);
	glfwWindowHint(GLFW_ALPHA_BITS,8);
	glfwWindowHint(GLFW_DEPTH_BITS,24);
	glfwWindowHint(GLFW_STENCIL_BITS,8);
	glfwWindowHint(GLFW_OPENGL_PROFILE, par.getParam<bool>("runtime.useGLCompatProfile",true) ? GLFW_OPENGL_COMPAT_PROFILE : GLFW_OPENGL_CORE_PROFILE);
	
	//Store the main window ID for future reference
	// Open an OpenGL window; resolution is specified in the external XML files
	bool window = par.getParam<bool>("runtime.windowedMode",true);
	Divide::GL::_mainWindow = glfwCreateWindow( resolution.width,
												resolution.height,
												par.getParam<std::string>("appTitle").c_str(),
												window ? NULL : glfwGetPrimaryMonitor(),
												NULL);

	if(!Divide::GL::_mainWindow){
		glfwTerminate();
		return( GLFW_WINDOW_INIT_ERROR );
	}

	glfwMakeContextCurrent(Divide::GL::_mainWindow);
	//Init glew for main context
	Divide::GL::initGlew();
	
	//Geometry shaders became core in version 3.3
	if(!GLEW_VERSION_3_3){
		ERROR_FN(Locale::get("ERROR_GFX_DEVICE"),"The OpenGL version supported by the current GPU is too old!");
		return GLEW_OLD_HARDWARE;
	}

	glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
	Divide::GL::_loaderWindow = glfwCreateWindow(1,1,"divide-res-loader",NULL, Divide::GL::_mainWindow);
	if(!Divide::GL::_loaderWindow){
		glfwTerminate();
		return( GLFW_WINDOW_INIT_ERROR );
	}

#ifdef _DEBUG
	if(GLEW_ARB_debug_output) {
		glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
		glDebugMessageCallbackARB(&Divide::GL::DebugCallbackARB, NULL);
		///Disable shader compiler errors (shader class handles that)
		glDebugMessageControlARB(GL_DEBUG_SOURCE_SHADER_COMPILER_ARB,
			                     GL_DEBUG_TYPE_ERROR_ARB,
								 GL_DONT_CARE,
								 0,
								 NULL,
								 GL_FALSE);
		Divide::GL::_useDebugOutputCallback = true;
	}else if(GLEW_AMD_debug_output){
		glDebugMessageCallbackAMD(&Divide::GL::DebugCallbackAMD, NULL);
		glDebugMessageEnableAMD(GL_DEBUG_CATEGORY_SHADER_COMPILER_AMD,
								GL_DONT_CARE,
								0,
								NULL,
								GL_FALSE);
		Divide::GL::_useDebugOutputCallback = true;
	}else{
		Divide::GL::_useDebugOutputCallback = false;
	}
#endif

	const GLFWvidmode* return_struct = glfwGetVideoMode(glfwGetPrimaryMonitor());

	I32 height = return_struct->height;
	I32 width = return_struct->width;
	glfwSetWindowPos(Divide::GL::_mainWindow, (width - resolution.width)*0.5f,(height - resolution.height)*0.5f);

#if defined( OS_WINDOWS )
	_hwnd = FindWindow(NULL,par.getParam<std::string>("appTitle").c_str());
	_hdc = GetDC(_hwnd);
#elif defined( OS_APPLE ) // Apple OS X
///??
#else //Linux
	_dpy = XOpenDisplay();
	_drawable = XCreateWindow( ...
#endif

	//If we got here, let's figure out what capabilities we have available
	GLint max_frag_uniform = 0, max_varying_floats = 0;
	GLint max_vertex_uniform = 0, max_vertex_attrib = 0,max_texture_units = 0;
	GLint buffers = 0,samplesEffective = 0;
	GLint major = 0, minor = 0, maxMinor = 0;
	GLint maxAnisotrophy = 0;
	GLint maxUBOBindings = 0, maxUBOBlockSize = 0;

	GLCheck(glGetIntegerv(GL_MAJOR_VERSION, &major)); // OpenGL major version
    GLCheck(glGetIntegerv(GL_MINOR_VERSION, &minor)); // OpenGL minor version
	GLCheck(glGetIntegerv(GL_SAMPLE_BUFFERS, &buffers));
	GLCheck(glGetIntegerv(GL_SAMPLES, &samplesEffective));
	GLCheck(glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, &max_frag_uniform)); //How many uniforms can we send to fragment shaders
	GLCheck(glGetIntegerv(GL_MAX_VARYING_FLOATS, &max_varying_floats)); //How many varying floats can we use inside a shader program
	GLCheck(glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS, &max_vertex_uniform)); //How many uniforms can we send to vertex shaders
	GLCheck(glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_vertex_attrib)); //How many attributes can we send to a vertex shader
	GLCheck(glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_texture_units)); //Maximum number of texture units we can address in shaders
	GLCheck(glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maxAnisotrophy));//Maximum supporter anisotropic filtering level
	GLCheck(glGetIntegerv(GL_MAX_UNIFORM_BUFFER_BINDINGS, &maxUBOBindings));
	GLCheck(glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &maxUBOBlockSize));

	const GLubyte* glslVersionSupported;
	GLCheck(glslVersionSupported = glGetString(GL_SHADING_LANGUAGE_VERSION));
	std::string gpuVendorByte(reinterpret_cast<const char*>(glGetString(GL_VENDOR)));
	setGPUVendor(GPU_VENDOR_OTHER);
	if(!gpuVendorByte.empty()){
		     if(gpuVendorByte.compare(0,5,"Intel") == 0)  { setGPUVendor(GPU_VENDOR_INTEL);  }
		else if(gpuVendorByte.compare(0,6,"NVIDIA") == 0) { setGPUVendor(GPU_VENDOR_NVIDIA); }
		else if(gpuVendorByte.compare(0,3,"ATI") == 0)    { setGPUVendor(GPU_VENDOR_AMD);    }
		else if(gpuVendorByte.compare(0,3,"AMD") == 0)    { setGPUVendor(GPU_VENDOR_AMD);    }
	}else{
		gpuVendorByte = "Unknown GPU Vendor";
	}

	//Shader selection based on detail
	par.setParam("shaderDetailToken",par.getParam<GLubyte>("rendering.detailLevel"));
	par.setParam("GFX_DEVICE.maxTextureCombinedUnits",max_texture_units);
	//Cap max aniso to what the hardware supports
	if(maxAnisotrophy < par.getParam<U8>("rendering.anisotropicFilteringLevel",1)){
		par.setParam("rendering.anisotropicFilteringLevel",maxAnisotrophy);
	}
	//Time to select our shaders.
	//We do not support OpenGL version lower than 3.0;
	if(major < 3){
		ERROR_FN(Locale::get("ERROR_OPENGL_NOT_SUPPORTED"));
		PRINT_FN(Locale::get("WARN_SWITCH_D3D"));
		PRINT_FN(Locale::get("WARN_APPLICATION_CLOSE"));
		return GLEW_OLD_HARDWARE;
	}else if(major == 3){
		setVersionId(OpenGL3x);
		maxMinor = 3;
	}else{
		setVersionId(OpenGL4x);
		/*   if(GLEW_VERSION_4_4) maxMinor = 4;
		else*/if(GLEW_VERSION_4_3) maxMinor = 3;
		else  if(GLEW_VERSION_4_2) maxMinor = 2;
		else  if(GLEW_VERSION_4_1) maxMinor = 1;
	}

	//Print all of the OpenGL functionality info to the console
	PRINT_FN(Locale::get("GL_MAX_UNIFORM"),max_frag_uniform);
	PRINT_FN(Locale::get("GL_MAX_FRAG_VARYING"),max_varying_floats);
	PRINT_FN(Locale::get("GL_MAX_VERT_UNIFORM"),max_vertex_uniform);
	PRINT_FN(Locale::get("GL_MAX_VERT_ATTRIB"),max_vertex_attrib);
	PRINT_FN(Locale::get("GL_MAX_TEX_UNITS"),max_texture_units);
	PRINT_FN(Locale::get("GL_MAX_VERSION"),major,maxMinor);
	PRINT_FN(Locale::get("GL_GLSL_SUPPORT"),glslVersionSupported);
	PRINT_FN(Locale::get("GL_VENDOR_STRING"),gpuVendorByte.c_str(), glGetString(GL_RENDERER));
	PRINT_FN(Locale::get("GL_MULTI_SAMPLE_INFO"),samplesEffective,buffers);
	PRINT_FN(Locale::get("GL_UBO_INFO"),maxUBOBindings, maxUBOBlockSize);

	GL_ENUM_TABLE::fill();

	//Set the clear color to a nice blue
	GL_API::clearColor(DIVIDE_BLUE());
	if(glewIsSupported("GL_ARB_seamless_cube_map")){
		GLCheck(glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS));
	}
	//keep normals in the [0..1] range despite scaling geometry
	GLCheck(glEnable(GL_NORMALIZE));
	if(_msaaSamples > 1 && _useMSAA){
		GLCheck(glEnable(GL_MULTISAMPLE));
	}
	//Correct texcoord generation during rasterization despite Perspective changes
	GLCheck(glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST));

	//MipMap detail
	switch(par.getParam<U8>("rendering.mipMapDetailLevel", 2)){
		case 0: glHint (GL_GENERATE_MIPMAP_HINT, GL_FASTEST); break;
		case 1: glHint (GL_GENERATE_MIPMAP_HINT, GL_DONT_CARE); break;
		default:
		case 2: glHint (GL_GENERATE_MIPMAP_HINT, GL_NICEST); break;
	}

	glfwSwapInterval(par.getParam<bool>("runtime.enableVSync",false) ? 1 : 0);
	I32 numberOfDisplayModes;
	const GLFWvidmode* modes = glfwGetVideoModes(glfwGetPrimaryMonitor(), &numberOfDisplayModes );
	if(modes) PRINT_FN(Locale::get("AVAILABLE_VIDEO_MODES"),numberOfDisplayModes);

	//start background loading thread
	_closeLoadingThread = false;
	_loaderThread = New boost::thread(&GL_API::loadInContextInternal, DELEGATE_REF(GL_API::getInstance()));

	//OpenGL is up and ready
	Divide::GL::_contextAvailable = true;

	_uniformBufferObjects.resize(UBO_PLACEHOLDER,NULL);
	_uniformBufferObjects[Matrices_UBO] = New glUniformBufferObject();
	_uniformBufferObjects[Matrices_UBO]->Create(Matrices_UBO, true,true);
	_uniformBufferObjects[Matrices_UBO]->ReserveBuffer(2 * 16, sizeof(F32)); //View and Projection 2 x 16 float values
	_uniformBufferObjects[Lights_UBO]  = New glUniformBufferObject();
	_uniformBufferObjects[Lights_UBO]->Create(Lights_UBO,true,false);
	_uniformBufferObjects[Lights_UBO]->ReserveBuffer(Config::MAX_LIGHTS_PER_SCENE_NODE, sizeof(LightProperties)); //Usually less or equal to 4

/*
	_uniformBufferObjects[Material_UBO]  = New glUniformBufferObject();
	_uniformBufferObjects[Material_UBO]->Create(Material_UBO,true,false);
	_uniformBufferObjects[Material_UBO]->ReserveBuffer(num materials here, sizeof(_mat->getShaderData()) );
*/
	for(GLuint index = 0; index < Config::MAX_CLIP_PLANES; ){
		_activeClipPlanes[index++] = false;
	}

	//That's it. Everything should be ready for draw calls
	PRINT_FN(Locale::get("START_OGL_API_OK"));

	RenderStateBlockDescriptor defaultGLStateDescriptor;
	GFX_DEVICE._defaultStateBlock = GFX_DEVICE.createStateBlock(defaultGLStateDescriptor);

    RenderStateBlockDescriptor defaultGLStateDescriptorNoDepth;
    defaultGLStateDescriptorNoDepth.setZReadWrite(false,false);
    _defaultStateNoDepth = GFX_DEVICE.createStateBlock(defaultGLStateDescriptorNoDepth);

	RenderStateBlockDescriptor state2DRenderingDesc;
	state2DRenderingDesc.setCullMode(CULL_MODE_NONE);
	state2DRenderingDesc.setZReadWrite(false,true);
	_state2DRendering = GFX_DEVICE.createStateBlock(state2DRenderingDesc);

	SET_DEFAULT_STATE_BLOCK(true);

	//Create an immediate mode shader
    ShaderManager::getInstance().init();
	ResourceDescriptor immediateModeShader("ImmediateModeEmulation");
	_imShader = CreateResource<ShaderProgram>(immediateModeShader);

	_prevPointString = New FTPoint();

	_glimInterfaces.reserve(4); //<For Bounding boxes, Skeletons, Debug Axis and Nav Meshes
	CEGUI::OpenGL3Renderer& GUIGLrenderer = CEGUI::OpenGL3Renderer::create();
	GUIGLrenderer.enableExtraStateSettings(par.getParam<bool>("GUI.CEGUI.ExtraStates"));
	GUI::getInstance().bindRenderer(GUIGLrenderer);

	GFX_DEVICE.changeResolution(resolution.width,resolution.height);
	return 0;
}

void GL_API::exitRenderLoop(const bool killCommand) {
	Divide::GL::_applicationClosing = true;
	glfwSetWindowShouldClose(Divide::GL::_mainWindow,true);
	glfwSetWindowShouldClose(Divide::GL::_loaderWindow,true);
}

///clear up stuff ...
void GL_API::closeRenderingApi(){
	_closeLoadingThread = true;
	_loaderThread->join();

	Divide::GL::_applicationClosing = true;
	glfwSetWindowShouldClose(Divide::GL::_mainWindow,true);
	glfwSetWindowShouldClose(Divide::GL::_loaderWindow,true);

	try{
		CEGUI::System::destroy();
	}
	catch( ... ){
		D_ERROR_FN(Locale::get("ERROR_CEGUI_DESTROY"));
	}
	//Clean font cache
	for_each(FontCache::value_type it, _fonts){
		SAFE_DELETE(it.second);
	}
	for_each(glIMPrimitive* priv, _glimInterfaces){
		SAFE_DELETE(priv);
	}
	for(U8 i = 0; i < UBO_PLACEHOLDER; i++){
		SAFE_DELETE(_uniformBufferObjects[i]);
	}

	_fonts.clear();
	_glimInterfaces.clear(); //<Should call all destructors
	SAFE_DELETE(_prevPointString);
	SAFE_DELETE(_state2DRendering);

	glfwDestroyWindow(Divide::GL::_mainWindow);
	glfwDestroyWindow(Divide::GL::_loaderWindow);
	glfwTerminate();
	
	SAFE_DELETE(_loaderThread);
}

void GL_API::initDevice(GLuint targetFrameRate){
	assert(_imShader != NULL);
	while(!glfwWindowShouldClose(Divide::GL::_mainWindow)) {
		Kernel::MainLoopStatic();
	}
}

bool GL_API::initShaders(){
    //Init glsw library
	I32 glswState = glswInit();
    glswAddDirectiveToken("","#version 130\n/*“Copyright 2009-2013 DIVIDE-Studio”*/");
    glswAddDirectiveToken("Fragment","#extension GL_EXT_texture_array : require");
	glswAddDirectiveToken("","#extension GL_ARB_uniform_buffer_object : require");
	glswAddDirectiveToken("","#extension GL_EXT_gpu_shader4 : enable");

    if(getGPUVendor() == GPU_VENDOR_NVIDIA){ //nVidia specific
        glswAddDirectiveToken("","#pragma optionNV(fastmath on)");
        glswAddDirectiveToken("","#pragma optionNV(fastprecision on)");
        glswAddDirectiveToken("","#pragma optionNV(inline all)");
        glswAddDirectiveToken("","#pragma optionNV(strict on)");
        glswAddDirectiveToken("","#pragma optionNV(unroll all)");
	}

	if(getGPUVendor() == GPU_VENDOR_AMD){
		glswAddDirectiveToken("","#define SKIP_HARDWARE_CLIPPING");
	}

	std::string clipPlanes("#define MAX_CLIP_PLANES " + Util::toString(Config::MAX_CLIP_PLANES));
    std::string lightCount("#define MAX_LIGHT_COUNT " + Util::toString(Config::MAX_LIGHTS_PER_SCENE_NODE));
	std::string shadowCount("#define MAX_SHADOW_CASTING_LIGHTS " + Util::toString(Config::MAX_SHADOW_CASTING_LIGHTS_PER_NODE));
	glswAddDirectiveToken("", clipPlanes.c_str());
	glswAddDirectiveToken("", lightCount.c_str());
	glswAddDirectiveToken("", shadowCount.c_str());
    glswAddDirectiveToken("","#define Z_TEST_SIGMA 0.0001");
    glswAddDirectiveToken("","#define ALPHA_DISCARD_THRESHOLD 0.2");
    glswAddDirectiveToken("","//__CUSTOM_DEFINES__");
	glswAddDirectiveToken("Fragment","//__CUSTOM_FRAGMENT_UNIFORMS__");
	glswAddDirectiveToken("Vertex","//__CUSTOM_VERTEX_UNIFORMS__");

    GL_API::_GLSLOptContex = glslopt_initialize(GFX_DEVICE.getApi() == OpenGLES);
    if(glswState == 1 && GL_API::_GLSLOptContex != NULL){
        return true;
    }
    return false;
}

bool GL_API::deInitShaders(){
    glslopt_cleanup(_GLSLOptContex);
    //Shut down glsw and clean memory
	return (glswShutdown() == 1);
}

void GL_API::changeResolutionInternal(U16 w, U16 h){
	glfwSetWindowSize(Divide::GL::_mainWindow,w,h);

	ParamHandler& par = ParamHandler::getInstance();
	GLfloat zNear  = par.getParam<GLfloat>("runtime.zNear");
	GLfloat zFar   = par.getParam<GLfloat>("runtime.zFar");
	GLfloat fov    = par.getParam<GLfloat>("runtime.verticalFOV");
	GLfloat ratio  = par.getParam<GLfloat>("runtime.aspectRatio");

	// Reset the coordinate system before modifying
    Divide::GL::_matrixMode(PROJECTION_MATRIX);
	Divide::GL::_loadIdentity();
	// Set the viewport to be the entire window
    GL_API::setViewport(vec4<U32>(0,0,w,h),true);
	// Set the clipping volume
	Divide::GL::_perspective(fov,ratio,zNear,zFar);

    Divide::GL::_matrixMode(VIEW_MATRIX);
    Divide::GL::_loadIdentity();

	_cachedResolution.width = w;
	_cachedResolution.height = h;
	//Update view frustum
	Frustum::getInstance().setZPlanes(vec2<GLfloat>(zNear, zFar));
	//Inform the Kernel
	Kernel::updateResolutionCallback(w,h);
}

void GL_API::setWindowPos(GLushort w, GLushort h) const {
	glfwSetWindowPos(Divide::GL::_mainWindow,w,h);
}

void GL_API::setMousePosition(D32 x, D32 y) const {
	glfwSetCursorPos(Divide::GL::_mainWindow,x,y);
}

void GL_API::idle(){
	glfwPollEvents();
}

bool GL_API::loadInContext(const CurrentContext& context, boost::function0<GLvoid> callback) {
	if(callback.empty())
		return false;

	if(context == GFX_LOADING_CONTEXT){
		while(!_loadQueue.push(callback));
	}else{
		callback();
	}
	return true;
}

void GL_API::loadInContextInternal(){
	glfwMakeContextCurrent(Divide::GL::_loaderWindow);
#ifdef GLEW_MX
	Divide::GL::initGlew();
#endif
	while(!_closeLoadingThread){
		if(_loadQueue.empty()){
			boost::this_thread::sleep(boost::posix_time::milliseconds(10));//<Avoid burning the CPU - Ionut
			continue;
		}
		boost::function0<GLvoid> callback;
		while(_loadQueue.pop(callback)){
			callback();
			glFlush();
		}
	}
	glfwMakeContextCurrent(NULL);
}

Commits for Divide-Framework/trunk/Source Code/Hardware/Video/OpenGL/GLFWWrapper.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]]

163 Diff Diff k1ngp1n picture k1ngp1n Thu 18 Jul, 2013 12:24:26 +0000

[Ionut] [[BR]]
- Fixed a rendering bug with the previous terrain rendering system (number of strips was not calculated correctly. had to add the primitive restart indices to the list as well) [[BR]]
- Fixed a rendering bug with the previous double sided Quad3D patch (water planes should not be double sided. The first parameter of the bool mask of the resource descriptor for water planes now controls whether the Quad will be single or double sided) [[BR]]
- NavMesh debug draw now uses a caching system for rendering instead of re-submitting the same geometry every frame [[BR]]
— Fixed a bug that prevented GLIM primitives to be cached if they had “canZombify” set to false [[BR]]
- Navigation meshes are now saved and loaded from file on creation. Delete the “nm” file from the navMeshes subfolder to recreate a navigation mesh for a scene. [[BR]]
- LightManager is now a FrameListener. ShadowMap generation is called with the “FramePreRenderEnd” event [[BR]]
- Terrain NavMesh uses the lowest LoD possible for now to improve creation times until all bugs are resolved [[BR]]
- Geometry importer now uses the “replace” operation for the base texture of objects [[BR]]
- glUniformBufferObjects are now a little less dependent on the GLM library [[BR]]
- Primitive restart is now toggled on or off at each VAO draw call [[BR]]
- Some GFXDevice inlining [[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]]

153 Diff Diff k1ngp1n picture k1ngp1n Fri 21 Jun, 2013 14:06:55 +0000

[Ionut] [[BR]]
- Small fix to resolution changing system [[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]]

149 Diff Diff k1ngp1n picture k1ngp1n Sun 21 Apr, 2013 21:38:05 +0000

[Ionut] [[BR]]
- Major GUI revamp: [[BR]]
— Fixed CEGUI rendering (invalid state reset after VBO/VAO unbind) [[BR]]
— Added a working Console window with a basic command parser [[BR]]
— GUI inputs take priority over scene (e.g. pressing a key in the console, does not affect the scene)[[BR]]
— Added AutoKey repeat [[BR]]
— Added config options for the GUI [[BR]]
- Revamped OpenGL Vertex Array Object class [[BR]]
— VBO’s without a shader attached will not use VAO’s [[BR]]
— VAO’s and VBO’s cleanup all states after them [[BR]]
- Added multiple Joystick support [[BR]]
- FrameBufferObject take in account the combination of texture id and bind slot when checking for double binds [[BR]]
- Upgraded Framerate/timing system [[BR]]
- Fixed Deferred rendering (typo in normal buffer creation) [[BR]]
- Fixed initial camera placement via scene config (RotateX(Y) replace with setAngleX(Y)) on camera init) [[BR]]
- Added better thread deletion in Event class [[BR]]
- Major mutex/semaphore/shared_lock rework in threaded classes [[BR]]
- Better A.I. initialization/destruction [[BR]]
- Fixed a typo in window positioning [[BR]]
- Better Unit movement code [[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]]