Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/water/src/world_entities/world_entity.cc @ 8680

Last change on this file since 8680 was 8316, checked in by bensch, 18 years ago

trunk: fixed most -Wall warnings… but there are still many missing :/

File size: 20.2 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  return true;
404}
405
406
407/**
408 * registers a new collision event to this woeld entity
409 *  @param entity the entity that collides
410 *  @param plane it stands on
411 *  @param position it collides on the plane
412 */
413bool WorldEntity::registerCollision(WorldEntity* entity, Plane* plane, Vector position)
414{
415  // is there any handler listening?
416  if( !this->bReactive)
417    return false;
418
419  // get a collision event
420  CollisionEvent* c = CREngine::getInstance()->popCollisionEventObject();
421  assert(c != NULL); // if this should fail: we got not enough precached CollisionEvents: alter value in cr_defs.h
422  c->collide(entity, plane, position);
423
424  for( int i = 0; i < CREngine::CR_NUMBER; ++i)
425    if( this->collisionHandles[i] != NULL)
426      this->collisionHandles[i]->registerCollisionEvent(c);
427  return true;
428}
429
430
431/**
432 * @brief moves this entity to the List OM_List
433 * @param list the list to set this Entity to.
434 *
435 * this is the same as a call to State::getObjectManager()->toList(entity , list);
436 * directly, but with an easier interface.
437 *
438 * @todo inline this (peut etre)
439 */
440void WorldEntity::toList(OM_LIST list)
441{
442  State::getObjectManager()->toList(this, list);
443}
444
445void WorldEntity::toReflectionList()
446{
447  State::getObjectManager()->toReflectionList( this );
448}
449
450void removeFromReflectionList()
451{
452/// TODO
453///  State::getObject
454}
455
456/**
457 * sets the character attributes of a worldentity
458 * @param character attributes
459 *
460 * these attributes don't have to be set, only use them, if you need them
461*/
462//void WorldEntity::setCharacterAttributes(CharacterAttributes* charAttr)
463//{}
464
465
466/**
467 *  this function is called, when two entities collide
468 * @param entity: the world entity with whom it collides
469 *
470 * Implement behaviour like damage application or other miscellaneous collision stuff in this function
471 */
472void WorldEntity::collidesWith(WorldEntity* entity, const Vector& location)
473{
474  /**
475   * THIS IS A DEFAULT COLLISION-Effect.
476   * IF YOU WANT TO CREATE A SPECIFIC COLLISION ON EACH OBJECT
477   * USE::
478   * if (entity->isA(CL_WHAT_YOU_ARE_LOOKING_FOR)) { printf "dothings"; };
479   *
480   * You can always define a default Action.... don't be affraid just test it :)
481   */
482  //  PRINTF(3)("collision %s vs %s @ (%f,%f,%f)\n", this->getClassName(), entity->getClassName(), location.x, location.y, location.z);
483}
484
485
486/**
487 *  this function is called, when two entities collide
488 * @param entity: the world entity with whom it collides
489 *
490 * Implement behaviour like damage application or other miscellaneous collision stuff in this function
491 */
492void WorldEntity::collidesWithGround(const Vector& location)
493{
494  PRINTF(0)("BSP_GROUND: %s collides \n", this->getClassName() );
495}
496
497void WorldEntity::collidesWithGround(const Vector& feet, const Vector& ray_1, const Vector& ray_2)
498{
499
500  // PRINTF(0)("BSP_GROUND: Player collides \n", this->getClassName() );
501
502  Vector v = this->getAbsDirX();
503  v.x *= 10;
504  v.y *= 10;
505  v.z *= 10;
506  Vector u = this->getAbsDirY();
507
508  if(feet.x == (u.x+this->getAbsCoor().x) &&  feet.y == u.y +this->getAbsCoor().y && feet.z == this->getAbsCoor().z)
509  {
510
511  this->setAbsCoor(ray_2 - v);
512  }
513  else
514  {
515    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)
516    {
517      this->setAbsCoor(feet -u );
518    }
519
520    this->setAbsCoor(ray_2 - v);
521
522  }
523}
524
525/**
526 *  this is called immediately after the Entity has been constructed, initialized and then Spawned into the World
527 *
528 */
529void WorldEntity::postSpawn ()
530{}
531
532
533/**
534 *  this method is called by the world if the WorldEntity leaves the game
535 */
536void WorldEntity::leaveWorld ()
537{}
538
539
540/**
541 * resets the WorldEntity to its initial values. eg. used for multiplayer games: respawning
542 */
543void WorldEntity::reset()
544{}
545
546/**
547 *  this method is called every frame
548 * @param time: the time in seconds that has passed since the last tick
549 *
550 * Handle all stuff that should update with time inside this method (movement, animation, etc.)
551*/
552void WorldEntity::tick(float time)
553{}
554
555
556/**
557 *  the entity is drawn onto the screen with this function
558 *
559 * This is a central function of an entity: call it to let the entity painted to the screen.
560 * Just override this function with whatever you want to be drawn.
561*/
562void WorldEntity::draw() const
563{
564  //PRINTF(0)("(%s::%s)\n", this->getClassName(), this->getName());
565  //  assert(!unlikely(this->models.empty()));
566  {
567    glMatrixMode(GL_MODELVIEW);
568    glPushMatrix();
569
570    /* translate */
571    glTranslatef (this->getAbsCoor ().x,
572                  this->getAbsCoor ().y,
573                  this->getAbsCoor ().z);
574    Vector tmpRot = this->getAbsDir().getSpacialAxis();
575    glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
576
577
578    // This Draws the LOD's
579    float cameraDistance = State::getCamera()->distance(this);
580    if (cameraDistance > 30 && this->models.size() >= 3 && this->models[2] != NULL)
581    {
582      this->models[2]->draw();
583    }
584    else if (cameraDistance > 10 && this->models.size() >= 2 && this->models[1] != NULL)
585    {
586      this->models[1]->draw();
587    }
588    else if (this->models.size() >= 1 && this->models[0] != NULL)
589    {
590      this->models[0]->draw();
591    }
592    glPopMatrix();
593  }
594}
595
596/**
597 * @param health the Health to add.
598 * @returns the health left (this->healthMax - health+this->health)
599 */
600float WorldEntity::increaseHealth(float health)
601{
602  this->health += health;
603  if (this->health > this->healthMax)
604  {
605    float retHealth = this->healthMax - this->health;
606    this->health = this->healthMax;
607    this->updateHealthWidget();
608    return retHealth;
609  }
610  this->updateHealthWidget();
611  return 0.0;
612}
613
614/**
615 * @param health the Health to be removed
616 * @returns 0.0 or the rest, that was not substracted (bellow 0.0)
617 */
618float WorldEntity::decreaseHealth(float health)
619{
620  this->health -= health;
621
622  if (this->health < 0)
623  {
624    float retHealth = -this->health;
625    this->health = 0.0f;
626    this->updateHealthWidget();
627    return retHealth;
628  }
629  this->updateHealthWidget();
630  return 0.0;
631
632}
633
634/**
635 * @param maxHealth the maximal health that can be loaded onto the entity.
636 */
637void WorldEntity::setHealthMax(float healthMax)
638{
639  this->healthMax = healthMax;
640  if (this->health > this->healthMax)
641  {
642    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());
643    this->health = this->healthMax;
644  }
645  this->updateHealthWidget();
646}
647
648/**
649 * @brief creates the HealthWidget
650 *
651 * since not all entities need an HealthWidget, it is only created on request.
652 */
653void WorldEntity::createHealthWidget()
654{
655  if (this->healthWidget == NULL)
656  {
657    this->healthWidget = new OrxGui::GLGuiBar();
658    this->healthWidget->setSize2D(30,400);
659    this->healthWidget->setAbsCoor2D(10,100);
660
661    this->updateHealthWidget();
662  }
663  else
664    PRINTF(3)("Allready created the HealthWidget for %s::%s\n", this->getClassName(), this->getName());
665}
666
667void WorldEntity::increaseHealthMax(float increaseHealth)
668{
669  this->healthMax += increaseHealth;
670  this->updateHealthWidget();
671}
672
673
674OrxGui::GLGuiWidget* WorldEntity::getHealthWidget()
675{
676  this->createHealthWidget();
677  return this->healthWidget;
678}
679
680/**
681 * @param visibility shows or hides the health-bar
682 * (creates the widget if needed)
683 */
684void WorldEntity::setHealthWidgetVisibilit(bool visibility)
685{
686  if (visibility)
687  {
688    if (this->healthWidget != NULL)
689      this->healthWidget->show();
690    else
691    {
692      this->createHealthWidget();
693      this->updateHealthWidget();
694      this->healthWidget->show();
695    }
696  }
697  else if (this->healthWidget != NULL)
698    this->healthWidget->hide();
699}
700
701/**
702 * @brief updates the HealthWidget
703 */
704void WorldEntity::updateHealthWidget()
705{
706  if (this->healthWidget != NULL)
707  {
708    this->healthWidget->setMaximum(this->healthMax);
709    this->healthWidget->setValue(this->health);
710  }
711}
712
713
714/**
715 * DEBUG-DRAW OF THE BV-Tree.
716 * @param depth What depth to draw
717 * @param drawMode the mode to draw this entity under
718 */
719void WorldEntity::drawBVTree(int depth, int drawMode) const
720{
721  glMatrixMode(GL_MODELVIEW);
722  glPushMatrix();
723  /* translate */
724  glTranslatef (this->getAbsCoor ().x,
725                this->getAbsCoor ().y,
726                this->getAbsCoor ().z);
727  /* rotate */
728  Vector tmpRot = this->getAbsDir().getSpacialAxis();
729  glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
730
731
732  if (this->obbTree)
733    this->obbTree->drawBV(depth, drawMode);
734
735
736  glPopMatrix();
737}
738
739
740/**
741 * Debug the WorldEntity
742 */
743void WorldEntity::debugEntity() const
744{
745  PRINT(0)("WorldEntity %s::%s  (DEBUG)\n", this->getClassName(), this->getName());
746  this->debugNode();
747  PRINT(0)("List: %s ; ModelCount %d - ", ObjectManager::OMListToString(this->objectListNumber) , this->models.size());
748  for (unsigned int i = 0; i < this->models.size(); i++)
749  {
750    if (models[i] != NULL)
751      PRINT(0)(" : %d:%s", i, this->models[i]->getName());
752  }
753  PRINT(0)("\n");
754
755}
756
757
758/**
759 * handler for changes on registred vars
760 * @param id id's which changed
761 */
762void WorldEntity::varChangeHandler( std::list< int > & id )
763{
764  if ( std::find( id.begin(), id.end(), modelFileName_handle ) != id.end() ||
765       std::find( id.begin(), id.end(), scaling_handle ) != id.end()
766     )
767  {
768    loadModel( modelFileName, scaling );
769  }
770
771  PNode::varChangeHandler( id );
772}
773
Note: See TracBrowser for help on using the repository browser.