/
OpenGLRenderSystem.cpp
643 lines (520 loc) · 18.2 KB
/
OpenGLRenderSystem.cpp
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
#include "OpenGLRenderSystem.h"
#include "ishaders.h"
#include "igl.h"
#include "itextstream.h"
#include "iradiant.h"
#include "math/Matrix4.h"
#include "module/StaticModule.h"
#include "backend/GLProgramFactory.h"
#include "backend/BuiltInShader.h"
#include "backend/ColourShader.h"
#include "backend/LightInteractions.h"
#include "debugging/debugging.h"
#include "LightingModeRenderResult.h"
#include <functional>
namespace render {
namespace {
// Polygon stipple pattern
const GLubyte POLYGON_STIPPLE_PATTERN[132] = {
0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55,
0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55,
0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55,
0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55,
0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55,
0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55,
0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55,
0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55,
0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55,
0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55,
0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55,
0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55,
0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55,
0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55,
0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55,
0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55
};
}
/**
* Main constructor.
*/
OpenGLRenderSystem::OpenGLRenderSystem() :
_realised(false),
_shaderProgramsAvailable(false),
_glProgramFactory(std::make_shared<GLProgramFactory>()),
_currentShaderProgram(SHADER_PROGRAM_NONE),
_time(0),
m_traverseRenderablesMutex(false)
{
bool shouldRealise = false;
// For the static default rendersystem, the MaterialManager is not existent yet,
// hence it will be attached in initialiseModule().
if (module::GlobalModuleRegistry().moduleExists(MODULE_SHADERSYSTEM))
{
_materialDefsLoaded = GlobalMaterialManager().signal_DefsLoaded().connect(
sigc::mem_fun(*this, &OpenGLRenderSystem::realise));
_materialDefsUnloaded = GlobalMaterialManager().signal_DefsUnloaded().connect(
sigc::mem_fun(*this, &OpenGLRenderSystem::unrealise));
if (GlobalMaterialManager().isRealised())
{
// Hold back with the realise() call until we know whether we can call
// extensionsInitialised() below - this should happen before realise()
shouldRealise = true;
}
}
// If the openGL module is already initialised and a shared context is created
// trigger a call to extensionsInitialised().
if (module::GlobalModuleRegistry().moduleExists(MODULE_SHARED_GL_CONTEXT) &&
GlobalOpenGLContext().getSharedContext())
{
extensionsInitialised();
}
if (shouldRealise)
{
realise();
}
}
OpenGLRenderSystem::~OpenGLRenderSystem()
{
_materialDefsLoaded.disconnect();
_materialDefsUnloaded.disconnect();
}
ITextRenderer::Ptr OpenGLRenderSystem::captureTextRenderer(IGLFont::Style style, std::size_t size)
{
// Try to find an existing text renderer with this combination
auto fontKey = std::make_pair(style, size);
auto existing = _textRenderers.find(fontKey);
if (existing == _textRenderers.end())
{
auto font = GlobalOpenGL().getFont(fontKey.first, fontKey.second);
existing = _textRenderers.emplace(fontKey, std::make_shared<TextRenderer>(font)).first;
}
return existing->second;
}
ShaderPtr OpenGLRenderSystem::capture(const std::string& name, const std::function<OpenGLShaderPtr()>& createShader)
{
// Usual ritual, check cache and return if found, otherwise create/
// insert/return.
auto existing = _shaders.find(name);
if (existing != _shaders.end())
{
return existing->second;
}
// Either the shader was not found, or the weak pointer failed to lock
// because the shader had been deleted. Either way, create a new shader
// using the given factory functor and insert into the cache.
auto shader = createShader();
_shaders[name] = shader;
// Realise the shader if the cache is realised
if (_realised)
{
shader->realise();
}
return shader;
}
ShaderPtr OpenGLRenderSystem::capture(const std::string& name)
{
// Forward to the method accepting our factory function
return capture(name, [&]()
{
return std::make_shared<OpenGLShader>(name, *this);
});
}
ShaderPtr OpenGLRenderSystem::capture(BuiltInShaderType type)
{
// Forward to the method accepting our factory function
auto name = BuiltInShader::GetNameForType(type);
return capture(name, [&]()
{
return std::make_shared<BuiltInShader>(type, *this);
});
}
ShaderPtr OpenGLRenderSystem::capture(ColourShaderType type, const Colour4& colour)
{
// Forward to the method accepting our factory function
auto name = ColourShader::ConstructName(type, colour);
return capture(name, [&]()
{
return std::make_shared<ColourShader>(type, colour, *this);
});
}
void OpenGLRenderSystem::beginRendering(OpenGLState& state)
{
glPushAttrib(GL_ALL_ATTRIB_BITS);
// global settings that are not set in renderstates
glFrontFace(GL_CW);
glCullFace(GL_BACK);
glPolygonOffset(-1, 1);
// Set polygon stipple pattern from constant
glPolygonStipple(POLYGON_STIPPLE_PATTERN);
glEnableClientState(GL_VERTEX_ARRAY);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
if (GLEW_VERSION_1_3) {
glActiveTexture(GL_TEXTURE0);
glClientActiveTexture(GL_TEXTURE0);
}
if (GLEW_ARB_shader_objects) {
glUseProgramObjectARB(0);
glDisableVertexAttribArrayARB(c_attr_TexCoord0);
glDisableVertexAttribArrayARB(c_attr_Tangent);
glDisableVertexAttribArrayARB(c_attr_Binormal);
}
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// Set up initial GL state. This MUST MATCH the defaults in the OpenGLState
// object, otherwise required state changes may not occur.
glLineStipple(state.m_linestipple_factor,
state.m_linestipple_pattern);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDisable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisable(GL_BLEND);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glShadeModel(GL_FLAT);
glDisable(GL_DEPTH_TEST);
// RENDER_DEPTHWRITE defaults to 0
glDepthMask(GL_FALSE);
// RENDER_MASKCOLOUR defaults to 0
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glDisable(GL_ALPHA_TEST);
glDisable(GL_LINE_STIPPLE);
glDisable(GL_POLYGON_STIPPLE);
glDisable(GL_POLYGON_OFFSET_LINE);
glDisable(GL_POLYGON_OFFSET_FILL); // greebo: otherwise tiny gap lines between brushes are visible
glBindTexture(GL_TEXTURE_2D, 0);
glColor4f(1, 1, 1, 1);
glDepthFunc(state.getDepthFunc());
glAlphaFunc(GL_ALWAYS, 0);
glLineWidth(1);
glPointSize(1);
glHint(GL_FOG_HINT, GL_NICEST);
glDisable(GL_FOG);
}
void OpenGLRenderSystem::setupViewMatrices(const Matrix4& modelview, const Matrix4& projection)
{
// Set the projection and modelview matrices
glMatrixMode(GL_PROJECTION);
glLoadMatrixd(projection);
glMatrixMode(GL_MODELVIEW);
glLoadMatrixd(modelview);
}
void OpenGLRenderSystem::finishRendering()
{
if (GLEW_ARB_shader_objects)
{
glUseProgramObjectARB(0);
}
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glPopAttrib();
}
/*
* Render all states in the ShaderCache along with their renderables. This
* is where the actual OpenGL rendering starts.
*/
void OpenGLRenderSystem::render(RenderViewType renderViewType,
RenderStateFlags globalstate,
const Matrix4& modelview,
const Matrix4& projection,
const Vector3& viewer,
const VolumeTest& view)
{
// Construct default OpenGL state
OpenGLState current;
beginRendering(current);
setupViewMatrices(modelview, projection);
// Iterate over the sorted mapping between OpenGLStates and their
// OpenGLShaderPasses (containing the renderable geometry), and render the
// contents of each bucket. Each pass is passed a reference to the "current"
// state, which it can change.
for (const auto& pair : _state_sorted)
{
// Render the OpenGLShaderPass
if (pair.second->empty()) continue;
if (pair.second->isApplicableTo(renderViewType))
{
pair.second->render(current, globalstate, viewer, view, _time);
}
pair.second->clearRenderables();
}
renderText();
finishRendering();
}
IRenderResult::Ptr OpenGLRenderSystem::renderLitScene(RenderStateFlags globalFlagsMask,
const IRenderView& view)
{
auto result = std::make_shared<LightingModeRenderResult>();
// Construct default OpenGL state
OpenGLState current;
beginRendering(current);
setupViewMatrices(view.GetModelview(), view.GetProjection());
std::size_t visibleLights = 0;
std::vector<LightInteractions> interactionLists;
interactionLists.reserve(_lights.size());
// Gather all visible lights and render the surfaces touched by them
for (const auto& light : _lights)
{
LightInteractions interaction(*light);
if (!interaction.isInView(view))
{
result->skippedLights++;
continue;
}
result->visibleLights++;
// Check all the surfaces that are touching this light
interaction.collectSurfaces(_entities);
result->objects += interaction.getObjectCount();
result->entities += interaction.getEntityCount();
interactionLists.emplace_back(std::move(interaction));
}
// Run the depth fill pass
for (auto& interactionList : interactionLists)
{
interactionList.fillDepthBuffer(current, globalFlagsMask, view, _time);
}
// Draw the surfaces per light and material
for (auto& interactionList : interactionLists)
{
interactionList.render(current, globalFlagsMask, view, _time);
result->drawCalls += interactionList.getDrawCalls();
}
renderText();
finishRendering();
return result;
}
void OpenGLRenderSystem::renderText()
{
// Render all text
glDisable(GL_DEPTH_TEST);
for (const auto& [_, textRenderer] : _textRenderers)
{
textRenderer->render();
}
}
void OpenGLRenderSystem::realise()
{
if (_realised) {
return; // already realised
}
_realised = true;
if (shaderProgramsAvailable() && getCurrentShaderProgram() != SHADER_PROGRAM_NONE)
{
// Realise the GLPrograms
_glProgramFactory->realise();
}
// Realise all shaders
for (auto& [_, shader] : _shaders)
{
shader->realise();
}
}
void OpenGLRenderSystem::unrealise()
{
if (!_realised) {
return;
}
_realised = false;
// Unrealise all OpenGLShader objects
for (auto& [_, shader] : _shaders)
{
shader->unrealise();
}
if (GlobalOpenGLContext().getSharedContext() &&
shaderProgramsAvailable() &&
getCurrentShaderProgram() != SHADER_PROGRAM_NONE)
{
// Unrealise the GLPrograms
_glProgramFactory->unrealise();
}
}
GLProgramFactory& OpenGLRenderSystem::getGLProgramFactory()
{
return *_glProgramFactory;
}
std::size_t OpenGLRenderSystem::getTime() const
{
return _time;
}
void OpenGLRenderSystem::setTime(std::size_t milliSeconds)
{
_time = milliSeconds;
}
RenderSystem::ShaderProgram OpenGLRenderSystem::getCurrentShaderProgram() const
{
return _currentShaderProgram;
}
void OpenGLRenderSystem::setShaderProgram(RenderSystem::ShaderProgram newProg)
{
ShaderProgram oldProgram = _currentShaderProgram;
if (oldProgram != newProg)
{
unrealise();
GlobalMaterialManager().setLightingEnabled(
newProg == SHADER_PROGRAM_INTERACTION
);
}
_currentShaderProgram = newProg;
if (oldProgram != newProg)
{
realise();
}
}
void OpenGLRenderSystem::extensionsInitialised()
{
// Determine if lighting is available based on GL extensions
bool haveGLSL = GLEW_VERSION_2_0 ? true : false;
#if defined(DEBUG_NO_LIGHTING)
haveGLSL = false;
#endif
rMessage() << "[OpenGLRenderSystem] GLSL shading "
<< (haveGLSL ? "IS" : "IS NOT" ) << " available.\n";
// Set the flag in the openGL module
setShaderProgramsAvailable(haveGLSL);
// Inform the user of missing extensions
if (!haveGLSL)
{
rWarning() << "Light rendering requires OpenGL 2.0 or newer.\n";
}
// Now that GL extensions are done, we can realise our shaders
// This was previously done explicitly by the OpenGLModule after the
// shared context was created. But we need realised shaders before
// we can fire off the "extensions initialised" signal, map loading
// code might rely on materials being constructed.
realise();
// Notify all our observers
_sigExtensionsInitialised();
}
sigc::signal<void> OpenGLRenderSystem::signal_extensionsInitialised()
{
return _sigExtensionsInitialised;
}
bool OpenGLRenderSystem::shaderProgramsAvailable() const
{
return _shaderProgramsAvailable;
}
void OpenGLRenderSystem::setShaderProgramsAvailable(bool available)
{
_shaderProgramsAvailable = available;
}
void OpenGLRenderSystem::insertSortedState(const OpenGLStates::value_type& val) {
_state_sorted.insert(val);
}
void OpenGLRenderSystem::eraseSortedState(const OpenGLStates::key_type& key) {
_state_sorted.erase(key);
}
// renderables
void OpenGLRenderSystem::attachRenderable(Renderable& renderable) {
ASSERT_MESSAGE(!m_traverseRenderablesMutex, "attaching renderable during traversal");
ASSERT_MESSAGE(m_renderables.find(&renderable) == m_renderables.end(), "renderable could not be attached");
m_renderables.insert(&renderable);
}
void OpenGLRenderSystem::detachRenderable(Renderable& renderable) {
ASSERT_MESSAGE(!m_traverseRenderablesMutex, "detaching renderable during traversal");
ASSERT_MESSAGE(m_renderables.find(&renderable) != m_renderables.end(), "renderable could not be detached");
m_renderables.erase(&renderable);
}
void OpenGLRenderSystem::forEachRenderable(const RenderableCallback& callback) const {
ASSERT_MESSAGE(!m_traverseRenderablesMutex, "for-each during traversal");
m_traverseRenderablesMutex = true;
for (Renderables::iterator i = m_renderables.begin(); i != m_renderables.end(); ++i) {
callback(*(*i));
}
m_traverseRenderablesMutex = false;
}
void OpenGLRenderSystem::setMergeModeEnabled(bool enabled)
{
for (auto& [_, shader] : _shaders)
{
shader->setMergeModeEnabled(enabled);
}
}
// RegisterableModule implementation
const std::string& OpenGLRenderSystem::getName() const
{
static std::string _name(MODULE_RENDERSYSTEM);
return _name;
}
const StringSet& OpenGLRenderSystem::getDependencies() const
{
static StringSet _dependencies
{
MODULE_SHADERSYSTEM,
MODULE_SHARED_GL_CONTEXT,
};
return _dependencies;
}
void OpenGLRenderSystem::initialiseModule(const IApplicationContext& ctx)
{
rMessage() << getName() << "::initialiseModule called." << std::endl;
_materialDefsLoaded = GlobalMaterialManager().signal_DefsLoaded().connect(
sigc::mem_fun(*this, &OpenGLRenderSystem::realise));
_materialDefsUnloaded = GlobalMaterialManager().signal_DefsUnloaded().connect(
sigc::mem_fun(*this, &OpenGLRenderSystem::unrealise));
if (GlobalMaterialManager().isRealised())
{
realise();
}
// greebo: Don't realise the module yet, this must wait
// until the shared GL context has been created (this
// happens as soon as the first GL widget has been realised).
_sharedContextCreated = GlobalOpenGLContext().signal_sharedContextCreated()
.connect(sigc::mem_fun(this, &OpenGLRenderSystem::extensionsInitialised));
_sharedContextDestroyed = GlobalOpenGLContext().signal_sharedContextDestroyed()
.connect(sigc::mem_fun(this, &OpenGLRenderSystem::unrealise));
}
void OpenGLRenderSystem::shutdownModule()
{
_textRenderers.clear();
_sharedContextCreated.disconnect();
_sharedContextDestroyed.disconnect();
_materialDefsLoaded.disconnect();
_materialDefsUnloaded.disconnect();
}
void OpenGLRenderSystem::addEntity(const IRenderEntityPtr& renderEntity)
{
assert(renderEntity);
if (!_entities.insert(renderEntity).second)
{
throw std::logic_error("Duplicate entity registration.");
}
auto light = std::dynamic_pointer_cast<RendererLight>(renderEntity);
if (!light) return;
if (!_lights.insert(light).second)
{
throw std::logic_error("Duplicate light registration.");
}
}
void OpenGLRenderSystem::removeEntity(const IRenderEntityPtr& renderEntity)
{
if (_entities.erase(renderEntity) == 0)
{
throw std::logic_error("Entity has not been registered.");
}
auto light = std::dynamic_pointer_cast<RendererLight>(renderEntity);
if (!light) return;
if (_lights.erase(light) == 0)
{
throw std::logic_error("Light has not been registered.");
}
}
void OpenGLRenderSystem::foreachEntity(const std::function<void(const IRenderEntityPtr&)>& functor)
{
std::for_each(_entities.begin(), _entities.end(), functor);
}
void OpenGLRenderSystem::foreachLight(const std::function<void(const RendererLightPtr&)>& functor)
{
std::for_each(_lights.begin(), _lights.end(), functor);
}
IGeometryStore& OpenGLRenderSystem::getGeometryStore()
{
return _geometryStore;
}
// Define the static OpenGLRenderSystem module
module::StaticModule<OpenGLRenderSystem> openGLRenderSystemModule;
} // namespace render