openFunctions.cc 19.1 KB
Newer Older
Jan Möbius's avatar
 
Jan Möbius committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
//=============================================================================
//
//                               OpenFlipper
//        Copyright (C) 2008 by Computer Graphics Group, RWTH Aachen
//                           www.openflipper.org
//
//-----------------------------------------------------------------------------
//
//                                License
//
//  OpenFlipper is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  OpenFlipper is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public License
//  along with OpenFlipper.  If not, see <http://www.gnu.org/licenses/>.
//
//-----------------------------------------------------------------------------
//
//   $Revision$
//   $Author$
//   $Date$
//
//=============================================================================





#include "Core.hh"

#include <ACG/QtWidgets/QtFileDialog.hh>

#include "OpenFlipper/common/GlobalOptions.hh"
#include "OpenFlipper/BasePlugin/PluginFunctions.hh"

#include "OpenFlipper/widgets/loadWidget/loadWidget.hh"
#include "OpenFlipper/widgets/addEmptyWidget/addEmptyWidget.hh"

46 47
#include <time.h>

48
void Core::resetScenegraph() {
49
  if ( OpenFlipper::Options::gui() && !OpenFlipper::Options::loadingSettings() ) {
Jan Möbius's avatar
Jan Möbius committed
50 51

    for ( unsigned int i = 0 ; i < OpenFlipper::Options::examinerWidgets() ; ++i ) {
52
      // update scene graph (get new bounding box and set projection right, including near and far plane)
53
      PluginFunctions::viewerProperties(i).lockUpdate();
54
      coreWidget_->examiner_widgets_[i]->sceneGraph(root_node_scenegraph_, true);
55
      PluginFunctions::viewerProperties(i).unLockUpdate();
Jan Möbius's avatar
Jan Möbius committed
56 57 58
      coreWidget_->examiner_widgets_[i]->updateGL();
    }

Jan Möbius's avatar
 
Jan Möbius committed
59
  }
60

Jan Möbius's avatar
Jan Möbius committed
61
  // Update the draw Modes Menu
Dirk Wilden's avatar
Dirk Wilden committed
62 63
  if ( OpenFlipper::Options::gui() )
    coreWidget_->slotUpdateGlobalDrawMenu();
Jan Möbius's avatar
 
Jan Möbius committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
}

//========================================================================================
// ===            Open/Add-Empty Functions                    ============================
//========================================================================================


void Core::slotGetAllFilters ( QStringList& _list){

  for (int i=0; i < (int)supportedTypes_.size(); i++){
    QString f = supportedTypes_[i].plugin->getLoadFilters();
    f = f.section(")",0,0).section("(",1,1).trimmed();
    _list << (QString::number(supportedTypes_[i].plugin->supportedType()) + " " + f);
  }
}

void Core::commandLineOpen(const char* _filename, bool asPolyMesh ){
81 82 83 84 85 86 87 88 89 90 91

	QString file(_filename);

	if ( !file.startsWith("/") && !file.contains(":") ) {

		file = QDir::currentPath();
		file += OpenFlipper::Options::dirSeparator();
		file += _filename;
	}

	commandLineFileNames_.push_back(std::pair< std::string , bool >(file.toStdString(), asPolyMesh));
Jan Möbius's avatar
 
Jan Möbius committed
92 93 94
}

void Core::commandLineScript(const char* _filename ) {
95 96 97
  commandLineScriptNames_.push_back(_filename);
}

Jan Möbius's avatar
Jan Möbius committed
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
void Core::slotExecuteAfterStartup() {

  //check if we have scripting support:
  bool scriptingSupport = false;
  slotPluginExists("scripting",scriptingSupport);
  if ( ! scriptingSupport ) {
    emit log(LOGERR ,"No scripting support available, please check if we load a scripting plugin .. Skipping script execution on startup");
  }

  // Collect all script files from the scripting subdirectory and execute them if possible
  if ( scriptingSupport ) {

    QDir scriptDir = OpenFlipper::Options::scriptDir();
    QStringList scriptFiles = scriptDir.entryList(QDir::Files,QDir::Name);

    for ( int i = 0 ; i  < scriptFiles.size(); ++i )
Jan Möbius's avatar
Jan Möbius committed
114 115
      if ( scriptFiles[i].endsWith("ofs") )
        emit executeFileScript(scriptDir.path() + QDir::separator() + scriptFiles[i]);
Jan Möbius's avatar
Jan Möbius committed
116 117 118

  }

119
  for ( uint i = 0 ; i < commandLineFileNames_.size() ; ++i ) {
120 121

    // Skip scripts here as they will be handled by a different function
122
    QString tmp = QString::fromStdString(commandLineFileNames_[i].first);
123 124 125 126 127
    if ( tmp.endsWith("ofs") ) {
      commandLineScriptNames_.push_back(commandLineFileNames_[i].first);
      continue;
    }

128
    if (commandLineFileNames_[i].second)
129 130 131 132
      loadObject(DATA_POLY_MESH, QString::fromStdString(commandLineFileNames_[i].first));
    else {
      loadObject(QString::fromStdString(commandLineFileNames_[i].first));
    }
Jan Möbius's avatar
 
Jan Möbius committed
133 134
  }

Jan Möbius's avatar
Jan Möbius committed
135
  if ( scriptingSupport )
136 137
    for ( uint i = 0 ; i < commandLineScriptNames_.size() ; ++i ) {
      // Add the full path to the script to set scripting dir right
138
      QString tmp = QString::fromStdString(commandLineScriptNames_[i]);
139 140 141
      tmp = QDir::currentPath() + QDir::separator() + tmp;
      emit executeFileScript(tmp);
    }
142

Dirk Wilden's avatar
Dirk Wilden committed
143 144
  if ( !OpenFlipper::Options::gui() && !OpenFlipper::Options::remoteControl())
    exitApplication();
Jan Möbius's avatar
 
Jan Möbius committed
145 146 147 148
}

/// Load object by guessing DataType depending on the files extension
int Core::loadObject ( QString _filename ) {
149

Jan Möbius's avatar
 
Jan Möbius committed
150
  if (_filename.endsWith(".ini")) {
151 152

    // Load all information from the given ini file
153
    openIniFile(_filename,true,true,true);
154

Jan Möbius's avatar
 
Jan Möbius committed
155 156
    if ( OpenFlipper::Options::gui() )
      coreWidget_->addRecent(_filename, DATA_NONE);
157

Jan Möbius's avatar
 
Jan Möbius committed
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
    return -2;
  } else
  if (_filename.endsWith(".ofs")) {
     emit log(LOGINFO ,"Starting script execution of " + _filename);
     emit executeFileScript(_filename);
  } else
    return loadObject( DATA_TRIANGLE_MESH, _filename);

  return -1;
}

/// Function for loading a given file
int Core::loadObject( DataType _type, QString _filename) {

  if (_type == DATA_NONE)
    return loadObject(_filename);

  for (int i=0; i < (int)supportedTypes_.size(); i++)
    if (supportedTypes_[i].type == _type) {


      if ( OpenFlipper::Options::gui() ) {
        coreWidget_->statusMessage( "Loading " + _filename + " ...");
181
        if ( !OpenFlipper::Options::loadingSettings() )
Jan Möbius's avatar
 
Jan Möbius committed
182 183 184 185 186 187 188 189 190 191 192 193
          coreWidget_->setStatus(ApplicationStatus::PROCESSING );
      }

      //load file
      int id = supportedTypes_[i].plugin->loadObject(_filename);

      if ( OpenFlipper::Options::gui() ) {
        if ( id != -1 )
          coreWidget_->statusMessage( "Loading " + _filename + " ... done", 4000 );
        else
          coreWidget_->statusMessage( "Loading " + _filename + " ... failed!", 4000 );

194
        if ( !OpenFlipper::Options::loadingSettings() )
Jan Möbius's avatar
 
Jan Möbius committed
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
          coreWidget_->setStatus(ApplicationStatus::READY );
      }

      return id;
    }
  return -1; //no plugin found
}

/// Function for adding an empty object of given DataType
int Core::addEmptyObject( DataType _type ) {
  for (int i=0; i < (int)supportedTypes_.size(); i++)
    if (supportedTypes_[i].type == _type)
      return supportedTypes_[i].plugin->addEmpty();
  return -1; //no plugin found
}

//========================================================================================
// ===             Open/Add-Empty Slots                       ============================
//========================================================================================

/// Slot for adding an empty object of given DataType
void Core::slotAddEmptyObject( DataType _type , int& _id ) {
  _id = addEmptyObject( _type );
}

220
/// Slot creating a copy of an existing object
Jan Möbius's avatar
Jan Möbius committed
221
void Core::slotCopyObject( int _oldId , int& _newId ) {
222

Jan Möbius's avatar
Jan Möbius committed
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
  if ( _oldId == -1 ) {
    emit log(LOGERR,"Requested copy for illegal Object id : " + QString::number(_oldId) );
    _newId = -1;
    return;
  }

  // get the node
  BaseObject* object = objectRoot_->childExists(_oldId);

  if ( !object ) {
    emit log(LOGERR,"Requested copy for unknown Object id : " + QString::number(_oldId) );
    _newId = -1;
    return ;
  }

  // Copy the item
  BaseObject* copy = object->copy();

  if ( copy == 0 ) {
    emit log(LOGERR,"Unable to create a copy of the object.");
    return;
  }

  // Integrate into object tree
  copy->setParent( object->parent() );
  if ( object->parent() )
    object->parent()->appendChild(copy);
  else
    std::cerr << "Unable to add copy to object list" << std::endl;

253
  // return the new id
Jan Möbius's avatar
Jan Möbius committed
254
  _newId = copy->id();
255

256 257 258 259 260 261
  // tell plugins that a new object has been created
  slotEmptyObjectAdded(_newId);

  // tell plugins that the object has been updated
  slotObjectUpdated(_newId);

262 263
}

Jan Möbius's avatar
 
Jan Möbius committed
264 265 266 267 268 269
/// Slot for loading a given file
void Core::slotLoad(QString _filename, DataType _type, int& _id) {
  _id = loadObject(_type,_filename);
  if ( _id < 0 )
    _id = -1;
  else
270
    if ( OpenFlipper::Options::gui() )
Jan Möbius's avatar
 
Jan Möbius committed
271 272 273 274
      coreWidget_->addRecent(_filename,_type);
}

/// Slot gets called after a file-plugin has opened an object
275 276 277 278 279 280 281 282 283 284 285
void Core::slotObjectOpened ( int _id ) {
  if ( OpenFlipper::Options::doSlotDebugging() ) {
    if ( sender() != 0 ) {
      if ( sender()->metaObject() != 0 ) {
        emit log(LOGINFO,"slotObjectOpened( " + QString::number(_id) + " ) called by " +
                  QString( sender()->metaObject()->className() ) );
      }
    } else {
      emit log(LOGINFO,"slotObjectOpened( " + QString::number(_id) + " ) called by Core" );
    }
  }
286 287

  // get the opened object
288 289
  BaseObjectData* object;
  PluginFunctions::getObject(_id,object);
290

291
  QColor color;
292

293
  if ( OpenFlipper::Options::randomBaseColor() ){
294 295 296 297 298
      //init random seed
      srand ( time(NULL) );

      QColor bckgrnd = OpenFlipper::Options::defaultBackgroundColor();
      int diff;
299

300 301
      do{
        color.setRgb(rand()%255, rand()%255, rand()%255);
302

303 304 305
        diff = (bckgrnd.red()   - color.red())  *(bckgrnd.red()   - color.red())
              +(bckgrnd.green() - color.green())*(bckgrnd.green() - color.green())
              +(bckgrnd.blue()  - color.blue()) *(bckgrnd.blue()  - color.blue());
306
      }while (diff < 70000);
307 308
  }
  else{
309
      color = OpenFlipper::Options::defaultBaseColor();
310
  }
311

312 313 314 315 316
  ACG::Vec4f colorV;
  colorV[0] = color.redF();
  colorV[1] = color.greenF();
  colorV[2] = color.blueF();
  colorV[3] = color.alphaF();
317

318
  object->setBaseColor( colorV );
Jan Möbius's avatar
 
Jan Möbius committed
319

Jan Möbius's avatar
Jan Möbius committed
320 321 322 323 324 325 326 327 328 329 330
  // ================================================================================
  // Set standard draw mode if this is the first opened object
  // If a plugin changes the drawmode later, this setting will be overridden!
  // ================================================================================
  if ( PluginFunctions::objectCount() == 1 && OpenFlipper::Options::gui() && !OpenFlipper::Options::loadingSettings() )
    for ( unsigned int i = 0 ; i < OpenFlipper::Options::examinerWidgets() ; ++i )
      PluginFunctions::viewerProperties(i).drawMode( OpenFlipper::Options::standardDrawMode() );

  // ================================================================================
  // Recompute bounding box and scenegraph info
  // ================================================================================
331
  resetScenegraph();
Jan Möbius's avatar
 
Jan Möbius committed
332

Jan Möbius's avatar
Jan Möbius committed
333 334 335
  // ================================================================================
  // Tell plugins, that a file has been opened
  // ================================================================================
336
  emit openedFile( _id );
Jan Möbius's avatar
 
Jan Möbius committed
337

Jan Möbius's avatar
Jan Möbius committed
338 339 340
  // ================================================================================
  // Tell plugins, that the Object is updated and the active object has changed
  // ================================================================================
341 342
  emit signalObjectUpdated(_id);
  emit objectSelectionChanged( _id );
Jan Möbius's avatar
 
Jan Möbius committed
343

Jan Möbius's avatar
Jan Möbius committed
344 345 346
  // ================================================================================
  // Create initial backup
  // ================================================================================
347
  backupRequest(_id,"Original Object");
Jan Möbius's avatar
 
Jan Möbius committed
348

349 350 351
  // ================================================================================
  // Add the file to the recent files menu
  // ================================================================================
352 353 354 355
  QString filename = object->path() + OpenFlipper::Options::dirSeparator() + object->name();
  BaseObject* object2;
  PluginFunctions::getObject(_id,object2);
  if ( OpenFlipper::Options::gui() )
Jan Möbius's avatar
 
Jan Möbius committed
356 357
    coreWidget_->addRecent( filename, object2->dataType() );

Jan Möbius's avatar
Jan Möbius committed
358 359 360
  // ================================================================================
  // if this is the first object opend, reset the global view
  // ================================================================================
361
  if ( PluginFunctions::objectCount() == 1 && OpenFlipper::Options::gui() && !OpenFlipper::Options::loadingSettings() )
362 363 364
    for ( unsigned int i = 0 ; i < OpenFlipper::Options::examinerWidgets() ; ++i ) {
      coreWidget_->examiner_widgets_[i]->viewAll();
    }
365

Jan Möbius's avatar
 
Jan Möbius committed
366
  // objectRoot_->dumpTree();
367
}
Jan Möbius's avatar
 
Jan Möbius committed
368 369

 /// Slot gets called after a file-plugin has opened an object
370 371 372 373 374 375 376 377 378 379 380 381
void Core::slotEmptyObjectAdded ( int _id ) {
  if ( OpenFlipper::Options::doSlotDebugging() ) {
    if ( sender() != 0 ) {
      if ( sender()->metaObject() != 0 ) {
        emit log(LOGINFO,"slotEmptyObjectAdded( " + QString::number(_id) + " ) called by " +
                  QString( sender()->metaObject()->className() ) );
      }
    } else {
      emit log(LOGINFO,"slotEmptyObjectAdded( " + QString::number(_id) + " ) called by Core" );
    }
  }

382 383 384 385 386
  // get the opened object
  BaseObjectData* object;
  PluginFunctions::getObject(_id,object);

  emit emptyObjectAdded( _id );
387

Jan Möbius's avatar
 
Jan Möbius committed
388
  // Tell the Plugins that the Object List and the active object have changed
389 390
  emit signalObjectUpdated(_id);
  emit objectSelectionChanged(_id);
Jan Möbius's avatar
 
Jan Möbius committed
391

392
  backupRequest(_id,"Original Object");
Jan Möbius's avatar
 
Jan Möbius committed
393

394
  ///@todo : set a default path for new objects
Jan Möbius's avatar
 
Jan Möbius committed
395 396 397
//    QString filename = object->path() + OpenFlipper::Options::dirSeparator() + object->name();

//    addRecent(filename);
398
}
Jan Möbius's avatar
 
Jan Möbius committed
399 400 401 402 403 404 405 406 407 408 409 410

//========================================================================================
// ===             Menu Slots                                 ============================
//========================================================================================

/// Opens AddEmpty-Object widget
void Core::slotAddEmptyObjectMenu() {
  if (supportedTypes_.size() != 0){
    static addEmptyWidget* widget = 0;
    if ( !widget ){
      std::vector< DataType > types;
      QStringList typeNames;
Jan Möbius's avatar
 
Jan Möbius committed
411 412 413 414
      for (int i=0; i < (int)supportedTypes_.size(); i++) {
        types.push_back(supportedTypes_[i].type);
        typeNames.push_back(supportedTypes_[i].plugin->typeName());
      }
Jan Möbius's avatar
 
Jan Möbius committed
415
      widget = new addEmptyWidget(types,typeNames);
416
      widget->setWindowIcon( OpenFlipper::Options::OpenFlipperIcon() );
Jan Möbius's avatar
 
Jan Möbius committed
417 418 419 420 421 422 423
      connect(widget,SIGNAL(chosen(DataType, int&)),this,SLOT(slotAddEmptyObject(DataType, int&)));
    }
    widget->show();
  }else
    emit log(LOGERR,"Could not show 'add Empty' dialog. Missing file-plugins.");
}

424 425 426 427
//========================================================================================
// ===             Public Slots                                 ============================
//========================================================================================

Jan Möbius's avatar
 
Jan Möbius committed
428
/// Open Load-Object Widget
429 430 431 432 433
void Core::loadObject() {

  if ( OpenFlipper::Options::gui() ){

    if (supportedTypes_.size() != 0){
434 435 436
      LoadWidget* widget = new LoadWidget(supportedTypes_);
      connect(widget,SIGNAL(load(QString, DataType, int&)),this,SLOT(slotLoad(QString, DataType, int&)));
      connect(widget,SIGNAL(save(int, QString)),this,SLOT(saveObject(int, QString)));
Jan Möbius's avatar
Jan Möbius committed
437

438 439
      widget->setWindowIcon( OpenFlipper::Options::OpenFlipperIcon() );

440
      widget->showLoad();
441 442 443 444

      widget->disconnect();
      delete widget;

445 446
    }else
      emit log(LOGERR,"Could not show 'load objects' dialog. Missing file-plugins.");
Jan Möbius's avatar
 
Jan Möbius committed
447

448
  }
Jan Möbius's avatar
 
Jan Möbius committed
449 450
}

451 452 453 454 455 456
/// Load settings from file
void Core::loadSettings(){

  if ( OpenFlipper::Options::gui() ){

    QString complete_name;
Jan Möbius's avatar
Jan Möbius committed
457

458 459 460 461 462 463

    QFileDialog fileDialog( coreWidget_,
                            tr("Load Settings"),
                            OpenFlipper::Options::currentDirStr(),
                            tr("INI files (*.ini);;OBJ files (*.obj )") );

464
    fileDialog.setOption (QFileDialog::DontUseNativeDialog, true);
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
    fileDialog.setAcceptMode ( QFileDialog::AcceptOpen );
    fileDialog.setFileMode ( QFileDialog::AnyFile );

    QGridLayout *layout = (QGridLayout*)fileDialog.layout();

    QGroupBox* optionsBox = new QGroupBox( &fileDialog ) ;
    optionsBox->setSizePolicy( QSizePolicy ( QSizePolicy::Expanding , QSizePolicy::Preferred ) );
    optionsBox->setTitle("Options");
    layout->addWidget( optionsBox, layout->rowCount() , 0 , 1,layout->columnCount() );

    QCheckBox *loadProgramSettings = new QCheckBox(optionsBox);
    loadProgramSettings->setText("Load program settings");
    loadProgramSettings->setToolTip("Load all current program settings from the file ( This will include view settings, colors,...) ");
    loadProgramSettings->setCheckState( Qt::Unchecked );

    QCheckBox *loadPluginSettings = new QCheckBox(optionsBox);
    loadPluginSettings->setText("Load per Plugin Settings");
    loadPluginSettings->setToolTip("Plugins should load their current global settings from the file");
    loadPluginSettings->setCheckState( Qt::Checked );

    QCheckBox *loadObjectInfo = new QCheckBox(optionsBox);
    loadObjectInfo->setText("Load all objects defined in the file");
    loadObjectInfo->setToolTip("Load all objects which are defined in the file");
    loadObjectInfo->setCheckState( Qt::Checked );

    QBoxLayout* frameLayout = new QBoxLayout(QBoxLayout::TopToBottom,optionsBox);
    frameLayout->addWidget( loadProgramSettings , 0 , 0);
    frameLayout->addWidget( loadPluginSettings  , 1 , 0);
    frameLayout->addWidget( loadObjectInfo      , 2 , 0);
    frameLayout->addStretch();

Jan Möbius's avatar
Jan Möbius committed
496 497
    fileDialog.resize(550 ,500);

498 499 500 501 502 503 504 505 506 507 508 509
    // ========================================================================================
    // show the saveSettings-Dialog and get the target file
    // ========================================================================================
    QStringList fileNames;
    if (fileDialog.exec()) {
      fileNames = fileDialog.selectedFiles();
    } else {
      return;
    }

    if ( fileNames.size() > 1 ) {
      std::cerr << "Too many save filenames selected" << std::endl;
510
      return;
511 512 513 514
    }

    complete_name = fileNames[0];

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

516 517
    QString newpath = complete_name.section(OpenFlipper::Options::dirSeparator(),0,-2);
    OpenFlipper::Options::currentDir(newpath);
Jan Möbius's avatar
Jan Möbius committed
518

519
    if ( complete_name.endsWith("ini") ) {
520 521 522 523
      openIniFile( complete_name,
                   loadProgramSettings->isChecked(),
                   loadPluginSettings->isChecked(),
                   loadObjectInfo->isChecked());
524 525
      if ( loadProgramSettings->isChecked() )
        applyOptions();
526 527
    } else if ( complete_name.endsWith("obj") ) {
      openObjFile(complete_name);
528 529
      if ( loadProgramSettings->isChecked() )
        applyOptions();
530
    }
Jan Möbius's avatar
Jan Möbius committed
531

532 533 534
    coreWidget_->addRecent(complete_name, DATA_NONE);
  }
}
Jan Möbius's avatar
 
Jan Möbius committed
535

536 537
/// Load settings from file
void Core::loadSettings(QString _filename){
Jan Möbius's avatar
Jan Möbius committed
538

539
  if ( !QFile(_filename).exists() )
Jan Möbius's avatar
 
Jan Möbius committed
540 541
    return;

542
  QString newpath = _filename.section(OpenFlipper::Options::dirSeparator(),0,-2);
Jan Möbius's avatar
 
Jan Möbius committed
543 544
  OpenFlipper::Options::currentDir(newpath);

545
  if ( _filename.endsWith("ini") ) {
546
    // Loaded function for recent files. Load everything.
547
    openIniFile(_filename,true,true,true);
Jan Möbius's avatar
 
Jan Möbius committed
548
    applyOptions();
549 550
  } else if ( _filename.endsWith("obj") ) {
    openObjFile(_filename);
Jan Möbius's avatar
 
Jan Möbius committed
551 552 553 554
    applyOptions();
  }

}