Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 7042 was 7015, checked in by bensch, 19 years ago

orxonox/trunk: flare work

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