SkeletonEditingPlugin.cc 55.1 KB
Newer Older
Dirk Wilden's avatar
Dirk Wilden committed
1 2 3 4 5 6 7
#include "SkeletonEditingPlugin.hh"

#include <iostream>

#include <OpenFlipper/BasePlugin/PluginFunctions.hh>
#include <OpenFlipper/common/GlobalOptions.hh>
#include <ObjectTypes/Skeleton/Skeleton.hh>
Dirk Wilden's avatar
Dirk Wilden committed
8 9
#include <ObjectTypes/Skeleton/BaseSkin.hh>
#include <ObjectTypes/Skeleton/SkeletonObjectData.hh>
10
#include <ACG/Geometry/Algorithms.hh>
Dirk Wilden's avatar
Dirk Wilden committed
11 12 13 14 15 16 17 18 19
//--------------------------------------------------------------------------------

/** \brief Default Constructor
 *
 */
SkeletonEditingPlugin::SkeletonEditingPlugin()
 : currentSkeleton_(-1),
   currentJoint_(-1),
   jointPreview_(false),
Dirk Wilden's avatar
Dirk Wilden committed
20
   transformChildJoints_(false),
Jan Möbius's avatar
Jan Möbius committed
21
   transformAllFrames_(true),
22
   inverseKinematic_(false),
23
   rotateCoordSystem_(false),
24 25 26
   dblClick_(false),
   lastRenderer_(""),
   rendererChanged_(false)
27

Dirk Wilden's avatar
Dirk Wilden committed
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
{
    manip_size_          = 1.0;
    manip_size_modifier_ = 1.0;
}

//--------------------------------------------------------------------------------

/** \brief Destructor
 *
 */
SkeletonEditingPlugin::~SkeletonEditingPlugin()
{

}


/*******************************************************************************
        BaseInterface implementation
 *******************************************************************************/

/** \brief Initialization of the plugin when it is loaded by the core
 *
 */
void SkeletonEditingPlugin::pluginsInitialized() {

  emit addHiddenPickMode("MoveJoints");
  emit addHiddenPickMode("DeleteJoints");
  emit addHiddenPickMode("InsertJoints");
56
  emit addHiddenPickMode("SplitJoints");
Dirk Wilden's avatar
Dirk Wilden committed
57 58 59
  emit addHiddenPickMode("SelectJoints");
  emit setPickModeMouseTracking ("MoveJoints", true);
  emit setPickModeMouseTracking ("InsertJoints", true);
60
  emit setPickModeMouseTracking ("SplitJoints", true);
Dirk Wilden's avatar
Dirk Wilden committed
61 62 63 64 65 66 67

  //KEYS
  emit registerKey (Qt::Key_Shift, Qt::ShiftModifier, tr("Manipulator rotation"), true);
  emit registerKey (Qt::Key_Shift, Qt::NoModifier, tr("Manipulator rotation"), true);

  //TOOLBAR
  toolbar_ = new QToolBar(tr("Skeleton Editing"));
68
  toolbar_->setObjectName("Skeleton_Editing_Toolbar");
Dirk Wilden's avatar
Dirk Wilden committed
69 70 71 72 73 74 75 76 77 78 79 80

  toolBarActions_ = new QActionGroup(toolbar_);

  skeletonEditingAction_ = new QAction(tr("<B>Skeleton Editing</B><br>Modify the structure of a skeleton"), toolBarActions_);
  skeletonEditingAction_->setStatusTip(tr("Modify the structure of a skeleton."));
  skeletonEditingAction_->setIcon(QIcon(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"skeleton_editing.png") );
  skeletonEditingAction_->setCheckable(true);
  toolbar_->addAction(skeletonEditingAction_);

  connect(toolBarActions_, SIGNAL(triggered(QAction*)), this, SLOT(slotSetEditingMode(QAction*)) );

  emit addToolbar(toolbar_);
81

Dirk Wilden's avatar
Dirk Wilden committed
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
  pickToolbar_ = new QToolBar(tr("Skeleton Editing"));
  pickToolbar_->setAttribute(Qt::WA_AlwaysShowToolTips, true);
  pickToolBarActions_ = new QActionGroup(pickToolbar_);
  pickToolBarActions_->setExclusive (false);

  selectJointAction_ = new QAction(tr("<B>Select Joint</B><br>Toggle joint selection"), pickToolBarActions_);
  selectJointAction_->setStatusTip(tr("Toggle the selection state of a joint."));
  selectJointAction_->setIcon(QIcon(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"skeleton_selectJoint.png") );
  selectJointAction_->setCheckable(true);
  pickToolbar_->addAction(selectJointAction_);

  insertJointAction_ = new QAction(tr("<B>Insert Joint</B><br>Add a joint to the skeleton"), pickToolBarActions_);
  insertJointAction_->setStatusTip(tr("<DoubleClick> to start a new skeleton and end joint path. <Click> to select parent and position for new joints."));
  insertJointAction_->setIcon(QIcon(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"skeleton_insertJoint.png") );
  insertJointAction_->setCheckable(true);
  pickToolbar_->addAction(insertJointAction_);

99 100 101 102 103 104
  splitJointAction_ = new QAction(tr("<B>Split Joint</B><br>Add a Joint between two other Joints"), pickToolBarActions_);
  splitJointAction_->setStatusTip(tr("Click on a joint which will be the new child Joint."));
  splitJointAction_->setIcon(QIcon(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"skeleton_splitJoint.png") );
  splitJointAction_->setCheckable(true);
  pickToolbar_->addAction(splitJointAction_);

Dirk Wilden's avatar
Dirk Wilden committed
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
  deleteJointAction_ = new QAction(tr("<B>Delete Joint</B><br>Remove a joint from the skeleton"), pickToolBarActions_);
  deleteJointAction_->setStatusTip(tr("<Press> to select a joint. <Release> to delete it."));
  deleteJointAction_->setIcon(QIcon(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"skeleton_deleteJoint.png") );
  deleteJointAction_->setCheckable(true);
  pickToolbar_->addAction(deleteJointAction_);

  moveJointAction_ = new QAction(tr("<B>Transform Joint</B><br>Transform a joint from the skeleton"), pickToolBarActions_);
  moveJointAction_->setStatusTip(tr("Transform a joint from the skeleton."));
  moveJointAction_->setIcon(QIcon(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"skeleton_moveJoint.png") );
  moveJointAction_->setCheckable(true);
  pickToolbar_->addAction(moveJointAction_);

  pickToolbar_->addSeparator();

  rotateManipAction_ = new QAction(tr("Rotate manipulator"), pickToolBarActions_);
  rotateManipAction_->setStatusTip(tr("Rotate manipulator. <Shift>"));
  rotateManipAction_->setToolTip(tr("Rotate manipulator. <Shift>"));
  rotateManipAction_->setIcon(QIcon(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"skeleton_maniprotate.png") );
  rotateManipAction_->setCheckable(true);
  pickToolbar_->addAction(rotateManipAction_);
  connect(rotateManipAction_, SIGNAL(toggled(bool)), this, SLOT(slotRotateManipulator(bool)) );

  pickToolbar_->addSeparator();

  transformAllManipAction_ = new QAction(tr(""), pickToolBarActions_);
  transformAllManipAction_->setStatusTip(tr("Apply the relative transformation to all frames of the animation."));
  transformAllManipAction_->setToolTip(tr("<B>Transform whole animation</B><br>Transform all frames of the animation simultaneously."));
  transformAllManipAction_->setIcon(QIcon(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"skeleton_manipAllFrames.png") );
  transformAllManipAction_->setCheckable(true);
  transformAllManipAction_->setChecked(transformAllFrames_);
  pickToolbar_->addAction(transformAllManipAction_);
136

Dirk Wilden's avatar
Dirk Wilden committed
137 138 139 140 141 142 143
  transformChildManipAction_ = new QAction(tr("Transform Child Joints"), pickToolBarActions_);
  transformChildManipAction_->setStatusTip(tr("Apply joint transformation to child joints as well and thereby rigidly move the whole subtree."));
  transformChildManipAction_->setToolTip(tr("<B>Transform child joints</B><br>Apply joint transformation to all child joints as well."));
  transformChildManipAction_->setIcon(QIcon(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"skeleton_manipChildTransform.png") );
  transformChildManipAction_->setCheckable(true);
  transformChildManipAction_->setChecked(transformChildJoints_);
  pickToolbar_->addAction(transformChildManipAction_);
144

145 146 147
  inverseKinematicAction_ = new QAction(tr("Inverse kinematic"), pickToolBarActions_);
  inverseKinematicAction_->setStatusTip(tr("Move selected joint using inverse kinematic."));
  inverseKinematicAction_->setToolTip(tr("<B>Inverse kinematic</B><br>Move selected joint using inverse kinematic."));
148
  inverseKinematicAction_->setIcon(QIcon(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"skeleton_inverseKinematic.png") );
149 150 151 152
  inverseKinematicAction_->setCheckable(true);
  inverseKinematicAction_->setChecked(inverseKinematic_);
  pickToolbar_->addAction(inverseKinematicAction_);

153 154 155 156 157 158 159 160 161
  rotateCoordSystemAction_ = new QAction(tr("Rotate local coordinate system"), pickToolBarActions_);
  rotateCoordSystemAction_->setStatusTip(tr(""));
  rotateCoordSystemAction_->setToolTip(tr("<B></B><br>."));
  rotateCoordSystemAction_->setIcon(QIcon(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"skeleton_invkinematic.png") );
  rotateCoordSystemAction_->setCheckable(true);
  rotateCoordSystemAction_->setChecked(rotateCoordSystem_);
  pickToolbar_->addAction(rotateCoordSystemAction_);


Dirk Wilden's avatar
Dirk Wilden committed
162 163 164 165 166
  connect(pickToolBarActions_, SIGNAL(triggered(QAction*)), this, SLOT(slotPickToolbarAction(QAction*)) );

  emit setPickModeToolbar("MoveJoints", pickToolbar_);
  emit setPickModeToolbar("DeleteJoints", pickToolbar_);
  emit setPickModeToolbar("InsertJoints", pickToolbar_);
167
  emit setPickModeToolbar("SplitJoints", pickToolbar_);
Dirk Wilden's avatar
Dirk Wilden committed
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
  emit setPickModeToolbar("SelectJoints", pickToolbar_);

  setDescriptions();
}

//------------------------------------------------------------------------------

void SkeletonEditingPlugin::slotObjectUpdated( int _id, const UpdateType _type){

  if ( !_type.contains(UPDATE_GEOMETRY) )
    return;

  for (uint i=0; i < activeManipulators_.size(); i++){

    if ( activeManipulators_[i] != _id )
      continue;

    BaseObjectData* obj = 0;

    PluginFunctions::getObject( activeManipulators_[i], obj );

    if (obj != 0 && obj->manipPlaced())
      updateManipulatorPosition(obj);
  }
}

/*******************************************************************************
        ToolBoxInterface implementation
 *******************************************************************************/

void SkeletonEditingPlugin::initializePlugin()
{

}


/*******************************************************************************
        MouseInterface implementation
 *******************************************************************************/

/** \brief MouseWheel event occured
 *
 * @param _event the event that occured
 */
void SkeletonEditingPlugin::slotMouseWheelEvent(QWheelEvent * _event, const std::string & /*_mode*/)
{
  // Skip execution if this is not our pick mode
  if( (PluginFunctions::pickMode() != "MoveJoints") || PluginFunctions::actionMode() != Viewer::PickingMode)
    return;

  // compute the manipulator size modifier based on the mouse wheel change
  manip_size_modifier_ = manip_size_modifier_ - (float)_event->delta() / 120.0 * 0.1;

  // Resize all manipulators based on the modifier on all objects
  for ( PluginFunctions::ObjectIterator o_it(PluginFunctions::ALL_OBJECTS) ; o_it != PluginFunctions::objectsEnd(); ++o_it)
    o_it->manipulatorNode()->set_size(manip_size_ * manip_size_modifier_);

  // Redraw scene with updated manipulators
  emit updateView();
}


//------------------------------------------------------------------------------

/** \brief MousePress event occured
 *
 * @param _event the event that occured
 */
void SkeletonEditingPlugin::slotMouseEvent(QMouseEvent* _event) {

  if (PluginFunctions::actionMode() != Viewer::PickingMode)
    return;

  if ( PluginFunctions::pickMode() == ("DeleteJoints") )
    deleteJoint(_event);
  if ( PluginFunctions::pickMode() == ("InsertJoints") )
    insertJoint(_event);
  if ( PluginFunctions::pickMode() == ("MoveJoints") )
    moveJoint(_event);
  if ( PluginFunctions::pickMode() == ("SelectJoints") )
    selectJoint(_event);
249 250
  if (PluginFunctions::pickMode() == ("SplitJoints"))
  	splitJoint(_event);
Dirk Wilden's avatar
Dirk Wilden committed
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
}

/*******************************************************************************
        KeyInterface implementation
 *******************************************************************************/

void SkeletonEditingPlugin::slotKeyEvent (QKeyEvent* _event)
{
  if (_event->key() == Qt::Key_Shift)
    rotateManipAction_->setChecked(true);
}

//------------------------------------------------------------------------------

void SkeletonEditingPlugin::slotKeyReleaseEvent (QKeyEvent* _event)
{
  if ( _event->key() == Qt::Key_Shift)
    rotateManipAction_->setChecked(false);
}

/*******************************************************************************
        PickingInterface implementation
 *******************************************************************************/

/** \brief slot is called when the pickMode changed
 *
 * @param _mode new pickMode
 */
void SkeletonEditingPlugin::slotPickModeChanged( const std::string& _mode)
{
  if (_mode != "InsertJoints")
    if ( insertJointAction_->isChecked() )
      cancelJointInsertion();

285
  moveJointAction_->setChecked(   _mode == "MoveJoints" );
Dirk Wilden's avatar
Dirk Wilden committed
286 287 288
  insertJointAction_->setChecked( _mode == "InsertJoints" );
  deleteJointAction_->setChecked( _mode == "DeleteJoints" );
  selectJointAction_->setChecked( _mode == "SelectJoints" );
289
  splitJointAction_->setChecked(  _mode == "SplitJoints" );
290

Dirk Wilden's avatar
Dirk Wilden committed
291
  skeletonEditingAction_->setChecked( (_mode == "MoveJoints")  ||(_mode == "InsertJoints")
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
                                    ||(_mode == "DeleteJoints")||(_mode == "SelectJoints")
                                    || (_mode == "SplitJoints"));

  // We left the pickmodes, that are used for skeletonediting
  // If the mode is "", we are in examine mode or anything else
  // But we do not change the renderer than
  if ( (_mode != "")              &&
       (_mode != "MoveJoints")    &&
       (_mode != "InsertJoints")  &&
       (_mode != "DeleteJoints")  &&
       (_mode != "SelectJoints")  &&
       (_mode != "SplitJoints")) {

    // Get the currently active renderer and switch to default one
    QString currentRenderer;
    emit getCurrentRenderer(PluginFunctions::activeExaminer(), currentRenderer);

    // If we still have the Depth peeling renderer, we switch back
    // otherwise the user changed the active renderer and we do not override the setting
    if ( rendererChanged_ && (currentRenderer == "Depth Peeling Renderer" ) ) {
      emit setRenderer(PluginFunctions::activeExaminer(),lastRenderer_);
      rendererChanged_ = false;
    }


  }

319

Dirk Wilden's avatar
Dirk Wilden committed
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
  showManipulators();
}

/*******************************************************************************
        SkeletonEditingPlugin implementation
 *******************************************************************************/

void SkeletonEditingPlugin::slotPickToolbarAction(QAction* _action)
{
  if (_action != insertJointAction_)
    if ( insertJointAction_->isChecked() )
      cancelJointInsertion();

  if (_action == insertJointAction_){
    PluginFunctions::actionMode(Viewer::PickingMode);
    PluginFunctions::pickMode("InsertJoints");

337 338 339 340 341
  }else if (_action == splitJointAction_){
    PluginFunctions::actionMode(Viewer::PickingMode);
    PluginFunctions::pickMode("SplitJoints");

  }else if (_action == deleteJointAction_){
Dirk Wilden's avatar
Dirk Wilden committed
342 343 344 345 346 347 348 349 350 351 352 353 354 355
    PluginFunctions::actionMode(Viewer::PickingMode);
    PluginFunctions::pickMode("DeleteJoints");

  } else if (_action == moveJointAction_) {
    PluginFunctions::actionMode(Viewer::PickingMode);
    PluginFunctions::pickMode("MoveJoints");
  } else if (_action == selectJointAction_) {
    PluginFunctions::actionMode(Viewer::PickingMode);
    PluginFunctions::pickMode("SelectJoints");

  } else if (_action == transformAllManipAction_)
    transformAllFrames_ = transformAllManipAction_->isChecked();
  else if (_action == transformChildManipAction_)
    transformChildJoints_ = transformChildManipAction_->isChecked();
356 357
  else if (_action == inverseKinematicAction_)
  	inverseKinematic_ = inverseKinematicAction_->isChecked();
358 359
  else if (_action == rotateCoordSystemAction_)
  	rotateCoordSystem_ = rotateCoordSystemAction_->isChecked();
360

Dirk Wilden's avatar
Dirk Wilden committed
361 362 363 364
  moveJointAction_->setChecked(   _action == moveJointAction_);
  insertJointAction_->setChecked( _action == insertJointAction_ );
  deleteJointAction_->setChecked( _action == deleteJointAction_ );
  selectJointAction_->setChecked( _action == selectJointAction_ );
365
  splitJointAction_->setChecked( _action == splitJointAction_ );
Dirk Wilden's avatar
Dirk Wilden committed
366 367 368 369
}

//--------------------------------------------------------------------------------

Dirk Wilden's avatar
Dirk Wilden committed
370
void SkeletonEditingPlugin::slotSetEditingMode(QAction* /*_action*/)
Dirk Wilden's avatar
Dirk Wilden committed
371
{
372 373 374 375 376 377 378 379 380 381 382 383

  if ( ! rendererChanged_ ) {

    // Get the currently active renderer and switch to default one
    emit getCurrentRenderer(PluginFunctions::activeExaminer(), lastRenderer_);
    emit setRenderer(PluginFunctions::activeExaminer(),"Depth Peeling Renderer");

    // remember, that we changed the active renderer in this plugin
    // to prevent switching, if we did not do it
    rendererChanged_ = true;
  }

Dirk Wilden's avatar
Dirk Wilden committed
384 385 386 387
  PluginFunctions::actionMode(Viewer::PickingMode);
  PluginFunctions::pickMode("MoveJoints");
}

388
//--------------------------------------------------------------------------------
Dirk Wilden's avatar
Dirk Wilden committed
389 390 391 392 393

void SkeletonEditingPlugin::slotRotateManipulator(bool _toggled)
{
  QtTranslationManipulatorNode::ManipulatorMode mode;

Dirk Wilden's avatar
Dirk Wilden committed
394 395 396 397
  bool ourPickMode = (PluginFunctions::actionMode() == Viewer::PickingMode)
                   &&( ( PluginFunctions::pickMode() == ("DeleteJoints") )
                     ||( PluginFunctions::pickMode() == ("InsertJoints") )
                     ||( PluginFunctions::pickMode() == ("MoveJoints") )
398 399
                     ||( PluginFunctions::pickMode() == ("SelectJoints")
                     ||( PluginFunctions::pickMode() == ("SplitJoints"))));
Dirk Wilden's avatar
Dirk Wilden committed
400 401

  if (_toggled && ourPickMode){
Dirk Wilden's avatar
Dirk Wilden committed
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
    mode = QtTranslationManipulatorNode::LocalRotation;
    PluginFunctions::setViewObjectMarker (&objectMarker_);
  } else {
    mode = QtTranslationManipulatorNode::TranslationRotation;
    PluginFunctions::setViewObjectMarker (PluginFunctions::defaultViewObjectMarker ());
  }

  for (uint i=0; i < activeManipulators_.size(); i++){

    BaseObjectData* obj = 0;

    PluginFunctions::getObject( activeManipulators_[i], obj );

    if (obj != 0 && obj->manipPlaced())
      obj->manipulatorNode()->setMode ( mode );
  }
}

420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
//--------------------------------------------------------------------------------
/** \brief split the selected joint. selected joint will be child of new joint
 *
 * @param _event  mouseEvent that occured
 */
void SkeletonEditingPlugin::splitJoint(QMouseEvent* _event)
{
	if ( _event->type() == QEvent::MouseButtonPress )
	{
		if ( jointPreview_ )
			return;

		// try to select a joint from which the insertion should be started
		unsigned int    node_idx, target_idx;
		ACG::Vec3d      hitPoint;
		BaseObjectData* object;

		//disable picking for anything but skeletons
		for ( PluginFunctions::ObjectIterator o_it(PluginFunctions::ALL_OBJECTS) ; o_it != PluginFunctions::objectsEnd(); ++o_it)
			o_it->enablePicking( o_it->dataType(DATA_SKELETON) );

		//perform picking
442
		bool successfullyPicked = PluginFunctions::scenegraphPick(ACG::SceneGraph::PICK_ANYTHING, _event->pos(), node_idx,
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
				target_idx, &hitPoint) && PluginFunctions::getPickedObject(node_idx, object);

		//reenable picking for anything
		for ( PluginFunctions::ObjectIterator o_it(PluginFunctions::ALL_OBJECTS) ; o_it != PluginFunctions::objectsEnd(); ++o_it)
			o_it->enablePicking( true );

		if ( successfullyPicked )
		{
			Skeleton* skeleton = PluginFunctions::skeleton( object );

			if ( !skeleton )
				return;

			currentSkeleton_ = object->id();
			jointPreview_ = false;

			Skeleton::Joint* joint = skeleton->joint( target_idx );

			if ( joint )
			{
				//clear selection
				for (Skeleton::Iterator it=skeleton->begin(); it != skeleton->end(); ++it)
					(*it)->setSelected(false);

				currentJoint_ = joint->id();
				joint->setSelected(true);
			}
			else
				return;

			Skeleton::Joint* parent = joint->parent();
			if (!parent)
				return;

			BaseObjectData* baseObject = 0;
			PluginFunctions::getObject(currentSkeleton_, baseObject);
			if (baseObject == 0)
				return;

			//now we got all data (selected joint, is not root)
			//so we can insert a new Joint
			Skeleton::Joint* newJoint = new Skeleton::Joint(joint);
			skeleton->insertJoint(joint,newJoint);

			//compute the middle of Joint and his old parent
			ACG::Vec3d middle = ACG::Vec3d(0.0,0.0,0.0);

			//first, modify the reference pose
			Skeleton::Pose* pose = skeleton->referencePose();

			ACG::Vec3d jointPos = pose->globalTranslation(joint->id());
			ACG::Vec3d parentPos = pose->globalTranslation(parent->id());

			middle = parentPos + 0.5*(jointPos-parentPos);
			pose->setGlobalTranslation(newJoint->id(),middle,true);


			//second, modify all poses in all animations
			for (unsigned int a=0; a < skeleton->animationCount(); a++)
				if ( AnimationHandle(a, 0 ).isValid() )
				{
					AnimationT<ACG::Vec3d> *animation = skeleton->animation( AnimationHandle(a, 0 ) );
					for (int iFrame=0; iFrame < (int)animation->frameCount(); iFrame++)
					{
						Skeleton::Pose* pose = skeleton->pose( AnimationHandle(a, iFrame ) );
						if (!pose)
							continue;

						ACG::Vec3d jointPos = pose->globalTranslation(joint->id());
						ACG::Vec3d parentPos = pose->globalTranslation(parent->id());

						middle = parentPos + 0.5*(jointPos-parentPos);
						pose->setGlobalTranslation(newJoint->id(),middle,true);
					}
				}

			emit updatedObject(baseObject->id(), UPDATE_GEOMETRY);
		}
	}
}
Dirk Wilden's avatar
Dirk Wilden committed
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
//------------------------------------------------------------------------------

/** \brief Place and show the Manipulator
 *
 * @param _event  mouseEvent that occured
 */
void SkeletonEditingPlugin::placeManip(QMouseEvent * _event) {
    unsigned int node_idx, target_idx;
    OpenMesh::Vec3d hitPoint;
    BaseObjectData* object;

    bool successfullyPicked = false;

    int data = -1;

    //disable picking for anything but skeletons
    for ( PluginFunctions::ObjectIterator o_it(PluginFunctions::ALL_OBJECTS) ; o_it != PluginFunctions::objectsEnd(); ++o_it)
      o_it->enablePicking( o_it->dataType(DATA_SKELETON) );

    //perform picking
543 544
    successfullyPicked = PluginFunctions::scenegraphPick(ACG::SceneGraph::PICK_ANYTHING, _event->pos(), node_idx, target_idx, &hitPoint) &&
                         PluginFunctions::getPickedObject(node_idx, object);
545

Dirk Wilden's avatar
Dirk Wilden committed
546 547 548 549 550 551 552 553
    //reenable picking for anything
    for ( PluginFunctions::ObjectIterator o_it(PluginFunctions::ALL_OBJECTS) ; o_it != PluginFunctions::objectsEnd(); ++o_it)
      o_it->enablePicking( true );

    if ( successfullyPicked && object->dataType(DATA_SKELETON) ) {

      hitPoint = getNearestJoint(PluginFunctions::skeletonObject(object), hitPoint, data);

Jan Möbius's avatar
Jan Möbius committed
554
      PluginFunctions::setDrawMode(ACG::SceneGraph::DrawModes::SOLID_SMOOTH_SHADED | ACG::SceneGraph::DrawModes::WIREFRAME );
Dirk Wilden's avatar
Dirk Wilden committed
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
    }

    if (successfullyPicked) {

        object->manipPlaced(true);

        if (data != -1)
          object->manipulatorNode()->setData( data );

        object->manipulatorNode()->loadIdentity();
        object->manipulatorNode()->set_center(hitPoint);
        object->manipulatorNode()->set_draw_cylinder(true);
        object->manipulatorNode()->set_autosize(QtTranslationManipulatorNode::Once);
        object->manipulatorNode()->set_size(manip_size_ * manip_size_modifier_);
        object->manipulatorNode()->setMode( QtTranslationManipulatorNode::TranslationRotation );
        object->manipulatorNode()->show();

572 573 574 575 576 577 578 579 580 581 582
        // Get the global matrix from the picked joint
        Skeleton* skeleton = PluginFunctions::skeleton( object );
        Skeleton::Joint* pickedJoint = skeleton->joint( data );
        Skeleton::Pose* currentPose = activePose(PluginFunctions::skeletonObject(object));
        const Matrix4x4 pickedGlobalMatrix = currentPose->globalMatrix(pickedJoint->id());

        // Orient the manipulator to be aligned with the joint coordinate system.
        Vector x_axis = pickedGlobalMatrix.transform_vector(Vector(1.0, 0.0, 0.0));
        Vector y_axis = pickedGlobalMatrix.transform_vector(Vector(0.0, 1.0, 0.0));

        object->manipulatorNode()->set_direction(x_axis,y_axis);
583
        object->manipulatorNode()->enable_rotations(QtTranslationManipulatorNode::ALL_AXIS);
584

Dirk Wilden's avatar
Dirk Wilden committed
585 586
        object->manipulatorNode()->apply_transformation(false);

587 588 589 590
        //deactivate unused rotation axes
        //and set the direction correctly
        if (rotateCoordSystem_)
        {
591 592 593
          // Get parent and child joints if they exist.
          Skeleton::Joint* parentJoint = pickedJoint->parent();
          Skeleton::Joint* childJoint  = pickedJoint->child(0);
594

595 596
          // Root joint uses the local joint coordinate system
          if ( parentJoint == 0 ) {
597

598 599 600
          } else if ( childJoint == 0) { // Leaf joint, only the previous axis is important
            Vector prevAxis = currentPose->globalTranslation(pickedJoint->id()) - currentPose->globalTranslation(parentJoint->id());
            prevAxis.normalize();
601

602 603 604
            // Create a local coordinate system based on the axis and an arbitrary right vector
            Vector cross = ACG::Geometry::perpendicular(prevAxis);
            cross.normalize();
605 606


607 608 609
            object->manipulatorNode()->set_direction(prevAxis,cross);

            // As we only allow rotations around the main axis, we disable the others
Jan Möbius's avatar
Jan Möbius committed
610
            //object->manipulatorNode()->enable_rotations(QtTranslationManipulatorNode::X_AXIS);
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625

          } else { //Joint in between, use both to estimate a good orientation of the manipulator
            Vector prevAxis = currentPose->globalTranslation(pickedJoint->id()) - currentPose->globalTranslation(parentJoint->id());
            Vector nextAxis = currentPose->globalTranslation(childJoint->id())  - currentPose->globalTranslation(pickedJoint->id());
            prevAxis.normalize();
            nextAxis.normalize();

            // Create a local coordinate system based on the axis and an right vector depending on the bone positions
            Vector right = prevAxis % nextAxis;
            right.normalize();


            object->manipulatorNode()->set_direction(prevAxis,right);

            // As we only allow rotations around the main axis, we disable the others
Jan Möbius's avatar
Jan Möbius committed
626
            //object->manipulatorNode()->enable_rotations(QtTranslationManipulatorNode::X_AXIS);
627 628 629

          }

630 631
        }

Dirk Wilden's avatar
Dirk Wilden committed
632 633 634
        // Disconnect a previously connected Signal
        disconnect(object->manipulatorNode() , SIGNAL(manipulatorMoved(QtTranslationManipulatorNode*,QMouseEvent*)),
                   this , SLOT( manipulatorMoved(QtTranslationManipulatorNode*,QMouseEvent*)));
635

Dirk Wilden's avatar
Dirk Wilden committed
636 637
        disconnect(object->manipulatorNode() , SIGNAL(positionChanged(QtTranslationManipulatorNode*)),
                  this , SLOT( ManipulatorPositionChanged(QtTranslationManipulatorNode*)));
638

Dirk Wilden's avatar
Dirk Wilden committed
639 640 641 642 643 644 645 646
        // Reconnect the signals.
        connect(object->manipulatorNode() , SIGNAL(manipulatorMoved(QtTranslationManipulatorNode*,QMouseEvent*)),
                this , SLOT( manipulatorMoved(QtTranslationManipulatorNode*,QMouseEvent*)));

        connect(object->manipulatorNode() , SIGNAL(positionChanged(QtTranslationManipulatorNode*)),
                this , SLOT( ManipulatorPositionChanged(QtTranslationManipulatorNode*)));

        emit updateView();
647

Dirk Wilden's avatar
Dirk Wilden committed
648
        bool found = false;
649

Dirk Wilden's avatar
Dirk Wilden committed
650 651 652 653 654 655 656 657 658 659 660
        for (uint i=0; i < activeManipulators_.size(); i++)
          if ( activeManipulators_[i] == object->id() ){
            found = true;
            break;
          }

        if ( !found )
          activeManipulators_.push_back( object->id() );

    }
}
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
//------------------------------------------------------------------------------
/*
 * \brief move a joint using inverse Kinematic
 * @param dest the new position of the joint
 * @param currentPose the current pose in which the joint is moved
 * @param pickedJoint your picked joint
 * @param rotatbleJoints joints, which can be rotate. It has to be a ordered set in this order (picked,marked]. "picked" is our imaginary -1th element, his parent the 0th element and so on. "marked" is the last element. "marked"s matrix can rotate, but the "marked" will not be translated.
 */
void SkeletonEditingPlugin::inverseKinematic(ACG::Vec3d dest,Skeleton::Pose* currentPose,Skeleton::Joint* pickedJoint, std::vector<Skeleton::Joint*> rotatableJoints)
{
	//Now we can rotate every Joint in rotatableJoints
	ACG::Vec3d pickedJointPos = currentPose->globalMatrix(pickedJoint->id()).transform_point(ACG::Vec3d(0.0,0.0,0.0));
	for(std::size_t i = 5; i && pickedJointPos != dest; --i )
	{

		//iterates through the skeleton from our picked joint to our fixed/root
		for (std::vector<Skeleton::Joint*>::iterator iter = rotatableJoints.begin() ; iter != rotatableJoints.end();  ++iter)
		{
			const unsigned int currentId = (*iter)->id();

			//when we rotate to the false side
			//we are going to compute a new angle
			//it is more precise
			int angleFac = -1;
			bool rightRotation = true;
			unsigned int tries = 0;//to be sure that we are terminate
			do
			{
				//update the position of our picked Joint
				pickedJointPos = currentPose->globalMatrix(pickedJoint->id()).transform_point(ACG::Vec3d(0.0,0.0,0.0));

				//get the position and the matrix of our current joint
				const ACG::Matrix4x4d currentGlobalMatrix = currentPose->globalMatrix(currentId);
				const ACG::Vec3d currentJointPos = currentGlobalMatrix.transform_point(ACG::Vec3d(0.0,0.0,0.0));

				ACG::Vec3d toDest = currentJointPos - dest; //distance from current to Destination
				ACG::Vec3d toPickedJoint = currentJointPos - pickedJointPos;//distance from current to picked Joint

				//get angle of toDest and toPickedJoint
				double theta = (double)angleFac*acos(dot(toPickedJoint ,toDest) / sqrt( toDest.sqrnorm() * toPickedJoint.sqrnorm()));

				if(theta != theta || theta == 0)//test nan
					break;

				//get rotation matrix for theta and our rotation axis
				ACG::Vec3d rotationAxis = cross(toDest,toPickedJoint);
				ACG::Quaterniond quaternion(rotationAxis ,theta);

				ACG::Matrix4x4d changingMatrix = currentGlobalMatrix * quaternion.rotation_matrix();
				ACG::Vec3d currentTranslation = currentPose->globalTranslation( currentId );

				//set position and rotation of our currentJoint, so pickedJoint is moving to our destination
				currentPose->setGlobalMatrix(currentId, changingMatrix, false);

				//////////////todo compute direction of the angle "theta"
				//test new position
				//it is false, when the distance of pickedJoint and destination is far more away then before
				ACG::Vec3d pickedJointPosOld = pickedJointPos;
				pickedJointPos = currentPose->globalMatrix(pickedJoint->id()).transform_point(ACG::Vec3d(0.0,0.0,0.0));
				//compare the distance of the old/new position
				bool rightRotation = !( (pickedJointPos -dest).sqrnorm() > (pickedJointPosOld -dest).sqrnorm());

				if ( !rightRotation )
				{
					//not the right rotation? then rotate back and compute a new angle
					ACG::Quaterniond quaternionBack(rotationAxis ,-theta);
					ACG::Vec3d currentTranslation = currentPose->globalTranslation( currentId );

					//rotate back and compute our angle again
					changingMatrix = currentGlobalMatrix * quaternionBack.rotation_matrix();

					currentPose->setGlobalMatrix(currentId, changingMatrix , false);
					currentPose->setGlobalTranslation(currentId, currentTranslation, false);

					//compute angle again and this time, we try the other side for our rotation
					++tries;
					angleFac *= 1;
				}
			}while( rightRotation && tries <= 5);
		}
	}
}
Dirk Wilden's avatar
Dirk Wilden committed
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760

//------------------------------------------------------------------------------

/** \brief move the object when its manipulator moves
 *
 * @param _node the manipulator node
 * @param _event the mouse event
 */
void SkeletonEditingPlugin::manipulatorMoved( QtTranslationManipulatorNode* _node , QMouseEvent* _event) {

  // React on event only in move mode
  if ( PluginFunctions::pickMode() != "MoveJoints" )
    return;

  OpenFlipper::Options::redrawDisabled( true );

  int objectId = _node->getIdentifier();

761
  // rotation matrix from the manipulator
Dirk Wilden's avatar
Dirk Wilden committed
762 763 764 765
  ACG::Matrix4x4d mat;
  mat.identity();
  mat = _node->matrix();

766 767 768
  BaseObjectData* object = 0;
  PluginFunctions::getObject(objectId, object);

769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
  if(rotateCoordSystem_)
  {
  	Skeleton* skeleton = PluginFunctions::skeleton( object );

  	if (skeleton == 0)
  		return;

  	Skeleton::Joint* pickedJoint = skeleton->joint( _node->getData().toInt() );

  	if (!pickedJoint)
  		return;

  	Skeleton::Pose* currentPose = activePose(PluginFunctions::skeletonObject(object));


784 785
  	// we compute the rotation angle by applying the
        // rotation matrix from the manipulator to an arbitrary point
786 787 788 789 790 791 792 793 794
  	ACG::Vec3d tmpVec = ACG::Vec3d( 1.0, 1.0, 1.0 ).normalize();
  	ACG::Vec3d tmpRotVec = mat.transform_point( tmpVec ).normalize();

  	const ACG::Vec3d rotation_axis = cross(tmpVec,tmpRotVec).normalize();

  	const ACG::Vec3d right = cross(tmpVec, rotation_axis).normalize();

  	double angle = acos( dot(tmpVec , tmpRotVec) );

795
  	if (angle != angle) // NaN?
796 797
  		return;

798 799
  	// compute the direction of the rotation
        if (dot(right, tmpRotVec) < 0)
800 801
  		angle = -angle;

802
        // count all joints from including the picked joint to the selected joint
803 804 805 806 807 808 809 810
  	Skeleton::Joint* iter = pickedJoint;
  	unsigned int count_joint = 0;
  	while(iter && ((!iter->selected() && !iter->isRoot()) || iter == pickedJoint))
  	{
  		++count_joint;
  		iter = iter->parent();
  	}

811 812 813
  	// the weight of our rotation
        // the first joint gets rotated by 100%
  	double weight = 1.0;
814

815 816 817 818
  	// rotate the joints including the picked joints and its children
        // until the selected joint
  	// with the given angle and the given weight
  	// iter can be NULL, when pickedJoint == Root
819 820 821 822
  	iter = pickedJoint;
  	while(iter && ((!iter->selected() && !iter->isRoot()) || iter == pickedJoint))
  	{
  		unsigned int id = iter->id();
823 824
  		// get our rotation axis. notice: vector given back by "localTranslation" is in localMatrix space
  		ACG::Vec3d axis = currentPose->localTranslation(id);
825 826 827

  		ACG::Quaterniond quaternion(axis, weight*angle);

828 829 830
                // rotate the joint around its own axis
                ACG::Matrix4x4d newLocalMatrix = currentPose->localMatrix(id) * quaternion.rotation_matrix();
                currentPose->setLocalMatrix(id, newLocalMatrix, true);
831 832

  		iter = iter->parent();
833
                // interpolate the weight of the rotation between the joints
834 835 836 837
  		weight -= 1.0/count_joint;
  	}
  }

838 839 840
  if(inverseKinematic_)
  {
    Skeleton* skeleton = PluginFunctions::skeleton( object );
841
    SkeletonObject* skeletonObj = PluginFunctions::skeletonObject(object);
842

843
    if (!skeleton || !skeletonObj)
844 845 846 847 848 849 850
    	return;

    Skeleton::Joint* pickedJoint = skeleton->joint( _node->getData().toInt() );

    if (!pickedJoint)
    	return;

Jan Möbius's avatar
Jan Möbius committed
851
    Skeleton::Pose* currentPose = activePose(PluginFunctions::skeletonObject(object));
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

    const Matrix4x4 pickedGlobalMatrix = currentPose->globalMatrix(pickedJoint->id());

    //get our destination
    const ACG::Vec3d dest = (mat*pickedGlobalMatrix).transform_point( ACG::Vec3d(0.0,0.0,0.0) );

    if (pickedJoint->isRoot())
    {
    	//we have no fixed points, when we pick our root
    	currentPose->setGlobalTranslation(pickedJoint->id(), dest, false);
    }
    else
    {
    	//get all Parent Joints (picked,fixed]
    	std::vector<Skeleton::Joint*> rotatableJoints;

    	Skeleton::Iterator iter = pickedJoint->parent();

    	//go from our picked Joint and find the first fixed/root Joint
    	for (;iter && !iter->selected() && !iter->isRoot(); iter = iter->parent())
    		rotatableJoints.push_back(*iter);

    	if (iter)
    		rotatableJoints.push_back(*iter); //save the fixed/root Joint, because he can rotate
    	else
    		return;

879
    	inverseKinematic(dest, currentPose, pickedJoint, rotatableJoints);
880

881
    	if (transformAllFrames_ && _event->type() == QEvent::MouseButtonRelease)
882 883
    		for (std::vector<Skeleton::Joint*>::iterator iter = rotatableJoints.begin() ; iter != rotatableJoints.end();  ++iter)
    		{
884 885
    			ACG::Vec3d position = currentPose->globalTranslation((*iter)->id());
    			setJointPosition(skeletonObj,*iter,position);
886
    		}
887
    }
888 889 890 891 892 893
    //update
    emit updatedObject(objectId, UPDATE_GEOMETRY);
  }
  else
  	transformJoint( objectId, _node->getData().toInt(), mat );

Dirk Wilden's avatar
Dirk Wilden committed
894 895 896 897 898
  // Reset Node
  _node->loadIdentity();
  _node->set_center(mat.transform_point(_node->center()));


Dirk Wilden's avatar
Dirk Wilden committed
899 900 901 902 903 904 905 906 907
  if (_event->type() == QEvent::MouseButtonPress)
    accumMatrix_.identity();

  accumMatrix_ *= mat;

  //only backup on mouseRelease
  if ( (_event->type() == QEvent::MouseButtonRelease) && !accumMatrix_.is_identity() )
    emit createBackup(objectId, "Joint Transformation", UPDATE_GEOMETRY);

Dirk Wilden's avatar
Dirk Wilden committed
908 909 910 911 912 913 914
  if ( object != 0)
    //check if there is a skin which has to be deformed
    if ( object->hasObjectData(OBJECTDATA_SKELETON) ){

      SkeletonObjectData* skeletonData = reinterpret_cast< SkeletonObjectData* >( object->objectData(OBJECTDATA_SKELETON) );

      AnimationHandle hAni = PluginFunctions::skeletonObject(object)->activePose();
915

Dirk Wilden's avatar
Dirk Wilden committed
916 917 918 919 920 921
      for (unsigned int i=0; i < skeletonData->skinCount(); i++){
        //deform all attached skin meshes
        int meshId = skeletonData->skin(i);

        BaseObjectData* meshObject = 0;
        PluginFunctions::getObject(meshId, meshObject);
922

Dirk Wilden's avatar
Dirk Wilden committed
923 924 925 926 927 928 929 930 931 932 933 934 935
        if (meshObject == 0)
          continue;

        if ( !meshObject->hasObjectData(OBJECTDATA_SKIN) )
          continue;

        BaseSkin* skin = reinterpret_cast< BaseSkin* > ( meshObject->objectData(OBJECTDATA_SKIN) );
        skin->deformSkin( hAni, BaseSkin::M_LBS );

        emit updatedObject(meshObject->id(), UPDATE_GEOMETRY);
      }
    }

Dirk Wilden's avatar
Dirk Wilden committed
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
  if (_event->type() == QEvent::MouseButtonRelease)
    emit updatedObject(objectId, UPDATE_GEOMETRY);

  OpenFlipper::Options::redrawDisabled( false );
}


//------------------------------------------------------------------------------

/** \brief update object when its manipulator changes position
 *
 * @param _node the manipulator node
 */
void SkeletonEditingPlugin::ManipulatorPositionChanged(QtTranslationManipulatorNode* _node ) {

  // Position has been changed of the manipulator by a direct function
  int objectId = _node->getIdentifier();

  if ( objectId > 0 ){

    BaseObjectData* object;
    PluginFunctions::getObject(objectId,object);

    // Assume that it has a good position now
    object->manipPlaced( true );
  }
}

//------------------------------------------------------------------------------

/** \brief Checks if the manipulators should be visible or not
 *
 */
void SkeletonEditingPlugin::showManipulators(){

  if ( (PluginFunctions::pickMode() == "MoveJoints") && (PluginFunctions::actionMode() == Viewer::PickingMode) ){

    for (uint i=0; i < activeManipulators_.size(); i++){

      BaseObjectData* obj = 0;

      PluginFunctions::getObject( activeManipulators_[i], obj );

      if (obj != 0 && obj->manipPlaced()) {
        obj->manipulatorNode()->show();
        emit nodeVisibilityChanged(obj->id());
      }
    }

  } else {

    for (uint i=0; i < activeManipulators_.size(); i++){

      BaseObjectData* obj = 0;

      PluginFunctions::getObject( activeManipulators_[i], obj );

      if ( obj != 0 ) {
        obj->manipulatorNode()->hide();
        emit nodeVisibilityChanged(obj->id());
      }
    }
  }

  emit updateView();
}

//--------------------------------------------------------------------------------

void SkeletonEditingPlugin::deleteJoint(QMouseEvent* _event)
{
  if ( (_event->type() == QEvent::MouseButtonPress) || (_event->type() == QEvent::MouseButtonRelease) ){
    // only select the joint on mousePress
    unsigned int    node_idx, target_idx;
    ACG::Vec3d      hitPoint;
    BaseObjectData* object;

    //disable picking for anything but skeletons
    for ( PluginFunctions::ObjectIterator o_it(PluginFunctions::ALL_OBJECTS) ; o_it != PluginFunctions::objectsEnd(); ++o_it)
      o_it->enablePicking( o_it->dataType(DATA_SKELETON) );

    //perform picking
    bool successfullyPicked = PluginFunctions::scenegraphPick(ACG::SceneGraph::PICK_VERTEX, _event->pos(), node_idx,
                                                              target_idx, &hitPoint) && PluginFunctions::getPickedObject(node_idx, object);

    //reenable picking for anything
    for ( PluginFunctions::ObjectIterator o_it(PluginFunctions::ALL_OBJECTS) ; o_it != PluginFunctions::objectsEnd(); ++o_it)
      o_it->enablePicking( true );

    if ( successfullyPicked ){
      Skeleton* skeleton = PluginFunctions::skeleton( object );

      if ( !skeleton )
        return;

      currentSkeleton_ = object->id();

      Skeleton::Joint* joint = skeleton->joint( target_idx );

      if ( joint != 0 ){

        bool wasSelected = joint->selected();

        //clear selection
        for (Skeleton::Iterator it=skeleton->begin(); it != skeleton->end(); ++it)
          (*it)->setSelected(false);

        currentJoint_ = joint->id();

        if ( _event->type() == QEvent::MouseButtonPress ) //select on press
          joint->setSelected(true);
        else{
          //delete on release
          if ( wasSelected ){
1050

Dirk Wilden's avatar
Dirk Wilden committed
1051 1052 1053 1054
            if (skeleton->jointCount() > 1){
              skeleton->removeJoint(joint);
              PluginFunctions::skeletonObject(object)->updateIndices();
              emit updatedObject(object->id(), UPDATE_ALL);
Dirk Wilden's avatar
Dirk Wilden committed
1055
              emit createBackup(object->id(), "Delete Joint", UPDATE_TOPOLOGY);
Dirk Wilden's avatar
Dirk Wilden committed
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
            } else
              emit deleteObject( object->id() );
          }
        }
      }
    }
  }

  //make sure the joint is deselected
  if (_event->type() == QEvent::MouseButtonRelease){

    BaseObjectData* baseObject = 0;
    PluginFunctions::getObject(currentSkeleton_, baseObject);

    if (baseObject == 0)
      return;

    Skeleton* skeleton = PluginFunctions::skeleton( baseObject );

    if (skeleton == 0)
      return;

    Skeleton::Joint* joint = skeleton->joint( currentJoint_ );

    if (joint != 0)
      joint->setSelected(false);

    currentSkeleton_ = -1;
    currentJoint_    = -1;
  }
}

//--------------------------------------------------------------------------------

void SkeletonEditingPlugin::insertJoint(QMouseEvent* _event)
{

  //----------------------------------------------------------------------
  // handle PRESS events
  //----------------------------------------------------------------------
  if ( _event->type() == QEvent::MouseButtonPress ){

    if ( jointPreview_ )
      return;

    // try to select a joint from which the insertion should be started
    //
    unsigned int    node_idx, target_idx;
    ACG::Vec3d      hitPoint;
    BaseObjectData* object;

    //disable picking for anything but skeletons
    for ( PluginFunctions::ObjectIterator o_it(PluginFunctions::ALL_OBJECTS) ; o_it != PluginFunctions::objectsEnd(); ++o_it)
      o_it->enablePicking( o_it->dataType(DATA_SKELETON) );

    //perform picking
    bool successfullyPicked = PluginFunctions::scenegraphPick(ACG::SceneGraph::PICK_VERTEX, _event->pos(), node_idx,
                                                              target_idx, &hitPoint) && PluginFunctions::getPickedObject(node_idx, object);

    //reenable picking for anything
    for ( PluginFunctions::ObjectIterator o_it(PluginFunctions::ALL_OBJECTS) ; o_it != PluginFunctions::objectsEnd(); ++o_it)
      o_it->enablePicking( true );

    if ( successfullyPicked ){
      Skeleton* skeleton = PluginFunctions::skeleton( object );

      if ( !skeleton )
        return;

      currentSkeleton_ = object->id();
      jointPreview_ = false;

      Skeleton::Joint* joint = skeleton->joint( target_idx );

      if ( joint != 0 ){
        //clear selection
        for (Skeleton::Iterator it=skeleton->begin(); it != skeleton->end(); ++it)
          (*it)->setSelected(false);

        currentJoint_ = joint->id();
        joint->setSelected(true);
      }
    }
  }

  //----------------------------------------------------------------------
  // handle DOUBLE CLICK events
  //----------------------------------------------------------------------
  else if ( _event->type() == QEvent::MouseButtonDblClick ){

Jan Möbius's avatar
Jan Möbius committed
1146 1147

  	dblClick_ = true;
Dirk Wilden's avatar
Dirk Wilden committed
1148 1149 1150 1151 1152 1153 1154
    // end the path in the skeleton
    if (currentSkeleton_ != -1){
      cancelJointInsertion();
      return;
    }

    // add a new skeleton at this position
Dirk Wilden's avatar
Dirk Wilden committed
1155 1156 1157 1158 1159 1160 1161 1162 1163
    unsigned int    node_idx, target_idx;
    ACG::Vec3d      lastHitPoint(0.0, 0.0, 0.0);

    // first try to pick something
    if( !PluginFunctions::scenegraphPick(ACG::SceneGraph::PICK_FACE, _event->pos(), node_idx, target_idx, &lastHitPoint) ){
      //if picking fails just unproject at position
      ACG::Vec3d viewCoords   = ACG::Vec3d(_event->pos().x(), PluginFunctions::viewerProperties().glState().context_height() - _event->pos().y(), 0.5);
      lastHitPoint = PluginFunctions::viewerProperties().glState().unproject(viewCoords);
    }
Dirk Wilden's avatar
Dirk Wilden committed
1164

Jan Möbius's avatar
Jan Möbius committed
1165

Dirk Wilden's avatar
Dirk Wilden committed
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
    int newSkeletonID = -1;
    emit addEmptyObject(DATA_SKELETON, newSkeletonID);

    BaseObjectData* baseObject = 0;
    PluginFunctions::getObject(newSkeletonID, baseObject);

    if (baseObject == 0)
      return;

    Skeleton* skeleton = PluginFunctions::skeleton( baseObject );

    if (skeleton == 0)
      return;

    Skeleton::Joint* rootJoint = new Skeleton::Joint(0);
    skeleton->addJoint(0, rootJoint);

    // set joint position
    setJointPosition(PluginFunctions::skeletonObject(baseObject), rootJoint, lastHitPoint);
    emit updatedObject(baseObject->id(), UPDATE_ALL);
Dirk Wilden's avatar
Dirk Wilden committed
1186
    emit createBackup(baseObject->id(), "Add Joints", UPDATE_ALL);
Dirk Wilden's avatar
Dirk Wilden committed
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234

    // add an additional joint which is moved on mousemove
    Skeleton::Joint* tmpJoint = new Skeleton::Joint(rootJoint);
    skeleton->addJoint(rootJoint, tmpJoint);

    // set joint position
    setJointPosition(PluginFunctions::skeletonObject(baseObject), tmpJoint, lastHitPoint);

    currentSkeleton_ = baseObject->id();
    currentJoint_    = tmpJoint->id();
    jointPreview_    = true;

  //----------------------------------------------------------------------
  // handle MOVE events
  //----------------------------------------------------------------------
  } else if ( _event->type() == QEvent::MouseMove ){

    if ( jointPreview_ ){
      //only if jointPreview_ is enabled a joint is under construction
      BaseObjectData* baseObject = 0;
      PluginFunctions::getObject(currentSkeleton_, baseObject);

      if (baseObject == 0)
        return;

      Skeleton* skeleton = PluginFunctions::skeleton( baseObject );

      if (skeleton == 0)
        return;

      Skeleton::Joint* joint = skeleton->joint( currentJoint_ );

      if (joint != 0){

        ACG::Vec3d parentPosition = activePose(PluginFunctions::skeletonObject(baseObject))->globalTranslation(joint->parent()->id());
        ACG::Vec3d parentViewer = PluginFunctions::viewerProperties().glState().project(parentPosition);

        ACG::Vec3d viewCoords   = ACG::Vec3d(_event->pos().x(), PluginFunctions::viewerProperties().glState().context_height() - _event->pos().y(), parentViewer[2]);
        ACG::Vec3d lastHitPoint = PluginFunctions::viewerProperties().glState().unproject(viewCoords);

        // set joint position
        setJointPosition(PluginFunctions::skeletonObject(baseObject), joint, lastHitPoint);
      }
    }

  //----------------------------------------------------------------------
  // handle RELEASE events
  //----------------------------------------------------------------------
Jan Möbius's avatar
Jan Möbius committed
1235 1236 1237
  } else if ( _event->type() == QEvent::MouseButtonRelease){

    if (!dblClick_) {
Dirk Wilden's avatar
Dirk Wilden committed
1238

Jan Möbius's avatar
Jan Möbius committed
1239 1240 1241 1242 1243 1244
      // CASE 1 : this is a release on a joint from which the insertion should be started
      if ( !jointPreview_ ){
        // in
        unsigned int    node_idx, target_idx;
        ACG::Vec3d      hitPoint;
        BaseObjectData* object;
Dirk Wilden's avatar
Dirk Wilden committed
1245

Jan Möbius's avatar
Jan Möbius committed
1246 1247 1248
        //disable picking for anything but skeletons
        for ( PluginFunctions::ObjectIterator o_it(PluginFunctions::ALL_OBJECTS) ; o_it != PluginFunctions::objectsEnd(); ++o_it)
          o_it->enablePicking( o_it->dataType(DATA_SKELETON) );
Dirk Wilden's avatar
Dirk Wilden committed
1249

Jan Möbius's avatar
Jan Möbius committed
1250 1251 1252
        //perform picking
        bool successfullyPicked = PluginFunctions::scenegraphPick(ACG::SceneGraph::PICK_VERTEX, _event->pos(), node_idx,
            target_idx, &hitPoint) && PluginFunctions::getPickedObject(node_idx, object);
Dirk Wilden's avatar
Dirk Wilden committed
1253

Jan Möbius's avatar
Jan Möbius committed
1254 1255 1256
        //reenable picking for anything
        for ( PluginFunctions::ObjectIterator o_it(PluginFunctions::ALL_OBJECTS) ; o_it != PluginFunctions::objectsEnd(); ++o_it)
          o_it->enablePicking( true );
Dirk Wilden's avatar
Dirk Wilden committed
1257

Jan Möbius's avatar
Jan Möbius committed
1258 1259
        if ( successfullyPicked ){
          Skeleton* skeleton = PluginFunctions::skeleton( object );
Dirk Wilden's avatar
Dirk Wilden committed
1260

Jan Möbius's avatar
Jan Möbius committed
1261 1262
          if ( !skeleton )
            return;
Dirk Wilden's avatar
Dirk Wilden committed
1263

Jan Möbius's avatar
Jan Möbius committed
1264
          currentSkeleton_ = object->id();
Dirk Wilden's avatar
Dirk Wilden committed
1265

Jan Möbius's avatar
Jan Möbius committed
1266
          Skeleton::Joint* joint = skeleton->joint( target_idx );
Dirk Wilden's avatar
Dirk Wilden committed
1267

Jan Möbius's avatar
Jan Möbius committed
1268
          if ( joint != 0 ){
Dirk Wilden's avatar
Dirk Wilden committed
1269

Jan Möbius's avatar
Jan Möbius committed
1270 1271 1272 1273 1274
            if ( joint->selected() ){
              //only if the joint is selected we are sure it was the same joint
              //like on the mouse press
              Skeleton::Joint* tmpJoint = new Skeleton::Joint(joint);
              skeleton->addJoint(joint, tmpJoint);
Dirk Wilden's avatar
Dirk Wilden committed
1275

Jan Möbius's avatar
Jan Möbius committed
1276 1277 1278
              currentJoint_ = tmpJoint->id();
              jointPreview_ = true;
            }
Dirk Wilden's avatar
Dirk Wilden committed
1279 1280 1281
          }
        }

Jan Möbius's avatar
Jan Möbius committed
1282 1283 1284 1285 1286
      } else {
        // CASE 2 : a joint is already under construction
  			//          so we insert the new joint at the current position
  			BaseObjectData* baseObject = 0;
  			PluginFunctions::getObject(currentSkeleton_, baseObject);
Dirk Wilden's avatar
Dirk Wilden committed
1287

Jan Möbius's avatar
Jan Möbius committed
1288 1289
  			if (baseObject == 0)
  				return;
Dirk Wilden's avatar
Dirk Wilden committed
1290

Jan Möbius's avatar
Jan Möbius committed
1291
  			Skeleton* skeleton = PluginFunctions::skeleton( baseObject );
Dirk Wilden's avatar
Dirk Wilden committed
1292

Jan Möbius's avatar
Jan Möbius committed
1293 1294
  			if (skeleton == 0)
  				return;
Dirk Wilden's avatar
Dirk Wilden committed
1295

Jan Möbius's avatar
Jan Möbius committed
1296
  			Skeleton::Joint* joint = skeleton->joint( currentJoint_ );
Dirk Wilden's avatar
Dirk Wilden committed
1297

Jan Möbius's avatar
Jan Möbius committed
1298
  			if (joint != 0){
Dirk Wilden's avatar
Dirk Wilden committed
1299

Jan Möbius's avatar
Jan Möbius committed
1300 1301
  				ACG::Vec3d parentPosition = activePose(PluginFunctions::skeletonObject(baseObject))->globalTranslation(joint->parent()->id());
  				ACG::Vec3d parentViewer = PluginFunctions::viewerProperties().glState().project(parentPosition);
Dirk Wilden's avatar
Dirk Wilden committed
1302

Jan Möbius's avatar
Jan Möbius committed
1303 1304
  				ACG::Vec3d viewCoords   = ACG::Vec3d(_event->pos().x(), PluginFunctions::viewerProperties().glState().context_height() - _event->pos().y(), parentViewer[2]);
  				ACG::Vec3d lastHitPoint = PluginFunctions::viewerProperties().glState().unproject(viewCoords);
Dirk Wilden's avatar
Dirk Wilden committed
1305

Jan Möbius's avatar
Jan Möbius committed
1306 1307 1308
  				// set joint position
  				setJointPosition(PluginFunctions::skeletonObject(baseObject), joint, lastHitPoint);
  				emit updatedObject(baseObject->id(), UPDATE_ALL);
1309

Jan Möbius's avatar
Jan Möbius committed
1310 1311 1312
  				Skeleton::Joint* tmpJoint = new Skeleton::Joint(joint);
  				skeleton->addJoint(joint, tmpJoint);
  				setJointPosition(PluginFunctions::skeletonObject(baseObject), tmpJoint, lastHitPoint);
1313

Jan Möbius's avatar
Jan Möbius committed
1314 1315
  				currentJoint_ = tmpJoint->id();
  			}
Dirk Wilden's avatar
Dirk Wilden committed
1316 1317


Jan Möbius's avatar
Jan Möbius committed
1318 1319 1320
  		}
  	} else
  	  dblClick_ = false;
Dirk Wilden's avatar
Dirk Wilden committed
1321 1322
  }

Jan Möbius's avatar
Jan Möbius committed
1323

Dirk Wilden's avatar
Dirk Wilden committed
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
  // keep the joint selection correct
  if ( (_event->type() != QEvent::MouseButtonPress) ){
      BaseObjectData* baseObject = 0;
      PluginFunctions::getObject(currentSkeleton_, baseObject);

      if (baseObject == 0)
        return;

      Skeleton* skeleton = PluginFunctions::skeleton( baseObject );

      if (skeleton == 0)
        return;

      for (Skeleton::Iterator it=skeleton->begin(); it != skeleton->end(); ++it)
        (*it)->setSelected(false);
  }
}

//--------------------------------------------------------------------------------

Skeleton::Pose* SkeletonEditingPlugin::activePose(SkeletonObject* _skeletonObj){

  Skeleton* skeleton = PluginFunctions::skeleton(_skeletonObj);

Mike Kremer's avatar
Mike Kremer committed
1348 1349
  if(!skeleton) return NULL;

Dirk Wilden's avatar
Dirk Wilden committed
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
  AnimationHandle handle = _skeletonObj->skeletonNode()->activePose();

  if ( !handle.isValid() ){
    //no current animation found -> transform the reference Pose
    return skeleton->referencePose();
  } else {

    Skeleton::Animation* animation = skeleton->animation(handle);
    return animation->pose( handle.frame() );
  }
}

//--------------------------------------------------------------------------------

void SkeletonEditingPlugin::setJointPosition(SkeletonObject* _skeletonObj, Skeleton::Joint* _joint, ACG::Vec3d& _position){

  Skeleton* skeleton = PluginFunctions::skeleton(_skeletonObj);

  if (skeleton == 0)
    return;

  //set position in refPose
  Skeleton::Pose* currentPose = activePose(_skeletonObj);
  currentPose->setGlobalTranslation(_joint->id(), _position );

  ACG::Matrix4x4d localMatrix = currentPose->localMatrix(_joint->id());

  //set position in animations
  for (unsigned int a=0; a < skeleton->animationCount(); a++)
    if ( AnimationHandle(a, 0 ).isValid() ){

      AnimationT<ACG::Vec3d> *animation = skeleton->animation( AnimationHandle(a, 0 ) );

      if ( animation != 0){

        //set initial joint translation
        for (int iFrame=0; iFrame < (int)animation->frameCount(); iFrame++) {

          PoseT<ACG::Vec3d>* pose = skeleton->pose( AnimationHandle(a, iFrame ) );

          if (pose != currentPose)
            pose->setLocalMatrix(_joint->id(), localMatrix );
        }
      }
    }

  if (currentPose != skeleton->referencePose())
    skeleton->referencePose()->setLocalMatrix(_joint->id(), localMatrix );
}

//--------------------------------------------------------------------------------

void SkeletonEditingPlugin::cancelJointInsertion(){

  int cSkeleton = currentSkeleton_;
  int cJoint    = currentJoint_;

  currentSkeleton_ = -1;
  currentJoint_    = -1;
  jointPreview_    = false;

  BaseObjectData* baseObject = 0;
  PluginFunctions::getObject(cSkeleton, baseObject);

  if (baseObject == 0)
    return;

  Skeleton* skeleton = PluginFunctions::skeleton( baseObject );

  if (skeleton == 0)
    return;

  Skeleton::Joint* joint = skeleton->joint( cJoint );

  if (joint != 0)
    skeleton->removeJoint(joint);

  emit updatedObject(baseObject->id(), UPDATE_ALL);
Dirk Wilden's avatar
Dirk Wilden committed
1428
  emit createBackup(baseObject->id(), "Add Joints", UPDATE_ALL);
Dirk Wilden's avatar
Dirk Wilden committed
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
}

//--------------------------------------------------------------------------------

void SkeletonEditingPlugin::moveJoint(QMouseEvent* _event)
{

  if (_event->type() == QEvent::MouseButtonDblClick && _event->button() == Qt::LeftButton){
      placeManip(_event);
  } else {

    // interaction
    ACG::SceneGraph::MouseEventAction action(_event,PluginFunctions::viewerProperties().glState());
    PluginFunctions::traverse(action);
  }
}

//--------------------------------------------------------------------------------

void SkeletonEditingPlugin::selectJoint(QMouseEvent* _event)
{

  if ( _event->type() == QEvent::MouseButtonRelease ){

    unsigned int    node_idx, target_idx;
    ACG::Vec3d      hitPoint;
    BaseObjectData* object;

    //disable picking for anything but skeletons
    for ( PluginFunctions::ObjectIterator o_it(PluginFunctions::ALL_OBJECTS) ; o_it != PluginFunctions::objectsEnd(); ++o_it)
      o_it->enablePicking( o_it->dataType(DATA_SKELETON) );

    //perform picking
    bool successfullyPicked = PluginFunctions::scenegraphPick(ACG::SceneGraph::PICK_VERTEX, _event->pos(), node_idx,
                                                              target_idx, &hitPoint) && PluginFunctions::getPickedObject(node_idx, object);

    //reenable picking for anything
    for ( PluginFunctions::ObjectIterator o_it(PluginFunctions::ALL_OBJECTS) ; o_it != PluginFunctions::objectsEnd(); ++o_it)
      o_it->enablePicking( true );

    if ( successfullyPicked ){
      Skeleton* skeleton = PluginFunctions::skeleton( object );

      if ( !skeleton )
        return;

      Skeleton::Joint* joint = skeleton->joint( target_idx );

      if ( joint != 0 ){
        joint->setSelected( !joint->selected() );
        emit updatedObject(object->id(), UPDATE_SELECTION);
      }
    }
  }
}

//--------------------------------------------------------------------------------

/**
 * \brief Get nearest joint to hitPoint (used for snapping)
 */
OpenMesh::Vec3d SkeletonEditingPlugin::getNearestJoint(SkeletonObject* _skeletonObj, OpenMesh::Vec3d &_hitPoint, int& _bestJointID) {

  ACG::Vec3d    bestJoint;
  double        bestDistance = DBL_MAX;
1494

Dirk Wilden's avatar
Dirk Wilden committed
1495
  _bestJointID = -1;
1496

Dirk Wilden's avatar
Dirk Wilden committed
1497 1498 1499 1500 1501 1502
  Skeleton* skeleton = PluginFunctions::skeleton(_skeletonObj);

  Skeleton::Pose* pose = activePose(_skeletonObj);

  //find the nearest joint
  for (unsigned int joint = 0; joint < skeleton->jointCount(); joint++){
1503

Dirk Wilden's avatar
Dirk Wilden committed
1504
    double dist = (_hitPoint - pose->globalTranslation(joint)).sqrnorm();
1505

Dirk Wilden's avatar
Dirk Wilden committed
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
    if (dist < bestDistance){
      bestJoint     = pose->globalTranslation(joint);
      _bestJointID  = joint;
      bestDistance  = dist;
    }
  }

  return (OpenMesh::Vec3d) bestJoint;
}

//--------------------------------------------------------------------------------

/** \brief make sure the manipulator is positioned on a joint
 *
 */
void SkeletonEditingPlugin::updateManipulatorPosition(BaseObjectData* _skeletonObj){

  int jointID = _skeletonObj->manipulatorNode()->getData().toInt();

  Skeleton* skeleton = PluginFunctions::skeleton(_skeletonObj);

  if (skeleton == 0)
    return;

  if (skeleton->joint(jointID) == 0)
    return;

  Skeleton::Pose* pose = activePose(PluginFunctions::skeletonObject(_skeletonObj));

Mike Kremer's avatar
Mike Kremer committed
1535 1536
  if(!pose) return;

Dirk Wilden's avatar
Dirk Wilden committed
1537 1538 1539 15