Source

gazebo / src / rendering / UserCamera.cc

Full commit
  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
/*
 * Copyright 2011 Nate Koenig & Andrew Howard
 *
 * 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.
 *
*/
/* Desc: Camera for viewing the world
 * Author: Nate Koenig
 * Date: 19 Jun 2008
 */

#include "rendering/ogre.h"
#include <sstream>

#include "common/Console.hh"
#include "common/Exception.hh"
#include "common/Events.hh"

#include "rendering/GUIOverlay.hh"
#include "rendering/Conversions.hh"
#include "rendering/WindowManager.hh"
#include "rendering/FPSViewController.hh"
#include "rendering/OrbitViewController.hh"
#include "rendering/RenderTypes.hh"
#include "rendering/Scene.hh"
#include "rendering/RTShaderSystem.hh"
#include "rendering/Camera.hh"
#include "rendering/Visual.hh"
#include "rendering/DynamicLines.hh"
#include "rendering/UserCamera.hh"   

using namespace gazebo;
using namespace rendering;


int UserCamera::count = 0;

////////////////////////////////////////////////////////////////////////////////
/// Constructor
UserCamera::UserCamera(const std::string &name_, Scene *scene_)
  : Camera(name_, scene_)
{
  std::stringstream stream;

  stream << "UserCamera_" << this->count++;
  this->name = stream.str(); 

  this->connections.push_back(
      event::Events::ConnectShowCameras(
        boost::bind(&UserCamera::ToggleShowVisual, this) ) );
  this->animState = NULL;

  this->gui = new GUIOverlay();

  this->orbitViewController = new OrbitViewController(this);
  this->fpsViewController = new FPSViewController(this);
  this->viewController = this->fpsViewController;
}

////////////////////////////////////////////////////////////////////////////////
/// Destructor
UserCamera::~UserCamera()
{
  delete this->orbitViewController;
  delete this->fpsViewController;

  delete this->gui;
  this->gui = NULL;

  this->connections.clear();
}

////////////////////////////////////////////////////////////////////////////////
// Load child
void UserCamera::Load( sdf::ElementPtr _sdf )
{
  Camera::Load(_sdf);
}

////////////////////////////////////////////////////////////////////////////////
// Load 
void UserCamera::Load( )
{
  Camera::Load();
}

////////////////////////////////////////////////////////////////////////////////
/// Initialize
void UserCamera::Init()
{
  Camera::Init();
  this->SetHFOV(GZ_DTOR(60));
  this->SetClipDist(0.001, 100);

  /*this->visual = new Visual(this->GetName() + "_OUTLINE", this->pitchNode);

  // The lines draw a visualization of the camera
  DynamicLines *line = this->visual->CreateDynamicLine( RENDERING_LINE_LIST );

  float f = 0.2;

  // Create the front face
  line->AddPoint(math::Vector3(0, -f, -f)); 
  line->AddPoint(math::Vector3(0, -f, +f)); 

  line->AddPoint(math::Vector3(0, -f, +f)); 
  line->AddPoint(math::Vector3(0, +f, +f)); 

  line->AddPoint(math::Vector3(0, +f, +f)); 
  line->AddPoint(math::Vector3(0, +f, -f)); 

  line->AddPoint(math::Vector3(0, +f, -f)); 
  line->AddPoint(math::Vector3(0, -f, -f)); 


  // Create the connecting lines
  line->AddPoint(math::Vector3(-0.4, 0, 0)); 
  line->AddPoint(math::Vector3(+0.0, -f, -f)); 

  line->AddPoint(math::Vector3(-0.4, 0, 0)); 
  line->AddPoint(math::Vector3(+0.0, -f, +f)); 

  line->AddPoint(math::Vector3(-0.4, 0, 0)); 
  line->AddPoint(math::Vector3(+0.0, +f, +f)); 

  line->AddPoint(math::Vector3(-0.4, 0, 0)); 
  line->AddPoint(math::Vector3(+0.0, +f, -f)); 

  line->AddPoint(math::Vector3(-0.4, 0, 0)); 
  line->AddPoint(math::Vector3(+0.0, -f, -f)); 

  // Draw up arrow
  line->AddPoint(math::Vector3(0, 0, +f)); 
  line->AddPoint(math::Vector3(0, 0, +f+0.1)); 

  line->AddPoint(math::Vector3(0.0, -0.02, +f+0.1)); 
  line->AddPoint(math::Vector3(0.0, +0.02, +f+0.1)); 

  line->AddPoint(math::Vector3(0.0, +0.02, +f+0.1)); 
  line->AddPoint(math::Vector3(0.0, +0.00, +f+0.15)); 

  line->AddPoint(math::Vector3(0.0, +0.00, +f+0.15)); 
  line->AddPoint(math::Vector3(0.0, -0.02, +f+0.1)); 

  line->setMaterial("Gazebo/WhiteGlow");
  line->setVisibilityFlags(GZ_VISIBILITY_GUI);

  this->visual->SetVisible(false);
  */
}

////////////////////////////////////////////////////////////////////////////////
/// Update
void UserCamera::Update()
{
  this->viewController->Update();

  Camera::Update();

  if (this->animState)
  {
    this->animState->addTime(0.01);
    if (this->animState->hasEnded())
    {
      this->animState = NULL;

      this->scene->GetManager()->destroyAnimation("cameratrack");
      this->scene->GetManager()->destroyAnimationState("cameratrack");
      if (this->onAnimationComplete)
        this->onAnimationComplete();
    }
  }

  if (this->gui)
    this->gui->Update();
}

////////////////////////////////////////////////////////////////////////////////
// Post Render
void UserCamera::PostRender()
{
  Camera::PostRender();
  sdf::ElementPtr elem = this->sdf->GetOrCreateElement("save");

  if (elem->GetValueBool("enabled"))
  {
    std::string path = elem->GetValueString("path");

    char tmp[1024];
    if (!path.empty())
    {
      sprintf(tmp, "%s/%s-%04d.jpg", path.c_str(),
          this->name.c_str(), this->saveCount);
    }
    else
    {
      sprintf(tmp, "%s-%04d.jpg", this->name.c_str(), this->saveCount);
    }

    // TODO: Use the window manager instead.
    //this->window->writeContentsToFile(tmp);

    this->saveCount++;
  }
}


////////////////////////////////////////////////////////////////////////////////
void UserCamera::Fini()
{
  Camera::Fini();
}

////////////////////////////////////////////////////////////////////////////////
void UserCamera::HandleMouseEvent(const common::MouseEvent &_evt)
{
  if (!this->gui || !this->gui->HandleMouseEvent(_evt))
    this->viewController->HandleMouseEvent(_evt);
}

void UserCamera::HandleKeyPressEvent(const std::string &_key)
{
  if (this->gui)
    this->gui->HandleKeyPressEvent(_key);
}

void UserCamera::HandleKeyReleaseEvent(const std::string &_key)
{
  if (this->gui)
    this->gui->HandleKeyReleaseEvent(_key);
}

bool UserCamera::AttachToVisualImpl( VisualPtr _visual,bool _inheritOrientation,
                                     double _minDist, double _maxDist )
{
  Camera::AttachToVisualImpl(_visual, _inheritOrientation);
  if (_visual)
  {
    math::Pose origPose = this->GetWorldPose();
    double yaw = atan2(origPose.pos.x - _visual->GetWorldPose().pos.x,
                       origPose.pos.y - _visual->GetWorldPose().pos.y);
    yaw = _visual->GetWorldPose().rot.GetAsEuler().z;

    double zDiff = origPose.pos.z - _visual->GetWorldPose().pos.z;
    double pitch = 0;

    if (fabs(zDiff) > 1e-3) 
    {
      double dist = _visual->GetWorldPose().pos.Distance( 
          this->GetWorldPose().pos);
      pitch = acos(zDiff/dist );
    }

    this->RotateYaw(yaw);
    this->RotatePitch(pitch);

    math::Box bb = _visual->GetBoundingBox();
    math::Vector3 pos = bb.GetCenter();
    pos.z = bb.max.z; 

    this->SetViewController(OrbitViewController::GetTypeString(), pos);
    ((OrbitViewController*)this->viewController)->SetDistanceRange( _minDist, _maxDist );
  }
  else
    this->SetViewController(FPSViewController::GetTypeString());

  return true;
}

bool UserCamera::TrackVisualImpl( VisualPtr _visual )
{
  Camera::TrackVisualImpl( _visual );
  if (_visual)
    this->SetViewController(OrbitViewController::GetTypeString());
  else
    this->SetViewController(FPSViewController::GetTypeString());

  return true;
}

////////////////////////////////////////////////////////////////////////////////
// Set view controller
void UserCamera::SetViewController( const std::string &type )
{
  if (this->viewController->GetTypeString() == type)
    return;

  if (type == OrbitViewController::GetTypeString())
    this->viewController = this->orbitViewController;
  else if (type == FPSViewController::GetTypeString())
    this->viewController = this->fpsViewController;
  else
    gzthrow("Invalid view controller type: " + type );

  this->viewController->Init();
}

////////////////////////////////////////////////////////////////////////////////
// Set view controller
void UserCamera::SetViewController( const std::string &type, 
                                    const math::Vector3 &_pos )
{
  if (this->viewController->GetTypeString() == type)
    return;

  if (type == OrbitViewController::GetTypeString())
    this->viewController = this->orbitViewController;
  else if (type == FPSViewController::GetTypeString())
    this->viewController = this->fpsViewController;
  else
    gzthrow("Invalid view controller type: " + type );

  this->viewController->Init(_pos);
}

////////////////////////////////////////////////////////////////////////////////
/// Resize the camera
void UserCamera::Resize(unsigned int /*_w*/, unsigned int /*_h*/)
{
  if (this->viewport)
  {
    this->viewport->setDimensions(0,0,1,1);
    double ratio = (double)this->viewport->getActualWidth() / 
                   (double)this->viewport->getActualHeight();

    double hfov = this->sdf->GetOrCreateElement("horizontal_fov")->GetValueDouble("angle");
    double vfov = 2.0 * atan(tan( hfov / 2.0) / ratio);
    this->camera->setAspectRatio(ratio);
    this->camera->setFOVy(Ogre::Radian(vfov));

    if (this->gui)
    {
      this->gui->Resize(this->viewport->getActualWidth(),
                        this->viewport->getActualHeight());
    }
  }

}

////////////////////////////////////////////////////////////////////////////////
// Set the dimensions of the viewport
void UserCamera::SetViewportDimensions(float /*x_*/, float /*y_*/, float /*w_*/, float /*h_*/)
{
  //this->viewport->setDimensions(x, y, w, h);
}

////////////////////////////////////////////////////////////////////////////////
/// Get the average frames per second
float UserCamera::GetAvgFPS() const
{
  return WindowManager::Instance()->GetAvgFPS(this->windowId);
}

////////////////////////////////////////////////////////////////////////////////
/// Get the triangle count 
float UserCamera::GetTriangleCount() const
{
  return WindowManager::Instance()->GetTriangleCount(this->windowId);
}

////////////////////////////////////////////////////////////////////////////////
// Toggle whether to show the visual
void UserCamera::ToggleShowVisual()
{
  //this->visual->ToggleVisible();
}

////////////////////////////////////////////////////////////////////////////////
// Set whether to show the visual
void UserCamera::ShowVisual(bool /*_s*/)
{
  //this->visual->SetVisible(_s);
}

//////////////////////////////////////////////////////////////////////////////
void UserCamera::MoveToVisual( const std::string &_name )
{
  VisualPtr visual = this->scene->GetVisual(_name);
  if (visual)
    this->MoveToVisual(visual);
  else
    gzerr << "MoveTo Unknown visual[" << _name << "]\n";
}

//////////////////////////////////////////////////////////////////////////////
// Move the camera to focus on an scene node
void UserCamera::MoveToVisual( VisualPtr _visual )
{
    if (!_visual)
    return;

  if (this->scene->GetManager()->hasAnimation("cameratrack"))
  {
    this->scene->GetManager()->destroyAnimation("cameratrack");
    this->scene->GetManager()->destroyAnimationState("cameratrack");
  }

  Ogre::Animation *anim = this->scene->GetManager()->createAnimation("cameratrack",.5);
  anim->setInterpolationMode(Ogre::Animation::IM_SPLINE);

  Ogre::NodeAnimationTrack *strack = anim->createNodeTrack(0,this->sceneNode);
  Ogre::NodeAnimationTrack *ptrack = anim->createNodeTrack(1,this->pitchNode);

  math::Box box = _visual->GetBoundingBox();
  math::Vector3 size = box.GetSize();
  double maxSize = std::max(std::max(size.x, size.y), size.z);


  math::Vector3 start = this->GetWorldPose().pos;
  start.Correct();
  math::Vector3 end = box.GetCenter();
  end.Correct();
  math::Vector3 dir = end - start;
  dir.Correct();
  dir.Normalize();

  double dist = start.Distance(end) - maxSize;

  math::Vector3 mid = start + dir*(dist*.5);
  mid.z = box.GetCenter().z + box.GetSize().z + 2.0;

  dir = end - mid;
  dir.Correct();

  dist = mid.Distance(end) - maxSize;

  double yawAngle = atan2(dir.y,dir.x);
  double pitchAngle = atan2(-dir.z, sqrt(dir.x*dir.x + dir.y*dir.y));
  Ogre::Quaternion yawFinal(Ogre::Radian(yawAngle), Ogre::Vector3(0,0,1));
  Ogre::Quaternion pitchFinal(Ogre::Radian(pitchAngle), Ogre::Vector3(0,1,0));

  dir.Normalize();

  double scale = maxSize / tan( (this->GetHFOV()/2.0).GetAsRadian() );

  end = mid + dir*(dist - scale);

  Ogre::TransformKeyFrame *key;

  key = strack->createNodeKeyFrame(0);
  key->setTranslate(Ogre::Vector3(start.x, start.y, start.z));
  key->setRotation(this->sceneNode->getOrientation());

  key = ptrack->createNodeKeyFrame(0);
  key->setRotation(this->pitchNode->getOrientation());

  key = strack->createNodeKeyFrame(.2);
  key->setTranslate( Ogre::Vector3(mid.x, mid.y, mid.z));
  key->setRotation(yawFinal);

  key = ptrack->createNodeKeyFrame(.2);
  key->setRotation(pitchFinal);

  key = strack->createNodeKeyFrame(.5);
  key->setTranslate( Ogre::Vector3(end.x, end.y, end.z));
  key->setRotation(yawFinal);

  key = ptrack->createNodeKeyFrame(.5);
  key->setRotation(pitchFinal);

  this->animState = this->scene->GetManager()->createAnimationState("cameratrack");

  this->animState->setTimePosition(0);
  this->animState->setEnabled(true);
  this->animState->setLoop(false);
}

bool UserCamera::MoveToPosition( const math::Vector3 &_end, 
                                 double _pitch, double _yaw, double _time)
{
  if (this->animState)
    return false;

  Ogre::TransformKeyFrame *key;
  math::Vector3 start = this->GetWorldPose().pos;

  double dyaw =  this->GetWorldRotation().GetAsEuler().z - _yaw;

  if (dyaw > M_PI)
    _yaw += 2*M_PI;
  else if (dyaw < -M_PI)
    _yaw -= 2*M_PI;

  Ogre::Quaternion yawFinal(Ogre::Radian(_yaw), Ogre::Vector3(0,0,1));
  Ogre::Quaternion pitchFinal(Ogre::Radian(_pitch), Ogre::Vector3(0,1,0));

  Ogre::Animation *anim = this->scene->GetManager()->createAnimation("cameratrack",_time);
  anim->setInterpolationMode(Ogre::Animation::IM_SPLINE);

  Ogre::NodeAnimationTrack *strack = anim->createNodeTrack(0,this->sceneNode);
  Ogre::NodeAnimationTrack *ptrack = anim->createNodeTrack(1,this->pitchNode);

  key = strack->createNodeKeyFrame(0);
  key->setTranslate(Ogre::Vector3(start.x, start.y, start.z));
  key->setRotation(this->sceneNode->getOrientation());

  key = ptrack->createNodeKeyFrame(0);
  key->setRotation(this->pitchNode->getOrientation());

  key = strack->createNodeKeyFrame(_time);
  key->setTranslate( Ogre::Vector3(_end.x, _end.y, _end.z));
  key->setRotation(yawFinal);

  key = ptrack->createNodeKeyFrame(_time);
  key->setRotation(pitchFinal);

  this->animState = this->scene->GetManager()->createAnimationState("cameratrack");

  this->animState->setTimePosition(0);
  this->animState->setEnabled(true);
  this->animState->setLoop(false);
  return true;
}

bool UserCamera::MoveToPositions(const std::vector<math::Pose> &_pts, 
                                 double _time,
                                 boost::function<void()> _onComplete)
{
  if (this->animState)
    return false;

  this->onAnimationComplete = _onComplete;

  Ogre::TransformKeyFrame *key;
  math::Vector3 start = this->GetWorldPose().pos;

  Ogre::Animation *anim =
    this->scene->GetManager()->createAnimation("cameratrack",_time);
  anim->setInterpolationMode(Ogre::Animation::IM_SPLINE);

  Ogre::NodeAnimationTrack *strack = anim->createNodeTrack(0,this->sceneNode);
  Ogre::NodeAnimationTrack *ptrack = anim->createNodeTrack(1,this->pitchNode);

  key = strack->createNodeKeyFrame(0);
  key->setTranslate(Ogre::Vector3(start.x, start.y, start.z));
  key->setRotation(this->sceneNode->getOrientation());

  key = ptrack->createNodeKeyFrame(0);
  key->setRotation(this->pitchNode->getOrientation());

  double dt = _time / (_pts.size()-1);
  double tt = 0;
  for (unsigned int i=0; i < _pts.size(); i++)
  {
    math::Vector3 pos = _pts[i].pos;
    math::Vector3 rpy = _pts[i].rot.GetAsEuler();
    double dyaw =  this->GetWorldRotation().GetAsEuler().z - rpy.z;

    if (dyaw > M_PI)
      rpy.z += 2*M_PI;
    else if (dyaw < -M_PI)
      rpy.z -= 2*M_PI;

    Ogre::Quaternion yawFinal(Ogre::Radian(rpy.z), Ogre::Vector3(0,0,1));
    Ogre::Quaternion pitchFinal(Ogre::Radian(rpy.y), Ogre::Vector3(0,1,0));

    key = strack->createNodeKeyFrame(tt);
    key->setTranslate(Ogre::Vector3(pos.x, pos.y, pos.z));
    key->setRotation(yawFinal);

    key = ptrack->createNodeKeyFrame(tt);
    key->setRotation(pitchFinal);

    tt += dt;
  }

  this->animState = this->scene->GetManager()->createAnimationState(
      "cameratrack");

  this->animState->setTimePosition(0);
  this->animState->setEnabled(true);
  this->animState->setLoop(false);
  return true;
}

//////////////////////////////////////////////////////////////////////////////
void UserCamera::SetRenderTarget(Ogre::RenderTarget *_target)
{
  Camera::SetRenderTarget(_target);

  this->viewport->setVisibilityMask(GZ_VISIBILITY_ALL);
  this->gui->Init(this->renderTarget);
  this->initialized = true;
}

//////////////////////////////////////////////////
GUIOverlay *UserCamera::GetGUIOverlay()
{
  return this->gui;
}

//////////////////////////////////////////////////
void UserCamera::EnableViewController(bool _value) const
{
  this->viewController->SetEnabled(_value);
}