Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/cleanup/src/world_entities/world_entity.cc @ 10664

Last change on this file since 10664 was 10618, checked in by bknecht, 18 years ago

merged cleanup into trunk (only improvements)

File size: 25.2 KB
Line 
1
2
3/*
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
15   main-programmer: Benjamin Grauer
16   co-programmer:   Christian Meier
17*/
18#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_WORLD_ENTITY
19
20#include "world_entity.h"
21#include "shell_command.h"
22
23#include "util/loading/resource_manager.h"
24#include "resource_obj.h"
25#include "md2/md2Model.h"
26#include "md3/md3_model.h"
27
28#include "oif/object_information_file.h"
29#include "tools/mount_point.h"
30
31#include "aabb_tree_node.h"
32
33#include "util/loading/load_param.h"
34#include "loading/load_param_xml.h"
35#include "util/loading/factory.h"
36
37#include "obb_tree.h"
38
39#include "elements/glgui_energywidget.h"
40#include "elements/glgui_energywidgetvertical.h"
41
42#include "state.h"
43#include "tools/camera.h"
44
45#include "collision_filter.h"
46#include "collision_event.h"
47#include "game_rules.h"
48#include "kill.h"
49#include "debug.h"
50
51#include "track/track.h"
52
53#include "projectiles/projectile.h"
54
55SHELL_COMMAND(model, WorldEntity, loadModel)
56->describe("sets the Model of the WorldEntity")
57->defaultValues("models/ships/fighter.obj", 1.0f);
58
59SHELL_COMMAND(debugEntity, WorldEntity, debugWE);
60
61
62ObjectListDefinition(WorldEntity);
63/**
64 *  Loads the WordEntity-specific Part of any derived Class
65 *
66 * @param root: Normally NULL, as the Derived Entities define a loadParams Function themeselves,
67 *              that can calls WorldEntities loadParams for itself.
68 */
69WorldEntity::WorldEntity()
70    : Synchronizeable(), _collisionFilter(this)
71{
72  this->registerObject(this, WorldEntity::_objectList);
73
74  this->obbTree = NULL;
75  this->aabbNode = NULL;
76  this->healthWidget = NULL;
77  this->healthMax = 1.0f;
78  this->health = 1.0f;
79  this->damage = 0.0f; // no damage dealt by a default entity
80  this->scaling = 1.0f;
81  this->oiFile = NULL;
82  // add 10 members to this array
83  this->mountPoints.reserve(10);
84
85  /* OSOLETE */
86  this->bVisible = true;
87  this->bCollide = true;
88
89  this->objectListNumber = OM_INIT;
90  this->lastObjectListNumber = OM_INIT;
91
92  this->_bOnGround = false;
93
94  // Track of this entity
95  this->entityTrack = NULL;
96  this->bDrawTrack = false;
97
98  // registering default reactions:
99  this->subscribeReaction(CoRe::CREngine::CR_OBJECT_DAMAGE, Projectile::staticClassID());
100
101  this->toList(OM_NULL);
102
103  this->registerVar( new SynchronizeableString( &this->md2TextureFileName, &this->md2TextureFileName, "md2TextureFileName", PERMISSION_MASTER_SERVER ) );
104  this->modelFileName_handle = registerVarId( new SynchronizeableString( &modelFileName, &modelFileName, "modelFileName", PERMISSION_MASTER_SERVER ) );
105  this->scaling_handle = registerVarId( new SynchronizeableFloat( &scaling, &scaling, "scaling", PERMISSION_MASTER_SERVER ) );
106  this->list_handle = registerVarId( new SynchronizeableInt( (int*)&objectListNumber, &list_write, "list", PERMISSION_MASTER_SERVER ) );
107
108  this->health_handle = registerVarId( new SynchronizeableFloat( &this->health, &this->health_write, "health", PERMISSION_MASTER_SERVER ) );
109  this->healthMax_handle = registerVarId( new SynchronizeableFloat( &this->healthMax, &this->healthMax_write, "maxHealth", PERMISSION_MASTER_SERVER ) );
110}
111
112/**
113 *  standard destructor
114*/
115WorldEntity::~WorldEntity ()
116{
117  State::getObjectManager()->toList(this, OM_INIT);
118
119  // Delete the model (unregister it with the ResourceManager)
120  for (unsigned int i = 0; i < this->models.size(); i++)
121    this->setModel(NULL, i);
122
123  // remove the object information file
124  if( this->oiFile)
125    delete this->oiFile;
126  // and clear all monut points
127  this->mountPoints.clear();
128
129  // Delete the obbTree
130  if( this->obbTree != NULL)
131    delete this->obbTree;
132
133  if (this->healthWidget != NULL)
134    delete this->healthWidget;
135
136  this->unsubscribeReactions();
137}
138
139/**
140 * loads the WorldEntity Specific Parameters.
141 * @param root: the XML-Element to load the Data From
142 */
143void WorldEntity::loadParams(const TiXmlElement* root)
144{
145  // Do the PNode loading stuff
146  PNode::loadParams(root);
147
148  LoadParam(root, "md2texture", this, WorldEntity, loadMD2Texture)
149  .describe("the fileName of the texture, that should be loaded onto this world-entity. (must be relative to the data-dir)")
150  .defaultValues("");
151
152  // Model Loading
153  LoadParam(root, "model", this, WorldEntity, loadModel)
154  .describe("the fileName of the model, that should be loaded onto this world-entity. (must be relative to the data-dir)")
155  .defaultValues("", 1.0f, 0);
156
157  LoadParam(root, "mountpoints", this, WorldEntity, loadMountPoints)
158  .describe("the fileName of the object information file (optional)");
159
160  // Entity Attributes
161  LoadParam(root, "maxHealth", this, WorldEntity, setHealthMax)
162  .describe("The Maximum health that can be loaded onto this entity")
163  .defaultValues(1.0f);
164
165  LoadParam(root, "health", this, WorldEntity, setHealth)
166  .describe("The Health the WorldEntity has at this moment")
167  .defaultValues(1.0f);
168
169  LoadParam(root, "list", this, WorldEntity, toListS);
170
171  LoadParam(root, "drawTrack", this, WorldEntity, drawDebugTrack)
172      .describe("draws the track for debugging purposes");
173
174  // Track
175  LoadParamXML(root, "Track", this, WorldEntity, addTrack)
176  .describe("creates and adds a track to this WorldEntity");
177}
178
179
180/**
181 * this functions adds a track to this workd entity. This can be usefull, if you like this WE to follow a some waypoints.
182 * here the track is created and further initializing left for the Track itself
183 */
184void WorldEntity::addTrack(const TiXmlElement* root)
185{
186  // The problem we have is most likely here. The track should be constructed WITH the XML-Code
187  this->entityTrack = new Track(root);
188  this->setParent(this->entityTrack->getTrackNode());
189  this->entityTrack->getTrackNode()->setParentMode(PNODE_ALL);
190  /*LOAD_PARAM_START_CYCLE(root, element);
191  {
192    PRINTF(4)("element is: %s\n", element->Value());
193    Factory::fabricate(element);
194  }
195  LOAD_PARAM_END_CYCLE(element);*/
196
197
198}
199
200void WorldEntity::pauseTrack(bool stop)
201{
202     if(this->entityTrack)
203       this->entityTrack->pauseTrack(stop);
204}
205
206
207/**
208 * loads a Model onto a WorldEntity
209 * @param fileName the name of the model to load
210 * @param scaling the Scaling of the model
211 *
212 * FIXME
213 * @todo: separate the obb tree generation from the model
214 */
215void WorldEntity::loadModel(const std::string& fileName, float scaling, unsigned int modelNumber, unsigned int obbTreeDepth)
216{
217  this->modelLODName = fileName;
218  this->scaling = scaling;
219
220  std::string name = fileName;
221
222  if (  name.find( Resources::ResourceManager::getInstance()->mainGlobalPath().name() ) == 0 )
223  {
224    name.erase(Resources::ResourceManager::getInstance()->mainGlobalPath().name().size());
225  }
226
227  this->modelFileName = name;
228
229  if (!fileName.empty())
230  {
231    // search for the special character # in the LoadParam
232    if (fileName.find('#') != std::string::npos)
233    {
234      PRINTF(4)("Found # in %s... searching for LOD's\n", fileName.c_str());
235      std::string lodFile = fileName;
236      unsigned int offset = lodFile.find('#');
237      for (unsigned int i = 0; i < 3; i++)
238      {
239        lodFile[offset] = 48+(int)i;
240        if (Resources::ResourceManager::getInstance()->checkFileInMainPath( lodFile))
241          this->loadModel(lodFile, scaling, i);
242      }
243      return;
244    }
245    if (this->scaling <= 0.0)
246    {
247      PRINTF(1)("YOU GAVE ME A CRAPY SCALE resetting to 1.0\n");
248      this->scaling = 1.0;
249    }
250    /// LOADING AN OBJ FILE
251    if(fileName.find(".obj") != std::string::npos)
252    {
253      PRINTF(4)("fetching OBJ file: %s\n", fileName.c_str());
254      // creating the model and loading it
255      StaticModel* model = new StaticModel();
256      *model = ResourceOBJ(fileName, this->scaling);
257
258      // check if ther is a valid model and load other stuff
259      if (model->getVertexCount() > 0)
260      {
261        this->setModel(model, modelNumber);
262
263        if( modelNumber == 0)
264        {
265          this->buildObbTree(obbTreeDepth);
266        }
267      }
268      else
269        delete model;
270    }
271    /// LOADING AN MD2-model
272    else if(fileName.find(".md2") != std::string::npos)
273    {
274      PRINTF(4)("fetching MD2 file: %s\n", fileName.c_str());
275      Model* m = new MD2Model(fileName, this->md2TextureFileName, this->scaling);
276      //this->setModel((Model*)ResourceManager::getInstance()->load(fileName, MD2, RP_CAMPAIGN), 0);
277      this->setModel(m, 0);
278
279      if( m != NULL)
280        this->buildObbTree(obbTreeDepth);
281    }
282    /// LOADING AN MD3-MODEL.
283    else if(fileName.find(".md3") != std::string::npos)
284    {
285      PRINTF(4)("fetching MD3 file: %s\n", fileName.c_str());
286      //      Model* m = new md3::MD3Model(fileName, this->scaling);
287      //      this->setModel(m, 0);
288
289      //       if( m != NULL)
290      //         this->buildObbTree(obbTreeDepth);
291    }
292  }
293  else
294  {
295    this->setModel(NULL);
296  }
297}
298
299/**
300 * sets a specific Model for the Object.
301 * @param model The Model to set
302 * @param modelNumber the n'th model in the List to get.
303 */
304void WorldEntity::setModel(Model* model, unsigned int modelNumber)
305{
306  if (this->models.size() <= modelNumber)
307    this->models.resize(modelNumber+1, NULL);
308
309  if (this->models[modelNumber] != NULL)
310  {
311    delete this->models[modelNumber];
312  }
313
314  this->models[modelNumber] = model;
315}
316
317
318
319/**
320 * loads the object information file for this model
321 * @param fileName the name of the file
322 */
323void WorldEntity::loadMountPoints(const std::string& fileName)
324{
325  PRINTF(5)("loading the oif File: %s\n", fileName.c_str());
326
327  // now load the object information file
328  this->oiFile = new ObjectInformationFile(fileName);
329
330  // get the model to load
331  Model* model = this->getModel();
332
333  // extract the mount points
334  if(model != NULL)
335    model->extractMountPoints();
336  else
337  {
338    PRINTF(0)("Worldentity %s has no mount points", (this->getName()).c_str());
339    return;
340  }
341
342  // first get all mount points from the model
343  const std::list<mountPointSkeleton> mpList = model->getMountPoints();
344  // for each skeleton create a mounting point world entity
345  std::list<mountPointSkeleton>::const_iterator it = mpList.begin();
346
347  for( ; it != mpList.end(); it++)
348  {
349    // create the mount points world entity
350    MountPoint* mp = new MountPoint( (*it).up, (*it).forward, (*it).center, (*it).name);
351    // parent it to this WE
352    mp->setParent( this);
353    // now add to the right group
354    mp->toList( (OM_LIST)(this->getOMListNumber()+1));
355    // now get the number and add the mount point to the slot
356    std::string nrStr = (*it).name.substr(3, 2);
357    // add the mount point
358    this->addMountPoint(atoi(nrStr.c_str()), mp);
359
360    // now fill the mount point
361    mp->initMountPoint( this->oiFile->getMountPointDescription());
362  }
363
364}
365
366
367/**
368 * builds the obb-tree
369 * @param depth the depth to calculate
370 */
371bool WorldEntity::buildObbTree(int depth)
372{
373  if( this->obbTree != NULL)
374  {
375    delete this->obbTree;
376    this->obbTree = NULL;
377  }
378
379  if (this->models[0] != NULL)
380    this->obbTree = new OBBTree(depth, models[0]->getModelInfo(), this);
381  else
382  {
383    PRINTF(1)("could not create obb-tree, because no model was loaded yet\n");
384    this->obbTree = NULL;
385    return false;
386  }
387
388
389  // create the axis aligned bounding box
390  if( this->aabbNode != NULL)
391  {
392    delete this->aabbNode;
393    this->aabbNode = NULL;
394  }
395
396  if( this->models[0] != NULL)
397  {
398    this->aabbNode = new AABBTreeNode();
399    this->aabbNode->spawnBVTree(this->models[0]);
400  }
401  else
402  {
403    PRINTF(1)("could not create aabb bounding box, because no model was loaded yet\n");
404    this->aabbNode = NULL;
405    return false;
406  }
407  return true;
408}
409
410
411/**
412 * adds a mount point to the end of the list
413 * @param mountPoint point to be added
414 */
415void WorldEntity::addMountPoint(MountPoint* mountPoint)
416{
417  // add the mount point at the last position
418//   this->mountPointMap[](mountPoint);
419  assert(false);
420}
421
422/**
423 * adds a mount point to a world entity
424 * @param mountPoint point to be added
425 */
426void WorldEntity::addMountPoint(int slot, MountPoint* mountPoint)
427{
428  if( this->mountPointMap.find(slot) != this->mountPointMap.end())
429  {
430    PRINTF(2)("adding a mount point to a slot, that already is occupied! ignoring - maybe some object did not get connected well (object: %s)\n", this->getClassCName());
431  }
432
433  // just connect the mount point
434  this->mountPointMap[slot] = mountPoint;
435}
436
437
438/**
439 * mounts a world entity on a specified mount point (~socket)
440 * @param entity entity to be connected
441 */
442void WorldEntity::mount(int slot, WorldEntity* entity)
443{
444  if( this->mountPointMap.find(slot) != this->mountPointMap.end())
445  {
446    PRINTF(0)("you tried to add an entity to a mount point that doesn't exist (slot %i)\n", slot);
447    return;
448  }
449
450  // mount the entity
451  this->mountPoints[slot]->mount(entity);
452}
453
454
455/**
456 * removes a mount point from a specified mount point
457 * @param mountPoint entity to be unconnected
458 */
459void WorldEntity::unmount(int slot)
460{
461  if( this->mountPoints[slot] == NULL)
462  {
463    PRINTF(0)("you tried to remove an entity from a mount point that doesn't exist (slot %i)\n", slot);
464    return;
465  }
466
467  // unmount the entity
468  this->mountPoints[slot]->unmount();
469}
470
471
472/**
473 * subscribes this world entity to a collision reaction
474 *  @param type the type of reaction to subscribe to
475 *  @param target1 a filter target (classID)
476 */
477void WorldEntity::subscribeReaction(CoRe::CREngine::ReactionType type, const ClassID& target1)
478{
479  this->_collisionFilter.subscribeReaction(type, target1);
480}
481
482
483/**
484 * subscribes this world entity to a collision reaction
485 *  @param type the type of reaction to subscribe to
486 *  @param target1 a filter target (classID)
487 */
488void WorldEntity::subscribeReaction(CoRe::CREngine::ReactionType type, const ClassID& target1, const ClassID& target2)
489{
490  this->_collisionFilter.subscribeReaction(type, target1, target2);
491}
492
493
494/**
495 * subscribes this world entity to a collision reaction
496 *  @param type the type of reaction to subscribe to
497 *  @param target1 a filter target (classID)
498 */
499void WorldEntity::subscribeReaction(CoRe::CREngine::ReactionType type, const ClassID& target1, const ClassID& target2, const ClassID& target3)
500{
501  this->_collisionFilter.subscribeReaction(type, target1, target2, target3);
502}
503
504
505/**
506 * unsubscribes a specific reaction from the worldentity
507 *  @param type the reaction to unsubscribe
508 */
509void WorldEntity::unsubscribeReaction(CoRe::CREngine::ReactionType type)
510{
511  this->_collisionFilter.unsubscribeReaction(type);
512}
513
514
515/**
516 * unsubscribes all collision reactions
517 */
518void WorldEntity::unsubscribeReactions()
519{
520  this->_collisionFilter.unsubscribeReactions();
521}
522
523
524/**
525 * @brief moves this entity to the List OM_List
526 * @param list the list to set this Entity to.
527 *
528 * this is the same as a call to State::getObjectManager()->toList(entity , list);
529 * directly, but with an easier interface.
530 *
531 * @todo inline this (peut etre)
532 */
533void WorldEntity::toList(OM_LIST list)
534{
535  State::getObjectManager()->toList(this, list);
536}
537
538void WorldEntity::toListS(const std::string& listName)
539{
540  OM_LIST id = ObjectManager::StringToOMList(listName);
541  if (id != OM_NULL)
542    this->toList(id);
543  else
544    PRINTF(2)("List %s not found\n", listName.c_str());
545}
546
547
548void WorldEntity::toReflectionList()
549{
550  State::getObjectManager()->toReflectionList( this );
551}
552
553void removeFromReflectionList()
554{
555  /// TODO
556  ///  State::getObject
557}
558
559/**
560 * sets the character attributes of a worldentity
561 * @param character attributes
562 *
563 * these attributes don't have to be set, only use them, if you need them
564*/
565//void WorldEntity::setCharacterAttributes(CharacterAttributes* charAttr)
566//{}
567
568
569/**
570 *  this function is called, when two entities collide
571 * @param entity: the world entity with whom it collides
572 *
573 * Implement behaviour like damage application or other miscellaneous collision stuff in this function
574 */
575void WorldEntity::collidesWith(WorldEntity* entity, const Vector& location)
576{
577  /**
578   * THIS IS A DEFAULT COLLISION-Effect.
579   * IF YOU WANT TO CREATE A SPECIFIC COLLISION ON EACH OBJECT
580   * USE::
581   * if (entity->isA(CL_WHAT_YOU_ARE_LOOKING_FOR)) { printf "dothings"; };
582   *
583   * You can always define a default Action.... don't be affraid just test it :)
584   */
585  //  PRINTF(3)("collision %s vs %s @ (%f,%f,%f)\n", this->getClassCName(), entity->getClassCName(), location.x, location.y, location.z);
586}
587
588
589/**
590 *  this function is called, when two entities collide
591 * @param entity: the world entity with whom it collides
592 *
593 * Implement behaviour like damage application or other miscellaneous collision stuff in this function
594 */
595void WorldEntity::collidesWithGround(const Vector& location)
596{
597  PRINTF(0)("BSP_GROUND: %s collides \n", this->getClassCName() );
598}
599
600void WorldEntity::collidesWithGround(const Vector& feet, const Vector& ray_1, const Vector& ray_2)
601{
602
603  // PRINTF(0)("BSP_GROUND: Player collides \n", this->getClassCName() );
604
605  Vector v = this->getAbsDirX();
606  v.x *= 10.1;
607  v.y *= 10.1;
608  v.z *= 10.1;
609  Vector u = Vector(0.0,-20.0,0.0);
610
611
612  if(!(this->getAbsCoor().x == ray_2.x && this->getAbsCoor().y == ray_2.y && this->getAbsCoor().z == ray_2.z) )
613  {
614
615    this->setAbsCoor(ray_2 - v);
616
617  }
618  else
619  {
620    if(ray_1.x == this->getAbsCoor().x + v.x && ray_1.y == this->getAbsCoor().y + v.y + 0.1 && ray_1.z ==this->getAbsCoor().z + v.z)
621    {
622      this->setAbsCoor(feet -u );
623    }
624
625    this->setAbsCoor(ray_2 - v);
626
627  }
628
629
630}
631
632/**
633 *  this is called immediately after the Entity has been constructed, initialized and then Spawned into the World
634 *
635 */
636void WorldEntity::postSpawn ()
637{}
638
639
640/**
641 *  this method is called by the world if the WorldEntity leaves the game
642 */
643void WorldEntity::leaveWorld ()
644{}
645
646
647/**
648 * resets the WorldEntity to its initial values. eg. used for multiplayer games: respawning
649 */
650void WorldEntity::reset()
651{
652  this->setHealth( this->getHealthMax() );
653}
654
655/**
656 *  this method is called every frame
657 * @param time: the time in seconds that has passed since the last tick
658 *
659 * Handle all stuff that should update with time inside this method (movement, animation, etc.)
660*/
661void WorldEntity::tick(float time)
662{}
663
664
665/**
666 *  the entity is drawn onto the screen with this function
667 *
668 * This is a central function of an entity: call it to let the entity painted to the screen.
669 * Just override this function with whatever you want to be drawn.
670*/
671void WorldEntity::draw() const
672{
673  //PRINTF(0)("(%s::%s)\n", this->getClassCName(), this->getName());
674  //  assert(!unlikely(this->models.empty()));
675  {
676    glMatrixMode(GL_MODELVIEW);
677    glPushMatrix();
678
679    /* translate */
680    glTranslatef (this->getAbsCoor ().x,
681                  this->getAbsCoor ().y,
682                  this->getAbsCoor ().z);
683    Vector tmpRot = this->getAbsDir().getSpacialAxis();
684    glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
685
686
687    // This Draws the LOD's
688    float cameraDistance = State::getCamera()->distance(this);
689    if (cameraDistance > 30 && this->models.size() >= 3 && this->models[2] != NULL)
690    {
691      this->models[2]->draw();
692    }
693    else if (cameraDistance > 10 && this->models.size() >= 2 && this->models[1] != NULL)
694    {
695      this->models[1]->draw();
696    }
697    else if (this->models.size() >= 1 && this->models[0] != NULL)
698    {
699      this->models[0]->draw();
700    }
701
702    //if (this->entityTrack)
703    //this->entityTrack->drawGraph(0.02);
704
705    //     if( this->aabbNode != NULL)
706    //       this->aabbNode->drawBV(0, DRAW_BV_POLYGON, Vector(1, 0.6, 0.2), true);
707
708    glPopMatrix();
709  }
710}
711
712
713/**
714 *  the entity is drawn onto the screen with this function
715 *
716 * This is a central function of an entity: call it to let the entity painted to the screen.
717 * Just override this function with whatever you want to be drawn.
718*/
719void WorldEntity::draw(const Model* model) const
720{
721  if(bVisible)
722  {
723  glMatrixMode(GL_MODELVIEW);
724  glPushMatrix();
725
726  /* translate */
727  glTranslatef (this->getAbsCoor ().x,
728                this->getAbsCoor ().y,
729                this->getAbsCoor ().z);
730  Vector tmpRot = this->getAbsDir().getSpacialAxis();
731  glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
732
733
734  // This Draws the LOD's
735  if( model != NULL)
736    model->draw();
737
738  glPopMatrix();
739  }
740}
741
742
743/**
744 * @param health the Health to add.
745 * @returns the health left (this->healthMax - health+this->health)
746 */
747float WorldEntity::increaseHealth(float health)
748{
749  this->health += health;
750  if (this->health > this->healthMax)
751  {
752    float retHealth = this->healthMax - this->health;
753    this->health = this->healthMax;
754    this->updateHealthWidget();
755    return retHealth;
756  }
757  this->updateHealthWidget();
758  return 0.0;
759}
760
761/**
762 * @param health the Health to be removed
763 * @returns 0.0 or the rest, that was not substracted (bellow 0.0)
764 */
765float WorldEntity::decreaseHealth(float health)
766{
767  this->health -= health;
768
769  if (this->health < 0)
770  {
771    float retHealth = -this->health;
772    this->health = 0.0f;
773    this->updateHealthWidget();
774    return retHealth;
775  }
776  this->updateHealthWidget();
777  return 0.0;
778
779}
780
781/**
782 * @param maxHealth the maximal health that can be loaded onto the entity.
783 */
784void WorldEntity::setHealthMax(float healthMax)
785{
786  this->healthMax = healthMax;
787  if (this->health > this->healthMax)
788  {
789    PRINTF(3)("new maxHealth is bigger as the old health. Did you really intend to do this for (%s::%s)\n", this->getClassCName(), this->getCName());
790    this->health = this->healthMax;
791  }
792  this->updateHealthWidget();
793}
794
795/**
796 * @brief creates the HealthWidget
797 *
798 * since not all entities need an HealthWidget, it is only created on request.
799 */
800void WorldEntity::createHealthWidget()
801{
802  if (this->healthWidget == NULL)
803  {
804    this->healthWidget = new OrxGui::GLGuiEnergyWidgetVertical();
805    //this->healthWidget->setDisplayedName("Health");
806    //this->healthWidget->setSize2D(100,20);
807    //this->healthWidget->setAbsCoor2D(100,200);
808
809    this->updateHealthWidget();
810  }
811  else
812    PRINTF(3)("Allready created the HealthWidget for %s::%s\n", this->getClassCName(), this->getCName());
813}
814
815void WorldEntity::increaseHealthMax(float increaseHealth)
816{
817  this->healthMax += increaseHealth;
818  this->updateHealthWidget();
819}
820
821
822OrxGui::GLGuiWidget* WorldEntity::getHealthWidget()
823{
824  this->createHealthWidget();
825  return this->healthWidget;
826}
827
828/**
829 * @param visibility shows or hides the health-bar
830 * (creates the widget if needed)
831 */
832void WorldEntity::setHealthWidgetVisibilit(bool visibility)
833{
834  if (visibility)
835  {
836    if (this->healthWidget != NULL)
837      this->healthWidget->show();
838    else
839    {
840      this->createHealthWidget();
841      this->updateHealthWidget();
842      this->healthWidget->show();
843    }
844  }
845  else if (this->healthWidget != NULL)
846    this->healthWidget->hide();
847}
848
849
850/**
851 * hit the world entity with
852 *  @param damage damage to be dealt
853 */
854void WorldEntity::hit(float damage, WorldEntity* killer)
855{
856
857  this->decreaseHealth(damage);
858
859  PRINTF(5)("Hit me: %s::%s now only %f/%f health\n", this->getClassCName(), this->getCName(), this->getHealth(), this->getHealthMax());
860
861  if( this->getHealth() > 0)
862  {
863    // any small explosion animaitions
864  }
865  else
866  {
867    this->destroy( killer );
868  }
869}
870
871
872/**
873 * destoys the world entity
874 */
875void WorldEntity::destroy(WorldEntity* killer)
876{
877  this->toList(OM_DEAD);
878}
879
880
881/**
882 * @brief updates the HealthWidget
883 */
884void WorldEntity::updateHealthWidget()
885{
886  if (this->healthWidget != NULL)
887  {
888    this->healthWidget->setMaximum(this->healthMax);
889    this->healthWidget->setValue(this->health);
890  }
891}
892
893
894/**
895 * DEBUG-DRAW OF THE BV-Tree.
896 * @param depth What depth to draw
897 * @param drawMode the mode to draw this entity under
898 */
899void WorldEntity::drawBVTree(int depth, int drawMode) const
900{
901  glMatrixMode(GL_MODELVIEW);
902  glPushMatrix();
903  /* translate */
904  glTranslatef (this->getAbsCoor ().x,
905                this->getAbsCoor ().y,
906                this->getAbsCoor ().z);
907  /* rotate */
908  Vector tmpRot = this->getAbsDir().getSpacialAxis();
909  glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
910
911
912  if (this->obbTree)
913    this->obbTree->drawBV(depth, drawMode);
914
915
916  glPopMatrix();
917}
918
919
920
921/**
922 * draw the mounting points
923 */
924void WorldEntity::debugDrawMountPoints() const
925{
926
927  std::vector<MountPoint*>::const_iterator it = this->mountPoints.begin();
928  for( ; it < this->mountPoints.end(); it++)
929  {
930    if( (*it) != NULL)
931    {
932      (*it)->debugDraw();
933    }
934  }
935}
936
937
938/**
939 * Debug the WorldEntity
940 */
941void WorldEntity::debugEntity() const
942{
943  PRINT(0)("WorldEntity %s::%s  (DEBUG)\n", this->getClassCName(), this->getCName());
944  this->debugNode();
945  PRINT(0)("List: %s ; ModelCount %d - ", ObjectManager::OMListToString(this->objectListNumber).c_str(), this->models.size());
946  for (unsigned int i = 0; i < this->models.size(); i++)
947  {
948    if (models[i] != NULL)
949      PRINT(0)(" : %d:%s", i, this->models[i]->getCName());
950  }
951  PRINT(0)("\n");
952
953}
954
955
956/**
957 * handler for changes on registred vars
958 * @param id id's which changed
959 */
960void WorldEntity::varChangeHandler( std::list< int > & id )
961{
962  if ( std::find( id.begin(), id.end(), modelFileName_handle ) != id.end() ||
963       std::find( id.begin(), id.end(), scaling_handle ) != id.end()
964     )
965  {
966    loadModel( modelFileName, scaling );
967  }
968
969  if ( std::find( id.begin(), id.end(), list_handle ) != id.end() )
970  {
971    this->toList( (OM_LIST)list_write );
972  }
973
974  if ( std::find( id.begin(), id.end(), health_handle ) != id.end() )
975  {
976    this->setHealth( health_write );
977  }
978
979  if ( std::find( id.begin(), id.end(), healthMax_handle ) != id.end() )
980  {
981    this->setHealthMax( healthMax_write );
982  }
983
984  PNode::varChangeHandler( id );
985}
986
Note: See TracBrowser for help on using the repository browser.