Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/AsteroidMining_HS17/src/modules/asteroidmining/AsteroidMinable.cc @ 11581

Last change on this file since 11581 was 11581, checked in by remartin, 6 years ago

Doesn-t freeze any more. Asteroids and the pickup seem to collide with things they shouldn-t.

File size: 18.2 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 *      Simon Miescher
26 *
27 */
28
29/*
30
31*
32*
33* An asteroid which can be destroyed. Some smaller asteroids are created and a pickup
34* spawns.
35*
36*
37*
38
39*/
40
41/*
42Veraenderungstagebuch
43++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
44
45KNACKPUNKTE:
46o Collision Shape-Problem (Funktioniert nur, wenn im Konstruktor) -> Mit Factory-Methode oder so basteln.
47o Maximale Hitpunkte = 200?
48
49o Neue Asteroiden generieren -> Absturz
50--> Kollidiert sofort mit irgendetwas, death() wird mehrfach aufgerufen.
51--> Funktioniert der Test in den hit()-Methoden?
52--> Welcher Aufruf loest die death()-Methode auf?
53
54
55
56OFFEN:
57o Add custom pickup 'resources'. Weird template stuff -> Problems setting 'size' and other properties? setNumber of Resources.
58o Explosion parts
59o custom HUD
60
61HANDBUCH:
62o im Level-File includes/pickups.oxi importieren.
63
64Anpassungen Pickup-Zeug:
65o Pickup.h: Zugriffsänderung createSpawner
66o PickupSpawner.h: Zugriffsrechte setPickupTemplateName() und setMaxSpawnedItems()
67
68ERLEGT:
69o Rand() geht bis zu riesigen Nummern!
70o Pickupgenerierung: vgl. Anpassungen.
71o Dummes fisch-- statt fisch++ , Endlosschleife!
72o Dynamische Definition -> putStuff-Methode, Werte noch nicht durchgesickert.
73o Error-Nachricht: Einfach Argumente leer lassen.
74o Pickups: setMaxSpawned funktioniert nicht -> Bastelloesung: Auf 2 statt eins setzen, erstes wird wohl direkt zerstoert.
75*/
76
77
78#include "../../orxonox/worldentities/pawns/Pawn.h"
79#include "../../orxonox/worldentities/WorldEntity.h"
80
81#include "AsteroidMinable.h"
82
83#include <algorithm>
84
85#include "core/CoreIncludes.h"
86#include "core/GameMode.h"
87#include "core/XMLPort.h"
88#include "core/EventIncludes.h"
89#include "network/NetworkFunction.h"
90
91// #include "infos/PlayerInfo.h"
92// #include "controllers/Controller.h"
93// #include "gametypes/Gametype.h"
94// #include "graphics/ParticleSpawner.h"
95// #include "worldentities/ExplosionChunk.h"
96// #include "worldentities/ExplosionPart.h"
97
98// #include "core/object/ObjectListIterator.h"
99// #include "controllers/FormationController.h"
100
101#include "../pickup/items/HealthPickup.h"
102#include "../pickup/PickupSpawner.h"
103#include "../pickup/Pickup.h"
104//#include "../pickup/pickup ..... pickupable
105#include "../objects/collisionshapes/SphereCollisionShape.h"
106#include "../../orxonox/graphics/Model.h"
107
108
109
110
111
112
113namespace orxonox
114{
115    RegisterClass(AsteroidMinable);
116
117    AsteroidMinable::AsteroidMinable(Context* context) : Pawn(context)
118    {
119        RegisterObject(AsteroidMinable);
120
121        // Old stuff from pawn
122        this->setRadarObjectColour(ColourValue(1.0f, 1.0f, 0.0f, 1.0f));
123        this->setRadarObjectShape(RadarViewable::Shape::Dot);
124        this->setCollisionType(WorldEntity::CollisionType::Dynamic);
125        this->bAlive_ = true;
126
127        this->bVulnerable_ = true;
128        this->enableCollisionCallback();
129
130        // Default Values
131        this->generateSmaller = true; 
132        //this->setHealth(50);
133        this->size = 10; // customSize
134        this->context = context;
135        this->initialised = false;
136        //this->roll = rand()*5; //etwas Drehung. richtige Variable
137//this = new AsteroidMinable()
138
139
140
141        // DELETE if other stuff works! (wrong size etc.)
142        SphereCollisionShape* cs = new SphereCollisionShape(this->context);
143        cs->setRadius((this->size)*2); //OFFEN: Feinabstimmung der Radien
144        this->attachCollisionShape(cs); 
145
146
147
148
149        // Old from Pawn
150        this->registerVariables();
151
152        orxout() << "AsteroidMining:: Konstruktor passiert!" << endl;
153
154    }
155
156    AsteroidMinable::~AsteroidMinable()
157    {
158
159    }
160
161    void AsteroidMinable::putStuff(){
162
163        // Add Model
164        //<Model position="0,-40,40" yaw="90" pitch="-90" roll="0" scale="4" mesh="ast6.mesh" />
165        Model* hull = new Model(this->context);
166        // random one of the 6 shapes
167        char meshThingy[] = "";
168        sprintf(meshThingy, "ast%.0f.mesh", (round((5*(double)rand()/(double)RAND_MAX))+1)); //    sprintf(str, "Value of Pi = %f", M_PI);
169        hull->setMeshSource(meshThingy);
170        hull->setScale(this->size);
171        this->attach(hull);
172
173        // Collision shape
174        SphereCollisionShape* cs = new SphereCollisionShape(this->context);
175        cs->setRadius((this->size)*2); //OFFEN: Feinabstimmung der Radien. 2.5 in AsteroidField.lua
176        this->attachCollisionShape(cs); 
177
178
179        this->initialised=true; 
180
181        orxout() << "AsteroidMining:: Initialisierung abgeschlosssssen." << endl;
182
183    }
184
185    void AsteroidMinable::XMLPort(Element& xmlelement, XMLPort::Mode mode)
186    {
187        SUPER(AsteroidMinable, XMLPort, xmlelement, mode);
188        //        XMLPortParam(PickupSpawner, "pickup", setPickupTemplateName, getPickupTemplateName, xmlelement, mode);
189        XMLPortParam(AsteroidMinable, "size", setSize, getSize, xmlelement, mode);
190
191    }
192
193    void AsteroidMinable::XMLEventPort(Element& xmlelement, XMLPort::Mode mode)
194    {
195        SUPER(AsteroidMinable, XMLEventPort, xmlelement, mode);
196
197        XMLPortEventState(AsteroidMinable, BaseObject, "vulnerability", setVulnerable, xmlelement, mode);
198    }
199
200    void AsteroidMinable::registerVariables()
201    {
202        registerVariable(this->bAlive_,            VariableDirection::ToClient);
203        registerVariable(this->bVulnerable_,       VariableDirection::ToClient);
204        registerVariable(this->health_,            VariableDirection::ToClient);
205        registerVariable(this->maxHealth_,         VariableDirection::ToClient);
206
207        registerVariable(this->size, VariableDirection::ToClient);
208        registerVariable(this->generateSmaller, VariableDirection::ToClient);
209
210        registerVariable(this->initialised, VariableDirection::ToClient);
211        //registerVariable(this->context, VariableDirection::ToClient); // can't link that since it's a context
212
213
214            //         float size;
215            // bool generateSmaller;
216            // bool initialised;
217
218            // Context* context;
219    }
220
221    void AsteroidMinable::tick(float dt)
222    {
223        // SUPER(Pawn, tick, dt);
224        if(!(this->initialised)){this->putStuff();}
225
226        if(this->health_ <=0){this->death();}
227
228    }
229
230    void AsteroidMinable::setSize(float s){
231        this->size = s;
232        this->health_ = 5*s;// capped at 200 in pawn or smth?
233        this->setHealth(health_);
234    }
235
236    float AsteroidMinable::getSize(){
237        return this->size;
238    }
239
240    void AsteroidMinable::death() //ueberschreiben
241    {
242
243        orxout() << "AsteroidMinable::Death() aufgerufen." << endl;
244
245        // OFFEN: Sauber kapputten
246        // just copied other stuff:
247        // this->setHealth(1);
248        this->bAlive_ = false;
249        this->destroyLater();
250        this->setDestroyWhenPlayerLeft(false);
251        // pawn -> addExplosionPart
252        // this->goWithStyle();
253
254
255        // // Stuff that can be harvested.
256        // PickupSpawner* thingy = new PickupSpawner(this->context);
257
258        // // OFFEN: more precise size relation in custom resource pickup.
259        // char tname[] = ""; // can-t overwrite strings easily in C (strcat etc.)
260        // if(this->size <= 5){
261        //     strcat(tname, "smallmunitionpickup");
262        // }else if(this->size <= 20){
263        //     strcat(tname, "mediummunitionpickup");
264        // }else{
265        //     strcat(tname, "hugemunitionpickup");
266        // }
267        // thingy->setPickupTemplateName(tname);
268        // thingy->setPosition(this->getPosition());
269        // thingy->setMaxSpawnedItems(2); // The first somehow gets destroyed immediately.
270        // thingy->setRespawnTime(0.5f);
271
272        // orxout() << "AsteroidMining::Death(): Passed Pickup stuff!" << endl;
273
274
275        // Smaller Parts = 'Children'
276        if(this->generateSmaller){
277            this->spawnChildren();
278        }
279
280
281
282
283
284
285
286
287        orxout() << "Wieder retour in death() geschafft. " << endl;
288
289        // if (this->getGametype() && this->getGametype()->allowPawnDeath(this, this->lastHitOriginator_))
290        // {
291        //     // Set bAlive_ to false and wait for destroyLater() to do the destruction
292        //     this->bAlive_ = false;
293        //     this->destroyLater();
294
295        //     this->setDestroyWhenPlayerLeft(false);
296
297        // }
298    }
299
300
301void AsteroidMinable::spawnChildren(){
302   
303    if (this->size <=1){return;} // Absicherung trivialer Fall
304
305
306
307    // Spawn smaller Children
308    int massRem = this->size-1; //some mass is lost
309    int num = round((massRem-1)*(double)rand() / (double)RAND_MAX)+1; // random number of children, at least one // Tweak towards bigger junks?
310    num = 1; // zum Testen mal nur einen generieren.
311   
312    massRem = massRem-num;   
313    int extra = 0;
314
315
316    //orxout() << "Number of Children: " << num << endl;
317
318
319    for(int fisch=num; fisch>=1; --fisch){
320        // to distribute remaining mass
321
322        //orxout() << "AsteroidMining::spawnChildren(): Fisch-Variable: " << fisch << endl;
323
324        if(fisch==1){ 
325            extra = massRem;
326        }else{
327            extra = round(massRem*(double)rand() / (double)RAND_MAX);
328            massRem = massRem-extra;
329
330        }
331
332        //orxout() << "Mass chosen: " << extra+1 << endl;
333
334        //orxout() << "AsteroidMining::spawnChildren(): Inside for-loop." << endl;
335
336        //Spawn this child  Game crashes!
337        AsteroidMinable* child = new AsteroidMinable(this->context);
338        // if(!(child == nullptr)){//Errorgebastel
339
340        // Position zu spaet gesetzt? Tick nicht atomar -> falsche Groesse evtl?
341
342        if(child == nullptr){
343            orxout(internal_error, context::pickups) << "Weird, can't create new AsteroidMinable." << endl;
344        }
345
346        child->setSize(extra + 1);
347               
348            //OFFEN:Kollision der Kinder verhindern
349            //Relativ zu Elternteil automatisch?
350            //Typ position:rand()*Vektoriwas?
351            //pawn->getWorldPosition() + Vector3(30,0,-30);
352        child->setPosition(this->getPosition() + Vector3(num*5, 0, 0));
353        //child->setPosition(Vector3(0,0,0));
354
355        //orxout() << "Done: Creating new Asteroid" << endl;
356
357        // }
358
359
360                //         Pawn* pawn = this->carrierToPawnHelper();
361                // if(pawn == nullptr) // If the PickupCarrier is no Pawn, then this pickup is useless and therefore is destroyed.
362                //     this->Pickupable::destroy();
363
364                // //Attach to pawn
365                // Drone* drone = new Drone(pawn->getContext()); // this is neccessary because the projectiles fired need a valid creator for the particlespawner (when colliding against something)
366                // drone->addTemplate(this->getDroneTemplate());
367
368
369    }
370    orxout() << "Leaving spawnChildren() method. " << endl;
371}
372
373
374    void AsteroidMinable::hit(Pawn* originator, const Vector3& force, const btCollisionShape* cs, float damage, float healthdamage, float shielddamage){
375
376        orxout() << "AsteroidMining::Hit(Variante 1) Dings aufgerufen. " << endl;
377
378        // Kollision mit anderem Asteroid oder Pickup (OFFEN: evtl. Spawner oder irgendwas?) verhindern. In diesem Fall einfach nichts tun.
379        // Wird staending aufgerufen -> Rechenleistung?
380        if(orxonox_cast<AsteroidMinable*>(originator) || orxonox_cast<Pickup*>(originator)){return;}
381        this->damage(damage, healthdamage, shielddamage, originator, cs);
382        this->setVelocity(this->getVelocity() + force);
383
384
385
386        // if (this->getGametype() && this->getGametype()->allowPawnHit(this, originator))// && (!this->getController() || !this->getController()->getGodMode()) )
387        // {
388        //     this->damage(damage, healthdamage, shielddamage, originator, cs);
389        //     this->setVelocity(this->getVelocity() + force);
390        // }
391    }
392
393    void AsteroidMinable::hit(Pawn* originator, btManifoldPoint& contactpoint, const btCollisionShape* cs, float damage, float healthdamage, float shielddamage){
394
395        orxout() << "AsteroidMining::Hit(Variante 2) Dings aufgerufen. " << endl;
396        // Kollision mit anderem Asteroid oder Pickup (OFFEN: evtl. Spawner oder irgendwas?) verhindern. In diesem Fall einfach nichts tun.
397        // Wird staending aufgerufen -> Rechenleistung?
398        if(orxonox_cast<AsteroidMinable*>(originator) || orxonox_cast<Pickup*>(originator)){return;}
399
400
401
402        this->damage(damage, healthdamage, shielddamage, originator, cs);
403
404
405
406
407        // if (this->getGametype() && this->getGametype()->allowPawnHit(this, originator))// && (!this->getController() || !this->getController()->getGodMode()) )
408        // {
409        //     this->damage(damage, healthdamage, shielddamage, originator, cs);
410
411        //     //if ( this->getController() )
412        //     //    this->getController()->hit(originator, contactpoint, damage); // changed to damage, why shielddamage?
413        // }
414    }
415
416
417
418
419            // Cast-Test aus movableEntity():
420            // Pawn* victim = orxonox_cast<Pawn*>(otherObject);
421            // if (victim)
422
423
424
425
426//Pawn:
427    // void Pawn::hit(Pawn* originator, const Vector3& force, const btCollisionShape* cs, float damage, float healthdamage, float shielddamage)
428    // {
429    //     if (this->getGametype() && this->getGametype()->allowPawnHit(this, originator) && (!this->getController() || !this->getController()->getGodMode()) )
430    //     {
431    //         this->damage(damage, healthdamage, shielddamage, originator, cs);
432    //         this->setVelocity(this->getVelocity() + force);
433    //     }
434    // }
435
436    // void Pawn::hit(Pawn* originator, btManifoldPoint& contactpoint, const btCollisionShape* cs, float damage, float healthdamage, float shielddamage)
437    // {
438    //     if (this->getGametype() && this->getGametype()->allowPawnHit(this, originator) && (!this->getController() || !this->getController()->getGodMode()) )
439    //     {
440    //         this->damage(damage, healthdamage, shielddamage, originator, cs);
441
442    //         if ( this->getController() )
443    //             this->getController()->hit(originator, contactpoint, damage); // changed to damage, why shielddamage?
444    //     }
445    // }
446
447
448
449
450            // /**
451            // @brief
452            //     Virtual function that gets called when this object collides with another.
453            // @param otherObject
454            //     The object this one has collided into.
455            // @param ownCollisionShape
456            //     The collision shape of the other object
457            // @param contactPoint
458            //     Contact point provided by Bullet. Holds more information and can me modified. See return value.
459            // @return
460            //     Returning false means that no modification to the contactPoint has been made. Return true otherwise!
461            // @note
462            //     Condition is that enableCollisionCallback() was called.
463            // */
464            // virtual inline bool collidesAgainst(WorldEntity* otherObject, const btCollisionShape* ownCollisionShape, btManifoldPoint& contactPoint)
465            //     { return false; } /* With false, Bullet assumes no modification to the collision objects. */
466
467            // //! Enables the collidesAgainst(.) function. The object doesn't respond to collision otherwise!
468            // inline void enableCollisionCallback()
469            //     { this->bCollisionCallbackActive_ = true; this->collisionCallbackActivityChanged(); }
470
471
472
473            // //! Disables the collidesAgainst(.) function. @see enableCollisionCallback()
474            // inline void disableCollisionCallback()
475            //     { this->bCollisionCallbackActive_ = false; this->collisionCallbackActivityChanged(); }
476
477
478            // //! Tells whether there could be a collision callback via collidesAgainst(.)
479            // inline bool isCollisionCallbackActive() const
480            //     { return this->bCollisionCallbackActive_; }
481
482            // //! Enables or disables collision response (default is of course on)
483            // inline void setCollisionResponse(bool value)
484            //     { this->bCollisionResponseActive_ = value; this->collisionResponseActivityChanged(); }
485
486
487            // //! Tells whether there could be a collision response
488            // inline bool hasCollisionResponse()
489            //     { return this->bCollisionResponseActive_; }
490
491
492}
493
494
495
496
497
498/*
499    void DronePickup::changedUsed(void)
500    {
501        SUPER(DronePickup, changedUsed);
502
503        // If the pickup has transited to used.
504        if(this->isUsed())
505        {
506
507                Pawn* pawn = this->carrierToPawnHelper();
508                if(pawn == nullptr) // If the PickupCarrier is no Pawn, then this pickup is useless and therefore is destroyed.
509                    this->Pickupable::destroy();
510
511                //Attach to pawn
512                Drone* drone = new Drone(pawn->getContext()); // this is neccessary because the projectiles fired need a valid creator for the particlespawner (when colliding against something)
513                drone->addTemplate(this->getDroneTemplate());
514
515                Controller* controller = drone->getController();
516                DroneController* droneController = orxonox_cast<DroneController*>(controller);
517                if(droneController != nullptr)
518                {
519                    droneController->setOwner(pawn);
520                }
521
522                Vector3 spawnPosition = pawn->getWorldPosition() + Vector3(30,0,-30);
523                drone->setPosition(spawnPosition);
524
525                // The pickup has been used up.
526                this->setUsed(false);
527        }
528        else
529        {
530            // If either the pickup can only be used once or it is continuous and used up, it is destroyed upon setting it to unused.
531            if(this->isOnce() || (this->isContinuous() ))
532            {
533                this->Pickupable::destroy();
534            }
535        }
536    }
537*/
Note: See TracBrowser for help on using the repository browser.