Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/world_entities/world_entity.cc @ 8076

Last change on this file since 8076 was 8037, checked in by bensch, 18 years ago

trunk: merged the water back
merged with command
svn merge -r7798:HEAD https://svn.orxonox.net/orxonox/branches/water .

conflicts are all resolved

File size: 14.2 KB
RevLine 
[2036]1
2
[4570]3/*
[2036]4   orxonox - the future of 3D-vertical-scrollers
5
6   Copyright (C) 2004 orx
7
8   This program is free software; you can redistribute it and/or modify
9   it under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2, or (at your option)
11   any later version.
12
13   ### File Specific:
14   main-programmer: Patrick Boenzli
[2190]15   co-programmer: Christian Meyer
[2036]16*/
[5300]17#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_WORLD_ENTITY
[2036]18
19#include "world_entity.h"
[5208]20#include "shell_command.h"
[5143]21
[5511]22#include "model.h"
[6222]23#include "md2Model.h"
[7193]24#include "util/loading/resource_manager.h"
25#include "util/loading/load_param.h"
[3803]26#include "vector.h"
[4682]27#include "obb_tree.h"
[3608]28
[6430]29#include "glgui_bar.h"
30
[6002]31#include "state.h"
[7014]32#include "camera.h"
[6002]33
[7927]34#include "cr_engine.h"
35#include "collision_handle.h"
36
37
[2036]38using namespace std;
39
[5208]40SHELL_COMMAND(model, WorldEntity, loadModel)
[6430]41->describe("sets the Model of the WorldEntity")
[7711]42->defaultValues("models/ships/fighter.obj", 1.0f);
[5208]43
[6424]44SHELL_COMMAND(debugEntity, WorldEntity, debugWE);
[5208]45
[2043]46/**
[4836]47 *  Loads the WordEntity-specific Part of any derived Class
[5498]48 *
49 * @param root: Normally NULL, as the Derived Entities define a loadParams Function themeselves,
50 *              that can calls WorldEntities loadParams for itself.
51 */
[6430]52WorldEntity::WorldEntity()
53    : Synchronizeable()
[2190]54{
[4320]55  this->setClassID(CL_WORLD_ENTITY, "WorldEntity");
[4597]56
[4682]57  this->obbTree = NULL;
[6700]58  this->healthWidget = NULL;
59  this->healthMax = 1.0f;
60  this->health = 1.0f;
[6695]61  this->scaling = 1.0f;
[4261]62
[6695]63  /* OSOLETE */
64  this->bVisible = true;
65  this->bCollide = true;
66
[6142]67  this->objectListNumber = OM_INIT;
68  this->objectListIterator = NULL;
69
70  this->toList(OM_NULL);
[7927]71
[7954]72  modelFileName_handle = registerVarId( new SynchronizeableString( &modelFileName, &modelFileName, "modelFileName" ) );
73  scaling_handle = registerVarId( new SynchronizeableFloat( &scaling, &scaling, "scaling" ) );
[2190]74}
[2043]75
76/**
[4836]77 *  standard destructor
[2043]78*/
[2190]79WorldEntity::~WorldEntity ()
[2036]80{
[7125]81  State::getObjectManager()->toList(this, OM_INIT);
82
83  // Delete the model (unregister it with the ResourceManager)
84  for (unsigned int i = 0; i < this->models.size(); i++)
85    this->setModel(NULL, i);
86
[5498]87  // Delete the obbTree
[5302]88  if( this->obbTree != NULL)
[4814]89    delete this->obbTree;
[5994]90
[6700]91  if (this->healthWidget != NULL)
92    delete this->healthWidget;
[3531]93}
94
[5498]95/**
96 * loads the WorldEntity Specific Parameters.
97 * @param root: the XML-Element to load the Data From
98 */
[4436]99void WorldEntity::loadParams(const TiXmlElement* root)
100{
[5498]101  // Do the PNode loading stuff
[6512]102  PNode::loadParams(root);
[5498]103
[6222]104  LoadParam(root, "md2texture", this, WorldEntity, loadMD2Texture)
[6430]105  .describe("the fileName of the texture, that should be loaded onto this world-entity. (must be relative to the data-dir)")
[7198]106  .defaultValues("");
[6222]107
[4436]108  // Model Loading
[5671]109  LoadParam(root, "model", this, WorldEntity, loadModel)
[6430]110  .describe("the fileName of the model, that should be loaded onto this world-entity. (must be relative to the data-dir)")
[7198]111  .defaultValues("", 1.0f, 0);
[6430]112
[6700]113  LoadParam(root, "maxHealth", this, WorldEntity, setHealthMax)
114  .describe("The Maximum health that can be loaded onto this entity")
[7198]115  .defaultValues(1.0f);
[6430]116
[6700]117  LoadParam(root, "health", this, WorldEntity, setHealth)
118  .describe("The Health the WorldEntity has at this moment")
[7198]119  .defaultValues(1.0f);
[4436]120}
121
[6222]122
[3531]123/**
[4885]124 * loads a Model onto a WorldEntity
[4836]125 * @param fileName the name of the model to load
[5057]126 * @param scaling the Scaling of the model
[7711]127 *
128 * FIXME
129 * @todo: separate the obb tree generation from the model
[7221]130 */
[7711]131void WorldEntity::loadModel(const std::string& fileName, float scaling, unsigned int modelNumber, unsigned int obbTreeDepth)
[4261]132{
[6695]133  this->modelLODName = fileName;
[6424]134  this->scaling = scaling;
[7954]135
136  std::string name = fileName;
137
138  if (  name.find( ResourceManager::getInstance()->getDataDir() ) == 0 )
139  {
140    name.erase(ResourceManager::getInstance()->getDataDir().size());
141  }
142
143  this->modelFileName = name;
144
[7221]145  if (!fileName.empty())
[6142]146  {
[6430]147    // search for the special character # in the LoadParam
[7221]148    if (fileName.find('#') != std::string::npos)
[6222]149    {
[7221]150      PRINTF(4)("Found # in %s... searching for LOD's\n", fileName.c_str());
151      std::string lodFile = fileName;
152      unsigned int offset = lodFile.find('#');
[6720]153      for (unsigned int i = 0; i < 3; i++)
[6005]154      {
[7221]155        lodFile[offset] = 48+(int)i;
[6222]156        if (ResourceManager::isInDataDir(lodFile))
157          this->loadModel(lodFile, scaling, i);
[6005]158      }
[6222]159      return;
160    }
[6720]161    if (this->scaling <= 0.0)
[6424]162    {
[7193]163      PRINTF(1)("YOU GAVE ME A CRAPY SCALE resetting to 1.0\n");
[6720]164      this->scaling = 1.0;
[6424]165    }
[7221]166    if(fileName.find(".obj") != std::string::npos)
[6222]167    {
[7221]168      PRINTF(4)("fetching OBJ file: %s\n", fileName.c_str());
[7193]169      BaseObject* loadedModel = ResourceManager::getInstance()->load(fileName, OBJ, RP_CAMPAIGN, this->scaling);
170      if (loadedModel != NULL)
171        this->setModel(dynamic_cast<Model*>(loadedModel), modelNumber);
[7221]172      else
173        PRINTF(1)("OBJ-File %s not found.\n", fileName.c_str());
[6222]174
175      if( modelNumber == 0)
[7711]176        this->buildObbTree(obbTreeDepth);
[6222]177    }
[7221]178    else if(fileName.find(".md2") != std::string::npos)
[6222]179    {
[7221]180      PRINTF(4)("fetching MD2 file: %s\n", fileName.c_str());
[7055]181      Model* m = new MD2Model(fileName, this->md2TextureFileName, this->scaling);
[6430]182      //this->setModel((Model*)ResourceManager::getInstance()->load(fileName, MD2, RP_CAMPAIGN), 0);
[6222]183      this->setModel(m, 0);
[7068]184
185      if( m != NULL)
[7711]186        this->buildObbTree(obbTreeDepth);
[6222]187    }
[4732]188  }
189  else
[6341]190  {
[5995]191    this->setModel(NULL);
[6341]192  }
[4261]193}
194
[5061]195/**
[5994]196 * sets a specific Model for the Object.
197 * @param model The Model to set
198 * @param modelNumber the n'th model in the List to get.
199 */
200void WorldEntity::setModel(Model* model, unsigned int modelNumber)
201{
[5995]202  if (this->models.size() <= modelNumber)
203    this->models.resize(modelNumber+1, NULL);
204
205  if (this->models[modelNumber] != NULL)
[6004]206  {
[7193]207    Resource* resource = ResourceManager::getInstance()->locateResourceByPointer(dynamic_cast<BaseObject*>(this->models[modelNumber]));
[7123]208    if (resource != NULL)
209      ResourceManager::getInstance()->unload(resource, RP_LEVEL);
210    else
211    {
212      PRINTF(4)("Forcing model deletion\n");
213      delete this->models[modelNumber];
214    }
[5994]215  }
[6222]216
[5995]217  this->models[modelNumber] = model;
[5994]218
[6222]219
[6430]220  //   if (this->model != NULL)
221  //     this->buildObbTree(4);
[5994]222}
223
224
225/**
[5061]226 * builds the obb-tree
227 * @param depth the depth to calculate
228 */
[7711]229bool WorldEntity::buildObbTree(int depth)
[5061]230{
[5428]231  if (this->obbTree)
232    delete this->obbTree;
233
[5995]234  if (this->models[0] != NULL)
[5428]235  {
[7711]236    this->obbTree = new OBBTree(depth, models[0]->getModelInfo(), this);
[5428]237    return true;
238  }
239  else
240  {
[7711]241    PRINTF(1)("could not create obb-tree, because no model was loaded yet\n");
[5428]242    this->obbTree = NULL;
243    return false;
244  }
[5061]245}
[5057]246
[7927]247
[6142]248/**
[7927]249 * subscribes this world entity to a collision reaction
250 *  @param type the type of reaction to subscribe to
251 *  @param nrOfTargets number of target filters
252 *  @param ... the targets as classIDs
253 */
254void WorldEntity::subscribeReaction(CREngine::CRType type, int nrOfTargets, ...)
255{}
256
257
258/**
[6142]259 * @brief moves this entity to the List OM_List
260 * @param list the list to set this Entity to.
261 *
262 * this is the same as a call to State::getObjectManager()->toList(entity , list);
263 * directly, but with an easier interface.
264 *
265 * @todo inline this (peut etre)
266 */
267void WorldEntity::toList(OM_LIST list)
268{
269  State::getObjectManager()->toList(this, list);
270}
[5061]271
[8037]272void WorldEntity::toReflectionList()
273{
274  State::getObjectManager()->toReflectionList( this );
275}
[6142]276
[8037]277void removeFromReflectionList()
278{
279/// TODO
280///  State::getObject
281}
[6142]282
[4261]283/**
[4885]284 * sets the character attributes of a worldentity
[4836]285 * @param character attributes
[4885]286 *
287 * these attributes don't have to be set, only use them, if you need them
[2043]288*/
[5498]289//void WorldEntity::setCharacterAttributes(CharacterAttributes* charAttr)
290//{}
[2036]291
[3583]292
[2043]293/**
[5029]294 *  this function is called, when two entities collide
295 * @param entity: the world entity with whom it collides
296 *
297 * Implement behaviour like damage application or other miscellaneous collision stuff in this function
298 */
299void WorldEntity::collidesWith(WorldEntity* entity, const Vector& location)
300{
[5498]301  /**
302   * THIS IS A DEFAULT COLLISION-Effect.
303   * IF YOU WANT TO CREATE A SPECIFIC COLLISION ON EACH OBJECT
304   * USE::
305   * if (entity->isA(CL_WHAT_YOU_ARE_LOOKING_FOR)) { printf "dothings"; };
306   *
307   * You can always define a default Action.... don't be affraid just test it :)
308   */
[6430]309  //  PRINTF(3)("collision %s vs %s @ (%f,%f,%f)\n", this->getClassName(), entity->getClassName(), location.x, location.y, location.z);
[5029]310}
311
[2043]312
313/**
[5498]314 *  this is called immediately after the Entity has been constructed, initialized and then Spawned into the World
[4885]315 *
[5498]316 */
[3229]317void WorldEntity::postSpawn ()
[6430]318{}
[2043]319
[3583]320
[2043]321/**
[6959]322 *  this method is called by the world if the WorldEntity leaves the game
[5498]323 */
[6959]324void WorldEntity::leaveWorld ()
[6430]325{}
[2043]326
[3583]327
[2190]328/**
[7085]329 * resets the WorldEntity to its initial values. eg. used for multiplayer games: respawning
330 */
331void WorldEntity::reset()
332{}
333
334/**
[4836]335 *  this method is called every frame
336 * @param time: the time in seconds that has passed since the last tick
[4885]337 *
338 * Handle all stuff that should update with time inside this method (movement, animation, etc.)
[2043]339*/
[4570]340void WorldEntity::tick(float time)
[6430]341{}
[3583]342
[5498]343
[3583]344/**
[4836]345 *  the entity is drawn onto the screen with this function
[4885]346 *
347 * This is a central function of an entity: call it to let the entity painted to the screen.
348 * Just override this function with whatever you want to be drawn.
[3365]349*/
[5500]350void WorldEntity::draw() const
[3803]351{
[6430]352  //PRINTF(0)("(%s::%s)\n", this->getClassName(), this->getName());
[6281]353  //  assert(!unlikely(this->models.empty()));
[6002]354  {
355    glMatrixMode(GL_MODELVIEW);
356    glPushMatrix();
[4570]357
[6002]358    /* translate */
359    glTranslatef (this->getAbsCoor ().x,
360                  this->getAbsCoor ().y,
361                  this->getAbsCoor ().z);
[6004]362    Vector tmpRot = this->getAbsDir().getSpacialAxis();
363    glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
[2043]364
[6004]365
366    // This Draws the LOD's
[7014]367    float cameraDistance = State::getCamera()->distance(this);
[6004]368    if (cameraDistance > 30 && this->models.size() >= 3 && this->models[2] != NULL)
[6002]369    {
[6222]370      this->models[2]->draw();
[6004]371    }
372    else if (cameraDistance > 10 && this->models.size() >= 2 && this->models[1] != NULL)
[6002]373    {
374      this->models[1]->draw();
[6004]375    }
376    else if (this->models.size() >= 1 && this->models[0] != NULL)
[6002]377    {
378      this->models[0]->draw();
379    }
380    glPopMatrix();
381  }
[3803]382}
[3583]383
[6430]384/**
[6700]385 * @param health the Health to add.
386 * @returns the health left (this->healthMax - health+this->health)
[6430]387 */
[6700]388float WorldEntity::increaseHealth(float health)
[6430]389{
[6700]390  this->health += health;
391  if (this->health > this->healthMax)
[6430]392  {
[6700]393    float retHealth = this->healthMax - this->health;
394    this->health = this->healthMax;
395    this->updateHealthWidget();
396    return retHealth;
[6430]397  }
[6700]398  this->updateHealthWidget();
[6430]399  return 0.0;
400}
[6281]401
[5498]402/**
[6700]403 * @param health the Health to be removed
[6430]404 * @returns 0.0 or the rest, that was not substracted (bellow 0.0)
405 */
[6700]406float WorldEntity::decreaseHealth(float health)
[6430]407{
[6700]408  this->health -= health;
[6430]409
[6700]410  if (this->health < 0)
[6430]411  {
[6700]412    float retHealth = -this->health;
413    this->health = 0.0f;
414    this->updateHealthWidget();
415    return retHealth;
[6430]416  }
[6700]417  this->updateHealthWidget();
[6430]418  return 0.0;
419
420}
421
422/**
[6700]423 * @param maxHealth the maximal health that can be loaded onto the entity.
[6430]424 */
[6700]425void WorldEntity::setHealthMax(float healthMax)
[6430]426{
[6700]427  this->healthMax = healthMax;
428  if (this->health > this->healthMax)
[6430]429  {
[6700]430    PRINTF(3)("new maxHealth is bigger as the old health. Did you really intend to do this for (%s::%s)\n", this->getClassName(), this->getName());
431    this->health = this->healthMax;
[6430]432  }
[6700]433  this->updateHealthWidget();
[6430]434}
435
[6431]436/**
[6700]437 * @brief creates the HealthWidget
[6431]438 *
[6700]439 * since not all entities need an HealthWidget, it is only created on request.
[6431]440 */
[6700]441void WorldEntity::createHealthWidget()
[6430]442{
[6700]443  if (this->healthWidget == NULL)
[6430]444  {
[7779]445    this->healthWidget = new OrxGui::GLGuiBar();
[6700]446    this->healthWidget->setSize2D(30,400);
447    this->healthWidget->setAbsCoor2D(10,100);
[6430]448
[6700]449    this->updateHealthWidget();
[6430]450  }
451  else
[6700]452    PRINTF(3)("Allready created the HealthWidget for %s::%s\n", this->getClassName(), this->getName());
[6430]453}
454
[6700]455void WorldEntity::increaseHealthMax(float increaseHealth)
[6440]456{
[6700]457  this->healthMax += increaseHealth;
458  this->updateHealthWidget();
[6440]459}
460
[6700]461
[7779]462OrxGui::GLGuiWidget* WorldEntity::getHealthWidget()
[6700]463{
464  this->createHealthWidget();
465  return this->healthWidget;
466}
467
[6431]468/**
[6700]469 * @param visibility shows or hides the health-bar
[6431]470 * (creates the widget if needed)
471 */
[6700]472void WorldEntity::setHealthWidgetVisibilit(bool visibility)
[6430]473{
[7198]474  if (visibility)
475  {
476    if (this->healthWidget != NULL)
477      this->healthWidget->show();
478    else
[6430]479    {
[7198]480      this->createHealthWidget();
481      this->updateHealthWidget();
482      this->healthWidget->show();
[6430]483    }
[7198]484  }
485  else if (this->healthWidget != NULL)
486    this->healthWidget->hide();
[6430]487}
488
[6431]489/**
[6700]490 * @brief updates the HealthWidget
[6431]491 */
[6700]492void WorldEntity::updateHealthWidget()
[6430]493{
[6700]494  if (this->healthWidget != NULL)
[6430]495  {
[6700]496    this->healthWidget->setMaximum(this->healthMax);
497    this->healthWidget->setValue(this->health);
[6430]498  }
499}
500
501
502/**
[5498]503 * DEBUG-DRAW OF THE BV-Tree.
504 * @param depth What depth to draw
505 * @param drawMode the mode to draw this entity under
506 */
[7711]507void WorldEntity::drawBVTree(int depth, int drawMode) const
[4684]508{
509  glMatrixMode(GL_MODELVIEW);
510  glPushMatrix();
511  /* translate */
512  glTranslatef (this->getAbsCoor ().x,
513                this->getAbsCoor ().y,
514                this->getAbsCoor ().z);
515  /* rotate */
[4998]516  Vector tmpRot = this->getAbsDir().getSpacialAxis();
517  glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
[4684]518
[7711]519
[4684]520  if (this->obbTree)
521    this->obbTree->drawBV(depth, drawMode);
[7711]522
523
[4684]524  glPopMatrix();
525}
[6341]526
[6424]527
[6341]528/**
[6424]529 * Debug the WorldEntity
530 */
531void WorldEntity::debugEntity() const
532{
533  PRINT(0)("WorldEntity %s::%s  (DEBUG)\n", this->getClassName(), this->getName());
534  this->debugNode();
535  PRINT(0)("List: %s ; ModelCount %d - ", ObjectManager::OMListToString(this->objectListNumber) , this->models.size());
536  for (unsigned int i = 0; i < this->models.size(); i++)
537  {
538    if (models[i] != NULL)
539      PRINT(0)(" : %d:%s", i, this->models[i]->getName());
540  }
541  PRINT(0)("\n");
542
543}
544
545
546/**
[7954]547 * handler for changes on registred vars
548 * @param id id's which changed
[6341]549 */
[7954]550void WorldEntity::varChangeHandler( std::list< int > & id )
[6341]551{
[7954]552  if ( std::find( id.begin(), id.end(), modelFileName_handle ) != id.end() ||
553       std::find( id.begin(), id.end(), scaling_handle ) != id.end()
554     )
[6341]555  {
[7954]556    loadModel( modelFileName, scaling );
[6341]557  }
558
[7954]559  PNode::varChangeHandler( id );
[6341]560}
561
Note: See TracBrowser for help on using the repository browser.