Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/mount_points/src/world_entities/world_entity.cc @ 10053

Last change on this file since 10053 was 10053, checked in by patrick, 17 years ago

more oif starting procedures

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