Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 7209 was 7198, checked in by bensch, 19 years ago

orxonox/trunk: new Default Values… they now too are in MultiType instead of (count, …) or (count, va_arg) style

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