Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

cr: collision objects handling

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