Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

trunk: merged the network branche back to trunk.

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