Oolite
Loading...
Searching...
No Matches
ShipEntityAI.m
Go to the documentation of this file.
1/*
2
3 ShipEntityAI.m
4
5 Oolite
6 Copyright (C) 2004-2013 Giles C Williams and contributors
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,
21 MA 02110-1301, USA.
22
23 */
24
25#import "ShipEntityAI.h"
26#import "AI.h"
27#import "OOMaths.h"
28#import "Universe.h"
29
30#import "OOJSFunction.h"
31#import "OOJavaScriptEngine.h"
32#import "OOPlanetEntity.h"
33#import "OOShipGroup.h"
34#import "OOSunEntity.h"
35#import "PlayerEntity.h"
37#import "StationEntity.h"
38#import "WormholeEntity.h"
39
41#import "OOConstToJSString.h"
42#import "OOConstToString.h"
44#import "OOStringExpander.h"
45#import "OOStringParsing.h"
46#import "ResourceManager.h"
47
48@interface ShipEntity (OOAIPrivate)
49
50- (void)checkFoundTarget;
51
52- (BOOL)performHyperSpaceExitReplace:(BOOL)replace;
53- (BOOL)performHyperSpaceExitReplace:(BOOL)replace toSystem:(OOSystemID)systemID;
54
55- (void)scanForNearestShipWithPredicate:(EntityFilterPredicate)predicate parameter:(void*)parameter;
56- (void)scanForNearestShipWithNegatedPredicate:(EntityFilterPredicate)predicate parameter:(void*)parameter;
57
58- (void)acceptDistressMessageFrom:(ShipEntity*)other;
59
60@end
61
62@interface StationEntity (OOAIPrivate)
63
64- (void)acceptDistressMessageFrom:(ShipEntity*)other;
65
66@end
67
68@interface ShipEntity (PureAI)
69
70// Methods used only by AI.
71
72- (void)setStateTo:(NSString*)state;
73
74- (void)pauseAI:(NSString*)intervalString;
75
76- (void)randomPauseAI:(NSString*)intervalString;
77
78- (void)dropMessages:(NSString*)messageString;
79
81
83
84- (void)setDesiredRangeTo:(NSString*)rangeString;
85
87
88- (void)setSpeedTo:(NSString*)speedString;
89
90- (void)setSpeedFactorTo:(NSString*)speedString;
91
93
94- (void)setThrustFactorTo:(NSString*)thrustFactorString;
95
97
100
101- (void)scanForLoot;
102
103- (void)scanForRandomLoot;
104
106
107- (void)checkForFullHold;
108
110
113
114- (void)fightOrFleeMissile;
115
116- (void)setCourseToPlanet;
118- (void)landOnPlanet;
119
121- (void)checkOwnLegalStatus;
122
123- (void)exitAIWithMessage:(NSString*)message;
124
127
129
130- (void)checkAegis;
131
132- (void)checkEnergy;
133- (void)checkHeatInsulation;
134
135- (void)scanForOffenders;
136
138
141
144- (void)wormholeGroup;
145
146- (void)commsMessage:(NSString*)valueString;
147- (void)commsMessageByUnpiloted:(NSString*)valueString;
148
149- (void)ejectCargo;
150
151- (void)scanForThargoid;
152- (void)scanForNonThargoid;
153- (void)thargonCheckMother;
155
157
158- (void)fightOrFleeHostiles;
159
160- (void)suggestEscort;
161
162- (void)escortCheckMother;
163
165
167
168- (void)messageMother:(NSString*)msgString;
169
171
173
175
177
178- (void)patrolReportIn;
179
181
182- (void)sendTargetCommsMessage:(NSString*)message;
183
184- (void)markTargetForFines;
185
186- (void)markTargetForOffence:(NSString*)valueString;
187
188- (void)storeTarget;
189- (void)recallStoredTarget;
190
191- (void)scanForRocks;
192
194
195- (void)requestNewTarget;
196
197- (void)rollD:(NSString*)die_number;
198
199- (void)scanForNearestShipWithPrimaryRole:(NSString*)scanRole;
200- (void)scanForNearestShipHavingRole:(NSString*)scanRole;
201- (void)scanForNearestShipWithAnyPrimaryRole:(NSString*)scanRoles;
202- (void)scanForNearestShipHavingAnyRole:(NSString*)scanRoles;
203- (void)scanForNearestShipWithScanClass:(NSString*)scanScanClass;
204
205- (void)scanForNearestShipWithoutPrimaryRole:(NSString*)scanRole;
206- (void)scanForNearestShipNotHavingRole:(NSString*)scanRole;
207- (void)scanForNearestShipWithoutAnyPrimaryRole:(NSString*)scanRoles;
208- (void)scanForNearestShipNotHavingAnyRole:(NSString*)scanRoles;
209- (void)scanForNearestShipWithoutScanClass:(NSString*)scanScanClass;
210
211- (void)setCoordinates:(NSString*)system_x_y_z;
212
213- (void)checkForNormalSpace;
214
217
218- (void)addFuel:(NSString*)fuel_number;
219
220- (void)scriptActionOnTarget:(NSString*)action;
221
222- (void)sendScriptMessage:(NSString*)message;
223
224- (void)ai_throwSparks;
225
226- (void)explodeSelf;
227
228- (void)ai_debugMessage:(NSString*)message;
229
230// racing code.
231- (void)targetFirstBeaconWithCode:(NSString*)code;
232- (void)targetNextBeaconWithCode:(NSString*)code;
235
236// defense targets
240
241@end
242
243@implementation ShipEntity (AI)
244
245- (void)setAITo:(NSString*)aiString
246{
247 // don't try to load real AIs if the game hasn't started yet
248 if (![PLAYER scriptsLoaded]) {
249 aiString = @"oolite-nullAI.js";
250 }
251 if ([aiString hasSuffix:@".plist"]) {
252 [[self getAI] setStateMachine:aiString withJSScript:@"oolite-nullAI.js"];
253 [self setAIScript:@"oolite-nullAI.js"];
254 } else if ([aiString hasSuffix:@".js"]) {
255 [[self getAI] setStateMachine:@"nullAI.plist" withJSScript:aiString];
256 [self setAIScript:aiString];
257 } else {
258 NSString* path = [ResourceManager pathForFileNamed:[aiString stringByAppendingString:@".js"] inFolder:@"AIs"];
259 if (path == nil) // no js, use plist
260 {
261 [self setAITo:[aiString stringByAppendingString:@".plist"]];
262 } else {
263 [self setAITo:[aiString stringByAppendingString:@".js"]];
264 }
265 }
266}
267
268- (void)setAIScript:(NSString*)aiString
269{
270 NSMutableDictionary* properties = nil;
271
272 properties = [NSMutableDictionary dictionary];
273 [properties setObject:self forKey:@"ship"];
274
275 [aiScript autorelease];
276 aiScript = [OOScript jsAIScriptFromFileNamed:aiString properties:properties];
277 if (aiScript == nil) {
278 OOLog(@"ai.load.failed.unknownAI", @"Unable to load JS AI %@ for ship %@ (%@ for role %@)", aiString, self, [self shipDataKey], [self primaryRole]);
279 aiScript = [OOScript jsAIScriptFromFileNamed:@"oolite-nullAI.js" properties:properties];
280 } else {
281 aiScriptWakeTime = 0;
282 haveStartedJSAI = NO;
283 }
284 [aiScript retain];
285}
286
287- (void)switchAITo:(NSString*)aiString
288{
289 [self setAITo:aiString];
290 [[self getAI] clearStack];
291}
292
294{
295 /*-- Locates all the ships in range targeting the receiver and chooses the nearest --*/
296 DESTROY(_foundTarget);
297
298 [self checkScanner];
299 unsigned i;
300 GLfloat found_d2 = scannerRange * scannerRange;
301 for (i = 0; i < n_scanned_ships; i++) {
302 ShipEntity* thing = scanned_ships[i];
303 GLfloat d2 = distance2_scanned_ships[i];
304 if ((d2 < found_d2)
305 && ([thing isThargoid] || (([thing primaryTarget] == self) && [thing hasHostileTarget]) || [thing isDefenseTarget:self])
306 && ![thing isCloaked]) {
307 [self setFoundTarget:thing];
308 found_d2 = d2;
309 }
310 }
311
312 [self checkFoundTarget];
313}
314
316{
317 ShipEntity *target = nil, *ship = nil;
318
319 target = [self primaryTarget];
320
321 if (target == nil)
322 return;
323
324 if ([self group] == nil) // ship is alone!
325 {
326 [self setFoundTarget:target];
327 [shipAI reactToMessage:@"GROUP_ATTACK_TARGET" context:@"groupAttackTarget"];
328 [self doScriptEvent:OOJSID("helpRequestReceived") withArgument:self andArgument:target];
329 return;
330 }
331
332 foreach (ship, [[self group] mutationSafeEnumerator]) {
333 [ship setFoundTarget:target];
334 [ship reactToAIMessage:@"GROUP_ATTACK_TARGET" context:@"groupAttackTarget"];
335 [ship doScriptEvent:OOJSID("helpRequestReceived") withArgument:self andArgument:target];
336
337 if ([ship escortGroup] != [ship group] && [[ship escortGroup] count] > 1) // Ship has a seperate escort group.
338 {
339 ShipEntity* escort = nil;
340 NSArray* escortMembers = [[ship escortGroup] memberArrayExcludingLeader];
341 foreach (escort, escortMembers) {
342 [escort setFoundTarget:target];
343 [escort reactToAIMessage:@"GROUP_ATTACK_TARGET" context:@"groupAttackTarget"];
344 [escort doScriptEvent:OOJSID("helpRequestReceived") withArgument:self andArgument:target];
345 }
346 }
347 }
348}
349
351{
352 if (behaviour != BEHAVIOUR_EVASIVE_ACTION) {
353 behaviour = BEHAVIOUR_ATTACK_TARGET;
354 desired_range = 1250 * randf() + 750; // 750 til 2000
355 frustration = 0.0;
356 }
357}
358
360{
361 behaviour = BEHAVIOUR_COLLECT_TARGET;
362 frustration = 0.0;
363}
364
366{
367 if (behaviour != BEHAVIOUR_FORMATION_FORM_UP) {
368 behaviour = BEHAVIOUR_FORMATION_FORM_UP;
369 frustration = 0.0; // behavior changed, reset frustration.
370 }
371}
372
374{
375 behaviour = BEHAVIOUR_FACE_DESTINATION;
376 frustration = 0.0;
377}
378
380{
381 if (behaviour != BEHAVIOUR_FLEE_EVASIVE_ACTION) {
382 behaviour = BEHAVIOUR_FLEE_TARGET;
383 [self setEvasiveJink:400.0];
384 frustration = 0.0;
385 if (accuracy > COMBAT_AI_ISNT_AWFUL) {
386 // alert! they've got us in their sights! react!!
387 if ([self approachAspectToPrimaryTarget] > 0.9995) {
388 behaviour = randf() < 0.15 ? BEHAVIOUR_EVASIVE_ACTION : BEHAVIOUR_FLEE_EVASIVE_ACTION;
389 }
390 }
391 }
392}
393
395{
396 behaviour = BEHAVIOUR_FLY_RANGE_FROM_DESTINATION;
397 frustration = 0.0;
398}
399
401{
402 desired_speed = 0.0;
403 behaviour = BEHAVIOUR_TRACK_TARGET;
404 frustration = 0.0;
405}
406
408{
409 behaviour = BEHAVIOUR_IDLE;
410 frustration = 0.0;
411}
412
414{
415 behaviour = BEHAVIOUR_INTERCEPT_TARGET;
416 frustration = 0.0;
417}
418
420{
421 OOPlanetEntity* nearest = [self findNearestPlanet];
422 if (isNearPlanetSurface) {
423 _destination = [nearest position];
424 behaviour = BEHAVIOUR_LAND_ON_PLANET;
425 planetForLanding = [nearest universalID];
426 } else {
427 behaviour = BEHAVIOUR_IDLE;
428 [shipAI message:@"NO_PLANET_NEARBY"];
429 }
430
431 frustration = 0.0;
432}
433
435{
436 Entity* target = [self primaryTarget];
437 // mining is not seen as hostile behaviour, so ensure it is only used against rocks.
438 if (target && [target scanClass] == CLASS_ROCK) {
439 behaviour = BEHAVIOUR_ATTACK_MINING_TARGET;
440 frustration = 0.0;
441 } else {
443 }
444}
445
447{
448 behaviour = BEHAVIOUR_SCRIPTED_AI;
449 frustration = 0.0;
450}
451
453{
454 behaviour = BEHAVIOUR_SCRIPTED_ATTACK_AI;
455 frustration = 0.0;
456}
457
459{
460 stick_roll = 0.10;
461 stick_pitch = 0.15;
462 behaviour = BEHAVIOUR_TUMBLE;
463 frustration = 0.0;
464}
465
467{
468 behaviour = BEHAVIOUR_STOP_STILL;
469 desired_speed = 0.0;
470 frustration = 0.0;
471}
472
474{
475 stick_roll = max_flight_roll * 2.0 * (randf() - 0.5);
476 stick_pitch = max_flight_pitch * 2.0 * (randf() - 0.5);
477 behaviour = BEHAVIOUR_TUMBLE;
478 frustration = 0.0;
479}
480
481- (BOOL)performHyperSpaceToSpecificSystem:(OOSystemID)systemID
482{
483 return [self performHyperSpaceExitReplace:NO toSystem:systemID];
484}
485
487{
488 /*- requests coordinates from the target station
489 if the target station can't be found
490 then use the nearest it can find (which may be a rock hermit) -*/
491
492 StationEntity* station = nil;
493 Entity* targStation = nil;
494 NSString* message = nil;
495 double distanceToStation2 = 0.0;
496
497 targStation = [self targetStation];
498 if ([targStation isStation]) {
499 station = (StationEntity*)targStation;
500 } else {
501 station = [UNIVERSE nearestShipMatchingPredicate:IsStationPredicate
502 parameter:nil
503 relativeToEntity:self];
504 }
505
506 distanceToStation2 = HPdistance2([station position], [self position]);
507
508 // Player check for being inside the aegis already exists in PlayerEntityControls. We just
509 // check here that distance to station is less than 2.5 times scanner range to avoid problems with
510 // NPC ships getting stuck with a dockingAI while just outside the aegis - Nikos 20090630, as proposed by Eric
511 // On very busy systems (> 50 docking ships) docking ships can be sent to a hold position outside the range,
512 // so also test for presence of dockingInstructions. - Eric 20091130
513 if (station != nil && (distanceToStation2 < SCANNER_MAX_RANGE2 * 6.25 || dockingInstructions != nil)) {
514 // remember the instructions
515 [dockingInstructions release];
516 dockingInstructions = [[station dockingInstructionsForShip:self] retain];
517 if (dockingInstructions != nil) {
519
520 message = [dockingInstructions objectForKey:@"ai_message"];
521 if (message != nil)
522 [shipAI message:message];
523 message = [dockingInstructions objectForKey:@"comms_message"];
524 if (message != nil)
525 [station sendExpandedMessage:message toShip:self];
526 }
527 } else {
528 DESTROY(dockingInstructions);
529 }
530
531 if (dockingInstructions == nil) {
532 [shipAI message:@"NO_STATION_FOUND"];
533 }
534}
535
537{
538 if (dockingInstructions != nil) {
539 _destination = [dockingInstructions oo_hpvectorForKey:@"destination"];
540 desired_speed = fmin([dockingInstructions oo_floatForKey:@"speed"], maxFlightSpeed);
541 desired_range = [dockingInstructions oo_floatForKey:@"range"];
542 if ([dockingInstructions objectForKey:@"station"]) {
543 StationEntity* targetStation = [[dockingInstructions objectForKey:@"station"] weakRefUnderlyingObject];
544 if (targetStation != nil) {
545 [self addTarget:targetStation];
546 [self setTargetStation:targetStation];
547 } else {
548 [self removeTarget:[self primaryTarget]];
549 }
550 }
551 docking_match_rotation = [dockingInstructions oo_boolForKey:@"match_rotation"];
552 }
553}
554
556{
558 HasScanClassPredicate, [NSNumber numberWithInt:CLASS_MISSILE],
560 };
561 [self scanForNearestShipWithPredicate:ANDPredicate parameter:&param];
562}
563
565{
566 [self enterWormhole:[PLAYER wormhole] replacing:NO];
567}
568
570{
571 WormholeEntity* whole = nil;
572 ShipEntity* targEnt = [self primaryTarget];
573 double found_d2 = scannerRange * scannerRange;
574
575 if (targEnt && (HPdistance2(position, [targEnt position]) < found_d2)) {
576 if ([targEnt isWormhole])
577 whole = (WormholeEntity*)targEnt;
578 else if ([targEnt isPlayer])
579 whole = [PLAYER wormhole];
580 }
581
582 if (!whole) {
583 // locate nearest wormhole
584 int ent_count = UNIVERSE->n_entities;
585 Entity** uni_entities = UNIVERSE->sortedEntities; // grab the public sorted list
586 WormholeEntity* wormholes[ent_count];
587 int i;
588 int wh_count = 0;
589 for (i = 0; i < ent_count; i++)
590 if (uni_entities[i]->isWormhole)
591 wormholes[wh_count++] = [(WormholeEntity*)uni_entities[i] retain];
592 //
593 // double found_d2 = scannerRange * scannerRange;
594 for (i = 0; i < wh_count; i++) {
595 WormholeEntity* wh = wormholes[i];
596 double d2 = HPdistance2(position, wh->position);
597 if (d2 < found_d2) {
598 whole = wh;
599 found_d2 = d2;
600 }
601 [wh release];
602 }
603 }
604
605 [self enterWormhole:whole replacing:NO];
606}
607
608// FIXME: resolve this stuff.
610{
611 ShipEntity* ship = nil;
612 NSString* context = nil;
613 WormholeEntity* whole = nil;
614
615 whole = [self primaryTarget];
616 if (![whole isWormhole])
617 return;
618
619#ifndef NDEBUG
620 context = [NSString stringWithFormat:@"%@ wormholeEscorts", [self shortDescription]];
621#endif
622
623 foreach (ship, [self escortEnumerator]) {
624 [ship addTarget:whole];
625 [ship reactToAIMessage:@"ENTER WORMHOLE" context:context];
626 [ship doScriptEvent:OOJSID("wormholeSuggested") withArgument:whole];
627 }
628
629 // We now have no escorts..
630
631 [_escortGroup release];
632 _escortGroup = nil;
633}
634
636{
637 [self wormholeGroup];
638 [self wormholeEscorts];
639}
640
641- (BOOL)suggestEscortTo:(ShipEntity*)mother
642{
643 if (mother) {
644#ifdef OO_DEBUG_MONITOR_ENABLED
645 if (reportAIMessages) {
646 OOLog(@"ai.suggestEscort", @"DEBUG: %@ suggests escorting %@", self, mother);
647 }
648#endif
649
650 if ([mother acceptAsEscort:self]) {
651 // copy legal status across
652 if (([mother legalStatus] > 0) && (bounty <= 0)) {
653 int extra = 1 | (ranrot_rand() & 15);
654 // [mother setBounty: [mother legalStatus] + extra withReason:kOOLegalStatusReasonAssistingOffender];
655 [self markAsOffender:extra withReason:kOOLegalStatusReasonAssistingOffender];
656 // bounty += extra; // obviously we're dodgier than we thought!
657 }
658
659 [self setOwner:mother];
660 [self setGroup:[mother escortGroup]];
661 [shipAI message:@"ESCORTING"];
662 return YES;
663 }
664
665#ifdef OO_DEBUG_MONITOR_ENABLED
666 if (reportAIMessages) {
667 OOLog(@"ai.suggestEscort.refused", @"DEBUG: %@ refused by %@", self, mother);
668 }
669#endif
670 }
671 [self setOwner:self];
672 [shipAI message:@"NOT_ESCORTING"];
673 [self doScriptEvent:OOJSID("escortRejected") withArgument:mother];
674 return NO;
675}
676
678{
679 /*-- Locates all the stations, bounty hunters and police ships in range and tells them that you are under attack --*/
681}
682
683- (void)broadcastDistressMessageWithDumping:(BOOL)dumpCargo
684{
686 DESTROY(_foundTarget);
687
688 ShipEntity* aggressor_ship = (ShipEntity*)[self primaryAggressor];
689 if (aggressor_ship == nil)
690 return;
691
692 // don't send too many distress messages at once, space them out semi-randomly
693 if (messageTime > 2.0 * randf())
694 return;
695
696 NSString* distress_message = nil;
697 BOOL is_buoy = (scanClass == CLASS_BUOY);
698 if (is_buoy)
699 distress_message = @"[buoy-distress-call]";
700 else
701 distress_message = @"[distress-call]";
702
703 unsigned i;
704 for (i = 0; i < n_scanned_ships; i++) {
705 ShipEntity* ship = scanned_ships[i];
706
707 // dump cargo if energy is low
708 if (dumpCargo && !is_buoy && [self primaryAggressor] == ship && energy < 0.375 * maxEnergy) {
709 [self ejectCargo];
710 [self performFlee];
711 }
712
713 // tell it! (only plist AIs send comms here; JS AIs are
714 // expected to handle their own)
715 if (ship->isPlayer && ![self hasNewAI]) {
716 [ship doScriptEvent:OOJSID("distressMessageReceived") withArgument:aggressor_ship andArgument:self];
717
718 if (!is_buoy && [self primaryAggressor] == ship && energy < 0.375 * maxEnergy) {
719 [self sendExpandedMessage:@"[beg-for-mercy]" toShip:ship];
720 } else if ([self bounty] == 0) {
721 // only send distress message to player if plausibly sending
722 // one more generally
723 [self sendExpandedMessage:distress_message toShip:ship];
724 }
725
726 // reset the thanked_ship_id
727 DESTROY(_thankedShip);
728 } else if ([self bounty] == 0 && [ship crew]) // Only clean ships can have their distress calls accepted
729 {
730 [ship doScriptEvent:OOJSID("distressMessageReceived") withArgument:aggressor_ship andArgument:self];
731
732 // we only can send distressMessages to ships that are known to have a "ACCEPT_DISTRESS_CALL" reaction
733 // in their AI, or they might react wrong on the added found_target.
734
735 // ship must have a plist AI for this next bit. JS AIs
736 // should already have done something sensible on
737 // distressMessageReceived
738 if (![self hasNewAI]) {
739 // FIXME: this test only works with core AIs
740 if (ship->isStation || [ship hasPrimaryRole:@"police"] || [ship hasPrimaryRole:@"hunter"]) {
742 }
743 }
744 }
745 }
746}
747
748@end
749
750@implementation ShipEntity (PureAI)
751
752- (void)setStateTo:(NSString*)state
753{
754 [[self getAI] setState:state];
755}
756
757- (void)pauseAI:(NSString*)intervalString
758{
759 [shipAI setNextThinkTime:[UNIVERSE getTime] + [intervalString doubleValue]];
760}
761
762- (void)randomPauseAI:(NSString*)intervalString
763{
764 NSArray* tokens = ScanTokensFromString(intervalString);
765 double start, end;
766
767 if ([tokens count] != 2) {
768 OOLog(@"ai.syntax.randomPauseAI", @"***** ERROR: cannot read min and max value for randomPauseAI:, needs 2 values: '%@'.", intervalString);
769 return;
770 }
771
772 start = [tokens oo_doubleAtIndex:0];
773 end = [tokens oo_doubleAtIndex:1];
774
775 [shipAI setNextThinkTime:[UNIVERSE getTime] + (start + (end - start) * randf())];
776}
777
778- (void)dropMessages:(NSString*)messageString
779{
780 NSArray* messages = nil;
781 NSString* message = nil;
782 NSCharacterSet* whiteSpace = [NSCharacterSet whitespaceCharacterSet];
783
784 messages = [messageString componentsSeparatedByString:@","];
785 foreach (message, messages) {
786 [shipAI dropMessage:[message stringByTrimmingCharactersInSet:whiteSpace]];
787 }
788}
789
791{
792 [shipAI debugDumpPendingMessages];
793}
794
796{
797 // randomly add a .5m variance
798 _destination = HPvector_add(position, OOHPVectorRandomSpatial(0.5));
799}
800
802{
803 Vector front = vector_multiply_scalar([self forwardVector], flightSpeed / max_flight_pitch * 2);
804 _destination = HPvector_add(position, vectorToHPVector(vector_add(front, OOVectorRandomSpatial(100))));
805 pitching_over = YES; // don't complete roll first, but immediately start with pitching.
806}
807
808- (void)setDesiredRangeTo:(NSString*)rangeString
809{
810 desired_range = [rangeString doubleValue];
811}
812
814{
815 desired_range = fmax(maxFlightSpeed / max_flight_pitch / 6, 50.0); // some ships need a longer range to reach a waypoint.
816}
817
818- (void)setSpeedTo:(NSString*)speedString
819{
820 desired_speed = [speedString doubleValue];
821}
822
823- (void)setSpeedFactorTo:(NSString*)speedString
824{
825 desired_speed = maxFlightSpeed * [speedString doubleValue];
826}
827
829{
830 desired_speed = cruiseSpeed;
831}
832
833- (void)setThrustFactorTo:(NSString*)thrustFactorString
834{
835 thrust = OOClamp_0_1_f([thrustFactorString doubleValue]) * max_thrust;
836}
837
839{
840 Entity* primeAggressor = [self primaryAggressor];
841 if (!primeAggressor)
842 return;
843 if ([self primaryTarget] == primeAggressor)
844 return;
845
846 // a more considered approach here:
847 // if we're already busy attacking a target we don't necessarily want to break off
848 //
849 if ([self hasHostileTarget] && randf() < 0.75) // if I'm attacking, ignore 75% of new aggressor's attacks
850 {
851 // but add them as a secondary target anyway
852 [self addDefenseTarget:(ShipEntity*)primeAggressor];
853 return;
854 }
855 // react only if the primary aggressor is not a friendly ship, else ignore it
856 if ([primeAggressor isShip] && ![(ShipEntity*)primeAggressor isFriendlyTo:self]) {
857 // inform our old target of our new target
858 //
859 Entity* primeTarget = [self primaryTarget];
860 if ((primeTarget) && (primeTarget->isShip)) {
861 ShipEntity* currentShip = [self primaryTarget];
862 [[currentShip getAI] message:[NSString stringWithFormat:@"%@ %d %d", AIMS_AGGRESSOR_SWITCHED_TARGET, universalID, [[self primaryAggressor] universalID]]];
863 [currentShip doScriptEvent:OOJSID("shipAttackerDistracted") withArgument:[self primaryAggressor]];
864 }
865
866 // okay, so let's now target the aggressor
867 [self addTarget:[self primaryAggressor]];
868 }
869}
870
872{
873 Entity* primeAggressor = [self primaryAggressor];
874 if (!primeAggressor)
875 return;
876 if ([self isDefenseTarget:primeAggressor])
877 return;
878
879 if ([primeAggressor isShip] && ![(ShipEntity*)primeAggressor isFriendlyTo:self]) {
880 [self addDefenseTarget:primeAggressor];
881 }
882}
883
885{
886 float d2, found_d2;
887 unsigned i;
888 ShipEntity* ship = nil;
889
890 //-- Locates the nearest merchantman in range.
892
893 found_d2 = scannerRange * scannerRange;
894 DESTROY(_foundTarget);
895
896 for (i = 0; i < n_scanned_ships; i++) {
897 ship = scanned_ships[i];
898 if ([ship isPirateVictim] && ([ship status] != STATUS_DEAD) && ([ship status] != STATUS_DOCKED) && ![ship isCloaked]) {
899 d2 = distance2_scanned_ships[i];
900 if (PIRATES_PREFER_PLAYER && (d2 < desired_range * desired_range) && ship->isPlayer && [self isPirate]) {
901 d2 = 0.0;
902 } else
903 d2 = distance2_scanned_ships[i];
904 if (d2 < found_d2) {
905 found_d2 = d2;
906 [self setFoundTarget:ship];
907 }
908 }
909 }
910 [self checkFoundTarget];
911}
912
914{
915 unsigned n_found, i;
916
917 //-- Locates one of the merchantman in range.
919 ShipEntity* ids_found[n_scanned_ships];
920
921 n_found = 0;
922 DESTROY(_foundTarget);
923 for (i = 0; i < n_scanned_ships; i++) {
924 ShipEntity* ship = scanned_ships[i];
925 if (([ship status] != STATUS_DEAD) && ([ship status] != STATUS_DOCKED) && [ship isPirateVictim] && ![ship isCloaked])
926 ids_found[n_found++] = ship;
927 }
928 if (n_found == 0) {
929 [shipAI message:@"NOTHING_FOUND"];
930 } else {
931 i = ranrot_rand() % n_found; // pick a number from 0 -> (n_found - 1)
932 [self setFoundTarget:ids_found[i]];
933 [shipAI message:@"TARGET_FOUND"];
934 }
935}
936
938{
939 /*-- Locates the nearest debris in range --*/
940 if (!isStation) {
941 if (![self hasCargoScoop]) {
942 [shipAI message:@"NOTHING_FOUND"]; // can't collect loot if you have no scoop!
943 return;
944 }
945 if ([cargo count] >= [self maxAvailableCargoSpace]) {
946 if (max_cargo)
947 [shipAI message:@"HOLD_FULL"]; // can't collect loot if holds are full!
948 [shipAI message:@"NOTHING_FOUND"]; // can't collect loot if holds are full!
949 return;
950 }
951 } else {
952 if (magnitude2([self velocity])) {
953 [shipAI message:@"NOTHING_FOUND"]; // can't collect loot if you're a moving station
954 return;
955 }
956 }
957
958 [self checkScanner];
959
960 double found_d2 = scannerRange * scannerRange;
961 DESTROY(_foundTarget);
962 unsigned i;
963 for (i = 0; i < n_scanned_ships; i++) {
964 ShipEntity* other = (ShipEntity*)scanned_ships[i];
965 if ([other scanClass] == CLASS_CARGO && [other cargoType] != CARGO_NOT_CARGO && [other status] != STATUS_BEING_SCOOPED) {
966 if ((![self isPolice]) || ([[other commodityType] isEqualToString:@"slaves"])) // police only rescue lifepods and slaves
967 {
968 GLfloat d2 = distance2_scanned_ships[i];
969 if (d2 < found_d2) {
970 found_d2 = d2;
971 [self setFoundTarget:other];
972 }
973 }
974 }
975 }
976 [self checkFoundTarget];
977}
978
980{
981 /*-- Locates the all debris in range and chooses a piece at random from the first sixteen found --*/
982 if (![self isStation] && ![self hasCargoScoop]) {
983 [shipAI message:@"NOTHING_FOUND"]; // can't collect loot if you have no scoop!
984 return;
985 }
986 //
987 [self checkScanner];
988 //
989 ShipEntity* thing_uids_found[16];
990 unsigned things_found = 0;
991 DESTROY(_foundTarget);
992 unsigned i;
993 for (i = 0; (i < n_scanned_ships) && (things_found < 16); i++) {
994 ShipEntity* other = scanned_ships[i];
995 if ([other scanClass] == CLASS_CARGO && [other cargoType] != CARGO_NOT_CARGO && [other status] != STATUS_BEING_SCOOPED) {
996 thing_uids_found[things_found++] = other;
997 }
998 }
999
1000 if (things_found != 0) {
1001 [self setFoundTarget:thing_uids_found[ranrot_rand() % things_found]];
1002 [shipAI message:@"TARGET_FOUND"];
1003 } else
1004 [shipAI message:@"NOTHING_FOUND"];
1005}
1006
1008{
1009 if ([self foundTarget] != nil) {
1010 [self addTarget:[self foundTarget]];
1011 } else {
1012 [shipAI message:@"TARGET_LOST"]; // to prevent the ship going for a wrong, previous target. Should not be a reactToMessage.
1013 }
1014}
1015
1017{
1018 Entity* fTarget = [self foundTarget];
1019 if (fTarget != nil) {
1020 if ([fTarget isShip] && ![(ShipEntity*)fTarget isFriendlyTo:self]) {
1021 [self addDefenseTarget:fTarget];
1022 }
1023 }
1024}
1025
1027{
1028 if (!max_cargo) {
1029 [shipAI message:@"NO_CARGO_BAY"];
1030 } else if ([cargo count] >= [self maxAvailableCargoSpace]) {
1031 [shipAI message:@"HOLD_FULL"];
1032 } else {
1033 [shipAI message:@"HOLD_NOT_FULL"];
1034 }
1035}
1036
1038{
1039 /*- calculates coordinates from the nearest station it can find, or just fly 10s forward -*/
1040 if (!UNIVERSE) {
1041 Vector vr = vector_multiply_scalar(v_forward, maxFlightSpeed * 10.0); // 10 second flying away
1042 coordinates = HPvector_add(position, vectorToHPVector(vr));
1043 return;
1044 }
1045 //
1046 // find the nearest station...
1047 //
1048 // we don't use "checkScanner" because we must rely on finding a present station.
1049 //
1050 StationEntity* station = nil;
1051 station = [UNIVERSE nearestShipMatchingPredicate:IsStationPredicate
1052 parameter:nil
1053 relativeToEntity:self];
1054
1055 if (station && HPdistance2([station position], position) < SCANNER_MAX_RANGE2) // there is a station in range.
1056 {
1057 Vector vr = vector_multiply_scalar([station rightVector], 10000); // 10km from station
1058 coordinates = HPvector_add([station position], vectorToHPVector(vr));
1059 } else {
1060 Vector vr = vector_multiply_scalar(v_forward, maxFlightSpeed * 10.0); // 10 second flying away
1061 coordinates = HPvector_add(position, vectorToHPVector(vr));
1062 }
1063}
1064
1066{
1067 _destination = coordinates;
1068}
1069
1071{
1072 coordinates = position;
1073}
1074
1076{
1077 // find an incoming missile...
1078 //
1079 ShipEntity* missile = nil;
1080 unsigned i;
1081 ShipEntity* escort = nil;
1082 ShipEntity* target = nil;
1083
1085 for (i = 0; (i < n_scanned_ships) && (missile == nil); i++) {
1086 ShipEntity* thing = scanned_ships[i];
1087 if (thing->scanClass == CLASS_MISSILE) {
1088 target = [thing primaryTarget];
1089
1090 if (target == self) {
1091 missile = thing;
1092 } else {
1093 foreach (escort, [self escortEnumerator]) {
1094 if (target == escort) {
1095 missile = thing;
1096 }
1097 }
1098 }
1099 }
1100 }
1101
1102 if (missile == nil)
1103 return;
1104
1105 [self addTarget:missile];
1106 [self addDefenseTarget:missile];
1107
1108 // Notify own ship script that we are being attacked.
1109 ShipEntity* hunter = [missile owner];
1110 [self doScriptEvent:OOJSID("shipBeingAttacked") withArgument:hunter];
1111 [hunter doScriptEvent:OOJSID("shipAttackedOther") withArgument:self];
1112
1113 if ([self isPolice]) {
1114 // Notify other police in group of attacker.
1115 // Note: prior to 1.73 this was done only if we had ECM.
1116 ShipEntity* police = nil;
1117
1118 foreach (police, [[self group] mutationSafeEnumerator]) {
1119 [police setFoundTarget:hunter];
1120 [police setPrimaryAggressor:hunter];
1121 }
1122 }
1123
1124 // if I'm a copper and you're not, then mark the other as an offender!
1125 if ([self isPolice] && ![hunter isPolice])
1126 [hunter markAsOffender:64 withReason:kOOLegalStatusReasonAttackedPolice];
1127
1128 if ([self hasECM]) {
1129 // use the ECM and battle on
1130
1131 [self setPrimaryAggressor:hunter]; // lets get them now for that!
1132 [self setFoundTarget:hunter];
1133
1134 [self fireECM];
1135 return;
1136 }
1137
1138 // RUN AWAY !!
1139 desired_range = 10000;
1140 [self performFlee];
1141 [shipAI message:@"FLEEING"];
1142}
1143
1145{
1146 /*- selects the nearest planet it can find -*/
1147 OOPlanetEntity* the_planet = [self findNearestPlanetExcludingMoons];
1148 if (the_planet) {
1149 double variation = (aegis_status == AEGIS_NONE ? 0.5 : 0.2); // more random deviation when far from planet.
1150 HPVector p_pos = the_planet->position;
1151 double p_cr = the_planet->collision_radius; // the surface
1152 HPVector p1 = HPvector_between(p_pos, position);
1153 p1 = HPvector_normal(p1); // vector towards ship
1154 p1.x += variation * (randf() - variation);
1155 p1.y += variation * (randf() - variation);
1156 p1.z += variation * (randf() - variation);
1157 p1 = HPvector_normal(p1);
1158 _destination = HPvector_add(p_pos, HPvector_multiply_scalar(p1, p_cr)); // on surface
1159 desired_range = collision_radius + 100.0; // +100m from the destination
1160 } else {
1161 [shipAI message:@"NO_PLANET_FOUND"];
1162 }
1163}
1164
1166{
1167 /*- selects the nearest planet it can find -*/
1168 OOPlanetEntity* the_planet = [self findNearestPlanet];
1169 if (the_planet) {
1170 _destination = HPvector_add([the_planet position], HPvector_multiply_scalar(HPvector_normal(HPvector_subtract([the_planet position], position)), -10000.0 - the_planet->collision_radius)); // 10km straight up
1171 desired_range = 50.0;
1172 } else {
1173 OOLog(@"ai.setTakeOffFromPlanet.noPlanet", @"%@", @"***** Error. Planet not found during take off!");
1174 }
1175}
1176
1178{
1179 // Selects the nearest planet it can find.
1180 [self landOnPlanet:[self findNearestPlanet]];
1181}
1182
1184{
1185 ShipEntity* other_ship = [self primaryTarget];
1186 if (!other_ship) {
1187 [shipAI message:@"NO_TARGET"];
1188 return;
1189 } else {
1190 int ls = [other_ship legalStatus];
1191 if (ls > 50) {
1192 [shipAI message:@"TARGET_FUGITIVE"];
1193 return;
1194 }
1195 if (ls > 20) {
1196 [shipAI message:@"TARGET_OFFENDER"];
1197 return;
1198 }
1199 if (ls > 0) {
1200 [shipAI message:@"TARGET_MINOR_OFFENDER"];
1201 return;
1202 }
1203 [shipAI message:@"TARGET_CLEAN"];
1204 }
1205}
1206
1208{
1209 if (scanClass == CLASS_THARGOID) {
1210 [shipAI message:@"SELF_THARGOID"];
1211 return;
1212 }
1213 int ls = [self legalStatus];
1214 if (ls > 50) {
1215 [shipAI message:@"SELF_FUGITIVE"];
1216 return;
1217 }
1218 if (ls > 20) {
1219 [shipAI message:@"SELF_OFFENDER"];
1220 return;
1221 }
1222 if (ls > 0) {
1223 [shipAI message:@"SELF_MINOR_OFFENDER"];
1224 return;
1225 }
1226 [shipAI message:@"SELF_CLEAN"];
1227}
1228
1229- (void)exitAIWithMessage:(NSString*)message
1230{
1231 if ([message length] == 0)
1232 message = @"RESTARTED";
1233 [shipAI exitStateMachineWithMessage:message];
1234}
1235
1237{
1238 Entity* the_target = [self primaryTarget];
1239 if (the_target)
1240 _destination = the_target->position;
1241}
1242
1244{
1245 Entity* the_target = [self primaryTarget];
1246 if (the_target) {
1247 HPVector pos = the_target->position;
1248 Quaternion q;
1251 GLfloat d = (randf() - randf()) * the_target->collision_radius;
1252 _destination = make_HPvector(pos.x + d * v.x, pos.y + d * v.y, pos.z + d * v.z);
1253 }
1254}
1255
1257{
1258 Entity* hazard = [UNIVERSE hazardOnRouteFromEntity:self toDistance:desired_range fromPoint:_destination];
1259
1260 if (hazard == nil || ([hazard isShip] && HPdistance(position, [hazard position]) > scannerRange) || ([hazard isPlanet] && aegis_status == AEGIS_NONE))
1261 [shipAI message:@"COURSE_OK"]; // Avoid going into a waypoint.plist for far away objects, it cripples the main AI a bit in its funtionality.
1262 else {
1263 if ([hazard isShip] && (weapon_damage * 24.0 > [hazard energy])) {
1264 [shipAI reactToMessage:@"HAZARD_CAN_BE_DESTROYED" context:@"checkCourseToDestination"];
1265 }
1266
1267 _destination = [UNIVERSE getSafeVectorFromEntity:self toDistance:desired_range fromPoint:_destination];
1268 [shipAI message:@"WAYPOINT_SET"];
1269 }
1270}
1271
1273{
1274 switch (aegis_status) {
1276 [shipAI message:@"AEGIS_CLOSE_TO_MAIN_PLANET"];
1277 // It's been a few years since 1.71 - it should be safe enough to comment out the line below for 1.77/1.78 -- Kaks 20120917
1278 //[shipAI message:@"AEGIS_CLOSE_TO_PLANET"]; // fires only for main planets, kept for compatibility with pre-1.72 AI plists.
1279 return;
1282
1283 if ([nearest isSun]) {
1284 [shipAI message:@"CLOSE_TO_SUN"];
1285 } else {
1286 [shipAI message:@"CLOSE_TO_PLANET"];
1287 if ([nearest planetType] == STELLAR_TYPE_MOON) {
1288 [shipAI message:@"CLOSE_TO_MOON"];
1289 } else {
1290 [shipAI message:@"CLOSE_TO_SECONDARY_PLANET"];
1291 }
1292 }
1293 return;
1294 }
1296 [shipAI message:@"AEGIS_IN_DOCKING_RANGE"];
1297 return;
1298 case AEGIS_NONE:
1299 [shipAI message:@"AEGIS_NONE"];
1300 return;
1301 }
1302
1303 NSLog(@"Aegis status for %@ has taken on invalid value %i. This is an internal error, please report it.", self, aegis_status);
1304 aegis_status = AEGIS_NONE;
1305 [shipAI message:@"AEGIS_NONE"];
1306}
1307
1309{
1310 if (energy == maxEnergy) {
1311 [shipAI message:@"ENERGY_FULL"];
1312 return;
1313 }
1314 if (energy >= maxEnergy * 0.75) {
1315 [shipAI message:@"ENERGY_HIGH"];
1316 return;
1317 }
1318 if (energy <= maxEnergy * 0.25) {
1319 [shipAI message:@"ENERGY_LOW"];
1320 return;
1321 }
1322 [shipAI message:@"ENERGY_MEDIUM"];
1323}
1324
1326{
1327 float minInsulation = 1000 / [self maxFlightSpeed] + 1;
1328
1329 if ([self heatInsulation] < minInsulation) {
1330 [shipAI message:@"INSULATION_POOR"];
1331 return;
1332 }
1333 [shipAI message:@"INSULATION_OK"];
1334}
1335
1337{
1338 [self checkScanner];
1339 unsigned i;
1340 for (i = 0; i < n_scanned_ships; i++) {
1341 ShipEntity* ship = scanned_ships[i];
1342 if (![ship isCloaked] && (([ship primaryTarget] == self && [ship hasHostileTarget]) || [ship isMine] || ([ship isThargoid] != [self isThargoid]))) {
1343 if (![self isDefenseTarget:ship]) {
1344 [self addDefenseTarget:ship];
1345 return;
1346 }
1347 }
1348 }
1349}
1350
1352{
1353 /*-- Locates all the ships in range and compares their legal status or bounty against ranrot_rand() & 255 - chooses the worst offender --*/
1354 NSDictionary* systeminfo = [UNIVERSE currentSystemData];
1355 float gov_factor = 0.4 * [(NSNumber*)[systeminfo objectForKey:KEY_GOVERNMENT] intValue]; // 0 .. 7 (0 anarchic .. 7 most stable) --> [0.0, 0.4, 0.8, 1.2, 1.6, 2.0, 2.4, 2.8]
1356 //
1357 if ([UNIVERSE sun] == nil)
1358 gov_factor = 1.0;
1359 //
1360 DESTROY(_foundTarget);
1361
1362 // find the worst offender on the scanner
1363 //
1364 [self checkScanner];
1365 unsigned i;
1366 float worst_legal_factor = 0;
1367 GLfloat found_d2 = scannerRange * scannerRange;
1368 OOShipGroup* group = [self group];
1369 for (i = 0; i < n_scanned_ships; i++) {
1370 ShipEntity* ship = scanned_ships[i];
1371 if ((ship->scanClass != CLASS_CARGO) && ([ship status] != STATUS_DEAD) && ([ship status] != STATUS_DOCKED) && ![ship isCloaked]) {
1372 GLfloat d2 = distance2_scanned_ships[i];
1373 float legal_factor = [ship legalStatus] * gov_factor;
1374 int random_factor = ranrot_rand() & 255; // 25% chance of spotting a fugitive in 15s
1375 if ((d2 < found_d2) && (random_factor < legal_factor) && (legal_factor > worst_legal_factor)) {
1376 if (group == nil || group != [ship group]) // fellows with bounty can't be offenders
1377 {
1378 [self setFoundTarget:ship];
1379 worst_legal_factor = legal_factor;
1380 }
1381 }
1382 }
1383 }
1384
1385 [self checkFoundTarget];
1386}
1387
1389{
1390 if (UNIVERSE) {
1391 _destination = [UNIVERSE getWitchspaceExitPosition];
1392 desired_range = 10000.0; // 10km away
1393 }
1394}
1395
1397{
1398 _destination = [UNIVERSE getWitchspaceExitPosition];
1399}
1400
1402{
1403 if ([UNIVERSE station]) {
1404 _destination = [[UNIVERSE station] beaconPosition];
1405 }
1406}
1407
1409{
1411}
1412
1417
1419{
1420 OOLogERR(@"ai.invalid.notPlayer", @"Error in %@:%@, AI method endAutoPilot is only applicable to the player.", [shipAI name], [shipAI state]);
1421}
1422
1424{
1425 ShipEntity* ship = nil;
1426 WormholeEntity* whole = nil;
1427
1428 whole = [self primaryTarget];
1429 if (![whole isWormhole])
1430 return;
1431
1432 foreach (ship, [[self group] mutationSafeEnumerator]) {
1433 [ship addTarget:whole];
1434 [ship reactToAIMessage:@"ENTER WORMHOLE" context:@"wormholeGroup"];
1435 [ship doScriptEvent:OOJSID("wormholeSuggested") withArgument:whole];
1436 }
1437}
1438
1439- (void)commsMessage:(NSString*)valueString
1440{
1441 [self commsMessage:valueString withUnpilotedOverride:NO];
1442}
1443
1444- (void)commsMessageByUnpiloted:(NSString*)valueString
1445{
1446 [self commsMessage:valueString withUnpilotedOverride:YES];
1447}
1448
1450{
1451 OOCargoQuantity i, cargo_to_go = 0.1 * [self maxAvailableCargoSpace];
1452 while (cargo_to_go > 15) {
1453 cargo_to_go = ranrot_rand() % cargo_to_go;
1454 }
1455 [self dumpCargo];
1456 for (i = 1; i < cargo_to_go; i++) {
1457 [self performSelector:@selector(dumpCargo) withObject:nil afterDelay:0.75 * i]; // drop 3 canisters per 2 seconds
1458 }
1459}
1460
1462{
1463 return [self scanForNearestShipWithPrimaryRole:@"thargoid"];
1464}
1465
1467{
1468 /*-- Locates all the non thargoid ships in range and chooses the nearest --*/
1469 DESTROY(_foundTarget);
1470
1471 [self checkScanner];
1472 unsigned i;
1473 GLfloat found_d2 = scannerRange * scannerRange;
1474 for (i = 0; i < n_scanned_ships; i++) {
1475 ShipEntity* thing = scanned_ships[i];
1476 GLfloat d2 = distance2_scanned_ships[i];
1477 if (([thing scanClass] != CLASS_CARGO) && ([thing status] != STATUS_DOCKED) && ![thing isThargoid] && ![thing isCloaked] && (d2 < found_d2)) {
1478 [self setFoundTarget:thing];
1479 if ([thing isPlayer])
1480 d2 = 0.0; // prefer the player
1481 found_d2 = d2;
1482 }
1483 }
1484
1485 [self checkFoundTarget];
1486}
1487
1489{
1490 ShipEntity* mother = [self owner];
1491 if (mother == nil && [self group])
1492 mother = [[self group] leader];
1493
1494 double maxRange2 = scannerRange * scannerRange;
1495
1496 if (mother && mother != self && HPdistance2(mother->position, position) < maxRange2) {
1497 [shipAI message:@"TARGET_FOUND"]; // no need for scanning, we still have our mother.
1498 } else {
1499 // we lost the old mother, search for a new one
1500 [self scanForNearestShipHavingRole:@"thargoid-mothership"]; // the scan will send further AI messages.
1501 if ([self foundTarget] != nil) {
1502 mother = (ShipEntity*)[self foundTarget];
1503 [self setOwner:mother];
1504 if ([mother group] != [mother escortGroup]) // avoid adding thargon to an escort group.
1505 {
1506 [self setGroup:[mother group]];
1507 }
1508 };
1509 }
1510}
1511
1513{
1514 int ent_count = UNIVERSE->n_entities;
1515 Entity** uni_entities = UNIVERSE->sortedEntities; // grab the public sorted list
1516 int i;
1517 for (i = 0; i < ent_count; i++)
1518 if (uni_entities[i]->isShip) {
1519 ShipEntity* other = (ShipEntity*)uni_entities[i];
1520 if ([other primaryTarget] == self) {
1521 [other removeTarget:self];
1522 }
1523 if ([other isDefenseTarget:self]) {
1525 }
1526 }
1527 // now we're just a bunch of alien artefacts!
1528 scanClass = CLASS_CARGO;
1529 reportAIMessages = NO;
1530 [self setAITo:@"dumbAI.plist"];
1531 DESTROY(_primaryTarget);
1532 [self setSpeed:0.0];
1533 [self setGroup:nil];
1534}
1535
1537{
1538 if (distanceTravelled > desired_range)
1539 [shipAI message:@"GONE_BEYOND_RANGE"];
1540}
1541
1543{
1544 [self addDefenseTarget:[self foundTarget]];
1545
1546 if ([self hasEscorts]) {
1547 Entity* leTarget = [self lastEscortTarget];
1548 if (leTarget != nil) {
1549 [self setFoundTarget:leTarget];
1550 [shipAI message:@"FLEEING"];
1551 return;
1552 }
1553
1554 [self setPrimaryAggressor:[self foundTarget]];
1555 [self addTarget:[self foundTarget]];
1556 [self deployEscorts];
1557 [shipAI message:@"DEPLOYING_ESCORTS"];
1558 [shipAI message:@"FLEEING"];
1559 return;
1560 }
1561
1562 // consider launching a missile
1563 if (missiles > 2) // keep a reserve
1564 {
1565 if (randf() < 0.50) {
1566 [self setPrimaryAggressor:[self foundTarget]];
1567 [self addTarget:[self foundTarget]];
1568 [self fireMissile];
1569 [shipAI message:@"FLEEING"];
1570 return;
1571 }
1572 }
1573
1574 // consider fighting
1575 if (energy > maxEnergy * 0.80) {
1576 [self setPrimaryAggressor:[self foundTarget]];
1577 //[self performAttack];
1578 [shipAI message:@"FIGHTING"];
1579 return;
1580 }
1581
1582 [shipAI message:@"FLEEING"];
1583}
1584
1586{
1587 ShipEntity* mother = [self primaryTarget];
1588 [self suggestEscortTo:mother];
1589}
1590
1592{
1593 ShipEntity* mother = [self owner];
1594
1595 if ([mother acceptAsEscort:self]) {
1596 [self setOwner:mother];
1597 [self setGroup:[mother escortGroup]];
1598 [shipAI message:@"ESCORTING"];
1599 } else {
1600 [self setOwner:self];
1601 if ([self group] == [mother escortGroup])
1602 [self setGroup:nil];
1603 [shipAI message:@"NOT_ESCORTING"];
1604 }
1605}
1606
1608{
1609 NSUInteger ownGroupCount = [[self group] count] + (ranrot_rand() & 3); // add a random fudge factor
1610 NSUInteger targetGroupCount = [[[self primaryTarget] group] count] + (ranrot_rand() & 3); // add a random fudge factor
1611
1612 if (ownGroupCount == targetGroupCount) {
1613 [shipAI message:@"ODDS_LEVEL"];
1614 } else if (ownGroupCount > targetGroupCount) {
1615 [shipAI message:@"ODDS_GOOD"];
1616 } else {
1617 [shipAI message:@"ODDS_BAD"];
1618 }
1619}
1620
1622{
1623 //-- Locates the nearest suitable formation leader in range --//
1624 DESTROY(_foundTarget);
1626 unsigned i;
1627 GLfloat found_d2 = scannerRange * scannerRange;
1628 for (i = 0; i < n_scanned_ships; i++) {
1629 ShipEntity* ship = scanned_ships[i];
1630 if ((ship != self) && (!ship->isPlayer) && (ship->scanClass == scanClass) && [ship primaryTarget] != self && ![ship isCloaked]) // look for alike
1631 {
1632 GLfloat d2 = distance2_scanned_ships[i];
1633 if ((d2 < found_d2) && [ship canAcceptEscort:self]) {
1634 found_d2 = d2;
1635 [self setFoundTarget:ship];
1636 }
1637 }
1638 }
1639
1640 if ([self foundTarget] != nil)
1641 [shipAI message:@"TARGET_FOUND"];
1642 else {
1643 [shipAI message:@"NOTHING_FOUND"];
1644 if ([self hasPrimaryRole:@"wingman"]) {
1645 // become free-lance police :)
1646 [self setAITo:@"route1patrolAI.plist"]; // use this to avoid referencing a released AI
1647 [self setPrimaryRole:@"police"]; // other wingman can now select this ship as leader.
1648 }
1649 }
1650}
1651
1652- (void)messageMother:(NSString*)msgString
1653{
1654 ShipEntity* mother = [self owner];
1655 if (mother != nil && mother != self) {
1656 NSString* context = nil;
1657#ifndef NDEBUG
1658 context = [NSString stringWithFormat:@"%@ messageMother", [self shortDescription]];
1659#endif
1660 [mother reactToAIMessage:msgString
1661 context:context];
1662 }
1663}
1664
1665- (void)messageSelf:(NSString*)msgString
1666{
1667 [self sendAIMessage:msgString];
1668}
1669
1671{
1672 // check we've arrived near the last given coordinates
1673 HPVector r_pos = HPvector_subtract(position, coordinates);
1674 if (HPmagnitude2(r_pos) < 1000000 || patrol_counter == 0) {
1675 Entity* the_sun = [UNIVERSE sun];
1676 ShipEntity* the_station = [[self group] leader];
1677 if (!the_station || ![the_station isStation])
1678 the_station = [UNIVERSE station];
1679 if ((!the_sun) || (!the_station))
1680 return;
1681 HPVector sun_pos = the_sun->position;
1682 HPVector stn_pos = the_station->position;
1683 HPVector sun_dir = HPvector_subtract(sun_pos, stn_pos);
1684 Vector vSun = make_vector(0, 0, 1);
1685 if (sun_dir.x || sun_dir.y || sun_dir.z)
1686 vSun = HPVectorToVector(HPvector_normal(sun_dir));
1688 Vector v1 = cross_product(v0, vSun);
1689 Vector v2 = cross_product(v0, v1);
1690 switch (patrol_counter) {
1691 case 0: // first go to 5km ahead of the station
1692 coordinates = make_HPvector(stn_pos.x + 5000 * v0.x, stn_pos.y + 5000 * v0.y, stn_pos.z + 5000 * v0.z);
1693 desired_range = 250.0;
1694 break;
1695 case 1: // go to 25km N of the station
1696 coordinates = make_HPvector(stn_pos.x + 25000 * v1.x, stn_pos.y + 25000 * v1.y, stn_pos.z + 25000 * v1.z);
1697 desired_range = 250.0;
1698 break;
1699 case 2: // go to 25km E of the station
1700 coordinates = make_HPvector(stn_pos.x + 25000 * v2.x, stn_pos.y + 25000 * v2.y, stn_pos.z + 25000 * v2.z);
1701 desired_range = 250.0;
1702 break;
1703 case 3: // go to 25km S of the station
1704 coordinates = make_HPvector(stn_pos.x - 25000 * v1.x, stn_pos.y - 25000 * v1.y, stn_pos.z - 25000 * v1.z);
1705 desired_range = 250.0;
1706 break;
1707 case 4: // go to 25km W of the station
1708 coordinates = make_HPvector(stn_pos.x - 25000 * v2.x, stn_pos.y - 25000 * v2.y, stn_pos.z - 25000 * v2.z);
1709 desired_range = 250.0;
1710 break;
1711 default: // We should never come here
1712 coordinates = make_HPvector(stn_pos.x + 5000 * v0.x, stn_pos.y + 5000 * v0.y, stn_pos.z + 5000 * v0.z);
1713 desired_range = 250.0;
1714 break;
1715 }
1716 patrol_counter++;
1717 if (patrol_counter > 4) {
1718 if (randf() < .25) {
1719 // consider docking
1720 [self setTargetStation:the_station];
1721 [self setAITo:@"dockingAI.plist"];
1722 return;
1723 } else {
1724 // go around again
1725 patrol_counter = 1;
1726 }
1727 }
1728 }
1729 [shipAI message:@"APPROACH_COORDINATES"];
1730}
1731
1733{
1734 if ([UNIVERSE sun] == nil) {
1735 [shipAI message:@"NO_SUN_FOUND"];
1736 return;
1737 }
1738
1739 HPVector v0 = [UNIVERSE getSunSkimStartPositionForShip:self];
1740
1741 if (!HPvector_equal(v0, kZeroHPVector)) {
1742 coordinates = v0;
1743 [shipAI message:@"APPROACH_COORDINATES"];
1744 } else {
1745 [shipAI message:@"WAIT_FOR_SUN"];
1746 }
1747}
1748
1750{
1751 if ([UNIVERSE sun] == nil) {
1752 [shipAI message:@"NO_SUN_FOUND"];
1753 return;
1754 }
1755
1756 coordinates = [UNIVERSE getSunSkimEndPositionForShip:self];
1757 [shipAI message:@"APPROACH_COORDINATES"];
1758}
1759
1761{
1762 Entity* the_sun = [UNIVERSE sun];
1763 if (the_sun == nil)
1764 return;
1765 HPVector v1 = [UNIVERSE getSunSkimEndPositionForShip:self];
1766 HPVector vs = the_sun->position;
1767 HPVector vout = HPvector_subtract(v1, vs);
1768 if (vout.x || vout.y || vout.z)
1769 vout = HPvector_normal(vout);
1770 else
1771 vout.z = 1.0;
1772 v1.x += 10000 * vout.x;
1773 v1.y += 10000 * vout.y;
1774 v1.z += 10000 * vout.z;
1775 coordinates = v1;
1776 [shipAI message:@"APPROACH_COORDINATES"];
1777}
1778
1780{
1781 // Set a report time in the patrolled station to delay a new launch.
1782 ShipEntity* the_station = [[self group] leader];
1783 if (!the_station || ![the_station isStation])
1784 the_station = [UNIVERSE station];
1786}
1787
1789{
1790 ShipEntity* motherStation = [[self group] leader];
1791 if ((!motherStation) || (!(motherStation->isStation))) {
1792 [shipAI message:@"NOTHING_FOUND"];
1793 return;
1794 }
1795 double found_d2 = scannerRange * scannerRange;
1796 HPVector v0 = motherStation->position;
1797 if (HPdistance2(v0, position) > found_d2) {
1798 [shipAI message:@"NOTHING_FOUND"];
1799 return;
1800 }
1801 [shipAI message:@"STATION_FOUND"];
1802}
1803
1804- (void)sendTargetCommsMessage:(NSString*)message
1805{
1806 ShipEntity* ship = [self primaryTarget];
1807 if ((ship == nil) || ([ship status] == STATUS_DEAD) || ([ship status] == STATUS_DOCKED)) {
1808 [self noteLostTarget];
1809 return;
1810 }
1811 [self sendExpandedMessage:message toShip:[self primaryTarget]];
1812}
1813
1815{
1816 ShipEntity* ship = [self primaryTarget];
1817 if ((ship == nil) || ([ship status] == STATUS_DEAD) || ([ship status] == STATUS_DOCKED)) {
1818 [self noteLostTarget];
1819 return;
1820 }
1821 if ([ship markForFines])
1822 [shipAI message:@"TARGET_MARKED"];
1823}
1824
1825- (void)markTargetForOffence:(NSString*)valueString
1826{
1827 if ((isStation) || (scanClass == CLASS_POLICE)) {
1828 ShipEntity* ship = [self primaryTarget];
1829 if ((ship == nil) || ([ship status] == STATUS_DEAD) || ([ship status] == STATUS_DOCKED)) {
1830 [self noteLostTarget];
1831 return;
1832 }
1833 NSString* finalValue = OOExpand(valueString); // expand values
1834 [ship markAsOffender:[finalValue intValue] withReason:kOOLegalStatusReasonSeenByPolice];
1835 }
1836}
1837
1839{
1840 Entity* target = [self primaryTarget];
1841
1842 if (target) {
1843 [self setRememberedShip:target];
1844 } else {
1845 DESTROY(_rememberedShip);
1846 }
1847}
1848
1850{
1851 ShipEntity* oldTarget = (ShipEntity*)[self rememberedShip];
1852 BOOL found = NO;
1853
1854 if (oldTarget && ![oldTarget isCloaked]) {
1855 GLfloat range2 = HPdistance2([oldTarget position], position);
1856 if (range2 <= scannerRange * scannerRange && range2 <= SCANNER_MAX_RANGE2) {
1857 found = YES;
1858 }
1859 }
1860
1861 if (found) {
1862 [self setFoundTarget:oldTarget];
1863 [shipAI message:@"TARGET_FOUND"];
1864 } else {
1865 if (oldTarget == nil)
1866 DESTROY(_rememberedShip); // ship no longer exists
1867 [shipAI message:@"NOTHING_FOUND"];
1868 }
1869}
1870
1872{
1873 /*-- Locates the all boulders and asteroids in range and selects nearest --*/
1874
1875 // find boulders then asteroids within range
1876 //
1877 DESTROY(_foundTarget);
1878 [self checkScanner];
1879 unsigned i;
1880 GLfloat found_d2 = scannerRange * scannerRange;
1881 for (i = 0; i < n_scanned_ships; i++) {
1882 ShipEntity* thing = scanned_ships[i];
1883 if ([thing isBoulder]) {
1884 GLfloat d2 = distance2_scanned_ships[i];
1885 if (d2 < found_d2) {
1886 [self setFoundTarget:thing];
1887 found_d2 = d2;
1888 }
1889 }
1890 }
1891 if ([self foundTarget] == nil) {
1892 for (i = 0; i < n_scanned_ships; i++) {
1893 ShipEntity* thing = scanned_ships[i];
1894 if ([thing hasRole:@"asteroid"]) {
1895 GLfloat d2 = distance2_scanned_ships[i];
1896 if (d2 < found_d2) {
1897 [self setFoundTarget:thing];
1898 found_d2 = d2;
1899 }
1900 }
1901 }
1902 }
1903
1904 [self checkFoundTarget];
1905}
1906
1908{
1909 Entity* the_target = [self targetStation];
1910 if (!the_target) {
1911 /* Probably the player trying to dock with docking computer
1912 * from out of scanner range */
1913 the_target = [UNIVERSE station];
1914 }
1915 double bo_distance = 8000; // 8km back off
1916 HPVector v0 = position;
1917 HPVector d0 = (the_target) ? the_target->position : kZeroHPVector;
1918 v0.x += (randf() - 0.5) * collision_radius;
1919 v0.y += (randf() - 0.5) * collision_radius;
1920 v0.z += (randf() - 0.5) * collision_radius;
1921 v0.x -= d0.x;
1922 v0.y -= d0.y;
1923 v0.z -= d0.z;
1924 v0 = HPvector_normal_or_fallback(v0, make_HPvector(0, 0, -1));
1925
1926 v0.x *= bo_distance;
1927 v0.y *= bo_distance;
1928 v0.z *= bo_distance;
1929 v0.x += d0.x;
1930 v0.y += d0.y;
1931 v0.z += d0.z;
1932 coordinates = v0;
1933 _destination = v0;
1934}
1935
1937{
1938 ShipEntity* mother = [[self group] leader];
1939 if (mother == nil) {
1940 [shipAI message:@"MOTHER_LOST"];
1941 return;
1942 }
1943
1944 /*-- Locates all the ships in range targeting the mother ship and chooses the nearest/biggest --*/
1945 DESTROY(_foundTarget);
1946 [self checkScanner];
1947 unsigned i;
1948 GLfloat found_d2 = scannerRange * scannerRange;
1949 GLfloat max_e = 0;
1950 for (i = 0; i < n_scanned_ships; i++) {
1951 ShipEntity* thing = scanned_ships[i];
1952 GLfloat d2 = distance2_scanned_ships[i];
1953 GLfloat e1 = [thing energy];
1954 if ((d2 < found_d2) && ![thing isCloaked] && (([thing isThargoid] && ![mother isThargoid]) || (([thing primaryTarget] == mother) && [thing hasHostileTarget]))) {
1955 if (e1 > max_e) {
1956 [self setFoundTarget:thing];
1957 max_e = e1;
1958 }
1959 }
1960 }
1961
1962 [self checkFoundTarget];
1963}
1964
1965- (void)rollD:(NSString*)die_number
1966{
1967 int die_sides = [die_number intValue];
1968 if (die_sides > 0) {
1969 int die_roll = 1 + (ranrot_rand() % die_sides);
1970 NSString* result = [NSString stringWithFormat:@"ROLL_%d", die_roll];
1971 [shipAI reactToMessage:result context:@"rollD:"];
1972 } else {
1973 OOLog(@"ai.rollD.invalidValue", @"***** ERROR: invalid value supplied to rollD: '%@'.", die_number);
1974 }
1975}
1976
1977- (void)scanForNearestShipWithPrimaryRole:(NSString*)scanRole
1978{
1979 [self scanForNearestShipWithPredicate:HasPrimaryRolePredicate parameter:scanRole];
1980}
1981
1982- (void)scanForNearestShipHavingRole:(NSString*)scanRole
1983{
1984 [self scanForNearestShipWithPredicate:HasRolePredicate parameter:scanRole];
1985}
1986
1987- (void)scanForNearestShipWithAnyPrimaryRole:(NSString*)scanRoles
1988{
1989 NSSet* set = [NSSet setWithArray:ScanTokensFromString(scanRoles)];
1990 [self scanForNearestShipWithPredicate:HasPrimaryRoleInSetPredicate parameter:set];
1991}
1992
1993- (void)scanForNearestShipHavingAnyRole:(NSString*)scanRoles
1994{
1995 NSSet* set = [NSSet setWithArray:ScanTokensFromString(scanRoles)];
1996 [self scanForNearestShipWithPredicate:HasRoleInSetPredicate parameter:set];
1997}
1998
1999- (void)scanForNearestShipWithScanClass:(NSString*)scanScanClass
2000{
2001 NSNumber* parameter = [NSNumber numberWithInt:OOScanClassFromString(scanScanClass)];
2002 [self scanForNearestShipWithPredicate:HasScanClassPredicate parameter:parameter];
2003}
2004
2005- (void)scanForNearestShipWithoutPrimaryRole:(NSString*)scanRole
2006{
2007 [self scanForNearestShipWithNegatedPredicate:HasPrimaryRolePredicate parameter:scanRole];
2008}
2009
2010- (void)scanForNearestShipNotHavingRole:(NSString*)scanRole
2011{
2012 [self scanForNearestShipWithNegatedPredicate:HasRolePredicate parameter:scanRole];
2013}
2014
2015- (void)scanForNearestShipWithoutAnyPrimaryRole:(NSString*)scanRoles
2016{
2017 NSSet* set = [NSSet setWithArray:ScanTokensFromString(scanRoles)];
2018 [self scanForNearestShipWithNegatedPredicate:HasPrimaryRoleInSetPredicate parameter:set];
2019}
2020
2021- (void)scanForNearestShipNotHavingAnyRole:(NSString*)scanRoles
2022{
2023 NSSet* set = [NSSet setWithArray:ScanTokensFromString(scanRoles)];
2024 [self scanForNearestShipWithNegatedPredicate:HasRoleInSetPredicate parameter:set];
2025}
2026
2027- (void)scanForNearestShipWithoutScanClass:(NSString*)scanScanClass
2028{
2029 NSNumber* parameter = [NSNumber numberWithInt:OOScanClassFromString(scanScanClass)];
2030 [self scanForNearestShipWithNegatedPredicate:HasScanClassPredicate parameter:parameter];
2031}
2032
2033- (void)scanForNearestShipMatchingPredicate:(NSString*)predicateExpression
2034{
2035 /* Takes a boolean-valued JS expression where "ship" is the ship being
2036 evaluated and "this" is our ship's ship script. the expression is
2037 turned into a JS function of the form:
2038
2039 function _oo_AIScanPredicate(ship)
2040 {
2041 return $expression;
2042 }
2043
2044 Examples of expressions:
2045 ship.isWeapon
2046 this.someComplicatedPredicate(ship)
2047 function (ship) { ...do something complicated... } ()
2048 */
2049
2050 static NSMutableDictionary* scriptCache = nil;
2051 NSString* aiName = nil;
2052 NSString* key = nil;
2053 OOJSFunction* function = nil;
2054 JSContext* context = NULL;
2055
2056 context = OOJSAcquireContext();
2057
2058 if (predicateExpression == nil)
2059 predicateExpression = @"false";
2060
2061 aiName = [[self getAI] name];
2062#ifndef NDEBUG
2063 /* In debug/test release builds, scripts are cached per AI in order to be
2064 able to report errors correctly. For end-user releases, we only cache
2065 one copy of each predicate, potentially leading to error messages for
2066 the wrong AI.
2067 */
2068 key = [NSString stringWithFormat:@"%@\n%@", aiName, predicateExpression];
2069#else
2070 key = predicateExpression;
2071#endif
2072
2073 // Look for cached function
2074 function = [scriptCache objectForKey:key];
2075 if (function == nil) {
2076 NSString* predicateCode = nil;
2077 const char* argNames[] = { "ship" };
2078
2079 // Stuff expression in a function.
2080 predicateCode = [NSString stringWithFormat:@"return %@;", predicateExpression];
2081 function = [[OOJSFunction alloc] initWithName:@"_oo_AIScanPredicate"
2082#if OOJS_QUICKJS
2083 scope:JS_UNDEFINED
2084#else
2085 scope:NULL
2086#endif
2087 code:predicateCode
2088 argumentCount:1
2089 argumentNames:argNames
2090 fileName:aiName
2091 lineNumber:0
2092 context:context];
2093 [function autorelease];
2094
2095 // Cache function.
2096 if (function != nil) {
2097 if (scriptCache == nil)
2098 scriptCache = [[NSMutableDictionary alloc] init];
2099 [scriptCache setObject:function forKey:key];
2100 }
2101 }
2102
2103 if (function != nil) {
2104#if OOJS_QUICKJS
2105 JSValue jsThis = OOJSObjectFromNativeObject(context, self); // Owned.
2107 .context = context,
2108 .function = [function function], // Borrowed.
2109 .jsThis = jsThis
2110 };
2111 [self scanForNearestShipWithPredicate:JSFunctionPredicate parameter:&param];
2112 JS_FreeValue(context, jsThis);
2113#else
2115 .context = context,
2116 .function = [function functionValue],
2117 .jsThis = OOJSObjectFromNativeObject(context, self)
2118 };
2119 [self scanForNearestShipWithPredicate:JSFunctionPredicate parameter:&param];
2120#endif
2121 } else {
2122 // Report error (once per occurrence)
2123 static NSMutableSet* errorCache = nil;
2124
2125 if (![errorCache containsObject:key]) {
2126 OOLog(@"ai.scanForNearestShipMatchingPredicate.compile.failed", @"Could not compile JavaScript predicate \"%@\" for AI %@.", predicateExpression, [[self getAI] name]);
2127 if (errorCache == nil)
2128 errorCache = [[NSMutableSet alloc] init];
2129 [errorCache addObject:key];
2130 }
2131
2132 // Select nothing
2133 DESTROY(_foundTarget);
2134 [[self getAI] message:@"NOTHING_FOUND"];
2135 }
2136
2138 OOJSRelinquishContext(context);
2139}
2140
2141- (void)setCoordinates:(NSString*)system_x_y_z
2142{
2143 NSArray* tokens = ScanTokensFromString(system_x_y_z);
2144 NSString* systemString = nil;
2145 NSString* xString = nil;
2146 NSString* yString = nil;
2147 NSString* zString = nil;
2148
2149 if ([tokens count] != 4) {
2150 OOLog(@"ai.syntax.setCoordinates", @"***** ERROR: cannot setCoordinates: '%@'.", system_x_y_z);
2151 return;
2152 }
2153
2154 systemString = (NSString*)[tokens objectAtIndex:0];
2155 xString = (NSString*)[tokens objectAtIndex:1];
2156 if ([xString hasPrefix:@"rand:"])
2157 xString = [NSString stringWithFormat:@"%.3f", bellf([(NSString*)[[xString componentsSeparatedByString:@":"] objectAtIndex:1] intValue])];
2158 yString = (NSString*)[tokens objectAtIndex:2];
2159 if ([yString hasPrefix:@"rand:"])
2160 yString = [NSString stringWithFormat:@"%.3f", bellf([(NSString*)[[yString componentsSeparatedByString:@":"] objectAtIndex:1] intValue])];
2161 zString = (NSString*)[tokens objectAtIndex:3];
2162 if ([zString hasPrefix:@"rand:"])
2163 zString = [NSString stringWithFormat:@"%.3f", bellf([(NSString*)[[zString componentsSeparatedByString:@":"] objectAtIndex:1] intValue])];
2164
2165 HPVector posn = make_HPvector([xString floatValue], [yString floatValue], [zString floatValue]);
2166 GLfloat scalar = 1.0;
2167
2168 coordinates = [UNIVERSE coordinatesForPosition:posn withCoordinateSystem:systemString returningScalar:&scalar];
2169
2170 [shipAI message:@"APPROACH_COORDINATES"];
2171}
2172
2174{
2175 if ([UNIVERSE sun] && [UNIVERSE planet])
2176 [shipAI message:@"NORMAL_SPACE"];
2177 else
2178 [shipAI message:@"INTERSTELLAR_SPACE"];
2179}
2180
2182{
2183 /*- selects the nearest station it can find -*/
2184 int ent_count = UNIVERSE->n_entities;
2185 Entity** uni_entities = UNIVERSE->sortedEntities; // grab the public sorted list
2186 Entity* my_entities[ent_count];
2187 StationEntity *station = nil, *my_station = nil;
2188 double maxRange2 = desired_range * desired_range;
2189 int i;
2190 int station_count = 0;
2191
2192 for (i = 0; i < ent_count; i++) {
2193 // find stations within range but exclude carriers.
2194 if (uni_entities[i]->isStation) {
2195 my_station = (StationEntity*)uni_entities[i];
2196 if ([my_station maxFlightSpeed] == 0 && [my_station hasNPCTraffic] && HPdistance2(position, [my_station position]) < maxRange2) {
2197 my_entities[station_count++] = [uni_entities[i] retain]; // retained
2198 }
2199 }
2200 }
2201
2202 if (station_count != 0) {
2203 // select a random station
2204 station = (StationEntity*)my_entities[ranrot_rand() % station_count];
2205 // if more than one candidate do not select main station
2206 if (station == [UNIVERSE station] && station_count > 1) {
2207 while (station == [UNIVERSE station]) {
2208 station = (StationEntity*)my_entities[ranrot_rand() % station_count];
2209 }
2210 }
2211 }
2212
2213 for (i = 0; i < station_count; i++)
2214 [my_entities[i] release]; // released
2215 //
2216 if (station) {
2217 [self addTarget:station];
2218 [self setTargetStation:station];
2219 [shipAI message:@"STATION_FOUND"];
2220 } else {
2221 [shipAI message:@"NO_STATION_IN_RANGE"];
2222 }
2223}
2224
2226{
2227 Entity* station = [self targetStation];
2228
2229 if (station != nil && [station isStation]) {
2230 [self addTarget:station];
2231 } else {
2232 [shipAI message:@"NO_STATION_FOUND"];
2233 [self setTargetStation:nil];
2234 }
2235}
2236
2237- (void)addFuel:(NSString*)fuel_number
2238{
2239 [self setFuel:[self fuel] + [fuel_number intValue] * 10];
2240}
2241
2242- (void)scriptActionOnTarget:(NSString*)action
2243{
2244 PlayerEntity* player = PLAYER;
2245 ShipEntity* targEnt = [self primaryTarget];
2246 ShipEntity* oldTarget = nil;
2247
2248#ifndef NDEBUG
2249 static BOOL deprecationWarning = NO;
2250
2251 if (!deprecationWarning) {
2252 deprecationWarning = YES;
2253 OOLog(@"script.deprecated.scriptActionOnTarget", @"----- WARNING in AI %@: the AI method scriptActionOnTarget: is deprecated and should not be used. It is slow and has unpredictable side effects. The recommended alternative is to use sendScriptMessage: to call a function in a ship's JavaScript ship script instead. scriptActionOnTarget: should not be used at all from scripts. An alternative is safeScriptActionOnTarget:, which is similar to scriptActionOnTarget: but has less side effects.", [AI currentlyRunningAIDescription]);
2254 } else {
2255 OOLog(@"script.deprecated.scriptActionOnTarget.repeat", @"----- WARNING in AI %@: the AI method scriptActionOnTarget: is deprecated and should not be used.", [AI currentlyRunningAIDescription]);
2256 }
2257#endif
2258
2259 if ([targEnt isShip]) {
2260 oldTarget = [player scriptTarget];
2261 [player setScriptTarget:(ShipEntity*)targEnt];
2262 [player runUnsanitizedScriptActions:[NSArray arrayWithObject:action]
2264 withContextName:[NSString stringWithFormat:@"<AI \"%@\" state %@ - scriptActionOnTarget:>", [[self getAI] name], [[self getAI] state]]
2265 forTarget:targEnt];
2266 [player checkScript]; // react immediately to any changes this makes
2267 [player setScriptTarget:oldTarget];
2268 }
2269}
2270
2271- (void)safeScriptActionOnTarget:(NSString*)action
2272{
2273 PlayerEntity* player = PLAYER;
2274 ShipEntity* targEnt = [self primaryTarget];
2275 ShipEntity* oldTarget = nil;
2276
2277 if ([targEnt isShip]) {
2278 oldTarget = [player scriptTarget];
2279 [player setScriptTarget:(ShipEntity*)targEnt];
2280 [player runUnsanitizedScriptActions:[NSArray arrayWithObject:action]
2282 withContextName:[NSString stringWithFormat:@"<AI \"%@\" state %@ - safeScriptActionOnTarget:>", [[self getAI] name], [[self getAI] state]]
2283 forTarget:targEnt];
2284 [player setScriptTarget:oldTarget];
2285 }
2286}
2287
2288// Send own ship script a message.
2289- (void)sendScriptMessage:(NSString*)message
2290{
2291 NSArray* components = ScanTokensFromString(message);
2292
2293 if ([components count] == 1) {
2294 [self doScriptEvent:OOJSIDFromString(message)];
2295 } else {
2296 NSString* function = [components objectAtIndex:0];
2297 components = [components subarrayWithRange:NSMakeRange(1, [components count] - 1)];
2298 [self doScriptEvent:OOJSIDFromString(function) withArgument:components];
2299 }
2300}
2301
2303{
2304 [self setThrowSparks:YES];
2305}
2306
2308{
2309 [self getDestroyedBy:nil damageType:kOODamageTypeEnergy];
2310}
2311
2312- (void)ai_debugMessage:(NSString*)message
2313{
2314 NSString* desc = [NSString stringWithFormat:@"%@ %d", [self name], [self universalID]];
2315 if ([self isPlayer])
2316 desc = @"player autopilot";
2317 OOLog(@"ai.takeAction.debugMessage", @"DEBUG: AI MESSAGE from %@: %@", desc, message);
2318}
2319
2320// racing code TODO
2321- (void)targetFirstBeaconWithCode:(NSString*)code
2322{
2323 NSArray* all_beacons = [UNIVERSE listBeaconsWithCode:code];
2324 if ([all_beacons count]) {
2325 [self addTarget:(ShipEntity*)[all_beacons objectAtIndex:0]];
2326 [shipAI message:@"TARGET_FOUND"];
2327 } else
2328 [shipAI message:@"NOTHING_FOUND"];
2329}
2330
2331- (void)targetNextBeaconWithCode:(NSString*)code
2332{
2333 NSArray* all_beacons = [UNIVERSE listBeaconsWithCode:code];
2334 ShipEntity* current_beacon = [self primaryTarget];
2335
2336 if ((!current_beacon) || (![current_beacon isBeacon])) {
2337 [shipAI message:@"NO_CURRENT_BEACON"];
2338 [shipAI message:@"NOTHING_FOUND"];
2339 return;
2340 }
2341
2342 // find the current beacon in the list..
2343 NSUInteger i = [all_beacons indexOfObject:current_beacon];
2344
2345 if (i == NSNotFound) {
2346 [shipAI message:@"NOTHING_FOUND"];
2347 return;
2348 }
2349
2350 i++; // next index
2351
2352 if (i < [all_beacons count]) {
2353 // locate current target in list
2354 [self addTarget:(ShipEntity*)[all_beacons objectAtIndex:i]];
2355 [shipAI message:@"TARGET_FOUND"];
2356 } else {
2357 [shipAI message:@"LAST_BEACON"];
2358 [shipAI message:@"NOTHING_FOUND"];
2359 }
2360}
2361
2363{
2364 // two point - one at z - cr one at z + cr
2365 ShipEntity* ship = [self primaryTarget];
2366 if (ship == nil) {
2367 [shipAI message:@"NOTHING_FOUND"];
2368 return;
2369 }
2370 Vector k = ship->v_forward;
2371 GLfloat c = ship->collision_radius;
2372 HPVector o = ship->position;
2373 navpoints[0] = make_HPvector(o.x - c * k.x, o.y - c * k.y, o.z - c * k.z);
2374 navpoints[1] = make_HPvector(o.x + c * k.x, o.y + c * k.y, o.z + c * k.z);
2375 navpoints[2] = make_HPvector(o.x + 2.0 * c * k.x, o.y + 2.0 * c * k.y, o.z + 2.0 * c * k.z);
2376 number_of_navpoints = 2;
2377 next_navpoint_index = 0;
2378 _destination = navpoints[0];
2379 [shipAI message:@"RACEPOINTS_SET"];
2380}
2381
2383{
2384 next_navpoint_index = 0;
2385 desired_range = collision_radius;
2386 behaviour = BEHAVIOUR_FLY_THRU_NAVPOINTS;
2387}
2388
2389@end
2390
2391@implementation ShipEntity (OOAIPrivate)
2392
2394{
2395 if ([self foundTarget] != nil) {
2396 [shipAI message:@"TARGET_FOUND"];
2397 } else {
2398 [shipAI message:@"NOTHING_FOUND"];
2399 }
2400}
2401
2402- (BOOL)performHyperSpaceExitReplace:(BOOL)replace
2403{
2404 return [self performHyperSpaceExitReplace:replace toSystem:-1];
2405}
2406
2407- (BOOL)performHyperSpaceExitReplace:(BOOL)replace toSystem:(OOSystemID)systemID
2408{
2409 if (![self hasHyperspaceMotor]) {
2410 [shipAI reactToMessage:@"WITCHSPACE UNAVAILABLE" context:@"performHyperSpaceExit"];
2411 return NO;
2412 }
2413 if ([self status] == STATUS_ENTERING_WITCHSPACE) {
2414 // already in a wormhole
2415 return NO;
2416 }
2417
2418 NSArray* sDests = nil;
2419 OOSystemID targetSystem;
2420 NSUInteger i = 0;
2421
2422 // get a list of destinations within range
2423 sDests = [UNIVERSE nearbyDestinationsWithinRange:0.1f * fuel];
2424 NSUInteger n_dests = [sDests count];
2425
2426 // if none available report to the AI and exit
2427 if (n_dests == 0) {
2428 [shipAI reactToMessage:@"WITCHSPACE UNAVAILABLE" context:@"performHyperSpaceExit"];
2429
2430 // If no systems exist near us, the AI is switched to a different state, so we do not need
2431 // the nearby destinations array anymore.
2432 return NO;
2433 }
2434
2435 // check if we're clear of nearby masses
2436 ShipEntity* blocker = [UNIVERSE entityForUniversalID:[self checkShipsInVicinityForWitchJumpExit]];
2437 if (blocker) {
2438 [self setFoundTarget:blocker];
2439 [shipAI reactToMessage:@"WITCHSPACE BLOCKED" context:@"performHyperSpaceExit"];
2440 [self doScriptEvent:OOJSID("shipWitchspaceBlocked") withArgument:blocker];
2441
2442 return NO;
2443 }
2444
2445 if (systemID == -1) {
2446 // select one at random
2447 if (n_dests > 1) {
2448 i = ranrot_rand() % n_dests;
2449 }
2450
2451 targetSystem = [[sDests oo_dictionaryAtIndex:i] oo_intForKey:@"sysID"];
2452 } else {
2453 targetSystem = systemID;
2454
2455 for (i = 0; i < n_dests; i++) {
2456 if (systemID == [[sDests oo_dictionaryAtIndex:i] oo_intForKey:@"sysID"])
2457 break;
2458 }
2459
2460 if (i == n_dests) // no match found
2461 {
2462 return NO;
2463 }
2464 }
2465 float dist = [[sDests oo_dictionaryAtIndex:i] oo_floatForKey:@"distance"];
2466 if (dist > [self maxHyperspaceDistance] || dist > fuel / 10.0f) {
2467 OOLogWARN(@"script.debug", @"DEBUG: %@ Jumping %f which is further than allowed. I have %d fuel", self, dist, fuel);
2468 }
2469 fuel -= 10 * dist;
2470
2471 // create wormhole
2472 WormholeEntity* whole = [[[WormholeEntity alloc] initWormholeTo:targetSystem fromShip:self] autorelease];
2473 [UNIVERSE addEntity:whole];
2474
2475 [self enterWormhole:whole replacing:replace];
2476
2477 // we've no need for the destinations array anymore.
2478 return YES;
2479}
2480
2481- (void)scanForNearestShipWithPredicate:(EntityFilterPredicate)predicate parameter:(void*)parameter
2482{
2483 // Locates all the ships in range for which predicate returns YES, and chooses the nearest.
2484 unsigned i;
2485 ShipEntity* candidate;
2486 float d2, found_d2 = scannerRange * scannerRange;
2487
2488 DESTROY(_foundTarget);
2489 [self checkScanner];
2490
2491 if (predicate == NULL)
2492 return;
2493
2494 for (i = 0; i < n_scanned_ships; i++) {
2495 candidate = scanned_ships[i];
2496 d2 = distance2_scanned_ships[i];
2497 if ((d2 < found_d2) && (candidate->scanClass != CLASS_CARGO) && ([candidate status] != STATUS_DOCKED)
2498 && predicate(candidate, parameter) && ![candidate isCloaked]) {
2499 [self setFoundTarget:candidate];
2500 found_d2 = d2;
2501 }
2502 }
2503
2504 [self checkFoundTarget];
2505}
2506
2507- (void)scanForNearestShipWithNegatedPredicate:(EntityFilterPredicate)predicate parameter:(void*)parameter
2508{
2509 ChainedEntityPredicateParameter param = { predicate, parameter };
2510 [self scanForNearestShipWithPredicate:NOTPredicate parameter:&param];
2511}
2512
2513- (void)acceptDistressMessageFrom:(ShipEntity*)other
2514{
2516 if ([self isPolice]) {
2517 [(ShipEntity*)[self foundTarget] markAsOffender:8 withReason:kOOLegalStatusReasonDistressCall]; // you have been warned!!
2518 }
2519
2520 NSString* context = nil;
2521#ifndef NDEBUG
2522 context = [NSString stringWithFormat:@"%@ broadcastDistressMessage", [other shortDescription]];
2523#endif
2524 [shipAI reactToMessage:@"ACCEPT_DISTRESS_CALL"
2525 context:context];
2526}
2527
2528@end
2529
2530@implementation StationEntity (OOAIPrivate)
2531
2532- (void)acceptDistressMessageFrom:(ShipEntity*)other
2533{
2534 if (self != [UNIVERSE station])
2535 return;
2536
2537 OOWeakReference* old_target = _primaryTarget;
2538 _primaryTarget = [[[other primaryTarget] weakRetain] autorelease];
2539 [(ShipEntity*)[other primaryTarget] markAsOffender:8 withReason:kOOLegalStatusReasonDistressCall]; // mark their card
2540 [self launchDefenseShip];
2541 _primaryTarget = old_target;
2542}
2543
2544@end
2545
2546@implementation ShipEntity (OOAIStationStubs)
2547
2548// AI methods for stations, have no effect on normal ships.
2549
2550#define STATION_STUB_BASE(PROTO, NAME) \
2551 PROTO { OOLog(@"ai.invalid.notAStation", @"Attempt to use station AI method \"%s\" on non-station %@.", NAME, self); }
2552#define STATION_STUB_NOARG(NAME) STATION_STUB_BASE(-(void)NAME, #NAME)
2553#define STATION_STUB_ARG(NAME) STATION_STUB_BASE(-(void)NAME(NSString*) param, #NAME)
2554
2555STATION_STUB_NOARG(increaseAlertLevel)
2556STATION_STUB_NOARG(decreaseAlertLevel)
2557STATION_STUB_NOARG(launchPolice)
2558STATION_STUB_NOARG(launchDefenseShip)
2559STATION_STUB_NOARG(launchScavenger)
2560STATION_STUB_NOARG(launchMiner)
2561STATION_STUB_NOARG(launchPirateShip)
2562STATION_STUB_NOARG(launchShuttle)
2563STATION_STUB_NOARG(launchTrader)
2564STATION_STUB_NOARG(launchEscort)
2566{
2567 OOLog(@"ai.invalid.notAStation", @"Attempt to use station AI method \"%s\" on non-station %@.", "launchPatrol", self);
2568 return NO;
2569}
2570STATION_STUB_ARG(launchShipWithRole:)
2571STATION_STUB_NOARG(abortAllDockings)
2572
2573@end
#define SCANNER_MAX_RANGE2
Definition Entity.h:54
BOOL HasScanClassPredicate(Entity *entity, void *parameter)
BOOL IsHostileAgainstTargetPredicate(Entity *ship, void *parameter)
OOINLINE float OOClamp_0_1_f(float value) INLINE_CONST_FUNC
#define DESTROY(x)
OOINLINE HPVector vectorToHPVector(Vector v) INLINE_CONST_FUNC
Definition OOHPVector.h:166
OOINLINE HPVector HPvector_subtract(HPVector a, HPVector b) INLINE_CONST_FUNC
Definition OOHPVector.h:236
OOINLINE HPVector HPvector_multiply_scalar(HPVector v, OOHPScalar s) INLINE_CONST_FUNC
Definition OOHPVector.h:198
const HPVector kZeroHPVector
Definition OOHPVector.m:27
OOINLINE bool HPvector_equal(HPVector a, HPVector b) INLINE_CONST_FUNC
Definition OOHPVector.h:250
OOINLINE HPVector HPvector_normal_or_fallback(HPVector vec, HPVector fallback) INLINE_CONST_FUNC
Definition OOHPVector.h:265
OOINLINE Vector HPVectorToVector(HPVector v) INLINE_CONST_FUNC
Definition OOHPVector.h:175
OOINLINE HPVector make_HPvector(OOHPScalar vx, OOHPScalar vy, OOHPScalar vz) INLINE_CONST_FUNC
Definition OOHPVector.h:149
OOINLINE OOHPScalar HPdistance2(HPVector v1, HPVector v2) INLINE_CONST_FUNC
Definition OOHPVector.h:293
OOINLINE HPVector HPvector_normal(HPVector vec) INLINE_CONST_FUNC
Definition OOHPVector.h:288
OOINLINE HPVector HPvector_add(HPVector a, HPVector b) INLINE_CONST_FUNC
Definition OOHPVector.h:213
HPVector OOHPVectorRandomSpatial(OOHPScalar maxLength)
Definition OOHPVector.m:75
#define HPvector_between(a, b)
Definition OOHPVector.h:83
OOINLINE OOHPScalar HPmagnitude2(HPVector vec) INLINE_CONST_FUNC
Definition OOHPVector.h:255
OOINLINE OOHPScalar HPdistance(HPVector v1, HPVector v2) INLINE_CONST_FUNC
Definition OOHPVector.h:298
JSObject * OOJSObjectFromNativeObject(JSContext *context, id object)
OOINLINE JSContext * OOJSAcquireContext(void)
OOINLINE void OOJSReportPendingException(JSContext *context)
OOINLINE void OOJSRelinquishContext(JSContext *context)
#define OOLogWARN(class, format,...)
Definition OOLogging.h:126
#define OOLogERR(class, format,...)
Definition OOLogging.h:125
#define NSLog(format,...)
Definition OOLogging.h:148
#define OOLog(class, format,...)
Definition OOLogging.h:84
unsigned count
return nil
Vector vector_forward_from_quaternion(Quaternion quat) CONST_FUNC
void quaternion_set_random(Quaternion *quat) NONNULL_FUNC
@ STELLAR_TYPE_MOON
#define OOExpand(string,...)
NSMutableArray * ScanTokensFromString(NSString *values)
@ AEGIS_IN_DOCKING_RANGE
Definition OOTypes.h:57
@ AEGIS_CLOSE_TO_MAIN_PLANET
Definition OOTypes.h:56
@ AEGIS_CLOSE_TO_ANY_PLANET
Definition OOTypes.h:55
@ AEGIS_NONE
Definition OOTypes.h:54
int16_t OOSystemID
Definition OOTypes.h:183
@ CARGO_NOT_CARGO
Definition OOTypes.h:61
uint32_t OOCargoQuantity
Definition OOTypes.h:155
OOINLINE Vector vector_add(Vector a, Vector b) INLINE_CONST_FUNC
Definition OOVector.h:195
OOINLINE Vector make_vector(OOScalar vx, OOScalar vy, OOScalar vz) INLINE_CONST_FUNC
Definition OOVector.h:149
OOINLINE Vector cross_product(Vector first, Vector second) INLINE_CONST_FUNC
Definition OOVector.h:294
OOINLINE OOScalar magnitude2(Vector vec) INLINE_CONST_FUNC
Definition OOVector.h:237
Vector OOVectorRandomSpatial(OOScalar maxLength)
Definition OOVector.m:89
OOINLINE Vector vector_multiply_scalar(Vector v, OOScalar s) INLINE_CONST_FUNC
Definition OOVector.h:180
#define PLAYER
#define STATION_STUB_NOARG(NAME)
#define STATION_STUB_ARG(NAME)
#define COMBAT_AI_ISNT_AWFUL
Definition ShipEntity.h:124
#define PIRATES_PREFER_PLAYER
Definition ShipEntity.h:42
#define UNIVERSE
Definition Universe.h:827
BOOL(* EntityFilterPredicate)(Entity *entity, void *parameter)
Definition Universe.h:51
void broadcastDistressMessage()
void performFlyToRangeFromDestination()
void scanForNearestIncomingMissile()
void enterPlayerWormhole()
void performFaceDestination()
void enterTargetWormhole()
void performScriptedAttackAI()
void performLandOnPlanet()
void recallDockingInstructions()
void requestDockingCoordinates()
void wormholeEntireGroup()
void setDesiredRangeForWaypoint()
void performHyperSpaceExitWithoutReplacing()
void addFoundTargetAsDefenseTarget()
void setDestinationToStationBeacon()
void setTargetToPrimaryAggressor()
void setDestinationToJinkPosition()
void setDestinationToCurrentLocation()
void setDestinationToDockingAbort()
void addPrimaryAggressorAsDefenseTarget()
void setDestinationFromCoordinates()
void getWitchspaceEntryCoordinates()
Definition AI.h:35
void setStateMachine:withJSScript:(NSString *smName,[withJSScript] NSString *script)
Definition AI.m:278
void clearStack()
Definition AI.m:604
NSString * name()
Definition AI.m:329
void message:(NSString *ms)
Definition AI.m:536
void setState:(NSString *stateName)
Definition AI.m:303
NSString * state()
Definition AI.m:339
GLfloat collision_radius
Definition Entity.h:107
OOUniversalID universalID
Definition Entity.m:522
void setThrowSparks:(BOOL value)
Definition Entity.m:532
GLfloat energy
Definition Entity.m:753
unsigned isShip
Definition Entity.m:125
unsigned isStation
Definition Entity.m:135
unsigned isPlayer
Definition Entity.m:145
HPVector position
Definition Entity.m:576
id owner()
Definition Entity.m:548
id jsAIScriptFromFileNamed:properties:(NSString *fileName,[properties] NSDictionary *properties)
Definition OOScript.m:202
NSUInteger count()
ShipEntity * leader()
void runUnsanitizedScriptActions:allowingAIMethods:withContextName:forTarget:(NSArray *unsanitizedActions,[allowingAIMethods] BOOL allowAIMethods,[withContextName] NSString *contextName,[forTarget] ShipEntity *target)
void setScriptTarget:(ShipEntity *ship)
NSString * pathForFileNamed:inFolder:(NSString *fileName,[inFolder] NSString *folderName)
Vector forwardVector()
void getDestroyedBy:damageType:(Entity *whom,[damageType] OOShipDamageType type)
void doScriptEvent:(OOJSPropID message)
void landOnPlanet:(OOPlanetEntity *planet)
void setTargetStation:(Entity *targetEntity)
void noteLostTarget()
void wormholeGroup()
void checkFoundTarget()
void addTarget:(Entity *targetEntity)
void setPrimaryAggressor:(Entity *targetEntity)
Vector v_forward
Definition ShipEntity.h:189
void scanForNearestShipWithPredicate:parameter:(EntityFilterPredicate predicate,[parameter] void *parameter)
void setFuel:(OOFuelQuantity amount)
void removeTarget:(Entity *targetEntity)
BOOL addDefenseTarget:(Entity *target)
void setAIScript:(NSString *aiString)
void setEvasiveJink:(GLfloat z)
OOShipGroup * escortGroup()
void setSpeed:(double amount)
void scanForNearestShipWithPrimaryRole:(NSString *scanRole)
BOOL suggestEscortTo:(ShipEntity *mother)
int checkShipsInVicinityForWitchJumpExit()
void setGroup:(OOShipGroup *group)
OOShipGroup * group()
NSString * name
Entity * primaryAggressor()
void setPrimaryRole:(NSString *role)
void deployEscorts()
void broadcastDistressMessageWithDumping:(BOOL dumpCargo)
BOOL performHyperSpaceExitReplace:(BOOL replace)
OOFuelQuantity fuel
OOScanClass scanClass()
void checkScannerIgnoringUnpowered()
StationEntity * targetStation()
void doScriptEvent:withArgument:andArgument:(OOJSPropID message,[withArgument] id argument1,[andArgument] id argument2)
ShipEntity * fireMissile()
void removeDefenseTarget:(Entity *target)
OOPlanetEntity * findNearestPlanet()
OOCommodityType dumpCargo()
void setAITo:(NSString *aiString)
void commsMessage:withUnpilotedOverride:(NSString *valueString,[withUnpilotedOverride] BOOL unpilotedOverride)
void performFlee()
void scanForNearestShipHavingRole:(NSString *scanRole)
BOOL performHyperSpaceExitReplace:toSystem:(BOOL replace,[toSystem] OOSystemID systemID)
Entity< OOStellarBody > * findNearestStellarBody()
int legalStatus()
void sendExpandedMessage:toShip:(NSString *message_text,[toShip] ShipEntity *other_ship)
void wormholeEscorts()
void scanForNearestShipWithNegatedPredicate:parameter:(EntityFilterPredicate predicate,[parameter] void *parameter)
void noteLostTargetAndGoIdle()
OOCargoQuantity maxAvailableCargoSpace()
void checkScanner()
void doScriptEvent:withArgument:(OOJSPropID message,[withArgument] id argument)
void markAsOffender:withReason:(int offence_value,[withReason] OOLegalStatusReason reason)
void setRememberedShip:(Entity *targetEntity)
void reactToAIMessage:context:(NSString *message,[context] NSString *debugContext)
void setFoundTarget:(Entity *targetEntity)
OOPlanetEntity * findNearestPlanetExcludingMoons()
void sendAIMessage:(NSString *message)
void acceptDistressMessageFrom:(ShipEntity *other)
void enterWormhole:replacing:(WormholeEntity *w_hole,[replacing] BOOL replacing)
GLfloat maxFlightSpeed
void setOwner:(Entity *who_owns_entity)
Entity * lastEscortTarget()
void recallDockingInstructions()
Entity * foundTarget()
void acceptPatrolReportFrom:(ShipEntity *patrol_ship)
ShipEntity * launchDefenseShip()
NSDictionary * dockingInstructionsForShip:(ShipEntity *ship)
float randf(void)
#define ranrot_rand()
OOHPScalar x
Definition OOHPVector.h:36
OOHPScalar y
Definition OOHPVector.h:37
OOHPScalar z
Definition OOHPVector.h:38
OOScalar x
Definition OOVector.h:32
OOScalar y
Definition OOVector.h:33
OOScalar z
Definition OOVector.h:34