Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/network/src/world_entities/world_entity.cc @ 7446

Last change on this file since 7446 was 7446, checked in by rennerc, 18 years ago

implemented some varChangeHandler functions

File size: 13.6 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
34using namespace std;
35
36SHELL_COMMAND(model, WorldEntity, loadModel)
37->describe("sets the Model of the WorldEntity")
38->defaultValues("models/ships/fighter.obj", 1.0);
39
40SHELL_COMMAND(debugEntity, WorldEntity, debugWE);
41
42/**
43 *  Loads the WordEntity-specific Part of any derived Class
44 *
45 * @param root: Normally NULL, as the Derived Entities define a loadParams Function themeselves,
46 *              that can calls WorldEntities loadParams for itself.
47 */
48WorldEntity::WorldEntity()
49    : Synchronizeable()
50{
51  this->setClassID(CL_WORLD_ENTITY, "WorldEntity");
52
53  this->obbTree = NULL;
54  this->healthWidget = NULL;
55  this->healthMax = 1.0f;
56  this->health = 1.0f;
57  this->scaling = 1.0f;
58
59  /* OSOLETE */
60  this->bVisible = true;
61  this->bCollide = true;
62
63  this->objectListNumber = OM_INIT;
64  this->objectListIterator = NULL;
65
66  this->toList(OM_NULL);
67 
68  modelFileName_handle = registerVarId( new SynchronizeableString( &modelFileName, &modelFileName, "modelFileName" ) );
69  scaling_handle = registerVarId( new SynchronizeableFloat( &scaling, &scaling, "scaling" ) );
70}
71
72/**
73 *  standard destructor
74*/
75WorldEntity::~WorldEntity ()
76{
77  State::getObjectManager()->toList(this, OM_INIT);
78
79  // Delete the model (unregister it with the ResourceManager)
80  for (unsigned int i = 0; i < this->models.size(); i++)
81    this->setModel(NULL, i);
82
83  // Delete the obbTree
84  if( this->obbTree != NULL)
85    delete this->obbTree;
86
87  if (this->healthWidget != NULL)
88    delete this->healthWidget;
89}
90
91/**
92 * loads the WorldEntity Specific Parameters.
93 * @param root: the XML-Element to load the Data From
94 */
95void WorldEntity::loadParams(const TiXmlElement* root)
96{
97  // Do the PNode loading stuff
98  PNode::loadParams(root);
99
100  LoadParam(root, "md2texture", this, WorldEntity, loadMD2Texture)
101  .describe("the fileName of the texture, that should be loaded onto this world-entity. (must be relative to the data-dir)")
102  .defaultValues("");
103
104  // Model Loading
105  LoadParam(root, "model", this, WorldEntity, loadModel)
106  .describe("the fileName of the model, that should be loaded onto this world-entity. (must be relative to the data-dir)")
107  .defaultValues("", 1.0f, 0);
108
109  LoadParam(root, "maxHealth", this, WorldEntity, setHealthMax)
110  .describe("The Maximum health that can be loaded onto this entity")
111  .defaultValues(1.0f);
112
113  LoadParam(root, "health", this, WorldEntity, setHealth)
114  .describe("The Health the WorldEntity has at this moment")
115  .defaultValues(1.0f);
116}
117
118
119/**
120 * loads a Model onto a WorldEntity
121 * @param fileName the name of the model to load
122 * @param scaling the Scaling of the model
123 */
124void WorldEntity::loadModel(const std::string& fileName, float scaling, unsigned int modelNumber)
125{
126  this->modelLODName = fileName;
127  this->scaling = scaling;
128 
129  std::string name = fileName;
130
131  if (  name.find( ResourceManager::getInstance()->getDataDir() ) == 0 ) 
132  {
133    name.erase(ResourceManager::getInstance()->getDataDir().size());
134  }
135
136  this->modelFileName = name;
137 
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(4);
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(4);
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(unsigned int depth)
223{
224  if (this->obbTree)
225    delete this->obbTree;
226
227  if (this->models[0] != NULL)
228  {
229    PRINTF(4)("creating obb tree\n");
230
231
232    this->obbTree = new OBBTree(depth, (sVec3D*)this->models[0]->getVertexArray(), this->models[0]->getVertexCount());
233    return true;
234  }
235  else
236  {
237    PRINTF(2)("could not create obb-tree, because no model was loaded yet\n");
238    this->obbTree = NULL;
239    return false;
240  }
241}
242
243/**
244 * @brief moves this entity to the List OM_List
245 * @param list the list to set this Entity to.
246 *
247 * this is the same as a call to State::getObjectManager()->toList(entity , list);
248 * directly, but with an easier interface.
249 *
250 * @todo inline this (peut etre)
251 */
252void WorldEntity::toList(OM_LIST list)
253{
254  State::getObjectManager()->toList(this, list);
255}
256
257
258
259/**
260 * sets the character attributes of a worldentity
261 * @param character attributes
262 *
263 * these attributes don't have to be set, only use them, if you need them
264*/
265//void WorldEntity::setCharacterAttributes(CharacterAttributes* charAttr)
266//{}
267
268
269/**
270 *  this function is called, when two entities collide
271 * @param entity: the world entity with whom it collides
272 *
273 * Implement behaviour like damage application or other miscellaneous collision stuff in this function
274 */
275void WorldEntity::collidesWith(WorldEntity* entity, const Vector& location)
276{
277  /**
278   * THIS IS A DEFAULT COLLISION-Effect.
279   * IF YOU WANT TO CREATE A SPECIFIC COLLISION ON EACH OBJECT
280   * USE::
281   * if (entity->isA(CL_WHAT_YOU_ARE_LOOKING_FOR)) { printf "dothings"; };
282   *
283   * You can always define a default Action.... don't be affraid just test it :)
284   */
285  //  PRINTF(3)("collision %s vs %s @ (%f,%f,%f)\n", this->getClassName(), entity->getClassName(), location.x, location.y, location.z);
286}
287
288
289/**
290 *  this is called immediately after the Entity has been constructed, initialized and then Spawned into the World
291 *
292 */
293void WorldEntity::postSpawn ()
294{}
295
296
297/**
298 *  this method is called by the world if the WorldEntity leaves the game
299 */
300void WorldEntity::leaveWorld ()
301{}
302
303
304/**
305 * resets the WorldEntity to its initial values. eg. used for multiplayer games: respawning
306 */
307void WorldEntity::reset()
308{}
309
310/**
311 *  this method is called every frame
312 * @param time: the time in seconds that has passed since the last tick
313 *
314 * Handle all stuff that should update with time inside this method (movement, animation, etc.)
315*/
316void WorldEntity::tick(float time)
317{}
318
319
320/**
321 *  the entity is drawn onto the screen with this function
322 *
323 * This is a central function of an entity: call it to let the entity painted to the screen.
324 * Just override this function with whatever you want to be drawn.
325*/
326void WorldEntity::draw() const
327{
328  //PRINTF(0)("(%s::%s)\n", this->getClassName(), this->getName());
329  //  assert(!unlikely(this->models.empty()));
330  {
331    glMatrixMode(GL_MODELVIEW);
332    glPushMatrix();
333
334    /* translate */
335    glTranslatef (this->getAbsCoor ().x,
336                  this->getAbsCoor ().y,
337                  this->getAbsCoor ().z);
338    Vector tmpRot = this->getAbsDir().getSpacialAxis();
339    glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
340
341
342    // This Draws the LOD's
343    float cameraDistance = State::getCamera()->distance(this);
344    if (cameraDistance > 30 && this->models.size() >= 3 && this->models[2] != NULL)
345    {
346      this->models[2]->draw();
347    }
348    else if (cameraDistance > 10 && this->models.size() >= 2 && this->models[1] != NULL)
349    {
350      this->models[1]->draw();
351    }
352    else if (this->models.size() >= 1 && this->models[0] != NULL)
353    {
354      this->models[0]->draw();
355    }
356    glPopMatrix();
357  }
358}
359
360/**
361 * @param health the Health to add.
362 * @returns the health left (this->healthMax - health+this->health)
363 */
364float WorldEntity::increaseHealth(float health)
365{
366  this->health += health;
367  if (this->health > this->healthMax)
368  {
369    float retHealth = this->healthMax - this->health;
370    this->health = this->healthMax;
371    this->updateHealthWidget();
372    return retHealth;
373  }
374  this->updateHealthWidget();
375  return 0.0;
376}
377
378/**
379 * @param health the Health to be removed
380 * @returns 0.0 or the rest, that was not substracted (bellow 0.0)
381 */
382float WorldEntity::decreaseHealth(float health)
383{
384  this->health -= health;
385
386  if (this->health < 0)
387  {
388    float retHealth = -this->health;
389    this->health = 0.0f;
390    this->updateHealthWidget();
391    return retHealth;
392  }
393  this->updateHealthWidget();
394  return 0.0;
395
396}
397
398/**
399 * @param maxHealth the maximal health that can be loaded onto the entity.
400 */
401void WorldEntity::setHealthMax(float healthMax)
402{
403  this->healthMax = healthMax;
404  if (this->health > this->healthMax)
405  {
406    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());
407    this->health = this->healthMax;
408  }
409  this->updateHealthWidget();
410}
411
412/**
413 * @brief creates the HealthWidget
414 *
415 * since not all entities need an HealthWidget, it is only created on request.
416 */
417void WorldEntity::createHealthWidget()
418{
419  if (this->healthWidget == NULL)
420  {
421    this->healthWidget = new GLGuiBar();
422    this->healthWidget->setSize2D(30,400);
423    this->healthWidget->setAbsCoor2D(10,100);
424
425    this->updateHealthWidget();
426  }
427  else
428    PRINTF(3)("Allready created the HealthWidget for %s::%s\n", this->getClassName(), this->getName());
429}
430
431void WorldEntity::increaseHealthMax(float increaseHealth)
432{
433  this->healthMax += increaseHealth;
434  this->updateHealthWidget();
435}
436
437
438GLGuiWidget* WorldEntity::getHealthWidget()
439{
440  this->createHealthWidget();
441  return this->healthWidget;
442}
443
444/**
445 * @param visibility shows or hides the health-bar
446 * (creates the widget if needed)
447 */
448void WorldEntity::setHealthWidgetVisibilit(bool visibility)
449{
450  if (visibility)
451  {
452    if (this->healthWidget != NULL)
453      this->healthWidget->show();
454    else
455    {
456      this->createHealthWidget();
457      this->updateHealthWidget();
458      this->healthWidget->show();
459    }
460  }
461  else if (this->healthWidget != NULL)
462    this->healthWidget->hide();
463}
464
465/**
466 * @brief updates the HealthWidget
467 */
468void WorldEntity::updateHealthWidget()
469{
470  if (this->healthWidget != NULL)
471  {
472    this->healthWidget->setMaximum(this->healthMax);
473    this->healthWidget->setValue(this->health);
474  }
475}
476
477
478/**
479 * DEBUG-DRAW OF THE BV-Tree.
480 * @param depth What depth to draw
481 * @param drawMode the mode to draw this entity under
482 */
483void WorldEntity::drawBVTree(unsigned int depth, int drawMode) const
484{
485  glMatrixMode(GL_MODELVIEW);
486  glPushMatrix();
487  /* translate */
488  glTranslatef (this->getAbsCoor ().x,
489                this->getAbsCoor ().y,
490                this->getAbsCoor ().z);
491  /* rotate */
492  Vector tmpRot = this->getAbsDir().getSpacialAxis();
493  glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
494
495  if (this->obbTree)
496    this->obbTree->drawBV(depth, drawMode);
497  glPopMatrix();
498}
499
500
501/**
502 * Debug the WorldEntity
503 */
504void WorldEntity::debugEntity() const
505{
506  PRINT(0)("WorldEntity %s::%s  (DEBUG)\n", this->getClassName(), this->getName());
507  this->debugNode();
508  PRINT(0)("List: %s ; ModelCount %d - ", ObjectManager::OMListToString(this->objectListNumber) , this->models.size());
509  for (unsigned int i = 0; i < this->models.size(); i++)
510  {
511    if (models[i] != NULL)
512      PRINT(0)(" : %d:%s", i, this->models[i]->getName());
513  }
514  PRINT(0)("\n");
515
516}
517
518
519/**
520 * handler for changes on registred vars
521 * @param id id's which changed
522 */
523void WorldEntity::varChangeHandler( std::list< int > & id )
524{
525  if ( std::find( id.begin(), id.end(), modelFileName_handle ) != id.end() ||
526       std::find( id.begin(), id.end(), scaling_handle ) != id.end()
527     )
528  {
529    loadModel( modelFileName, scaling );
530  }
531 
532  PNode::varChangeHandler( id );
533}
Note: See TracBrowser for help on using the repository browser.