Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 10769 was 10768, checked in by rennerc, 18 years ago

shield init

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