Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/terrain/src/world_entities/world_entity.cc @ 10656

Last change on this file since 10656 was 10013, checked in by patrick, 18 years ago

merged the collision reaction branche back to trunk

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