Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/orxonox/objects/SpaceShip.cc @ 1401

Last change on this file since 1401 was 1401, checked in by FelixSchulthess, 16 years ago

better this way

File size: 20.8 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Fabian 'x3n' Landau
24 *   Co-authors:
25 *      Benjamin Knecht
26 *
27 */
28
29#include "OrxonoxStableHeaders.h"
30#include "SpaceShip.h"
31
32#include <OgreCamera.h>
33#include <OgreRenderWindow.h>
34#include <OgreParticleSystem.h>
35#include <OgreSceneNode.h>
36
37#include "CameraHandler.h"
38#include "util/Convert.h"
39#include "util/Math.h"
40#include "core/CoreIncludes.h"
41#include "core/ConfigValueIncludes.h"
42#include "core/Debug.h"
43#include "GraphicsEngine.h"
44#include "core/InputManager.h"
45#include "particle/ParticleInterface.h"
46#include "Projectile.h"
47#include "core/XMLPort.h"
48#include "core/ConsoleCommand.h"
49#include "network/Client.h"
50
51namespace orxonox
52{
53    ConsoleCommand(SpaceShip, setMaxSpeedTest, AccessLevel::Debug, false);
54    ConsoleCommand(SpaceShip, whereAmI, AccessLevel::User, true);
55    ConsoleCommandGeneric(test1, SpaceShip, createExecutor(createFunctor(&SpaceShip::setMaxSpeedTest), "setMaxSpeed", AccessLevel::Debug), false);
56    ConsoleCommandGeneric(test2, SpaceShip, createExecutor(createFunctor(&SpaceShip::setMaxSpeedTest), "setMaxBlubber", AccessLevel::Debug), false);
57    ConsoleCommandGeneric(test3, SpaceShip, createExecutor(createFunctor(&SpaceShip::setMaxSpeedTest), "setRofl", AccessLevel::Debug), false);
58
59    CreateFactory(SpaceShip);
60
61    SpaceShip* SpaceShip::instance_s;
62
63    SpaceShip *SpaceShip::getLocalShip(){
64      Iterator<SpaceShip> it;
65      for(it = ObjectList<SpaceShip>::start(); it; ++it){
66        if((it)->server_ || ( network::Client::getSingleton() && network::Client::getSingleton()->getShipID()==it->objectID ) )
67          return *it;
68      }
69      return NULL;
70    }
71
72    SpaceShip::SpaceShip() :
73      //testvector_(0,0,0),
74      //bInvertYAxis_(false),
75      setMouseEventCallback_(false),
76      bLMousePressed_(false),
77      bRMousePressed_(false),
78      camNode_(0),
79      cam_(0),
80      camName_("CamNode"),
81      tt_(0),
82      redNode_(0),
83      greenNode_(0),
84      blinkTime_(0.0f),
85      chNearNode_(0),
86      chFarNode_(0),
87      timeToReload_(0.0f),
88      //reloadTime_(0.0f),
89      maxSideAndBackSpeed_(0.0f),
90      maxSpeed_(0.0f),
91      maxRotation_(0.0f),
92      translationAcceleration_(0.0f),
93      rotationAcceleration_(0.0f),
94      translationDamping_(0.0f),
95      rotationDamping_(0.0f),
96      maxRotationRadian_(0),
97      rotationAccelerationRadian_(0),
98      rotationDampingRadian_(0),
99      zeroRadian_(0),
100      mouseXRotation_(0),
101      mouseYRotation_(0),
102      mouseX_(0.0f),
103      mouseY_(0.0f),
104      emitterRate_(0.0f),
105      server_(false)
106    {
107        RegisterObject(SpaceShip);
108        this->registerAllVariables();
109
110        SpaceShip::instance_s = this;
111
112        this->setConfigValues();
113
114        initialDir_ = Vector3(1.0, 0.0, 0.0);
115        currentDir_ = initialDir_;
116        initialOrth_ = Vector3(0.0, 0.0, 1.0);
117        currentOrth_ = initialOrth_;
118
119        this->setRotationAxis(1, 0, 0);
120        this->setStatic(false);
121
122        COUT(3) << "Info: SpaceShip was loaded" << std::endl;
123    }
124
125    SpaceShip::~SpaceShip()
126    {
127        if (this->tt_)
128            delete this->tt_;
129        if(setMouseEventCallback_)
130          InputManager::removeMouseHandler("SpaceShip");
131        if (this->cam_)
132          delete this->cam_;
133    }
134
135    bool SpaceShip::create(){
136      if(Model::create())
137        this->init();
138      else
139        return false;
140      return true;
141    }
142
143    void SpaceShip::registerAllVariables(){
144      registerVar( &camName_, camName_.length()+1, network::STRING, 0x1);
145      registerVar( &maxSpeed_, sizeof(maxSpeed_), network::DATA, 0x1);
146      registerVar( &maxSideAndBackSpeed_, sizeof(maxSideAndBackSpeed_), network::DATA, 0x1);
147      registerVar( &maxRotation_, sizeof(maxRotation_), network::DATA, 0x1);
148      registerVar( &translationAcceleration_, sizeof(translationAcceleration_), network::DATA, 0x1);
149      registerVar( &rotationAcceleration_, sizeof(rotationAcceleration_), network::DATA, 0x1);
150      registerVar( &rotationAccelerationRadian_, sizeof(rotationAccelerationRadian_), network::DATA, 0x1);
151      registerVar( &translationDamping_, sizeof(translationDamping_), network::DATA, 0x1);
152      registerVar( &rotationDamping_, sizeof(rotationDamping_), network::DATA, 0x1);
153      registerVar( &rotationDampingRadian_, sizeof(rotationDampingRadian_), network::DATA, 0x1);
154
155    }
156
157    void SpaceShip::init()
158    {
159        if ((server_ || ( network::Client::getSingleton() && network::Client::getSingleton()->getShipID()==objectID ) ))
160        {
161              if (!setMouseEventCallback_)
162              {
163                  InputManager::addMouseHandler(this, "SpaceShip");
164                  //InputManager::enableMouseHandler("SpaceShip");
165                  setMouseEventCallback_ = true;
166              }
167        }
168
169        // START CREATING THRUSTER
170        this->tt_ = new ParticleInterface(GraphicsEngine::getSingleton().getSceneManager(),"twinthruster" + this->getName(),"Orxonox/engineglow");
171        this->tt_->getParticleSystem()->setParameter("local_space","true");
172        this->tt_->newEmitter();
173/*
174        this->tt_->setDirection(Vector3(0,0,1));
175        this->tt_->setPositionOfEmitter(0, Vector3(20,-1,-15));
176        this->tt_->setPositionOfEmitter(1, Vector3(-20,-1,-15));
177*/
178        this->tt_->setDirection(Vector3(-1,0,0));
179        this->tt_->setPositionOfEmitter(0, Vector3(-15,20,-1));
180        this->tt_->setPositionOfEmitter(1, Vector3(-15,-20,-1));
181        this->tt_->setVelocity(50);
182
183        emitterRate_ = tt_->getRate();
184
185        Ogre::SceneNode* node2 = this->getNode()->createChildSceneNode(this->getName() + "particle2");
186        node2->setInheritScale(false);
187        tt_->addToSceneNode(node2);
188        // END CREATING THRUSTER
189
190        // START CREATING BLINKING LIGHTS
191        this->redBillboard_.setBillboardSet("Examples/Flare", ColourValue(1.0, 0.0, 0.0), 1);
192        this->greenBillboard_.setBillboardSet("Examples/Flare", ColourValue(0.0, 1.0, 0.0), 1);
193
194        this->redNode_ = this->getNode()->createChildSceneNode(this->getName() + "red", Vector3(0.3, 4.0, -0.3));
195        this->redNode_->setInheritScale(false);
196        this->greenNode_ = this->getNode()->createChildSceneNode(this->getName() + "green", Vector3(0.3, -4.0, -0.3));
197        this->greenNode_->setInheritScale(false);
198
199        this->redNode_->attachObject(this->redBillboard_.getBillboardSet());
200        this->redNode_->setScale(0.3, 0.3, 0.3);
201
202        this->greenNode_->attachObject(this->greenBillboard_.getBillboardSet());
203        this->greenNode_->setScale(0.3, 0.3, 0.3);
204        // END CREATING BLINKING LIGHTS
205
206        // START of testing crosshair
207        this->crosshairNear_.setBillboardSet("Orxonox/Crosshair", ColourValue(1.0, 1.0, 0.0), 1);
208        this->crosshairFar_.setBillboardSet("Orxonox/Crosshair", ColourValue(1.0, 1.0, 0.0), 1);
209
210        this->chNearNode_ = this->getNode()->createChildSceneNode(this->getName() + "near", Vector3(50.0, 0.0, 0.0));
211        this->chNearNode_->setInheritScale(false);
212        this->chFarNode_ = this->getNode()->createChildSceneNode(this->getName() + "far", Vector3(200.0, 0.0, 0.0));
213        this->chFarNode_->setInheritScale(false);
214
215        this->chNearNode_->attachObject(this->crosshairNear_.getBillboardSet());
216        this->chNearNode_->setScale(0.2, 0.2, 0.2);
217
218        this->chFarNode_->attachObject(this->crosshairFar_.getBillboardSet());
219        this->chFarNode_->setScale(0.4, 0.4, 0.4);
220
221        createCamera();
222        // END of testing crosshair
223    }
224
225    void SpaceShip::setConfigValues()
226    {
227        SetConfigValue(bInvertYAxis_, false).description("Set this to true for joystick-like mouse behaviour (mouse up = ship down).");
228        SetConfigValue(reloadTime_, 0.125).description("The reload time of the weapon in seconds");
229        SetConfigValue(testvector_, Vector3()).description("asdfblah");
230    }
231
232    void SpaceShip::setCamera(const std::string& camera)
233    {
234      camName_=camera;
235      // change camera attributes here, if you want to ;)
236    }
237
238    void SpaceShip::getFocus(){
239      COUT(4) << "requesting focus" << std::endl;
240      if(network::Client::getSingleton()==0 || network::Client::getSingleton()->getShipID()==objectID)
241        CameraHandler::getInstance()->requestFocus(cam_);
242
243    }
244
245    Camera* SpaceShip::getCamera(){
246        return cam_;
247    }
248
249    void SpaceShip::createCamera(){
250//       COUT(4) << "begin camera creation" << std::endl;
251      this->camNode_ = this->getNode()->createChildSceneNode(camName_);
252      COUT(4) << "position: (this)" << this->getNode()->getPosition() << std::endl;
253      this->camNode_->setPosition(Vector3(-50,0,10));
254//      Quaternion q1 = Quaternion(Radian(Degree(90)),Vector3(0,-1,0));
255//      Quaternion q2 = Quaternion(Radian(Degree(90)),Vector3(0,0,-1));
256//      camNode_->setOrientation(q1*q2);
257      COUT(4) << "position: (cam)" << this->camNode_->getPosition() << std::endl;
258      cam_ = new Camera(this->camNode_);
259
260      cam_->setTargetNode(this->getNode());
261//        cam->setPosition(Vector3(0,-350,0));
262      Quaternion q1 = Quaternion(Radian(Degree(90)),Vector3(0,-1,0));
263      Quaternion q2 = Quaternion(Radian(Degree(90)),Vector3(1,0,0));
264      camNode_->setOrientation(q2*q1);
265      if(network::Client::getSingleton()!=0 && network::Client::getSingleton()->getShipID()==objectID){
266        this->setBacksync(true);
267        CameraHandler::getInstance()->requestFocus(cam_);
268      }
269
270    }
271
272    void SpaceShip::setMaxSpeed(float value)
273    { this->maxSpeed_ = value; }
274    void SpaceShip::setMaxSideAndBackSpeed(float value)
275    { this->maxSideAndBackSpeed_ = value; }
276    void SpaceShip::setMaxRotation(float value)
277    { this->maxRotation_ = value; this->maxRotationRadian_ = Radian(value); }
278    void SpaceShip::setTransAcc(float value)
279    { this->translationAcceleration_ = value; }
280    void SpaceShip::setRotAcc(float value)
281    { this->rotationAcceleration_ = value; this->rotationAccelerationRadian_ = Radian(value); }
282    void SpaceShip::setTransDamp(float value)
283    { this->translationDamping_ = value; }
284    void SpaceShip::setRotDamp(float value)
285    { this->rotationDamping_ = value; this->rotationDampingRadian_ = Radian(value); }
286
287    /**
288        @brief XML loading and saving.
289        @param xmlelement The XML-element
290        @param loading Loading (true) or saving (false)
291        @return The XML-element
292    */
293    void SpaceShip::XMLPort(Element& xmlelement, XMLPort::Mode mode)
294    {
295        Model::XMLPort(xmlelement, mode);
296
297        XMLPortParamLoadOnly(SpaceShip, "camera", setCamera, xmlelement, mode);
298        XMLPortParamLoadOnly(SpaceShip, "maxSpeed", setMaxSpeed, xmlelement, mode);
299        XMLPortParamLoadOnly(SpaceShip, "maxSideAndBackSpeed", setMaxSideAndBackSpeed, xmlelement, mode);
300        XMLPortParamLoadOnly(SpaceShip, "maxRotation", setMaxRotation, xmlelement, mode);
301        XMLPortParamLoadOnly(SpaceShip, "transAcc", setTransAcc, xmlelement, mode);
302        XMLPortParamLoadOnly(SpaceShip, "rotAcc", setRotAcc, xmlelement, mode);
303        XMLPortParamLoadOnly(SpaceShip, "transDamp", setTransDamp, xmlelement, mode);
304        XMLPortParamLoadOnly(SpaceShip, "rotDamp", setRotDamp, xmlelement, mode);
305        server_=true; // TODO: this is only a hack
306        SpaceShip::create();
307        getFocus();
308    }
309
310    int sgn(float x)
311    {
312        if (x >= 0)
313            return 1;
314        else
315            return -1;
316    }
317
318    void SpaceShip::mouseMoved(IntVector2 abs, IntVector2 rel, IntVector2 clippingSize)
319    {
320/*
321        this->mouseX += e.state.X.rel;
322        if (this->bInvertMouse_)
323            this->mouseY += e.state.Y.rel;
324        else
325            this->mouseY -= e.state.Y.rel;
326
327//        if(mouseX>maxMouseX) maxMouseX = mouseX;
328//        if(mouseX<minMouseX) minMouseX = mouseX;
329//        cout << "mouseX: " << mouseX << "\tmouseY: " << mouseY << endl;
330
331        this->moved = true;
332*/
333        if (this->bRMousePressed_)
334        {
335            this->camNode_->roll(Degree(-rel.x * 0.10));
336            this->camNode_->yaw(Degree(rel.y * 0.10));
337        }
338        else
339        {
340            float minDimension = clippingSize.y;
341            if (clippingSize.x < minDimension)
342                minDimension = clippingSize.x;
343
344            this->mouseX_ += rel.x;
345            if (this->mouseX_ < -minDimension)
346                this->mouseX_ = -minDimension;
347            if (this->mouseX_ > minDimension)
348                this->mouseX_ = minDimension;
349
350            this->mouseY_ += rel.y;
351            if (this->mouseY_ < -minDimension)
352                this->mouseY_ = -minDimension;
353            if (this->mouseY_ > minDimension)
354                this->mouseY_ = minDimension;
355
356            float xRotation = this->mouseX_ / minDimension;
357            xRotation = xRotation*xRotation * sgn(xRotation);
358            xRotation *= -this->rotationAcceleration_;
359            if (xRotation > this->maxRotation_)
360                xRotation = this->maxRotation_;
361            if (xRotation < -this->maxRotation_)
362                xRotation = -this->maxRotation_;
363            this->mouseXRotation_ = Radian(xRotation);
364
365            float yRotation = this->mouseY_ / minDimension;
366            yRotation = yRotation*yRotation * sgn(yRotation);
367            yRotation *= this->rotationAcceleration_;
368            if (yRotation > this->maxRotation_)
369                yRotation = this->maxRotation_;
370            if (yRotation < -this->maxRotation_)
371                yRotation = -this->maxRotation_;
372            this->mouseYRotation_ = Radian(yRotation);
373        }
374    }
375
376    void SpaceShip::mouseButtonPressed(MouseButton::Enum id)
377    {
378        if (id == MouseButton::Left)
379            this->bLMousePressed_ = true;
380        else if (id == MouseButton::Right)
381            this->bRMousePressed_ = true;
382    }
383
384    void SpaceShip::mouseButtonReleased(MouseButton::Enum id)
385    {
386        if (id == MouseButton::Left)
387            this->bLMousePressed_ = false;
388        else if (id == MouseButton::Right)
389        {
390            this->bRMousePressed_ = false;
391            this->camNode_->resetOrientation();
392        }
393    }
394
395    std::string SpaceShip::whereAmI() {
396        return getConvertedValue<float, std::string>(SpaceShip::getLocalShip()->getPosition().x)
397        + "  " + getConvertedValue<float, std::string>(SpaceShip::getLocalShip()->getPosition().y)
398        + "  " + getConvertedValue<float, std::string>(SpaceShip::getLocalShip()->getPosition().z);
399    }
400
401    Vector3 SpaceShip::getDir() {
402        return currentDir_;
403    }
404
405    Vector3 SpaceShip::getOrth(){
406        return currentOrth_;
407    }
408
409    float SpaceShip::getMaxSpeed() { return maxSpeed_; }
410
411    void SpaceShip::tick(float dt)
412    {
413        currentDir_ = getOrientation()*initialDir_;
414                currentOrth_ = getOrientation()*initialOrth_;
415
416        if (this->cam_)
417            this->cam_->tick(dt);
418
419        if (this->redNode_ && this->greenNode_)
420        {
421            this->blinkTime_ += dt;
422            float redScale = 0.15 + 0.15 * sin(this->blinkTime_ * 10.0);
423            float greenScale = 0.15 - 0.15 * sin(this->blinkTime_ * 10.0);
424            this->redNode_->setScale(redScale, redScale, redScale);
425            this->greenNode_->setScale(greenScale, greenScale, greenScale);
426        }
427
428        if (this->timeToReload_ > 0)
429            this->timeToReload_ -= dt;
430        else
431            this->timeToReload_ = 0;
432
433        if (this->bLMousePressed_ && this->timeToReload_ <= 0)
434        {
435
436            Projectile *p = new Projectile(this);
437
438            p->setBacksync(true);
439            this->timeToReload_ = this->reloadTime_;
440        }
441
442
443        // #####################################
444        // ############# STEERING ##############
445        // #####################################
446
447        if (this->velocity_.x > this->maxSpeed_)
448            this->velocity_.x = this->maxSpeed_;
449        if (this->velocity_.x < -this->maxSideAndBackSpeed_)
450            this->velocity_.x = -this->maxSideAndBackSpeed_;
451        if (this->velocity_.y > this->maxSideAndBackSpeed_)
452            this->velocity_.y = this->maxSideAndBackSpeed_;
453        if (this->velocity_.y < -this->maxSideAndBackSpeed_)
454            this->velocity_.y = -this->maxSideAndBackSpeed_;
455        if (this->rotationRate_ > this->maxRotationRadian_)
456            this->rotationRate_ = this->maxRotationRadian_;
457        if (this->rotationRate_ < -this->maxRotationRadian_)
458            this->rotationRate_ = -this->maxRotationRadian_;
459
460        if (this->acceleration_.x == 0)
461        {
462            if (this->velocity_.x > 0)
463            {
464                this->velocity_.x -= (this->translationDamping_ * dt);
465                if (this->velocity_.x < 0)
466                    this->velocity_.x = 0;
467            }
468            else if (this->velocity_.x < 0)
469            {
470                this->velocity_.x += (this->translationDamping_ * dt);
471                if (this->velocity_.x > 0)
472                    this->velocity_.x = 0;
473            }
474        }
475
476        if (this->acceleration_.y == 0)
477        {
478            if (this->velocity_.y > 0)
479            {
480                this->velocity_.y -= (this->translationDamping_ * dt);
481                if (this->velocity_.y < 0)
482                    this->velocity_.y = 0;
483            }
484            else if (this->velocity_.y < 0)
485            {
486                this->velocity_.y += (this->translationDamping_ * dt);
487                if (this->velocity_.y > 0)
488                    this->velocity_.y = 0;
489            }
490        }
491
492        if (this->momentum_ == this->zeroRadian_)
493        {
494            if (this->rotationRate_ > this->zeroRadian_)
495            {
496                this->rotationRate_ -= (this->rotationDampingRadian_ * dt);
497                if (this->rotationRate_ < this->zeroRadian_)
498                    this->rotationRate_ = 0;
499            }
500            else if (this->rotationRate_ < this->zeroRadian_)
501            {
502                this->rotationRate_ += (this->rotationDampingRadian_ * dt);
503                if (this->rotationRate_ > this->zeroRadian_)
504                    this->rotationRate_ = 0;
505            }
506        }
507
508        if( (network::Client::getSingleton() &&  network::Client::getSingleton()->getShipID() == objectID) || server_ )
509        {
510          COUT(4) << "steering our ship: " << objectID << std::endl;
511          if (InputManager::isKeyDown(KeyCode::Up) || InputManager::isKeyDown(KeyCode::W))
512            this->acceleration_.x = this->translationAcceleration_;
513          else if(InputManager::isKeyDown(KeyCode::Down) || InputManager::isKeyDown(KeyCode::S))
514            this->acceleration_.x = -this->translationAcceleration_;
515          else
516            this->acceleration_.x = 0;
517
518          if (InputManager::isKeyDown(KeyCode::Right) || InputManager::isKeyDown(KeyCode::D))
519            this->acceleration_.y = -this->translationAcceleration_;
520          else if (InputManager::isKeyDown(KeyCode::Left) || InputManager::isKeyDown(KeyCode::A))
521            this->acceleration_.y = this->translationAcceleration_;
522          else
523            this->acceleration_.y = 0;
524
525          if (InputManager::isKeyDown(KeyCode::Delete) || InputManager::isKeyDown(KeyCode::Q))
526            this->momentum_ = Radian(-this->rotationAccelerationRadian_);
527          else if (InputManager::isKeyDown(KeyCode::PageDown) || InputManager::isKeyDown(KeyCode::E))
528            this->momentum_ = Radian(this->rotationAccelerationRadian_);
529          else
530            this->momentum_ = 0;
531        }/*else
532          COUT(4) << "not steering ship: " << objectID << " our ship: " << network::Client::getSingleton()->getShipID() << std::endl;*/
533
534        WorldEntity::tick(dt);
535
536        this->roll(this->mouseXRotation_ * dt);
537        if (this->bInvertYAxis_)
538            this->yaw(Radian(-this->mouseYRotation_ * dt));
539        else
540            this->yaw(Radian(this->mouseYRotation_ * dt));
541
542        if (this->acceleration_.x > 0)
543            this->tt_->setRate(emitterRate_);
544        else
545            this->tt_->setRate(0);
546    }
547
548}
Note: See TracBrowser for help on using the repository browser.