Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 7186 was 7125, checked in by bensch, 19 years ago

try fix

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