Oolite
Loading...
Searching...
No Matches
StationEntity.m
Go to the documentation of this file.
1/*
2
3 StationEntity.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 "StationEntity.h"
26#import "DockEntity.h"
29#import "OOStringParsing.h"
30#import "ShipEntityAI.h"
31
32#import "GameController.h"
33#import "HeadUpDisplay.h"
34#import "OOConstToString.h"
35#import "Universe.h"
36
38#import "OOPlanetEntity.h"
40#import "OOShipGroup.h"
42
43#import "AI.h"
44#import "OOCharacter.h"
45
46#import "OODebugFlags.h"
47#import "OODebugGLDrawing.h"
48#import "OODebugStandards.h"
49#import "OOJSScript.h"
50#import "OOWeakSet.h"
51
52@interface StationEntity (OOPrivate)
53
54- (void)pullInShipIfPermitted:(ShipEntity*)ship;
55- (void)addShipToStationCount:(ShipEntity*)ship;
56
57- (void)addShipToLaunchQueue:(ShipEntity*)ship withPriority:(BOOL)priority;
58- (unsigned)countOfShipsInLaunchQueueWithPrimaryRole:(NSString*)role;
59
60- (NSDictionary*)holdPositionInstructionForShip:(ShipEntity*)ship;
61
62@end
63
64#ifndef NDEBUG
65@interface StationEntity (mwDebug)
66
68- (NSArray*)dbgGetIdLocks;
69- (NSString*)dbgDumpIdLocks;
70@end
71#endif
72
73@implementation StationEntity
74
75/* Override ShipEntity: stations of CLASS_ROCK or CLASS_CARGO are not automatically unpiloted. */
77{
78 return [self isExplicitlyUnpiloted] || [self isHulk];
79}
80
82{
83 if (equivalentTechLevel == NSNotFound) {
84 return [[UNIVERSE currentSystemData] oo_intForKey:KEY_TECHLEVEL];
85 } else {
87 }
88}
89
90- (void)setEquivalentTechLevel:(OOTechLevelID)value
91{
92 equivalentTechLevel = value;
93}
94
99
104
106{
107 double buoy_distance = 10000.0; // distance from station entrance
109 HPVector result = HPvector_add([self position], vectorToHPVector(vector_multiply_scalar(v_f, buoy_distance)));
110
111 return result;
112}
113
115{
117}
118
123
125{
126 return marketDefinition;
127}
128
130{
131 return marketScriptName;
132}
133
135{
136 if (self == [UNIVERSE station]) {
137 return YES;
138 }
139 return marketMonitored;
140}
141
143{
144 if (self == [UNIVERSE station]) {
145 return YES;
146 }
147 return marketBroadcast;
148}
149
150- (OOCreditsQuantity)legalStatusOfManifest:(OOCommodityMarket*)manifest export:(BOOL)export
151{
152 OOCreditsQuantity penalty, status = 0;
153 OOCommodityMarket* market = [self localMarket];
154 OOCommodityType good = nil;
155 foreach (good, [market goods]) {
156 if (export) {
157 penalty = [market exportLegalityForGood:good];
158 } else {
159 penalty = [market importLegalityForGood:good];
160 }
161 status += penalty * [manifest quantityForGood:good];
162 }
163 return status;
164}
165
167{
168 if (self == [UNIVERSE station]) {
169 // main stations use the system market
170 // just return a reference
171 return [UNIVERSE commodityMarket];
172 }
173 if (!localMarket) {
175 }
176 return localMarket;
177}
178
179- (void)setLocalMarket:(NSArray*)some_market
180{
181 [[self localMarket] loadStationAmounts:some_market];
182}
183
185{
186 return [[self localMarket] dictionaryForScripting];
187}
188
189- (void)setPrice:(OOCreditsQuantity)price forCommodity:(OOCommodityType)commodity
190{
191 [[self localMarket] setPrice:price forGood:commodity];
192}
193
194- (void)setQuantity:(OOCargoQuantity)quantity forCommodity:(OOCommodityType)commodity
195{
196 [[self localMarket] setQuantity:quantity forGood:commodity];
197}
198
199- (NSMutableArray*)localShipyard
200{
201 return localShipyard;
202}
203
204- (void)setLocalShipyard:(NSArray*)some_market
205{
206 if (localShipyard)
207 [localShipyard release];
208 localShipyard = [[NSMutableArray alloc] initWithArray:some_market];
209}
210
211- (NSMutableDictionary*)localInterfaces
212{
213 return localInterfaces;
214}
215
216- (void)setInterfaceDefinition:(OOJSInterfaceDefinition*)definition forKey:(NSString*)key
217{
218 if (definition == nil) {
219 [localInterfaces removeObjectForKey:key];
220 } else {
221 [localInterfaces setObject:definition forKey:key];
222 }
223}
224
226{
228 localMarket = [[[UNIVERSE commodities] generateMarketForStation:self] retain];
229 return localMarket;
230}
231
232- (void)setPlanet:(OOPlanetEntity*)planet_entity
233{
234 if (planet_entity)
235 planet = [planet_entity universalID];
236 else
238}
239
240- (OOPlanetEntity*)planet
241{
242 return [UNIVERSE entityForUniversalID:planet];
243}
244
249
254
259
261{
262 return [[self subEntities] objectEnumeratorFilteredWithSelector:@selector(isDock)];
263}
264
266{
267
268 NSEnumerator* subEnum = nil;
269 DockEntity* sub = nil;
270 unsigned soa = 0;
271 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
273 }
274
275 if (soa == 0) {
276 // if all docks have no ships on approach
277 [shipAI message:@"DOCKING_COMPLETE"];
278 [self doScriptEvent:OOJSID("stationDockingQueuesAreEmpty")];
279 }
280}
281
282// only used by player - everything else ends up in a Dock's launch queue
283- (void)launchShip:(ShipEntity*)ship
284{
285 NSEnumerator* subEnum = nil;
286 DockEntity* sub = nil;
287
288 // try to find an unused dock first
289 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
290 if ([sub allowsLaunching] && [sub countOfShipsInLaunchQueue] == 0) {
291 [sub launchShip:ship];
292 return;
293 }
294 }
295 // otherwise any launchable dock will do
296 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
297 if ([sub allowsLaunching]) {
298 [sub launchShip:ship];
299 return;
300 }
301 }
302
303 // ship has no launch docks specified; just use the last one
304 if (sub != nil) {
305 [sub launchShip:ship];
306 return;
307 }
308 // guaranteed to always be a dock as virtual dock will suffice
309}
310
311// Exposed to AI
313{
314 NSEnumerator* subEnum = nil;
315 DockEntity* sub = nil;
316 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
318 }
319
320 [_shipsOnHold makeObjectsPerformSelector:@selector(sendAIMessage:) withObject:@"DOCKING_ABORTED"];
321 NSEnumerator* holdEnum = nil;
322 ShipEntity* hold = nil;
323 for (holdEnum = [_shipsOnHold objectEnumerator]; (hold = [holdEnum nextObject]);) {
324 [hold doScriptEvent:OOJSID("stationWithdrewDockingClearance")];
325 }
326
327 PlayerEntity* player = PLAYER;
328
329 if ([player getTargetDockStation] == self && [player getDockingClearanceStatus] >= DOCKING_CLEARANCE_STATUS_REQUESTED) {
330 // then docking clearance is requested but hasn't been cancelled
331 // yet by a DockEntity
332 [self sendExpandedMessage:@"[station-docking-clearance-abort-cancelled]" toShip:player];
333 [player setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_NONE];
334 [player doScriptEvent:OOJSID("stationWithdrewDockingClearance")];
335 }
336
338
339 [shipAI message:@"DOCKING_COMPLETE"];
340 [self doScriptEvent:OOJSID("stationDockingQueuesAreEmpty")];
341}
342
344{
345 NSEnumerator* onHoldEnum = [_shipsOnHold objectEnumerator];
346 ShipEntity* ship = nil;
347 while ((ship = [onHoldEnum nextObject])) {
348 [self pullInShipIfPermitted:ship];
349 }
350
352}
353
355{
356 NSEnumerator* subEnum = nil;
357 DockEntity* sub = nil;
358 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
360 }
361
362 [self autoDockShipsOnHold];
363
364 [shipAI message:@"DOCKING_COMPLETE"];
365 [self doScriptEvent:OOJSID("stationDockingQueuesAreEmpty")];
366}
367
368- (Vector)portUpVectorForShip:(ShipEntity*)ship
369{
370 NSEnumerator* subEnum = nil;
371 DockEntity* sub = nil;
372 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
373 if ([sub shipIsInDockingQueue:ship]) {
374 return [sub portUpVectorForShipsBoundingBox:[ship totalBoundingBox]];
375 }
376 }
377 return kZeroVector;
378}
379
380NSDictionary* OOMakeDockingInstructions(StationEntity* station, HPVector coords, float speed, float range, NSString* ai_message, NSString* comms_message, BOOL match_rotation, int docking_stage)
381{
382 NSMutableDictionary* acc = [NSMutableDictionary dictionaryWithCapacity:8];
383 [acc oo_setHPVector:coords forKey:@"destination"];
384 [acc oo_setFloat:speed forKey:@"speed"];
385 [acc oo_setFloat:range forKey:@"range"];
386 [acc setObject:[[station weakRetain] autorelease] forKey:@"station"];
387 [acc oo_setBool:match_rotation forKey:@"match_rotation"];
388 [acc oo_setInteger:docking_stage forKey:@"docking_stage"];
389 if (ai_message) {
390 [acc setObject:ai_message forKey:@"ai_message"];
391 }
392 if (comms_message) {
393 [acc setObject:comms_message forKey:@"comms_message"];
394 }
395 return [NSDictionary dictionaryWithDictionary:acc];
396}
397
398// this method does initial traffic control, before passing the ship
399// to an appropriate dock for docking coordinates and instructions.
400// used for NPCs, and the player when they use the docking computer
401- (NSDictionary*)dockingInstructionsForShip:(ShipEntity*)ship
402{
403 if (ship == nil)
404 return nil;
405
406 [self doScriptEvent:OOJSID("stationReceivedDockingRequest") withArgument:ship];
407
408 if ([ship isPlayer]) {
409 player_reserved_dock = nil; // clear any dock reservation for manual docking
410 }
411
412 if ([ship isPlayer] && [ship legalStatus] > 50) // note: non-player fugitives dock as normal
413 {
414 // refuse docking to the fugitive player
415 return OOMakeDockingInstructions(self, [ship position], 0, 100, @"DOCKING_REFUSED", @"[station-docking-refused-to-fugitive]", NO, -1);
416 }
417
418 if (magnitude2(velocity) > 1.0 || fabs(flightPitch) > 0.01 || fabs(flightYaw) > 0.01) {
419 // no docking while station is moving, pitching or yawing
420 return [self holdPositionInstructionForShip:ship];
421 }
422 PlayerEntity* player = PLAYER;
424
425 NSEnumerator* subEnum = nil;
426 DockEntity* chosenDock = nil;
427 NSString* docking = nil;
428 DockEntity* sub = nil;
429 NSUInteger queue = 100;
430
431 BOOL alldockstoosmall = YES;
432 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
433 if ([sub shipIsInDockingQueue:ship]) {
434 // if already claimed a docking queue, use that one
435 chosenDock = sub;
436 alldockstoosmall = NO;
437 break;
438 }
439 if (player_is_ahead) {
440 // can't allocate a new queue while player is manually docking
441 continue;
442 }
443 if (sub != player_reserved_dock || [ship isPlayer]) {
444 docking = [sub canAcceptShipForDocking:ship];
445 if ([docking isEqualToString:@"DOCK_CLOSED"]) {
446 JSContext* context = OOJSAcquireContext();
448 OOJSVal args[] = { OOJSValueFromNativeObject(context, sub),
449 OOJSValueFromNativeObject(context, ship) };
450 BOOL tempreject = NO;
451
452 BOOL OK = [[self script] callMethod:OOJSID("willOpenDockingPortFor") inContext:context withArguments:args count:2 result:&rval];
453 if (OK)
454 tempreject = OOJSValueToBOOL(context, rval);
455 if (!OK)
456 tempreject = NO; // default to permreject
457 if (tempreject) {
458 docking = @"TRY_AGAIN_LATER";
459 } else {
460 docking = @"TOO_BIG_TO_DOCK";
461 }
462
463 OOJSFreeValue(context, rval);
464 OOJSFreeValue(context, args[0]);
465 OOJSFreeValue(context, args[1]);
466 OOJSRelinquishContext(context);
467 }
468
469 if ([docking isEqualToString:@"DOCKING_POSSIBLE"] && [sub countOfShipsInDockingQueue] < queue) {
470 // try to select the dock with the fewest ships already enqueued
471 chosenDock = sub;
473 alldockstoosmall = NO;
474 } else if (![docking isEqualToString:@"TOO_BIG_TO_DOCK"]) {
475 alldockstoosmall = NO;
476 }
477 } else {
478 alldockstoosmall = NO;
479 }
480 }
481 if (chosenDock == nil) {
482 if (player_is_ahead || ([docking isEqualToString:@"TOO_BIG_TO_DOCK"] && !alldockstoosmall) || docking == nil) {
483 // either player is manually docking and we can't allocate new docks,
484 // or the last dock was too small, and there may be an acceptable one
485 // not tested yet or returning TRY_AGAIN_LATER
486 docking = @"TRY_AGAIN_LATER";
487 }
488 // no docks accept this ship (or the player is blocking them)
489 return OOMakeDockingInstructions(self, [ship position], 200, 100, docking, nil, NO, -1);
490 }
491
492 // rolling is okay for some
493 if (fabs(flightRoll) > 0.01 && [chosenDock isOffCentre]) {
494 return [self holdPositionInstructionForShip:ship];
495 }
496
497 // we made it through holding!
499
500 [shipAI reactToMessage:@"DOCKING_REQUESTED" context:@"requestDockingCoordinates"]; // react to the request
501 [self doScriptEvent:OOJSID("stationAcceptedDockingRequest") withArgument:ship];
502
504}
505
506- (NSDictionary*)holdPositionInstructionForShip:(ShipEntity*)ship
507{
508 if (![_shipsOnHold containsObject:ship]) {
509 [self sendExpandedMessage:@"[station-acknowledges-hold-position]" toShip:ship];
510 [_shipsOnHold addObject:ship];
511 }
512
513 return OOMakeDockingInstructions(self, [ship position], 0, 100, @"HOLD_POSITION", nil, NO, -1);
514}
515
516- (void)abortDockingForShip:(ShipEntity*)ship
517{
518 [ship sendAIMessage:@"DOCKING_ABORTED"];
519 [ship doScriptEvent:OOJSID("stationWithdrewDockingClearance")];
520
522
523 NSEnumerator* subEnum = nil;
524 DockEntity* sub = nil;
525 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
527 }
528
529 if ([ship isPlayer]) {
531 }
532
534}
535
537
538- (id)initWithKey:(NSString*)key definition:(NSDictionary*)dict
539{
541
542 self = [super initWithKey:key definition:dict];
543 if (self != nil) {
544 isStation = YES;
545 _shipsOnHold = [[OOWeakSet alloc] init];
546 hasBreakPattern = YES;
547 localInterfaces = [[NSMutableDictionary alloc] init];
548 }
549 return self;
550
552}
553
554- (void)dealloc
555{
561 // DESTROY(localPassengers);
562 // DESTROY(localContracts);
565
566 [super dealloc];
567}
568
569- (BOOL)setUpShipFromDictionary:(NSDictionary*)dict
570{
572
573 isShip = YES;
574 isStation = YES;
576
577 port_radius = [dict oo_nonNegativeDoubleForKey:@"port_radius" defaultValue:500.0];
578
579 // port_dimensions is deprecated
580 port_dimensions = make_vector(69, 69, 250);
581 NSString* portDimensionsStr = [dict oo_stringForKey:@"port_dimensions"];
582 if (portDimensionsStr != nil) {
583 OOStandardsDeprecated(@"The port_dimensions key is deprecated");
584 if (!OOEnforceStandards()) {
585 NSArray* tokens = [portDimensionsStr componentsSeparatedByString:@"x"];
586 if ([tokens count] == 3) {
587 port_dimensions = make_vector([[tokens objectAtIndex:0] floatValue],
588 [[tokens objectAtIndex:1] floatValue],
589 [[tokens objectAtIndex:2] floatValue]);
590 }
591 }
592 }
593
594 if (![super setUpShipFromDictionary:dict])
595 return NO;
596
597 equivalentTechLevel = [dict oo_unsignedIntegerForKey:@"equivalent_tech_level" defaultValue:NSNotFound];
598 max_scavengers = [dict oo_unsignedIntForKey:@"max_scavengers" defaultValue:3];
599 max_defense_ships = [dict oo_unsignedIntForKey:@"max_defense_ships" defaultValue:3];
600 max_police = [dict oo_unsignedIntForKey:@"max_police" defaultValue:STATION_MAX_POLICE];
601 equipmentPriceFactor = [dict oo_nonNegativeFloatForKey:@"equipment_price_factor" defaultValue:1.0];
603 hasNPCTraffic = [dict oo_fuzzyBooleanForKey:@"has_npc_traffic" defaultValue:(maxFlightSpeed == 0)]; // carriers default to NO
604 hasPatrolShips = [dict oo_fuzzyBooleanForKey:@"has_patrol_ships" defaultValue:NO];
605 suppress_arrival_reports = [dict oo_boolForKey:@"suppress_arrival_reports" defaultValue:NO];
606 [self setAllegiance:[dict oo_stringForKey:@"allegiance"]];
607
608 marketCapacity = [dict oo_unsignedIntForKey:@"market_capacity" defaultValue:MAIN_SYSTEM_MARKET_LIMIT];
609 marketDefinition = [[dict oo_arrayForKey:@"market_definition" defaultValue:nil] retain];
610 marketScriptName = [[dict oo_stringForKey:@"market_script" defaultValue:nil] retain];
611 marketMonitored = [dict oo_boolForKey:@"market_monitored" defaultValue:NO];
612 marketBroadcast = [dict oo_boolForKey:@"market_broadcast" defaultValue:YES];
613
614 // Non main stations may have requiresDockingClearance set to yes as a result of the code below,
615 // but this variable should be irrelevant for them, as they do not make use of it anyway.
616 requiresDockingClearance = [dict oo_boolForKey:@"requires_docking_clearance" defaultValue:[UNIVERSE dockingClearanceProtocolActive]];
617
618 allowsFastDocking = [dict oo_boolForKey:@"allows_fast_docking" defaultValue:NO];
619
620 allowsAutoDocking = [dict oo_boolForKey:@"allows_auto_docking" defaultValue:YES];
621
622 allowsSaving = [UNIVERSE deterministicPopulation];
623
624 interstellarUndockingAllowed = [dict oo_boolForKey:@"interstellar_undocking" defaultValue:NO];
625
626 double unitime = [UNIVERSE getTime];
627
628 if ([self hasNPCTraffic]) // removed the 'isRotatingStation' restriction.
629 {
630 docked_shuttles = ranrot_rand() & 3; // 0..3;
631 shuttle_launch_interval = 15.0 * 60.0; // every 15 minutes
633
634 docked_traders = 3 + (ranrot_rand() & 7); // 1..3;
635 trader_launch_interval = 3600.0 / docked_traders; // every few minutes
636 last_trader_launch_time = unitime + 60.0 - trader_launch_interval; // in one minute's time
637 } else {
638 docked_shuttles = 0;
639 docked_traders = 0; // 1..3;
640 }
641
642 patrol_launch_interval = 300.0; // 5 minutes
644
645 if ([self crew] == nil) {
646 [self setSingleCrewWithRole:@"police"];
647 }
648
649 if ([self group] == nil) {
650 [self setGroup:[self stationGroup]];
651 }
652 return YES;
653
655}
656
657// used to set up a virtual dock if necessary
659{
660 if (![super setUpSubEntities]) {
661 return NO;
662 }
663
664 NSEnumerator* subEnum = nil;
665
666#ifndef NDEBUG
667 ShipEntity* subEntity = nil;
668 for (subEnum = [self shipSubEntityEnumerator]; (subEntity = [subEnum nextObject]);) {
669 if ([subEntity isStation]) {
670 OOLog(@"setup.ship.badType.subentities", @"Subentity %@ (%@) of station %@ is itself a StationEntity. This is an internal error - please report it. ", subEntity, [subEntity shipDataKey], [self displayName]);
671 }
672 }
673#endif
674
675 // and now check for docks
676 DockEntity* sub = nil;
677 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
678 return YES;
679 }
680
681 OOStandardsDeprecated([NSString stringWithFormat:@"No docks set up for %@", self]);
682 OOLog(@"ship.setup.docks", @"No docks set up for %@, making virtual dock", self);
683
684 // no real docks, make a virtual one
685 NSMutableDictionary* virtualDockDict = [NSMutableDictionary dictionaryWithCapacity:10];
686 [virtualDockDict setObject:@"standard" forKey:@"type"];
687 [virtualDockDict setObject:@"oolite-dock-virtual" forKey:@"subentity_key"];
688 [virtualDockDict oo_setVector:make_vector(0, 0, port_radius) forKey:@"position"];
689 [virtualDockDict oo_setQuaternion:kIdentityQuaternion forKey:@"orientation"];
690 [virtualDockDict oo_setBool:YES forKey:@"is_dock"];
691 [virtualDockDict setObject:@"the docking bay" forKey:@"dock_label"];
692 [virtualDockDict oo_setBool:YES forKey:@"allow_docking"];
693 [virtualDockDict oo_setBool:NO forKey:@"disallowed_docking_collides"];
694 [virtualDockDict oo_setBool:YES forKey:@"allow_launching"];
695 [virtualDockDict oo_setBool:YES forKey:@"_is_virtual_dock"];
696
697 if (![self setUpOneStandardSubentity:virtualDockDict asTurret:NO]) {
698 return NO;
699 }
700 return YES;
701}
702
703- (BOOL)shipIsInDockingCorridor:(ShipEntity*)ship
704{
705 if (![ship isShip])
706 return NO;
707 if ([ship isPlayer] && [ship status] == STATUS_DEAD)
708 return NO;
709
710 NSEnumerator* subEnum = nil;
711 DockEntity* sub = nil;
712 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
713 if ([sub shipIsInDockingCorridor:ship]) {
714 return YES;
715 }
716 }
717 return NO;
718}
719
720- (void)pullInShipIfPermitted:(ShipEntity*)ship
721{
722 [ship enterDock:self]; // dock performs permitted checks
723}
724
726{
727 if (!UNIVERSE)
728 return NO;
729
730 NSEnumerator* subEnum = nil;
731 DockEntity* sub = nil;
732 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
733 if ([sub dockingCorridorIsEmpty]) {
734 return YES; // if any are
735 }
736 }
737 return NO;
738}
739
741{
742 if (!UNIVERSE)
743 return;
744
745 NSEnumerator* subEnum = nil;
746 DockEntity* sub = nil;
747 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
749 }
750
751 return;
752}
753
754- (void)update:(OOTimeDelta)delta_t
755{
756 BOOL isRockHermit = (scanClass == CLASS_ROCK);
757 BOOL isMainStation = (self == [UNIVERSE station]);
758
759 double unitime = [UNIVERSE getTime];
760
761 if (!isMainStation && localMarket == nil) {
763 }
764
765 [super update:delta_t];
766
767 PlayerEntity* player = PLAYER;
768
769 BOOL isDockingStation = (self == [player getTargetDockStation]);
770 if (isDockingStation && [player status] == STATUS_IN_FLIGHT) {
771 if ([player getDockingClearanceStatus] >= DOCKING_CLEARANCE_STATUS_GRANTED) {
772 if (last_launch_time - 30 < unitime && [player getDockingClearanceStatus] != DOCKING_CLEARANCE_STATUS_TIMING_OUT) {
773 [self sendExpandedMessage:@"[station-docking-clearance-about-to-expire]" toShip:player];
774 [player setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_TIMING_OUT];
775 } else if (last_launch_time < unitime) {
776 [self sendExpandedMessage:@"[station-docking-clearance-expired]" toShip:player];
777 [player setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_NONE]; // Docking clearance for player has expired.
778 [player doScriptEvent:OOJSID("playerDockingClearanceExpired")];
779 if ([self currentlyInDockingQueues] == 0) {
780 [[self getAI] message:@"DOCKING_COMPLETE"];
781 [self doScriptEvent:OOJSID("stationDockingQueuesAreEmpty")];
782 }
784 }
785 }
786
787 else if ([player getDockingClearanceStatus] == DOCKING_CLEARANCE_STATUS_NOT_REQUIRED) {
788 if (last_launch_time < unitime) {
789 [player setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_NONE];
790 if ([self currentlyInDockingQueues] == 0) {
791 [[self getAI] message:@"DOCKING_COMPLETE"];
792 [self doScriptEvent:OOJSID("stationDockingQueuesAreEmpty")];
793 }
794 }
795 }
796
797 else if ([player getDockingClearanceStatus] == DOCKING_CLEARANCE_STATUS_REQUESTED &&
798 [self hasClearDock]) {
799 DockEntity* dock = [self selectDockForDocking];
801 if ([self hasMultipleDocks]) {
802 [self sendExpandedMessage:[NSString stringWithFormat:
803 DESC(@"station-docking-clearance-granted-in-@-until-@"),
805 ClockToString([player clockTime] + DOCKING_CLEARANCE_WINDOW, NO)]
806 toShip:player];
807 } else {
808 [self sendExpandedMessage:[NSString stringWithFormat:
809 DESC(@"station-docking-clearance-granted-until-@"),
810 ClockToString([player clockTime] + DOCKING_CLEARANCE_WINDOW, NO)]
811 toShip:player];
812 }
814 [player setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_GRANTED];
815 [player doScriptEvent:OOJSID("playerDockingClearanceGranted")];
816 }
817 }
818
819 if (approach_spacing > 0.0) {
820 approach_spacing -= delta_t * 10.0; // reduce by 10 m/s
821 if (approach_spacing < 0.0)
822 approach_spacing = 0.0;
823 }
824
825 /* JSAI: JS-based AIs handle their own traffic either alone or
826 * in conjunction with the system repopulator */
827 if (![self hasNewAI]) {
828 // begin launch of shuttles, traders, patrols
829 if ((docked_shuttles > 0) && (!isRockHermit)) {
831 if (([self hasNPCTraffic]) && (aegis_status != AEGIS_NONE)) {
832 [self launchShuttle];
833 }
834 last_shuttle_launch_time = unitime;
835 }
836 }
837
838 if ((docked_traders > 0) && (!isRockHermit)) {
840 if ([self hasNPCTraffic]) {
841 [self launchIndependentShip:@"trader"];
843 }
844 last_trader_launch_time = unitime;
845 }
846 }
847
848 // testing patrols
850 if (!((isMainStation && [self hasNPCTraffic]) || hasPatrolShips) || [self launchPatrol] != nil)
851 last_patrol_report_time = unitime;
852 }
853 }
854}
855
856- (void)clear
857{
858 NSEnumerator* subEnum = nil;
859 DockEntity* sub = nil;
860 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
861 [sub clear];
862 }
863
865}
866
868{
869 NSEnumerator* subEnum = nil;
870 DockEntity* sub = nil;
871 unsigned docks = 0;
872 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
873 docks++;
874 if (docks > 1) {
875 return YES;
876 }
877 }
878 return NO;
879}
880
881// is there a dock free for the player to dock manually?
882// not used for NPCs
884{
885 NSEnumerator* subEnum = nil;
886 DockEntity* sub = nil;
887 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
888 if ([sub allowsDocking] && [sub countOfShipsInLaunchQueue] == 0 && [sub countOfShipsInDockingQueue] == 0) {
889 if ([[sub canAcceptShipForDocking:PLAYER] isEqualToString:@"DOCKING_POSSIBLE"]) {
890 return YES;
891 }
892 }
893 }
894 return NO;
895}
896
898{
899 NSEnumerator* subEnum = nil;
900 DockEntity* sub = nil;
901 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
902 // TRY_AGAIN_LATER in this context means "ships launching now"
903 if ([sub allowsDocking] && ([[sub canAcceptShipForDocking:PLAYER] isEqualToString:@"DOCKING_POSSIBLE"] || [[sub canAcceptShipForDocking:PLAYER] isEqualToString:@"TRY_AGAIN_LATER"])) {
904 return YES;
905 }
906 }
907 return NO;
908}
909
910// is there any dock which may launch ships?
912{
913 NSEnumerator* subEnum = nil;
914 DockEntity* sub = nil;
915 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
916 if ([sub allowsLaunching]) {
917 return YES;
918 }
919 }
920 return NO;
921}
922
923// only used to pick a dock for the player
925{
926 NSEnumerator* subEnum = nil;
927 DockEntity* sub = nil;
928 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
929 if ([sub allowsDocking] && [sub countOfShipsInLaunchQueue] == 0 && [sub countOfShipsInDockingQueue] == 0) {
930 return sub;
931 }
932 }
933 return nil;
934}
935
936- (void)addShipToLaunchQueue:(ShipEntity*)ship withPriority:(BOOL)priority
937{
938 NSEnumerator* subEnum = nil;
939 DockEntity* sub = nil;
940 unsigned threshold = 0;
941
942 // quickest launch if we assign ships to those bays with no incoming ships
943 // and spread the ships evenly around those bays
944 // much easier if the station has at least one launch-only dock
945 while (threshold < 16) {
946 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
947 if (sub != player_reserved_dock) {
948 if ([sub countOfShipsInDockingQueue] == 0) {
949 if ([sub allowsLaunching] && [sub countOfShipsInLaunchQueue] <= threshold) {
950 if ([sub allowsLaunchingOf:ship]) {
951 [sub addShipToLaunchQueue:ship withPriority:priority];
952 return;
953 }
954 }
955 }
956 }
957 }
958 threshold++;
959 }
960 // if we get this far, all docks have at least some incoming traffic.
961 // usually most efficient (since launching is far faster than docking)
962 // to assign all ships to the *same* dock with the smallest incoming queue
963 // rather than to try spreading them out across several queues
964 // also stops escorts being launched before their mothership
965 threshold = 0;
966 while (threshold < 16) {
967 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
968 /* so this time as long as it allows launching only check
969 * the docking queue size so long as enumerator order is
970 * deterministic, this will assign every launch this
971 * update to the same dock (edge case where new docking
972 * ship appears in the middle, probably not a problem) */
973 if ([sub allowsLaunching] && [sub countOfShipsInDockingQueue] <= threshold) {
974 if ([sub allowsLaunchingOf:ship]) {
975 [sub addShipToLaunchQueue:ship withPriority:priority];
976 return;
977 }
978 }
979 }
980 threshold++;
981 }
982
983 OOLog(@"station.launchShip.failed", @"Cancelled launch for a %@ with role %@, as the %@ has too many ships in its launch queue(s) or no suitable launch docks.",
984 [ship displayName], [ship primaryRole], [self displayName]);
985}
986
987- (unsigned)countOfShipsInLaunchQueueWithPrimaryRole:(NSString*)role
988{
989 unsigned result = 0;
990 NSEnumerator* subEnum = nil;
991 DockEntity* sub = nil;
992 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
994 }
995 return result;
996}
997
998- (BOOL)fitsInDock:(ShipEntity*)ship
999{
1000 return [self fitsInDock:ship andLogNoFit:YES];
1001}
1002
1003- (BOOL)fitsInDock:(ShipEntity*)ship andLogNoFit:(BOOL)logNoFit
1004{
1005 if (![ship isShip])
1006 return NO;
1007
1008 NSEnumerator* subEnum = nil;
1009 DockEntity* sub = nil;
1010 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
1011 if ([sub allowsLaunchingOf:ship]) {
1012 return YES;
1013 }
1014 }
1015
1016 if (logNoFit)
1017 OOLog(@"station.launchShip.failed", @"Cancelled launch for a %@ with role %@, as it is too large for the docking port of the %@.",
1018 [ship displayName], [ship primaryRole], self);
1019 return NO;
1020}
1021
1022- (void)noteDockedShip:(ShipEntity*)ship
1023{
1024 if (ship == nil)
1025 return;
1026
1027 PlayerEntity* player = PLAYER;
1028 // set last launch time to avoid clashes with outgoing ships
1029 if ([player getDockingClearanceStatus] != DOCKING_CLEARANCE_STATUS_GRANTED) {
1030 // avoid interfering with docking clearance on another bay
1031 last_launch_time = [UNIVERSE getTime];
1032 }
1033 [self addShipToStationCount:ship];
1034
1035 NSEnumerator* subEnum = nil;
1036 DockEntity* sub = nil;
1037 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
1038 [sub noteDockingForShip:ship];
1039 }
1041
1042 [self doScriptEvent:OOJSID("otherShipDocked") withArgument:ship];
1043
1044 BOOL isDockingStation = (self == [player getTargetDockStation]);
1045 if (isDockingStation && [player status] == STATUS_IN_FLIGHT &&
1046 [player getDockingClearanceStatus] == DOCKING_CLEARANCE_STATUS_REQUESTED) {
1047 if (![self hasClearDock]) {
1048 // then say why
1049 if ([self currentlyInDockingQueues]) {
1050 [self sendExpandedMessage:[NSString stringWithFormat:
1051 DESC(@"station-docking-clearance-holding-d-ships-approaching"),
1052 [self currentlyInDockingQueues] + 1]
1053 toShip:player];
1054 } else if ([self currentlyInLaunchingQueues]) {
1055 [self sendExpandedMessage:[NSString stringWithFormat:
1056 DESC(@"station-docking-clearance-holding-d-ships-departing"),
1057 [self currentlyInLaunchingQueues] + 1]
1058 toShip:player];
1059 }
1060 }
1061 }
1062
1063 if ([ship isPlayer]) {
1065 }
1066}
1067
1068- (void)addShipToStationCount:(ShipEntity*)ship
1069{
1070 if ([ship isShuttle])
1071 docked_shuttles++;
1072 else if ([ship isTrader] && ![ship isPlayer])
1073 docked_traders++;
1074 else if (([ship isPolice] && ![ship isEscort]) || [ship hasPrimaryRole:@"defense_ship"]) {
1075 if (0 < defenders_launched)
1076 defenders_launched--;
1077 } else if ([ship hasPrimaryRole:@"scavenger"] || [ship hasPrimaryRole:@"miner"]) // treat miners and scavengers alike!
1078 {
1079 if (0 < scavengers_launched)
1080 scavengers_launched--;
1081 }
1082}
1083
1088
1090{
1091 return hasNPCTraffic;
1092}
1093
1094- (void)setHasNPCTraffic:(BOOL)flag
1095{
1096 hasNPCTraffic = flag != NO;
1097}
1098
1099- (BOOL)collideWithShip:(ShipEntity*)other
1100{
1101 /*
1102 There used to be a [self abortAllDockings] here. Removed as there
1103 doesn't appear to be a good reason for it and it interferes with
1104 docking clearance.
1105 -- Micha 2010-06-10
1106 Reformatted, Ahruman 2012-08-26
1107 */
1108 return [super collideWithShip:other];
1109}
1110
1112{
1114}
1115
1116- (void)takeEnergyDamage:(double)amount from:(Entity*)ent becauseOf:(Entity*)other weaponIdentifier:(NSString*)weaponIdentifier
1117{
1118 // stations must ignore friendly fire, otherwise the defenders' AI gets stuck.
1119 BOOL isFriend = NO;
1120 OOShipGroup* group = [self group];
1121
1122 if ([other isShip] && group != nil) {
1123 OOShipGroup* otherGroup = [(ShipEntity*)other group];
1124 isFriend = otherGroup == group || [otherGroup leader] == self;
1125 }
1126
1127 // If this is the system's main station...
1128 if (self == [UNIVERSE station] && !isFriend) {
1129 //...get angry
1130 BOOL isEnergyMine = [ent isCascadeWeapon];
1131
1132 // JSAIs might ignore friendly fire from conventional weapons
1133 if ([self hasNewAI] || isEnergyMine) {
1134 unsigned b = isEnergyMine ? 96 : 64;
1135 if ([(ShipEntity*)other bounty] >= b) // already a hardened criminal?
1136 {
1137 b *= 1.5; // bigger bounty!
1138 }
1139 [(ShipEntity*)other markAsOffender:b withReason:kOOLegalStatusReasonAttackedMainStation];
1140 [self setPrimaryAggressor:other];
1141 [self setFoundTarget:other];
1142 [self launchPolice];
1143 }
1144
1145 if (isEnergyMine) // don't blow up!
1146 {
1147 [self increaseAlertLevel];
1148 [self respondToAttackFrom:ent becauseOf:other];
1149 return;
1150 }
1151 }
1152 // Stop damage if main station & close to death!
1153 if (!isFriend && (self != [UNIVERSE station] || amount < energy)) {
1154 // Handle damage like a ship.
1155 [super takeEnergyDamage:amount from:ent becauseOf:other weaponIdentifier:weaponIdentifier];
1156 }
1157}
1158
1159- (void)adjustVelocity:(Vector)xVel
1160{
1161 if (self != [UNIVERSE station])
1162 [super adjustVelocity:xVel]; // dont get moved
1163}
1164
1165- (void)takeScrapeDamage:(double)amount from:(Entity*)ent
1166{
1167 // Stop damage if main station
1168 if (self != [UNIVERSE station])
1169 [super takeScrapeDamage:amount from:ent];
1170}
1171
1172- (void)takeHeatDamage:(double)amount
1173{
1174 // Stop damage if main station
1175 if (self != [UNIVERSE station])
1176 [super takeHeatDamage:amount];
1177}
1178
1179- (NSString*)allegiance
1180{
1181 return allegiance;
1182}
1183
1184- (void)setAllegiance:(NSString*)newAllegiance
1185{
1186 [allegiance release];
1187 allegiance = [newAllegiance copy];
1188}
1189
1191{
1192 return alertLevel;
1193}
1194
1195- (void)setAlertLevel:(OOStationAlertLevel)level signallingScript:(BOOL)signallingScript
1196{
1197 if (level < STATION_ALERT_LEVEL_GREEN)
1199 if (level > STATION_ALERT_LEVEL_RED)
1201
1202 if (alertLevel != level) {
1204 alertLevel = level;
1205 if (signallingScript) {
1206 [self doScriptEvent:OOJSID("alertConditionChanged") withArgument:[NSNumber numberWithInt:level] andArgument:[NSNumber numberWithInt:oldLevel]];
1207 }
1208 switch (level) {
1210 [shipAI reactToMessage:@"GREEN_ALERT" context:nil];
1211 break;
1212
1214 [shipAI reactToMessage:@"YELLOW_ALERT" context:nil];
1215 break;
1216
1218 [shipAI reactToMessage:@"RED_ALERT" context:nil];
1219 break;
1220 }
1221 }
1222}
1223
1224// Exposed to AI
1225- (ShipEntity*)launchIndependentShip:(NSString*)role
1226{
1227 if (![self hasLaunchDock]) {
1228 OOLog(@"station.launchShip.impossible", @"Cancelled launch for a ship with role %@, as the %@ has no launch docks.",
1229 role, [self displayName]);
1230 return nil;
1231 }
1232
1233 BOOL trader = [role isEqualToString:@"trader"];
1234 BOOL sunskimmer = ([role isEqualToString:@"sunskim-trader"]);
1235 ShipEntity* ship = nil;
1236
1237 if ((trader && (randf() < 0.1)) || sunskimmer) {
1238 ship = [UNIVERSE newShipWithRole:@"sunskim-trader"];
1239 sunskimmer = true;
1240 trader = true;
1241 role = @"trader"; // make sure also sunskimmers get trader role.
1242 } else {
1243 ship = [UNIVERSE newShipWithRole:role];
1244 }
1245
1246 if (![self fitsInDock:ship]) {
1247 [ship release];
1248 return nil;
1249 }
1250
1251 if (ship) {
1252 if (![ship crew]) {
1254 }
1255 [ship setPrimaryRole:role];
1256
1257 if (trader || ship->scanClass == CLASS_NOT_SET)
1258 [ship setScanClass:CLASS_NEUTRAL]; // keep defined scanclasses for non-traders.
1259
1260 if (trader) {
1261 [ship setBounty:0 withReason:kOOLegalStatusReasonSetup];
1262 [ship setCargoFlag:CARGO_FLAG_FULL_PLENTIFUL];
1263 if (sunskimmer) {
1264 [ship setFuel:(Ranrot() & 31)];
1265 [UNIVERSE makeSunSkimmer:ship andSetAI:YES];
1266 } else {
1267 // JSAI: not needed - oolite-traderAI.js handles exiting if full fuel and plentiful cargo
1268 // [ship switchAITo:@"exitingTraderAI.plist"];
1269 if ([ship fuel] == 0)
1270 [ship setFuel:70];
1271 // if ([ship hasRole:@"sunskim-trader"]) [UNIVERSE makeSunSkimmer:ship andSetAI:NO];
1272 }
1273 }
1274
1275 [self addShipToLaunchQueue:ship withPriority:NO];
1276
1278 if ([ship group] == nil)
1279 [ship setGroup:escortGroup];
1280 // Eric: Escorts are defined both as _group and as _escortGroup because friendly attacks are only handled within _group.
1281 [escortGroup setLeader:ship];
1282
1283 // add escorts to the trader
1284 unsigned escorts = [ship pendingEscortCount];
1285 if (escorts > 0) {
1286 [ship setOwner:self]; // makes escorts get added to station launch queue
1288 [ship setOwner:ship];
1289 }
1290
1292 [ship autorelease];
1293 }
1294 return ship;
1295}
1296
1298
1299// Exposed to AI
1301{
1302 [self setAlertLevel:[self alertLevel] + 1 signallingScript:YES];
1303}
1304
1305// Exposed to AI
1307{
1308 [self setAlertLevel:[self alertLevel] - 1 signallingScript:YES];
1309}
1310
1311// Exposed to AI
1312- (NSArray*)launchPolice
1313{
1314 if (![self hasLaunchDock]) {
1315 OOLog(@"station.launchShip.impossible", @"Cancelled launch for a police ship, as the %@ has no launch docks.",
1316 [self displayName]);
1317 return [NSArray array];
1318 }
1319
1320 OOUniversalID police_target = [[self primaryTarget] universalID];
1321 unsigned i;
1322 NSMutableArray* result = nil;
1323 OOTechLevelID techlevel = [self equivalentTechLevel];
1324 if (techlevel == NSNotFound)
1325 techlevel = 6;
1326
1327 result = [NSMutableArray arrayWithCapacity:4];
1328
1329 for (i = 0; (i < 4) && (defenders_launched < max_police); i++) {
1330 ShipEntity* police_ship = nil;
1331 if (![UNIVERSE entityForUniversalID:police_target]) {
1332 [self noteLostTarget];
1333 return [NSArray array];
1334 }
1335 /* this is more likely to give interceptors than the
1336 * equivalent populator function: save them for defense
1337 * ships */
1338 if ((Ranrot() & 3) + 9 < techlevel) {
1339 police_ship = [UNIVERSE newShipWithRole:@"interceptor"]; // retain count = 1
1340 } else {
1341 police_ship = [UNIVERSE newShipWithRole:@"police"]; // retain count = 1
1342 }
1343
1344 if (police_ship && [self fitsInDock:police_ship]) {
1345 if (![police_ship crew]) {
1347 }
1348
1349 [police_ship setGroup:[self stationGroup]]; // who's your Daddy
1350 [police_ship setPrimaryRole:@"police"];
1351 [police_ship addTarget:[UNIVERSE entityForUniversalID:police_target]];
1352 if ([police_ship scanClass] == CLASS_NOT_SET)
1353 [police_ship setScanClass:CLASS_POLICE];
1354 [police_ship setBounty:0 withReason:kOOLegalStatusReasonSetup];
1355 if ([police_ship heatInsulation] < [self heatInsulation])
1357 [police_ship switchAITo:@"oolite-defenseShipAI.js"];
1358 [self addShipToLaunchQueue:police_ship withPriority:YES];
1360 [result addObject:police_ship];
1361 }
1362 [police_ship autorelease];
1363 }
1364 [self abortAllDockings];
1365 return result;
1366}
1367
1368// Exposed to AI
1370{
1371 if (![self hasLaunchDock]) {
1372 OOLog(@"station.launchShip.impossible", @"Cancelled launch for a defense ship, as the %@ has no launch docks.",
1373 [self displayName]);
1374 return nil;
1375 }
1376
1377 OOUniversalID defense_target = [[self primaryTarget] universalID];
1378 ShipEntity* defense_ship = nil;
1379 NSString *defense_ship_key = nil,
1380 *defense_ship_role = nil,
1381 *default_defense_ship_role = nil;
1382 NSString* defense_ship_ai = @"oolite-defenseShipAI.js";
1383
1384 OOTechLevelID techlevel;
1385
1386 techlevel = [self equivalentTechLevel];
1387 if (techlevel == NSNotFound)
1388 techlevel = 6;
1389 if ((Ranrot() & 7) + 6 <= techlevel)
1390 default_defense_ship_role = @"interceptor";
1391 else
1392 default_defense_ship_role = @"police";
1393
1394 if (scanClass == CLASS_ROCK)
1395 default_defense_ship_role = @"hermit-ship";
1396
1397 if (defenders_launched >= max_defense_ships) // shuttles are to rockhermits what police ships are to stations
1398 return nil;
1399
1400 if (![UNIVERSE entityForUniversalID:defense_target]) {
1401 [self noteLostTarget];
1402 return nil;
1403 }
1404
1405 defense_ship_key = [shipinfoDictionary oo_stringForKey:@"defense_ship"];
1406 if (defense_ship_key != nil) {
1407 defense_ship = [UNIVERSE newShipWithName:defense_ship_key];
1408 }
1409 if (!defense_ship) {
1410 defense_ship_role = [shipinfoDictionary oo_stringForKey:@"defense_ship_role" defaultValue:default_defense_ship_role];
1411 defense_ship = [UNIVERSE newShipWithRole:defense_ship_role];
1412 }
1413
1414 if (!defense_ship && default_defense_ship_role != defense_ship_role)
1415 defense_ship = [UNIVERSE newShipWithRole:default_defense_ship_role];
1416
1417 if (!defense_ship || ![self fitsInDock:defense_ship]) {
1418 [defense_ship release];
1419 return nil;
1420 }
1421
1422 if ([defense_ship isPolice] || [defense_ship hasPrimaryRole:@"hermit-ship"]) {
1423 [defense_ship switchAITo:defense_ship_ai];
1424 }
1425
1426 [defense_ship setPrimaryRole:@"defense_ship"];
1427
1429
1430 if (![defense_ship crew]) {
1431 if ([defense_ship isPolice]) {
1433 } else {
1435 }
1436 }
1437
1438 [defense_ship setOwner:self];
1439 if ([self group] == nil) {
1440 [self setGroup:[self stationGroup]];
1441 }
1442 [defense_ship setGroup:[self stationGroup]]; // who's your Daddy
1443
1444 [defense_ship addTarget:[UNIVERSE entityForUniversalID:defense_target]];
1445
1446 if ((scanClass != CLASS_ROCK) && (scanClass != CLASS_STATION)) {
1447 [defense_ship setScanClass:scanClass]; // same as self
1448 } else if ([defense_ship scanClass] == CLASS_NOT_SET) {
1449 [defense_ship setScanClass:CLASS_NEUTRAL];
1450 }
1451
1452 if ([defense_ship heatInsulation] < [self heatInsulation]) {
1454 }
1455
1456 [self addShipToLaunchQueue:defense_ship withPriority:YES];
1457 [defense_ship autorelease];
1458 [self abortAllDockings];
1459
1460 return defense_ship;
1461}
1462
1463// Exposed to AI
1465{
1466 if (![self hasLaunchDock]) {
1467 OOLog(@"station.launchShip.impossible", @"Cancelled launch for a scavenger ship, as the %@ has no launch docks.",
1468 [self displayName]);
1469 return nil;
1470 }
1471
1472 ShipEntity* scavenger_ship;
1473
1474 unsigned scavs = [UNIVERSE countShipsWithPrimaryRole:@"scavenger" inRange:SCANNER_MAX_RANGE ofEntity:self] + [self countOfShipsInLaunchQueueWithPrimaryRole:@"scavenger"];
1475
1476 if (scavs >= max_scavengers)
1477 return nil;
1479 return nil;
1480
1481 scavenger_ship = [UNIVERSE newShipWithRole:@"scavenger"]; // retain count = 1
1482
1483 if (![self fitsInDock:scavenger_ship]) {
1484 [scavenger_ship release];
1485 return nil;
1486 }
1487
1488 if (scavenger_ship) {
1489 if (![scavenger_ship crew]) {
1491 }
1492
1494 [scavenger_ship setScanClass:CLASS_NEUTRAL];
1495 if ([scavenger_ship heatInsulation] < [self heatInsulation])
1497 [scavenger_ship setGroup:[self stationGroup]]; // who's your Daddy -- FIXME: should we have a separate group for non-escort auxiliaires?
1498 [scavenger_ship switchAITo:@"oolite-scavengerAI.js"];
1499 [self addShipToLaunchQueue:scavenger_ship withPriority:NO];
1500 [scavenger_ship autorelease];
1501 }
1502 return scavenger_ship;
1503}
1504
1505// Exposed to AI
1507{
1508 if (![self hasLaunchDock]) {
1509 OOLog(@"station.launchShip.impossible", @"Cancelled launch for a miner ship, as the %@ has no launch docks.",
1510 [self displayName]);
1511 return nil;
1512 }
1513
1514 ShipEntity* miner_ship;
1515
1516 int n_miners = [UNIVERSE countShipsWithPrimaryRole:@"miner" inRange:SCANNER_MAX_RANGE ofEntity:self] + [self countOfShipsInLaunchQueueWithPrimaryRole:@"miner"];
1517
1518 if (n_miners >= 1) // just the one
1519 return nil;
1520
1521 // count miners as scavengers...
1523 return nil;
1524
1525 miner_ship = [UNIVERSE newShipWithRole:@"miner"]; // retain count = 1
1526
1527 if (![self fitsInDock:miner_ship]) {
1528 [miner_ship release];
1529 return nil;
1530 }
1531
1532 if (miner_ship) {
1533 if (![miner_ship crew]) {
1535 }
1536
1538 [miner_ship setScanClass:CLASS_NEUTRAL];
1539 if ([miner_ship heatInsulation] < [self heatInsulation])
1541 [miner_ship setGroup:[self stationGroup]]; // who's your Daddy -- FIXME: should we have a separate group for non-escort auxiliaires?
1542 [miner_ship switchAITo:@"oolite-scavengerAI.js"];
1543 [self addShipToLaunchQueue:miner_ship withPriority:NO];
1544 [miner_ship autorelease];
1545 }
1546 return miner_ship;
1547}
1548
1551// Exposed to AI
1553{
1554 if (![self hasLaunchDock]) {
1555 OOLog(@"station.launchShip.impossible", @"Cancelled launch for a pirate ship, as the %@ has no launch docks.",
1556 [self displayName]);
1557 return nil;
1558 }
1559 // Pirate ships are launched from the same pool as defence ships.
1560 OOUniversalID defense_target = [[self primaryTarget] universalID];
1561 ShipEntity* pirate_ship = nil;
1562
1564 return nil; // shuttles are to rockhermits what police ships are to stations
1565
1566 if (![UNIVERSE entityForUniversalID:defense_target]) {
1567 [self noteLostTarget];
1568 return nil;
1569 }
1570
1571 // Yep! The standard hermit defence ships, even if they're the aggressor.
1572 pirate_ship = [UNIVERSE newShipWithRole:@"pirate"]; // retain count = 1
1573 // Nope, use standard pirates in a generic method.
1574
1575 if (![self fitsInDock:pirate_ship]) {
1576 [pirate_ship release];
1577 return nil;
1578 }
1579
1580 if (pirate_ship) {
1581 if (![pirate_ship crew]) {
1583 }
1584
1586
1587 // set the owner of the ship to the station so that it can check back for docking later
1588 [pirate_ship setOwner:self];
1589 [pirate_ship setGroup:[self stationGroup]]; // who's your Daddy
1590 [pirate_ship setPrimaryRole:@"defense_ship"];
1591 [pirate_ship addTarget:[UNIVERSE entityForUniversalID:defense_target]];
1592 [pirate_ship setScanClass:CLASS_NEUTRAL];
1593 if ([pirate_ship heatInsulation] < [self heatInsulation])
1595 //**Lazygun** added 30 Nov 04 to put a bounty on those pirates' heads.
1596 [pirate_ship setBounty:10 + floor(randf() * 20) withReason:kOOLegalStatusReasonSetup]; // modified for variety
1597
1598 [self addShipToLaunchQueue:pirate_ship withPriority:NO];
1599 [pirate_ship autorelease];
1600 [self abortAllDockings];
1601 }
1602 return pirate_ship;
1603}
1604
1605// Exposed to AI
1607{
1608 if (![self hasLaunchDock]) {
1609 OOLog(@"station.launchShip.impossible", @"Cancelled launch for a shuttle ship, as the %@ has no launch docks.",
1610 [self displayName]);
1611 return nil;
1612 }
1613 ShipEntity* shuttle_ship;
1614
1615 shuttle_ship = [UNIVERSE newShipWithRole:@"shuttle"]; // retain count = 1
1616
1617 if (![self fitsInDock:shuttle_ship]) {
1618 [shuttle_ship release];
1619 return nil;
1620 }
1621
1622 if (shuttle_ship) {
1623 if (![shuttle_ship crew]) {
1625 }
1626
1628 [shuttle_ship setScanClass:CLASS_NEUTRAL];
1629 [shuttle_ship setCargoFlag:CARGO_FLAG_FULL_SCARCE];
1630 [shuttle_ship switchAITo:@"oolite-shuttleAI.js"];
1631 [self addShipToLaunchQueue:shuttle_ship withPriority:NO];
1632
1633 [shuttle_ship autorelease];
1634 }
1635 return shuttle_ship;
1636}
1637
1638// Exposed to AI
1640{
1641 if (![self hasLaunchDock]) {
1642 OOLog(@"station.launchShip.impossible", @"Cancelled launch for an escort ship, as the %@ has no launch docks.",
1643 [self displayName]);
1644 return nil;
1645 }
1646 ShipEntity* escort_ship;
1647
1648 escort_ship = [UNIVERSE newShipWithRole:@"escort"]; // retain count = 1
1649
1650 if (escort_ship && [self fitsInDock:escort_ship]) {
1651 if (![escort_ship crew]) {
1653 }
1654
1655 [escort_ship setScanClass:CLASS_NEUTRAL];
1656 [escort_ship setCargoFlag:CARGO_FLAG_FULL_PLENTIFUL];
1657 [escort_ship switchAITo:@"oolite-escortAI.js"];
1658 [self addShipToLaunchQueue:escort_ship withPriority:NO];
1659 }
1660 [escort_ship release];
1661 return escort_ship;
1662}
1663
1664// Exposed to AI
1666{
1667 if (![self hasLaunchDock]) {
1668 OOLog(@"station.launchShip.impossible", @"Cancelled launch for a patrol ship, as the %@ has no launch docks.",
1669 [self displayName]);
1670 return nil;
1671 }
1673 ShipEntity* patrol_ship = nil;
1674 OOTechLevelID techlevel;
1675
1676 techlevel = [self equivalentTechLevel];
1677 if (techlevel == NSNotFound)
1678 techlevel = 6;
1679
1680 if ((Ranrot() & 7) + 6 <= techlevel)
1681 patrol_ship = [UNIVERSE newShipWithRole:@"interceptor"]; // retain count = 1
1682 else
1683 patrol_ship = [UNIVERSE newShipWithRole:@"police"]; // retain count = 1
1684
1685 if (![self fitsInDock:patrol_ship]) {
1686 [patrol_ship release];
1687 return nil;
1688 }
1689
1690 if (patrol_ship) {
1691 if (![patrol_ship crew]) {
1693 }
1694
1697 if ([patrol_ship scanClass] == CLASS_NOT_SET)
1698 [patrol_ship setScanClass:CLASS_POLICE];
1699 if ([patrol_ship heatInsulation] < [self heatInsulation])
1701 [patrol_ship setPrimaryRole:@"police-station-patrol"];
1702 [patrol_ship setBounty:0 withReason:kOOLegalStatusReasonSetup];
1703 [patrol_ship setGroup:[self stationGroup]]; // who's your Daddy
1704 [patrol_ship switchAITo:@"oolite-policeAI.js"];
1705 [self addShipToLaunchQueue:patrol_ship withPriority:NO];
1706 [self acceptPatrolReportFrom:patrol_ship];
1707 [patrol_ship autorelease];
1708 return patrol_ship;
1709 }
1710 }
1711 return nil;
1712}
1713
1714// Exposed to AI
1715- (void)launchShipWithRole:(NSString*)role
1716{
1717 if (![self hasLaunchDock]) {
1718 OOLog(@"station.launchShip.impossible", @"Cancelled launch for a ship with role %@, as the %@ has no launch docks.",
1719 role, [self displayName]);
1720 return;
1721 }
1722 ShipEntity* ship = [UNIVERSE newShipWithRole:role]; // retain count = 1
1723 if (ship && [self fitsInDock:ship]) {
1724 if (![ship crew]) {
1726 }
1727 if (ship->scanClass == CLASS_NOT_SET)
1728 [ship setScanClass:CLASS_NEUTRAL];
1729 [ship setPrimaryRole:role];
1730 [ship setGroup:[self stationGroup]]; // who's your Daddy
1731 [self addShipToLaunchQueue:ship withPriority:NO];
1732 }
1733 [ship release];
1734}
1735
1736// Exposed to AI
1738{
1739 if (self == [UNIVERSE station])
1740 return;
1741
1742 // launch docked ships if possible
1743 PlayerEntity* player = PLAYER;
1744 if ((player) && ([player status] == STATUS_DOCKED || [player status] == STATUS_DOCKING) && ([player dockedStation] == self)) {
1745 // undock the player!
1746 [player leaveDock:self];
1747 [UNIVERSE setViewDirection:VIEW_FORWARD];
1748 [[UNIVERSE gameController] setMouseInteractionModeForFlight];
1749 [player warnAboutHostiles]; // sound a klaxon
1750 }
1751
1752 if (scanClass == CLASS_ROCK) // ie we're a rock hermit or similar
1753 {
1754 // set the role so that we break up into rocks!
1755 [self setPrimaryRole:@"asteroid"];
1756 being_mined = YES;
1757 }
1758
1759 // finally bite the bullet
1760 [super becomeExplosion];
1761}
1762
1763// Exposed to AI
1765{
1766 if (self == [UNIVERSE station])
1767 return;
1768 [super becomeEnergyBlast];
1769}
1770
1771- (void)becomeLargeExplosion:(double)factor
1772{
1773 if (self == [UNIVERSE station])
1774 return;
1775 [super becomeLargeExplosion:factor];
1776}
1777
1778- (void)acceptPatrolReportFrom:(ShipEntity*)patrol_ship
1779{
1780 last_patrol_report_time = [UNIVERSE getTime];
1781}
1782
1783// used by player - "other" should always be a reference to the player
1784// there are some checks in the function from possibly when this wasn't true?
1785- (NSString*)acceptDockingClearanceRequestFrom:(ShipEntity*)other
1786{
1787 NSString* result = nil;
1788 double timeNow = [UNIVERSE getTime];
1789 PlayerEntity* player = PLAYER;
1790
1791 [self doScriptEvent:OOJSID("stationReceivedDockingRequest") withArgument:other];
1792
1793 [UNIVERSE clearPreviousMessage];
1794
1796
1797 // Docking clearance not required - clear it just in case it's been
1798 // set for another nearby station.
1799 if (![self requiresDockingClearance]) {
1800 // TODO: We're potentially cancelling docking at another station, so
1801 // ensure we clear the timer to allow NPC traffic. If we
1802 // don't, normal traffic will resume once the timer runs out.
1803 // No clearance is needed, but don't send friendly messages to hostile ships!
1804 if (!(([other isPlayer] && [other hasHostileTarget]) || (self == [UNIVERSE station] && [other bounty] > 50))) {
1805 [self sendExpandedMessage:@"[station-docking-clearance-not-required]" toShip:other];
1806 }
1807 if ([other isPlayer]) {
1808 [player setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_NOT_REQUIRED];
1809 }
1810 [shipAI reactToMessage:@"DOCKING_REQUESTED" context:nil]; // react to the request
1811 [self doScriptEvent:OOJSID("stationAcceptedDockingRequest") withArgument:other];
1812
1814 result = @"DOCKING_CLEARANCE_NOT_REQUIRED";
1815 }
1816
1817 // Docking clearance already granted for this station - check for
1818 // time-out or cancellation (but only for the Player).
1819 if (result == nil && [other isPlayer] && self == [player getTargetDockStation]) {
1820 switch ([player getDockingClearanceStatus]) {
1824 [self sendExpandedMessage:[NSString stringWithFormat:
1825 DESC(@"station-docking-clearance-extended-until-@"),
1826 ClockToString([player clockTime] + DOCKING_CLEARANCE_WINDOW, NO)]
1827 toShip:other];
1828 [player setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_GRANTED];
1829 result = @"DOCKING_CLEARANCE_EXTENDED";
1830 break;
1831 }
1832 // else, continue with canceling.
1835 last_launch_time = timeNow;
1836 [self sendExpandedMessage:@"[station-docking-clearance-cancelled]" toShip:other];
1837 [player setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_NONE];
1838 result = @"DOCKING_CLEARANCE_CANCELLED";
1840 if ([self currentlyInDockingQueues] == 0) {
1841 [shipAI message:@"DOCKING_COMPLETE"];
1842 [self doScriptEvent:OOJSID("stationDockingQueuesAreEmpty")];
1843 }
1844 break;
1847 break;
1848 }
1849 }
1850
1851 // First we must set the status to REQUESTED to avoid problems when
1852 // switching docking targets - even if we later set it back to NONE.
1853 if (result == nil && [other isPlayer] && self != [player getTargetDockStation]) {
1854 player_reserved_dock = nil; // and clear any previously reserved dock
1855 [player setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_REQUESTED];
1856 }
1857
1858 // Deny docking for fugitives at the main station
1859 // TODO: Should this be another key in shipdata.plist and/or should this
1860 // apply to all stations?
1861 if (result == nil && self == [UNIVERSE station] && [other bounty] > 50) // do not grant docking clearance to fugitives
1862 {
1863 [self sendExpandedMessage:@"[station-docking-clearance-H-clearance-refused]" toShip:other];
1864 if ([other isPlayer])
1865 [player setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_NONE];
1866 result = @"DOCKING_CLEARANCE_DENIED_SHIP_FUGITIVE";
1867 }
1868
1869 if (result == nil && [other hasHostileTarget]) // do not grant docking clearance to hostile ships.
1870 {
1871 [self sendExpandedMessage:@"[station-docking-clearance-denied]" toShip:other];
1872 if ([other isPlayer])
1873 [player setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_NONE];
1874 result = @"DOCKING_CLEARANCE_DENIED_SHIP_HOSTILE";
1875 }
1876
1877 if (![self hasEligibleDock]) // make sure at least one dock could plausibly accept the player
1878 {
1879 if ([other isPlayer]) {
1880 [player setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_NONE];
1881 }
1882 [self sendExpandedMessage:@"[station-docking-clearance-denied-no-docks]" toShip:other];
1883
1884 result = @"DOCKING_CLEARANCE_DENIED_NO_DOCKS";
1885 } else if (![self hasClearDock]) // skip check if at least one dock clear
1886 {
1887 // Put ship in queue if we've got incoming or outgoing traffic or
1888 // if the player is waiting for manual clearance and we are not
1889 // the player
1890 if (result == nil && (([self currentlyInDockingQueues] && last_launch_time < timeNow) || (![other isPlayer] && [player getDockingClearanceStatus] == DOCKING_CLEARANCE_STATUS_REQUESTED))) {
1891 [self sendExpandedMessage:[NSString stringWithFormat:
1892 DESC(@"station-docking-clearance-acknowledged-d-ships-approaching"),
1893 [self currentlyInDockingQueues] + 1]
1894 toShip:other];
1895 // No need to set status to REQUESTED as we've already done that earlier.
1896 result = @"DOCKING_CLEARANCE_DENIED_TRAFFIC_INBOUND";
1897 }
1898
1899 if (result == nil && [self currentlyInLaunchingQueues]) {
1900 [self sendExpandedMessage:[NSString stringWithFormat:
1901 DESC(@"station-docking-clearance-acknowledged-d-ships-departing"),
1902 [self currentlyInLaunchingQueues] + 1]
1903 toShip:other];
1904 // No need to set status to REQUESTED as we've already done that earlier.
1905 result = @"DOCKING_CLEARANCE_DENIED_TRAFFIC_OUTBOUND";
1906 }
1907 if (result == nil) {
1908 // if this happens, the station has no docks which allow
1909 // docking, so deny clearance
1910 if ([other isPlayer]) {
1911 [player setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_NONE];
1912 }
1913 result = @"DOCKING_CLEARANCE_DENIED_NO_DOCKS";
1914 // but can check to see if we'll open some for later.
1915 NSEnumerator* subEnum = nil;
1916 DockEntity* sub = nil;
1917 BOOL openLater = NO;
1918 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
1919 NSString* docking = [sub canAcceptShipForDocking:other];
1920 if ([docking isEqualToString:@"DOCK_CLOSED"]) {
1921 JSContext* context = OOJSAcquireContext();
1922 OOJSVal rval = OOJSUndefinedValue();
1923 OOJSVal args[] = { OOJSValueFromNativeObject(context, sub),
1924 OOJSValueFromNativeObject(context, other) };
1925 BOOL tempreject = NO;
1926
1927 BOOL OK = [[self script] callMethod:OOJSID("willOpenDockingPortFor") inContext:context withArguments:args count:2 result:&rval];
1928 if (OK)
1929 tempreject = OOJSValueToBOOL(context, rval);
1930 if (!OK)
1931 tempreject = NO; // default to permreject
1932 if (tempreject) {
1933 openLater = YES;
1934 }
1935
1936 OOJSFreeValue(context, rval);
1937 OOJSFreeValue(context, args[0]);
1938 OOJSFreeValue(context, args[1]);
1939 OOJSRelinquishContext(context);
1940 }
1941 if (openLater)
1942 break;
1943 }
1944
1945 if (openLater) {
1946 [self sendExpandedMessage:@"[station-docking-clearance-denied-no-docks-yet]" toShip:other];
1947 } else {
1948 [self sendExpandedMessage:@"[station-docking-clearance-denied-no-docks]" toShip:other];
1949 }
1950 }
1951 }
1952
1953 // Ship has passed all checks - grant docking!
1954 if (result == nil) {
1956 if ([other isPlayer]) {
1957 [player setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_GRANTED];
1959 }
1960
1961 if ([self hasMultipleDocks] && [other isPlayer]) {
1962 [self sendExpandedMessage:[NSString stringWithFormat:
1963 DESC(@"station-docking-clearance-granted-in-@-until-@"),
1965 ClockToString([player clockTime] + DOCKING_CLEARANCE_WINDOW, NO)]
1966 toShip:other];
1967 } else {
1968 [self sendExpandedMessage:[NSString stringWithFormat:
1969 DESC(@"station-docking-clearance-granted-until-@"),
1970 ClockToString([player clockTime] + DOCKING_CLEARANCE_WINDOW, NO)]
1971 toShip:other];
1972 }
1973
1974 result = @"DOCKING_CLEARANCE_GRANTED";
1975 [shipAI reactToMessage:@"DOCKING_REQUESTED" context:nil]; // react to the request
1976 [self doScriptEvent:OOJSID("stationAcceptedDockingRequest") withArgument:other];
1977 }
1978 return result;
1979}
1980
1982{
1983 NSEnumerator* subEnum = nil;
1984 DockEntity* sub = nil;
1985 unsigned soa = 0;
1986 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
1988 }
1989 soa += [_shipsOnHold count];
1990 return soa;
1991}
1992
1994{
1995 NSEnumerator* subEnum = nil;
1996 DockEntity* sub = nil;
1997 unsigned soa = 0;
1998 for (subEnum = [self dockSubEntityEnumerator]; (sub = [subEnum nextObject]);) {
2000 }
2001 return soa;
2002}
2003
2008
2009- (void)setRequiresDockingClearance:(BOOL)newValue
2010{
2011 requiresDockingClearance = !!newValue; // Ensure yes or no
2012}
2013
2015{
2016 return allowsFastDocking;
2017}
2018
2019- (void)setAllowsFastDocking:(BOOL)newValue
2020{
2021 allowsFastDocking = !!newValue; // Ensure yes or no
2022}
2023
2025{
2026 return allowsAutoDocking;
2027}
2028
2029- (void)setAllowsAutoDocking:(BOOL)newValue
2030{
2031 allowsAutoDocking = !!newValue; // Ensure yes or no
2032}
2033
2035{
2036 // fixed stations only, not carriers!
2037 return allowsSaving && ([self maxFlightSpeed] == 0);
2038}
2039
2041{
2042 if ([shipinfoDictionary oo_boolForKey:@"rotating" defaultValue:NO])
2043 return YES;
2044 return [[shipinfoDictionary objectForKey:@"roles"] rangeOfString:@"rotating-station"].location != NSNotFound; // legacy
2045}
2046
2048{
2049 // 2010.06.14 - Micha - we can't default to the primary role as otherwise the logic
2050 // generating the market in [Universe commodityDataForEconomy:] doesn't
2051 // work properly with the various overrides. The primary role will get
2052 // used if either there is no market override, or the market wasn't
2053 // defined.
2054 return [shipinfoDictionary oo_stringForKey:@"market"];
2055}
2056
2058{
2059 if ([UNIVERSE station] == self)
2060 return YES;
2061 id determinant = [shipinfoDictionary objectForKey:@"has_shipyard"];
2062
2063 if (!determinant)
2064 determinant = [shipinfoDictionary objectForKey:@"hasShipyard"];
2065
2066 // NOTE: non-standard capitalization is documented and entrenched.
2067 if (determinant) {
2068 if ([determinant isKindOfClass:[NSArray class]]) {
2069 return [PLAYER scriptTestConditions:OOSanitizeLegacyScriptConditions(determinant, nil)];
2070 } else {
2071 return OOFuzzyBooleanFromObject(determinant, 0.0f);
2072 }
2073 } else {
2074 return NO;
2075 }
2076}
2077
2079{
2081}
2082
2083- (void)generateShipyard:(OOTechLevelID)stationTechLevel
2084{
2085 unsigned i;
2086
2087 if ([self localShipyard] == nil) {
2088 [self setLocalShipyard:[UNIVERSE shipsForSaleForSystem:[UNIVERSE currentSystemID] withTL:stationTechLevel atTime:[PLAYER clockTime]]];
2089 }
2090
2091 NSMutableArray* shipyard = [self localShipyard];
2092
2093 // remove ships that the player has already bought
2094 for (i = 0; i < [shipyard count]; i++) {
2095 NSString* shipID = [[shipyard oo_dictionaryAtIndex:i] oo_stringForKey:SHIPYARD_KEY_ID];
2096 if ([[PLAYER shipyardRecord] objectForKey:shipID]) {
2097 [shipyard removeObjectAtIndex:i--];
2098 }
2099 }
2100}
2101
2103{
2105}
2106
2107- (void)setSuppressArrivalReports:(BOOL)newValue
2108{
2109 suppress_arrival_reports = !!newValue; // ensure YES or NO
2110}
2111
2113{
2114 return hasBreakPattern;
2115}
2116
2117- (void)setHasBreakPattern:(BOOL)newValue
2118{
2119 hasBreakPattern = !!newValue;
2120}
2121
2123{
2124 return [NSString stringWithFormat:@"\"%@\" %@", name, [super descriptionComponents]];
2125}
2126
2128{
2129 NSMutableArray* flags = nil;
2130 NSString* flagsString = nil;
2131 NSString* alertString = @"*** ERROR: UNKNOWN ALERT LEVEL ***";
2132
2133 [super dumpSelfState];
2134
2135 switch (alertLevel) {
2137 alertString = @"green";
2138 break;
2139
2141 alertString = @"yellow";
2142 break;
2143
2145 alertString = @"red";
2146 break;
2147 }
2148
2149 OOLog(@"dumpState.stationEntity", @"Alert level: %@", alertString);
2150 OOLog(@"dumpState.stationEntity", @"Max police: %u", max_police);
2151 OOLog(@"dumpState.stationEntity", @"Max defense ships: %u", max_defense_ships);
2152 OOLog(@"dumpState.stationEntity", @"Defenders launched: %u", defenders_launched);
2153 OOLog(@"dumpState.stationEntity", @"Max scavengers: %u", max_scavengers);
2154 OOLog(@"dumpState.stationEntity", @"Scavengers launched: %u", scavengers_launched);
2155 OOLog(@"dumpState.stationEntity", @"Docked shuttles: %u", docked_shuttles);
2156 OOLog(@"dumpState.stationEntity", @"Docked traders: %u", docked_traders);
2157 OOLog(@"dumpState.stationEntity", @"Equivalent tech level: %zu", equivalentTechLevel);
2158 OOLog(@"dumpState.stationEntity", @"Equipment price factor: %g", equipmentPriceFactor);
2159
2160 flags = [NSMutableArray array];
2161#define ADD_FLAG_IF_SET(x) \
2162 if (x) { \
2163 [flags addObject:@ #x]; \
2164 }
2166 if ([self isRotatingStation]) {
2167 [flags addObject:@"rotatingStation"];
2168 }
2169 if (![self dockingCorridorIsEmpty]) {
2170 [flags addObject:@"dockingCorridorIsBusy"];
2171 }
2172 flagsString = [flags count] ? [flags componentsJoinedByString:@", "] : (NSString*)@"none";
2173 OOLog(@"dumpState.stationEntity", @"Flags: %@", flagsString);
2174
2175 // approach and hold lists.
2176
2177 // Ships on hold list, only used with moving stations (= carriers)
2178 if ([_shipsOnHold count] > 0) {
2179 OOLog(@"dumpState.stationEntity", @"%zu Ships on hold (unsorted):", [_shipsOnHold count]);
2180
2181 OOLogIndent();
2182 NSEnumerator* onHoldEnum = [_shipsOnHold objectEnumerator];
2183 ShipEntity* ship = nil;
2184 unsigned i = 1;
2185 foreach (ship, onHoldEnum) {
2186 OOLog(@"dumpState.stationEntity", @"Nr %i: %@ at distance %g with role: %@", i++, [ship displayName], HPdistance([self position], [ship position]), [ship primaryRole]);
2187 }
2188 OOLogOutdent();
2189 }
2190}
2191
2192@end
#define ADD_FLAG_IF_SET(x)
BOOL OOFuzzyBooleanFromObject(id object, float defaultValue)
void OOStandardsDeprecated(NSString *message)
BOOL OOEnforceStandards(void)
#define DESTROY(x)
OOINLINE HPVector vectorToHPVector(Vector v) INLINE_CONST_FUNC
Definition OOHPVector.h:166
OOINLINE HPVector HPvector_add(HPVector a, HPVector b) INLINE_CONST_FUNC
Definition OOHPVector.h:213
OOINLINE OOHPScalar HPdistance(HPVector v1, HPVector v2) INLINE_CONST_FUNC
Definition OOHPVector.h:298
#define OOJS_PROFILE_EXIT
#define OOJS_PROFILE_ENTER
jsval OOJSVal
#define OOJSFreeValue(context, value)
#define OOJSUndefinedValue()
OOINLINE jsval OOJSValueFromNativeObject(JSContext *context, id object)
OOINLINE BOOL OOJSValueToBOOL(JSContext *context, jsval value)
OOINLINE JSContext * OOJSAcquireContext(void)
OOINLINE void OOJSRelinquishContext(JSContext *context)
void OOLogOutdent(void)
Definition OOLogging.m:354
#define OOLog(class, format,...)
Definition OOLogging.h:84
void OOLogIndent(void)
Definition OOLogging.m:345
unsigned count
return nil
Vector vector_forward_from_quaternion(Quaternion quat) CONST_FUNC
@ NO_TARGET
Definition OOTypes.h:169
NSString * OOCommodityType
Definition OOTypes.h:97
@ AEGIS_NONE
Definition OOTypes.h:54
uint64_t OOCreditsQuantity
Definition OOTypes.h:160
uint16_t OOUniversalID
Definition OOTypes.h:165
NSUInteger OOTechLevelID
Definition OOTypes.h:177
uint32_t OOCargoQuantity
Definition OOTypes.h:155
double OOTimeDelta
Definition OOTypes.h:193
@ DOCKING_CLEARANCE_STATUS_TIMING_OUT
Definition OOTypes.h:152
@ DOCKING_CLEARANCE_STATUS_NOT_REQUIRED
Definition OOTypes.h:149
@ DOCKING_CLEARANCE_STATUS_GRANTED
Definition OOTypes.h:151
@ DOCKING_CLEARANCE_STATUS_NONE
Definition OOTypes.h:148
@ DOCKING_CLEARANCE_STATUS_REQUESTED
Definition OOTypes.h:150
OOINLINE Vector make_vector(OOScalar vx, OOScalar vy, OOScalar vz) INLINE_CONST_FUNC
Definition OOVector.h:149
const Vector kZeroVector
Definition OOVector.m:27
OOINLINE OOScalar magnitude2(Vector vec) INLINE_CONST_FUNC
Definition OOVector.h:237
OOINLINE Vector vector_multiply_scalar(Vector v, OOScalar s) INLINE_CONST_FUNC
Definition OOVector.h:180
#define PLAYER
NSDictionary * OOMakeDockingInstructions(StationEntity *station, HPVector coords, float speed, float range, NSString *ai_message, NSString *comms_message, BOOL match_rotation, int docking_stage)
OOStationAlertLevel
@ STATION_ALERT_LEVEL_RED
@ STATION_ALERT_LEVEL_YELLOW
@ STATION_ALERT_LEVEL_GREEN
#define DOCKING_CLEARANCE_WINDOW
#define UNIVERSE
Definition Universe.h:827
NSString * dbgDumpIdLocks()
NSArray * dbgGetShipsOnApproach()
Definition AI.h:35
void message:(NSString *ms)
Definition AI.m:536
void reactToMessage:context:(NSString *message,[context] NSString *debugContext)
Definition AI.m:363
void abortAllDockings()
Definition DockEntity.m:89
void launchShip:(ShipEntity *ship)
Definition DockEntity.m:804
NSUInteger countOfShipsInLaunchQueueWithPrimaryRole:(NSString *role)
Definition DockEntity.m:857
Vector portUpVectorForShipsBoundingBox:(BoundingBox bb)
Definition DockEntity.m:563
NSDictionary * dockingInstructionsForShip:(ShipEntity *ship)
Definition DockEntity.m:249
NSUInteger countOfShipsInLaunchQueue()
Definition DockEntity.m:599
NSUInteger countOfShipsInDockingQueue()
Definition DockEntity.m:594
NSUInteger pruneAndCountShipsOnApproach()
Definition DockEntity.m:60
NSString * canAcceptShipForDocking:(ShipEntity *ship)
Definition DockEntity.m:194
void autoDockShipsOnApproach()
Definition DockEntity.m:148
void abortDockingForShip:(ShipEntity *ship)
Definition DockEntity.m:534
void noteDockingForShip:(ShipEntity *ship)
Definition DockEntity.m:525
void clearDockingCorridor()
Definition DockEntity.m:972
void addShipToLaunchQueue:withPriority:(ShipEntity *ship,[withPriority] BOOL priority)
Definition DockEntity.m:785
Quaternion orientation
Definition Entity.m:682
GLfloat energy
Definition Entity.m:753
unsigned isShip
Definition Entity.m:125
void setScanClass:(OOScanClass sClass)
Definition Entity.m:738
OOEntityStatus status()
Definition Entity.m:733
unsigned isStation
Definition Entity.m:135
unsigned isPlayer
Definition Entity.m:145
void dumpSelfState()
Definition Entity.m:918
HPVector position
Definition Entity.m:576
double speed()
Definition Entity.m:713
NSUInteger exportLegalityForGood:(OOCommodityType good)
NSDictionary * dictionaryForScripting()
NSUInteger importLegalityForGood:(OOCommodityType good)
BOOL setQuantity:forGood:(OOCargoQuantity quantity,[forGood] OOCommodityType good)
OOCargoQuantity quantityForGood:(OOCommodityType good)
BOOL setPrice:forGood:(OOCreditsQuantity price,[forGood] OOCommodityType good)
void loadStationAmounts:(NSArray *amounts)
BOOL callMethod:inContext:withArguments:count:result:(jsid methodID,[inContext] JSContext *context,[withArguments] jsval *argv,[count] intN argc,[result] jsval *outResult)
Definition OOJSScript.m:328
void setLeader:(ShipEntity *leader)
ShipEntity * leader()
NSEnumerator * objectEnumerator()
Definition OOWeakSet.m:144
void makeObjectsPerformSelector:withObject:(SEL selector,[withObject] id argument)
Definition OOWeakSet.m:184
void removeObject:(id< OOWeakReferenceSupport > object)
Definition OOWeakSet.m:160
void removeAllObjects()
Definition OOWeakSet.m:209
NSUInteger count()
Definition OOWeakSet.m:129
OODockingClearanceStatus getDockingClearanceStatus()
StationEntity * getTargetDockStation()
void setDockingClearanceStatus:(OODockingClearanceStatus newValue)
void warnAboutHostiles()
void leaveDock:(StationEntity *station)
BOOL isExplicitlyUnpiloted()
void doScriptEvent:(OOJSPropID message)
void noteLostTarget()
void setBounty:withReason:(OOCreditsQuantity amount,[withReason] OOLegalStatusReason reason)
void addTarget:(Entity *targetEntity)
void setPrimaryAggressor:(Entity *targetEntity)
void setUpEscorts()
void setFuel:(OOFuelQuantity amount)
void takeEnergyDamage:from:becauseOf:weaponIdentifier:(double amount, [from] Entity *ent, [becauseOf] Entity *other, [weaponIdentifier] NSString *weaponIdentifier)
id initWithKey:definition:(NSString *key,[definition] NSDictionary *dict)
Definition ShipEntity.m:190
void setCargoFlag:(OOCargoFlag flag)
NSDictionary * shipinfoDictionary
Definition ShipEntity.h:206
BOOL collideWithShip:(ShipEntity *other)
OOShipGroup * escortGroup()
void takeScrapeDamage:from:(double amount,[from] Entity *ent)
void setSingleCrewWithRole:(NSString *crewRole)
NSString * shipDataKey()
void setGroup:(OOShipGroup *group)
NSString * primaryRole
OOShipGroup * group()
OOShipGroup * stationGroup()
GLfloat flightPitch
BOOL isPolice()
void setPrimaryRole:(NSString *role)
NSString * descriptionComponents()
BOOL hasNewAI()
void setHeatInsulation:(GLfloat value)
OOFuelQuantity fuel
OOCreditsQuantity bounty
OOAegisStatus aegis_status
Definition ShipEntity.h:367
OOScanClass scanClass()
void respondToAttackFrom:becauseOf:(Entity *from,[becauseOf] Entity *other)
void doScriptEvent:withArgument:andArgument:(OOJSPropID message,[withArgument] id argument1,[andArgument] id argument2)
unsigned being_mined
Definition ShipEntity.h:246
void becomeLargeExplosion:(double factor)
NSEnumerator * shipSubEntityEnumerator()
void switchLightsOff()
void adjustVelocity:(Vector xVel)
void setPendingEscortCount:(uint8_t count)
int legalStatus()
void sendExpandedMessage:toShip:(NSString *message_text,[toShip] ShipEntity *other_ship)
OOJSScript * script
Vector velocity()
GLfloat heatInsulation()
BOOL hasHostileTarget()
void update:(OOTimeDelta delta_t)
uint8_t pendingEscortCount()
void takeHeatDamage:(double amount)
void doScriptEvent:withArgument:(OOJSPropID message,[withArgument] id argument)
void markAsOffender:withReason:(int offence_value,[withReason] OOLegalStatusReason reason)
void dealloc()
Definition ShipEntity.m:986
void switchAITo:(NSString *aiString)
unsigned isHulk
void setFoundTarget:(Entity *targetEntity)
void becomeExplosion()
void sendAIMessage:(NSString *message)
NSArray * crew
GLfloat flightRoll
NSMutableArray * subEntities
GLfloat maxFlightSpeed
void setOwner:(Entity *who_owns_entity)
NSString * displayName
void becomeEnergyBlast()
GLfloat flightYaw
void enterDock:(StationEntity *station)
Vector port_dimensions
void addShipToLaunchQueue:withPriority:(ShipEntity *ship, [withPriority] BOOL priority)
void acceptPatrolReportFrom:(ShipEntity *patrol_ship)
NSArray * launchPolice()
ShipEntity * launchMiner()
double last_launch_time
ShipEntity * launchScavenger()
OOCommodityMarket * localMarket
double patrol_launch_interval
ShipEntity * launchIndependentShip:(NSString *role)
NSString * marketOverrideName()
double last_trader_launch_time
OOCommodityMarket * initialiseLocalMarket()
ShipEntity * launchDefenseShip()
void autoDockShipsOnApproach()
ShipEntity * launchPirateShip()
void setAlertLevel:signallingScript:(OOStationAlertLevel level,[signallingScript] BOOL signallingScript)
unsigned currentlyInDockingQueues()
BOOL suppressArrivalReports()
Vector virtualPortDimensions()
NSMutableDictionary * localInterfaces
DockEntity * player_reserved_dock
ShipEntity * launchShuttle()
NSMutableArray * localShipyard
unsigned allowsAutoDocking
void generateShipyard:(OOTechLevelID stationTechLevel)
BOOL dockingCorridorIsEmpty()
ShipEntity * launchPatrol()
NSDictionary * OOMakeDockingInstructions(StationEntity *station, HPVector coords, float speed, float range, NSString *ai_message, NSString *comms_message, BOOL match_rotation, int docking_stage)
unsigned defenders_launched
unsigned marketMonitored
NSString * descriptionComponents()
OOUniversalID planet
unsigned countOfDockedDefenders()
unsigned max_police
unsigned countOfDockedPolice()
unsigned no_docking_while_launching
OOCargoQuantity marketCapacity
NSDictionary * localMarketForScripting()
OOTechLevelID equivalentTechLevel
unsigned allowsSaving
unsigned max_scavengers
OOStationAlertLevel alertLevel
void autoDockShipsOnHold()
unsigned countOfDockedContractors()
unsigned marketBroadcast
unsigned hasBreakPattern
void sanityCheckShipsOnApproach()
double last_shuttle_launch_time
unsigned interstellarUndockingAllowed
NSString * allegiance
unsigned currentlyInLaunchingQueues()
unsigned scavengers_launched
unsigned docked_traders
void addShipToStationCount:(ShipEntity *ship)
unsigned countOfShipsInLaunchQueueWithPrimaryRole:(NSString *role)
OOWeakSet * _shipsOnHold
unsigned suppress_arrival_reports
HPVector beaconPosition()
unsigned allowsFastDocking
double shuttle_launch_interval
BOOL fitsInDock:andLogNoFit:(ShipEntity *ship,[andLogNoFit] BOOL logNoFit)
unsigned hasNPCTraffic
ShipEntity * launchEscort()
unsigned docked_shuttles
unsigned max_defense_ships
NSArray * marketDefinition
double approach_spacing
float equipmentPriceFactor
void pullInShipIfPermitted:(ShipEntity *ship)
void setLocalShipyard:(NSArray *market)
double last_patrol_report_time
NSString * marketScriptName
DockEntity * playerReservedDock()
DockEntity * selectDockForDocking()
NSEnumerator * dockSubEntityEnumerator()
unsigned requiresDockingClearance
double trader_launch_interval
NSDictionary * holdPositionInstructionForShip:(ShipEntity *ship)
void clearDockingCorridor()
void setAllegiance:(NSString *newAllegiance)
float randf(void)
unsigned Ranrot(void)
#define ranrot_rand()