Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/world_entities/world_entity.cc @ 8251

Last change on this file since 8251 was 8190, checked in by patrick, 19 years ago

trunk: merged the cr branche to trunk

File size: 20.1 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   co-programmer: Christian Meyer
16*/
17#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_WORLD_ENTITY
18
19#include "world_entity.h"
20#include "shell_command.h"
21
22#include "model.h"
23#include "md2Model.h"
24#include "util/loading/resource_manager.h"
25#include "util/loading/load_param.h"
26#include "vector.h"
27#include "obb_tree.h"
28
29#include "glgui_bar.h"
30
31#include "state.h"
32#include "camera.h"
33
34#include "collision_handle.h"
35#include "collision_event.h"
36
37#include <stdarg.h>
38
39
40using namespace std;
41
42SHELL_COMMAND(model, WorldEntity, loadModel)
43->describe("sets the Model of the WorldEntity")
44->defaultValues("models/ships/fighter.obj", 1.0f);
45
46SHELL_COMMAND(debugEntity, WorldEntity, debugWE);
47
48/**
49 *  Loads the WordEntity-specific Part of any derived Class
50 *
51 * @param root: Normally NULL, as the Derived Entities define a loadParams Function themeselves,
52 *              that can calls WorldEntities loadParams for itself.
53 */
54WorldEntity::WorldEntity()
55    : Synchronizeable()
56{
57  this->setClassID(CL_WORLD_ENTITY, "WorldEntity");
58
59  this->obbTree = NULL;
60  this->healthWidget = NULL;
61  this->healthMax = 1.0f;
62  this->health = 1.0f;
63  this->damage = 0.0f; // no damage dealt by a default entity
64  this->scaling = 1.0f;
65
66  /* OSOLETE */
67  this->bVisible = true;
68  this->bCollide = true;
69
70  this->objectListNumber = OM_INIT;
71  this->objectListIterator = NULL;
72
73  // reset all collision handles to NULL == unsubscribed state
74  for(int i = 0; i < CREngine::CR_NUMBER; ++i)
75    this->collisionHandles[i] = NULL;
76  this->bReactive = false;
77
78  // registering default reactions:
79  this->subscribeReaction(CREngine::CR_OBJECT_DAMAGE, CL_WORLD_ENTITY);
80  this->subscribeReaction(CREngine::CR_PHYSICS_GROUND, CL_TERRAIN);
81
82  this->toList(OM_NULL);
83
84  modelFileName_handle = registerVarId( new SynchronizeableString( &modelFileName, &modelFileName, "modelFileName" ) );
85  scaling_handle = registerVarId( new SynchronizeableFloat( &scaling, &scaling, "scaling" ) );
86}
87
88/**
89 *  standard destructor
90*/
91WorldEntity::~WorldEntity ()
92{
93  State::getObjectManager()->toList(this, OM_INIT);
94
95  // Delete the model (unregister it with the ResourceManager)
96  for (unsigned int i = 0; i < this->models.size(); i++)
97    this->setModel(NULL, i);
98
99  // Delete the obbTree
100  if( this->obbTree != NULL)
101    delete this->obbTree;
102
103  if (this->healthWidget != NULL)
104    delete this->healthWidget;
105
106  this->unsubscribeReaction();
107}
108
109/**
110 * loads the WorldEntity Specific Parameters.
111 * @param root: the XML-Element to load the Data From
112 */
113void WorldEntity::loadParams(const TiXmlElement* root)
114{
115  // Do the PNode loading stuff
116  PNode::loadParams(root);
117
118  LoadParam(root, "md2texture", this, WorldEntity, loadMD2Texture)
119  .describe("the fileName of the texture, that should be loaded onto this world-entity. (must be relative to the data-dir)")
120  .defaultValues("");
121
122  // Model Loading
123  LoadParam(root, "model", this, WorldEntity, loadModel)
124  .describe("the fileName of the model, that should be loaded onto this world-entity. (must be relative to the data-dir)")
125  .defaultValues("", 1.0f, 0);
126
127  LoadParam(root, "maxHealth", this, WorldEntity, setHealthMax)
128  .describe("The Maximum health that can be loaded onto this entity")
129  .defaultValues(1.0f);
130
131  LoadParam(root, "health", this, WorldEntity, setHealth)
132  .describe("The Health the WorldEntity has at this moment")
133  .defaultValues(1.0f);
134}
135
136
137/**
138 * loads a Model onto a WorldEntity
139 * @param fileName the name of the model to load
140 * @param scaling the Scaling of the model
141 *
142 * FIXME
143 * @todo: separate the obb tree generation from the model
144 */
145void WorldEntity::loadModel(const std::string& fileName, float scaling, unsigned int modelNumber, unsigned int obbTreeDepth)
146{
147  this->modelLODName = fileName;
148  this->scaling = scaling;
149
150  std::string name = fileName;
151
152  if (  name.find( ResourceManager::getInstance()->getDataDir() ) == 0 )
153  {
154    name.erase(ResourceManager::getInstance()->getDataDir().size());
155  }
156
157  this->modelFileName = name;
158
159  if (!fileName.empty())
160  {
161    // search for the special character # in the LoadParam
162    if (fileName.find('#') != std::string::npos)
163    {
164      PRINTF(4)("Found # in %s... searching for LOD's\n", fileName.c_str());
165      std::string lodFile = fileName;
166      unsigned int offset = lodFile.find('#');
167      for (unsigned int i = 0; i < 3; i++)
168      {
169        lodFile[offset] = 48+(int)i;
170        if (ResourceManager::isInDataDir(lodFile))
171          this->loadModel(lodFile, scaling, i);
172      }
173      return;
174    }
175    if (this->scaling <= 0.0)
176    {
177      PRINTF(1)("YOU GAVE ME A CRAPY SCALE resetting to 1.0\n");
178      this->scaling = 1.0;
179    }
180    if(fileName.find(".obj") != std::string::npos)
181    {
182      PRINTF(4)("fetching OBJ file: %s\n", fileName.c_str());
183      BaseObject* loadedModel = ResourceManager::getInstance()->load(fileName, OBJ, RP_CAMPAIGN, this->scaling);
184      if (loadedModel != NULL)
185        this->setModel(dynamic_cast<Model*>(loadedModel), modelNumber);
186      else
187        PRINTF(1)("OBJ-File %s not found.\n", fileName.c_str());
188
189      if( modelNumber == 0)
190        this->buildObbTree(obbTreeDepth);
191    }
192    else if(fileName.find(".md2") != std::string::npos)
193    {
194      PRINTF(4)("fetching MD2 file: %s\n", fileName.c_str());
195      Model* m = new MD2Model(fileName, this->md2TextureFileName, this->scaling);
196      //this->setModel((Model*)ResourceManager::getInstance()->load(fileName, MD2, RP_CAMPAIGN), 0);
197      this->setModel(m, 0);
198
199      if( m != NULL)
200        this->buildObbTree(obbTreeDepth);
201    }
202  }
203  else
204  {
205    this->setModel(NULL);
206  }
207}
208
209/**
210 * sets a specific Model for the Object.
211 * @param model The Model to set
212 * @param modelNumber the n'th model in the List to get.
213 */
214void WorldEntity::setModel(Model* model, unsigned int modelNumber)
215{
216  if (this->models.size() <= modelNumber)
217    this->models.resize(modelNumber+1, NULL);
218
219  if (this->models[modelNumber] != NULL)
220  {
221    Resource* resource = ResourceManager::getInstance()->locateResourceByPointer(dynamic_cast<BaseObject*>(this->models[modelNumber]));
222    if (resource != NULL)
223      ResourceManager::getInstance()->unload(resource, RP_LEVEL);
224    else
225    {
226      PRINTF(4)("Forcing model deletion\n");
227      delete this->models[modelNumber];
228    }
229  }
230
231  this->models[modelNumber] = model;
232
233
234  //   if (this->model != NULL)
235  //     this->buildObbTree(4);
236}
237
238
239/**
240 * builds the obb-tree
241 * @param depth the depth to calculate
242 */
243bool WorldEntity::buildObbTree(int depth)
244{
245  if (this->obbTree)
246    delete this->obbTree;
247
248  if (this->models[0] != NULL)
249  {
250    this->obbTree = new OBBTree(depth, models[0]->getModelInfo(), this);
251    return true;
252  }
253  else
254  {
255    PRINTF(1)("could not create obb-tree, because no model was loaded yet\n");
256    this->obbTree = NULL;
257    return false;
258  }
259}
260
261
262/**
263 * subscribes this world entity to a collision reaction
264 *  @param type the type of reaction to subscribe to
265 *  @param target1 a filter target (classID)
266 */
267void WorldEntity::subscribeReaction(CREngine::CRType type, long target1)
268{
269  this->subscribeReaction(type);
270
271  // add the target filter
272  this->collisionHandles[type]->addTarget(target1);
273}
274
275
276/**
277 * subscribes this world entity to a collision reaction
278 *  @param type the type of reaction to subscribe to
279 *  @param target1 a filter target (classID)
280 */
281void WorldEntity::subscribeReaction(CREngine::CRType type, long target1, long target2)
282{
283  this->subscribeReaction(type);
284
285  // add the target filter
286  this->collisionHandles[type]->addTarget(target1);
287  this->collisionHandles[type]->addTarget(target2);
288}
289
290
291/**
292 * subscribes this world entity to a collision reaction
293 *  @param type the type of reaction to subscribe to
294 *  @param target1 a filter target (classID)
295 */
296void WorldEntity::subscribeReaction(CREngine::CRType type, long target1, long target2, long target3)
297{
298  this->subscribeReaction(type);
299
300  // add the target filter
301  this->collisionHandles[type]->addTarget(target1);
302  this->collisionHandles[type]->addTarget(target2);
303  this->collisionHandles[type]->addTarget(target3);
304}
305
306
307/**
308 * subscribes this world entity to a collision reaction
309 *  @param type the type of reaction to subscribe to
310 *  @param target1 a filter target (classID)
311 */
312void WorldEntity::subscribeReaction(CREngine::CRType type, long target1, long target2, long target3, long target4)
313{
314  this->subscribeReaction(type);
315
316  // add the target filter
317  this->collisionHandles[type]->addTarget(target1);
318  this->collisionHandles[type]->addTarget(target2);
319  this->collisionHandles[type]->addTarget(target3);
320  this->collisionHandles[type]->addTarget(target4);
321}
322
323
324/**
325 * subscribes this world entity to a collision reaction
326 *  @param type the type of reaction to subscribe to
327 *  @param nrOfTargets number of target filters
328 *  @param ... the targets as classIDs
329 */
330void WorldEntity::subscribeReaction(CREngine::CRType type)
331{
332  if( this->collisionHandles[type] != NULL)  {
333    PRINTF(2)("Registering for a CollisionReaction already subscribed to! Skipping\n");
334    return;
335  }
336
337  this->collisionHandles[type] = CREngine::getInstance()->subscribeReaction(this, type);
338
339  // now there is at least one collision reaction subscribed
340  this->bReactive = true;
341}
342
343
344/**
345 * unsubscribes a specific reaction from the worldentity
346 *  @param type the reaction to unsubscribe
347 */
348void WorldEntity::unsubscribeReaction(CREngine::CRType type)
349{
350  if( this->collisionHandles[type] == NULL)
351    return;
352
353  CREngine::getInstance()->unsubscribeReaction(this->collisionHandles[type]);
354  this->collisionHandles[type] = NULL;
355
356  // check if there is still any handler registered
357  for(int i = 0; i < CREngine::CR_NUMBER; ++i)
358  {
359    if( this->collisionHandles[i] != NULL)
360    {
361      this->bReactive = true;
362      return;
363    }
364  }
365  this->bReactive = false;
366}
367
368
369/**
370 * unsubscribes all collision reactions
371 */
372void WorldEntity::unsubscribeReaction()
373{
374  for( int i = 0; i < CREngine::CR_NUMBER; i++)
375    this->unsubscribeReaction((CREngine::CRType)i);
376
377  // there are no reactions subscribed from now on
378  this->bReactive = false;
379}
380
381
382/**
383 * registers a new collision event to this world entity
384 *  @param entityA entity of the collision
385 *  @param entityB entity of the collision
386 *  @param bvA colliding bounding volume of entityA
387 *  @param bvB colliding bounding volume of entityA
388 */
389bool WorldEntity::registerCollision(WorldEntity* entityA, WorldEntity* entityB, BoundingVolume* bvA, BoundingVolume* bvB)
390{
391  // is there any handler listening?
392  if( !this->bReactive)
393    return false;
394
395  // get a collision event
396  CollisionEvent* c = CREngine::getInstance()->popCollisionEventObject();
397  assert(c != NULL); // if this should fail: we got not enough precached CollisionEvents: alter value in cr_defs.h
398  c->collide(entityA, entityB, bvA, bvB);
399
400  for( int i = 0; i < CREngine::CR_NUMBER; ++i)
401    if( this->collisionHandles[i] != NULL)
402      this->collisionHandles[i]->registerCollisionEvent(c);
403}
404
405
406/**
407 * registers a new collision event to this woeld entity
408 *  @param entity the entity that collides
409 *  @param plane it stands on
410 *  @param position it collides on the plane
411 */
412bool WorldEntity::registerCollision(WorldEntity* entity, Plane* plane, Vector position)
413{
414  // is there any handler listening?
415  if( !this->bReactive)
416    return false;
417
418  // get a collision event
419  CollisionEvent* c = CREngine::getInstance()->popCollisionEventObject();
420  assert(c != NULL); // if this should fail: we got not enough precached CollisionEvents: alter value in cr_defs.h
421  c->collide(entity, plane, position);
422
423  for( int i = 0; i < CREngine::CR_NUMBER; ++i)
424    if( this->collisionHandles[i] != NULL)
425      this->collisionHandles[i]->registerCollisionEvent(c);
426}
427
428
429/**
430 * @brief moves this entity to the List OM_List
431 * @param list the list to set this Entity to.
432 *
433 * this is the same as a call to State::getObjectManager()->toList(entity , list);
434 * directly, but with an easier interface.
435 *
436 * @todo inline this (peut etre)
437 */
438void WorldEntity::toList(OM_LIST list)
439{
440  State::getObjectManager()->toList(this, list);
441}
442
443void WorldEntity::toReflectionList()
444{
445  State::getObjectManager()->toReflectionList( this );
446}
447
448void removeFromReflectionList()
449{
450/// TODO
451///  State::getObject
452}
453
454/**
455 * sets the character attributes of a worldentity
456 * @param character attributes
457 *
458 * these attributes don't have to be set, only use them, if you need them
459*/
460//void WorldEntity::setCharacterAttributes(CharacterAttributes* charAttr)
461//{}
462
463
464/**
465 *  this function is called, when two entities collide
466 * @param entity: the world entity with whom it collides
467 *
468 * Implement behaviour like damage application or other miscellaneous collision stuff in this function
469 */
470void WorldEntity::collidesWith(WorldEntity* entity, const Vector& location)
471{
472  /**
473   * THIS IS A DEFAULT COLLISION-Effect.
474   * IF YOU WANT TO CREATE A SPECIFIC COLLISION ON EACH OBJECT
475   * USE::
476   * if (entity->isA(CL_WHAT_YOU_ARE_LOOKING_FOR)) { printf "dothings"; };
477   *
478   * You can always define a default Action.... don't be affraid just test it :)
479   */
480  //  PRINTF(3)("collision %s vs %s @ (%f,%f,%f)\n", this->getClassName(), entity->getClassName(), location.x, location.y, location.z);
481}
482
483
484/**
485 *  this function is called, when two entities collide
486 * @param entity: the world entity with whom it collides
487 *
488 * Implement behaviour like damage application or other miscellaneous collision stuff in this function
489 */
490void WorldEntity::collidesWithGround(const Vector& location)
491{
492  PRINTF(0)("BSP_GROUND: %s collides \n", this->getClassName() );
493}
494
495void WorldEntity::collidesWithGround(const Vector& feet, const Vector& ray_1, const Vector& ray_2)
496{
497
498  // PRINTF(0)("BSP_GROUND: Player collides \n", this->getClassName() );
499
500  Vector v = this->getAbsDirX();
501  v.x *= 10;
502  v.y *= 10;
503  v.z *= 10;
504  Vector u = this->getAbsDirY();
505
506  if(feet.x == (u.x+this->getAbsCoor().x) &&  feet.y == u.y +this->getAbsCoor().y && feet.z == this->getAbsCoor().z)
507  {
508
509  this->setAbsCoor(ray_2 - v);
510  }
511  else
512  {
513    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)
514    {
515      this->setAbsCoor(feet -u );
516    }
517
518    this->setAbsCoor(ray_2 - v);
519
520  }
521}
522
523/**
524 *  this is called immediately after the Entity has been constructed, initialized and then Spawned into the World
525 *
526 */
527void WorldEntity::postSpawn ()
528{}
529
530
531/**
532 *  this method is called by the world if the WorldEntity leaves the game
533 */
534void WorldEntity::leaveWorld ()
535{}
536
537
538/**
539 * resets the WorldEntity to its initial values. eg. used for multiplayer games: respawning
540 */
541void WorldEntity::reset()
542{}
543
544/**
545 *  this method is called every frame
546 * @param time: the time in seconds that has passed since the last tick
547 *
548 * Handle all stuff that should update with time inside this method (movement, animation, etc.)
549*/
550void WorldEntity::tick(float time)
551{}
552
553
554/**
555 *  the entity is drawn onto the screen with this function
556 *
557 * This is a central function of an entity: call it to let the entity painted to the screen.
558 * Just override this function with whatever you want to be drawn.
559*/
560void WorldEntity::draw() const
561{
562  //PRINTF(0)("(%s::%s)\n", this->getClassName(), this->getName());
563  //  assert(!unlikely(this->models.empty()));
564  {
565    glMatrixMode(GL_MODELVIEW);
566    glPushMatrix();
567
568    /* translate */
569    glTranslatef (this->getAbsCoor ().x,
570                  this->getAbsCoor ().y,
571                  this->getAbsCoor ().z);
572    Vector tmpRot = this->getAbsDir().getSpacialAxis();
573    glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
574
575
576    // This Draws the LOD's
577    float cameraDistance = State::getCamera()->distance(this);
578    if (cameraDistance > 30 && this->models.size() >= 3 && this->models[2] != NULL)
579    {
580      this->models[2]->draw();
581    }
582    else if (cameraDistance > 10 && this->models.size() >= 2 && this->models[1] != NULL)
583    {
584      this->models[1]->draw();
585    }
586    else if (this->models.size() >= 1 && this->models[0] != NULL)
587    {
588      this->models[0]->draw();
589    }
590    glPopMatrix();
591  }
592}
593
594/**
595 * @param health the Health to add.
596 * @returns the health left (this->healthMax - health+this->health)
597 */
598float WorldEntity::increaseHealth(float health)
599{
600  this->health += health;
601  if (this->health > this->healthMax)
602  {
603    float retHealth = this->healthMax - this->health;
604    this->health = this->healthMax;
605    this->updateHealthWidget();
606    return retHealth;
607  }
608  this->updateHealthWidget();
609  return 0.0;
610}
611
612/**
613 * @param health the Health to be removed
614 * @returns 0.0 or the rest, that was not substracted (bellow 0.0)
615 */
616float WorldEntity::decreaseHealth(float health)
617{
618  this->health -= health;
619
620  if (this->health < 0)
621  {
622    float retHealth = -this->health;
623    this->health = 0.0f;
624    this->updateHealthWidget();
625    return retHealth;
626  }
627  this->updateHealthWidget();
628  return 0.0;
629
630}
631
632/**
633 * @param maxHealth the maximal health that can be loaded onto the entity.
634 */
635void WorldEntity::setHealthMax(float healthMax)
636{
637  this->healthMax = healthMax;
638  if (this->health > this->healthMax)
639  {
640    PRINTF(3)("new maxHealth is bigger as the old health. Did you really intend to do this for (%s::%s)\n", this->getClassName(), this->getName());
641    this->health = this->healthMax;
642  }
643  this->updateHealthWidget();
644}
645
646/**
647 * @brief creates the HealthWidget
648 *
649 * since not all entities need an HealthWidget, it is only created on request.
650 */
651void WorldEntity::createHealthWidget()
652{
653  if (this->healthWidget == NULL)
654  {
655    this->healthWidget = new OrxGui::GLGuiBar();
656    this->healthWidget->setSize2D(30,400);
657    this->healthWidget->setAbsCoor2D(10,100);
658
659    this->updateHealthWidget();
660  }
661  else
662    PRINTF(3)("Allready created the HealthWidget for %s::%s\n", this->getClassName(), this->getName());
663}
664
665void WorldEntity::increaseHealthMax(float increaseHealth)
666{
667  this->healthMax += increaseHealth;
668  this->updateHealthWidget();
669}
670
671
672OrxGui::GLGuiWidget* WorldEntity::getHealthWidget()
673{
674  this->createHealthWidget();
675  return this->healthWidget;
676}
677
678/**
679 * @param visibility shows or hides the health-bar
680 * (creates the widget if needed)
681 */
682void WorldEntity::setHealthWidgetVisibilit(bool visibility)
683{
684  if (visibility)
685  {
686    if (this->healthWidget != NULL)
687      this->healthWidget->show();
688    else
689    {
690      this->createHealthWidget();
691      this->updateHealthWidget();
692      this->healthWidget->show();
693    }
694  }
695  else if (this->healthWidget != NULL)
696    this->healthWidget->hide();
697}
698
699/**
700 * @brief updates the HealthWidget
701 */
702void WorldEntity::updateHealthWidget()
703{
704  if (this->healthWidget != NULL)
705  {
706    this->healthWidget->setMaximum(this->healthMax);
707    this->healthWidget->setValue(this->health);
708  }
709}
710
711
712/**
713 * DEBUG-DRAW OF THE BV-Tree.
714 * @param depth What depth to draw
715 * @param drawMode the mode to draw this entity under
716 */
717void WorldEntity::drawBVTree(int depth, int drawMode) const
718{
719  glMatrixMode(GL_MODELVIEW);
720  glPushMatrix();
721  /* translate */
722  glTranslatef (this->getAbsCoor ().x,
723                this->getAbsCoor ().y,
724                this->getAbsCoor ().z);
725  /* rotate */
726  Vector tmpRot = this->getAbsDir().getSpacialAxis();
727  glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
728
729
730  if (this->obbTree)
731    this->obbTree->drawBV(depth, drawMode);
732
733
734  glPopMatrix();
735}
736
737
738/**
739 * Debug the WorldEntity
740 */
741void WorldEntity::debugEntity() const
742{
743  PRINT(0)("WorldEntity %s::%s  (DEBUG)\n", this->getClassName(), this->getName());
744  this->debugNode();
745  PRINT(0)("List: %s ; ModelCount %d - ", ObjectManager::OMListToString(this->objectListNumber) , this->models.size());
746  for (unsigned int i = 0; i < this->models.size(); i++)
747  {
748    if (models[i] != NULL)
749      PRINT(0)(" : %d:%s", i, this->models[i]->getName());
750  }
751  PRINT(0)("\n");
752
753}
754
755
756/**
757 * handler for changes on registred vars
758 * @param id id's which changed
759 */
760void WorldEntity::varChangeHandler( std::list< int > & id )
761{
762  if ( std::find( id.begin(), id.end(), modelFileName_handle ) != id.end() ||
763       std::find( id.begin(), id.end(), scaling_handle ) != id.end()
764     )
765  {
766    loadModel( modelFileName, scaling );
767  }
768
769  PNode::varChangeHandler( id );
770}
771
Note: See TracBrowser for help on using the repository browser.