Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/bsp_model/src/world_entities/world_entity.cc @ 7833

Last change on this file since 7833 was 7833, checked in by bottac, 18 years ago

collision detection.

File size: 15.9 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
[2036]34using namespace std;
35
[5208]36SHELL_COMMAND(model, WorldEntity, loadModel)
[6430]37->describe("sets the Model of the WorldEntity")
[7198]38->defaultValues("models/ships/fighter.obj", 1.0);
[5208]39
[6424]40SHELL_COMMAND(debugEntity, WorldEntity, debugWE);
[5208]41
[2043]42/**
[4836]43 *  Loads the WordEntity-specific Part of any derived Class
[5498]44 *
45 * @param root: Normally NULL, as the Derived Entities define a loadParams Function themeselves,
46 *              that can calls WorldEntities loadParams for itself.
47 */
[6430]48WorldEntity::WorldEntity()
49    : Synchronizeable()
[2190]50{
[4320]51  this->setClassID(CL_WORLD_ENTITY, "WorldEntity");
[4597]52
[4682]53  this->obbTree = NULL;
[6700]54  this->healthWidget = NULL;
55  this->healthMax = 1.0f;
56  this->health = 1.0f;
[6695]57  this->scaling = 1.0f;
[4261]58
[6695]59  /* OSOLETE */
60  this->bVisible = true;
61  this->bCollide = true;
62
[6142]63  this->objectListNumber = OM_INIT;
64  this->objectListIterator = NULL;
65
66  this->toList(OM_NULL);
[2190]67}
[2043]68
69/**
[4836]70 *  standard destructor
[2043]71*/
[2190]72WorldEntity::~WorldEntity ()
[2036]73{
[7125]74  State::getObjectManager()->toList(this, OM_INIT);
75
76  // Delete the model (unregister it with the ResourceManager)
77  for (unsigned int i = 0; i < this->models.size(); i++)
78    this->setModel(NULL, i);
79
[5498]80  // Delete the obbTree
[5302]81  if( this->obbTree != NULL)
[4814]82    delete this->obbTree;
[5994]83
[6700]84  if (this->healthWidget != NULL)
85    delete this->healthWidget;
[3531]86}
87
[5498]88/**
89 * loads the WorldEntity Specific Parameters.
90 * @param root: the XML-Element to load the Data From
91 */
[4436]92void WorldEntity::loadParams(const TiXmlElement* root)
93{
[5498]94  // Do the PNode loading stuff
[6512]95  PNode::loadParams(root);
[5498]96
[6222]97  LoadParam(root, "md2texture", this, WorldEntity, loadMD2Texture)
[6430]98  .describe("the fileName of the texture, that should be loaded onto this world-entity. (must be relative to the data-dir)")
[7198]99  .defaultValues("");
[6222]100
[4436]101  // Model Loading
[5671]102  LoadParam(root, "model", this, WorldEntity, loadModel)
[6430]103  .describe("the fileName of the model, that should be loaded onto this world-entity. (must be relative to the data-dir)")
[7198]104  .defaultValues("", 1.0f, 0);
[6430]105
[6700]106  LoadParam(root, "maxHealth", this, WorldEntity, setHealthMax)
107  .describe("The Maximum health that can be loaded onto this entity")
[7198]108  .defaultValues(1.0f);
[6430]109
[6700]110  LoadParam(root, "health", this, WorldEntity, setHealth)
111  .describe("The Health the WorldEntity has at this moment")
[7198]112  .defaultValues(1.0f);
[4436]113}
114
[6222]115
[3531]116/**
[4885]117 * loads a Model onto a WorldEntity
[4836]118 * @param fileName the name of the model to load
[5057]119 * @param scaling the Scaling of the model
[7221]120 */
121void WorldEntity::loadModel(const std::string& fileName, float scaling, unsigned int modelNumber)
[4261]122{
[6695]123  this->modelLODName = fileName;
[6424]124  this->scaling = scaling;
[7221]125  if (!fileName.empty())
[6142]126  {
[6430]127    // search for the special character # in the LoadParam
[7221]128    if (fileName.find('#') != std::string::npos)
[6222]129    {
[7221]130      PRINTF(4)("Found # in %s... searching for LOD's\n", fileName.c_str());
131      std::string lodFile = fileName;
132      unsigned int offset = lodFile.find('#');
[6720]133      for (unsigned int i = 0; i < 3; i++)
[6005]134      {
[7221]135        lodFile[offset] = 48+(int)i;
[6222]136        if (ResourceManager::isInDataDir(lodFile))
137          this->loadModel(lodFile, scaling, i);
[6005]138      }
[6222]139      return;
140    }
[6720]141    if (this->scaling <= 0.0)
[6424]142    {
[7193]143      PRINTF(1)("YOU GAVE ME A CRAPY SCALE resetting to 1.0\n");
[6720]144      this->scaling = 1.0;
[6424]145    }
[7221]146    if(fileName.find(".obj") != std::string::npos)
[6222]147    {
[7221]148      PRINTF(4)("fetching OBJ file: %s\n", fileName.c_str());
[7193]149      BaseObject* loadedModel = ResourceManager::getInstance()->load(fileName, OBJ, RP_CAMPAIGN, this->scaling);
150      if (loadedModel != NULL)
151        this->setModel(dynamic_cast<Model*>(loadedModel), modelNumber);
[7221]152      else
153        PRINTF(1)("OBJ-File %s not found.\n", fileName.c_str());
[6222]154
155      if( modelNumber == 0)
156        this->buildObbTree(4);
157    }
[7221]158    else if(fileName.find(".md2") != std::string::npos)
[6222]159    {
[7221]160      PRINTF(4)("fetching MD2 file: %s\n", fileName.c_str());
[7055]161      Model* m = new MD2Model(fileName, this->md2TextureFileName, this->scaling);
[6430]162      //this->setModel((Model*)ResourceManager::getInstance()->load(fileName, MD2, RP_CAMPAIGN), 0);
[6222]163      this->setModel(m, 0);
[7068]164
165      if( m != NULL)
166        this->buildObbTree(4);
[6222]167    }
[4732]168  }
169  else
[6341]170  {
[5995]171    this->setModel(NULL);
[6341]172  }
[4261]173}
174
[5061]175/**
[5994]176 * sets a specific Model for the Object.
177 * @param model The Model to set
178 * @param modelNumber the n'th model in the List to get.
179 */
180void WorldEntity::setModel(Model* model, unsigned int modelNumber)
181{
[5995]182  if (this->models.size() <= modelNumber)
183    this->models.resize(modelNumber+1, NULL);
184
185  if (this->models[modelNumber] != NULL)
[6004]186  {
[7193]187    Resource* resource = ResourceManager::getInstance()->locateResourceByPointer(dynamic_cast<BaseObject*>(this->models[modelNumber]));
[7123]188    if (resource != NULL)
189      ResourceManager::getInstance()->unload(resource, RP_LEVEL);
190    else
191    {
192      PRINTF(4)("Forcing model deletion\n");
193      delete this->models[modelNumber];
194    }
[5994]195  }
[6222]196
[5995]197  this->models[modelNumber] = model;
[5994]198
[6222]199
[6430]200  //   if (this->model != NULL)
201  //     this->buildObbTree(4);
[5994]202}
203
204
205/**
[5061]206 * builds the obb-tree
207 * @param depth the depth to calculate
208 */
209bool WorldEntity::buildObbTree(unsigned int depth)
210{
[5428]211  if (this->obbTree)
212    delete this->obbTree;
213
[5995]214  if (this->models[0] != NULL)
[5428]215  {
216    PRINTF(4)("creating obb tree\n");
[5708]217
218
[5995]219    this->obbTree = new OBBTree(depth, (sVec3D*)this->models[0]->getVertexArray(), this->models[0]->getVertexCount());
[5428]220    return true;
221  }
222  else
223  {
224    PRINTF(2)("could not create obb-tree, because no model was loaded yet\n");
225    this->obbTree = NULL;
226    return false;
227  }
[5061]228}
[5057]229
[6142]230/**
231 * @brief moves this entity to the List OM_List
232 * @param list the list to set this Entity to.
233 *
234 * this is the same as a call to State::getObjectManager()->toList(entity , list);
235 * directly, but with an easier interface.
236 *
237 * @todo inline this (peut etre)
238 */
239void WorldEntity::toList(OM_LIST list)
240{
241  State::getObjectManager()->toList(this, list);
242}
[5061]243
[6142]244
245
[4261]246/**
[4885]247 * sets the character attributes of a worldentity
[4836]248 * @param character attributes
[4885]249 *
250 * these attributes don't have to be set, only use them, if you need them
[2043]251*/
[5498]252//void WorldEntity::setCharacterAttributes(CharacterAttributes* charAttr)
253//{}
[2036]254
[3583]255
[2043]256/**
[5029]257 *  this function is called, when two entities collide
258 * @param entity: the world entity with whom it collides
259 *
260 * Implement behaviour like damage application or other miscellaneous collision stuff in this function
261 */
262void WorldEntity::collidesWith(WorldEntity* entity, const Vector& location)
263{
[5498]264  /**
265   * THIS IS A DEFAULT COLLISION-Effect.
266   * IF YOU WANT TO CREATE A SPECIFIC COLLISION ON EACH OBJECT
267   * USE::
268   * if (entity->isA(CL_WHAT_YOU_ARE_LOOKING_FOR)) { printf "dothings"; };
269   *
270   * You can always define a default Action.... don't be affraid just test it :)
271   */
[6430]272  //  PRINTF(3)("collision %s vs %s @ (%f,%f,%f)\n", this->getClassName(), entity->getClassName(), location.x, location.y, location.z);
[5029]273}
274
[2043]275
276/**
[7833]277 *  this function is called, when two entities collide
278 * @param entity: the world entity with whom it collides
279 *
280 * Implement behaviour like damage application or other miscellaneous collision stuff in this function
281 */
282void WorldEntity::collidesWithGround(const Vector& location)
283{
284  PRINTF(0)("BSP_GROUND: %s collides \n", this->getClassName() );
285}
286
287void WorldEntity::collidesWithGround(const Vector& feet, const Vector& ray_1, const Vector& ray_2)
288{
289 
290  PRINTF(0)("BSP_GROUND: Player collides \n", this->getClassName() );
291  Vector v = this->getAbsDirX();
292  v.x *= 10;
293  v.y *= 10;
294  v.z *= 10;
295  this->setAbsCoor(ray_2 - v);
296}
297
298/**
[5498]299 *  this is called immediately after the Entity has been constructed, initialized and then Spawned into the World
[4885]300 *
[5498]301 */
[3229]302void WorldEntity::postSpawn ()
[6430]303{}
[2043]304
[3583]305
[2043]306/**
[6959]307 *  this method is called by the world if the WorldEntity leaves the game
[5498]308 */
[6959]309void WorldEntity::leaveWorld ()
[6430]310{}
[2043]311
[3583]312
[2190]313/**
[7085]314 * resets the WorldEntity to its initial values. eg. used for multiplayer games: respawning
315 */
316void WorldEntity::reset()
317{}
318
319/**
[4836]320 *  this method is called every frame
321 * @param time: the time in seconds that has passed since the last tick
[4885]322 *
323 * Handle all stuff that should update with time inside this method (movement, animation, etc.)
[2043]324*/
[4570]325void WorldEntity::tick(float time)
[6430]326{}
[3583]327
[5498]328
[3583]329/**
[4836]330 *  the entity is drawn onto the screen with this function
[4885]331 *
332 * This is a central function of an entity: call it to let the entity painted to the screen.
333 * Just override this function with whatever you want to be drawn.
[3365]334*/
[5500]335void WorldEntity::draw() const
[3803]336{
[6430]337  //PRINTF(0)("(%s::%s)\n", this->getClassName(), this->getName());
[6281]338  //  assert(!unlikely(this->models.empty()));
[6002]339  {
340    glMatrixMode(GL_MODELVIEW);
341    glPushMatrix();
[4570]342
[6002]343    /* translate */
344    glTranslatef (this->getAbsCoor ().x,
345                  this->getAbsCoor ().y,
346                  this->getAbsCoor ().z);
[6004]347    Vector tmpRot = this->getAbsDir().getSpacialAxis();
348    glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
[2043]349
[6004]350
351    // This Draws the LOD's
[7014]352    float cameraDistance = State::getCamera()->distance(this);
[6004]353    if (cameraDistance > 30 && this->models.size() >= 3 && this->models[2] != NULL)
[6002]354    {
[6222]355      this->models[2]->draw();
[6004]356    }
357    else if (cameraDistance > 10 && this->models.size() >= 2 && this->models[1] != NULL)
[6002]358    {
359      this->models[1]->draw();
[6004]360    }
361    else if (this->models.size() >= 1 && this->models[0] != NULL)
[6002]362    {
363      this->models[0]->draw();
364    }
365    glPopMatrix();
366  }
[3803]367}
[3583]368
[6430]369/**
[6700]370 * @param health the Health to add.
371 * @returns the health left (this->healthMax - health+this->health)
[6430]372 */
[6700]373float WorldEntity::increaseHealth(float health)
[6430]374{
[6700]375  this->health += health;
376  if (this->health > this->healthMax)
[6430]377  {
[6700]378    float retHealth = this->healthMax - this->health;
379    this->health = this->healthMax;
380    this->updateHealthWidget();
381    return retHealth;
[6430]382  }
[6700]383  this->updateHealthWidget();
[6430]384  return 0.0;
385}
[6281]386
[5498]387/**
[6700]388 * @param health the Health to be removed
[6430]389 * @returns 0.0 or the rest, that was not substracted (bellow 0.0)
390 */
[6700]391float WorldEntity::decreaseHealth(float health)
[6430]392{
[6700]393  this->health -= health;
[6430]394
[6700]395  if (this->health < 0)
[6430]396  {
[6700]397    float retHealth = -this->health;
398    this->health = 0.0f;
399    this->updateHealthWidget();
400    return retHealth;
[6430]401  }
[6700]402  this->updateHealthWidget();
[6430]403  return 0.0;
404
405}
406
407/**
[6700]408 * @param maxHealth the maximal health that can be loaded onto the entity.
[6430]409 */
[6700]410void WorldEntity::setHealthMax(float healthMax)
[6430]411{
[6700]412  this->healthMax = healthMax;
413  if (this->health > this->healthMax)
[6430]414  {
[6700]415    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());
416    this->health = this->healthMax;
[6430]417  }
[6700]418  this->updateHealthWidget();
[6430]419}
420
[6431]421/**
[6700]422 * @brief creates the HealthWidget
[6431]423 *
[6700]424 * since not all entities need an HealthWidget, it is only created on request.
[6431]425 */
[6700]426void WorldEntity::createHealthWidget()
[6430]427{
[6700]428  if (this->healthWidget == NULL)
[6430]429  {
[6700]430    this->healthWidget = new GLGuiBar();
431    this->healthWidget->setSize2D(30,400);
432    this->healthWidget->setAbsCoor2D(10,100);
[6430]433
[6700]434    this->updateHealthWidget();
[6430]435  }
436  else
[6700]437    PRINTF(3)("Allready created the HealthWidget for %s::%s\n", this->getClassName(), this->getName());
[6430]438}
439
[6700]440void WorldEntity::increaseHealthMax(float increaseHealth)
[6440]441{
[6700]442  this->healthMax += increaseHealth;
443  this->updateHealthWidget();
[6440]444}
445
[6700]446
447GLGuiWidget* WorldEntity::getHealthWidget()
448{
449  this->createHealthWidget();
450  return this->healthWidget;
451}
452
[6431]453/**
[6700]454 * @param visibility shows or hides the health-bar
[6431]455 * (creates the widget if needed)
456 */
[6700]457void WorldEntity::setHealthWidgetVisibilit(bool visibility)
[6430]458{
[7198]459  if (visibility)
460  {
461    if (this->healthWidget != NULL)
462      this->healthWidget->show();
463    else
[6430]464    {
[7198]465      this->createHealthWidget();
466      this->updateHealthWidget();
467      this->healthWidget->show();
[6430]468    }
[7198]469  }
470  else if (this->healthWidget != NULL)
471    this->healthWidget->hide();
[6430]472}
473
[6431]474/**
[6700]475 * @brief updates the HealthWidget
[6431]476 */
[6700]477void WorldEntity::updateHealthWidget()
[6430]478{
[6700]479  if (this->healthWidget != NULL)
[6430]480  {
[6700]481    this->healthWidget->setMaximum(this->healthMax);
482    this->healthWidget->setValue(this->health);
[6430]483  }
484}
485
486
487/**
[5498]488 * DEBUG-DRAW OF THE BV-Tree.
489 * @param depth What depth to draw
490 * @param drawMode the mode to draw this entity under
491 */
[5501]492void WorldEntity::drawBVTree(unsigned int depth, int drawMode) const
[4684]493{
494  glMatrixMode(GL_MODELVIEW);
495  glPushMatrix();
496  /* translate */
497  glTranslatef (this->getAbsCoor ().x,
498                this->getAbsCoor ().y,
499                this->getAbsCoor ().z);
500  /* rotate */
[4998]501  Vector tmpRot = this->getAbsDir().getSpacialAxis();
502  glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
[4684]503
504  if (this->obbTree)
505    this->obbTree->drawBV(depth, drawMode);
506  glPopMatrix();
507}
[6341]508
[6424]509
[6341]510/**
[6424]511 * Debug the WorldEntity
512 */
513void WorldEntity::debugEntity() const
514{
515  PRINT(0)("WorldEntity %s::%s  (DEBUG)\n", this->getClassName(), this->getName());
516  this->debugNode();
517  PRINT(0)("List: %s ; ModelCount %d - ", ObjectManager::OMListToString(this->objectListNumber) , this->models.size());
518  for (unsigned int i = 0; i < this->models.size(); i++)
519  {
520    if (models[i] != NULL)
521      PRINT(0)(" : %d:%s", i, this->models[i]->getName());
522  }
523  PRINT(0)("\n");
524
525}
526
527
[6498]528
529
530/********************************************************************************************
531 NETWORK STUFF
532 ********************************************************************************************/
533
534
[6424]535/**
[6341]536 * Writes data from network containing information about the state
537 * @param data pointer to data
538 * @param length length of data
539 * @param sender hostID of sender
540 */
541int WorldEntity::writeState( const byte * data, int length, int sender )
542{
[7230]543  std::string modelFileName;
[6341]544  SYNCHELP_READ_BEGIN();
545
[6815]546  SYNCHELP_READ_FKT( PNode::writeState, NWT_WE_PN_WRITESTATE );
[6341]547
[7230]548  SYNCHELP_READ_STRING( modelFileName, NWT_WE_PN_MODELFILENAME );
[6815]549  SYNCHELP_READ_FLOAT( scaling, NWT_WE_PN_SCALING );
[6341]550  //check if modelFileName is relative to datadir or absolute
[6424]551
[6695]552
[7230]553  PRINTF(0)("================ LOADING MODEL %s, %f\n", modelFileName.c_str(), scaling);
[6695]554
[7230]555  if ( modelFileName != "" )
[6341]556  {
[6695]557    loadModel( modelFileName, scaling);
558    PRINTF(0)("modelfilename: %s\n", getModel( 0 )->getName());
[6341]559  }
560
[6634]561  /*SYNCHELP_READ_STRINGM( modelFileName );
[6498]562
[6424]563  if ( strcmp(modelFileName, "") )
[6498]564    if ( strstr(modelFileName, ResourceManager::getInstance()->getDataDir()) )
565    {
566      this->md2TextureFileName = new char[strlen(modelFileName)-strlen(ResourceManager::getInstance()->getDataDir())+1];
567      strcpy((char*)this->md2TextureFileName, modelFileName+strlen(ResourceManager::getInstance()->getDataDir()));
568    }
569    else
570    {
571      this->md2TextureFileName = modelFileName;
572    }
[6634]573  */
[6424]574
[6341]575  return SYNCHELP_READ_N;
576}
577
[6498]578
[6341]579/**
580 * data copied in data will bee sent to another host
581 * @param data pointer to data
582 * @param maxLength max length of data
583 * @return the number of bytes writen
584 */
585int WorldEntity::readState( byte * data, int maxLength )
586{
587  SYNCHELP_WRITE_BEGIN();
588
[6815]589  SYNCHELP_WRITE_FKT( PNode::readState, NWT_WE_PN_WRITESTATE );
[6341]590
[7230]591  if ( getModel(0) && getModel(0)->getName() != "" )
[6634]592  {
[7230]593    std::string name = getModel( 0 )->getName();
[6634]594
[7230]595    if (  name.find( ResourceManager::getInstance()->getDataDir() ) == 0 ) 
[6634]596    {
[7230]597      name.erase(ResourceManager::getInstance()->getDataDir().size());
[6634]598    }
599
[6815]600    SYNCHELP_WRITE_STRING( name, NWT_WE_PN_MODELFILENAME );
[6634]601  }
602  else
603  {
[6815]604    SYNCHELP_WRITE_STRING("", NWT_WE_PN_MODELFILENAME);
[6634]605  }
606
[6815]607  SYNCHELP_WRITE_FLOAT( scaling, NWT_WE_PN_SCALING );
[6634]608  /*if ( this->md2TextureFileName!=NULL && strcmp(this->md2TextureFileName, "") )
[6424]609  {
610    SYNCHELP_WRITE_STRING(this->md2TextureFileName);
611  }
612  else
613  {
614    SYNCHELP_WRITE_STRING("");
[7198]615  }*/
[6424]616
[6341]617  return SYNCHELP_WRITE_N;
618}
Note: See TracBrowser for help on using the repository browser.