Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

orxonox/trunk: merged the std::branche back

File size: 15.3 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/**
[5498]277 *  this is called immediately after the Entity has been constructed, initialized and then Spawned into the World
[4885]278 *
[5498]279 */
[3229]280void WorldEntity::postSpawn ()
[6430]281{}
[2043]282
[3583]283
[2043]284/**
[6959]285 *  this method is called by the world if the WorldEntity leaves the game
[5498]286 */
[6959]287void WorldEntity::leaveWorld ()
[6430]288{}
[2043]289
[3583]290
[2190]291/**
[7085]292 * resets the WorldEntity to its initial values. eg. used for multiplayer games: respawning
293 */
294void WorldEntity::reset()
295{}
296
297/**
[4836]298 *  this method is called every frame
299 * @param time: the time in seconds that has passed since the last tick
[4885]300 *
301 * Handle all stuff that should update with time inside this method (movement, animation, etc.)
[2043]302*/
[4570]303void WorldEntity::tick(float time)
[6430]304{}
[3583]305
[5498]306
[3583]307/**
[4836]308 *  the entity is drawn onto the screen with this function
[4885]309 *
310 * This is a central function of an entity: call it to let the entity painted to the screen.
311 * Just override this function with whatever you want to be drawn.
[3365]312*/
[5500]313void WorldEntity::draw() const
[3803]314{
[6430]315  //PRINTF(0)("(%s::%s)\n", this->getClassName(), this->getName());
[6281]316  //  assert(!unlikely(this->models.empty()));
[6002]317  {
318    glMatrixMode(GL_MODELVIEW);
319    glPushMatrix();
[4570]320
[6002]321    /* translate */
322    glTranslatef (this->getAbsCoor ().x,
323                  this->getAbsCoor ().y,
324                  this->getAbsCoor ().z);
[6004]325    Vector tmpRot = this->getAbsDir().getSpacialAxis();
326    glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
[2043]327
[6004]328
329    // This Draws the LOD's
[7014]330    float cameraDistance = State::getCamera()->distance(this);
[6004]331    if (cameraDistance > 30 && this->models.size() >= 3 && this->models[2] != NULL)
[6002]332    {
[6222]333      this->models[2]->draw();
[6004]334    }
335    else if (cameraDistance > 10 && this->models.size() >= 2 && this->models[1] != NULL)
[6002]336    {
337      this->models[1]->draw();
[6004]338    }
339    else if (this->models.size() >= 1 && this->models[0] != NULL)
[6002]340    {
341      this->models[0]->draw();
342    }
343    glPopMatrix();
344  }
[3803]345}
[3583]346
[6430]347/**
[6700]348 * @param health the Health to add.
349 * @returns the health left (this->healthMax - health+this->health)
[6430]350 */
[6700]351float WorldEntity::increaseHealth(float health)
[6430]352{
[6700]353  this->health += health;
354  if (this->health > this->healthMax)
[6430]355  {
[6700]356    float retHealth = this->healthMax - this->health;
357    this->health = this->healthMax;
358    this->updateHealthWidget();
359    return retHealth;
[6430]360  }
[6700]361  this->updateHealthWidget();
[6430]362  return 0.0;
363}
[6281]364
[5498]365/**
[6700]366 * @param health the Health to be removed
[6430]367 * @returns 0.0 or the rest, that was not substracted (bellow 0.0)
368 */
[6700]369float WorldEntity::decreaseHealth(float health)
[6430]370{
[6700]371  this->health -= health;
[6430]372
[6700]373  if (this->health < 0)
[6430]374  {
[6700]375    float retHealth = -this->health;
376    this->health = 0.0f;
377    this->updateHealthWidget();
378    return retHealth;
[6430]379  }
[6700]380  this->updateHealthWidget();
[6430]381  return 0.0;
382
383}
384
385/**
[6700]386 * @param maxHealth the maximal health that can be loaded onto the entity.
[6430]387 */
[6700]388void WorldEntity::setHealthMax(float healthMax)
[6430]389{
[6700]390  this->healthMax = healthMax;
391  if (this->health > this->healthMax)
[6430]392  {
[6700]393    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());
394    this->health = this->healthMax;
[6430]395  }
[6700]396  this->updateHealthWidget();
[6430]397}
398
[6431]399/**
[6700]400 * @brief creates the HealthWidget
[6431]401 *
[6700]402 * since not all entities need an HealthWidget, it is only created on request.
[6431]403 */
[6700]404void WorldEntity::createHealthWidget()
[6430]405{
[6700]406  if (this->healthWidget == NULL)
[6430]407  {
[6700]408    this->healthWidget = new GLGuiBar();
409    this->healthWidget->setSize2D(30,400);
410    this->healthWidget->setAbsCoor2D(10,100);
[6430]411
[6700]412    this->updateHealthWidget();
[6430]413  }
414  else
[6700]415    PRINTF(3)("Allready created the HealthWidget for %s::%s\n", this->getClassName(), this->getName());
[6430]416}
417
[6700]418void WorldEntity::increaseHealthMax(float increaseHealth)
[6440]419{
[6700]420  this->healthMax += increaseHealth;
421  this->updateHealthWidget();
[6440]422}
423
[6700]424
425GLGuiWidget* WorldEntity::getHealthWidget()
426{
427  this->createHealthWidget();
428  return this->healthWidget;
429}
430
[6431]431/**
[6700]432 * @param visibility shows or hides the health-bar
[6431]433 * (creates the widget if needed)
434 */
[6700]435void WorldEntity::setHealthWidgetVisibilit(bool visibility)
[6430]436{
[7198]437  if (visibility)
438  {
439    if (this->healthWidget != NULL)
440      this->healthWidget->show();
441    else
[6430]442    {
[7198]443      this->createHealthWidget();
444      this->updateHealthWidget();
445      this->healthWidget->show();
[6430]446    }
[7198]447  }
448  else if (this->healthWidget != NULL)
449    this->healthWidget->hide();
[6430]450}
451
[6431]452/**
[6700]453 * @brief updates the HealthWidget
[6431]454 */
[6700]455void WorldEntity::updateHealthWidget()
[6430]456{
[6700]457  if (this->healthWidget != NULL)
[6430]458  {
[6700]459    this->healthWidget->setMaximum(this->healthMax);
460    this->healthWidget->setValue(this->health);
[6430]461  }
462}
463
464
465/**
[5498]466 * DEBUG-DRAW OF THE BV-Tree.
467 * @param depth What depth to draw
468 * @param drawMode the mode to draw this entity under
469 */
[5501]470void WorldEntity::drawBVTree(unsigned int depth, int drawMode) const
[4684]471{
472  glMatrixMode(GL_MODELVIEW);
473  glPushMatrix();
474  /* translate */
475  glTranslatef (this->getAbsCoor ().x,
476                this->getAbsCoor ().y,
477                this->getAbsCoor ().z);
478  /* rotate */
[4998]479  Vector tmpRot = this->getAbsDir().getSpacialAxis();
480  glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
[4684]481
482  if (this->obbTree)
483    this->obbTree->drawBV(depth, drawMode);
484  glPopMatrix();
485}
[6341]486
[6424]487
[6341]488/**
[6424]489 * Debug the WorldEntity
490 */
491void WorldEntity::debugEntity() const
492{
493  PRINT(0)("WorldEntity %s::%s  (DEBUG)\n", this->getClassName(), this->getName());
494  this->debugNode();
495  PRINT(0)("List: %s ; ModelCount %d - ", ObjectManager::OMListToString(this->objectListNumber) , this->models.size());
496  for (unsigned int i = 0; i < this->models.size(); i++)
497  {
498    if (models[i] != NULL)
499      PRINT(0)(" : %d:%s", i, this->models[i]->getName());
500  }
501  PRINT(0)("\n");
502
503}
504
505
[6498]506
507
508/********************************************************************************************
509 NETWORK STUFF
510 ********************************************************************************************/
511
512
[6424]513/**
[6341]514 * Writes data from network containing information about the state
515 * @param data pointer to data
516 * @param length length of data
517 * @param sender hostID of sender
518 */
519int WorldEntity::writeState( const byte * data, int length, int sender )
520{
[7230]521  std::string modelFileName;
[6341]522  SYNCHELP_READ_BEGIN();
523
[6815]524  SYNCHELP_READ_FKT( PNode::writeState, NWT_WE_PN_WRITESTATE );
[6341]525
[7230]526  SYNCHELP_READ_STRING( modelFileName, NWT_WE_PN_MODELFILENAME );
[6815]527  SYNCHELP_READ_FLOAT( scaling, NWT_WE_PN_SCALING );
[6341]528  //check if modelFileName is relative to datadir or absolute
[6424]529
[6695]530
[7230]531  PRINTF(0)("================ LOADING MODEL %s, %f\n", modelFileName.c_str(), scaling);
[6695]532
[7230]533  if ( modelFileName != "" )
[6341]534  {
[6695]535    loadModel( modelFileName, scaling);
536    PRINTF(0)("modelfilename: %s\n", getModel( 0 )->getName());
[6341]537  }
538
[6634]539  /*SYNCHELP_READ_STRINGM( modelFileName );
[6498]540
[6424]541  if ( strcmp(modelFileName, "") )
[6498]542    if ( strstr(modelFileName, ResourceManager::getInstance()->getDataDir()) )
543    {
544      this->md2TextureFileName = new char[strlen(modelFileName)-strlen(ResourceManager::getInstance()->getDataDir())+1];
545      strcpy((char*)this->md2TextureFileName, modelFileName+strlen(ResourceManager::getInstance()->getDataDir()));
546    }
547    else
548    {
549      this->md2TextureFileName = modelFileName;
550    }
[6634]551  */
[6424]552
[6341]553  return SYNCHELP_READ_N;
554}
555
[6498]556
[6341]557/**
558 * data copied in data will bee sent to another host
559 * @param data pointer to data
560 * @param maxLength max length of data
561 * @return the number of bytes writen
562 */
563int WorldEntity::readState( byte * data, int maxLength )
564{
565  SYNCHELP_WRITE_BEGIN();
566
[6815]567  SYNCHELP_WRITE_FKT( PNode::readState, NWT_WE_PN_WRITESTATE );
[6341]568
[7230]569  if ( getModel(0) && getModel(0)->getName() != "" )
[6634]570  {
[7230]571    std::string name = getModel( 0 )->getName();
[6634]572
[7230]573    if (  name.find( ResourceManager::getInstance()->getDataDir() ) == 0 ) 
[6634]574    {
[7230]575      name.erase(ResourceManager::getInstance()->getDataDir().size());
[6634]576    }
577
[6815]578    SYNCHELP_WRITE_STRING( name, NWT_WE_PN_MODELFILENAME );
[6634]579  }
580  else
581  {
[6815]582    SYNCHELP_WRITE_STRING("", NWT_WE_PN_MODELFILENAME);
[6634]583  }
584
[6815]585  SYNCHELP_WRITE_FLOAT( scaling, NWT_WE_PN_SCALING );
[6634]586  /*if ( this->md2TextureFileName!=NULL && strcmp(this->md2TextureFileName, "") )
[6424]587  {
588    SYNCHELP_WRITE_STRING(this->md2TextureFileName);
589  }
590  else
591  {
592    SYNCHELP_WRITE_STRING("");
[7198]593  }*/
[6424]594
[6341]595  return SYNCHELP_WRITE_N;
596}
Note: See TracBrowser for help on using the repository browser.