/
OgreApplicationContextBase.cpp
563 lines (477 loc) · 16.2 KB
/
OgreApplicationContextBase.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
// This file is part of the OGRE project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at https://www.ogre3d.org/licensing.
#include "OgreApplicationContextBase.h"
#include "OgreRoot.h"
#include "OgreGpuProgramManager.h"
#include "OgreConfigFile.h"
#include "OgreRenderWindow.h"
#include "OgreViewport.h"
#include "OgreOverlaySystem.h"
#include "OgreDataStream.h"
#include "OgreBitesConfigDialog.h"
#include "OgreWindowEventUtilities.h"
#include "OgreSceneNode.h"
#include "OgreCamera.h"
#include "OgreArchiveManager.h"
#include "OgreConfigPaths.h"
namespace OgreBites {
static const char* SHADER_CACHE_FILENAME = "cache.bin";
ApplicationContextBase::ApplicationContextBase(const Ogre::String& appName)
{
mAppName = appName;
mFSLayer = new Ogre::FileSystemLayer(mAppName);
if (char* val = getenv("OGRE_CONFIG_DIR"))
{
Ogre::String configDir = Ogre::StringUtil::standardisePath(val);
mFSLayer->setConfigPaths({ configDir });
}
mRoot = NULL;
mOverlaySystem = NULL;
mFirstRun = true;
#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM
mMaterialMgrListener = NULL;
mShaderGenerator = NULL;
#endif
}
ApplicationContextBase::~ApplicationContextBase()
{
delete mFSLayer;
}
void ApplicationContextBase::initApp()
{
createRoot();
if (!oneTimeConfig()) return;
#if OGRE_PLATFORM != OGRE_PLATFORM_ANDROID
// if the context was reconfigured, set requested renderer
if (!mFirstRun) mRoot->setRenderSystem(mRoot->getRenderSystemByName(mNextRenderer));
#endif
setup();
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
mRoot->saveConfig();
Ogre::Root::getSingleton().getRenderSystem()->_initRenderTargets();
// Clear event times
Ogre::Root::getSingleton().clearEventTimes();
#endif
}
void ApplicationContextBase::closeApp()
{
shutdown();
if (mRoot)
{
#if OGRE_PLATFORM != OGRE_PLATFORM_ANDROID
mRoot->saveConfig();
#endif
OGRE_DELETE mRoot;
mRoot = NULL;
}
#ifdef OGRE_BITES_STATIC_PLUGINS
mStaticPluginLoader.unload();
#endif
}
bool ApplicationContextBase::initialiseRTShaderSystem()
{
#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM
if (Ogre::RTShader::ShaderGenerator::initialize())
{
mShaderGenerator = Ogre::RTShader::ShaderGenerator::getSingletonPtr();
// Create and register the material manager listener if it doesn't exist yet.
if (!mMaterialMgrListener) {
mMaterialMgrListener = new SGTechniqueResolverListener(mShaderGenerator);
Ogre::MaterialManager::getSingleton().addListener(mMaterialMgrListener);
}
return true;
}
#endif
return false;
}
void ApplicationContextBase::setRTSSWriteShadersToDisk(bool write)
{
#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM
if(!write) {
mShaderGenerator->setShaderCachePath("");
return;
}
// Set shader cache path.
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
auto subdir = "";
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE
auto subdir = "org.ogre3d.RTShaderCache/";
#else
auto subdir = "RTShaderCache";
#endif
auto path = mFSLayer->getWritablePath(subdir);
if (!Ogre::FileSystemLayer::fileExists(path))
{
Ogre::FileSystemLayer::createDirectory(path);
}
mShaderGenerator->setShaderCachePath(path);
#endif
}
void ApplicationContextBase::destroyRTShaderSystem()
{
#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM
//mShaderGenerator->removeAllShaderBasedTechniques();
//mShaderGenerator->flushShaderCache();
// Restore default scheme.
Ogre::MaterialManager::getSingleton().setActiveScheme(Ogre::MaterialManager::DEFAULT_SCHEME_NAME);
// Unregister the material manager listener.
if (mMaterialMgrListener != NULL)
{
Ogre::MaterialManager::getSingleton().removeListener(mMaterialMgrListener);
delete mMaterialMgrListener;
mMaterialMgrListener = NULL;
}
// Destroy RTShader system.
if (mShaderGenerator != NULL)
{
Ogre::RTShader::ShaderGenerator::destroy();
mShaderGenerator = NULL;
}
#endif
}
void ApplicationContextBase::setup()
{
mRoot->initialise(false);
createWindow(mAppName);
locateResources();
initialiseRTShaderSystem();
loadResources();
// adds context as listener to process context-level (above the sample level) events
mRoot->addFrameListener(this);
}
void ApplicationContextBase::createRoot()
{
#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID
mRoot = OGRE_NEW Ogre::Root("");
#else
Ogre::String pluginsPath;
# ifndef OGRE_BITES_STATIC_PLUGINS
pluginsPath = mFSLayer->getConfigFilePath("plugins.cfg");
if (!Ogre::FileSystemLayer::fileExists(pluginsPath))
{
pluginsPath = Ogre::FileSystemLayer::resolveBundlePath(OGRE_CONFIG_DIR "/plugins.cfg");
}
# endif
mRoot = OGRE_NEW Ogre::Root(pluginsPath, mFSLayer->getWritablePath("ogre.cfg"),
mFSLayer->getWritablePath("ogre.log"));
#endif
#ifdef OGRE_BITES_STATIC_PLUGINS
mStaticPluginLoader.load();
#endif
mOverlaySystem = OGRE_NEW Ogre::OverlaySystem();
}
bool ApplicationContextBase::oneTimeConfig()
{
if(mRoot->getAvailableRenderers().empty())
{
Ogre::LogManager::getSingleton().logError("No RenderSystems available");
return false;
}
#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID
mRoot->setRenderSystem(mRoot->getAvailableRenderers().front());
#else
if (!mRoot->restoreConfig()) {
return mRoot->showConfigDialog(OgreBites::getNativeConfigDialog());
}
#endif
return true;
}
void ApplicationContextBase::createDummyScene()
{
mWindows[0].render->removeAllViewports();
Ogre::SceneManager* sm = mRoot->createSceneManager("DefaultSceneManager", "DummyScene");
sm->addRenderQueueListener(mOverlaySystem);
Ogre::Camera* cam = sm->createCamera("DummyCamera");
sm->getRootSceneNode()->attachObject(cam);
mWindows[0].render->addViewport(cam);
#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM
// Initialize shader generator.
// Must be before resource loading in order to allow parsing extended material attributes.
if (!initialiseRTShaderSystem())
{
OGRE_EXCEPT(Ogre::Exception::ERR_FILE_NOT_FOUND,
"Shader Generator Initialization failed - Core shader libs path not found",
"ApplicationContextBase::createDummyScene");
}
mShaderGenerator->addSceneManager(sm);
#endif // OGRE_BUILD_COMPONENT_RTSHADERSYSTEM
}
void ApplicationContextBase::destroyDummyScene()
{
if(!mRoot->hasSceneManager("DummyScene"))
return;
Ogre::SceneManager* dummyScene = mRoot->getSceneManager("DummyScene");
#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM
mShaderGenerator->removeSceneManager(dummyScene);
#endif
dummyScene->removeRenderQueueListener(mOverlaySystem);
mWindows[0].render->removeAllViewports();
mRoot->destroySceneManager(dummyScene);
}
void ApplicationContextBase::enableShaderCache() const
{
Ogre::GpuProgramManager::getSingleton().setSaveMicrocodesToCache(true);
// Load for a package version of the shaders.
Ogre::String path = mFSLayer->getWritablePath(SHADER_CACHE_FILENAME);
std::ifstream inFile(path.c_str(), std::ios::binary);
if (!inFile.is_open())
{
Ogre::LogManager::getSingleton().logWarning("Could not open '"+path+"'");
return;
}
Ogre::LogManager::getSingleton().logMessage("Loading shader cache from '"+path+"'");
Ogre::DataStreamPtr istream(new Ogre::FileStreamDataStream(path, &inFile, false));
Ogre::GpuProgramManager::getSingleton().loadMicrocodeCache(istream);
}
void ApplicationContextBase::addInputListener(NativeWindowType* win, InputListener* lis)
{
mInputListeners.insert(std::make_pair(0, lis));
}
void ApplicationContextBase::removeInputListener(NativeWindowType* win, InputListener* lis)
{
mInputListeners.erase(std::make_pair(0, lis));
}
bool ApplicationContextBase::frameRenderingQueued(const Ogre::FrameEvent& evt)
{
for(const auto & li : mInputListeners) {
li.second->frameRendered(evt);
}
return true;
}
NativeWindowPair ApplicationContextBase::createWindow(const Ogre::String& name, Ogre::uint32 w, Ogre::uint32 h, Ogre::NameValuePairList miscParams)
{
NativeWindowPair ret = {NULL, NULL};
if(!mWindows.empty())
{
// additional windows should reuse the context
miscParams["currentGLContext"] = "true";
}
auto p = mRoot->getRenderSystem()->getRenderWindowDescription();
miscParams.insert(p.miscParams.begin(), p.miscParams.end());
p.miscParams = miscParams;
p.name = name;
if(w > 0 && h > 0)
{
p.width = w;
p.height= h;
}
ret.render = mRoot->createRenderWindow(p);
mWindows.push_back(ret);
WindowEventUtilities::_addRenderWindow(ret.render);
return ret;
}
void ApplicationContextBase::destroyWindow(const Ogre::String& name)
{
for (auto it = mWindows.begin(); it != mWindows.end(); ++it)
{
if (it->render->getName() != name)
continue;
_destroyWindow(*it);
mWindows.erase(it);
return;
}
OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, "No window named '"+name+"'");
}
void ApplicationContextBase::_destroyWindow(const NativeWindowPair& win)
{
#if !OGRE_BITES_HAVE_SDL
// remove window event listener before destroying it
WindowEventUtilities::_removeRenderWindow(win.render);
#endif
mRoot->destroyRenderTarget(win.render);
}
void ApplicationContextBase::_fireInputEvent(const Event& event, uint32_t windowID) const
{
Event scaled = event;
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
if (event.type == MOUSEMOTION)
{
// assumes all windows have the same scale
float viewScale = getRenderWindow()->getViewPointToPixelScale();
scaled.motion.x *= viewScale;
scaled.motion.y *= viewScale;
}
else if(event.type == MOUSEBUTTONDOWN || event.type == MOUSEBUTTONUP)
{
float viewScale = getRenderWindow()->getViewPointToPixelScale();
scaled.button.x *= viewScale;
scaled.button.y *= viewScale;
}
#endif
for(const auto & li : mInputListeners)
{
// gamepad events are not window specific
if(li.first != windowID && event.type <= TEXTINPUT) continue;
InputListener& l = *li.second;
switch (event.type)
{
case KEYDOWN:
l.keyPressed(event.key);
break;
case KEYUP:
l.keyReleased(event.key);
break;
case MOUSEBUTTONDOWN:
l.mousePressed(scaled.button);
break;
case MOUSEBUTTONUP:
l.mouseReleased(scaled.button);
break;
case MOUSEWHEEL:
l.mouseWheelRolled(event.wheel);
break;
case MOUSEMOTION:
l.mouseMoved(scaled.motion);
break;
case FINGERDOWN:
// for finger down we have to move the pointer first
l.touchMoved(event.tfinger);
l.touchPressed(event.tfinger);
break;
case FINGERUP:
l.touchReleased(event.tfinger);
break;
case FINGERMOTION:
l.touchMoved(event.tfinger);
break;
case TEXTINPUT:
l.textInput(event.text);
break;
case JOYAXISMOTION:
case CONTROLLERAXISMOTION:
l.axisMoved(event.axis);
break;
case CONTROLLERBUTTONDOWN:
l.buttonPressed(event.cbutton);
break;
case CONTROLLERBUTTONUP:
l.buttonReleased(event.cbutton);
break;
}
}
}
Ogre::String ApplicationContextBase::getDefaultMediaDir()
{
return Ogre::FileSystemLayer::resolveBundlePath(OGRE_MEDIA_DIR);
}
void ApplicationContextBase::locateResources()
{
auto& rgm = Ogre::ResourceGroupManager::getSingleton();
// load resource paths from config file
Ogre::ConfigFile cf;
Ogre::String resourcesPath = mFSLayer->getConfigFilePath("resources.cfg");
#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID
Ogre::Archive* apk = Ogre::ArchiveManager::getSingleton().load("", "APKFileSystem", true);
cf.load(apk->open(resourcesPath));
#else
if (Ogre::FileSystemLayer::fileExists(resourcesPath) || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN)
{
Ogre::LogManager::getSingleton().logMessage("Parsing '"+resourcesPath+"'");
cf.load(resourcesPath);
}
else
{
rgm.addResourceLocation(getDefaultMediaDir(), "FileSystem", Ogre::RGN_DEFAULT);
}
#endif
Ogre::String sec, type, arch;
// go through all specified resource groups
Ogre::ConfigFile::SettingsBySection_::const_iterator seci;
for(seci = cf.getSettingsBySection().begin(); seci != cf.getSettingsBySection().end(); ++seci) {
sec = seci->first;
const Ogre::ConfigFile::SettingsMultiMap& settings = seci->second;
Ogre::ConfigFile::SettingsMultiMap::const_iterator i;
// go through all resource paths
for (i = settings.begin(); i != settings.end(); i++)
{
type = i->first;
arch = i->second;
Ogre::StringUtil::trim(arch);
if (arch.empty() || arch[0] == '.')
{
// resolve relative path with regards to configfile
Ogre::String baseDir, filename;
Ogre::StringUtil::splitFilename(resourcesPath, filename, baseDir);
arch = baseDir + arch;
}
arch = Ogre::FileSystemLayer::resolveBundlePath(arch);
#if OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN
if((type == "Zip" || type == "FileSystem") && !Ogre::FileSystemLayer::fileExists(arch))
{
Ogre::LogManager::getSingleton().logWarning("resource location '"+arch+"' does not exist - skipping");
continue;
}
#endif
rgm.addResourceLocation(arch, type, sec);
}
}
if(rgm.getResourceLocationList(Ogre::RGN_INTERNAL).empty())
{
const auto& mediaDir = getDefaultMediaDir();
// add default locations
rgm.addResourceLocation(mediaDir + "/Main", "FileSystem", Ogre::RGN_INTERNAL);
#ifdef OGRE_BUILD_COMPONENT_TERRAIN
rgm.addResourceLocation(mediaDir + "/Terrain", "FileSystem", Ogre::RGN_INTERNAL);
#endif
#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM
rgm.addResourceLocation(mediaDir + "/RTShaderLib", "FileSystem", Ogre::RGN_INTERNAL);
#endif
}
}
void ApplicationContextBase::loadResources()
{
Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
}
void ApplicationContextBase::reconfigure(const Ogre::String &renderer, Ogre::NameValuePairList &options)
{
mNextRenderer = renderer;
Ogre::RenderSystem* rs = mRoot->getRenderSystemByName(renderer);
// set all given render system options
for (auto & option : options)
{
rs->setConfigOption(option.first, option.second);
}
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
// Need to save the config on iOS to make sure that changes are kept on disk
mRoot->saveConfig();
#endif
mRoot->queueEndRendering(); // break from render loop
}
void ApplicationContextBase::shutdown()
{
const auto& gpuMgr = Ogre::GpuProgramManager::getSingleton();
if (gpuMgr.getSaveMicrocodesToCache() && gpuMgr.isCacheDirty())
{
Ogre::String path = mFSLayer->getWritablePath(SHADER_CACHE_FILENAME);
std::fstream outFile(path.c_str(), std::ios::out | std::ios::binary);
if (outFile.is_open())
{
Ogre::LogManager::getSingleton().logMessage("Writing shader cache to "+path);
Ogre::DataStreamPtr ostream(new Ogre::FileStreamDataStream(path, &outFile, false));
gpuMgr.saveMicrocodeCache(ostream);
}
else
Ogre::LogManager::getSingleton().logWarning("Cannot open shader cache for writing "+path);
}
#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM
// Destroy the RT Shader System.
destroyRTShaderSystem();
#endif
for(auto it = mWindows.rbegin(); it != mWindows.rend(); ++it)
{
_destroyWindow(*it);
}
mWindows.clear();
if (mOverlaySystem)
{
OGRE_DELETE mOverlaySystem;
}
mInputListeners.clear();
}
void ApplicationContextBase::pollEvents()
{
// just avoid "window not responding"
WindowEventUtilities::messagePump();
}
}