Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/cr/src/world_entities/world_entity.cc @ 7941

Last change on this file since 7941 was 7937, checked in by patrick, 19 years ago

cr: some more functions prototypes and interface ext

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