Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/cr/src/world_entities/world_entity.cc @ 7944

Last change on this file since 7944 was 7944, checked in by patrick, 18 years ago

cr: collision registration work

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