Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 8186 was 8186, checked in by bensch, 18 years ago

trunk: merged the branche bsp_model back here

File size: 15.2 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
272void WorldEntity::toReflectionList()
273{
274  State::getObjectManager()->toReflectionList( this );
275}
276
277void removeFromReflectionList()
278{
279/// TODO
280///  State::getObject
281}
282
283/**
284 * sets the character attributes of a worldentity
285 * @param character attributes
286 *
287 * these attributes don't have to be set, only use them, if you need them
288*/
289//void WorldEntity::setCharacterAttributes(CharacterAttributes* charAttr)
290//{}
291
292
293/**
294 *  this function is called, when two entities collide
295 * @param entity: the world entity with whom it collides
296 *
297 * Implement behaviour like damage application or other miscellaneous collision stuff in this function
298 */
299void WorldEntity::collidesWith(WorldEntity* entity, const Vector& location)
300{
301  /**
302   * THIS IS A DEFAULT COLLISION-Effect.
303   * IF YOU WANT TO CREATE A SPECIFIC COLLISION ON EACH OBJECT
304   * USE::
305   * if (entity->isA(CL_WHAT_YOU_ARE_LOOKING_FOR)) { printf "dothings"; };
306   *
307   * You can always define a default Action.... don't be affraid just test it :)
308   */
309  //  PRINTF(3)("collision %s vs %s @ (%f,%f,%f)\n", this->getClassName(), entity->getClassName(), location.x, location.y, location.z);
310}
311
312
313/**
314 *  this function is called, when two entities collide
315 * @param entity: the world entity with whom it collides
316 *
317 * Implement behaviour like damage application or other miscellaneous collision stuff in this function
318 */
319void WorldEntity::collidesWithGround(const Vector& location)
320{
321  PRINTF(0)("BSP_GROUND: %s collides \n", this->getClassName() );
322}
323
324void WorldEntity::collidesWithGround(const Vector& feet, const Vector& ray_1, const Vector& ray_2)
325{
326 
327  // PRINTF(0)("BSP_GROUND: Player collides \n", this->getClassName() );
328 
329  Vector v = this->getAbsDirX();
330  v.x *= 10;
331  v.y *= 10;
332  v.z *= 10;
333  Vector u = this->getAbsDirY();
334 
335  if(feet.x == (u.x+this->getAbsCoor().x) &&  feet.y == u.y +this->getAbsCoor().y && feet.z == this->getAbsCoor().z)
336  {
337   
338  this->setAbsCoor(ray_2 - v);
339  }
340  else
341  {
342    if(ray_1.x == this->getAbsCoor().x + v.x && ray_1.y == this->getAbsCoor().y + v.y + 0.1 && ray_1.z ==this->getAbsCoor().z + v.z)
343    {
344      this->setAbsCoor(feet -u ); 
345    }
346     
347    this->setAbsCoor(ray_2 - v); 
348   
349  }
350}
351
352/**
353 *  this is called immediately after the Entity has been constructed, initialized and then Spawned into the World
354 *
355 */
356void WorldEntity::postSpawn ()
357{}
358
359
360/**
361 *  this method is called by the world if the WorldEntity leaves the game
362 */
363void WorldEntity::leaveWorld ()
364{}
365
366
367/**
368 * resets the WorldEntity to its initial values. eg. used for multiplayer games: respawning
369 */
370void WorldEntity::reset()
371{}
372
373/**
374 *  this method is called every frame
375 * @param time: the time in seconds that has passed since the last tick
376 *
377 * Handle all stuff that should update with time inside this method (movement, animation, etc.)
378*/
379void WorldEntity::tick(float time)
380{}
381
382
383/**
384 *  the entity is drawn onto the screen with this function
385 *
386 * This is a central function of an entity: call it to let the entity painted to the screen.
387 * Just override this function with whatever you want to be drawn.
388*/
389void WorldEntity::draw() const
390{
391  //PRINTF(0)("(%s::%s)\n", this->getClassName(), this->getName());
392  //  assert(!unlikely(this->models.empty()));
393  {
394    glMatrixMode(GL_MODELVIEW);
395    glPushMatrix();
396
397    /* translate */
398    glTranslatef (this->getAbsCoor ().x,
399                  this->getAbsCoor ().y,
400                  this->getAbsCoor ().z);
401    Vector tmpRot = this->getAbsDir().getSpacialAxis();
402    glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
403
404
405    // This Draws the LOD's
406    float cameraDistance = State::getCamera()->distance(this);
407    if (cameraDistance > 30 && this->models.size() >= 3 && this->models[2] != NULL)
408    {
409      this->models[2]->draw();
410    }
411    else if (cameraDistance > 10 && this->models.size() >= 2 && this->models[1] != NULL)
412    {
413      this->models[1]->draw();
414    }
415    else if (this->models.size() >= 1 && this->models[0] != NULL)
416    {
417      this->models[0]->draw();
418    }
419    glPopMatrix();
420  }
421}
422
423/**
424 * @param health the Health to add.
425 * @returns the health left (this->healthMax - health+this->health)
426 */
427float WorldEntity::increaseHealth(float health)
428{
429  this->health += health;
430  if (this->health > this->healthMax)
431  {
432    float retHealth = this->healthMax - this->health;
433    this->health = this->healthMax;
434    this->updateHealthWidget();
435    return retHealth;
436  }
437  this->updateHealthWidget();
438  return 0.0;
439}
440
441/**
442 * @param health the Health to be removed
443 * @returns 0.0 or the rest, that was not substracted (bellow 0.0)
444 */
445float WorldEntity::decreaseHealth(float health)
446{
447  this->health -= health;
448
449  if (this->health < 0)
450  {
451    float retHealth = -this->health;
452    this->health = 0.0f;
453    this->updateHealthWidget();
454    return retHealth;
455  }
456  this->updateHealthWidget();
457  return 0.0;
458
459}
460
461/**
462 * @param maxHealth the maximal health that can be loaded onto the entity.
463 */
464void WorldEntity::setHealthMax(float healthMax)
465{
466  this->healthMax = healthMax;
467  if (this->health > this->healthMax)
468  {
469    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());
470    this->health = this->healthMax;
471  }
472  this->updateHealthWidget();
473}
474
475/**
476 * @brief creates the HealthWidget
477 *
478 * since not all entities need an HealthWidget, it is only created on request.
479 */
480void WorldEntity::createHealthWidget()
481{
482  if (this->healthWidget == NULL)
483  {
484    this->healthWidget = new OrxGui::GLGuiBar();
485    this->healthWidget->setSize2D(30,400);
486    this->healthWidget->setAbsCoor2D(10,100);
487
488    this->updateHealthWidget();
489  }
490  else
491    PRINTF(3)("Allready created the HealthWidget for %s::%s\n", this->getClassName(), this->getName());
492}
493
494void WorldEntity::increaseHealthMax(float increaseHealth)
495{
496  this->healthMax += increaseHealth;
497  this->updateHealthWidget();
498}
499
500
501OrxGui::GLGuiWidget* WorldEntity::getHealthWidget()
502{
503  this->createHealthWidget();
504  return this->healthWidget;
505}
506
507/**
508 * @param visibility shows or hides the health-bar
509 * (creates the widget if needed)
510 */
511void WorldEntity::setHealthWidgetVisibilit(bool visibility)
512{
513  if (visibility)
514  {
515    if (this->healthWidget != NULL)
516      this->healthWidget->show();
517    else
518    {
519      this->createHealthWidget();
520      this->updateHealthWidget();
521      this->healthWidget->show();
522    }
523  }
524  else if (this->healthWidget != NULL)
525    this->healthWidget->hide();
526}
527
528/**
529 * @brief updates the HealthWidget
530 */
531void WorldEntity::updateHealthWidget()
532{
533  if (this->healthWidget != NULL)
534  {
535    this->healthWidget->setMaximum(this->healthMax);
536    this->healthWidget->setValue(this->health);
537  }
538}
539
540
541/**
542 * DEBUG-DRAW OF THE BV-Tree.
543 * @param depth What depth to draw
544 * @param drawMode the mode to draw this entity under
545 */
546void WorldEntity::drawBVTree(int depth, int drawMode) const
547{
548  glMatrixMode(GL_MODELVIEW);
549  glPushMatrix();
550  /* translate */
551  glTranslatef (this->getAbsCoor ().x,
552                this->getAbsCoor ().y,
553                this->getAbsCoor ().z);
554  /* rotate */
555  Vector tmpRot = this->getAbsDir().getSpacialAxis();
556  glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
557
558
559  if (this->obbTree)
560    this->obbTree->drawBV(depth, drawMode);
561
562
563  glPopMatrix();
564}
565
566
567/**
568 * Debug the WorldEntity
569 */
570void WorldEntity::debugEntity() const
571{
572  PRINT(0)("WorldEntity %s::%s  (DEBUG)\n", this->getClassName(), this->getName());
573  this->debugNode();
574  PRINT(0)("List: %s ; ModelCount %d - ", ObjectManager::OMListToString(this->objectListNumber) , this->models.size());
575  for (unsigned int i = 0; i < this->models.size(); i++)
576  {
577    if (models[i] != NULL)
578      PRINT(0)(" : %d:%s", i, this->models[i]->getName());
579  }
580  PRINT(0)("\n");
581
582}
583
584
585/**
586 * handler for changes on registred vars
587 * @param id id's which changed
588 */
589void WorldEntity::varChangeHandler( std::list< int > & id )
590{
591  if ( std::find( id.begin(), id.end(), modelFileName_handle ) != id.end() ||
592       std::find( id.begin(), id.end(), scaling_handle ) != id.end()
593     )
594  {
595    loadModel( modelFileName, scaling );
596  }
597
598  PNode::varChangeHandler( id );
599}
600
Note: See TracBrowser for help on using the repository browser.