-
Notifications
You must be signed in to change notification settings - Fork 44
/
Scene3D.cc
1499 lines (1277 loc) · 44 KB
/
Scene3D.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) 2017 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.
*
*/
#include "Scene3D.hh"
#include <algorithm>
#include <cmath>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include <ignition/common/Console.hh>
#include <ignition/common/MouseEvent.hh>
#include <ignition/plugin/Register.hh>
#include <ignition/common/MeshManager.hh>
#include <ignition/math/Vector2.hh>
#include <ignition/math/Vector3.hh>
// TODO(louise) Remove these pragmas once ign-rendering and ign-msgs
// are disabling the warnings
#ifdef _MSC_VER
#pragma warning(push, 0)
#endif
#include <ignition/msgs.hh>
#include <ignition/rendering/Camera.hh>
#include <ignition/rendering/OrbitViewController.hh>
#include <ignition/rendering/RayQuery.hh>
#include <ignition/rendering/RenderEngine.hh>
#include <ignition/rendering/RenderingIface.hh>
#include <ignition/rendering/Scene.hh>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include <ignition/transport/Node.hh>
#include "ignition/gui/Conversions.hh"
namespace ignition
{
namespace gui
{
namespace plugins
{
/// \brief Scene manager class for loading and managing objects in the scene
class SceneManager
{
/// \brief Constructor
public: SceneManager();
/// \brief Constructor
/// \param[in] _service Ign transport scene service name
/// \param[in] _poseTopic Ign transport pose topic name
/// \param[in] _deletionTopic Ign transport deletion topic name
/// \param[in] _sceneTopic Ign transport scene topic name
/// \param[in] _scene Pointer to the rendering scene
public: SceneManager(const std::string &_service,
const std::string &_poseTopic,
const std::string &_deletionTopic,
const std::string &_sceneTopic,
rendering::ScenePtr _scene);
/// \brief Load the scene manager
/// \param[in] _service Ign transport service name
/// \param[in] _poseTopic Ign transport pose topic name
/// \param[in] _deletionTopic Ign transport deletion topic name
/// \param[in] _sceneTopic Ign transport scene topic name
/// \param[in] _scene Pointer to the rendering scene
public: void Load(const std::string &_service,
const std::string &_poseTopic,
const std::string &_deletionTopic,
const std::string &_sceneTopic,
rendering::ScenePtr _scene);
/// \brief Make the scene service request and populate the scene
public: void Request();
/// \brief Update the scene based on pose msgs received
public: void Update();
/// \brief Callback function for the pose topic
/// \param[in] _msg Pose vector msg
private: void OnPoseVMsg(const msgs::Pose_V &_msg);
/// \brief Load the scene from a scene msg
/// \param[in] _msg Scene msg
private: void LoadScene(const msgs::Scene &_msg);
/// \brief Callback function for the request topic
/// \param[in] _msg Deletion message
private: void OnDeletionMsg(const msgs::UInt32_V &_msg);
/// \brief Load the scene from a scene msg
/// \param[in] _msg Scene msg
private: void OnSceneSrvMsg(const msgs::Scene &_msg, const bool result);
/// \brief Called when there's an entity is added to the scene
/// \param[in] _msg Scene msg
private: void OnSceneMsg(const msgs::Scene &_msg);
/// \brief Load the model from a model msg
/// \param[in] _msg Model msg
/// \return Model visual created from the msg
private: rendering::VisualPtr LoadModel(const msgs::Model &_msg);
/// \brief Load a link from a link msg
/// \param[in] _msg Link msg
/// \return Link visual created from the msg
private: rendering::VisualPtr LoadLink(const msgs::Link &_msg);
/// \brief Load a visual from a visual msg
/// \param[in] _msg Visual msg
/// \return Visual visual created from the msg
private: rendering::VisualPtr LoadVisual(const msgs::Visual &_msg);
/// \brief Load a geometry from a geometry msg
/// \param[in] _msg Geometry msg
/// \param[out] _scale Geometry scale that will be set based on msg param
/// \param[out] _localPose Additional local pose to be applied after the
/// visual's pose
/// \return Geometry object created from the msg
private: rendering::GeometryPtr LoadGeometry(const msgs::Geometry &_msg,
math::Vector3d &_scale, math::Pose3d &_localPose);
/// \brief Load a material from a material msg
/// \param[in] _msg Material msg
/// \return Material object created from the msg
private: rendering::MaterialPtr LoadMaterial(const msgs::Material &_msg);
/// \brief Load a light from a light msg
/// \param[in] _msg Light msg
/// \return Light object created from the msg
private: rendering::LightPtr LoadLight(const msgs::Light &_msg);
/// \brief Delete an entity
/// \param[in] _entity Entity to delete
private: void DeleteEntity(const unsigned int _entity);
//// \brief Ign-transport scene service name
private: std::string service;
//// \brief Ign-transport pose topic name
private: std::string poseTopic;
//// \brief Ign-transport deletion topic name
private: std::string deletionTopic;
//// \brief Ign-transport scene topic name
private: std::string sceneTopic;
//// \brief Pointer to the rendering scene
private: rendering::ScenePtr scene;
//// \brief Mutex to protect the pose msgs
private: std::mutex mutex;
/// \brief Map of entity id to pose
private: std::map<unsigned int, math::Pose3d> poses;
/// \brief Map of entity id to initial local poses
/// This is currently used to handle the normal vector in plane visuals. In
/// general, this can be used to store any local transforms between the
/// parent Visual and geometry.
private: std::map<unsigned int, math::Pose3d> localPoses;
/// \brief Map of visual id to visual pointers.
private: std::map<unsigned int, rendering::VisualPtr::weak_type> visuals;
/// \brief Map of light id to light pointers.
private: std::map<unsigned int, rendering::LightPtr::weak_type> lights;
/// Entities to be deleted
private: std::vector<unsigned int> toDeleteEntities;
/// \brief Keeps the a list of unprocessed scene messages
private: std::vector<msgs::Scene> sceneMsgs;
/// \brief Transport node for making service request and subscribing to
/// pose topic
private: ignition::transport::Node node;
};
/// \brief Private data class for IgnRenderer
class IgnRendererPrivate
{
/// \brief Flag to indicate if mouse event is dirty
public: bool mouseDirty = false;
/// \brief Mouse event
public: common::MouseEvent mouseEvent;
/// \brief Mouse move distance since last event.
public: math::Vector2d drag;
/// \brief Mutex to protect mouse events
public: std::mutex mutex;
/// \brief User camera
public: rendering::CameraPtr camera;
/// \brief Camera orbit controller
public: rendering::OrbitViewController viewControl;
/// \brief Ray query for mouse clicks
public: rendering::RayQueryPtr rayQuery;
/// \brief Scene requester to get scene info
public: SceneManager sceneManager;
/// \brief View control focus target
public: math::Vector3d target;
};
/// \brief Private data class for RenderWindowItem
class RenderWindowItemPrivate
{
/// \brief Keep latest mouse event
public: common::MouseEvent mouseEvent;
/// \brief Render thread
public : RenderThread *renderThread = nullptr;
//// \brief List of threads
public: static QList<QThread *> threads;
};
/// \brief Private data class for Scene3D
class Scene3DPrivate
{
};
}
}
}
using namespace ignition;
using namespace gui;
using namespace plugins;
QList<QThread *> RenderWindowItemPrivate::threads;
/////////////////////////////////////////////////
SceneManager::SceneManager()
{
}
/////////////////////////////////////////////////
SceneManager::SceneManager(const std::string &_service,
const std::string &_poseTopic,
const std::string &_deletionTopic,
const std::string &_sceneTopic,
rendering::ScenePtr _scene)
{
this->Load(_service, _poseTopic, _deletionTopic, _sceneTopic, _scene);
}
/////////////////////////////////////////////////
void SceneManager::Load(const std::string &_service,
const std::string &_poseTopic,
const std::string &_deletionTopic,
const std::string &_sceneTopic,
rendering::ScenePtr _scene)
{
this->service = _service;
this->poseTopic = _poseTopic;
this->deletionTopic = _deletionTopic;
this->sceneTopic = _sceneTopic;
this->scene = _scene;
}
/////////////////////////////////////////////////
void SceneManager::Request()
{
// wait for the service to be advertized
std::vector<transport::ServicePublisher> publishers;
const std::chrono::duration<double> sleepDuration{1.0};
const std::size_t tries = 30;
for (std::size_t i = 0; i < tries; ++i)
{
this->node.ServiceInfo(this->service, publishers);
if (publishers.size() > 0)
break;
std::this_thread::sleep_for(sleepDuration);
igndbg << "Waiting for service " << this->service << "\n";
}
if (publishers.empty() ||
!this->node.Request(this->service, &SceneManager::OnSceneSrvMsg, this))
{
ignerr << "Error making service request to " << this->service << std::endl;
}
}
/////////////////////////////////////////////////
void SceneManager::OnPoseVMsg(const msgs::Pose_V &_msg)
{
std::lock_guard<std::mutex> lock(this->mutex);
for (int i = 0; i < _msg.pose_size(); ++i)
{
math::Pose3d pose = msgs::Convert(_msg.pose(i));
// apply additional local poses if available
const auto it = this->localPoses.find(_msg.pose(i).id());
if (it != this->localPoses.end())
{
pose = pose * it->second;
}
this->poses[_msg.pose(i).id()] = pose;
}
}
/////////////////////////////////////////////////
void SceneManager::OnDeletionMsg(const msgs::UInt32_V &_msg)
{
std::lock_guard<std::mutex> lock(this->mutex);
std::copy(_msg.data().begin(), _msg.data().end(),
std::back_inserter(this->toDeleteEntities));
}
/////////////////////////////////////////////////
void SceneManager::Update()
{
// process msgs
std::lock_guard<std::mutex> lock(this->mutex);
for (const auto &msg : this->sceneMsgs)
{
this->LoadScene(msg);
}
this->sceneMsgs.clear();
for (const auto &entity : this->toDeleteEntities)
{
this->DeleteEntity(entity);
}
this->toDeleteEntities.clear();
for (auto pIt = this->poses.begin(); pIt != this->poses.end();)
{
auto vIt = this->visuals.find(pIt->first);
if (vIt != this->visuals.end())
{
auto visual = vIt->second.lock();
if (visual)
{
visual->SetLocalPose(pIt->second);
}
else
{
this->visuals.erase(vIt);
}
this->poses.erase(pIt++);
}
else
{
auto lIt = this->lights.find(pIt->first);
if (lIt != this->lights.end())
{
auto light = lIt->second.lock();
if (light)
{
light->SetLocalPose(pIt->second);
}
else
{
this->lights.erase(lIt);
}
this->poses.erase(pIt++);
}
else
{
++pIt;
}
}
}
// Note we are clearing the pose msgs here but later on we may need to
// consider the case where pose msgs arrive before scene/visual msgs
this->poses.clear();
}
/////////////////////////////////////////////////
void SceneManager::OnSceneMsg(const msgs::Scene &_msg)
{
std::lock_guard<std::mutex> lock(this->mutex);
this->sceneMsgs.push_back(_msg);
}
/////////////////////////////////////////////////
void SceneManager::OnSceneSrvMsg(const msgs::Scene &_msg, const bool result)
{
if (!result)
{
ignerr << "Error making service request to " << this->service
<< std::endl;
return;
}
{
std::lock_guard<std::mutex> lock(this->mutex);
this->sceneMsgs.push_back(_msg);
}
if (!this->poseTopic.empty())
{
if (!this->node.Subscribe(this->poseTopic, &SceneManager::OnPoseVMsg, this))
{
ignerr << "Error subscribing to pose topic: " << this->poseTopic
<< std::endl;
}
}
else
{
ignwarn << "The pose topic, set via <pose_topic>, for the Scene3D plugin "
<< "is missing or empty. Please set this topic so that the Scene3D "
<< "can receive and process pose information.\n";
}
if (!this->deletionTopic.empty())
{
if (!this->node.Subscribe(this->deletionTopic, &SceneManager::OnDeletionMsg,
this))
{
ignerr << "Error subscribing to deletion topic: " << this->deletionTopic
<< std::endl;
}
}
else
{
ignwarn << "The deletion topic, set via <deletion_topic>, for the "
<< "Scene3D plugin is missing or empty. Please set this topic so that "
<< "the Scene3D can receive and process deletion information.\n";
}
if (!this->sceneTopic.empty())
{
if (!this->node.Subscribe(
this->sceneTopic, &SceneManager::OnSceneMsg, this))
{
ignerr << "Error subscribing to scene topic: " << this->sceneTopic
<< std::endl;
}
}
else
{
ignwarn << "The scene topic, set via <scene_topic>, for the "
<< "Scene3D plugin is missing or empty. Please set this topic so that "
<< "the Scene3D can receive and process scene information.\n";
}
}
void SceneManager::LoadScene(const msgs::Scene &_msg)
{
rendering::VisualPtr rootVis = this->scene->RootVisual();
// load models
for (int i = 0; i < _msg.model_size(); ++i)
{
// Only add if it's not already loaded
if (this->visuals.find(_msg.model(i).id()) == this->visuals.end())
{
rendering::VisualPtr modelVis = this->LoadModel(_msg.model(i));
if (modelVis)
rootVis->AddChild(modelVis);
else
ignerr << "Failed to load model: " << _msg.model(i).name() << std::endl;
}
}
// load lights
for (int i = 0; i < _msg.light_size(); ++i)
{
if (this->lights.find(_msg.light(i).id()) == this->lights.end())
{
rendering::LightPtr light = this->LoadLight(_msg.light(i));
if (light)
rootVis->AddChild(light);
else
ignerr << "Failed to load light: " << _msg.light(i).name() << std::endl;
}
}
}
/////////////////////////////////////////////////
rendering::VisualPtr SceneManager::LoadModel(const msgs::Model &_msg)
{
rendering::VisualPtr modelVis = this->scene->CreateVisual();
if (_msg.has_pose())
modelVis->SetLocalPose(msgs::Convert(_msg.pose()));
this->visuals[_msg.id()] = modelVis;
// load links
for (int i = 0; i < _msg.link_size(); ++i)
{
rendering::VisualPtr linkVis = this->LoadLink(_msg.link(i));
if (linkVis)
modelVis->AddChild(linkVis);
else
ignerr << "Failed to load link: " << _msg.link(i).name() << std::endl;
}
// load nested models
for (int i = 0; i < _msg.model_size(); ++i)
{
rendering::VisualPtr nestedModelVis = this->LoadModel(_msg.model(i));
if (nestedModelVis)
modelVis->AddChild(nestedModelVis);
else
ignerr << "Failed to load nested model: " << _msg.model(i).name()
<< std::endl;
}
return modelVis;
}
/////////////////////////////////////////////////
rendering::VisualPtr SceneManager::LoadLink(const msgs::Link &_msg)
{
rendering::VisualPtr linkVis = this->scene->CreateVisual();
if (_msg.has_pose())
linkVis->SetLocalPose(msgs::Convert(_msg.pose()));
this->visuals[_msg.id()] = linkVis;
// load visuals
for (int i = 0; i < _msg.visual_size(); ++i)
{
rendering::VisualPtr visualVis = this->LoadVisual(_msg.visual(i));
if (visualVis)
linkVis->AddChild(visualVis);
else
ignerr << "Failed to load visual: " << _msg.visual(i).name() << std::endl;
}
// load lights
for (int i = 0; i < _msg.light_size(); ++i)
{
rendering::LightPtr light = this->LoadLight(_msg.light(i));
if (light)
linkVis->AddChild(light);
else
ignerr << "Failed to load light: " << _msg.light(i).name() << std::endl;
}
return linkVis;
}
/////////////////////////////////////////////////
rendering::VisualPtr SceneManager::LoadVisual(const msgs::Visual &_msg)
{
if (!_msg.has_geometry())
return rendering::VisualPtr();
rendering::VisualPtr visualVis = this->scene->CreateVisual();
this->visuals[_msg.id()] = visualVis;
math::Vector3d scale = math::Vector3d::One;
math::Pose3d localPose;
rendering::GeometryPtr geom =
this->LoadGeometry(_msg.geometry(), scale, localPose);
if (_msg.has_pose())
visualVis->SetLocalPose(msgs::Convert(_msg.pose()) * localPose);
else
visualVis->SetLocalPose(localPose);
if (geom)
{
// store the local pose
this->localPoses[_msg.id()] = localPose;
visualVis->AddGeometry(geom);
visualVis->SetLocalScale(scale);
// set material
rendering::MaterialPtr material{nullptr};
if (_msg.has_material())
{
material = this->LoadMaterial(_msg.material());
}
// Don't set a default material for meshes because they
// may have their own
// TODO(anyone) support overriding mesh material
else if (_msg.geometry().has_mesh())
{
material = geom->Material();
}
else
{
// create default material
material = this->scene->Material("ign-grey");
if (!material)
{
material = this->scene->CreateMaterial("ign-grey");
material->SetAmbient(0.3, 0.3, 0.3);
material->SetDiffuse(0.7, 0.7, 0.7);
material->SetSpecular(1.0, 1.0, 1.0);
material->SetRoughness(0.2f);
material->SetMetalness(1.0f);
}
}
material->SetTransparency(_msg.transparency());
// TODO(anyone) Get roughness and metalness from message instead
// of giving a default value.
material->SetRoughness(0.3f);
material->SetMetalness(0.3f);
geom->SetMaterial(material);
}
else
{
ignerr << "Failed to load geometry for visual: " << _msg.name()
<< std::endl;
}
return visualVis;
}
/////////////////////////////////////////////////
rendering::GeometryPtr SceneManager::LoadGeometry(const msgs::Geometry &_msg,
math::Vector3d &_scale, math::Pose3d &_localPose)
{
math::Vector3d scale = math::Vector3d::One;
math::Pose3d localPose = math::Pose3d::Zero;
rendering::GeometryPtr geom{nullptr};
if (_msg.has_box())
{
geom = this->scene->CreateBox();
if (_msg.box().has_size())
scale = msgs::Convert(_msg.box().size());
}
else if (_msg.has_cylinder())
{
geom = this->scene->CreateCylinder();
scale.X() = _msg.cylinder().radius() * 2;
scale.Y() = scale.X();
scale.Z() = _msg.cylinder().length();
}
else if (_msg.has_plane())
{
geom = this->scene->CreatePlane();
if (_msg.plane().has_size())
{
scale.X() = _msg.plane().size().x();
scale.Y() = _msg.plane().size().y();
}
if (_msg.plane().has_normal())
{
// Create a rotation for the plane mesh to account for the normal vector.
// The rotation is the angle between the +z(0,0,1) vector and the
// normal, which are both expressed in the local (Visual) frame.
math::Vector3d normal = msgs::Convert(_msg.plane().normal());
localPose.Rot().From2Axes(math::Vector3d::UnitZ, normal.Normalized());
}
}
else if (_msg.has_sphere())
{
geom = this->scene->CreateSphere();
scale.X() = _msg.sphere().radius() * 2;
scale.Y() = scale.X();
scale.Z() = scale.X();
}
else if (_msg.has_mesh())
{
if (_msg.mesh().filename().empty())
{
ignerr << "Mesh geometry missing filename" << std::endl;
return geom;
}
rendering::MeshDescriptor descriptor;
// Assume absolute path to mesh file
descriptor.meshName = _msg.mesh().filename();
ignition::common::MeshManager* meshManager =
ignition::common::MeshManager::Instance();
descriptor.mesh = meshManager->Load(descriptor.meshName);
geom = this->scene->CreateMesh(descriptor);
scale = msgs::Convert(_msg.mesh().scale());
}
else
{
ignerr << "Unsupported geometry type" << std::endl;
}
_scale = scale;
_localPose = localPose;
return geom;
}
/////////////////////////////////////////////////
rendering::MaterialPtr SceneManager::LoadMaterial(const msgs::Material &_msg)
{
rendering::MaterialPtr material = this->scene->CreateMaterial();
if (_msg.has_ambient())
{
material->SetAmbient(msgs::Convert(_msg.ambient()));
}
if (_msg.has_diffuse())
{
material->SetDiffuse(msgs::Convert(_msg.diffuse()));
}
if (_msg.has_specular())
{
material->SetDiffuse(msgs::Convert(_msg.specular()));
}
if (_msg.has_emissive())
{
material->SetEmissive(msgs::Convert(_msg.emissive()));
}
return material;
}
/////////////////////////////////////////////////
rendering::LightPtr SceneManager::LoadLight(const msgs::Light &_msg)
{
rendering::LightPtr light;
switch (_msg.type())
{
case msgs::Light_LightType_POINT:
light = this->scene->CreatePointLight();
break;
case msgs::Light_LightType_SPOT:
{
light = this->scene->CreateSpotLight();
rendering::SpotLightPtr spotLight =
std::dynamic_pointer_cast<rendering::SpotLight>(light);
spotLight->SetInnerAngle(_msg.spot_inner_angle());
spotLight->SetOuterAngle(_msg.spot_outer_angle());
spotLight->SetFalloff(_msg.spot_falloff());
break;
}
case msgs::Light_LightType_DIRECTIONAL:
{
light = this->scene->CreateDirectionalLight();
rendering::DirectionalLightPtr dirLight =
std::dynamic_pointer_cast<rendering::DirectionalLight>(light);
if (_msg.has_direction())
dirLight->SetDirection(msgs::Convert(_msg.direction()));
break;
}
default:
ignerr << "Light type not supported" << std::endl;
return light;
}
if (_msg.has_pose())
light->SetLocalPose(msgs::Convert(_msg.pose()));
if (_msg.has_diffuse())
light->SetDiffuseColor(msgs::Convert(_msg.diffuse()));
if (_msg.has_specular())
light->SetSpecularColor(msgs::Convert(_msg.specular()));
light->SetAttenuationConstant(_msg.attenuation_constant());
light->SetAttenuationLinear(_msg.attenuation_linear());
light->SetAttenuationQuadratic(_msg.attenuation_quadratic());
light->SetAttenuationRange(_msg.range());
light->SetCastShadows(_msg.cast_shadows());
this->lights[_msg.id()] = light;
return light;
}
/////////////////////////////////////////////////
void SceneManager::DeleteEntity(const unsigned int _entity)
{
if (this->visuals.find(_entity) != this->visuals.end())
{
auto visual = this->visuals[_entity].lock();
if (visual)
{
this->scene->DestroyVisual(visual, true);
}
this->visuals.erase(_entity);
}
else if (this->lights.find(_entity) != this->lights.end())
{
auto light = this->lights[_entity].lock();
if (light)
{
this->scene->DestroyLight(light, true);
}
this->lights.erase(_entity);
}
}
/////////////////////////////////////////////////
IgnRenderer::IgnRenderer()
: dataPtr(new IgnRendererPrivate)
{
}
/////////////////////////////////////////////////
IgnRenderer::~IgnRenderer()
{
}
/////////////////////////////////////////////////
void IgnRenderer::Render()
{
if (this->textureDirty)
{
this->dataPtr->camera->SetImageWidth(this->textureSize.width());
this->dataPtr->camera->SetImageHeight(this->textureSize.height());
this->dataPtr->camera->SetAspectRatio(this->textureSize.width() /
this->textureSize.height());
// setting the size should cause the render texture to be rebuilt
this->dataPtr->camera->PreRender();
this->textureId = this->dataPtr->camera->RenderTextureGLId();
this->textureDirty = false;
}
// update the scene
this->dataPtr->sceneManager.Update();
// view control
this->HandleMouseEvent();
// update and render to texture
this->dataPtr->camera->Update();
}
/////////////////////////////////////////////////
void IgnRenderer::HandleMouseEvent()
{
std::lock_guard<std::mutex> lock(this->dataPtr->mutex);
if (!this->dataPtr->mouseDirty)
return;
this->dataPtr->viewControl.SetCamera(this->dataPtr->camera);
if (this->dataPtr->mouseEvent.Type() == common::MouseEvent::SCROLL)
{
this->dataPtr->target =
this->ScreenToScene(this->dataPtr->mouseEvent.Pos());
this->dataPtr->viewControl.SetTarget(this->dataPtr->target);
double distance = this->dataPtr->camera->WorldPosition().Distance(
this->dataPtr->target);
double amount = -this->dataPtr->drag.Y() * distance / 5.0;
this->dataPtr->viewControl.Zoom(amount);
}
else
{
if (this->dataPtr->drag == math::Vector2d::Zero)
{
this->dataPtr->target = this->ScreenToScene(
this->dataPtr->mouseEvent.PressPos());
this->dataPtr->viewControl.SetTarget(this->dataPtr->target);
}
// Pan with left button
if (this->dataPtr->mouseEvent.Buttons() & common::MouseEvent::LEFT)
{
if (Qt::ShiftModifier == QGuiApplication::queryKeyboardModifiers())
this->dataPtr->viewControl.Orbit(this->dataPtr->drag);
else
this->dataPtr->viewControl.Pan(this->dataPtr->drag);
}
// Orbit with middle button
else if (this->dataPtr->mouseEvent.Buttons() & common::MouseEvent::MIDDLE)
{
this->dataPtr->viewControl.Orbit(this->dataPtr->drag);
}
else if (this->dataPtr->mouseEvent.Buttons() & common::MouseEvent::RIGHT)
{
double hfov = this->dataPtr->camera->HFOV().Radian();
double vfov = 2.0f * atan(tan(hfov / 2.0f) /
this->dataPtr->camera->AspectRatio());
double distance = this->dataPtr->camera->WorldPosition().Distance(
this->dataPtr->target);
double amount = ((-this->dataPtr->drag.Y() /
static_cast<double>(this->dataPtr->camera->ImageHeight()))
* distance * tan(vfov/2.0) * 6.0);
this->dataPtr->viewControl.Zoom(amount);
}
}
this->dataPtr->drag = 0;
this->dataPtr->mouseDirty = false;
}
/////////////////////////////////////////////////
void IgnRenderer::Initialize()
{
if (this->initialized)
return;
std::map<std::string, std::string> params;
params["useCurrentGLContext"] = "1";
auto engine = rendering::engine(this->engineName, params);
if (!engine)
{
ignerr << "Engine [" << this->engineName << "] is not supported"
<< std::endl;
return;
}
// Scene
auto scene = engine->SceneByName(this->sceneName);
if (!scene)
{
igndbg << "Create scene [" << this->sceneName << "]" << std::endl;
scene = engine->CreateScene(this->sceneName);
scene->SetAmbientLight(this->ambientLight);
scene->SetBackgroundColor(this->backgroundColor);
}
auto root = scene->RootVisual();
// Camera
this->dataPtr->camera = scene->CreateCamera();
root->AddChild(this->dataPtr->camera);
this->dataPtr->camera->SetLocalPose(this->cameraPose);
this->dataPtr->camera->SetImageWidth(this->textureSize.width());
this->dataPtr->camera->SetImageHeight(this->textureSize.height());
this->dataPtr->camera->SetAntiAliasing(8);
this->dataPtr->camera->SetHFOV(M_PI * 0.5);
// setting the size and calling PreRender should cause the render texture to
// be rebuilt
this->dataPtr->camera->PreRender();
this->textureId = this->dataPtr->camera->RenderTextureGLId();
// Make service call to populate scene
if (!this->sceneService.empty())
{
this->dataPtr->sceneManager.Load(this->sceneService, this->poseTopic,
this->deletionTopic, this->sceneTopic,
scene);
this->dataPtr->sceneManager.Request();
}
// Ray Query
this->dataPtr->rayQuery = this->dataPtr->camera->Scene()->CreateRayQuery();
this->initialized = true;
}
/////////////////////////////////////////////////
void IgnRenderer::Destroy()
{
auto engine = rendering::engine(this->engineName);
if (!engine)
return;
auto scene = engine->SceneByName(this->sceneName);
if (!scene)
return;
scene->DestroySensor(this->dataPtr->camera);
// If that was the last sensor, destroy scene
if (scene->SensorCount() == 0)
{
igndbg << "Destroy scene [" << scene->Name() << "]" << std::endl;
engine->DestroyScene(scene);
// TODO(anyone) If that was the last scene, terminate engine?
}
}
/////////////////////////////////////////////////
void IgnRenderer::NewMouseEvent(const common::MouseEvent &_e,
const math::Vector2d &_drag)
{
std::lock_guard<std::mutex> lock(this->dataPtr->mutex);
this->dataPtr->mouseEvent = _e;
this->dataPtr->drag += _drag;
this->dataPtr->mouseDirty = true;
}
/////////////////////////////////////////////////
math::Vector3d IgnRenderer::ScreenToScene(
const math::Vector2i &_screenPos) const