Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/cr/src/world_entities/world_entity.cc @ 7964

Last change on this file since 7964 was 7958, checked in by patrick, 19 years ago

cr: collision reactance introduced

File size: 17.5 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.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->scaling = 1.0f;
64
65  /* OSOLETE */
66  this->bVisible = true;
67  this->bCollide = true;
68
69  this->objectListNumber = OM_INIT;
70  this->objectListIterator = NULL;
71
72  // reset all collision handles to NULL == unsubscribed state
73  for(int i = 0; i < CREngine::CR_NUMBER; ++i)
74    this->collisionHandles[i] = NULL;
75
76  this->toList(OM_NULL);
77}
78
79/**
80 *  standard destructor
81*/
82WorldEntity::~WorldEntity ()
83{
84  State::getObjectManager()->toList(this, OM_INIT);
85
86  // Delete the model (unregister it with the ResourceManager)
87  for (unsigned int i = 0; i < this->models.size(); i++)
88    this->setModel(NULL, i);
89
90  // Delete the obbTree
91  if( this->obbTree != NULL)
92    delete this->obbTree;
93
94  if (this->healthWidget != NULL)
95    delete this->healthWidget;
96
97  this->unsubscribeReaction();
98}
99
100/**
101 * loads the WorldEntity Specific Parameters.
102 * @param root: the XML-Element to load the Data From
103 */
104void WorldEntity::loadParams(const TiXmlElement* root)
105{
106  // Do the PNode loading stuff
107  PNode::loadParams(root);
108
109  LoadParam(root, "md2texture", this, WorldEntity, loadMD2Texture)
110  .describe("the fileName of the texture, that should be loaded onto this world-entity. (must be relative to the data-dir)")
111  .defaultValues("");
112
113  // Model Loading
114  LoadParam(root, "model", this, WorldEntity, loadModel)
115  .describe("the fileName of the model, that should be loaded onto this world-entity. (must be relative to the data-dir)")
116  .defaultValues("", 1.0f, 0);
117
118  LoadParam(root, "maxHealth", this, WorldEntity, setHealthMax)
119  .describe("The Maximum health that can be loaded onto this entity")
120  .defaultValues(1.0f);
121
122  LoadParam(root, "health", this, WorldEntity, setHealth)
123  .describe("The Health the WorldEntity has at this moment")
124  .defaultValues(1.0f);
125}
126
127
128/**
129 * loads a Model onto a WorldEntity
130 * @param fileName the name of the model to load
131 * @param scaling the Scaling of the model
132 *
133 * FIXME
134 * @todo: separate the obb tree generation from the model
135 */
136void WorldEntity::loadModel(const std::string& fileName, float scaling, unsigned int modelNumber, unsigned int obbTreeDepth)
137{
138  this->modelLODName = fileName;
139  this->scaling = scaling;
140  if (!fileName.empty())
141  {
142    // search for the special character # in the LoadParam
143    if (fileName.find('#') != std::string::npos)
144    {
145      PRINTF(4)("Found # in %s... searching for LOD's\n", fileName.c_str());
146      std::string lodFile = fileName;
147      unsigned int offset = lodFile.find('#');
148      for (unsigned int i = 0; i < 3; i++)
149      {
150        lodFile[offset] = 48+(int)i;
151        if (ResourceManager::isInDataDir(lodFile))
152          this->loadModel(lodFile, scaling, i);
153      }
154      return;
155    }
156    if (this->scaling <= 0.0)
157    {
158      PRINTF(1)("YOU GAVE ME A CRAPY SCALE resetting to 1.0\n");
159      this->scaling = 1.0;
160    }
161    if(fileName.find(".obj") != std::string::npos)
162    {
163      PRINTF(4)("fetching OBJ file: %s\n", fileName.c_str());
164      BaseObject* loadedModel = ResourceManager::getInstance()->load(fileName, OBJ, RP_CAMPAIGN, this->scaling);
165      if (loadedModel != NULL)
166        this->setModel(dynamic_cast<Model*>(loadedModel), modelNumber);
167      else
168        PRINTF(1)("OBJ-File %s not found.\n", fileName.c_str());
169
170      if( modelNumber == 0)
171        this->buildObbTree(obbTreeDepth);
172    }
173    else if(fileName.find(".md2") != std::string::npos)
174    {
175      PRINTF(4)("fetching MD2 file: %s\n", fileName.c_str());
176      Model* m = new MD2Model(fileName, this->md2TextureFileName, this->scaling);
177      //this->setModel((Model*)ResourceManager::getInstance()->load(fileName, MD2, RP_CAMPAIGN), 0);
178      this->setModel(m, 0);
179
180      if( m != NULL)
181        this->buildObbTree(obbTreeDepth);
182    }
183  }
184  else
185  {
186    this->setModel(NULL);
187  }
188}
189
190/**
191 * sets a specific Model for the Object.
192 * @param model The Model to set
193 * @param modelNumber the n'th model in the List to get.
194 */
195void WorldEntity::setModel(Model* model, unsigned int modelNumber)
196{
197  if (this->models.size() <= modelNumber)
198    this->models.resize(modelNumber+1, NULL);
199
200  if (this->models[modelNumber] != NULL)
201  {
202    Resource* resource = ResourceManager::getInstance()->locateResourceByPointer(dynamic_cast<BaseObject*>(this->models[modelNumber]));
203    if (resource != NULL)
204      ResourceManager::getInstance()->unload(resource, RP_LEVEL);
205    else
206    {
207      PRINTF(4)("Forcing model deletion\n");
208      delete this->models[modelNumber];
209    }
210  }
211
212  this->models[modelNumber] = model;
213
214
215  //   if (this->model != NULL)
216  //     this->buildObbTree(4);
217}
218
219
220/**
221 * builds the obb-tree
222 * @param depth the depth to calculate
223 */
224bool WorldEntity::buildObbTree(int depth)
225{
226  if (this->obbTree)
227    delete this->obbTree;
228
229  if (this->models[0] != NULL)
230  {
231    this->obbTree = new OBBTree(depth, models[0]->getModelInfo(), this);
232    return true;
233  }
234  else
235  {
236    PRINTF(1)("could not create obb-tree, because no model was loaded yet\n");
237    this->obbTree = NULL;
238    return false;
239  }
240}
241
242
243/**
244 * subscribes this world entity to a collision reaction
245 *  @param type the type of reaction to subscribe to
246 *  @param nrOfTargets number of target filters
247 *  @param ... the targets as classIDs
248 */
249void WorldEntity::subscribeReaction(CREngine::CRType type, int nrOfTargets, long target...)
250{
251  if( this->collisionHandles[type] != NULL)  {
252    PRINTF(2)("Registering for a CollisionReaction already subscribed to! Skipping\n");
253    return;
254  }
255
256  this->collisionHandles[type] = CREngine::getInstance()->subscribeReaction(this, type);
257
258  // add the target filter
259  va_list itemlist;
260  va_start (itemlist, target);
261  for (int i = 0; i < nrOfTargets; i++)
262    this->collisionHandles[type]->addTarget(va_arg(itemlist, long));
263  va_end(itemlist);
264
265  // now there is at least one collision reaction subsribed
266  this->bReactive = true;
267}
268
269
270/**
271 * unsubscribes a specific reaction from the worldentity
272 *  @param type the reaction to unsubscribe
273 */
274void WorldEntity::unsubscribeReaction(CREngine::CRType type)
275{
276  if( this->collisionHandles[type] == NULL)
277    return;
278
279  CREngine::getInstance()->unsubscribeReaction(this->collisionHandles[type]);
280  this->collisionHandles[type] = NULL;
281
282  //
283}
284
285
286/**
287 * unsubscribes all collision reactions
288 */
289void WorldEntity::unsubscribeReaction()
290{
291  for( int i = 0; i < CREngine::CR_NUMBER; i++)
292    this->unsubscribeReaction((CREngine::CRType)i);
293
294  this->bReactive = false;
295}
296
297
298/**
299 * registers a new collision to this world entity
300 *  @param collisionEvent the event
301 */
302bool WorldEntity::registerCollision(WorldEntity* entityA, WorldEntity* entityB, BoundingVolume* bvA, BoundingVolume* bvB)
303{
304  PRINTF(0)("Registering Collision: %s vs %s \n", entityA->getClassName(), entityB->getClassName());
305  // create a collision event
306  Collision* c = CREngine::getInstance()->popCollisionObject();
307  assert(c != NULL);
308  c->collide(entityA, entityB, bvA, bvB);
309
310  for(int i = 0; i < CREngine::CR_NUMBER; ++i)
311    if( this->collisionHandles[i] != NULL)
312      this->collisionHandles[i]->registerCollision(c);
313}
314
315
316/**
317 * @brief moves this entity to the List OM_List
318 * @param list the list to set this Entity to.
319 *
320 * this is the same as a call to State::getObjectManager()->toList(entity , list);
321 * directly, but with an easier interface.
322 *
323 * @todo inline this (peut etre)
324 */
325void WorldEntity::toList(OM_LIST list)
326{
327  State::getObjectManager()->toList(this, list);
328}
329
330
331
332/**
333 * sets the character attributes of a worldentity
334 * @param character attributes
335 *
336 * these attributes don't have to be set, only use them, if you need them
337*/
338//void WorldEntity::setCharacterAttributes(CharacterAttributes* charAttr)
339//{}
340
341
342/**
343 *  this function is called, when two entities collide
344 * @param entity: the world entity with whom it collides
345 *
346 * Implement behaviour like damage application or other miscellaneous collision stuff in this function
347 */
348void WorldEntity::collidesWith(WorldEntity* entity, const Vector& location)
349{
350  /**
351   * THIS IS A DEFAULT COLLISION-Effect.
352   * IF YOU WANT TO CREATE A SPECIFIC COLLISION ON EACH OBJECT
353   * USE::
354   * if (entity->isA(CL_WHAT_YOU_ARE_LOOKING_FOR)) { printf "dothings"; };
355   *
356   * You can always define a default Action.... don't be affraid just test it :)
357   */
358  //  PRINTF(3)("collision %s vs %s @ (%f,%f,%f)\n", this->getClassName(), entity->getClassName(), location.x, location.y, location.z);
359}
360
361
362/**
363 *  this is called immediately after the Entity has been constructed, initialized and then Spawned into the World
364 *
365 */
366void WorldEntity::postSpawn ()
367{}
368
369
370/**
371 *  this method is called by the world if the WorldEntity leaves the game
372 */
373void WorldEntity::leaveWorld ()
374{}
375
376
377/**
378 * resets the WorldEntity to its initial values. eg. used for multiplayer games: respawning
379 */
380void WorldEntity::reset()
381{}
382
383/**
384 *  this method is called every frame
385 * @param time: the time in seconds that has passed since the last tick
386 *
387 * Handle all stuff that should update with time inside this method (movement, animation, etc.)
388*/
389void WorldEntity::tick(float time)
390{}
391
392
393/**
394 *  the entity is drawn onto the screen with this function
395 *
396 * This is a central function of an entity: call it to let the entity painted to the screen.
397 * Just override this function with whatever you want to be drawn.
398*/
399void WorldEntity::draw() const
400{
401  //PRINTF(0)("(%s::%s)\n", this->getClassName(), this->getName());
402  //  assert(!unlikely(this->models.empty()));
403  {
404    glMatrixMode(GL_MODELVIEW);
405    glPushMatrix();
406
407    /* translate */
408    glTranslatef (this->getAbsCoor ().x,
409                  this->getAbsCoor ().y,
410                  this->getAbsCoor ().z);
411    Vector tmpRot = this->getAbsDir().getSpacialAxis();
412    glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
413
414
415    // This Draws the LOD's
416    float cameraDistance = State::getCamera()->distance(this);
417    if (cameraDistance > 30 && this->models.size() >= 3 && this->models[2] != NULL)
418    {
419      this->models[2]->draw();
420    }
421    else if (cameraDistance > 10 && this->models.size() >= 2 && this->models[1] != NULL)
422    {
423      this->models[1]->draw();
424    }
425    else if (this->models.size() >= 1 && this->models[0] != NULL)
426    {
427      this->models[0]->draw();
428    }
429    glPopMatrix();
430  }
431}
432
433/**
434 * @param health the Health to add.
435 * @returns the health left (this->healthMax - health+this->health)
436 */
437float WorldEntity::increaseHealth(float health)
438{
439  this->health += health;
440  if (this->health > this->healthMax)
441  {
442    float retHealth = this->healthMax - this->health;
443    this->health = this->healthMax;
444    this->updateHealthWidget();
445    return retHealth;
446  }
447  this->updateHealthWidget();
448  return 0.0;
449}
450
451/**
452 * @param health the Health to be removed
453 * @returns 0.0 or the rest, that was not substracted (bellow 0.0)
454 */
455float WorldEntity::decreaseHealth(float health)
456{
457  this->health -= health;
458
459  if (this->health < 0)
460  {
461    float retHealth = -this->health;
462    this->health = 0.0f;
463    this->updateHealthWidget();
464    return retHealth;
465  }
466  this->updateHealthWidget();
467  return 0.0;
468
469}
470
471/**
472 * @param maxHealth the maximal health that can be loaded onto the entity.
473 */
474void WorldEntity::setHealthMax(float healthMax)
475{
476  this->healthMax = healthMax;
477  if (this->health > this->healthMax)
478  {
479    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());
480    this->health = this->healthMax;
481  }
482  this->updateHealthWidget();
483}
484
485/**
486 * @brief creates the HealthWidget
487 *
488 * since not all entities need an HealthWidget, it is only created on request.
489 */
490void WorldEntity::createHealthWidget()
491{
492  if (this->healthWidget == NULL)
493  {
494    this->healthWidget = new OrxGui::GLGuiBar();
495    this->healthWidget->setSize2D(30,400);
496    this->healthWidget->setAbsCoor2D(10,100);
497
498    this->updateHealthWidget();
499  }
500  else
501    PRINTF(3)("Allready created the HealthWidget for %s::%s\n", this->getClassName(), this->getName());
502}
503
504void WorldEntity::increaseHealthMax(float increaseHealth)
505{
506  this->healthMax += increaseHealth;
507  this->updateHealthWidget();
508}
509
510
511OrxGui::GLGuiWidget* WorldEntity::getHealthWidget()
512{
513  this->createHealthWidget();
514  return this->healthWidget;
515}
516
517/**
518 * @param visibility shows or hides the health-bar
519 * (creates the widget if needed)
520 */
521void WorldEntity::setHealthWidgetVisibilit(bool visibility)
522{
523  if (visibility)
524  {
525    if (this->healthWidget != NULL)
526      this->healthWidget->show();
527    else
528    {
529      this->createHealthWidget();
530      this->updateHealthWidget();
531      this->healthWidget->show();
532    }
533  }
534  else if (this->healthWidget != NULL)
535    this->healthWidget->hide();
536}
537
538/**
539 * @brief updates the HealthWidget
540 */
541void WorldEntity::updateHealthWidget()
542{
543  if (this->healthWidget != NULL)
544  {
545    this->healthWidget->setMaximum(this->healthMax);
546    this->healthWidget->setValue(this->health);
547  }
548}
549
550
551/**
552 * DEBUG-DRAW OF THE BV-Tree.
553 * @param depth What depth to draw
554 * @param drawMode the mode to draw this entity under
555 */
556void WorldEntity::drawBVTree(int depth, int drawMode) const
557{
558  glMatrixMode(GL_MODELVIEW);
559  glPushMatrix();
560  /* translate */
561  glTranslatef (this->getAbsCoor ().x,
562                this->getAbsCoor ().y,
563                this->getAbsCoor ().z);
564  /* rotate */
565  Vector tmpRot = this->getAbsDir().getSpacialAxis();
566  glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
567
568
569  if (this->obbTree)
570    this->obbTree->drawBV(depth, drawMode);
571
572
573  glPopMatrix();
574}
575
576
577/**
578 * Debug the WorldEntity
579 */
580void WorldEntity::debugEntity() const
581{
582  PRINT(0)("WorldEntity %s::%s  (DEBUG)\n", this->getClassName(), this->getName());
583  this->debugNode();
584  PRINT(0)("List: %s ; ModelCount %d - ", ObjectManager::OMListToString(this->objectListNumber) , this->models.size());
585  for (unsigned int i = 0; i < this->models.size(); i++)
586  {
587    if (models[i] != NULL)
588      PRINT(0)(" : %d:%s", i, this->models[i]->getName());
589  }
590  PRINT(0)("\n");
591
592}
593
594
595
596
597/********************************************************************************************
598 NETWORK STUFF
599 ********************************************************************************************/
600
601
602/**
603 * Writes data from network containing information about the state
604 * @param data pointer to data
605 * @param length length of data
606 * @param sender hostID of sender
607 */
608int WorldEntity::writeState( const byte * data, int length, int sender )
609{
610  std::string modelFileName;
611  SYNCHELP_READ_BEGIN();
612
613  SYNCHELP_READ_FKT( PNode::writeState, NWT_WE_PN_WRITESTATE );
614
615  SYNCHELP_READ_STRING( modelFileName, NWT_WE_PN_MODELFILENAME );
616  SYNCHELP_READ_FLOAT( scaling, NWT_WE_PN_SCALING );
617  //check if modelFileName is relative to datadir or absolute
618
619
620  PRINTF(0)("================ LOADING MODEL %s, %f\n", modelFileName.c_str(), scaling);
621
622  if ( modelFileName != "" )
623  {
624    loadModel( modelFileName, scaling);
625    PRINTF(0)("modelfilename: %s\n", getModel( 0 )->getName());
626  }
627
628  /*SYNCHELP_READ_STRINGM( modelFileName );
629
630  if ( strcmp(modelFileName, "") )
631    if ( strstr(modelFileName, ResourceManager::getInstance()->getDataDir()) )
632    {
633      this->md2TextureFileName = new char[strlen(modelFileName)-strlen(ResourceManager::getInstance()->getDataDir())+1];
634      strcpy((char*)this->md2TextureFileName, modelFileName+strlen(ResourceManager::getInstance()->getDataDir()));
635    }
636    else
637    {
638      this->md2TextureFileName = modelFileName;
639    }
640  */
641
642  return SYNCHELP_READ_N;
643}
644
645
646/**
647 * data copied in data will bee sent to another host
648 * @param data pointer to data
649 * @param maxLength max length of data
650 * @return the number of bytes writen
651 */
652int WorldEntity::readState( byte * data, int maxLength )
653{
654  SYNCHELP_WRITE_BEGIN();
655
656  SYNCHELP_WRITE_FKT( PNode::readState, NWT_WE_PN_WRITESTATE );
657
658  if ( getModel(0) && getModel(0)->getName() != "" )
659  {
660    std::string name = getModel( 0 )->getName();
661
662    if (  name.find( ResourceManager::getInstance()->getDataDir() ) == 0 )
663    {
664      name.erase(ResourceManager::getInstance()->getDataDir().size());
665    }
666
667    SYNCHELP_WRITE_STRING( name, NWT_WE_PN_MODELFILENAME );
668  }
669  else
670  {
671    SYNCHELP_WRITE_STRING("", NWT_WE_PN_MODELFILENAME);
672  }
673
674  SYNCHELP_WRITE_FLOAT( scaling, NWT_WE_PN_SCALING );
675  /*if ( this->md2TextureFileName!=NULL && strcmp(this->md2TextureFileName, "") )
676  {
677    SYNCHELP_WRITE_STRING(this->md2TextureFileName);
678  }
679  else
680  {
681    SYNCHELP_WRITE_STRING("");
682  }*/
683
684  return SYNCHELP_WRITE_N;
685}
Note: See TracBrowser for help on using the repository browser.