Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/cd_merge/src/world_entities/world_entity.cc @ 6890

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

cd_merge: comipiles again. major interface adjustements

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