Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

Gebastel in spawnChildren, hat immer noch Fehler drin.

File size: 21.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:
46
47o Floating point exception
48o math.pi richtig einbinden.
49
50OFFEN:
51o Add custom pickup 'resources'. Weird template stuff -> Problems setting 'size' and other properties? setNumber of Resources.
52--> PickupTemplateName_ in PickupSpawner ist ein string. Wird via getBaseClassIdentifier ausgelesen, daraus wird ein Pickupable fabriziert.
53--> MunitionPickup erbt von Pickup erbt von collectiblePickup erbt von Pickupable
54----> im MineralsPickup die isPickedUp()-Methode überschreiben?
55--> data_extern/images/effects: PNG's für die Pickups und GUI-Dinger.
56
57o Explosion parts
58o custom HUD
59o asteroidField.lua anpassen, mit 'Mineraliendichten-Parameter'.
60
61o Dokumentieren mit @brief?
62
63o replace ugly random stuff with math.rnd()
64o set collisionDamage? Just for static entities?
65
66HANDBUCH:
67o im Level-File includes/pickups.oxi importieren.
68o Bei der XML-Variante wird beim ersten Aufruf der Tick-Methode ein neuer Asteroid generiert,
69  damit die Groesse der Collision Shape korrekt initialisiert wird.
70
71FREMDANPASSUNGEN:
72Pickup-Zeug:
73o Pickup.h: Zugriffsänderung createSpawner
74o PickupSpawner.h: Zugriffsrechte setPickupTemplateName() und setMaxSpawnedItems()
75o PickupSpawner.h: In Tick() zwei Testbedingungen eingefuegt.
76o Pawn.h: Attribut acceptsPickups_ inklusive get/set.
77
78ERLEGT:
79o Rand() geht bis zu riesigen Nummern!
80o Pickupgenerierung: vgl. Fremdanpassungen.
81o Minimalbegrenzung fuer Masse vergessen.
82o Dynamische Definition -> putStuff-Methode, Werte noch nicht durchgesickert.
83o Error-Nachricht: Einfach Argumente leer lassen.
84o Pickups: setMaxSpawned funktioniert nicht -> Bastelloesung: Auf 2 statt eins setzen, erstes wird wohl direkt zerstoert.
85o setHealth: Wird mit Max verwurstelt, war 0.
86o Position nicht gesetzt -> alles im Ursprung, Kollision -> fliegt davon.
87o nimmt zuviel Schaden. -> wird mit maxHealth verwurstelt -> einfach auch setzen.
88
89o Groessenabhaengige Collison shape: Umweg ueber zweiten Konstruktor.
90o Absturz beim Asteroidengenerieren: Health war auf 0 gesetzt! Wurde nur bei der xml-Variante definiert.
91o Asteroiden fressen Pickups: Argument in Pawn, Test darauf in Tick() von PickupSpawner.
92o Man kann keine Arrays der Groesse 0 initialisieren, aber auch nicht per IF 2x definieren.
93o i++ einfach ganz verhindern, ++i stattdessen.
94
95
96NOTIZEN:
97o SUPER entspricht ueberladen, andere Argumente der Methode.
98o Warnungsverhinderung anderswo: (void)pickedUp; // To avoid compiler warning.
99
100Was ist das?         friend class Pickupable;
101
102
103
104*/
105
106
107#include "../../orxonox/worldentities/pawns/Pawn.h"
108#include "../../orxonox/worldentities/WorldEntity.h"
109
110#include "AsteroidMinable.h"
111
112#include <algorithm>
113
114#include "core/CoreIncludes.h"
115#include "core/GameMode.h"
116#include "core/XMLPort.h"
117#include "core/EventIncludes.h"
118#include "network/NetworkFunction.h"
119#include "util/Math.h"
120
121
122// #include "infos/PlayerInfo.h"
123// #include "controllers/Controller.h"
124// #include "gametypes/Gametype.h"
125// #include "graphics/ParticleSpawner.h"
126// #include "worldentities/ExplosionChunk.h"
127// #include "worldentities/ExplosionPart.h"
128
129// #include "core/object/ObjectListIterator.h"
130// #include "controllers/FormationController.h"
131
132#include "../pickup/items/HealthPickup.h"
133#include "../pickup/PickupSpawner.h"
134#include "../pickup/Pickup.h"
135//#include "../pickup/pickup ..... pickupable
136#include "../objects/collisionshapes/SphereCollisionShape.h"
137#include "../../orxonox/graphics/Model.h"
138
139
140
141
142
143
144
145namespace orxonox
146{
147    RegisterClass(AsteroidMinable);
148
149
150    // This constructor is for XML access only.
151    AsteroidMinable::AsteroidMinable(Context* context) : Pawn(context){
152
153        // Da auch noetig? Wegen set in XML-Code?
154        RegisterObject(AsteroidMinable);
155
156        this->context = context;
157        this->initialised = false;
158
159        //Noetig, damit nicht sofort zerstoert?
160        this->setCollisionType(WorldEntity::CollisionType::Dynamic);
161
162        // Old from Pawn
163        this->registerVariables();
164
165        orxout() << "AsteroidMining:: Pseudo-Konstruktor passiert!" << endl;
166
167    }
168
169    // Call this one from other C-files. Takes arguments.
170    AsteroidMinable::AsteroidMinable(Context* c, float size, Vector3 position) : Pawn(c){
171
172        RegisterObject(AsteroidMinable);
173
174        // Old stuff from pawn
175        this->setRadarObjectColour(ColourValue(1.0f, 1.0f, 0.0f, 1.0f));
176        this->setRadarObjectShape(RadarViewable::Shape::Dot);
177        this->setCollisionType(WorldEntity::CollisionType::Dynamic);
178
179        this->enableCollisionCallback();
180
181        // Default Values
182        this->generateSmaller = true; 
183        //this->setHealth(50);
184        this->context = c;
185        this->size = size; // customSize
186        this->health_ = 15*size;// capped at 200 in pawn or smth?
187        this->maxHealth_ = this->health_;
188        this->acceptsPickups_ = false;
189
190        this->setPosition(position);
191        //this->roll = rand()*5; //etwas Drehung. richtige Variable
192
193        // // Fliegt davon, irgendwieso. Dies scheint auch nicht zu nuetzen.
194        // this->setVelocity(Vector3(0,0,0));
195
196
197
198        // Add Model    //<Model position="0,-40,40" yaw="90" pitch="-90" roll="0" scale="4" mesh="ast6.mesh" />
199        Model* hull = new Model(this->context);
200        // random one of the 6 shapes
201        char meshThingy[] = "";
202        sprintf(meshThingy, "ast%.0f.mesh", (round((5*(double)rand()/(double)RAND_MAX))+1)); //    sprintf(str, "Value of Pi = %f", M_PI);
203        hull->setMeshSource(meshThingy);
204        hull->setScale(this->size);
205        this->attach(hull);
206
207        // Collision shape
208        SphereCollisionShape* cs = new SphereCollisionShape(this->context);
209        cs->setRadius((this->size)*2); //OFFEN: Feinabstimmung der Radien. 2.5 in AsteroidField.lua
210        this->attachCollisionShape(cs); 
211
212        // Old from Pawn
213        this->registerVariables();
214
215        this->initialised=true; 
216
217        orxout() << "AsteroidMining:: Initialisierung Zweitkonstruktor abgeschlosssssen." << endl;
218
219    }
220
221    AsteroidMinable::~AsteroidMinable(){
222
223    }
224
225    void AsteroidMinable::putStuff(){
226
227        // Just create a new asteroid to avoid Collision shape scale problems etc.
228        AsteroidMinable* reborn = new AsteroidMinable(this->context, this->size, this->getPosition());
229        reborn->toggleShattering(true); // mainly here to avoid 'unused' warning.
230        this->~AsteroidMinable(); // seems dangerous. Necessary for efficiency?
231
232    }
233
234    void AsteroidMinable::XMLPort(Element& xmlelement, XMLPort::Mode mode)
235    {
236        SUPER(AsteroidMinable, XMLPort, xmlelement, mode);
237        //        XMLPortParam(PickupSpawner, "pickup", setPickupTemplateName, getPickupTemplateName, xmlelement, mode);
238        XMLPortParam(AsteroidMinable, "size", setSize, getSize, xmlelement, mode);
239
240    }
241
242    void AsteroidMinable::XMLEventPort(Element& xmlelement, XMLPort::Mode mode)
243    {
244        SUPER(AsteroidMinable, XMLEventPort, xmlelement, mode);
245
246        XMLPortEventState(AsteroidMinable, BaseObject, "vulnerability", setVulnerable, xmlelement, mode);
247    }
248
249    void AsteroidMinable::registerVariables()
250    {
251        // registerVariable(this->bAlive_,            VariableDirection::ToClient);
252        // registerVariable(this->bVulnerable_,       VariableDirection::ToClient);
253        // registerVariable(this->health_,            VariableDirection::ToClient);
254        // registerVariable(this->maxHealth_,         VariableDirection::ToClient);
255
256        registerVariable(this->size, VariableDirection::ToClient);
257        registerVariable(this->generateSmaller, VariableDirection::ToClient);
258
259        registerVariable(this->initialised, VariableDirection::ToClient);
260        //registerVariable(this->context, VariableDirection::ToClient); // can't link that since it's a context
261
262
263            //         float size;
264            // bool generateSmaller;
265            // bool initialised;
266
267            // Context* context;
268    }
269
270    void AsteroidMinable::tick(float dt)
271    {
272        if(!(this->initialised)){this->putStuff();}
273
274        if(this->health_ <=0){this->death();}
275
276        // if(this->initialised){
277        //     // this->setVelocity(Vector3(0,0,0));  // Funktioniert, scheint aber unsinnig.
278        //     orxout() << "Flying at speed: " << this->getVelocity() << endl;
279        // }
280
281    }
282
283    void AsteroidMinable::setSize(float s){
284        this->size = s;
285    }
286
287    float AsteroidMinable::getSize(){
288        return this->size;
289    }
290
291    void AsteroidMinable::toggleShattering(bool b){
292        this->generateSmaller = b;
293    }
294
295
296    void AsteroidMinable::death() //ueberschreiben
297    {
298
299        // orxout() << "AsteroidMinable::Death() aufgerufen." << endl;
300
301        // OFFEN: Sauber kapputten
302        // just copied other stuff:
303        // this->setHealth(1);
304        this->bAlive_ = false;
305        this->destroyLater();
306        this->setDestroyWhenPlayerLeft(false);
307        // pawn -> addExplosionPart
308        // this->goWithStyle();
309
310
311        // Stuff that can be harvested.
312        PickupSpawner* thingy = new PickupSpawner(this->context);
313        // OFFEN: more precise size relation in custom resource pickup.
314        char tname[] = ""; // can-t overwrite strings easily in C (strcat etc.)
315        if(this->size <= 5){
316            strcat(tname, "smallmunitionpickup");
317        }else if(this->size <= 20){
318            strcat(tname, "mediummunitionpickup");
319        }else{
320            strcat(tname, "hugemunitionpickup");
321        }
322        thingy->setPickupTemplateName(tname);
323        thingy->setPosition(this->getPosition());
324        thingy->setMaxSpawnedItems(1); // Would be default anyways
325        thingy->setRespawnTime(0.2f);
326
327        // orxout() << "AsteroidMining::Death(): Passed Pickup stuff!" << endl;
328
329        // Smaller Parts = 'Children'
330        if(this->generateSmaller){
331            this->spawnChildren();
332        }
333
334        // orxout() << "Wieder retour in death() geschafft. " << endl;
335
336    }
337
338
339void AsteroidMinable::spawnChildren(){// Spawn smaller Children
340
341   
342    if (this->size <=1){return;} // Absicherung trivialer Fall
343
344    int massRem = this->size-1; //some mass is lost
345    int num = round(rnd()*(massRem-1)) + 1; // random number of children, at least one
346    if(num > 10){num = 10;} // no max function in C!
347    int masses[num] = {1}; // Masses of the asteroids, at least one.
348    massRem = massRem-num; 
349
350    orxout() << "SpawnChildren(): passed basic stuff. num = " << num << endl;
351
352    // Randomnised spawning points for the new asteroids
353    float phi[num] = {0.0}; // assuming that it gets initialised to 0. Add (= {0.0})?
354    float theta[num] = {0.0};
355    float pi = 3.14159;//math.pi;
356
357    float d_p = 2*pi/num;
358    float d_t = pi/num;
359    float p = d_p/2;
360    float t = d_t/2;
361    // float phiOffset = rnd()*2*pi; // Added everywhere to become independent of the coordinate system
362    // float thetaOffset = rnd()*pi;
363    float rScaling = tan(t); // scale radius to prevent asteroids from touching. (distance=AsteroidRadius/tan(sector/2))
364
365    int pos;
366    for(int it = 0; it<num; ++it){
367        orxout() << "SpawnChildren(): Entering For. " << endl;
368
369        pos = mod((int)(rnd()*num),num); 
370        orxout() << "SpawnChildren(): Trying position: " << pos << endl;
371
372        while(phi[pos] != 0.0){// find empty spot in array
373            pos = (int)mod(++pos, num);
374            orxout() << "SpawnChildren(): Inside, testing position: " << pos << endl;
375        }
376        phi[pos] = p + it*d_p;// set angle there
377
378        pos = mod((int)(rnd()*num),num);
379        while(theta[pos] != 0.0){
380            pos = (int)mod(++pos, num);
381        }
382        theta[pos] = t + it*d_t;
383    }
384
385    orxout() << "SpawnChildren(): passed angle stuff. " << endl;
386
387    // 'Triangular', discrete probability density with max at the expected value massRem/num at a. a+b = c
388    if(massRem>0){ // Required to avoid array of size 0 or access problems
389        int c = massRem;
390        float probDensity[c] = {0.0};
391
392        int a = round(massRem/num);
393        int b = c-a;
394        int m = 2/c; // Peak value, is reached at the average size.
395        int z = 0;
396        for(z = 0; z<=a; ++z){probDensity[z] = m*z/a; } // rising part
397        for(z = a+1; z<c; ++z){probDensity[z] = m - m*(z-a)/b;} // falling part
398   
399        // Distributing the mass
400        for(int trav = 0; trav<num && massRem>0; ++trav){
401
402            int result = 0;
403            float rVal = rnd();// between 0 and 1
404            float probSum = probDensity[0];
405            while(rVal>probSum){
406                probSum = probSum+probDensity[result+1];
407                ++result;
408            }
409            if(result>massRem){result = massRem;}
410
411            massRem = massRem-result;
412            masses[trav] = masses[trav]+result; 
413
414        }
415    }
416       
417    orxout() << "SpawnChildren(): passed Mass stuff. " << endl;
418
419    for(int fisch = 0; fisch<num; ++fisch){// create the children
420
421        // Position offset:
422        float r = masses[fisch]/rScaling;
423        Vector3* pos = new Vector3(r*sin(theta[fisch])*cos(phi[fisch]), r*sin(theta[fisch])*sin(phi[fisch]), r*cos(theta[fisch]));
424
425        AsteroidMinable* child = new AsteroidMinable(this->context, masses[fisch], this->getPosition() + *pos);
426
427        if(child == nullptr){
428            orxout(internal_error, context::pickups) << "Weird, can't create new AsteroidMinable." << endl;
429        }
430
431    }
432    orxout() << "Leaving spawnChildren() method. " << endl;
433}
434
435
436    void AsteroidMinable::hit(Pawn* originator, const Vector3& force, const btCollisionShape* cs, float damage, float healthdamage, float shielddamage){
437
438        orxout() << "AsteroidMining::Hit(Variante 1) Dings aufgerufen. " << endl;
439
440        // Kollision mit anderem Asteroid oder Pickup (OFFEN: evtl. Spawner oder irgendwas?) verhindern. In diesem Fall einfach nichts tun.
441        // Wird staending aufgerufen -> Rechenleistung?
442        if(orxonox_cast<AsteroidMinable*>(originator) || orxonox_cast<Pickup*>(originator)){return;}
443        this->damage(damage, healthdamage, shielddamage, originator, cs);
444        this->setVelocity(this->getVelocity() + force);
445
446
447
448        // if (this->getGametype() && this->getGametype()->allowPawnHit(this, originator))// && (!this->getController() || !this->getController()->getGodMode()) )
449        // {
450        //     this->damage(damage, healthdamage, shielddamage, originator, cs);
451        //     this->setVelocity(this->getVelocity() + force);
452        // }
453    }
454
455    void AsteroidMinable::hit(Pawn* originator, btManifoldPoint& contactpoint, const btCollisionShape* cs, float damage, float healthdamage, float shielddamage){
456
457        //orxout() << "AsteroidMining::Hit(Variante 2) Dings aufgerufen. " << endl;
458        // Kollision mit anderem Asteroid oder Pickup (OFFEN: evtl. Spawner oder irgendwas?) verhindern. In diesem Fall einfach nichts tun.
459        // Wird staending aufgerufen -> Rechenleistung?
460        if(orxonox_cast<AsteroidMinable*>(originator) || orxonox_cast<Pickup*>(originator)){return;}
461
462        //orxout() << "Schaden. HP: " << this->health_ << " Dmg: " << damage << " hDmg: " << healthdamage << " sDmg: " << shielddamage << endl;
463
464        this->damage(damage, healthdamage, shielddamage, originator, cs);
465
466
467
468
469        // if (this->getGametype() && this->getGametype()->allowPawnHit(this, originator))// && (!this->getController() || !this->getController()->getGodMode()) )
470        // {
471        //     this->damage(damage, healthdamage, shielddamage, originator, cs);
472
473        //     //if ( this->getController() )
474        //     //    this->getController()->hit(originator, contactpoint, damage); // changed to damage, why shielddamage?
475        // }
476    }
477
478
479
480
481
482
483//Pawn:
484    // void Pawn::hit(Pawn* originator, const Vector3& force, const btCollisionShape* cs, float damage, float healthdamage, float shielddamage)
485    // {
486    //     if (this->getGametype() && this->getGametype()->allowPawnHit(this, originator) && (!this->getController() || !this->getController()->getGodMode()) )
487    //     {
488    //         this->damage(damage, healthdamage, shielddamage, originator, cs);
489    //         this->setVelocity(this->getVelocity() + force);
490    //     }
491    // }
492
493    // void Pawn::hit(Pawn* originator, btManifoldPoint& contactpoint, const btCollisionShape* cs, float damage, float healthdamage, float shielddamage)
494    // {
495    //     if (this->getGametype() && this->getGametype()->allowPawnHit(this, originator) && (!this->getController() || !this->getController()->getGodMode()) )
496    //     {
497    //         this->damage(damage, healthdamage, shielddamage, originator, cs);
498
499    //         if ( this->getController() )
500    //             this->getController()->hit(originator, contactpoint, damage); // changed to damage, why shielddamage?
501    //     }
502    // }
503
504
505
506
507            // /**
508            // @brief
509            //     Virtual function that gets called when this object collides with another.
510            // @param otherObject
511            //     The object this one has collided into.
512            // @param ownCollisionShape
513            //     The collision shape of the other object
514            // @param contactPoint
515            //     Contact point provided by Bullet. Holds more information and can me modified. See return value.
516            // @return
517            //     Returning false means that no modification to the contactPoint has been made. Return true otherwise!
518            // @note
519            //     Condition is that enableCollisionCallback() was called.
520            // */
521            // virtual inline bool collidesAgainst(WorldEntity* otherObject, const btCollisionShape* ownCollisionShape, btManifoldPoint& contactPoint)
522            //     { return false; } /* With false, Bullet assumes no modification to the collision objects. */
523
524            // //! Enables the collidesAgainst(.) function. The object doesn't respond to collision otherwise!
525            // inline void enableCollisionCallback()
526            //     { this->bCollisionCallbackActive_ = true; this->collisionCallbackActivityChanged(); }
527
528
529
530            // //! Disables the collidesAgainst(.) function. @see enableCollisionCallback()
531            // inline void disableCollisionCallback()
532            //     { this->bCollisionCallbackActive_ = false; this->collisionCallbackActivityChanged(); }
533
534
535            // //! Tells whether there could be a collision callback via collidesAgainst(.)
536            // inline bool isCollisionCallbackActive() const
537            //     { return this->bCollisionCallbackActive_; }
538
539            // //! Enables or disables collision response (default is of course on)
540            // inline void setCollisionResponse(bool value)
541            //     { this->bCollisionResponseActive_ = value; this->collisionResponseActivityChanged(); }
542
543
544            // //! Tells whether there could be a collision response
545            // inline bool hasCollisionResponse()
546            //     { return this->bCollisionResponseActive_; }
547
548
549}
550
551
552
553
554
555/*
556    void DronePickup::changedUsed(void)
557    {
558        SUPER(DronePickup, changedUsed);
559
560        // If the pickup has transited to used.
561        if(this->isUsed())
562        {
563
564                Pawn* pawn = this->carrierToPawnHelper();
565                if(pawn == nullptr) // If the PickupCarrier is no Pawn, then this pickup is useless and therefore is destroyed.
566                    this->Pickupable::destroy();
567
568                //Attach to pawn
569                Drone* drone = new Drone(pawn->getContext()); // this is neccessary because the projectiles fired need a valid creator for the particlespawner (when colliding against something)
570                drone->addTemplate(this->getDroneTemplate());
571
572                Controller* controller = drone->getController();
573                DroneController* droneController = orxonox_cast<DroneController*>(controller);
574                if(droneController != nullptr)
575                {
576                    droneController->setOwner(pawn);
577                }
578
579                Vector3 spawnPosition = pawn->getWorldPosition() + Vector3(30,0,-30);
580                drone->setPosition(spawnPosition);
581
582                // The pickup has been used up.
583                this->setUsed(false);
584        }
585        else
586        {
587            // If either the pickup can only be used once or it is continuous and used up, it is destroyed upon setting it to unused.
588            if(this->isOnce() || (this->isContinuous() ))
589            {
590                this->Pickupable::destroy();
591            }
592        }
593    }
594*/
Note: See TracBrowser for help on using the repository browser.