Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/blink/src/world_entities/world_entity.cc @ 10621

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

drawing track is now loadable, merge from branche playability

File size: 25.0 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 "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 "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
200
201/**
202 * loads a Model onto a WorldEntity
203 * @param fileName the name of the model to load
204 * @param scaling the Scaling of the model
205 *
206 * FIXME
207 * @todo: separate the obb tree generation from the model
208 */
209void WorldEntity::loadModel(const std::string& fileName, float scaling, unsigned int modelNumber, unsigned int obbTreeDepth)
210{
211  this->modelLODName = fileName;
212  this->scaling = scaling;
213
214  std::string name = fileName;
215
216  if (  name.find( Resources::ResourceManager::getInstance()->mainGlobalPath().name() ) == 0 )
217  {
218    name.erase(Resources::ResourceManager::getInstance()->mainGlobalPath().name().size());
219  }
220
221  this->modelFileName = name;
222
223  if (!fileName.empty())
224  {
225    // search for the special character # in the LoadParam
226    if (fileName.find('#') != std::string::npos)
227    {
228      PRINTF(4)("Found # in %s... searching for LOD's\n", fileName.c_str());
229      std::string lodFile = fileName;
230      unsigned int offset = lodFile.find('#');
231      for (unsigned int i = 0; i < 3; i++)
232      {
233        lodFile[offset] = 48+(int)i;
234        if (Resources::ResourceManager::getInstance()->checkFileInMainPath( lodFile))
235          this->loadModel(lodFile, scaling, i);
236      }
237      return;
238    }
239    if (this->scaling <= 0.0)
240    {
241      PRINTF(1)("YOU GAVE ME A CRAPY SCALE resetting to 1.0\n");
242      this->scaling = 1.0;
243    }
244    /// LOADING AN OBJ FILE
245    if(fileName.find(".obj") != std::string::npos)
246    {
247      PRINTF(4)("fetching OBJ file: %s\n", fileName.c_str());
248      // creating the model and loading it
249      StaticModel* model = new StaticModel();
250      *model = ResourceOBJ(fileName, this->scaling);
251
252      // check if ther is a valid model and load other stuff
253      if (model->getVertexCount() > 0)
254      {
255        this->setModel(model, modelNumber);
256
257        if( modelNumber == 0)
258        {
259          this->buildObbTree(obbTreeDepth);
260        }
261      }
262      else
263        delete model;
264    }
265    /// LOADING AN MD2-model
266    else if(fileName.find(".md2") != std::string::npos)
267    {
268      PRINTF(4)("fetching MD2 file: %s\n", fileName.c_str());
269      Model* m = new MD2Model(fileName, this->md2TextureFileName, this->scaling);
270      //this->setModel((Model*)ResourceManager::getInstance()->load(fileName, MD2, RP_CAMPAIGN), 0);
271      this->setModel(m, 0);
272
273      if( m != NULL)
274        this->buildObbTree(obbTreeDepth);
275    }
276    /// LOADING AN MD3-MODEL.
277    else if(fileName.find(".md3") != std::string::npos)
278    {
279      PRINTF(4)("fetching MD3 file: %s\n", fileName.c_str());
280      //      Model* m = new md3::MD3Model(fileName, this->scaling);
281      //      this->setModel(m, 0);
282
283      //       if( m != NULL)
284      //         this->buildObbTree(obbTreeDepth);
285    }
286  }
287  else
288  {
289    this->setModel(NULL);
290  }
291}
292
293/**
294 * sets a specific Model for the Object.
295 * @param model The Model to set
296 * @param modelNumber the n'th model in the List to get.
297 */
298void WorldEntity::setModel(Model* model, unsigned int modelNumber)
299{
300  if (this->models.size() <= modelNumber)
301    this->models.resize(modelNumber+1, NULL);
302
303  if (this->models[modelNumber] != NULL)
304  {
305    delete this->models[modelNumber];
306  }
307
308  this->models[modelNumber] = model;
309}
310
311
312
313/**
314 * loads the object information file for this model
315 * @param fileName the name of the file
316 */
317void WorldEntity::loadMountPoints(const std::string& fileName)
318{
319  PRINTF(5)("loading the oif File: %s\n", fileName.c_str());
320
321  // now load the object information file
322  this->oiFile = new ObjectInformationFile(fileName);
323
324  // get the model to load
325  Model* model = this->getModel();
326
327  // extract the mount points
328  model->extractMountPoints();
329
330  // first get all mount points from the model
331  const std::list<mountPointSkeleton> mpList = model->getMountPoints();
332  // for each skeleton create a mounting point world entity
333  std::list<mountPointSkeleton>::const_iterator it = mpList.begin();
334
335  for( ; it != mpList.end(); it++)
336  {
337    // create the mount points world entity
338    MountPoint* mp = new MountPoint( (*it).up, (*it).forward, (*it).center, (*it).name);
339    // parent it to this WE
340    mp->setParent( this);
341    // now add to the right group
342    mp->toList( (OM_LIST)(this->getOMListNumber()+1));
343    // now get the number and add the mount point to the slot
344    std::string nrStr = (*it).name.substr(3, 2);
345    // add the mount point
346    this->addMountPoint(atoi(nrStr.c_str()), mp);
347
348    // now fill the mount point
349    mp->initMountPoint( this->oiFile->getMountPointDescription());
350  }
351
352}
353
354
355/**
356 * builds the obb-tree
357 * @param depth the depth to calculate
358 */
359bool WorldEntity::buildObbTree(int depth)
360{
361  if( this->obbTree != NULL)
362  {
363    delete this->obbTree;
364    this->obbTree = NULL;
365  }
366
367  if (this->models[0] != NULL)
368    this->obbTree = new OBBTree(depth, models[0]->getModelInfo(), this);
369  else
370  {
371    PRINTF(1)("could not create obb-tree, because no model was loaded yet\n");
372    this->obbTree = NULL;
373    return false;
374  }
375
376
377  // create the axis aligned bounding box
378  if( this->aabbNode != NULL)
379  {
380    delete this->aabbNode;
381    this->aabbNode = NULL;
382  }
383
384  if( this->models[0] != NULL)
385  {
386    this->aabbNode = new AABBTreeNode();
387    this->aabbNode->spawnBVTree(this->models[0]);
388  }
389  else
390  {
391    PRINTF(1)("could not create aabb bounding box, because no model was loaded yet\n");
392    this->aabbNode = NULL;
393    return false;
394  }
395  return true;
396}
397
398
399/**
400 * adds a mount point to the end of the list
401 * @param mountPoint point to be added
402 */
403void WorldEntity::addMountPoint(MountPoint* mountPoint)
404{
405  // add the mount point at the last position
406  this->mountPoints.push_back(mountPoint);
407}
408
409/**
410 * adds a mount point to a world entity
411 * @param mountPoint point to be added
412 */
413void WorldEntity::addMountPoint(int slot, MountPoint* mountPoint)
414{
415  if( this->mountPoints.capacity() < (unsigned int)slot)
416  {
417    // reserve 5 more slots than needed so this function is called as rare as possible
418    this->mountPoints.reserve(slot + 5);
419  }
420  else if( this->mountPoints[slot] != NULL)
421  {
422    PRINTF(4)("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());
423  }
424
425  // just connect the mount point
426  this->mountPoints[slot] = mountPoint;
427}
428
429
430/**
431 * mounts a world entity on a specified mount point (~socket)
432 * @param entity entity to be connected
433 */
434void WorldEntity::mount(int slot, WorldEntity* entity)
435{
436  if( this->mountPoints[slot] == NULL)
437  {
438    PRINTF(0)("you tried to add an entity to a mount point that doesn't exist (slot %i)\n", slot);
439    return;
440  }
441
442  // mount the entity
443  this->mountPoints[slot]->mount(entity);
444}
445
446
447/**
448 * removes a mount point from a specified mount point
449 * @param mountPoint entity to be unconnected
450 */
451void WorldEntity::unmount(int slot)
452{
453  if( this->mountPoints[slot] == NULL)
454  {
455    PRINTF(0)("you tried to remove an entity from a mount point that doesn't exist (slot %i)\n", slot);
456    return;
457  }
458
459  // unmount the entity
460  this->mountPoints[slot]->unmount();
461}
462
463
464/**
465 * subscribes this world entity to a collision reaction
466 *  @param type the type of reaction to subscribe to
467 *  @param target1 a filter target (classID)
468 */
469void WorldEntity::subscribeReaction(CoRe::CREngine::ReactionType type, const ClassID& target1)
470{
471  this->_collisionFilter.subscribeReaction(type, target1);
472}
473
474
475/**
476 * subscribes this world entity to a collision reaction
477 *  @param type the type of reaction to subscribe to
478 *  @param target1 a filter target (classID)
479 */
480void WorldEntity::subscribeReaction(CoRe::CREngine::ReactionType type, const ClassID& target1, const ClassID& target2)
481{
482  this->_collisionFilter.subscribeReaction(type, target1, target2);
483}
484
485
486/**
487 * subscribes this world entity to a collision reaction
488 *  @param type the type of reaction to subscribe to
489 *  @param target1 a filter target (classID)
490 */
491void WorldEntity::subscribeReaction(CoRe::CREngine::ReactionType type, const ClassID& target1, const ClassID& target2, const ClassID& target3)
492{
493  this->_collisionFilter.subscribeReaction(type, target1, target2, target3);
494}
495
496
497/**
498 * unsubscribes a specific reaction from the worldentity
499 *  @param type the reaction to unsubscribe
500 */
501void WorldEntity::unsubscribeReaction(CoRe::CREngine::ReactionType type)
502{
503  this->_collisionFilter.unsubscribeReaction(type);
504}
505
506
507/**
508 * unsubscribes all collision reactions
509 */
510void WorldEntity::unsubscribeReactions()
511{
512  this->_collisionFilter.unsubscribeReactions();
513}
514
515
516/**
517 * @brief moves this entity to the List OM_List
518 * @param list the list to set this Entity to.
519 *
520 * this is the same as a call to State::getObjectManager()->toList(entity , list);
521 * directly, but with an easier interface.
522 *
523 * @todo inline this (peut etre)
524 */
525void WorldEntity::toList(OM_LIST list)
526{
527  State::getObjectManager()->toList(this, list);
528}
529
530void WorldEntity::toListS(const std::string& listName)
531{
532  OM_LIST id = ObjectManager::StringToOMList(listName);
533  if (id != OM_NULL)
534    this->toList(id);
535  else
536    PRINTF(2)("List %s not found\n", listName.c_str());
537}
538
539
540void WorldEntity::toReflectionList()
541{
542  State::getObjectManager()->toReflectionList( this );
543}
544
545void removeFromReflectionList()
546{
547  /// TODO
548  ///  State::getObject
549}
550
551/**
552 * sets the character attributes of a worldentity
553 * @param character attributes
554 *
555 * these attributes don't have to be set, only use them, if you need them
556*/
557//void WorldEntity::setCharacterAttributes(CharacterAttributes* charAttr)
558//{}
559
560
561/**
562 *  this function is called, when two entities collide
563 * @param entity: the world entity with whom it collides
564 *
565 * Implement behaviour like damage application or other miscellaneous collision stuff in this function
566 */
567void WorldEntity::collidesWith(WorldEntity* entity, const Vector& location)
568{
569  /**
570   * THIS IS A DEFAULT COLLISION-Effect.
571   * IF YOU WANT TO CREATE A SPECIFIC COLLISION ON EACH OBJECT
572   * USE::
573   * if (entity->isA(CL_WHAT_YOU_ARE_LOOKING_FOR)) { printf "dothings"; };
574   *
575   * You can always define a default Action.... don't be affraid just test it :)
576   */
577  //  PRINTF(3)("collision %s vs %s @ (%f,%f,%f)\n", this->getClassCName(), entity->getClassCName(), location.x, location.y, location.z);
578}
579
580
581/**
582 *  this function is called, when two entities collide
583 * @param entity: the world entity with whom it collides
584 *
585 * Implement behaviour like damage application or other miscellaneous collision stuff in this function
586 */
587void WorldEntity::collidesWithGround(const Vector& location)
588{
589  PRINTF(0)("BSP_GROUND: %s collides \n", this->getClassCName() );
590}
591
592void WorldEntity::collidesWithGround(const Vector& feet, const Vector& ray_1, const Vector& ray_2)
593{
594
595  // PRINTF(0)("BSP_GROUND: Player collides \n", this->getClassCName() );
596
597  Vector v = this->getAbsDirX();
598  v.x *= 10.1;
599  v.y *= 10.1;
600  v.z *= 10.1;
601  Vector u = Vector(0.0,-20.0,0.0);
602
603
604  if(!(this->getAbsCoor().x == ray_2.x && this->getAbsCoor().y == ray_2.y && this->getAbsCoor().z == ray_2.z) )
605  {
606
607    this->setAbsCoor(ray_2 - v);
608
609  }
610  else
611  {
612    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)
613    {
614      this->setAbsCoor(feet -u );
615    }
616
617    this->setAbsCoor(ray_2 - v);
618
619  }
620
621
622}
623
624/**
625 *  this is called immediately after the Entity has been constructed, initialized and then Spawned into the World
626 *
627 */
628void WorldEntity::postSpawn ()
629{}
630
631
632/**
633 *  this method is called by the world if the WorldEntity leaves the game
634 */
635void WorldEntity::leaveWorld ()
636{}
637
638
639/**
640 * resets the WorldEntity to its initial values. eg. used for multiplayer games: respawning
641 */
642void WorldEntity::reset()
643{
644  this->setHealth( this->getHealthMax() );
645}
646
647/**
648 *  this method is called every frame
649 * @param time: the time in seconds that has passed since the last tick
650 *
651 * Handle all stuff that should update with time inside this method (movement, animation, etc.)
652*/
653void WorldEntity::tick(float time)
654{}
655
656
657/**
658 *  the entity is drawn onto the screen with this function
659 *
660 * This is a central function of an entity: call it to let the entity painted to the screen.
661 * Just override this function with whatever you want to be drawn.
662*/
663void WorldEntity::draw() const
664{
665  //PRINTF(0)("(%s::%s)\n", this->getClassCName(), this->getName());
666  //  assert(!unlikely(this->models.empty()));
667  {
668    glMatrixMode(GL_MODELVIEW);
669    glPushMatrix();
670
671    /* translate */
672    glTranslatef (this->getAbsCoor ().x,
673                  this->getAbsCoor ().y,
674                  this->getAbsCoor ().z);
675    Vector tmpRot = this->getAbsDir().getSpacialAxis();
676    glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
677
678
679    // This Draws the LOD's
680    float cameraDistance = State::getCamera()->distance(this);
681    if (cameraDistance > 30 && this->models.size() >= 3 && this->models[2] != NULL)
682    {
683      this->models[2]->draw();
684    }
685    else if (cameraDistance > 10 && this->models.size() >= 2 && this->models[1] != NULL)
686    {
687      this->models[1]->draw();
688    }
689    else if (this->models.size() >= 1 && this->models[0] != NULL)
690    {
691      this->models[0]->draw();
692    }
693
694    //if (this->entityTrack)
695    //this->entityTrack->drawGraph(0.02);
696
697    //     if( this->aabbNode != NULL)
698    //       this->aabbNode->drawBV(0, DRAW_BV_POLYGON, Vector(1, 0.6, 0.2), true);
699
700    glPopMatrix();
701  }
702}
703
704
705/**
706 *  the entity is drawn onto the screen with this function
707 *
708 * This is a central function of an entity: call it to let the entity painted to the screen.
709 * Just override this function with whatever you want to be drawn.
710*/
711void WorldEntity::draw(const Model* model) const
712{
713  glMatrixMode(GL_MODELVIEW);
714  glPushMatrix();
715
716  /* translate */
717  glTranslatef (this->getAbsCoor ().x,
718                this->getAbsCoor ().y,
719                this->getAbsCoor ().z);
720  Vector tmpRot = this->getAbsDir().getSpacialAxis();
721  glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
722
723
724  // This Draws the LOD's
725  if( model != NULL)
726    model->draw();
727
728  glPopMatrix();
729}
730
731
732/**
733 * @param health the Health to add.
734 * @returns the health left (this->healthMax - health+this->health)
735 */
736float WorldEntity::increaseHealth(float health)
737{
738  this->health += health;
739  if (this->health > this->healthMax)
740  {
741    float retHealth = this->healthMax - this->health;
742    this->health = this->healthMax;
743    this->updateHealthWidget();
744    return retHealth;
745  }
746  this->updateHealthWidget();
747  return 0.0;
748}
749
750/**
751 * @param health the Health to be removed
752 * @returns 0.0 or the rest, that was not substracted (bellow 0.0)
753 */
754float WorldEntity::decreaseHealth(float health)
755{
756  this->health -= health;
757
758  if (this->health < 0)
759  {
760    float retHealth = -this->health;
761    this->health = 0.0f;
762    this->updateHealthWidget();
763    return retHealth;
764  }
765  this->updateHealthWidget();
766  return 0.0;
767
768}
769
770/**
771 * @param maxHealth the maximal health that can be loaded onto the entity.
772 */
773void WorldEntity::setHealthMax(float healthMax)
774{
775  this->healthMax = healthMax;
776  if (this->health > this->healthMax)
777  {
778    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());
779    this->health = this->healthMax;
780  }
781  this->updateHealthWidget();
782}
783
784/**
785 * @brief creates the HealthWidget
786 *
787 * since not all entities need an HealthWidget, it is only created on request.
788 */
789void WorldEntity::createHealthWidget()
790{
791  if (this->healthWidget == NULL)
792  {
793    this->healthWidget = new OrxGui::GLGuiEnergyWidgetVertical();
794    //this->healthWidget->setDisplayedName("Health");
795    //this->healthWidget->setSize2D(100,20);
796    //this->healthWidget->setAbsCoor2D(100,200);
797
798    this->updateHealthWidget();
799  }
800  else
801    PRINTF(3)("Allready created the HealthWidget for %s::%s\n", this->getClassCName(), this->getCName());
802}
803
804void WorldEntity::increaseHealthMax(float increaseHealth)
805{
806  this->healthMax += increaseHealth;
807  this->updateHealthWidget();
808}
809
810
811OrxGui::GLGuiWidget* WorldEntity::getHealthWidget()
812{
813  this->createHealthWidget();
814  return this->healthWidget;
815}
816
817/**
818 * @param visibility shows or hides the health-bar
819 * (creates the widget if needed)
820 */
821void WorldEntity::setHealthWidgetVisibilit(bool visibility)
822{
823  if (visibility)
824  {
825    if (this->healthWidget != NULL)
826      this->healthWidget->show();
827    else
828    {
829      this->createHealthWidget();
830      this->updateHealthWidget();
831      this->healthWidget->show();
832    }
833  }
834  else if (this->healthWidget != NULL)
835    this->healthWidget->hide();
836}
837
838
839/**
840 * hit the world entity with
841 *  @param damage damage to be dealt
842 */
843void WorldEntity::hit(float damage, WorldEntity* killer)
844{
845
846  this->decreaseHealth(damage);
847
848  PRINTF(5)("Hit me: %s::%s now only %f/%f health\n", this->getClassCName(), this->getCName(), this->getHealth(), this->getHealthMax());
849
850  if( this->getHealth() > 0)
851  {
852    // any small explosion animaitions
853  }
854  else
855  {
856    this->destroy( killer );
857  }
858}
859
860
861/**
862 * destoys the world entity
863 */
864void WorldEntity::destroy(WorldEntity* killer)
865{
866  this->toList(OM_DEAD);
867}
868
869
870/**
871 * @brief updates the HealthWidget
872 */
873void WorldEntity::updateHealthWidget()
874{
875  if (this->healthWidget != NULL)
876  {
877    this->healthWidget->setMaximum(this->healthMax);
878    this->healthWidget->setValue(this->health);
879  }
880}
881
882
883/**
884 * DEBUG-DRAW OF THE BV-Tree.
885 * @param depth What depth to draw
886 * @param drawMode the mode to draw this entity under
887 */
888void WorldEntity::drawBVTree(int depth, int drawMode) const
889{
890  glMatrixMode(GL_MODELVIEW);
891  glPushMatrix();
892  /* translate */
893  glTranslatef (this->getAbsCoor ().x,
894                this->getAbsCoor ().y,
895                this->getAbsCoor ().z);
896  /* rotate */
897  Vector tmpRot = this->getAbsDir().getSpacialAxis();
898  glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
899
900
901  if (this->obbTree)
902    this->obbTree->drawBV(depth, drawMode);
903
904
905  glPopMatrix();
906}
907
908
909
910/**
911 * draw the mounting points
912 */
913void WorldEntity::debugDrawMountPoints() const
914{
915
916  std::vector<MountPoint*>::const_iterator it = this->mountPoints.begin();
917  for( ; it < this->mountPoints.end(); it++)
918  {
919    if( (*it) != NULL)
920    {
921      (*it)->debugDraw();
922    }
923  }
924}
925
926
927/**
928 * Debug the WorldEntity
929 */
930void WorldEntity::debugEntity() const
931{
932  PRINT(0)("WorldEntity %s::%s  (DEBUG)\n", this->getClassCName(), this->getCName());
933  this->debugNode();
934  PRINT(0)("List: %s ; ModelCount %d - ", ObjectManager::OMListToString(this->objectListNumber).c_str(), this->models.size());
935  for (unsigned int i = 0; i < this->models.size(); i++)
936  {
937    if (models[i] != NULL)
938      PRINT(0)(" : %d:%s", i, this->models[i]->getCName());
939  }
940  PRINT(0)("\n");
941
942}
943
944
945/**
946 * handler for changes on registred vars
947 * @param id id's which changed
948 */
949void WorldEntity::varChangeHandler( std::list< int > & id )
950{
951  if ( std::find( id.begin(), id.end(), modelFileName_handle ) != id.end() ||
952       std::find( id.begin(), id.end(), scaling_handle ) != id.end()
953     )
954  {
955    loadModel( modelFileName, scaling );
956  }
957
958  if ( std::find( id.begin(), id.end(), list_handle ) != id.end() )
959  {
960    this->toList( (OM_LIST)list_write );
961  }
962
963  if ( std::find( id.begin(), id.end(), health_handle ) != id.end() )
964  {
965    this->setHealth( health_write );
966  }
967
968  if ( std::find( id.begin(), id.end(), healthMax_handle ) != id.end() )
969  {
970    this->setHealthMax( healthMax_write );
971  }
972
973  PNode::varChangeHandler( id );
974}
975
Note: See TracBrowser for help on using the repository browser.