Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/vs-enhencements/src/world_entities/world_entity.cc @ 10691

Last change on this file since 10691 was 10678, checked in by nicolasc, 17 years ago

xfer

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