Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/world_entities/world_entity.cc @ 7933

Last change on this file since 7933 was 7927, checked in by patrick, 19 years ago

trunk: added more cr framework, i will branche soon with this stuff so the trunk dosn't get involved to much in the development phase

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