GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: src/window-manager.cpp Lines: 1 372 0.3 %
Date: 2020-05-14 11:23:33 Branches: 2 710 0.3 %

Line Branch Exec Source
1
//
2
//  window-manager.cpp
3
//  gepetto-viewer
4
//
5
//  Created by Justin Carpentier, Mathieu Geisert in November 2014.
6
//  Copyright (c) 2014 LAAS-CNRS. All rights reserved.
7
//
8
9
#include <gepetto/viewer/window-manager.h>
10
11
#include <stdexcept>
12
13
#include <osg/DisplaySettings>
14
#include <osg/Camera>
15
#include <gepetto/viewer/OSGManipulator/keyboard-manipulator.h>
16
#include <osgGA/TrackballManipulator>
17
#include <osgGA/NodeTrackerManipulator>
18
#include <osgDB/WriteFile>
19
20
#include <../src/is-dirty-visitor.h>
21
#include <../src/internal/configuration.hh>
22
23
namespace gepetto {
24
namespace viewer {
25
  namespace {
26
    struct ScreenShot : public osg::Camera::DrawCallback
27
    {
28
      ScreenShot(const std::string& fn) : fn_ (fn) {}
29
30
      virtual void operator () (osg::RenderInfo& renderInfo) const;
31
32
      std::string fn_;
33
    };
34
35
    void ScreenShot::operator () (osg::RenderInfo& renderInfo) const
36
    {
37
      osg::Timer* timer = osg::Timer::instance();
38
      osg::Timer_t tick_start = timer->tick();
39
40
      osg::ref_ptr<osg::Image> image = new osg::Image;
41
      assert(renderInfo.getState());
42
      osg::GraphicsContext* gc = renderInfo.getState()->getGraphicsContext();
43
      assert(gc);
44
45
      glReadBuffer(GL_BACK);
46
      //osg::Camera* camera = renderInfo.getCurrentCamera();
47
      //osg::Viewport* viewport = camera ? camera->getViewport() : 0;
48
      //image->readPixels(viewport->x(),viewport->y(),viewport->width(),viewport->height(),
49
      image->readPixels(0, 0, gc->getTraits()->width, gc->getTraits()->height,
50
          GL_RGBA, GL_UNSIGNED_BYTE, 1);
51
52
      osgDB::writeImageFile(*image, fn_);
53
54
      bool res = osgDB::writeImageFile(*image, fn_);
55
      if (!res) {
56
        std::cerr << "Failed to write image " << fn_ << std::endl;
57
      } else {
58
        osg::Timer_t tick_end = timer->tick();
59
        std::cout<<"Time to generate image " << fn_ << " = "
60
          << timer->delta_s(tick_start, tick_end) << " seconds"<<std::endl;
61
      }
62
    }
63
64
    struct ResizeHandler: osgGA::GUIEventHandler
65
    {
66
      ResizeHandler(osg::Camera* camera) : camera_ (camera) {}
67
68
      virtual bool handle(
69
          const osgGA::GUIEventAdapter& gea,
70
          osgGA::GUIActionAdapter&      /*gaa*/,
71
          osg::Object*                  /*obj*/,
72
          osg::NodeVisitor*             /*nv*/
73
          )
74
      {
75
        osgGA::GUIEventAdapter::EventType ev = gea.getEventType();
76
77
        if(ev != osgGA::GUIEventAdapter::RESIZE) return false;
78
79
        float w = (float)gea.getWindowWidth();
80
        float h = (float)gea.getWindowHeight();
81
82
        if(camera_.valid())
83
          camera_->setProjectionMatrix(osg::Matrix::ortho2D(0.0f, w, 0.0f, h));
84
85
        float m = w*0.01f;
86
87
        texts_[WindowManager::BOTTOM][WindowManager::LEFT  ]->setPosition (osgVector3(  m,  m,0.f));
88
        texts_[WindowManager::BOTTOM][WindowManager::CENTER]->setPosition (osgVector3(w/2,  m,0.f));
89
        texts_[WindowManager::BOTTOM][WindowManager::RIGHT ]->setPosition (osgVector3(w-m,  m,0.f));
90
        texts_[WindowManager::CENTER][WindowManager::LEFT  ]->setPosition (osgVector3(  m,h/2,0.f));
91
        texts_[WindowManager::CENTER][WindowManager::CENTER]->setPosition (osgVector3(w/2,h/2,0.f));
92
        texts_[WindowManager::CENTER][WindowManager::RIGHT ]->setPosition (osgVector3(w-m,h/2,0.f));
93
        texts_[WindowManager::TOP   ][WindowManager::LEFT  ]->setPosition (osgVector3(  m,h-m,0.f));
94
        texts_[WindowManager::TOP   ][WindowManager::CENTER]->setPosition (osgVector3(w/2,h-m,0.f));
95
        texts_[WindowManager::TOP   ][WindowManager::RIGHT ]->setPosition (osgVector3(w-m,h-m,0.f));
96
        return true;
97
      }
98
99
      osg::ref_ptr<osgText::Text>   texts_[3][3];
100
      osg::observer_ptr<osg::Camera> camera_;
101
    };
102
  }
103
104
    void WindowManager::createManipulator()
105
    {
106
      osgViewer::Viewer::Windows windows;
107
      viewer_ptr_->getWindows(windows);
108
      manipulator_ptr = new ::osgGA::KeySwitchMatrixManipulator;
109
      manipulator_ptr->addMatrixManipulator('1',"trackball",new ::osgGA::TrackballManipulator);
110
      manipulator_ptr->addMatrixManipulator('2',"keyboard",new ::osgGA::KeyboardManipulator(windows.front()));
111
      manipulator_ptr->addMatrixManipulator('3',"tracker",new ::osgGA::NodeTrackerManipulator);
112
      viewer_ptr_->setCameraManipulator( manipulator_ptr);
113
    }
114
115
  void WindowManager::createBackground()
116
  {
117
    // Enable Outline highlight state.
118
    main_camera_->setClearMask(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
119
    main_camera_->setClearColor(osg::Vec4(0.,0.,0.,0.));
120
    // Create background camera
121
    bg_camera_ = new osg::Camera;
122
    bg_camera_->setName("bg_camera");
123
    const osg::Node::NodeMask mask = ~IntersectionBit;
124
    bg_camera_->setNodeMask(mask);
125
126
    osg::ref_ptr <const osg::GraphicsContext::Traits> traits_ptr = gc_->getTraits();
127
128
    // set the projection matrix
129
    bg_camera_->setProjectionMatrix(osg::Matrix::ortho2D(traits_ptr->x,traits_ptr->width,traits_ptr->y,traits_ptr->height));
130
131
    bg_camera_->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
132
    bg_camera_->setViewMatrix(osg::Matrix::identity());
133
134
    // only clear the depth buffer
135
    //      bg_camera_->setClearMask(GL_DEPTH_BUFFER_BIT);
136
    bg_camera_->setClearColor(osg::Vec4(0.,0.,0.,0.));
137
138
    // draw subgraph before main camera view.
139
    bg_camera_->setRenderOrder(osg::Camera::PRE_RENDER);
140
    bg_camera_->setCullingActive(false);
141
    bg_camera_->setAllowEventFocus(false);
142
143
    bg_color1_ = osg::Vec4(0.4f, 0.4f, 0.6f, 1.0f);
144
    bg_color2_ = osg::Vec4(0.6f, 0.6f, 0.6f, 1.0f);
145
146
    // Create the background geometry here
147
    {
148
      osg::Geode* geode = new osg::Geode();
149
      geode->setName("background");
150
      osg::StateSet* stateset = geode->getOrCreateStateSet();
151
      stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
152
153
      bg_geom_ = new osg::Geometry;
154
155
      const float depth = (float)-0.1;
156
      osg::Vec3Array* vertices = new osg::Vec3Array;
157
      vertices->push_back(osg::Vec3(0.,(float)traits_ptr->height,depth));
158
      vertices->push_back(osg::Vec3(0.,0.,depth));
159
      vertices->push_back(osg::Vec3((float)traits_ptr->width,0.,depth));
160
      vertices->push_back(osg::Vec3((float)traits_ptr->width,(float)traits_ptr->height,depth));
161
      bg_geom_->setVertexArray(vertices);
162
163
      osg::Vec3Array* normals = new osg::Vec3Array;
164
      normals->push_back(osg::Vec3(0.0f,0.0f,1.0f));
165
      bg_geom_->setNormalArray(normals, osg::Array::BIND_OVERALL);
166
167
      applyBackgroundColor();
168
169
      bg_geom_->addPrimitiveSet(new osg::DrawArrays(GL_QUADS,0,4));
170
171
      stateset = bg_geom_->getOrCreateStateSet();
172
      stateset->setMode(GL_BLEND,osg::StateAttribute::ON);
173
      stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
174
175
      geode->addDrawable(bg_geom_);
176
      bg_camera_->addChild(geode);
177
178
      bg_geom_  ->setDataVariance(osg::Object::STATIC);
179
      bg_camera_->setDataVariance(osg::Object::STATIC);
180
      geode     ->setDataVariance(osg::Object::STATIC);
181
      //bg_camera_->setGraphicsContext(camera->getGraphicsContext());
182
    }
183
184
    asGroup()->addChild(bg_camera_);
185
  }
186
187
  void WindowManager::createHUDcamera()
188
  {
189
    // Create HUD camera
190
    osg::ref_ptr <const osg::GraphicsContext::Traits> traits_ptr = gc_->getTraits();
191
192
    hud_camera_ = new osg::Camera;
193
    hud_camera_->setName("hud_camera");
194
    const osg::Node::NodeMask mask = ~IntersectionBit;
195
    hud_camera_->setNodeMask(mask);
196
197
    hud_camera_->setReferenceFrame( osg::Transform::ABSOLUTE_RF );
198
    hud_camera_->setClearMask( GL_DEPTH_BUFFER_BIT );
199
    hud_camera_->setRenderOrder( osg::Camera::POST_RENDER );
200
    hud_camera_->setAllowEventFocus( false );
201
    hud_camera_->setProjectionMatrix(
202
        osg::Matrix::ortho2D(traits_ptr->x,traits_ptr->width,traits_ptr->y,traits_ptr->height));
203
    hud_camera_->getOrCreateStateSet()->setMode(
204
        GL_LIGHTING, osg::StateAttribute::OFF );
205
206
    textGeode_ = new osg::Geode;
207
    hud_camera_->addChild (textGeode_);
208
209
    ResizeHandler* rh = new ResizeHandler(hud_camera_);
210
    static osg::ref_ptr<osgText::Font> font = defaultFont();
211
    for (int i = 0; i < 3; ++i)
212
      for (int j = 0; j < 3; ++j) {
213
        osg::ref_ptr<osgText::Text>& text      = texts_[i][j];
214
        text = new osgText::Text;
215
        text->setAxisAlignment( osgText::TextBase::XY_PLANE );
216
        text->setDataVariance( osg::Object::DYNAMIC );
217
        text->setFont( font );
218
        switch (i) {
219
          case TOP:
220
            switch (j) {
221
              case LEFT  : text->setAlignment( osgText::TextBase::  LEFT_TOP ); break;
222
              case CENTER: text->setAlignment( osgText::TextBase::CENTER_TOP ); break;
223
              case RIGHT : text->setAlignment( osgText::TextBase:: RIGHT_TOP ); break;
224
            }
225
            break;
226
          case CENTER:
227
            switch (j) {
228
              case LEFT  : text->setAlignment( osgText::TextBase::  LEFT_CENTER ); break;
229
              case CENTER: text->setAlignment( osgText::TextBase::CENTER_CENTER ); break;
230
              case RIGHT : text->setAlignment( osgText::TextBase:: RIGHT_CENTER ); break;
231
            }
232
            break;
233
          case BOTTOM:
234
            switch (j) {
235
              case LEFT  : text->setAlignment( osgText::TextBase::  LEFT_BOTTOM ); break;
236
              case CENTER: text->setAlignment( osgText::TextBase::CENTER_BOTTOM ); break;
237
              case RIGHT : text->setAlignment( osgText::TextBase:: RIGHT_BOTTOM ); break;
238
            }
239
            break;
240
        }
241
242
        rh->texts_[i][j] = text;
243
        textActive_[i][j] = false;
244
      }
245
    viewer_ptr_->addEventHandler (rh);
246
247
    // Property to scene
248
    addProperty (
249
        StringProperty::create("Text/TopLeft",
250
          boost::bind (&WindowManager::getText, this, TOP, LEFT),
251
          boost::bind (&WindowManager::setText, this, TOP, LEFT, _1, 20)));
252
    addProperty (
253
        StringProperty::create("Text/TopCenter",
254
          boost::bind (&WindowManager::getText, this, TOP, CENTER),
255
          boost::bind (&WindowManager::setText, this, TOP, CENTER, _1, 20)));
256
    addProperty (
257
        StringProperty::create("Text/TopRight",
258
          boost::bind (&WindowManager::getText, this, TOP, RIGHT),
259
          boost::bind (&WindowManager::setText, this, TOP, RIGHT, _1, 20)));
260
    addProperty (
261
        StringProperty::create("Text/CenterLeft",
262
          boost::bind (&WindowManager::getText, this, CENTER, LEFT),
263
          boost::bind (&WindowManager::setText, this, CENTER, LEFT, _1, 20)));
264
    addProperty (
265
        StringProperty::create("Text/CenterCenter",
266
          boost::bind (&WindowManager::getText, this, CENTER, CENTER),
267
          boost::bind (&WindowManager::setText, this, CENTER, CENTER, _1, 20)));
268
    addProperty (
269
        StringProperty::create("Text/CenterRight",
270
          boost::bind (&WindowManager::getText, this, CENTER, RIGHT),
271
          boost::bind (&WindowManager::setText, this, CENTER, RIGHT, _1, 20)));
272
    addProperty (
273
        StringProperty::create("Text/BottomLeft",
274
          boost::bind (&WindowManager::getText, this, BOTTOM, LEFT),
275
          boost::bind (&WindowManager::setText, this, BOTTOM, LEFT, _1, 20)));
276
    addProperty (
277
        StringProperty::create("Text/BottomCenter",
278
          boost::bind (&WindowManager::getText, this, BOTTOM, CENTER),
279
          boost::bind (&WindowManager::setText, this, BOTTOM, CENTER, _1, 20)));
280
    addProperty (
281
        StringProperty::create("Text/BottomRight",
282
          boost::bind (&WindowManager::getText, this, BOTTOM, RIGHT),
283
          boost::bind (&WindowManager::setText, this, BOTTOM, RIGHT, _1, 20)));
284
  }
285
286
  std::string WindowManager::getText (TextAlignment vPos, TextAlignment hPos) const
287
  {
288
    osg::ref_ptr<osgText::Text> text = texts_[vPos][hPos];
289
    if (!text) return std::string();
290
    else return text->getText().createUTF8EncodedString();
291
  }
292
293
  void WindowManager::setText (TextAlignment vPos, TextAlignment hPos,
294
      const std::string& content, float size)
295
  {
296
    if (content.size() == 0) {
297
      textGeode_->removeDrawable (texts_[vPos][hPos]);
298
      textActive_[vPos][hPos] = false;
299
300
      for (int i = 0; i < 3; ++i)
301
        for (int j = 0; j < 3; ++j)
302
          if (textActive_[i][j]) return;
303
      asGroup()->removeChild(hud_camera_);
304
      setDirty();
305
      return;
306
    }
307
308
    osg::ref_ptr<osgText::Text>& text      = texts_[vPos][hPos];
309
    if (!textActive_[vPos][hPos]) {
310
      textGeode_->addDrawable( text );
311
      textActive_[vPos][hPos] = true;
312
    }
313
    text->setCharacterSize( size );
314
    text->setText( content );
315
316
    if (!asGroup()->containsNode(hud_camera_)) {
317
      osg::Viewport* vp = viewer_ptr_->getCamera()->getViewport();
318
      viewer_ptr_->getEventQueue()->windowResize ((int)vp->x(), (int)vp->y(), (int)vp->width(), (int)vp->height());
319
320
      asGroup()->addChild(hud_camera_);
321
    }
322
    setDirty();
323
  }
324
325
  void WindowManager::applyBackgroundColor()
326
  {
327
    osg::Vec4Array* colors = new osg::Vec4Array;
328
    colors->push_back(bg_color1_);
329
    colors->push_back(bg_color2_);
330
    colors->push_back(bg_color2_);
331
    colors->push_back(bg_color1_);
332
    bg_geom_->setColorArray(colors, osg::Array::BIND_PER_VERTEX);
333
  }
334
335
  void WindowManager::captureFrame(const std::string& filename)
336
  {
337
    osg::ref_ptr<ScreenShot> screenshot_ = new ScreenShot(filename);
338
    main_camera_->setFinalDrawCallback (screenshot_);
339
    viewer_ptr_->renderingTraversals();
340
    main_camera_->setFinalDrawCallback(0);
341
  }
342
343
    /* Declaration of private function members */
344
    void WindowManager::init(const unsigned int& x,
345
                                  const unsigned int& y,
346
                                  const unsigned int& width,
347
                                  const unsigned int& height)
348
    {
349
      osg::DisplaySettings* ds = osg::DisplaySettings::instance().get();
350
      osg::TraitsRefPtr traits_ptr = new ::osg::GraphicsContext::Traits(ds);
351
352
      traits_ptr->windowName = "Gepetto Viewer";
353
      traits_ptr->x = x;
354
      traits_ptr->y = y;
355
      traits_ptr->width = width;
356
      traits_ptr->height = height;
357
      traits_ptr->windowDecoration = true;
358
      traits_ptr->doubleBuffer = true;
359
      traits_ptr->sharedContext = 0;
360
361
      traits_ptr->vsync = true;
362
      traits_ptr->readDISPLAY ();
363
      traits_ptr->setUndefinedScreenDetailsToDefaultScreen ();
364
365
      osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext( traits_ptr );
366
367
      init (gc.get ());
368
    }
369
370
    void WindowManager::init(osg::GraphicsContext* gc)
371
    {
372
      ::osgViewer::ViewerRefPtr viewer = new ::osgViewer::Viewer();
373
374
      /* init main camera */
375
      ::osg::CameraRefPtr camera = viewer->getCamera ();
376
      camera->setName("main_camera");
377
378
      const osg::GraphicsContext::Traits* traits_ptr = gc->getTraits ();
379
      camera->setGraphicsContext(gc);
380
      camera->setViewport(new osg::Viewport(0,0, traits_ptr->width, traits_ptr->height));
381
      camera->setProjectionMatrixAsPerspective(
382
          30.0f, static_cast<double>(traits_ptr->width)/static_cast<double>(traits_ptr->height), 1.0f, 10000.0f );
383
      GLenum buffer = traits_ptr->doubleBuffer ? GL_BACK : GL_FRONT;
384
      camera->setDrawBuffer(buffer);
385
      camera->setReadBuffer(buffer);
386
387
      /* Disable small features culling */
388
      osg::CullStack::CullingMode cullingMode = camera->getCullingMode();
389
      cullingMode &= ~(osg::CullStack::SMALL_FEATURE_CULLING);
390
      camera->setCullingMode( cullingMode );
391
392
      /* avoid ending */
393
      viewer->setKeyEventSetsDone (0);
394
      viewer->addEventHandler(new osgViewer::HelpHandler);
395
396
      init (viewer, gc);
397
    }
398
399
    void WindowManager::init(osgViewer::Viewer* v, osg::GraphicsContext* gc)
400
    {
401
      setID (gc->getTraits()->windowName);
402
403
      viewer_ptr_ = v;
404
      viewer_ptr_->setSceneData ( asGroup() );
405
      lastSceneWasDisrty_ = true;
406
407
      /* init main camera */
408
      main_camera_ = viewer_ptr_->getCamera ();
409
410
      // Enable Outline highlight state.
411
      main_camera_->setClearStencil(0);
412
      osg::DisplaySettings* ds = osg::DisplaySettings::instance().get();
413
      if (ds->getMinimumNumStencilBits() == 0)
414
        ds->setMinimumNumStencilBits(1);
415
416
      gc_ = osg::GraphicsContextRefPtr (gc);
417
      createBackground();
418
      createManipulator();
419
      createHUDcamera();
420
    }
421
422
    WindowManager::WindowManager ()
423
      : GroupNode ("")
424
      , nodeTrackerManipulatorIndex(2)
425
    {
426
        init (0, 0, 600, 480);
427
    }
428
429
    WindowManager::WindowManager (osg::GraphicsContext* gc)
430
      : GroupNode ("")
431
      , nodeTrackerManipulatorIndex(2)
432
    {
433
        init (gc);
434
    }
435
436
    WindowManager::WindowManager (osgViewer::Viewer* v, osg::GraphicsContext* gc)
437
      : GroupNode ("")
438
      , nodeTrackerManipulatorIndex(2)
439
    {
440
        init (v, gc);
441
    }
442
443
    WindowManager::WindowManager (const unsigned int& x,
444
                                  const unsigned int& y,
445
                                  const unsigned int& width,
446
                                  const unsigned int& height)
447
      : GroupNode ("")
448
      , nodeTrackerManipulatorIndex(2)
449
    {
450
        init (x, y, width, height);
451
    }
452
453
    WindowManager::WindowManager (const WindowManager& other)
454
      : GroupNode (other)
455
      , nodeTrackerManipulatorIndex(2)
456
    {
457
      init (viewer_ptr_, gc_);
458
    }
459
460
    void WindowManager::initWeakPtr (WindowManagerWeakPtr other_weak_ptr)
461
    {
462
        weak_ptr_ = other_weak_ptr;
463
    }
464
465
    /* End declaration of private function members */
466
467
    /* Declaration of protected function members */
468
469
    WindowManagerPtr_t WindowManager::create ()
470
    {
471
        WindowManagerPtr_t shared_ptr(new WindowManager());
472
473
        // Add reference to itself
474
        shared_ptr->initWeakPtr(shared_ptr);
475
476
        return shared_ptr;
477
    }
478
479
    WindowManagerPtr_t WindowManager::create (const unsigned int& x,
480
                                                            const unsigned int& y,
481
                                                            const unsigned int& width,
482
                                                            const unsigned int& height)
483
    {
484
        WindowManagerPtr_t shared_ptr(new WindowManager(x, y, width, height));
485
486
        // Add reference to itself
487
        shared_ptr->initWeakPtr(shared_ptr);
488
489
        return shared_ptr;
490
    }
491
492
    WindowManagerPtr_t WindowManager::create(osg::GraphicsContext* gc)
493
    {
494
        WindowManagerPtr_t shared_ptr(new WindowManager(gc));
495
496
        // Add reference to itself
497
        shared_ptr->initWeakPtr(shared_ptr);
498
499
        return shared_ptr;
500
    }
501
502
    WindowManagerPtr_t WindowManager::create(osgViewer::Viewer* v, osg::GraphicsContext* gc)
503
    {
504
        WindowManagerPtr_t shared_ptr(new WindowManager(v, gc));
505
506
        // Add reference to itself
507
        shared_ptr->initWeakPtr(shared_ptr);
508
509
        return shared_ptr;
510
    }
511
512
    WindowManagerPtr_t WindowManager::createCopy (WindowManagerPtr_t other)
513
    {
514
        WindowManagerPtr_t shared_ptr(new WindowManager(*other));
515
516
        // Add reference to itself
517
        shared_ptr->initWeakPtr(shared_ptr);
518
519
        return shared_ptr;
520
    }
521
522
    /* End declaration of protected function members */
523
524
    /* Declaration of public function members */
525
526
    WindowManagerPtr_t WindowManager::clone (void) const
527
    {
528
        return WindowManager::createCopy(weak_ptr_.lock());
529
    }
530
531
    WindowManagerPtr_t WindowManager::self (void) const
532
    {
533
        return weak_ptr_.lock();
534
    }
535
536
    bool WindowManager::addNode(NodePtr_t graphical_object_ptr)
537
    {
538
        bool result = addChild (graphical_object_ptr);
539
        return result;
540
    }
541
542
    bool WindowManager::done ()
543
    {
544
        return  viewer_ptr_->done();
545
    }
546
547
    bool WindowManager::frame ()
548
    {
549
      bool callFrame = screen_capture_ptr_;
550
      if (!callFrame) {
551
        IsDirtyVisitor isDirtyVisitor;
552
        accept (isDirtyVisitor);
553
        // FIXME For some reasons, when highlight state of a node is changed,
554
        // method frame must be called twice to get it rendered properly.
555
        // lastSceneWasDisrty_ forces to draw twice after a dirty scene.
556
        callFrame = lastSceneWasDisrty_
557
          || isDirtyVisitor.isDirty()
558
          || viewer_ptr_->checkNeedToDoFrame ();
559
        lastSceneWasDisrty_ = isDirtyVisitor.isDirty();
560
      }
561
      if (callFrame)
562
        viewer_ptr_->frame();
563
      else
564
        return false;
565
566
      SetCleanVisitor setCleanVisitor;
567
      accept (setCleanVisitor);
568
      return true;
569
    }
570
571
    bool WindowManager::run ()
572
    {
573
        return viewer_ptr_->run();
574
    }
575
576
    void WindowManager::setWindowDimension (const osgVector2& size)
577
    {
578
        /* Define new trait dimension of the main camera */
579
        const osg::GraphicsContext::Traits* traits_ptr = gc_->getTraits ();
580
        gc_->resized (traits_ptr->x, traits_ptr->y, (int)size[0], (int)size[1]);
581
    }
582
583
    osgVector2 WindowManager::getWindowDimension() const
584
    {
585
        osgVector2 dimention;
586
        const osg::GraphicsContext::Traits* traits_ptr = gc_->getTraits ();
587
        dimention.x() = (osg::Vec2f::value_type) traits_ptr->width;
588
        dimention.y() = (osg::Vec2f::value_type) traits_ptr->height;
589
        return dimention;
590
    }
591
592
    void WindowManager::setWindowPosition (const osgVector2& position)
593
    {
594
        /* Define new trait dimension of the main camera */
595
        const osg::GraphicsContext::Traits* traits_ptr = gc_->getTraits ();
596
        gc_->resized ((int)position[0], (int)position[1],
597
                traits_ptr->width, traits_ptr->height);
598
    }
599
600
    osgVector2 WindowManager::getWindowPosition() const
601
    {
602
        osgVector2 position;
603
        const osg::GraphicsContext::Traits* traits_ptr = gc_->getTraits ();
604
        position.x() = (osg::Vec2f::value_type) traits_ptr->x;
605
        position.y() = (osg::Vec2f::value_type) traits_ptr->y;
606
        return position;
607
    }
608
609
    WindowManager::~WindowManager()
610
    {
611
      stopCapture ();
612
      viewer_ptr_ = NULL;
613
    }
614
615
  osgViewer::ViewerRefPtr WindowManager::getViewerClone()
616
  {
617
    return ::osgViewer::ViewerRefPtr(viewer_ptr_.get());
618
  }
619
620
  void WindowManager::startCapture (const std::string& filename,
621
      const std::string& extension)
622
  {
623
    if (screen_capture_ptr_.valid ()) {
624
      screen_capture_ptr_->startCapture ();
625
      return;
626
    }
627
    /* Create an handler to save video */
628
    typedef osgViewer::ScreenCaptureHandler SCH_t;
629
    typedef SCH_t::WriteToFile WriteToFile;
630
    osg::ref_ptr<WriteToFile> wtf =
631
        new WriteToFile (filename, extension, WriteToFile::SEQUENTIAL_NUMBER);
632
    screen_capture_ptr_ = new SCH_t (wtf.get(), -1);
633
    /* Screen capture can be stopped with stopCapture */
634
    screen_capture_ptr_->setKeyEventTakeScreenShot (0);
635
    screen_capture_ptr_->setKeyEventToggleContinuousCapture (0);
636
    viewer_ptr_->addEventHandler (screen_capture_ptr_);
637
    screen_capture_ptr_->startCapture ();
638
  }
639
640
  void WindowManager::stopCapture ()
641
  {
642
    if (!screen_capture_ptr_) return;
643
    screen_capture_ptr_->stopCapture ();
644
    frame ();
645
    // Remove event handler
646
    typedef osgViewer::View::EventHandlers EventHandlers;
647
    EventHandlers& handlers = viewer_ptr_->getEventHandlers();
648
    EventHandlers::iterator _handler =
649
      std::find (handlers.begin(), handlers.end(), screen_capture_ptr_);
650
    if (_handler != handlers.end()) {
651
      handlers.erase (_handler);
652
      screen_capture_ptr_.release();
653
    }
654
  }
655
656
  bool WindowManager::writeNodeFile (const std::string& fn)
657
  {
658
    osg::ref_ptr <osgDB::Options> options = new osgDB::Options;
659
    options->setOptionString ("NoExtras");
660
    return osgDB::writeNodeFile (*(viewer_ptr_->getSceneData()), fn,
661
        options.get());
662
  }
663
664
  void WindowManager::attachCameraToNode(NodePtr_t node)
665
  {
666
    osgGA::NodeTrackerManipulator* manip
667
      = dynamic_cast<osgGA::NodeTrackerManipulator*>
668
      (manipulator_ptr->getMatrixManipulatorWithIndex(nodeTrackerManipulatorIndex));
669
670
    if (manip)
671
      {
672
	manip->setTrackNode(node->getOsgNode().get());
673
	// manip->setRotationMode(osgGA::NodeTrackerManipulator::TRACKBALL);
674
	manip->setTrackerMode(osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION);
675
	manipulator_ptr->selectMatrixManipulator(nodeTrackerManipulatorIndex);
676
      }
677
    else
678
      std::cout << "Unexpected manipulator in viewer" << std::endl;
679
  }
680
681
  void WindowManager::detachCamera()
682
  {
683
    manipulator_ptr->selectMatrixManipulator(0);
684
  }
685
686
  void WindowManager::getCameraTransform(osg::Vec3d& pos,osg::Quat& rot){
687
    osg::Matrixd matrix = manipulator_ptr->getMatrix();
688
    rot = matrix.getRotate();
689
    pos = matrix.getTrans();
690
  }
691
692
  void WindowManager::setCameraTransform(const osg::Vec3d &pos, const osg::Quat &rot){
693
   osg::Matrixd matrix= osg::Matrixd();
694
   matrix.setTrans(pos.x(),pos.y(),pos.z());
695
   matrix.setRotate(rot);
696
   manipulator_ptr->setByMatrix(matrix);
697
   lastSceneWasDisrty_=true;
698
  }
699
700
701
    /* End declaration of public function members */
702
703
} /* namespace viewer */
704
705

3
} /* namespace gepetto */