Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

merged the network branche to the trunk

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