Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

trunk: entity is reset now after death

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