Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/presentation/src/world_entities/world_entity.cc @ 10708

Last change on this file since 10708 was 10708, checked in by rennerc, 17 years ago

improved damage handling for adm

File size: 30.6 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->electronicWidget = NULL;
78  this->shieldWidget = NULL;
79  this->healthMax = 1.0f;
80  this->health = 1.0f;
81  this->damage = 0.0f; // no damage dealt by a default entity
82  this->scaling = 1.0f;
83  this->oiFile = NULL;
84  // add 10 members to this array
85  this->mountPoints.reserve(10);
86
87  /* OSOLETE */
88  this->bVisible = true;
89  this->bCollide = true;
90
91  this->objectListNumber = OM_INIT;
92  this->lastObjectListNumber = OM_INIT;
93
94  this->_bOnGround = false;
95
96  // Track of this entity
97  this->entityTrack = NULL;
98  this->bDrawTrack = false;
99 
100  this->forwardDamageToParent = false;
101
102  // registering default reactions:
103  this->subscribeReaction(CoRe::CREngine::CR_OBJECT_DAMAGE, Projectile::staticClassID());
104
105  this->toList(OM_NULL);
106
107  this->registerVar( new SynchronizeableString( &this->md2TextureFileName, &this->md2TextureFileName, "md2TextureFileName", PERMISSION_MASTER_SERVER ) );
108  this->modelFileName_handle = registerVarId( new SynchronizeableString( &modelFileName, &modelFileName, "modelFileName", PERMISSION_MASTER_SERVER ) );
109  this->scaling_handle = registerVarId( new SynchronizeableFloat( &scaling, &scaling, "scaling", PERMISSION_MASTER_SERVER ) );
110  this->list_handle = registerVarId( new SynchronizeableInt( (int*)&objectListNumber, &list_write, "list", PERMISSION_MASTER_SERVER ) );
111
112  this->health_handle = registerVarId( new SynchronizeableFloat( &this->health, &this->health_write, "health", PERMISSION_MASTER_SERVER ) );
113  this->healthMax_handle = registerVarId( new SynchronizeableFloat( &this->healthMax, &this->healthMax_write, "maxHealth", PERMISSION_MASTER_SERVER ) );
114}
115
116/**
117 *  standard destructor
118*/
119WorldEntity::~WorldEntity ()
120{
121  State::getObjectManager()->toList(this, OM_INIT);
122
123  // Delete the model (unregister it with the ResourceManager)
124  for (unsigned int i = 0; i < this->models.size(); i++)
125    this->setModel(NULL, i);
126
127  // remove the object information file
128  if( this->oiFile)
129    delete this->oiFile;
130  // and clear all monut points
131  this->mountPoints.clear();
132
133  // Delete the obbTree
134  if( this->obbTree)
135    delete this->obbTree;
136
137  if (this->healthWidget)
138    delete this->healthWidget;
139
140  if(this->shieldWidget)
141    delete this->shieldWidget;
142
143  if( this->electronicWidget)
144    delete this->electronicWidget;
145
146  this->unsubscribeReactions();
147}
148
149/**
150 * loads the WorldEntity Specific Parameters.
151 * @param root: the XML-Element to load the Data From
152 */
153void WorldEntity::loadParams(const TiXmlElement* root)
154{
155  // Do the PNode loading stuff
156  PNode::loadParams(root);
157
158  LoadParam(root, "md2texture", this, WorldEntity, loadMD2Texture)
159  .describe("the fileName of the texture, that should be loaded onto this world-entity. (must be relative to the data-dir)")
160  .defaultValues("");
161
162  // Model Loading
163  LoadParam(root, "model", this, WorldEntity, loadModel)
164  .describe("the fileName of the model, that should be loaded onto this world-entity. (must be relative to the data-dir)")
165  .defaultValues("", 1.0f, 0);
166
167  LoadParam(root, "mountpoints", this, WorldEntity, loadMountPoints)
168  .describe("the fileName of the object information file (optional)");
169
170  // Entity Attributes
171  LoadParam(root, "maxHealth", this, WorldEntity, setHealthMax)
172  .describe("The Maximum health that can be loaded onto this entity")
173  .defaultValues(1.0f);
174
175  LoadParam(root, "health", this, WorldEntity, setHealth)
176  .describe("The Health the WorldEntity has at this moment")
177  .defaultValues(1.0f);
178
179  LoadParam(root, "list", this, WorldEntity, toListS);
180
181  LoadParam(root, "drawTrack", this, WorldEntity, drawDebugTrack)
182      .describe("draws the track for debugging purposes");
183 
184  LoadParam(root, "forwardDamageToParent", this, WorldEntity, setForwardDamageToParent);
185
186  // Track
187  LoadParamXML(root, "Track", this, WorldEntity, addTrack)
188  .describe("creates and adds a track to this WorldEntity");
189}
190
191
192/**
193 * this functions adds a track to this workd entity. This can be usefull, if you like this WE to follow a some waypoints.
194 * here the track is created and further initializing left for the Track itself
195 */
196void WorldEntity::addTrack(const TiXmlElement* root)
197{
198  // The problem we have is most likely here. The track should be constructed WITH the XML-Code
199  this->entityTrack = new Track(root);
200  this->setParent(this->entityTrack->getTrackNode());
201  this->entityTrack->getTrackNode()->setParentMode(PNODE_ALL);
202  /*LOAD_PARAM_START_CYCLE(root, element);
203  {
204    PRINTF(4)("element is: %s\n", element->Value());
205    Factory::fabricate(element);
206  }
207  LOAD_PARAM_END_CYCLE(element);*/
208
209
210}
211
212void WorldEntity::pauseTrack(bool stop)
213{
214     if(this->entityTrack)
215       this->entityTrack->pauseTrack(stop);
216}
217
218
219/**
220 * loads a Model onto a WorldEntity
221 * @param fileName the name of the model to load
222 * @param scaling the Scaling of the model
223 *
224 * FIXME
225 * @todo: separate the obb tree generation from the model
226 */
227void WorldEntity::loadModel(const std::string& fileName, float scaling, unsigned int modelNumber, unsigned int obbTreeDepth)
228{
229  this->modelLODName = fileName;
230  this->scaling = scaling;
231
232  std::string name = fileName;
233
234  if (  name.find( Resources::ResourceManager::getInstance()->mainGlobalPath().name() ) == 0 )
235  {
236    name.erase(Resources::ResourceManager::getInstance()->mainGlobalPath().name().size());
237  }
238
239  this->modelFileName = name;
240
241  if (!fileName.empty())
242  {
243    // search for the special character # in the LoadParam
244    if (fileName.find('#') != std::string::npos)
245    {
246      PRINTF(4)("Found # in %s... searching for LOD's\n", fileName.c_str());
247      std::string lodFile = fileName;
248      unsigned int offset = lodFile.find('#');
249      for (unsigned int i = 0; i < 3; i++)
250      {
251        lodFile[offset] = 48+(int)i;
252        if (Resources::ResourceManager::getInstance()->checkFileInMainPath( lodFile))
253          this->loadModel(lodFile, scaling, i);
254      }
255      return;
256    }
257    if (this->scaling <= 0.0)
258    {
259      PRINTF(1)("YOU GAVE ME A CRAPY SCALE resetting to 1.0\n");
260      this->scaling = 1.0;
261    }
262    /// LOADING AN OBJ FILE
263    if(fileName.find(".obj") != std::string::npos)
264    {
265      PRINTF(4)("fetching OBJ file: %s\n", fileName.c_str());
266      // creating the model and loading it
267      StaticModel* model = new StaticModel();
268      *model = ResourceOBJ(fileName, this->scaling);
269
270      // check if ther is a valid model and load other stuff
271      if (model->getVertexCount() > 0)
272      {
273        this->setModel(model, modelNumber);
274
275        if( modelNumber == 0)
276        {
277          this->buildObbTree(obbTreeDepth);
278        }
279      }
280      else
281        delete model;
282    }
283    /// LOADING AN MD2-model
284    else if(fileName.find(".md2") != std::string::npos)
285    {
286      PRINTF(4)("fetching MD2 file: %s\n", fileName.c_str());
287      Model* m = new MD2Model(fileName, this->md2TextureFileName, this->scaling);
288      //this->setModel((Model*)ResourceManager::getInstance()->load(fileName, MD2, RP_CAMPAIGN), 0);
289      this->setModel(m, 0);
290
291      if( m != NULL)
292        this->buildObbTree(obbTreeDepth);
293    }
294    /// LOADING AN MD3-MODEL.
295    else if(fileName.find(".md3") != std::string::npos)
296    {
297      PRINTF(4)("fetching MD3 file: %s\n", fileName.c_str());
298      //      Model* m = new md3::MD3Model(fileName, this->scaling);
299      //      this->setModel(m, 0);
300
301      //       if( m != NULL)
302      //         this->buildObbTree(obbTreeDepth);
303    }
304  }
305  else
306  {
307    this->setModel(NULL);
308  }
309}
310
311/**
312 * sets a specific Model for the Object.
313 * @param model The Model to set
314 * @param modelNumber the n'th model in the List to get.
315 */
316void WorldEntity::setModel(Model* model, unsigned int modelNumber)
317{
318  if (this->models.size() <= modelNumber)
319    this->models.resize(modelNumber+1, NULL);
320
321  if (this->models[modelNumber] != NULL)
322  {
323    delete this->models[modelNumber];
324  }
325
326  this->models[modelNumber] = model;
327}
328
329
330
331/**
332 * loads the object information file for this model
333 * @param fileName the name of the file
334 */
335void WorldEntity::loadMountPoints(const std::string& fileName)
336{
337  PRINTF(5)("loading the oif File: %s\n", fileName.c_str());
338
339  // now load the object information file
340  this->oiFile = new ObjectInformationFile(fileName);
341
342  // get the model to load
343  Model* model = this->getModel();
344
345  // extract the mount points
346  if(model != NULL)
347    model->extractMountPoints();
348  else
349  {
350    PRINTF(0)("Worldentity %s has no mount points", (this->getName()).c_str());
351    return;
352  }
353
354  // first get all mount points from the model
355  const std::list<mountPointSkeleton> mpList = model->getMountPoints();
356  // for each skeleton create a mounting point world entity
357  std::list<mountPointSkeleton>::const_iterator it = mpList.begin();
358
359  for( ; it != mpList.end(); it++)
360  {
361    // create the mount points world entity
362    MountPoint* mp = new MountPoint( (*it).up, (*it).forward, (*it).center, (*it).name);
363    // parent it to this WE
364    mp->setParent( this);
365    // now add to the right group
366    mp->toList( (OM_LIST)(this->getOMListNumber()+1));
367    // now get the number and add the mount point to the slot
368    std::string nrStr = (*it).name.substr(3, 2);
369    // add the mount point
370    this->addMountPoint(atoi(nrStr.c_str()), mp);
371
372    // now fill the mount point
373    mp->initMountPoint( this->oiFile->getMountPointDescription());
374  }
375
376}
377
378
379/**
380 * builds the obb-tree
381 * @param depth the depth to calculate
382 */
383bool WorldEntity::buildObbTree(int depth)
384{
385  if( this->obbTree != NULL)
386  {
387    delete this->obbTree;
388    this->obbTree = NULL;
389  }
390
391  if (this->models[0] != NULL)
392    this->obbTree = new OBBTree(depth, models[0]->getModelInfo(), this);
393  else
394  {
395    PRINTF(1)("could not create obb-tree, because no model was loaded yet\n");
396    this->obbTree = NULL;
397    return false;
398  }
399
400
401  // create the axis aligned bounding box
402  if( this->aabbNode != NULL)
403  {
404    delete this->aabbNode;
405    this->aabbNode = NULL;
406  }
407
408  if( this->models[0] != NULL)
409  {
410    this->aabbNode = new AABBTreeNode();
411    this->aabbNode->spawnBVTree(this->models[0]);
412  }
413  else
414  {
415    PRINTF(1)("could not create aabb bounding box, because no model was loaded yet\n");
416    this->aabbNode = NULL;
417    return false;
418  }
419  return true;
420}
421
422
423/**
424 * adds a mount point to the end of the list
425 * @param mountPoint point to be added
426 */
427void WorldEntity::addMountPoint(MountPoint* mountPoint)
428{
429  // add the mount point at the last position
430//   this->mountPointMap[](mountPoint);
431  assert(false);
432}
433
434/**
435 * adds a mount point to a world entity
436 * @param mountPoint point to be added
437 */
438void WorldEntity::addMountPoint(int slot, MountPoint* mountPoint)
439{
440  if( this->mountPointMap.find(slot) != this->mountPointMap.end())
441  {
442    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());
443  }
444
445  // just connect the mount point
446  this->mountPointMap[slot] = mountPoint;
447}
448
449
450/**
451 * mounts a world entity on a specified mount point (~socket)
452 * @param entity entity to be connected
453 */
454void WorldEntity::mount(int slot, WorldEntity* entity)
455{
456  if( this->mountPointMap.find(slot) != this->mountPointMap.end())
457  {
458    PRINTF(0)("you tried to add an entity to a mount point that doesn't exist (slot %i)\n", slot);
459    return;
460  }
461
462  // mount the entity
463  this->mountPoints[slot]->mount(entity);
464}
465
466
467/**
468 * removes a mount point from a specified mount point
469 * @param mountPoint entity to be unconnected
470 */
471void WorldEntity::unmount(int slot)
472{
473  if( this->mountPoints[slot] == NULL)
474  {
475    PRINTF(0)("you tried to remove an entity from a mount point that doesn't exist (slot %i)\n", slot);
476    return;
477  }
478
479  // unmount the entity
480  this->mountPoints[slot]->unmount();
481}
482
483
484/**
485 * subscribes this world entity to a collision reaction
486 *  @param type the type of reaction to subscribe to
487 *  @param target1 a filter target (classID)
488 */
489void WorldEntity::subscribeReaction(CoRe::CREngine::ReactionType type, const ClassID& target1)
490{
491  this->_collisionFilter.subscribeReaction(type, target1);
492}
493
494
495/**
496 * subscribes this world entity to a collision reaction
497 *  @param type the type of reaction to subscribe to
498 *  @param target1 a filter target (classID)
499 */
500void WorldEntity::subscribeReaction(CoRe::CREngine::ReactionType type, const ClassID& target1, const ClassID& target2)
501{
502  this->_collisionFilter.subscribeReaction(type, target1, target2);
503}
504
505
506/**
507 * subscribes this world entity to a collision reaction
508 *  @param type the type of reaction to subscribe to
509 *  @param target1 a filter target (classID)
510 */
511void WorldEntity::subscribeReaction(CoRe::CREngine::ReactionType type, const ClassID& target1, const ClassID& target2, const ClassID& target3)
512{
513  this->_collisionFilter.subscribeReaction(type, target1, target2, target3);
514}
515
516
517/**
518 * unsubscribes a specific reaction from the worldentity
519 *  @param type the reaction to unsubscribe
520 */
521void WorldEntity::unsubscribeReaction(CoRe::CREngine::ReactionType type)
522{
523  this->_collisionFilter.unsubscribeReaction(type);
524}
525
526
527/**
528 * unsubscribes all collision reactions
529 */
530void WorldEntity::unsubscribeReactions()
531{
532  this->_collisionFilter.unsubscribeReactions();
533}
534
535
536/**
537 * @brief moves this entity to the List OM_List
538 * @param list the list to set this Entity to.
539 *
540 * this is the same as a call to State::getObjectManager()->toList(entity , list);
541 * directly, but with an easier interface.
542 *
543 * @todo inline this (peut etre)
544 */
545void WorldEntity::toList(OM_LIST list)
546{
547  State::getObjectManager()->toList(this, list);
548}
549
550void WorldEntity::toListS(const std::string& listName)
551{
552  OM_LIST id = ObjectManager::StringToOMList(listName);
553  if (id != OM_NULL)
554    this->toList(id);
555  else
556    PRINTF(2)("List %s not found\n", listName.c_str());
557}
558
559
560void WorldEntity::toReflectionList()
561{
562  State::getObjectManager()->toReflectionList( this );
563}
564
565void removeFromReflectionList()
566{
567  /// TODO
568  ///  State::getObject
569}
570
571/**
572 * sets the character attributes of a worldentity
573 * @param character attributes
574 *
575 * these attributes don't have to be set, only use them, if you need them
576*/
577//void WorldEntity::setCharacterAttributes(CharacterAttributes* charAttr)
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::collidesWith(WorldEntity* entity, const Vector& location)
588{
589  /**
590   * THIS IS A DEFAULT COLLISION-Effect.
591   * IF YOU WANT TO CREATE A SPECIFIC COLLISION ON EACH OBJECT
592   * USE::
593   * if (entity->isA(CL_WHAT_YOU_ARE_LOOKING_FOR)) { printf "dothings"; };
594   *
595   * You can always define a default Action.... don't be affraid just test it :)
596   */
597  //  PRINTF(3)("collision %s vs %s @ (%f,%f,%f)\n", this->getClassCName(), entity->getClassCName(), location.x, location.y, location.z);
598}
599
600
601/**
602 *  this function is called, when two entities collide
603 * @param entity: the world entity with whom it collides
604 *
605 * Implement behaviour like damage application or other miscellaneous collision stuff in this function
606 */
607void WorldEntity::collidesWithGround(const Vector& location)
608{
609  PRINTF(0)("BSP_GROUND: %s collides \n", this->getClassCName() );
610}
611
612void WorldEntity::collidesWithGround(const Vector& feet, const Vector& ray_1, const Vector& ray_2)
613{
614
615  // PRINTF(0)("BSP_GROUND: Player collides \n", this->getClassCName() );
616
617  Vector v = this->getAbsDirX();
618  v.x *= 10.1;
619  v.y *= 10.1;
620  v.z *= 10.1;
621  Vector u = Vector(0.0,-20.0,0.0);
622
623
624  if(!(this->getAbsCoor().x == ray_2.x && this->getAbsCoor().y == ray_2.y && this->getAbsCoor().z == ray_2.z) )
625  {
626
627    this->setAbsCoor(ray_2 - v);
628
629  }
630  else
631  {
632    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)
633    {
634      this->setAbsCoor(feet -u );
635    }
636
637    this->setAbsCoor(ray_2 - v);
638
639  }
640
641
642}
643
644/**
645 *  this is called immediately after the Entity has been constructed, initialized and then Spawned into the World
646 *
647 */
648void WorldEntity::postSpawn ()
649{}
650
651
652/**
653 *  this method is called by the world if the WorldEntity leaves the game
654 */
655void WorldEntity::leaveWorld ()
656{}
657
658
659/**
660 * resets the WorldEntity to its initial values. eg. used for multiplayer games: respawning
661 */
662void WorldEntity::reset()
663{
664  this->setHealth( this->getHealthMax() );
665}
666
667/**
668 *  this method is called every frame
669 * @param time: the time in seconds that has passed since the last tick
670 *
671 * Handle all stuff that should update with time inside this method (movement, animation, etc.)
672*/
673void WorldEntity::tick(float time)
674{}
675
676
677/**
678 *  the entity is drawn onto the screen with this function
679 *
680 * This is a central function of an entity: call it to let the entity painted to the screen.
681 * Just override this function with whatever you want to be drawn.
682*/
683void WorldEntity::draw() const
684{
685  //PRINTF(0)("(%s::%s)\n", this->getClassCName(), this->getName());
686  //  assert(!unlikely(this->models.empty()));
687  {
688    glMatrixMode(GL_MODELVIEW);
689    glPushMatrix();
690
691    /* translate */
692    glTranslatef (this->getAbsCoor ().x,
693                  this->getAbsCoor ().y,
694                  this->getAbsCoor ().z);
695    Vector tmpRot = this->getAbsDir().getSpacialAxis();
696    glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
697
698
699    // This Draws the LOD's
700    float cameraDistance = State::getCamera()->distance(this);
701    if (cameraDistance > 30 && this->models.size() >= 3 && this->models[2] != NULL)
702    {
703      this->models[2]->draw();
704    }
705    else if (cameraDistance > 10 && this->models.size() >= 2 && this->models[1] != NULL)
706    {
707      this->models[1]->draw();
708    }
709    else if (this->models.size() >= 1 && this->models[0] != NULL)
710    {
711      this->models[0]->draw();
712    }
713
714    //if (this->entityTrack)
715    //this->entityTrack->drawGraph(0.02);
716
717    //     if( this->aabbNode != NULL)
718    //       this->aabbNode->drawBV(0, DRAW_BV_POLYGON, Vector(1, 0.6, 0.2), true);
719
720    glPopMatrix();
721  }
722}
723
724
725/**
726 *  the entity is drawn onto the screen with this function
727 *
728 * This is a central function of an entity: call it to let the entity painted to the screen.
729 * Just override this function with whatever you want to be drawn.
730*/
731void WorldEntity::draw(const Model* model) const
732{
733  if(bVisible)
734  {
735  glMatrixMode(GL_MODELVIEW);
736  glPushMatrix();
737
738  /* translate */
739  glTranslatef (this->getAbsCoor ().x,
740                this->getAbsCoor ().y,
741                this->getAbsCoor ().z);
742  Vector tmpRot = this->getAbsDir().getSpacialAxis();
743  glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
744
745
746  // This Draws the LOD's
747  if( model != NULL)
748    model->draw();
749
750  glPopMatrix();
751  }
752}
753
754
755/**
756 * @param health the Health to add.
757 * @returns the health left (this->healthMax - health+this->health)
758 */
759float WorldEntity::increaseHealth(float health)
760{
761  this->health += health;
762  if (this->health > this->healthMax)
763  {
764    float retHealth = this->healthMax - this->health;
765    this->health = this->healthMax;
766    this->updateHealthWidget();
767    return retHealth;
768  }
769  this->updateHealthWidget();
770  return 0.0;
771}
772
773/**
774 * @param health the Health to be removed
775 * @returns 0.0 or the rest, that was not substracted (bellow 0.0)
776 */
777float WorldEntity::decreaseHealth(float health)
778{
779  this->health -= health;
780
781  if (this->health < 0)
782  {
783    float retHealth = -this->health;
784    this->health = 0.0f;
785    this->updateHealthWidget();
786    return retHealth;
787  }
788  this->updateHealthWidget();
789  return 0.0;
790}
791
792
793/**
794 * @param maxHealth the maximal health that can be loaded onto the entity.
795 */
796void WorldEntity::setHealthMax(float healthMax)
797{
798  this->healthMax = healthMax;
799  if (this->health > this->healthMax)
800  {
801    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());
802    this->health = this->healthMax;
803  }
804  this->updateHealthWidget();
805}
806
807
808
809/**
810 * @param shiled the Shieldstength to add.
811 * @returns the shield left (this->shieldMax - shiled + this->shield)
812 */
813float WorldEntity::increaseShield(float shiled)
814{
815  this->shield += shield;
816  if (this->shield > this->shieldTH * this->shieldMax) { this->bShieldActive = true; }
817  if (this->shield > this->shieldMax)
818  {
819    float retShield = this->shieldMax - this->shield;
820    this->shield = this->shieldMax;
821//     this->updateShieldWidget();
822    return retShield;
823  }
824//   this->updateShieldWidget();
825  return 0.0;
826}
827
828/**
829 * @param shield the Shieldstrength to be removed
830 * @returns 0.0 or the rest, if the shield drops belew 0.0
831 */
832float WorldEntity::decreaseShield(float shield)
833{
834  this->shield -= shield;
835
836  if (this->shield <= 0)
837  {
838    float retShield = -this->shield;
839//     this->updateShieldWidget();
840    this->bShieldActive = false;
841    return retShield;
842  }
843//   this->updateShieldWidget();
844  return 0.0;
845}
846
847
848
849/**
850 * @brief creates the HealthWidget
851 *
852 * since not all entities need an HealthWidget, it is only created on request.
853 */
854void WorldEntity::createHealthWidget()
855{
856  if (this->healthWidget == NULL)
857  {
858    this->healthWidget = new OrxGui::GLGuiEnergyWidgetVertical();
859    //this->healthWidget->setDisplayedName("Health");
860    //this->healthWidget->setSize2D(100,20);
861    //this->healthWidget->setAbsCoor2D(100,200);
862
863    this->updateHealthWidget();
864  }
865  else
866    PRINTF(3)("Allready created the HealthWidget for %s::%s\n", this->getClassCName(), this->getCName());
867}
868
869
870/**
871 * @brief creates the ImplantWidget
872 *
873 * since not all entities need an ImpantWidget, it is only created on request.
874 */
875void WorldEntity::createImplantWidget()
876{
877  if (this->implantWidget == NULL)
878  {
879    this->implantWidget = new OrxGui::GLGuiEnergyWidgetVertical();
880    //this->impantWidget->setDisplayedName("Implant");
881    //this->impantWidget->setSize2D(100,20);
882    //this->impantWidget->setAbsCoor2D(100,200);
883
884    //this->updateImplantWidget();
885  }
886  else
887    PRINTF(3)("Allready created the ImlpantWidget for %s::%s\n", this->getClassCName(), this->getCName());
888}
889
890
891
892void WorldEntity::createShieldWidget()
893{
894  if (this->shieldWidget == NULL)
895  {
896    this->shieldWidget = new OrxGui::GLGuiEnergyWidgetVertical();
897    this->updateShieldWidget();
898  }
899  else
900    PRINTF(3)("Allready created the ShieldWidget for %s::%s\n", this->getClassCName(), this->getCName());
901}
902
903void WorldEntity::createElectronicWidget()
904{
905  if (this->electronicWidget == NULL)
906  {
907    this->electronicWidget = new OrxGui::GLGuiEnergyWidgetVertical();
908    this->updateElectronicWidget();
909  }
910  else
911    PRINTF(3)("Allready created the ElectronicWidget for %s::%s\n", this->getClassCName(), this->getCName());
912}
913
914
915
916void WorldEntity::increaseHealthMax(float increaseHealth)
917{
918  this->healthMax += increaseHealth;
919  this->updateHealthWidget();
920}
921
922
923OrxGui::GLGuiWidget* WorldEntity::getHealthWidget()
924{
925  if ( this->healthWidget == NULL)
926    this->createHealthWidget();
927  return this->healthWidget;
928}
929
930
931
932OrxGui::GLGuiWidget* WorldEntity::getImplantWidget()
933{
934  this->createImplantWidget();
935  return this->implantWidget;
936}
937
938
939
940OrxGui::GLGuiWidget* WorldEntity::getShieldWidget()
941{
942  if ( this->shieldWidget == NULL)
943    this->createShieldWidget();
944  return this->shieldWidget;
945}
946
947
948OrxGui::GLGuiWidget* WorldEntity::getElectronicWidget()
949{
950  if ( this->electronicWidget == NULL)
951    this->createElectronicWidget();
952  return this->electronicWidget;
953}
954
955
956
957
958/**
959 * @param visibility shows or hides the health-bar
960 * (creates the widget if needed)
961 */
962void WorldEntity::setHealthWidgetVisibility(bool visibility)
963{
964  if (visibility)
965  {
966    if (this->healthWidget != NULL)
967      this->healthWidget->show();
968    else
969    {
970      this->createHealthWidget();
971      this->updateHealthWidget();
972      this->healthWidget->show();
973    }
974  }
975  else if (this->healthWidget != NULL)
976    this->healthWidget->hide();
977}
978
979
980/**
981 * hit the world entity with
982 *  @param damage damage to be dealt
983 */
984void WorldEntity::hit(float damage, WorldEntity* killer)
985{
986  PRINTF(0)("TESTS: %i %i %i\n", (forwardDamageToParent), (this->getParent() != NullParent::getNullParent()), (this->getParent()->isA( WorldEntity::staticClassID() )));
987  if ( forwardDamageToParent && this->getParent() != NullParent::getNullParent() && this->getParent()->isA( WorldEntity::staticClassID() ) )
988  {
989    WorldEntity* pa = dynamic_cast<WorldEntity*>(this->getParent());
990    pa->hit( damage, killer );
991    return;
992  }
993 
994  bool dead = this->getHealth()<=0;
995 
996  this->decreaseHealth(damage);
997
998  PRINTF(0)("Hit me: %s::%s now only %f/%f health\n", this->getClassCName(), this->getCName(), this->getHealth(), this->getHealthMax());
999
1000  if( this->getHealth() > 0)
1001  {
1002    // any small explosion animaitions
1003  }
1004  else
1005  {
1006    if ( !dead )
1007      this->destroy( killer );
1008  }
1009}
1010
1011
1012/**
1013 * destoys the world entity
1014 */
1015void WorldEntity::destroy(WorldEntity* killer)
1016{
1017  this->toList(OM_DEAD);
1018}
1019
1020
1021/**
1022 * @brief updates the HealthWidget
1023 */
1024void WorldEntity::updateHealthWidget()
1025{
1026  if (this->healthWidget != NULL)
1027  {
1028    this->healthWidget->setMaximum(this->healthMax);
1029    this->healthWidget->setValue(this->health);
1030  }
1031}
1032
1033/**
1034 * @brief updates the Electronic Widget
1035 */
1036//!< xferred from spaceship
1037void WorldEntity::updateElectronicWidget(){
1038  if (this->electronicWidget != NULL)
1039  { //if it exists already: update it
1040     this->electronicWidget->setMaximum(this->electronicMax);
1041     this->electronicWidget->setValue(this->electronic);
1042  }
1043  else
1044  { //create the widget
1045    this->electronicWidget = new OrxGui::GLGuiEnergyWidgetVertical();
1046    this->electronicWidget->getBarWidget()->setChangedValueColor(Color(1,0,0,1));
1047    //this->electronicWidget->setDisplayedName("Electronics:");
1048    //this->electronicWidget->setSize2D(100,20);
1049    //this->electronicWidget->setAbsCoor2D(150,200);
1050    this->updateElectronicWidget();
1051//     if ( dynamic_cast<SpaceShip*>(this)->hasPlayer() )
1052//       State::getPlayer()->hud().setEnergyWidget(this->electronicWidget);
1053  }
1054}
1055
1056/**
1057 * @brief updates the ShieldWidget
1058 */
1059//!< xferred from spaceship
1060void WorldEntity::updateShieldWidget()
1061{
1062  if (this->shieldWidget != NULL)
1063  {
1064    this->shieldWidget->setMaximum(this->shieldMax);
1065    this->shieldWidget->setValue(this->shield);;
1066  }
1067  else
1068  {
1069    this->shieldWidget = new OrxGui::GLGuiEnergyWidgetVertical();
1070    this->shieldWidget->getBarWidget()->setChangedValueColor(Color(1,0,0,1));
1071    //this->shieldWidget->setDisplayedName("Shield:");
1072    //his->shieldWidget->setSize2D(100,20);
1073    //this->shieldWidget->setAbsCoor2D(200,200);
1074    this->updateShieldWidget();
1075//     if (dynamic_cast<SpaceShip*>(this)->hasPlayer())
1076//       State::getPlayer()->hud().setShieldWidget(this->shieldWidget);
1077  }
1078}
1079
1080
1081
1082/**
1083 * DEBUG-DRAW OF THE BV-Tree.
1084 * @param depth What depth to draw
1085 * @param drawMode the mode to draw this entity under
1086 */
1087void WorldEntity::drawBVTree(int depth, int drawMode) const
1088{
1089  glMatrixMode(GL_MODELVIEW);
1090  glPushMatrix();
1091  /* translate */
1092  glTranslatef (this->getAbsCoor ().x,
1093                this->getAbsCoor ().y,
1094                this->getAbsCoor ().z);
1095  /* rotate */
1096  Vector tmpRot = this->getAbsDir().getSpacialAxis();
1097  glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
1098
1099
1100  if (this->obbTree)
1101    this->obbTree->drawBV(depth, drawMode);
1102
1103
1104  glPopMatrix();
1105}
1106
1107
1108
1109/**
1110 * draw the mounting points
1111 */
1112void WorldEntity::debugDrawMountPoints() const
1113{
1114
1115  std::vector<MountPoint*>::const_iterator it = this->mountPoints.begin();
1116  for( ; it < this->mountPoints.end(); it++)
1117  {
1118    if( (*it) != NULL)
1119    {
1120      (*it)->debugDraw();
1121    }
1122  }
1123}
1124
1125
1126/**
1127 * Debug the WorldEntity
1128 */
1129void WorldEntity::debugEntity() const
1130{
1131  PRINT(0)("WorldEntity %s::%s  (DEBUG)\n", this->getClassCName(), this->getCName());
1132  this->debugNode();
1133  PRINT(0)("List: %s ; ModelCount %d - ", ObjectManager::OMListToString(this->objectListNumber).c_str(), this->models.size());
1134  for (unsigned int i = 0; i < this->models.size(); i++)
1135  {
1136    if (models[i] != NULL)
1137      PRINT(0)(" : %d:%s", i, this->models[i]->getCName());
1138  }
1139  PRINT(0)("\n");
1140
1141}
1142
1143
1144/**
1145 * handler for changes on registred vars
1146 * @param id id's which changed
1147 */
1148void WorldEntity::varChangeHandler( std::list< int > & id )
1149{
1150  if ( std::find( id.begin(), id.end(), modelFileName_handle ) != id.end() ||
1151       std::find( id.begin(), id.end(), scaling_handle ) != id.end()
1152     )
1153  {
1154    loadModel( modelFileName, scaling );
1155  }
1156
1157  if ( std::find( id.begin(), id.end(), list_handle ) != id.end() )
1158  {
1159    this->toList( (OM_LIST)list_write );
1160  }
1161
1162  if ( std::find( id.begin(), id.end(), health_handle ) != id.end() )
1163  {
1164    this->setHealth( health_write );
1165  }
1166
1167  if ( std::find( id.begin(), id.end(), healthMax_handle ) != id.end() )
1168  {
1169    this->setHealthMax( healthMax_write );
1170  }
1171
1172  PNode::varChangeHandler( id );
1173}
1174
1175
1176void WorldEntity::regen(float time){
1177  static float tmp;
1178  increaseHealth(time * this->healthRegen);
1179  increaseShield(time * this->shieldRegen);
1180//   updateHealthWidget();
1181//   updateShieldWidget();
1182
1183  //this->setHealth( this->shieldCur);      // FIXME currently just to test share system
1184
1185  if (this->electronic != this->electronicMax || this->electronicRegen != 0){
1186    tmp = this->electronic + this->electronicRegen * time;
1187    if ( tmp > electronicMax)
1188      this->electronic = this->electronicMax;
1189    else
1190      this->electronic = tmp;
1191
1192    updateElectronicWidget();
1193  }
1194
1195}
Note: See TracBrowser for help on using the repository browser.