-
Notifications
You must be signed in to change notification settings - Fork 276
/
Scene3D.cc
3106 lines (2652 loc) · 95.3 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) 2019 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 <limits>
#include <map>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include <sdf/Link.hh>
#include <sdf/Model.hh>
#include <sdf/Root.hh>
#include <sdf/Visual.hh>
#include <ignition/common/Animation.hh>
#include <ignition/common/Console.hh>
#include <ignition/common/KeyFrame.hh>
#include <ignition/common/MeshManager.hh>
#include <ignition/common/Profiler.hh>
#include <ignition/common/Uuid.hh>
#include <ignition/common/VideoEncoder.hh>
#include <ignition/plugin/Register.hh>
#include <ignition/math/Vector2.hh>
#include <ignition/math/Vector3.hh>
#include <ignition/rendering/Image.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>
#include <ignition/rendering/TransformController.hh>
#include <ignition/transport/Node.hh>
#include <ignition/gui/Conversions.hh>
#include <ignition/gui/GuiEvents.hh>
#include <ignition/gui/Application.hh>
#include <ignition/gui/MainWindow.hh>
#include "ignition/gazebo/components/Name.hh"
#include "ignition/gazebo/components/RenderEngineGuiPlugin.hh"
#include "ignition/gazebo/components/World.hh"
#include "ignition/gazebo/EntityComponentManager.hh"
#include "ignition/gazebo/gui/GuiEvents.hh"
#include "ignition/gazebo/rendering/RenderUtil.hh"
Q_DECLARE_METATYPE(std::string)
namespace ignition
{
namespace gazebo
{
inline namespace IGNITION_GAZEBO_VERSION_NAMESPACE {
/// \brief Helper to store selection requests to be handled in the render
/// thread by `IgnRenderer::HandleEntitySelection`.
struct SelectionHelper
{
/// \brief Entity to be selected
Entity selectEntity{kNullEntity};
/// \brief Deselect all entities
bool deselectAll{false};
/// \brief True to send an event and notify all widgets
bool sendEvent{false};
};
//
/// \brief Helper class for animating a user camera to move to a target entity
/// todo(anyone) Move this functionality to rendering::Camera class in
/// ign-rendering3
class MoveToHelper
{
/// \brief Move the camera to look at the specified target
/// param[in] _camera Camera to be moved
/// param[in] _target Target to look at
/// param[in] _duration Duration of the move to animation, in seconds.
/// param[in] _onAnimationComplete Callback function when animation is
/// complete
public: void MoveTo(const rendering::CameraPtr &_camera,
const rendering::NodePtr &_target, double _duration,
std::function<void()> _onAnimationComplete);
/// \brief Move the camera to the specified pose.
/// param[in] _camera Camera to be moved
/// param[in] _target Pose to move to
/// param[in] _duration Duration of the move to animation, in seconds.
/// param[in] _onAnimationComplete Callback function when animation is
/// complete
public: void MoveTo(const rendering::CameraPtr &_camera,
const math::Pose3d &_target, double _duration,
std::function<void()> _onAnimationComplete);
/// \brief Move the camera to look at the specified target
/// param[in] _camera Camera to be moved
/// param[in] _direction The pose to assume relative to the entit(y/ies),
/// (0, 0, 0) indicates to return the camera back to the home pose
/// originally loaded in from the sdf.
/// param[in] _duration Duration of the move to animation, in seconds.
/// param[in] _onAnimationComplete Callback function when animation is
/// complete
public: void LookDirection(const rendering::CameraPtr &_camera,
const math::Vector3d &_direction, const math::Vector3d &_lookAt,
double _duration, std::function<void()> _onAnimationComplete);
/// \brief Add time to the animation.
/// \param[in] _time Time to add in seconds
public: void AddTime(double _time);
/// \brief Get whether the move to helper is idle, i.e. no animation
/// is being executed.
/// \return True if idle, false otherwise
public: bool Idle() const;
/// \brief Set the initial camera pose
/// param[in] _pose The init pose of the camera
public: void SetInitCameraPose(const math::Pose3d &_pose);
/// \brief Pose animation object
public: std::unique_ptr<common::PoseAnimation> poseAnim;
/// \brief Pointer to the camera being moved
public: rendering::CameraPtr camera;
/// \brief Callback function when animation is complete.
public: std::function<void()> onAnimationComplete;
/// \brief Initial pose of the camera used for view angles
public: math::Pose3d initCameraPose;
};
/// \brief Private data class for IgnRenderer
class IgnRendererPrivate
{
/// \brief Flag to indicate if mouse event is dirty
public: bool mouseDirty = false;
/// \brief Flag to indicate if hover event is dirty
public: bool hoverDirty = false;
/// \brief Mouse event
public: common::MouseEvent mouseEvent;
/// \brief Key event
public: common::KeyEvent keyEvent;
/// \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 Transform controller for models
public: rendering::TransformController transformControl;
/// \brief Transform space: local or world
public: rendering::TransformSpace transformSpace =
rendering::TransformSpace::TS_LOCAL;
/// \brief Transform mode: none, translation, rotation, or scale
public: rendering::TransformMode transformMode =
rendering::TransformMode::TM_NONE;
/// \brief True to record a video from the user camera
public: bool recordVideo = false;
/// \brief Video encoding format
public: std::string recordVideoFormat;
/// \brief Path to save the recorded video
public: std::string recordVideoSavePath;
/// \brief Target to move the user camera to
public: std::string moveToTarget;
/// \brief Helper object to move user camera
public: MoveToHelper moveToHelper;
/// \brief Helper object to select entities. Only the latest selection
/// request is kept.
public: SelectionHelper selectionHelper;
/// \brief Target to follow
public: std::string followTarget;
/// \brief Wait for follow target
public: bool followTargetWait = false;
/// \brief Offset of camera from taget being followed
public: math::Vector3d followOffset = math::Vector3d(-5, 0, 3);
/// \brief Flag to indicate the follow offset needs to be updated
public: bool followOffsetDirty = false;
/// \brief Follow P gain
public: double followPGain = 0.01;
/// \brief True follow the target at an offset that is in world frame,
/// false to follow in target's local frame
public: bool followWorldFrame = false;
/// \brief Flag for indicating whether we are in view angle mode or not
public: bool viewAngle = false;
/// \brief Flag for indicating whether we are spawning or not.
public: bool isSpawning = false;
/// \brief Flag for indicating whether the user is currently placing a
/// resource with the shapes plugin or not
public: bool isPlacing = false;
/// \brief The SDF string of the resource to be used with plugins that spawn
/// entities.
public: std::string spawnSdfString;
/// \brief Path of an SDF file, to be used with plugins that spawn entities.
public: std::string spawnSdfPath;
/// \brief The pose of the spawn preview.
public: ignition::math::Pose3d spawnPreviewPose =
ignition::math::Pose3d::Zero;
/// \brief The currently hovered mouse position in screen coordinates
public: math::Vector2i mouseHoverPos = math::Vector2i::Zero;
/// \brief The visual generated from the spawnSdfString / spawnSdfPath
public: rendering::VisualPtr spawnPreview = nullptr;
/// \brief A record of the ids currently used by the entity spawner
/// for easy deletion of visuals later
public: std::vector<Entity> previewIds;
/// \brief The pose set during a view angle button press that holds
/// the pose the camera should assume relative to the entit(y/ies).
/// The vector (0, 0, 0) indicates to return the camera back to the home
/// pose originally loaded from the sdf.
public: math::Vector3d viewAngleDirection = math::Vector3d::Zero;
/// \brief The pose set from the move to pose service.
public: std::optional<math::Pose3d> moveToPoseValue;
/// \brief Last move to animation time
public: std::chrono::time_point<std::chrono::system_clock> prevMoveToTime;
/// \brief Image from user camera
public: rendering::Image cameraImage;
/// \brief Video encoder
public: common::VideoEncoder videoEncoder;
/// \brief Ray query for mouse clicks
public: rendering::RayQueryPtr rayQuery;
/// \brief View control focus target
public: math::Vector3d target;
/// \brief Rendering utility
public: RenderUtil renderUtil;
/// \brief Transport node for making transform control requests
public: transport::Node node;
/// \brief Name of service for setting entity pose
public: std::string poseCmdService;
/// \brief Name of service for creating entity
public: std::string createCmdService;
/// \brief The starting world pose of a clicked visual.
public: ignition::math::Vector3d startWorldPos = math::Vector3d::Zero;
/// \brief Flag to keep track of world pose setting used
/// for button translating.
public: bool isStartWorldPosSet = false;
/// \brief Where the mouse left off - used to continue translating
/// smoothly when switching axes through keybinding and clicking
/// Updated on an x, y, or z, press or release and a mouse press
public: math::Vector2i mousePressPos = math::Vector2i::Zero;
/// \brief Flag to indicate whether the x key is currently being pressed
public: bool xPressed = false;
/// \brief Flag to indicate whether the y key is currently being pressed
public: bool yPressed = false;
/// \brief Flag to indicate whether the z key is currently being pressed
public: bool zPressed = false;
/// \brief Flag to indicate whether the escape key has been released.
public: bool escapeReleased = false;
/// \brief ID of thread where render calls can be made.
public: std::thread::id renderThreadId;
/// \brief The xyz values by which to snap the object.
public: math::Vector3d xyzSnap = math::Vector3d::One;
/// \brief The rpy values by which to snap the object.
public: math::Vector3d rpySnap = {45, 45, 45};
/// \brief The scale values by which to snap the object.
public: math::Vector3d scaleSnap = math::Vector3d::One;
};
/// \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
{
/// \brief Transport node
public: transport::Node node;
/// \brief Name of the world
public: std::string worldName;
/// \brief Rendering utility
public: RenderUtil *renderUtil = nullptr;
/// \brief Transform mode service
public: std::string transformModeService;
/// \brief Record video service
public: std::string recordVideoService;
/// \brief Move to service
public: std::string moveToService;
/// \brief Follow service
public: std::string followService;
/// \brief View angle service
public: std::string viewAngleService;
/// \brief Move to pose service
public: std::string moveToPoseService;
/// \brief Shapes service
public: std::string shapesService;
/// \brief Camera pose topic
public: std::string cameraPoseTopic;
/// \brief Camera pose publisher
public: transport::Node::Publisher cameraPosePub;
};
}
}
}
using namespace ignition;
using namespace gazebo;
QList<QThread *> RenderWindowItemPrivate::threads;
/////////////////////////////////////////////////
IgnRenderer::IgnRenderer()
: dataPtr(new IgnRendererPrivate)
{
this->dataPtr->moveToHelper.initCameraPose = this->cameraPose;
}
/////////////////////////////////////////////////
IgnRenderer::~IgnRenderer() = default;
////////////////////////////////////////////////
RenderUtil *IgnRenderer::RenderUtil() const
{
return &this->dataPtr->renderUtil;
}
/////////////////////////////////////////////////
void IgnRenderer::Render()
{
rendering::ScenePtr scene = this->dataPtr->renderUtil.Scene();
if (!scene)
{
ignwarn << "Scene is null. The render step will not occur in Scene3D."
<< std::endl;
return;
}
this->dataPtr->renderThreadId = std::this_thread::get_id();
IGN_PROFILE_THREAD_NAME("RenderThread");
IGN_PROFILE("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() /
static_cast<double>(this->textureSize.height()));
// setting the size should cause the render texture to be rebuilt
{
IGN_PROFILE("IgnRenderer::Render Pre-render camera");
this->dataPtr->camera->PreRender();
}
this->textureDirty = false;
}
// texture id could change so get the value in every render update
this->textureId = this->dataPtr->camera->RenderTextureGLId();
// update the scene
this->dataPtr->renderUtil.SetTransformActive(
this->dataPtr->transformControl.Active());
this->dataPtr->renderUtil.Update();
// view control
this->HandleMouseEvent();
// Entity selection
this->HandleEntitySelection();
// reset follow mode if target node got removed
if (!this->dataPtr->followTarget.empty())
{
rendering::NodePtr target = scene->NodeByName(this->dataPtr->followTarget);
if (!target && !this->dataPtr->followTargetWait)
{
this->dataPtr->camera->SetFollowTarget(nullptr);
this->dataPtr->camera->SetTrackTarget(nullptr);
this->dataPtr->followTarget.clear();
emit FollowTargetChanged(std::string(), false);
}
}
// update and render to texture
{
IGN_PROFILE("IgnRenderer::Render Update camera");
this->dataPtr->camera->Update();
}
// record video is requested
{
IGN_PROFILE("IgnRenderer::Render Record Video");
if (this->dataPtr->recordVideo)
{
unsigned int width = this->dataPtr->camera->ImageWidth();
unsigned int height = this->dataPtr->camera->ImageHeight();
if (this->dataPtr->cameraImage.Width() != width ||
this->dataPtr->cameraImage.Height() != height)
{
this->dataPtr->cameraImage = this->dataPtr->camera->CreateImage();
}
// Video recorder is on. Add more frames to it
if (this->dataPtr->videoEncoder.IsEncoding())
{
this->dataPtr->camera->Copy(this->dataPtr->cameraImage);
this->dataPtr->videoEncoder.AddFrame(
this->dataPtr->cameraImage.Data<unsigned char>(), width, height);
}
// Video recorder is idle. Start recording.
else
{
this->dataPtr->videoEncoder.Start(this->dataPtr->recordVideoFormat,
this->dataPtr->recordVideoSavePath, width, height);
}
}
else if (this->dataPtr->videoEncoder.IsEncoding())
{
this->dataPtr->videoEncoder.Stop();
}
}
// Move To
{
IGN_PROFILE("IgnRenderer::Render MoveTo");
if (!this->dataPtr->moveToTarget.empty())
{
if (this->dataPtr->moveToHelper.Idle())
{
rendering::NodePtr target = scene->NodeByName(
this->dataPtr->moveToTarget);
if (target)
{
this->dataPtr->moveToHelper.MoveTo(this->dataPtr->camera, target, 0.5,
std::bind(&IgnRenderer::OnMoveToComplete, this));
this->dataPtr->prevMoveToTime = std::chrono::system_clock::now();
}
else
{
ignerr << "Unable to move to target. Target: '"
<< this->dataPtr->moveToTarget << "' not found" << std::endl;
this->dataPtr->moveToTarget.clear();
}
}
else
{
auto now = std::chrono::system_clock::now();
std::chrono::duration<double> dt = now - this->dataPtr->prevMoveToTime;
this->dataPtr->moveToHelper.AddTime(dt.count());
this->dataPtr->prevMoveToTime = now;
}
}
}
// Move to pose
{
IGN_PROFILE("IgnRenderer::Render MoveToPose");
if (this->dataPtr->moveToPoseValue)
{
if (this->dataPtr->moveToHelper.Idle())
{
this->dataPtr->moveToHelper.MoveTo(this->dataPtr->camera,
*(this->dataPtr->moveToPoseValue),
0.5, std::bind(&IgnRenderer::OnMoveToPoseComplete, this));
this->dataPtr->prevMoveToTime = std::chrono::system_clock::now();
}
else
{
auto now = std::chrono::system_clock::now();
std::chrono::duration<double> dt = now - this->dataPtr->prevMoveToTime;
this->dataPtr->moveToHelper.AddTime(dt.count());
this->dataPtr->prevMoveToTime = now;
}
}
}
// Follow
{
IGN_PROFILE("IgnRenderer::Render Follow");
if (!this->dataPtr->moveToTarget.empty())
return;
rendering::NodePtr followTarget = this->dataPtr->camera->FollowTarget();
if (!this->dataPtr->followTarget.empty())
{
rendering::NodePtr target = scene->NodeByName(
this->dataPtr->followTarget);
if (target)
{
if (!followTarget || target != followTarget)
{
this->dataPtr->camera->SetFollowTarget(target,
this->dataPtr->followOffset,
this->dataPtr->followWorldFrame);
this->dataPtr->camera->SetFollowPGain(this->dataPtr->followPGain);
this->dataPtr->camera->SetTrackTarget(target);
// found target, no need to wait anymore
this->dataPtr->followTargetWait = false;
}
else if (this->dataPtr->followOffsetDirty)
{
math::Vector3d offset =
this->dataPtr->camera->WorldPosition() - target->WorldPosition();
if (!this->dataPtr->followWorldFrame)
{
offset = target->WorldRotation().RotateVectorReverse(offset);
}
this->dataPtr->camera->SetFollowOffset(offset);
this->dataPtr->followOffsetDirty = false;
}
}
else if (!this->dataPtr->followTargetWait)
{
ignerr << "Unable to follow target. Target: '"
<< this->dataPtr->followTarget << "' not found" << std::endl;
this->dataPtr->followTarget.clear();
}
}
else if (followTarget)
{
this->dataPtr->camera->SetFollowTarget(nullptr);
this->dataPtr->camera->SetTrackTarget(nullptr);
}
}
// View Angle
{
IGN_PROFILE("IgnRenderer::Render ViewAngle");
if (this->dataPtr->viewAngle)
{
if (this->dataPtr->moveToHelper.Idle())
{
std::vector<Entity> selectedEntities =
this->dataPtr->renderUtil.SelectedEntities();
// Look at the origin if no entities are selected
math::Vector3d lookAt = math::Vector3d::Zero;
if (!selectedEntities.empty())
{
for (const auto &entity : selectedEntities)
{
rendering::NodePtr node =
this->dataPtr->renderUtil.SceneManager().NodeById(entity);
if (!node)
continue;
math::Vector3d nodePos = node->WorldPose().Pos();
lookAt += nodePos;
}
lookAt /= selectedEntities.size();
}
this->dataPtr->moveToHelper.LookDirection(this->dataPtr->camera,
this->dataPtr->viewAngleDirection, lookAt,
0.5, std::bind(&IgnRenderer::OnViewAngleComplete, this));
this->dataPtr->prevMoveToTime = std::chrono::system_clock::now();
}
else
{
auto now = std::chrono::system_clock::now();
std::chrono::duration<double> dt = now - this->dataPtr->prevMoveToTime;
this->dataPtr->moveToHelper.AddTime(dt.count());
this->dataPtr->prevMoveToTime = now;
}
}
}
// Shapes
{
IGN_PROFILE("IgnRenderer::Render Shapes");
if (this->dataPtr->isSpawning)
{
// Generate spawn preview
rendering::VisualPtr rootVis = scene->RootVisual();
sdf::Root root;
if (!this->dataPtr->spawnSdfString.empty())
{
root.LoadSdfString(this->dataPtr->spawnSdfString);
}
else if (!this->dataPtr->spawnSdfPath.empty())
{
root.Load(this->dataPtr->spawnSdfPath);
}
else
{
ignwarn << "Failed to spawn: no SDF string or path" << std::endl;
}
this->dataPtr->isPlacing = this->GeneratePreview(root);
this->dataPtr->isSpawning = false;
}
}
// Escape action, clear all selections and terminate any
// spawned previews if escape button is released
{
if (this->dataPtr->escapeReleased)
{
this->DeselectAllEntities(true);
this->TerminateSpawnPreview();
this->dataPtr->escapeReleased = false;
}
}
if (ignition::gui::App())
{
gui::events::Render event;
ignition::gui::App()->sendEvent(
ignition::gui::App()->findChild<ignition::gui::MainWindow *>(),
&event);
}
}
/////////////////////////////////////////////////
bool IgnRenderer::GeneratePreview(const sdf::Root &_sdf)
{
// Terminate any pre-existing spawned entities
this->TerminateSpawnPreview();
if (!_sdf.ModelCount())
{
ignwarn << "Only model entities can be spawned at the moment." << std::endl;
this->TerminateSpawnPreview();
return false;
}
// Only preview first model
sdf::Model model = *(_sdf.ModelByIndex(0));
this->dataPtr->spawnPreviewPose = model.RawPose();
model.SetName(ignition::common::Uuid().String());
Entity modelId = this->UniqueId();
if (!modelId)
{
this->TerminateSpawnPreview();
return false;
}
this->dataPtr->spawnPreview =
this->dataPtr->renderUtil.SceneManager().CreateModel(
modelId, model,
this->dataPtr->renderUtil.SceneManager().WorldId());
this->dataPtr->previewIds.push_back(modelId);
for (auto j = 0u; j < model.LinkCount(); j++)
{
sdf::Link link = *(model.LinkByIndex(j));
link.SetName(ignition::common::Uuid().String());
Entity linkId = this->UniqueId();
if (!linkId)
{
this->TerminateSpawnPreview();
return false;
}
this->dataPtr->renderUtil.SceneManager().CreateLink(
linkId, link, modelId);
this->dataPtr->previewIds.push_back(linkId);
for (auto k = 0u; k < link.VisualCount(); k++)
{
sdf::Visual visual = *(link.VisualByIndex(k));
visual.SetName(ignition::common::Uuid().String());
Entity visualId = this->UniqueId();
if (!visualId)
{
this->TerminateSpawnPreview();
return false;
}
this->dataPtr->renderUtil.SceneManager().CreateVisual(
visualId, visual, linkId);
this->dataPtr->previewIds.push_back(visualId);
}
}
return true;
}
/////////////////////////////////////////////////
void IgnRenderer::TerminateSpawnPreview()
{
for (auto _id : this->dataPtr->previewIds)
this->dataPtr->renderUtil.SceneManager().RemoveEntity(_id);
this->dataPtr->previewIds.clear();
this->dataPtr->isPlacing = false;
}
/////////////////////////////////////////////////
Entity IgnRenderer::UniqueId()
{
auto timeout = 100000u;
for (auto i = 0u; i < timeout; ++i)
{
Entity id = std::numeric_limits<uint64_t>::max() - i;
if (!this->dataPtr->renderUtil.SceneManager().HasEntity(id))
return id;
}
return kNullEntity;
}
/////////////////////////////////////////////////
void IgnRenderer::HandleMouseEvent()
{
std::lock_guard<std::mutex> lock(this->dataPtr->mutex);
this->BroadcastHoverPos();
this->BroadcastLeftClick();
this->HandleMouseContextMenu();
this->HandleModelPlacement();
this->HandleMouseTransformControl();
this->HandleMouseViewControl();
}
/////////////////////////////////////////////////
void IgnRenderer::BroadcastHoverPos()
{
if (this->dataPtr->hoverDirty)
{
math::Vector3d pos = this->ScreenToScene(this->dataPtr->mouseHoverPos);
ignition::gui::events::HoverToScene hoverToSceneEvent(pos);
ignition::gui::App()->sendEvent(
ignition::gui::App()->findChild<ignition::gui::MainWindow *>(),
&hoverToSceneEvent);
}
}
/////////////////////////////////////////////////
void IgnRenderer::BroadcastLeftClick()
{
if (this->dataPtr->mouseEvent.Button() == common::MouseEvent::LEFT &&
this->dataPtr->mouseEvent.Type() == common::MouseEvent::RELEASE &&
!this->dataPtr->mouseEvent.Dragging() && this->dataPtr->mouseDirty)
{
math::Vector3d pos = this->ScreenToScene(this->dataPtr->mouseEvent.Pos());
ignition::gui::events::LeftClickToScene leftClickToSceneEvent(pos);
ignition::gui::App()->sendEvent(
ignition::gui::App()->findChild<ignition::gui::MainWindow *>(),
&leftClickToSceneEvent);
}
}
/////////////////////////////////////////////////
void IgnRenderer::HandleMouseContextMenu()
{
if (!this->dataPtr->mouseDirty)
return;
if (!this->dataPtr->mouseEvent.Dragging() &&
this->dataPtr->mouseEvent.Type() == common::MouseEvent::RELEASE &&
this->dataPtr->mouseEvent.Button() == common::MouseEvent::RIGHT)
{
math::Vector2i dt =
this->dataPtr->mouseEvent.PressPos() - this->dataPtr->mouseEvent.Pos();
// check for click with some tol for mouse movement
if (dt.Length() > 5.0)
return;
rendering::VisualPtr visual = this->dataPtr->camera->Scene()->VisualAt(
this->dataPtr->camera,
this->dataPtr->mouseEvent.Pos());
if (!visual)
return;
// get model visual
while (visual->HasParent() && visual->Parent() !=
visual->Scene()->RootVisual())
{
visual = std::dynamic_pointer_cast<rendering::Visual>(visual->Parent());
}
emit ContextMenuRequested(visual->Name().c_str());
this->dataPtr->mouseDirty = false;
}
}
////////////////////////////////////////////////
void IgnRenderer::HandleKeyPress(QKeyEvent *_e)
{
if (_e->isAutoRepeat())
return;
std::lock_guard<std::mutex> lock(this->dataPtr->mutex);
this->dataPtr->keyEvent.SetKey(_e->key());
this->dataPtr->keyEvent.SetText(_e->text().toStdString());
this->dataPtr->keyEvent.SetControl(
(_e->modifiers() & Qt::ControlModifier));
this->dataPtr->keyEvent.SetShift(
(_e->modifiers() & Qt::ShiftModifier));
this->dataPtr->keyEvent.SetAlt(
(_e->modifiers() & Qt::AltModifier));
this->dataPtr->mouseEvent.SetControl(this->dataPtr->keyEvent.Control());
this->dataPtr->mouseEvent.SetShift(this->dataPtr->keyEvent.Shift());
this->dataPtr->mouseEvent.SetAlt(this->dataPtr->keyEvent.Alt());
this->dataPtr->keyEvent.SetType(common::KeyEvent::PRESS);
// Update the object and mouse to be placed at the current position
// only for x, y, and z key presses
if (_e->key() == Qt::Key_X ||
_e->key() == Qt::Key_Y ||
_e->key() == Qt::Key_Z ||
_e->key() == Qt::Key_Shift)
{
this->dataPtr->transformControl.Start();
this->dataPtr->mousePressPos = this->dataPtr->mouseEvent.Pos();
}
// fullscreen
if (_e->key() == Qt::Key_F11)
{
if (ignition::gui::App()->findChild
<ignition::gui::MainWindow *>()->QuickWindow()->visibility()
== QWindow::FullScreen)
{
ignition::gui::App()->findChild
<ignition::gui::MainWindow *>()->QuickWindow()->showNormal();
}
else
{
ignition::gui::App()->findChild
<ignition::gui::MainWindow *>()->QuickWindow()->showFullScreen();
}
}
switch (_e->key())
{
case Qt::Key_X:
this->dataPtr->xPressed = true;
break;
case Qt::Key_Y:
this->dataPtr->yPressed = true;
break;
case Qt::Key_Z:
this->dataPtr->zPressed = true;
break;
default:
break;
}
}
////////////////////////////////////////////////
void IgnRenderer::HandleKeyRelease(QKeyEvent *_e)
{
if (_e->isAutoRepeat())
return;
std::lock_guard<std::mutex> lock(this->dataPtr->mutex);
this->dataPtr->keyEvent.SetKey(0);
this->dataPtr->keyEvent.SetControl(
(_e->modifiers() & Qt::ControlModifier)
&& (_e->key() != Qt::Key_Control));
this->dataPtr->keyEvent.SetShift(
(_e->modifiers() & Qt::ShiftModifier)
&& (_e->key() != Qt::Key_Shift));
this->dataPtr->keyEvent.SetAlt(
(_e->modifiers() & Qt::AltModifier)
&& (_e->key() != Qt::Key_Alt));
this->dataPtr->mouseEvent.SetControl(this->dataPtr->keyEvent.Control());
this->dataPtr->mouseEvent.SetShift(this->dataPtr->keyEvent.Shift());
this->dataPtr->mouseEvent.SetAlt(this->dataPtr->keyEvent.Alt());
this->dataPtr->keyEvent.SetType(common::KeyEvent::RELEASE);
// Update the object and mouse to be placed at the current position
// only for x, y, and z key presses
if (_e->key() == Qt::Key_X ||
_e->key() == Qt::Key_Y ||
_e->key() == Qt::Key_Z ||
_e->key() == Qt::Key_Shift)
{
this->dataPtr->transformControl.Start();
this->dataPtr->mousePressPos = this->dataPtr->mouseEvent.Pos();
this->dataPtr->isStartWorldPosSet = false;
}
switch (_e->key())
{
case Qt::Key_X:
this->dataPtr->xPressed = false;
break;
case Qt::Key_Y:
this->dataPtr->yPressed = false;
break;
case Qt::Key_Z:
this->dataPtr->zPressed = false;
break;
case Qt::Key_Escape:
this->dataPtr->escapeReleased = true;
break;
default:
break;
}
}
/////////////////////////////////////////////////
void IgnRenderer::HandleModelPlacement()
{
if (!this->dataPtr->isPlacing)
return;
if (this->dataPtr->spawnPreview && this->dataPtr->hoverDirty)
{
math::Vector3d pos = this->ScreenToPlane(this->dataPtr->mouseHoverPos);
pos.Z(this->dataPtr->spawnPreview->WorldPosition().Z());
this->dataPtr->spawnPreview->SetWorldPosition(pos);
this->dataPtr->hoverDirty = false;
}
if (this->dataPtr->mouseEvent.Button() == common::MouseEvent::LEFT &&
this->dataPtr->mouseEvent.Type() == common::MouseEvent::RELEASE &&
!this->dataPtr->mouseEvent.Dragging() && this->dataPtr->mouseDirty)
{
// Delete the generated visuals
this->TerminateSpawnPreview();