-
Notifications
You must be signed in to change notification settings - Fork 51
/
Ogre2RenderEngine.cc
1483 lines (1289 loc) · 43.4 KB
/
Ogre2RenderEngine.cc
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2018 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifdef _WIN32
// Ensure that Winsock2.h is included before Windows.h, which can get
// pulled in by anybody (e.g., Boost).
#include <Winsock2.h>
#endif
#include <gz/common/Console.hh>
#include <gz/common/Filesystem.hh>
#include <gz/common/Util.hh>
#include <gz/plugin/Register.hh>
#include "gz/rendering/GraphicsAPI.hh"
#include "gz/rendering/InstallationDirectories.hh"
#include "gz/rendering/RenderEngineManager.hh"
#include "gz/rendering/ogre2/Ogre2Includes.hh"
#include "gz/rendering/ogre2/Ogre2NativeWindow.hh"
#include "gz/rendering/ogre2/Ogre2RenderEngine.hh"
#include "gz/rendering/ogre2/Ogre2RenderTypes.hh"
#include "gz/rendering/ogre2/Ogre2Scene.hh"
#include "gz/rendering/ogre2/Ogre2Storage.hh"
#include "Ogre2GzHlmsPbsPrivate.hh"
#include "Ogre2GzHlmsTerraPrivate.hh"
#include "Ogre2GzHlmsUnlitPrivate.hh"
#ifdef OGRE_BUILD_RENDERSYSTEM_VULKAN
# include "vulkan/vulkan_core.h"
// Deal with old vulkan headers causing build errors
# ifndef VK_NV_device_generated_commands
# define VK_ACCESS_COMMAND_PREPROCESS_READ_BIT_NV 0x00020000
# endif
# define VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_KHR 0x00200000
// Needed headers to receive an external Vulkan device from Qt
// and inject it into OgreNext
# include "RenderSystems/Vulkan/OgreVulkanDevice.h"
# include "gz/rendering/RenderEngineVulkanExternalDeviceStructs.hh"
#endif
#include "Ogre2GzHlmsSphericalClipMinDistance.hh"
#include "Terra/Hlms/OgreHlmsTerra.h"
#include "Terra/Hlms/PbsListener/OgreHlmsPbsTerraShadows.h"
#include "Terra/TerraWorkspaceListener.h"
#if HAVE_GLX
# include <X11/Xlib.h>
# include <X11/Xutil.h>
# include <GL/glx.h>
# include <GL/glxext.h>
#endif
#if HAVE_EGL
#include <EGL/egl.h>
#endif
#if defined(__APPLE__)
#include <OpenGL/CGLCurrent.h>
#endif
class GZ_RENDERING_OGRE2_HIDDEN
gz::rendering::Ogre2RenderEnginePrivate
{
#if HAVE_GLX
public: GLXFBConfig* dummyFBConfigs = nullptr;
#endif
/// \brief The graphics API to use
public: gz::rendering::GraphicsAPI graphicsAPI{GraphicsAPI::OPENGL};
/// \brief A list of supported fsaa levels
public: std::vector<unsigned int> fsaaLevels;
/// \brief Controls Hlms customizations for both PBS and Unlit
public: gz::rendering::Ogre2GzHlmsSphericalClipMinDistance
sphericalClipMinDistance;
/// \brief Pbs listener that adds terra shadows
public: std::unique_ptr<Ogre::HlmsPbsTerraShadows> hlmsPbsTerraShadows;
/// \brief Listener that needs to be in every workspace
/// that wants terrain to cast shadows from spot and point lights
public: std::unique_ptr<Ogre::TerraWorkspaceListener> terraWorkspaceListener;
/// \brief Custom PBS modifications
public: Ogre::Ogre2GzHlmsPbs *gzHlmsPbs{nullptr};
/// \brief Custom Unlit modifications
public: Ogre::Ogre2GzHlmsUnlit *gzHlmsUnlit{nullptr};
/// \brief Custom Terra modifications
public: Ogre::Ogre2GzHlmsTerra *gzHlmsTerra{nullptr};
#ifdef OGRE_BUILD_RENDERSYSTEM_VULKAN
/// \brief Needed to receive an external Vulkan device from Qt
/// and inject it into OgreNext.
///
/// TODO(anyone): This struct doesn't need to live forever.
/// It only needs to live until Root::loadPlugin( "RenderSystem_Vulkan" )
/// is called.
public: Ogre::VulkanExternalInstance vkExternalInstance{};
/// \brief Needed to receive an external Vulkan device from Qt
/// and inject it into OgreNext.
///
/// TODO(anyone): This struct doesn't need to live forever.
/// It only needs to live until the first Root::createRenderWindow
/// is called.
public: Ogre::VulkanExternalDevice vkExternalDevice{};
#endif
};
using namespace gz;
using namespace rendering;
//////////////////////////////////////////////////
Ogre2RenderEnginePlugin::Ogre2RenderEnginePlugin()
{
}
//////////////////////////////////////////////////
std::string Ogre2RenderEnginePlugin::Name() const
{
return Ogre2RenderEngine::Instance()->Name();
}
//////////////////////////////////////////////////
RenderEngine *Ogre2RenderEnginePlugin::Engine() const
{
return Ogre2RenderEngine::Instance();
}
//////////////////////////////////////////////////
Ogre2RenderEngine::Ogre2RenderEngine() :
dataPtr(new Ogre2RenderEnginePrivate)
{
this->dummyDisplay = nullptr;
this->dummyContext = 0;
this->dummyWindowId = 0;
std::string ogrePath = std::string(OGRE2_RESOURCE_PATH);
std::vector<std::string> paths = common::split(ogrePath, ":");
for (const auto &path : paths)
this->ogrePaths.push_back(path);
const char *env = std::getenv("OGRE2_RESOURCE_PATH");
if (env)
{
paths = common::split(std::string(env), ":");
for (const auto &path : paths)
this->ogrePaths.push_back(path);
}
}
//////////////////////////////////////////////////
Ogre::Window * Ogre2RenderEngine::OgreWindow() const
{
return this->window;
}
//////////////////////////////////////////////////
Ogre2RenderEngine::~Ogre2RenderEngine()
{
}
//////////////////////////////////////////////////
void Ogre2RenderEngine::Destroy()
{
BaseRenderEngine::Destroy();
if (this->scenes)
{
this->scenes->RemoveAll();
}
delete this->ogreOverlaySystem;
this->ogreOverlaySystem = nullptr;
this->dataPtr->hlmsPbsTerraShadows.reset();
if (this->ogreRoot)
{
// Clean up any textures that may still be in flight.
Ogre::TextureGpuManager *mgr =
this->ogreRoot->getRenderSystem()->getTextureGpuManager();
auto entries = mgr->getEntries();
for (auto& [name, entry] : entries)
{
if (entry.resourceGroup == "General" && !entry.destroyRequested)
mgr->destroyTexture(entry.texture);
}
try
{
// TODO(anyone): do we need to catch segfault on delete?
delete this->ogreRoot;
}
catch (...)
{
gzerr << "Error deleting ogre root " << std::endl;
}
this->ogreRoot = nullptr;
}
delete this->ogreLogManager;
this->ogreLogManager = nullptr;
#if HAVE_GLX
if (this->dummyDisplay)
{
Display *x11Display = static_cast<Display*>(this->dummyDisplay);
if (this->dummyContext)
{
GLXContext x11Context = static_cast<GLXContext>(this->dummyContext);
glXDestroyContext(x11Display, x11Context);
this->dummyContext = nullptr;
}
XDestroyWindow(x11Display, this->dummyWindowId);
XCloseDisplay(x11Display);
this->dummyDisplay = nullptr;
if (this->dataPtr->dummyFBConfigs)
{
XFree(this->dataPtr->dummyFBConfigs);
this->dataPtr->dummyFBConfigs = nullptr;
}
}
#endif
#if HAVE_EGL
// release egl per-thread state otherwise this causes a crash on exit if
// ogre is created and deleted in a thread
// Do this only if we are using GL
if (this->dataPtr->graphicsAPI == GraphicsAPI::OPENGL)
eglReleaseThread();
#endif
}
//////////////////////////////////////////////////
bool Ogre2RenderEngine::IsEnabled() const
{
return BaseRenderEngine::IsEnabled();
}
//////////////////////////////////////////////////
std::string Ogre2RenderEngine::Name() const
{
return "ogre2";
}
//////////////////////////////////////////////////
void Ogre2RenderEngine::AddResourcePath(const std::string &_uri)
{
if (_uri == "__default__" || _uri.empty())
return;
std::string path = common::findFilePath(_uri);
if (path.empty())
{
gzerr << "URI doesn't exist[" << _uri << "]\n";
return;
}
this->resourcePaths.push_back(path);
try
{
if (!Ogre::ResourceGroupManager::getSingleton().resourceLocationExists(
path, "General"))
{
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
path, "FileSystem", "General", true);
Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup(
"General", false);
// Parse all material files in the path if any exist
if (common::isDirectory(path))
{
std::vector<std::string> paths;
common::DirIter endIter;
for (common::DirIter dirIter(path); dirIter != endIter; ++dirIter)
{
paths.push_back(*dirIter);
}
std::sort(paths.begin(), paths.end());
// Iterate over all the models in the current gz-rendering path
for (auto dIter = paths.begin(); dIter != paths.end(); ++dIter)
{
std::string fullPath = *dIter;
std::string matExtension = fullPath.substr(fullPath.size()-9);
if (matExtension == ".material")
{
Ogre::DataStreamPtr stream =
Ogre::ResourceGroupManager::getSingleton().openResource(
fullPath, "General");
// There is a material file under there somewhere, read the thing in
try
{
Ogre::MaterialManager::getSingleton().parseScript(
stream, "General");
Ogre::MaterialPtr matPtr =
Ogre::MaterialManager::getSingleton().getByName(
fullPath);
if (!matPtr.isNull())
{
// is this necessary to do here? Someday try it without
matPtr->compile();
matPtr->load();
}
}
catch(Ogre::Exception&)
{
gzerr << "Unable to parse material file[" << fullPath << "]\n";
}
stream->close();
}
}
}
}
}
catch(Ogre::Exception &)
{
gzerr << "Unable to load Ogre Resources.\nMake sure the"
"resources path in the world file is set correctly." << std::endl;
}
}
//////////////////////////////////////////////////
Ogre::Root *Ogre2RenderEngine::OgreRoot() const
{
return this->ogreRoot;
}
//////////////////////////////////////////////////
ScenePtr Ogre2RenderEngine::CreateSceneImpl(unsigned int _id,
const std::string &_name)
{
Ogre2ScenePtr scene = Ogre2ScenePtr(new Ogre2Scene(_id, _name));
this->scenes->Add(scene);
return scene;
}
//////////////////////////////////////////////////
SceneStorePtr Ogre2RenderEngine::Scenes() const
{
return this->scenes;
}
//////////////////////////////////////////////////
bool Ogre2RenderEngine::LoadImpl(
const std::map<std::string, std::string> &_params)
{
// parse params
auto it = _params.find("useCurrentGLContext");
if (it != _params.end())
std::istringstream(it->second) >> this->useCurrentGLContext;
it = _params.find("headless");
if (it != _params.end())
std::istringstream(it->second) >> this->isHeadless;
it = _params.find("winID");
if (it != _params.end())
std::istringstream(it->second) >> this->winID;
it = _params.find("metal");
if (it != _params.end())
{
bool useMetal;
std::istringstream(it->second) >> useMetal;
if(useMetal)
this->dataPtr->graphicsAPI = GraphicsAPI::METAL;
}
#ifdef OGRE_BUILD_RENDERSYSTEM_VULKAN
this->dataPtr->vkExternalInstance.instance = nullptr;
this->dataPtr->vkExternalDevice.physicalDevice = nullptr;
this->dataPtr->vkExternalDevice.device = nullptr;
this->dataPtr->vkExternalDevice.graphicsQueue = nullptr;
this->dataPtr->vkExternalDevice.presentQueue = nullptr;
#endif
it = _params.find("vulkan");
if (it != _params.end())
{
bool useVulkan;
std::istringstream(it->second) >> useVulkan;
if(useVulkan)
{
this->dataPtr->graphicsAPI = GraphicsAPI::VULKAN;
#ifdef OGRE_BUILD_RENDERSYSTEM_VULKAN
it = _params.find("external_instance");
if (it != _params.end())
{
auto *gzExternalInstance =
reinterpret_cast<const GzVulkanExternalInstance *>(
Ogre::StringConverter::parseUnsignedLong(it->second));
this->dataPtr->vkExternalInstance.instance =
gzExternalInstance->instance;
// This works as long as std::vector memory is actually contiguous
this->dataPtr->vkExternalInstance.instanceLayers.appendPOD(
&*gzExternalInstance->instanceLayers.begin(),
&*gzExternalInstance->instanceLayers.end());
this->dataPtr->vkExternalInstance.instanceExtensions.appendPOD(
&*gzExternalInstance->instanceExtensions.begin(),
&*gzExternalInstance->instanceExtensions.end());
}
it = _params.find("external_device");
if (it != _params.end())
{
auto *gzExternalDevice =
reinterpret_cast<const GzVulkanExternalDevice *>(
Ogre::StringConverter::parseUnsignedLong(it->second));
this->dataPtr->vkExternalDevice.physicalDevice =
gzExternalDevice->physicalDevice;
this->dataPtr->vkExternalDevice.device = gzExternalDevice->device;
this->dataPtr->vkExternalDevice.graphicsQueue =
gzExternalDevice->graphicsQueue;
this->dataPtr->vkExternalDevice.presentQueue =
gzExternalDevice->presentQueue;
// This works as long as std::vector memory is actually contiguous
this->dataPtr->vkExternalDevice.deviceExtensions.appendPOD(
&*gzExternalDevice->deviceExtensions.begin(),
&*gzExternalDevice->deviceExtensions.end());
}
#endif
}
}
try
{
this->LoadAttempt();
this->loaded = true;
return true;
}
catch (Ogre::Exception &ex)
{
gzerr << ex.what() << std::endl;
return false;
}
catch (...)
{
gzerr << "Failed to load render-engine" << std::endl;
return false;
}
}
//////////////////////////////////////////////////
bool Ogre2RenderEngine::InitImpl()
{
try
{
this->InitAttempt();
return true;
}
catch (...)
{
gzerr << "Failed to initialize render-engine" << std::endl;
gzerr << "Please see the troubleshooting page for possible fixes: "
<< "https://gazebosim.org/docs/fortress/troubleshooting"
<< std::endl;
return false;
}
}
//////////////////////////////////////////////////
void Ogre2RenderEngine::LoadAttempt()
{
this->CreateLogger();
if (!this->useCurrentGLContext &&
(this->dataPtr->graphicsAPI == GraphicsAPI::OPENGL ||
this->dataPtr->graphicsAPI == GraphicsAPI::VULKAN))
{
this->CreateContext();
}
this->CreateRoot();
this->CreateOverlay();
this->LoadPlugins();
this->CreateRenderSystem();
this->ogreRoot->initialise(false);
this->CreateRenderWindow();
this->CreateResources();
}
//////////////////////////////////////////////////
void Ogre2RenderEngine::CreateLogger()
{
// create log file path
std::string logPath;
common::env(GZ_HOMEDIR, logPath);
logPath = common::joinPaths(logPath, ".gz", "rendering");
common::createDirectories(logPath);
logPath = common::joinPaths(logPath, "ogre2.log");
// create actual log
this->ogreLogManager = new Ogre::LogManager();
this->ogreLogManager->createLog(logPath, true, false, false);
}
//////////////////////////////////////////////////
void Ogre2RenderEngine::CreateContext()
{
#ifdef OGRE_BUILD_RENDERSYSTEM_VULKAN
if (this->dataPtr->vkExternalInstance.instance)
{
return;
}
#endif
#if !defined(__APPLE__) && !defined(_WIN32)
if (this->Headless())
{
// Nothing to do
return;
}
#if HAVE_GLX
// create X11 display
this->dummyDisplay = XOpenDisplay(0);
Display *x11Display = static_cast<Display*>(this->dummyDisplay);
if (!this->dummyDisplay)
{
// Not able to create a Xwindow, try to run in headless mode
this->SetHeadless(true);
gzwarn << "Unable to open display: " << XDisplayName(0)
<< ". Trying to run in headless mode." << std::endl;
return;
}
// create X11 visual
int screenId = DefaultScreen(x11Display);
int attributeList[] = {
GLX_RENDER_TYPE, GLX_RGBA_BIT,
GLX_DOUBLEBUFFER, True,
GLX_DEPTH_SIZE, 16,
GLX_STENCIL_SIZE, 8,
None
};
if (this->dataPtr->graphicsAPI == GraphicsAPI::OPENGL)
{
int nelements = 0;
this->dataPtr->dummyFBConfigs =
glXChooseFBConfig(x11Display, screenId, attributeList, &nelements);
if (nelements <= 0)
{
gzerr << "Unable to create glx fbconfig" << std::endl;
return;
}
}
// create X11 context
this->dummyWindowId = XCreateSimpleWindow(x11Display,
RootWindow(this->dummyDisplay, screenId), 0, 0, 1, 1, 0, 0, 0);
if (this->dataPtr->graphicsAPI == GraphicsAPI::OPENGL)
{
PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = 0;
glXCreateContextAttribsARB =
(PFNGLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress(
(const GLubyte *)"glXCreateContextAttribsARB");
if (glXCreateContextAttribsARB)
{
int contextAttribs[] = {
GLX_CONTEXT_MAJOR_VERSION_ARB, 3, //
GLX_CONTEXT_MINOR_VERSION_ARB, 3, //
None //
};
// clang-format on
this->dummyContext =
glXCreateContextAttribsARB(x11Display, this->dataPtr->dummyFBConfigs[0],
nullptr, 1, contextAttribs);
}
else
{
gzwarn << "glXCreateContextAttribsARB() not found" << std::endl;
this->dummyContext =
glXCreateNewContext(x11Display, this->dataPtr->dummyFBConfigs[0],
GLX_RGBA_TYPE, nullptr, 1);
}
GLXContext x11Context = static_cast<GLXContext>(this->dummyContext);
if (!this->dummyContext)
{
gzerr << "Unable to create glx context" << std::endl;
return;
}
// select X11 context
glXMakeCurrent(x11Display, this->dummyWindowId, x11Context);
}
#endif
#endif
}
//////////////////////////////////////////////////
void Ogre2RenderEngine::CreateRoot()
{
try
{
this->ogreRoot = new Ogre::Root("", "", "");
}
catch (Ogre::Exception &)
{
gzerr << "Unable to create Ogre root" << std::endl;
}
}
//////////////////////////////////////////////////
void Ogre2RenderEngine::CreateOverlay()
{
this->ogreOverlaySystem = new Ogre::v1::OverlaySystem();
}
//////////////////////////////////////////////////
void Ogre2RenderEngine::LoadPlugins()
{
for (auto iter = this->ogrePaths.begin();
iter != this->ogrePaths.end(); ++iter)
{
std::string path(*iter);
if (!common::isDirectory(path))
continue;
struct PluginName
{
std::string name;
bool bOptional;
};
std::vector<PluginName> plugins;
#ifdef __APPLE__
std::string extension = ".dylib";
#elif _WIN32
std::string extension = ".dll";
#else
std::string extension = ".so";
#endif
std::string p = common::joinPaths(path, "RenderSystem_GL3Plus");
plugins.push_back({ p, false });
p = common::joinPaths(path, "Plugin_ParticleFX");
plugins.push_back({ p, false });
if (this->dataPtr->graphicsAPI == GraphicsAPI::VULKAN)
{
p = common::joinPaths(path, "RenderSystem_Vulkan");
// Vulkan is very recent, so mark it as optional, as it
// can easily fail to load
plugins.push_back({ p, true });
}
if (this->dataPtr->graphicsAPI == GraphicsAPI::METAL)
{
p = common::joinPaths(path, "RenderSystem_Metal");
plugins.push_back({ p, false });
}
Ogre::NameValuePairList pluginParams;
for (std::vector<PluginName>::iterator piter = plugins.begin();
piter != plugins.end(); ++piter)
{
// check if plugin library exists
#ifndef DEBUG
std::string filename = piter->name + extension;
#else
std::string filename = piter->name + "_d" + extension;
#endif
if (!common::exists(filename))
{
filename = filename + "." + std::string(OGRE2_VERSION);
if (!common::exists(filename))
{
if (piter->name.find("RenderSystem") != std::string::npos)
{
gzerr << "Unable to find Ogre Plugin[" << piter->name
<< "]. Rendering will not be possible."
<< "Make sure you have installed OGRE properly.\n";
}
continue;
}
}
// load the plugin
try
{
pluginParams.clear();
#ifdef OGRE_BUILD_RENDERSYSTEM_VULKAN
if (this->dataPtr->vkExternalInstance.instance &&
filename.find("RenderSystem_Vulkan") != std::string::npos)
{
pluginParams["external_instance"] = std::to_string(
reinterpret_cast<uintptr_t>(&this->dataPtr->vkExternalInstance));
}
#endif
#if HAVE_GLX
if (filename.find("RenderSystem_GL3Plus") != std::string::npos)
{
// Store the current GLX context in case OGRE plugin init changes it
const auto context = glXGetCurrentContext();
const auto display = glXGetCurrentDisplay();
const auto drawable = glXGetCurrentDrawable();
this->ogreRoot->loadPlugin(filename, piter->bOptional, &pluginParams);
// Restore GLX context
glXMakeCurrent(display, drawable, context);
}
else
#endif
{
// Load the plugin into OGRE
this->ogreRoot->loadPlugin(filename, piter->bOptional, &pluginParams);
}
}
catch(Ogre::Exception &)
{
if (piter->name.find("RenderSystem") != std::string::npos)
{
gzerr << "Unable to load Ogre Plugin[" << piter->name
<< "]. Rendering will not be possible."
<< "Make sure you have installed OGRE properly.\n";
}
}
}
}
}
//////////////////////////////////////////////////
void Ogre2RenderEngine::CreateRenderSystem()
{
Ogre::RenderSystem *renderSys;
const Ogre::RenderSystemList *rsList;
rsList = &(this->ogreRoot->getAvailableRenderers());
std::string targetRenderSysName("OpenGL 3+ Rendering Subsystem");
if (this->dataPtr->graphicsAPI == GraphicsAPI::VULKAN)
{
targetRenderSysName = "Vulkan Rendering Subsystem";
}
if (this->dataPtr->graphicsAPI == GraphicsAPI::METAL)
{
targetRenderSysName = "Metal Rendering Subsystem";
}
int c = 0;
renderSys = nullptr;
{
bool bContinue = false;
do
{
if (c == static_cast<int>(rsList->size()))
break;
renderSys = rsList->at(c);
c++;
// cpplint has a false positive when extending a while call to multiple
// lines (it thinks the while loop is empty), so we must put the whole
// while statement on one line and add NOLINT at the end so that cpplint
// doesn't complain about the line being too long
bContinue =
renderSys && renderSys->getName().compare(targetRenderSysName) != 0;
} while (bContinue);
}
if (renderSys == nullptr)
{
gzerr << "unable to find " << targetRenderSysName << ". OGRE is probably "
"installed incorrectly. Double check the OGRE cmake output, "
"and make sure OpenGL is enabled." << std::endl;
}
if (!this->Headless())
{
// We operate in windowed mode
renderSys->setConfigOption("Full Screen", "No");
if (this->dataPtr->graphicsAPI == GraphicsAPI::OPENGL)
{
/// We used to allow the user to set the RTT mode to PBuffer,
/// FBO, or Copy.
/// Copy is slow, and there doesn't seem to be a good reason to use it
/// PBuffer limits the size of the renderable area of the RTT to the
/// size of the first window created.
/// FBO is the only good option
renderSys->setConfigOption("RTT Preferred Mode", "FBO");
}
}
else
{
try
{
// This may fail if Ogre was *only* build with EGL support, but in that
// case we can ignore the error
renderSys->setConfigOption( "Interface", "Headless EGL / PBuffer" );
}
catch( Ogre::Exception & )
{
std::cerr << "Unable to setup EGL (headless mode)" << '\n';
}
}
// get all supported fsaa values
Ogre::ConfigOptionMap configMap = renderSys->getConfigOptions();
auto fsaaOoption = configMap.find("FSAA");
if (fsaaOoption != configMap.end())
{
auto values = (*fsaaOoption).second.possibleValues;
for (auto const &str : values)
{
int value = 0;
try
{
value = std::stoi(str);
}
catch(...)
{
continue;
}
this->dataPtr->fsaaLevels.push_back(value);
}
}
std::sort(this->dataPtr->fsaaLevels.begin(), this->dataPtr->fsaaLevels.end());
// check if target fsaa is supported
unsigned int fsaa = 0;
unsigned int targetFSAA = 4;
auto const it = std::find(this->dataPtr->fsaaLevels.begin(),
this->dataPtr->fsaaLevels.end(), targetFSAA);
if (it != this->dataPtr->fsaaLevels.end())
fsaa = targetFSAA;
renderSys->setConfigOption("FSAA", std::to_string(fsaa));
this->ogreRoot->setRenderSystem(renderSys);
}
void Ogre2RenderEngine::RegisterHlms()
{
const char *env = std::getenv("GZ_RENDERING_RESOURCE_PATH");
// TODO(CH3): Deprecated. Remove on tock.
if (!env)
{
env = std::getenv("IGN_RENDERING_RESOURCE_PATH");
if (env)
{
gzwarn << "Using deprecated environment variable "
<< "[IGN_RENDERING_RESOURCE_PATH]. Please use "
<< "[GZ_RENDERING_RESOURCE_PATH] instead." << std::endl;
}
}
std::string resourcePath = (env) ? std::string(env) :
gz::rendering::getResourcePath();
// install path
std::string mediaPath = common::joinPaths(resourcePath, "ogre2", "media");
if (!common::exists(mediaPath))
{
// src path
mediaPath = common::joinPaths(resourcePath, "ogre2", "src", "media");
}
// register PbsMaterial resources
Ogre::String rootHlmsFolder = mediaPath;
Ogre::String pbsCompositorFolder = common::joinPaths(
rootHlmsFolder, "2.0", "scripts", "Compositors");
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
pbsCompositorFolder, "FileSystem", "General");
Ogre::String commonMaterialFolder = common::joinPaths(
rootHlmsFolder, "2.0", "scripts", "materials", "Common");
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
commonMaterialFolder, "FileSystem", "General");
Ogre::String commonGLSLMaterialFolder = common::joinPaths(
rootHlmsFolder, "2.0", "scripts", "materials", "Common", "GLSL");
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
commonGLSLMaterialFolder, "FileSystem", "General");
Ogre::String terraMaterialFolder = common::joinPaths(
rootHlmsFolder, "2.0", "scripts", "materials", "Terra");
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
terraMaterialFolder, "FileSystem", "General");
Ogre::String terraGLSLMaterialFolder = common::joinPaths(
rootHlmsFolder, "2.0", "scripts", "materials", "Terra", "GLSL");
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
terraGLSLMaterialFolder, "FileSystem", "General");
if (this->dataPtr->graphicsAPI == GraphicsAPI::METAL)
{
Ogre::String commonMetalMaterialFolder = common::joinPaths(
rootHlmsFolder, "2.0", "scripts", "materials", "Common", "Metal");
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
commonMetalMaterialFolder, "FileSystem", "General");
Ogre::String terraMetalMaterialFolder = common::joinPaths(
rootHlmsFolder, "2.0", "scripts", "materials", "Terra", "Metal");
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
terraMetalMaterialFolder, "FileSystem", "General");
}
// The following code is taken from the registerHlms() function in ogre2
// samples framework
if (rootHlmsFolder.empty())
rootHlmsFolder = "./";
else if (*(rootHlmsFolder.end() - 1) != '/')
rootHlmsFolder += "/";
// At this point rootHlmsFolder should be a valid path to the Hlms data folder
// For retrieval of the paths to the different folders needed
Ogre::String mainFolderPath;
Ogre::StringVector libraryFoldersPaths;
Ogre::StringVector::const_iterator libraryFolderPathIt;
Ogre::StringVector::const_iterator libraryFolderPathEn;
Ogre::ArchiveManager &archiveManager = Ogre::ArchiveManager::getSingleton();
Ogre::Archive *customizationsArchiveLibrary =
archiveManager.load(common::joinPaths(rootHlmsFolder, "Hlms", "Gz"),
"FileSystem", true);
{
Ogre::Ogre2GzHlmsUnlit *hlmsUnlit = 0;
// Create & Register HlmsUnlit
// Get the path to all the subdirectories used by HlmsUnlit
Ogre::Ogre2GzHlmsUnlit::getDefaultPaths(mainFolderPath,
libraryFoldersPaths);
Ogre::Archive *archiveUnlit = archiveManager.load(
rootHlmsFolder + mainFolderPath, "FileSystem", true);
Ogre::ArchiveVec archiveUnlitLibraryFolders;
libraryFolderPathIt = libraryFoldersPaths.begin();
libraryFolderPathEn = libraryFoldersPaths.end();
while (libraryFolderPathIt != libraryFolderPathEn)
{
Ogre::Archive *archiveLibrary =
archiveManager.load(rootHlmsFolder + *libraryFolderPathIt,
"FileSystem", true);
archiveUnlitLibraryFolders.push_back(archiveLibrary);
++libraryFolderPathIt;
}
archiveUnlitLibraryFolders.push_back(customizationsArchiveLibrary);
// Create and register the unlit Hlms
hlmsUnlit = OGRE_NEW Ogre::Ogre2GzHlmsUnlit(
archiveUnlit, &archiveUnlitLibraryFolders,
&this->dataPtr->sphericalClipMinDistance);
Ogre::Root::getSingleton().getHlmsManager()->registerHlms(hlmsUnlit);
// disable writting debug output to disk
hlmsUnlit->setDebugOutputPath(false, false);
hlmsUnlit->setListener(hlmsUnlit);
this->dataPtr->gzHlmsUnlit = hlmsUnlit;
}
{
Ogre::Ogre2GzHlmsPbs *hlmsPbs = 0;
// Create & Register HlmsPbs
// Do the same for HlmsPbs:
Ogre::Ogre2GzHlmsPbs::GetDefaultPaths(mainFolderPath, libraryFoldersPaths);
Ogre::Archive *archivePbs = archiveManager.load(
rootHlmsFolder + mainFolderPath, "FileSystem", true);
// Get the library archive(s)
Ogre::ArchiveVec archivePbsLibraryFolders;