Oolite
Loading...
Searching...
No Matches
PlayerEntity.m
Go to the documentation of this file.
1/*
2
3PlayerEntity.m
4
5Oolite
6Copyright (C) 2004-2013 Giles C Williams and contributors
7
8This program is free software; you can redistribute it and/or
9modify it under the terms of the GNU General Public License
10as published by the Free Software Foundation; either version 2
11of the License, or (at your option) any later version.
12
13This program is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16GNU General Public License for more details.
17
18You should have received a copy of the GNU General Public License
19along with this program; if not, write to the Free Software
20Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21MA 02110-1301, USA.
22
23*/
24
25#include <assert.h>
26
27#import "PlayerEntity.h"
32#import "PlayerEntitySound.h"
33
34#import "OOLaserShotEntity.h"
35#import "OOMesh.h"
36#import "OOPlanetEntity.h"
38#import "OOSunEntity.h"
39#import "ProxyPlayerEntity.h"
40#import "StationEntity.h"
41#import "WormholeEntity.h"
42
43#import "AI.h"
44#import "GameController.h"
45#import "HeadUpDisplay.h"
46#import "MyOpenGLView.h"
48#import "OOCacheManager.h"
50#import "OOColor.h"
51#import "OOConstToString.h"
52#import "OODebugSupport.h"
54#import "OOEquipmentType.h"
56#import "OOMaths.h"
57#import "OOMusicController.h"
58#import "OOOXZManager.h"
60#import "OOPListParsing.h"
61#import "OORoleSet.h"
62#import "OOShipRegistry.h"
63#import "OOSound.h"
64#import "OOStringExpander.h"
65#import "OOStringParsing.h"
66#import "OOTexture.h"
67#import "OOTrumble.h"
68#import "Octree.h"
70#import "ResourceManager.h"
71#import "ShipEntityAI.h"
72#import "Universe.h"
73
74#import "CollisionRegion.h"
75
76#import "OOConstToJSString.h"
77#import "OOJSEngineTimeManagement.h"
78#import "OOJSGuiScreenKeyDefinition.h"
79#import "OOJSInterfaceDefinition.h"
80#import "OOJSScript.h"
81#import "OOScriptTimer.h"
82
83#import "OOJoystickManager.h"
88
89#define PLAYER_DEFAULT_NAME @"Jameson"
90
91enum {
92 // If comm log is kCommLogTrimThreshold or more lines long, it will be cut to kCommLogTrimSize.
95};
96
97static NSString* const kOOLogBuyMountedOK = @"equip.buy.mounted";
98static NSString* const kOOLogBuyMountedFailed = @"equip.buy.mounted.failed";
99static float const kDeadResetTime = 30.0f;
100
102static GLfloat sBaseMass = 0.0;
103
104NSComparisonResult marketSorterByName(id a, id b, void* market);
105NSComparisonResult marketSorterByPrice(id a, id b, void* market);
106NSComparisonResult marketSorterByQuantity(id a, id b, void* market);
107NSComparisonResult marketSorterByMassUnit(id a, id b, void* market);
108
109@interface PlayerEntity (OOPrivate)
110
112- (void)doTradeIn:(OOCreditsQuantity)tradeInValue forPriceFactor:(double)priceFactor;
113
114// Subs of update:
115- (void)updateMovementFlags;
117- (void)updateFuelScoops:(OOTimeDelta)delta_t;
118- (void)updateClocks:(OOTimeDelta)delta_t;
120- (void)updateTrumbles:(OOTimeDelta)delta_t;
121- (void)performAutopilotUpdates:(OOTimeDelta)delta_t;
122- (void)performInFlightUpdates:(OOTimeDelta)delta_t;
123- (void)performWitchspaceCountdownUpdates:(OOTimeDelta)delta_t;
124- (void)performWitchspaceExitUpdates:(OOTimeDelta)delta_t;
125- (void)performLaunchingUpdates:(OOTimeDelta)delta_t;
126- (void)performDockingUpdates:(OOTimeDelta)delta_t;
127- (void)performDeadUpdates:(OOTimeDelta)delta_t;
128- (void)gameOverFadeToBW;
129- (void)updateTargeting;
130- (void)showGameOver;
131- (void)updateWormholes;
132
134- (BOOL)checkEntityForMassLock:(Entity*)ent withScanClass:(int)scanClass;
135
136// Shopping
138- (void)showMarketScreenDataLine:(OOGUIRow)row forGood:(OOCommodityType)good inMarket:(OOCommodityMarket*)localMarket holdQuantity:(OOCargoQuantity)quantity;
140
141- (BOOL)tryBuyingItem:(NSString*)eqKey;
142
143// Cargo & passenger contracts
144- (NSArray*)contractsListForScriptingFromArray:(NSArray*)contractsArray forCargo:(BOOL)forCargo;
145
146- (void)prepareMarkedDestination:(NSMutableDictionary*)markers marker:(NSDictionary*)marker;
147
148- (void)witchStart;
149- (void)witchJumpTo:(OOSystemID)sTo misjump:(BOOL)misjump;
150- (void)witchEnd;
151
152// Jump distance/cost calculations for selected target.
153- (double)hyperspaceJumpDistance;
155
157
158@end
159
160@interface ShipEntity (Hax)
161
163
164@end
165
166@implementation PlayerEntity
167
169{
170 if (EXPECT_NOT(gOOPlayer == nil)) {
171 gOOPlayer = [[PlayerEntity alloc] init];
172 }
173 return gOOPlayer;
174}
175
176- (void)setName:(NSString*)inName
177{
178 // Block super method; player ship can't be renamed.
179}
180
181- (GLfloat)baseMass
182{
183 if (sBaseMass <= 0.0) {
184 // First call with initialised mass (in [UNIVERSE setUpInitialUniverse]) is always to the cobra 3, even when starting with a savegame.
185 if ([self mass] > 0.0) // bootstrap the base mass.
186 {
187 OOLog(@"fuelPrices", @"Setting Cobra3 base mass to: %.2f ", [self mass]);
188 sBaseMass = [self mass];
189 } else {
190 // This happened on startup when [UNIVERSE setUpSpace] was called before player init, inside [UNIVERSE setUpInitialUniverse].
191 OOLog(@"fuelPrices", @"%@", @"Player ship not initialised properly yet, using precalculated base mass.");
192 return 185580.0;
193 }
194 }
195
196 return sBaseMass;
197}
198
199- (void)unloadAllCargoPodsForType:(OOCommodityType)type toManifest:(OOCommodityMarket*)manifest
200{
201 NSInteger i, cargoCount = [cargo count];
202 if (cargoCount == 0)
203 return;
204
205 // step through the cargo pods adding in the quantities
206 for (i = cargoCount - 1; i >= 0; i--) {
207 ShipEntity* cargoItem = [cargo objectAtIndex:i];
209 if (commodityType == nil || [commodityType isEqualToString:type]) {
210 if ([commodityType isEqualToString:type]) {
211 // transfer
213 } else // undefined
214 {
215 OOLog(@"player.badCargoPod", @"Cargo pod %@ has bad commodity type, rejecting.", cargoItem);
216 continue;
217 }
218 [cargo removeObjectAtIndex:i];
219 }
220 }
221}
222
223- (void)unloadCargoPodsForType:(OOCommodityType)type amount:(OOCargoQuantity)quantity
224{
225 NSInteger i, n_cargo = [cargo count];
226 if (n_cargo == 0)
227 return;
228
229 ShipEntity* cargoItem = nil;
230 OOCommodityType co_type;
231 OOCargoQuantity amount;
232 OOCargoQuantity cargoToGo = quantity;
233
234 // step through the cargo pods removing pods or quantities
235 for (i = n_cargo - 1; (i >= 0 && cargoToGo > 0); i--) {
236 cargoItem = [cargo objectAtIndex:i];
237 co_type = [cargoItem commodityType];
238 if (co_type == nil || [co_type isEqualToString:type]) {
239 if ([co_type isEqualToString:type]) {
240 amount = [cargoItem commodityAmount];
241 if (amount <= cargoToGo) {
242 [cargo removeObjectAtIndex:i];
243 cargoToGo -= amount;
244 } else {
245 // we only need to remove a part of the cargo to meet our target
246 [cargoItem setCommodity:co_type andAmount:(amount - cargoToGo)];
247 cargoToGo = 0;
248 }
249 } else // undefined
250 {
251 OOLog(@"player.badCargoPod", @"Cargo pod %@ has bad commodity type (COMMODITY_UNDEFINED), rejecting.", cargoItem);
252 continue;
253 }
254 }
255 }
256
257 // now check if we are ready. When not, proceed with quantities in the manifest.
258 if (cargoToGo > 0) {
260 }
261}
262
264{
265 NSAssert([self isDocked], @"Cannot unload cargo pods unless docked.");
266
267 /* loads commodities from the cargo pods onto the ship's manifest */
268 NSString* good = nil;
269 foreach (good, [shipCommodityData goods]) {
270 [self unloadAllCargoPodsForType:good toManifest:shipCommodityData];
271 }
272#ifndef NDEBUG
273 if ([cargo count] > 0) {
274 OOLog(@"player.unloadCargo", @"Cargo remains in pods after unloading - %@", cargo);
275 }
276#endif
277
278 [self calculateCurrentCargo]; // work out the correct value for current_cargo
279}
280
281// TODO: better feedback on the log as to why failing to create player cargo pods causes a CTD?
282- (void)createCargoPodWithType:(OOCommodityType)type andAmount:(OOCargoQuantity)amount
283{
284 ShipEntity* container = [UNIVERSE newShipWithRole:@"1t-cargopod"];
285 if (container) {
286 [container setScanClass:CLASS_CARGO];
287 [container setStatus:STATUS_IN_HOLD];
288 [container setCommodity:type andAmount:amount];
289 [cargo addObject:container];
290 [container release];
291 } else {
292 OOLogERR(@"player.loadCargoPods.noContainer", @"%@", @"couldn't create a container in [PlayerEntity loadCargoPods]");
293 // throw an exception here...
294 [NSException raise:OOLITE_EXCEPTION_FATAL
295 format:@"[PlayerEntity loadCargoPods] failed to create a container for cargo with role 'cargopod'"];
296 }
297}
298
299- (void)loadCargoPodsForType:(OOCommodityType)type fromManifest:(OOCommodityMarket*)manifest
300{
301 // load commodities from the ships manifest into individual cargo pods
302 unsigned j;
303
304 OOCargoQuantity quantity = [manifest quantityForGood:type];
305 OOMassUnit units = [manifest massUnitForGood:type];
306
307 if (quantity > 0) {
308 if (units == UNITS_TONS) {
309 // easy case
310 for (j = 0; j < quantity; j++) {
311 [self createCargoPodWithType:type andAmount:1]; // or CTD if unsuccesful (!)
312 }
314 } else {
315 OOCargoQuantity podsRequiredForQuantity, amountToLoadInCargopod, tmpQuantity;
316 // reserve up to 1/2 ton of each commodity for the safe
317 if (units == UNITS_KILOGRAMS) {
318 if (quantity <= MAX_KILOGRAMS_IN_SAFE) {
319 tmpQuantity = quantity;
320 quantity = 0;
321 } else {
322 tmpQuantity = MAX_KILOGRAMS_IN_SAFE;
323 quantity -= tmpQuantity;
324 }
325 amountToLoadInCargopod = KILOGRAMS_PER_POD;
326 } else {
327 if (quantity <= MAX_GRAMS_IN_SAFE) {
328 tmpQuantity = quantity;
329 quantity = 0;
330 } else {
331 tmpQuantity = MAX_GRAMS_IN_SAFE;
332 quantity -= tmpQuantity;
333 }
334 amountToLoadInCargopod = GRAMS_PER_POD;
335 }
336 if (quantity > 0) {
337 podsRequiredForQuantity = 1 + (quantity / amountToLoadInCargopod);
338 // this check is needed so that initial quantities like 1499kg or 1499999g
339 // do not result in generation of an empty cargopod
340 if (quantity % amountToLoadInCargopod == 0)
341 podsRequiredForQuantity--;
342
343 // put each ton or part-ton beyond that in a separate container
344 for (j = 0; j < podsRequiredForQuantity; j++) {
345 if (amountToLoadInCargopod > quantity) {
346 // last pod gets the dregs. :)
347 amountToLoadInCargopod = quantity;
348 }
349 [self createCargoPodWithType:type andAmount:amountToLoadInCargopod]; // or CTD if unsuccesful (!)
350 quantity -= amountToLoadInCargopod;
351 }
352 // adjust manifest for this commodity
353 [manifest setQuantity:tmpQuantity forGood:type];
354 }
355 }
356 }
357}
358
359- (void)loadCargoPodsForType:(OOCommodityType)type amount:(OOCargoQuantity)quantity
360{
362
363 while (quantity) {
364 if (unit != UNITS_TONS) {
365 int amount_per_container = (unit == UNITS_KILOGRAMS) ? KILOGRAMS_PER_POD : GRAMS_PER_POD;
366 while (quantity > 0) {
367 int smaller_quantity = 1 + ((quantity - 1) % amount_per_container);
368 if ([cargo count] < [self maxAvailableCargoSpace]) {
369 ShipEntity* container = [UNIVERSE newShipWithRole:@"1t-cargopod"];
370 if (container) {
371 // the cargopod ship is just being set up. If ejected, will call UNIVERSE addEntity
372 [container setStatus:STATUS_IN_HOLD];
373 [container setScanClass:CLASS_CARGO];
374 [container setCommodity:type andAmount:smaller_quantity];
375 [cargo addObject:container];
376 [container release];
377 }
378 } else {
379 // try to squeeze any surplus, up to half a ton, in the manifest.
380 int amount = [shipCommodityData quantityForGood:type] + smaller_quantity;
381 if (amount > MAX_GRAMS_IN_SAFE && unit == UNITS_GRAMS)
382 amount = MAX_GRAMS_IN_SAFE;
383 else if (amount > MAX_KILOGRAMS_IN_SAFE && unit == UNITS_KILOGRAMS)
384 amount = MAX_KILOGRAMS_IN_SAFE;
385
387 }
388 quantity -= smaller_quantity;
389 }
390 } else {
391 // put each ton in a separate container
392 while (quantity) {
393 if ([cargo count] < [self maxAvailableCargoSpace]) {
394 ShipEntity* container = [UNIVERSE newShipWithRole:@"1t-cargopod"];
395 if (container) {
396 // the cargopod ship is just being set up. If ejected, will call UNIVERSE addEntity
397 [container setScanClass:CLASS_CARGO];
398 [container setStatus:STATUS_IN_HOLD];
400 [cargo addObject:container];
401 [container release];
402 }
403 }
404 quantity--;
405 }
406 }
407 }
408}
409
411{
412 /* loads commodities from the ships manifest into individual cargo pods */
413 NSString* good = nil;
414 foreach (good, [shipCommodityData goods]) {
415 [self loadCargoPodsForType:good fromManifest:shipCommodityData];
416 }
417 [self calculateCurrentCargo]; // work out the correct value for current_cargo
418 cargo_dump_time = 0;
419}
420
425
427{
428 return credits;
429}
430
432{
433 return market_rnd;
434}
435
436- (void)setRandom_factor:(int)rf
437{
438 market_rnd = rf;
439}
440
442{
443 return galaxy_number;
444}
445
447{
448 return galaxy_coordinates;
449}
450
451- (void)setGalaxyCoordinates:(NSPoint)newPosition
452{
453 galaxy_coordinates.x = newPosition.x;
454 galaxy_coordinates.y = newPosition.y;
455}
456
458{
459 return cursor_coordinates;
460}
461
463{
465}
466
478
483
484- (void)setCustomChartZoom:(OOScalar)zoom
485{
486 custom_chart_zoom = zoom;
487}
488
493
494- (void)setCustomChartCentre:(NSPoint)coords
495{
498}
499
501{
502 NSPoint acc; // adjusted chart centre
503 double scroll_pos; // cursor coordinate at which we'd want to scoll chart in the direction we're currently considering
504 double ecc; // chart centre coordinate we'd want if the cursor was on the edge of the galaxy in the current direction
505
507 return galaxy_coordinates;
509 return NSMakePoint(128.0, 128.0);
512 }
513 // When fully zoomed in we want to centre chart on chart_centre_coordinates. When zoomed out we want the chart centred on
514 // (128.0, 128.0) so the galaxy fits the screen width. For intermediate zoom we interpolate.
515 acc.x = chart_centre_coordinates.x + (128.0 - chart_centre_coordinates.x) * (chart_zoom - 1.0) / (CHART_MAX_ZOOM - 1.0);
516 acc.y = chart_centre_coordinates.y + (128.0 - chart_centre_coordinates.y) * (chart_zoom - 1.0) / (CHART_MAX_ZOOM - 1.0);
517
518 // If the cursor is out of the centre non-scrolling part of the screen adjust the chart centre. If the cursor is just at scroll_pos
519 // we want to return the chart centre as it is, but if it's at the edge of the galaxy we want the centre positioned so the cursor is
520 // at the edge of the screen
522 scroll_pos = acc.x - CHART_SCROLL_AT_X * chart_zoom;
524 if (scroll_pos <= 0) {
525 acc.x = ecc;
526 } else {
527 acc.x = ((scroll_pos - chart_focus_coordinates.x) * ecc + chart_focus_coordinates.x * acc.x) / scroll_pos;
528 }
529 } else if (chart_focus_coordinates.x - acc.x >= CHART_SCROLL_AT_X * chart_zoom) {
530 scroll_pos = acc.x + CHART_SCROLL_AT_X * chart_zoom;
531 ecc = 256.0 - CHART_WIDTH_AT_MAX_ZOOM * chart_zoom / 2.0;
532 if (scroll_pos >= 256.0) {
533 acc.x = ecc;
534 } else {
535 acc.x = ((chart_focus_coordinates.x - scroll_pos) * ecc + (256.0 - chart_focus_coordinates.x) * acc.x) / (256.0 - scroll_pos);
536 }
537 }
539 scroll_pos = acc.y - CHART_SCROLL_AT_Y * chart_zoom;
541 if (scroll_pos <= 0) {
542 acc.y = ecc;
543 } else {
544 acc.y = ((scroll_pos - chart_focus_coordinates.y) * ecc + chart_focus_coordinates.y * acc.y) / scroll_pos;
545 }
546 } else if (chart_focus_coordinates.y - acc.y >= CHART_SCROLL_AT_Y * chart_zoom) {
547 scroll_pos = acc.y + CHART_SCROLL_AT_Y * chart_zoom;
548 ecc = 256.0 - CHART_HEIGHT_AT_MAX_ZOOM * chart_zoom / 2.0;
549 if (scroll_pos >= 256.0) {
550 acc.y = ecc;
551 } else {
552 acc.y = ((chart_focus_coordinates.y - scroll_pos) * ecc + (256.0 - chart_focus_coordinates.y) * acc.y) / (256.0 - scroll_pos);
553 }
554 }
555 return acc;
556}
557
559{
560 return ANA_mode;
561}
562
564{
565 return system_id;
566}
567
568- (void)setSystemID:(OOSystemID)sid
569{
570 system_id = sid;
571 galaxy_coordinates = PointFromString([[UNIVERSE systemManager] getProperty:@"coordinates" forSystem:sid inGalaxy:galaxy_number]);
574}
575
580
581- (void)setPreviousSystemID:(OOSystemID)sid
582{
583 previous_system_id = sid;
584}
585
590
591- (void)setTargetSystemID:(OOSystemID)sid
592{
593 target_system_id = sid;
594 cursor_coordinates = PointFromString([[UNIVERSE systemManager] getProperty:@"coordinates" forSystemKey:[UNIVERSE keyForPlanetOverridesForSystem:sid inGalaxy:galaxy_number]]);
595}
596
597// just return target system id if no valid next hop
599{
600 // not available if no ANA
601 if (![self hasEquipmentItemProviding:@"EQ_ADVANCED_NAVIGATIONAL_ARRAY"]) {
602 return target_system_id;
603 }
604 // not available if ANA is turned off
606 return target_system_id;
607 }
608 // easy case
610 return system_id; // no need to calculate
611 }
612 NSDictionary* routeInfo = nil;
613 routeInfo = [UNIVERSE routeFromSystem:system_id toSystem:target_system_id optimizedBy:ANA_mode];
614 // no route to destination
615 if (routeInfo == nil) {
616 return target_system_id;
617 }
618 return [[routeInfo oo_arrayForKey:@"route"] oo_intAtIndex:1];
619}
620
622{
623 return info_system_id;
624}
625
626- (void)setInfoSystemID:(OOSystemID)sid moveChart:(BOOL)moveChart
627{
628 if (sid != info_system_id) {
630 info_system_id = sid;
631 JSContext* context = OOJSAcquireContext();
632 ShipScriptEvent(context, self, "infoSystemWillChange", OOJSValueFromDouble(context, info_system_id), OOJSValueFromDouble(context, old));
633 if (gui_screen == GUI_SCREEN_LONG_RANGE_CHART || gui_screen == GUI_SCREEN_SHORT_RANGE_CHART) {
634 if (moveChart) {
635 target_chart_focus = [[UNIVERSE systemManager] getCoordinatesForSystem:info_system_id inGalaxy:galaxy_number];
636 }
637 } else {
638 if (gui_screen == GUI_SCREEN_SYSTEM_DATA) {
640 }
641 if (moveChart) {
642 chart_centre_coordinates = [[UNIVERSE systemManager] getCoordinatesForSystem:info_system_id inGalaxy:galaxy_number];
646 }
647 }
648 ShipScriptEvent(context, self, "infoSystemChanged", OOJSValueFromDouble(context, info_system_id), OOJSValueFromDouble(context, old));
649 OOJSRelinquishContext(context);
650 }
651}
652
654{
656 [self setInfoSystemID:target_system_id moveChart:YES];
657 return;
658 }
659 NSArray* route = [[[UNIVERSE routeFromSystem:system_id toSystem:target_system_id optimizedBy:ANA_mode] oo_arrayForKey:@"route"] retain];
660 NSUInteger i;
661 if (route == nil) {
662 [self setInfoSystemID:target_system_id moveChart:YES];
663 return;
664 }
665 for (i = 0; i < [route count]; i++) {
666 if ([[route objectAtIndex:i] intValue] == info_system_id) {
667 if (i + 1 < [route count]) {
668 [self setInfoSystemID:[[route objectAtIndex:i + 1] unsignedIntValue] moveChart:YES];
669 [route release];
670 return;
671 }
672 break;
673 }
674 }
675 [route release];
676 [self setInfoSystemID:target_system_id moveChart:YES];
677 return;
678}
679
681{
683 [self setInfoSystemID:system_id moveChart:YES];
684 return;
685 }
686 NSArray* route = [[[UNIVERSE routeFromSystem:system_id toSystem:target_system_id optimizedBy:ANA_mode] oo_arrayForKey:@"route"] retain];
687 NSUInteger i;
688 if (route == nil) {
689 [self setInfoSystemID:system_id moveChart:YES];
690 return;
691 }
692 for (i = 0; i < [route count]; i++) {
693 if ([[route objectAtIndex:i] intValue] == info_system_id) {
694 if (i > 0) {
695 [self setInfoSystemID:[[route objectAtIndex:i - 1] unsignedIntValue] moveChart:YES];
696 [route release];
697 return;
698 }
699 break;
700 }
701 }
702 [route release];
703 [self setInfoSystemID:system_id moveChart:YES];
704 return;
705}
706
708{
709 [self setInfoSystemID:system_id moveChart:YES];
710 return;
711}
712
714{
715 [self setInfoSystemID:target_system_id moveChart:YES];
716 return;
717}
718
720{
721 NSArray* route = [[UNIVERSE routeFromSystem:system_id toSystem:target_system_id optimizedBy:ANA_mode] oo_arrayForKey:@"route"];
722 NSUInteger i;
723 if (route == nil) {
724 return NO;
725 }
726 for (i = 0; i < [route count]; i++) {
727 if ([[route objectAtIndex:i] intValue] == info_system_id) {
728 return YES;
729 }
730 }
731 return NO;
732}
733
735{
736 return wormhole;
737}
738
739- (void)setWormhole:(WormholeEntity*)newWormhole
740{
741 [wormhole release];
742 if (newWormhole != nil) {
743 wormhole = [newWormhole retain];
744 } else {
745 wormhole = nil;
746 }
747}
748
750{
751 int i;
752
753 NSMutableDictionary* result = [NSMutableDictionary dictionary];
754
755 [result setObject:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] forKey:@"written_by_version"];
756
757 NSString* gal_id = [NSString stringWithFormat:@"%u", galaxy_number];
758 NSString* sys_id = [NSString stringWithFormat:@"%d", system_id];
759 NSString* tgt_id = [NSString stringWithFormat:@"%d", target_system_id];
760 NSString* prv_id = [NSString stringWithFormat:@"%d", previous_system_id];
761
762 // Variable requiredCargoSpace not suitable for Oolite as it currently stands: it retroactively changes a savegame cargo space.
763 // unsigned passenger_space = [[OOEquipmentType equipmentTypeWithIdentifier:@"EQ_PASSENGER_BERTH"] requiredCargoSpace];
764 // if (passenger_space == 0) passenger_space = PASSENGER_BERTH_SPACE;
765
766 [result setObject:gal_id forKey:@"galaxy_id"];
767 [result setObject:sys_id forKey:@"system_id"];
768 [result setObject:tgt_id forKey:@"target_id"];
769 [result setObject:prv_id forKey:@"previous_system_id"];
770 [result setObject:[NSNumber numberWithFloat:saved_chart_zoom] forKey:@"chart_zoom"];
771 [result setObject:[NSNumber numberWithInt:ANA_mode] forKey:@"chart_ana_mode"];
772 [result setObject:[NSNumber numberWithInt:longRangeChartMode] forKey:@"chart_colour_mode"];
773
774 if (found_system_id >= 0) {
775 NSString* found_id = [NSString stringWithFormat:@"%d", found_system_id];
776 [result setObject:found_id forKey:@"found_system_id"];
777 }
778
779 // Write the name of the current system. Useful for looking up saved game information and for overlapping systems.
780 if (![UNIVERSE inInterstellarSpace]) {
781 [result setObject:[UNIVERSE getSystemName:[self currentSystemID]] forKey:@"current_system_name"];
782 OOGovernmentID government = [[UNIVERSE currentSystemData] oo_intForKey:KEY_GOVERNMENT];
783 OOTechLevelID techlevel = [[UNIVERSE currentSystemData] oo_intForKey:KEY_TECHLEVEL];
784 OOEconomyID economy = [[UNIVERSE currentSystemData] oo_intForKey:KEY_ECONOMY];
785 [result setObject:[NSNumber numberWithUnsignedShort:government] forKey:@"current_system_government"];
786 [result setObject:[NSNumber numberWithUnsignedInteger:techlevel] forKey:@"current_system_techlevel"];
787 [result setObject:[NSNumber numberWithUnsignedShort:economy] forKey:@"current_system_economy"];
788 }
789
790 [result setObject:[self commanderName] forKey:@"player_name"];
791 [result setObject:[self lastsaveName] forKey:@"player_save_name"];
792 [result setObject:[self shipUniqueName] forKey:@"ship_unique_name"];
793 [result setObject:[self shipClassName] forKey:@"ship_class_name"];
794
795 /*
796 BUG: GNUstep truncates integer values to 32 bits when loading XML plists.
797 Workaround: store credits as a double. 53 bits of precision ought to
798 be good enough for anybody. Besides, we display credits with double
799 precision anyway.
800 -- Ahruman 2011-02-15
801 */
802 [result oo_setFloat:credits forKey:@"credits"];
803 [result oo_setUnsignedInteger:fuel forKey:@"fuel"];
804
805 [result oo_setInteger:galaxy_number forKey:@"galaxy_number"];
806
807 [result oo_setBool:[self weaponsOnline] forKey:@"weapons_online"];
808
809 if (forward_weapon_type != nil) {
810 [result setObject:[forward_weapon_type identifier] forKey:@"forward_weapon"];
811 }
812 if (aft_weapon_type != nil) {
813 [result setObject:[aft_weapon_type identifier] forKey:@"aft_weapon"];
814 }
815 if (port_weapon_type != nil) {
816 [result setObject:[port_weapon_type identifier] forKey:@"port_weapon"];
817 }
818 if (starboard_weapon_type != nil) {
819 [result setObject:[starboard_weapon_type identifier] forKey:@"starboard_weapon"];
820 }
821 [result setObject:[self serializeShipSubEntities] forKey:@"subentities_status"];
822 if (hud != nil && [hud nonlinearScanner]) {
823 [result oo_setFloat:[hud scannerZoom] forKey:@"ship_scanner_zoom"];
824 }
825
826 [result oo_setInteger:max_cargo + PASSENGER_BERTH_SPACE * max_passengers forKey:@"max_cargo"];
827
828 [result setObject:[shipCommodityData savePlayerAmounts] forKey:@"shipCommodityData"];
829
830 NSMutableArray* missileRoles = [NSMutableArray arrayWithCapacity:max_missiles];
831
832 for (i = 0; i < (int)max_missiles; i++) {
833 if (missile_entity[i]) {
835 } else {
836 [missileRoles addObject:@"NONE"];
837 }
838 }
839 [result setObject:missileRoles forKey:@"missile_roles"];
840
841 [result oo_setInteger:missiles forKey:@"missiles"];
842
843 [result oo_setInteger:legalStatus forKey:@"legal_status"];
844 [result oo_setInteger:market_rnd forKey:@"market_rnd"];
845 [result oo_setInteger:ship_kills forKey:@"ship_kills"];
846
847 // ship depreciation
848 [result oo_setInteger:ship_trade_in_factor forKey:@"ship_trade_in_factor"];
849
850 // mission variables
851 if (mission_variables != nil) {
852 [result setObject:[NSDictionary dictionaryWithDictionary:mission_variables] forKey:@"mission_variables"];
853 }
854
855 // communications log
856 NSArray* log = [self commLog];
857 if (log != nil)
858 [result setObject:log forKey:@"comm_log"];
859
860 [result oo_setUnsignedInteger:entity_personality forKey:@"entity_personality"];
861
862 // extra equipment flags
863 NSMutableDictionary* equipment = [NSMutableDictionary dictionary];
864 NSEnumerator* eqEnum = nil;
865 NSString* eqDesc = nil;
866 for (eqEnum = [self equipmentEnumerator]; (eqDesc = [eqEnum nextObject]);) {
867 [equipment oo_setInteger:[self countEquipmentItem:eqDesc] forKey:eqDesc];
868 }
869 if ([equipment count] != 0) {
870 [result setObject:equipment forKey:@"extra_equipment"];
871 }
873 [result setObject:[[eqScripts oo_arrayAtIndex:primedEquipment] oo_stringAtIndex:0] forKey:@"primed_equipment"];
874
875 [result setObject:[self fastEquipmentA] forKey:@"primed_equipment_a"];
876 [result setObject:[self fastEquipmentB] forKey:@"primed_equipment_b"];
877
878 // roles
879 [result setObject:roleWeights forKey:@"role_weights"];
880
881 // role information
882 [result setObject:roleWeightFlags forKey:@"role_weight_flags"];
883
884 // role information
885 [result setObject:roleSystemList forKey:@"role_system_memory"];
886
887 // reputation
888 [result setObject:reputation forKey:@"reputation"];
889
890 // initialise parcel reputations in dictionary if not set
891 int pGood = [reputation oo_intForKey:PARCEL_GOOD_KEY];
892 int pBad = [reputation oo_intForKey:PARCEL_BAD_KEY];
893 int pUnknown = [reputation oo_intForKey:PARCEL_UNKNOWN_KEY];
894 if (pGood + pBad + pUnknown != MAX_CONTRACT_REP) {
895 [reputation oo_setInteger:0 forKey:PARCEL_GOOD_KEY];
896 [reputation oo_setInteger:0 forKey:PARCEL_BAD_KEY];
897 [reputation oo_setInteger:MAX_CONTRACT_REP forKey:PARCEL_UNKNOWN_KEY];
898 }
899
900 // passengers
901 [result oo_setInteger:max_passengers forKey:@"max_passengers"];
902 [result setObject:passengers forKey:@"passengers"];
903 [result setObject:passenger_record forKey:@"passenger_record"];
904
905 // parcels
906 [result setObject:parcels forKey:@"parcels"];
907 [result setObject:parcel_record forKey:@"parcel_record"];
908
909 // specialCargo
910 if (specialCargo)
911 [result setObject:specialCargo forKey:@"special_cargo"];
912
913 // contracts
914 [result setObject:contracts forKey:@"contracts"];
915 [result setObject:contract_record forKey:@"contract_record"];
916
917 [result setObject:missionDestinations forKey:@"mission_destinations"];
918
919 // shipyard
920 [result setObject:shipyard_record forKey:@"shipyard_record"];
921
922 // ship's clock
923 [result setObject:[NSNumber numberWithDouble:ship_clock] forKey:@"ship_clock"];
924
925 // speech
926 [result setObject:[NSNumber numberWithInt:isSpeechOn] forKey:@"speech_on"];
927#if OOLITE_ESPEAK
928 [result setObject:[UNIVERSE voiceName:voice_no]
929 forKey:@"speech_voice"];
930 [result setObject:[NSNumber numberWithBool:voice_gender_m] forKey:@"speech_gender"];
931#endif
932
933 // docking clearance
934 [result setObject:[NSNumber numberWithBool:[UNIVERSE dockingClearanceProtocolActive]] forKey:@"docking_clearance_protocol"];
935
936 // base ship description
937 [result setObject:[self shipDataKey] forKey:@"ship_desc"];
938 [result setObject:[[self shipInfoDictionary] oo_stringForKey:KEY_NAME] forKey:@"ship_name"];
939
940 // custom view no.
941 [result oo_setUnsignedInteger:_customViewIndex forKey:@"custom_view_index"];
942
943 // escape pod rescue time
944 [result oo_setFloat:[self escapePodRescueTime] forKey:@"escape_pod_rescue_time"];
945
946 // local market for main station
947 if ([[UNIVERSE station] localMarket])
948 [result setObject:[[[UNIVERSE station] localMarket] saveStationAmounts] forKey:@"localMarket"];
949
950 // Scenario restriction on OXZs
951 [result setObject:[UNIVERSE useAddOns] forKey:@"scenario_restriction"];
952
953 [result setObject:[[UNIVERSE systemManager] exportScriptedChanges] forKey:@"scripted_planetinfo_overrides"];
954
955 // trumble information
956 [result setObject:[self trumbleValue] forKey:@"trumbles"];
957
958 // wormhole information
959 NSMutableArray* wormholeDicts = [NSMutableArray arrayWithCapacity:[scannedWormholes count]];
960 WormholeEntity* wh = nil;
961 foreach (wh, scannedWormholes) {
962 [wormholeDicts addObject:[wh getDict]];
963 }
964 [result setObject:wormholeDicts forKey:@"wormholes"];
965
966 // docked station
968 [result setObject:dockedStation != nil ? [dockedStation primaryRole] : (NSString*)@"" forKey:@"docked_station_role"];
969 if (dockedStation) {
971 [result setObject:ArrayFromHPVector(dpos) forKey:@"docked_station_position"];
972 } else {
973 [result setObject:[NSArray array] forKey:@"docked_station_position"];
974 }
975 [result setObject:[UNIVERSE getStationMarkets] forKey:@"station_markets"];
976
977 // scenario information
978 if (scenarioKey != nil) {
979 [result setObject:scenarioKey forKey:@"scenario"];
980 }
981
982 // create checksum
984 // TODO: should checksum checks be removed?
985 // munge_checksum(galaxy_seed.a); munge_checksum(galaxy_seed.b); munge_checksum(galaxy_seed.c);
986 // munge_checksum(galaxy_seed.d); munge_checksum(galaxy_seed.e); munge_checksum(galaxy_seed.f);
996
997 if (mission_variables != nil) {
998 munge_checksum([[mission_variables description] length]);
999 }
1000 if (equipment != nil) {
1001 munge_checksum([[equipment description] length]);
1002 }
1003
1004 int final_checksum = munge_checksum([[self shipDataKey] length]);
1005
1006 // set checksum
1007 [result oo_setInteger:final_checksum forKey:@"checksum"];
1008
1009 return result;
1010}
1011
1012- (BOOL)setCommanderDataFromDictionary:(NSDictionary*)dict
1013{
1014 // multi-function displays
1015 // must be reset before ship setup
1016 [multiFunctionDisplayText release];
1018
1019 [multiFunctionDisplaySettings release];
1021
1022 [customDialSettings release];
1023 customDialSettings = [[NSMutableDictionary alloc] init];
1024
1025 [[UNIVERSE gameView] resetTypedString];
1026
1027 // Required keys
1028 if ([dict oo_stringForKey:@"ship_desc"] == nil)
1029 return NO;
1030 // galaxy_seed is used is 1.80 or earlier
1031 if ([dict oo_stringForKey:@"galaxy_seed"] == nil && [dict oo_stringForKey:@"galaxy_id"] == nil)
1032 return NO;
1033 // galaxy_coordinates is used is 1.80 or earlier
1034 if ([dict oo_stringForKey:@"galaxy_coordinates"] == nil && [dict oo_stringForKey:@"system_id"] == nil)
1035 return NO;
1036
1037 NSString* scenarioRestrict = [dict oo_stringForKey:@"scenario_restriction" defaultValue:nil];
1038 if (scenarioRestrict == nil) {
1039 // older save game - use the 'strict' key instead
1040 BOOL strict = [dict oo_boolForKey:@"strict" defaultValue:NO];
1041 if (strict) {
1042 scenarioRestrict = SCENARIO_OXP_DEFINITION_NONE;
1043 } else {
1044 scenarioRestrict = SCENARIO_OXP_DEFINITION_ALL;
1045 }
1046 }
1047
1048 if (![UNIVERSE setUseAddOns:scenarioRestrict fromSaveGame:YES]) {
1049 return NO;
1050 }
1051
1052 // base ship description
1053 [self setShipDataKey:[dict oo_stringForKey:@"ship_desc"]];
1054
1055 NSDictionary* shipDict = [[OOShipRegistry sharedRegistry] shipInfoForKey:[self shipDataKey]];
1056 if (shipDict == nil)
1057 return NO;
1058 if (![self setUpShipFromDictionary:shipDict])
1059 return NO;
1060 OOLog(@"fuelPrices", @"Got \"%@\", fuel charge rate: %.2f", [self shipDataKey], [self fuelChargeRate]);
1061
1062 // ship depreciation
1063 ship_trade_in_factor = [dict oo_intForKey:@"ship_trade_in_factor" defaultValue:95];
1064
1065 // newer savegames use galaxy_id
1066 if ([dict oo_stringForKey:@"galaxy_id"] != nil) {
1067 galaxy_number = [dict oo_unsignedIntegerForKey:@"galaxy_id"];
1069 return NO;
1070 }
1071 [UNIVERSE setGalaxyTo:galaxy_number andReinit:YES];
1072
1073 system_id = [dict oo_intForKey:@"system_id"];
1074 if (system_id < 0 || system_id >= OO_SYSTEMS_PER_GALAXY) {
1075 return NO;
1076 }
1077
1078 [UNIVERSE setSystemTo:system_id];
1079
1080 NSArray* coord_vals = ScanTokensFromString([[UNIVERSE systemManager] getProperty:@"coordinates" forSystem:system_id inGalaxy:galaxy_number]);
1081 galaxy_coordinates.x = [coord_vals oo_unsignedCharAtIndex:0];
1082 galaxy_coordinates.y = [coord_vals oo_unsignedCharAtIndex:1];
1086 chart_zoom = [dict oo_floatForKey:@"chart_zoom" defaultValue:1.0];
1089 ANA_mode = [dict oo_intForKey:@"chart_ana_mode" defaultValue:OPTIMIZED_BY_NONE];
1090 longRangeChartMode = [dict oo_intForKey:@"chart_colour_mode" defaultValue:OOLRC_MODE_SUNCOLOR];
1091 if (longRangeChartMode == OOLRC_MODE_UNKNOWN)
1092 longRangeChartMode = OOLRC_MODE_SUNCOLOR;
1093
1094 target_system_id = [dict oo_intForKey:@"target_id" defaultValue:system_id];
1095 previous_system_id = [dict oo_intForKey:@"previous_system_id" defaultValue:system_id];
1097 coord_vals = ScanTokensFromString([[UNIVERSE systemManager] getProperty:@"coordinates" forSystem:target_system_id inGalaxy:galaxy_number]);
1098 cursor_coordinates.x = [coord_vals oo_unsignedCharAtIndex:0];
1099 cursor_coordinates.y = [coord_vals oo_unsignedCharAtIndex:1];
1100
1103
1104 found_system_id = [dict oo_intForKey:@"found_system_id" defaultValue:-1];
1105 } else
1106 // compatibility for loading 1.80 savegames
1107 {
1108 galaxy_number = [dict oo_unsignedIntegerForKey:@"galaxy_number"];
1109
1110 [UNIVERSE setGalaxyTo:galaxy_number andReinit:YES];
1111
1112 NSArray* coord_vals = ScanTokensFromString([dict oo_stringForKey:@"galaxy_coordinates"]);
1113 galaxy_coordinates.x = [coord_vals oo_unsignedCharAtIndex:0];
1114 galaxy_coordinates.y = [coord_vals oo_unsignedCharAtIndex:1];
1118 chart_zoom = 1.0;
1119 target_chart_zoom = 1.0;
1120 saved_chart_zoom = 1.0;
1122
1123 NSString* keyStringValue = [dict oo_stringForKey:@"target_coordinates"];
1124
1125 if (keyStringValue != nil) {
1126 coord_vals = ScanTokensFromString(keyStringValue);
1127 cursor_coordinates.x = [coord_vals oo_unsignedCharAtIndex:0];
1128 cursor_coordinates.y = [coord_vals oo_unsignedCharAtIndex:1];
1129 }
1132
1133 // calculate system ID, target ID
1134 if ([dict objectForKey:@"current_system_name"]) {
1135 system_id = [UNIVERSE findSystemFromName:[dict oo_stringForKey:@"current_system_name"]];
1136 if (system_id == -1)
1137 system_id = [UNIVERSE findSystemNumberAtCoords:galaxy_coordinates withGalaxy:galaxy_number includingHidden:YES];
1138 } else {
1139 // really old save games don't have system name saved
1140 // use coordinates instead - unreliable in zero-distance pairs.
1141 system_id = [UNIVERSE findSystemNumberAtCoords:galaxy_coordinates withGalaxy:galaxy_number includingHidden:YES];
1142 }
1143 // and current_system_name and target_system_name
1144 // were introduced at different times, too
1145 if ([dict objectForKey:@"target_system_name"]) {
1146 target_system_id = [UNIVERSE findSystemFromName:[dict oo_stringForKey:@"target_system_name"]];
1147 if (target_system_id == -1)
1148 target_system_id = [UNIVERSE findSystemNumberAtCoords:cursor_coordinates withGalaxy:galaxy_number includingHidden:YES];
1149 } else {
1150 target_system_id = [UNIVERSE findSystemNumberAtCoords:cursor_coordinates withGalaxy:galaxy_number includingHidden:YES];
1151 }
1153 found_system_id = -1;
1154 }
1155
1156 NSString* cname = [dict oo_stringForKey:@"player_name" defaultValue:PLAYER_DEFAULT_NAME];
1157 [self setCommanderName:cname];
1158 [self setLastsaveName:[dict oo_stringForKey:@"player_save_name" defaultValue:cname]];
1159
1160 [self setShipUniqueName:[dict oo_stringForKey:@"ship_unique_name" defaultValue:@""]];
1161 [self setShipClassName:[dict oo_stringForKey:@"ship_class_name" defaultValue:[shipDict oo_stringForKey:@"name"]]];
1162
1163 [shipCommodityData loadPlayerAmounts:[dict oo_arrayForKey:@"shipCommodityData"]];
1164
1165 // extra equipment flags
1166 [self removeAllEquipment];
1167 NSMutableDictionary* equipment = [NSMutableDictionary dictionaryWithDictionary:[dict oo_dictionaryForKey:@"extra_equipment"]];
1168
1169 // Equipment flags (deprecated in favour of equipment dictionary, keep for compatibility)
1170 if ([dict oo_boolForKey:@"has_docking_computer"])
1171 [equipment oo_setInteger:1 forKey:@"EQ_DOCK_COMP"];
1172 if ([dict oo_boolForKey:@"has_galactic_hyperdrive"])
1173 [equipment oo_setInteger:1 forKey:@"EQ_GAL_DRIVE"];
1174 if ([dict oo_boolForKey:@"has_escape_pod"])
1175 [equipment oo_setInteger:1 forKey:@"EQ_ESCAPE_POD"];
1176 if ([dict oo_boolForKey:@"has_ecm"])
1177 [equipment oo_setInteger:1 forKey:@"EQ_ECM"];
1178 if ([dict oo_boolForKey:@"has_scoop"])
1179 [equipment oo_setInteger:1 forKey:@"EQ_FUEL_SCOOPS"];
1180 if ([dict oo_boolForKey:@"has_energy_bomb"])
1181 [equipment oo_setInteger:1 forKey:@"EQ_ENERGY_BOMB"];
1182 if ([dict oo_boolForKey:@"has_fuel_injection"])
1183 [equipment oo_setInteger:1 forKey:@"EQ_FUEL_INJECTION"];
1184
1185 // Legacy energy unit type -> energy unit equipment item
1186 if ([dict oo_boolForKey:@"has_energy_unit"] && [self installedEnergyUnitType] == ENERGY_UNIT_NONE) {
1187 OOEnergyUnitType eType = [dict oo_intForKey:@"energy_unit" defaultValue:ENERGY_UNIT_NORMAL];
1188 switch (eType) {
1189 // look for NEU first!
1191 [equipment oo_setInteger:1 forKey:@"EQ_NAVAL_ENERGY_UNIT"];
1192 break;
1193
1195 [equipment oo_setInteger:1 forKey:@"EQ_ENERGY_UNIT"];
1196 break;
1197
1198 default:
1199 break;
1200 }
1201 }
1202
1203 custom_chart_zoom = 1.0;
1205
1206 /* Energy bombs are no longer supported without OXPs. As compensation,
1207 we'll award either a Q-mine or some cash. We can't determine what to
1208 award until we've handled missiles later on, though.
1209 */
1210 BOOL energyBombCompensation = NO;
1211 if ([equipment oo_boolForKey:@"EQ_ENERGY_BOMB"] && [OOEquipmentType equipmentTypeWithIdentifier:@"EQ_ENERGY_BOMB"] == nil) {
1212 energyBombCompensation = YES;
1213 [equipment removeObjectForKey:@"EQ_ENERGY_BOMB"];
1214 }
1215
1216 eqScripts = [[NSMutableArray alloc] init];
1217 [self addEquipmentFromCollection:equipment];
1218 primedEquipment = [self eqScriptIndexForKey:[dict oo_stringForKey:@"primed_equipment"]]; // if key not found primedEquipment is set to primed-none
1219
1220 [self setFastEquipmentA:[dict oo_stringForKey:@"primed_equipment_a" defaultValue:@"EQ_CLOAKING_DEVICE"]];
1221 [self setFastEquipmentB:[dict oo_stringForKey:@"primed_equipment_b" defaultValue:@"EQ_ENERGY_BOMB"]]; // even though there isn't one, for compatibility.
1222
1223 if ([self hasEquipmentItemProviding:@"EQ_ADVANCED_COMPASS"])
1224 compassMode = COMPASS_MODE_PLANET;
1225 else
1226 compassMode = COMPASS_MODE_BASIC;
1228
1229 // speech
1230 isSpeechOn = [dict oo_intForKey:@"speech_on"];
1231#if OOLITE_ESPEAK
1232 voice_gender_m = [dict oo_boolForKey:@"speech_gender" defaultValue:YES];
1233 voice_no = [UNIVERSE setVoice:[UNIVERSE voiceNumber:[dict oo_stringForKey:@"speech_voice" defaultValue:nil]] withGenderM:voice_gender_m];
1234#endif
1235
1236 // reputation
1237 [reputation release];
1238 reputation = [[dict oo_dictionaryForKey:@"reputation"] mutableCopy];
1239 if (reputation == nil)
1240 reputation = [[NSMutableDictionary alloc] init];
1241 [self normaliseReputation];
1242
1243 // passengers and contracts
1244 [parcels release];
1245 [parcel_record release];
1246 [passengers release];
1247 [passenger_record release];
1248 [contracts release];
1249 [contract_record release];
1250
1251 max_passengers = [dict oo_intForKey:@"max_passengers" defaultValue:0];
1252 passengers = [[dict oo_arrayForKey:@"passengers"] mutableCopy];
1253 passenger_record = [[dict oo_dictionaryForKey:@"passenger_record"] mutableCopy];
1254 /* Note: contracts from older savegames will have ints in the commodity.
1255 * Need to fix this up */
1256 contracts = [[dict oo_arrayForKey:@"contracts"] mutableCopy];
1257 NSMutableDictionary* contractInfo = nil;
1258
1259 // iterate downwards; lets us remove invalid ones as we go
1260 for (NSInteger i = (NSInteger)[contracts count] - 1; i >= 0; i--) {
1261 contractInfo = [[[contracts oo_dictionaryAtIndex:i] mutableCopy] autorelease];
1262 // if the trade good ID is an int
1263 if ([[contractInfo objectForKey:CARGO_KEY_TYPE] isKindOfClass:[NSNumber class]]) {
1264 // look it up, and replace with a string
1265 NSUInteger legacy_type = [contractInfo oo_unsignedIntegerForKey:CARGO_KEY_TYPE];
1266 [contractInfo setObject:[OOCommodities legacyCommodityType:legacy_type] forKey:CARGO_KEY_TYPE];
1267 [contracts replaceObjectAtIndex:i withObject:[[contractInfo copy] autorelease]];
1268 } else {
1269 OOCommodityType new_type = [contractInfo oo_stringForKey:CARGO_KEY_TYPE];
1270 // check that that the type still exists
1271 if (![[UNIVERSE commodities] goodDefined:new_type]) {
1272 OOLog(@"setCommanderDataFromDictionary.warning.contract", @"Cargo contract to deliver %@ could not be loaded from the saved game, as the commodity is no longer defined", new_type);
1273 [contracts removeObjectAtIndex:i];
1274 }
1275 }
1276 }
1277
1278 contract_record = [[dict oo_dictionaryForKey:@"contract_record"] mutableCopy];
1279 parcels = [[dict oo_arrayForKey:@"parcels"] mutableCopy];
1280 parcel_record = [[dict oo_dictionaryForKey:@"parcel_record"] mutableCopy];
1281
1282 if (passengers == nil)
1283 passengers = [[NSMutableArray alloc] init];
1284 if (passenger_record == nil)
1285 passenger_record = [[NSMutableDictionary alloc] init];
1286 if (contracts == nil)
1287 contracts = [[NSMutableArray alloc] init];
1288 if (contract_record == nil)
1289 contract_record = [[NSMutableDictionary alloc] init];
1290 if (parcels == nil)
1291 parcels = [[NSMutableArray alloc] init];
1292 if (parcel_record == nil)
1293 parcel_record = [[NSMutableDictionary alloc] init];
1294
1295 // specialCargo
1296 [specialCargo release];
1297 specialCargo = [[dict oo_stringForKey:@"special_cargo"] copy];
1298
1299 // mission destinations
1300 NSArray* legacyDestinations = [dict oo_arrayForKey:@"missionDestinations"];
1301
1302 NSDictionary* newDestinations = [dict oo_dictionaryForKey:@"mission_destinations"];
1303 [self initialiseMissionDestinations:newDestinations andLegacy:legacyDestinations];
1304
1305 // shipyard
1307 shipyard_record = [[dict oo_dictionaryForKey:@"shipyard_record"] mutableCopy];
1308 if (shipyard_record == nil)
1309 shipyard_record = [[NSMutableDictionary alloc] init];
1310
1311 // Normalize cargo capacity
1312 unsigned original_hold_size = [UNIVERSE maxCargoForShip:[self shipDataKey]];
1313 // Not Suitable For Oolite
1314 // unsigned passenger_space = [[OOEquipmentType equipmentTypeWithIdentifier:@"EQ_PASSENGER_BERTH"] requiredCargoSpace];
1315 // if (passenger_space == 0) passenger_space = PASSENGER_BERTH_SPACE;
1316
1317 max_cargo = [dict oo_unsignedIntForKey:@"max_cargo" defaultValue:max_cargo];
1318 if (max_cargo > original_hold_size)
1319 [self addEquipmentItem:@"EQ_CARGO_BAY" inContext:@"loading"];
1320 max_cargo = original_hold_size + ([self hasExpandedCargoBay] ? extra_cargo : 0);
1322 // Something went wrong. Possibly the save file was hacked to contain more passenger cabins than the available cargo space would allow - Nikos 20110731
1323 unsigned originalMaxPassengers = max_passengers;
1325 OOLogWARN(@"setCommanderDataFromDictionary.inconsistency.max_passengers", @"player ship %@ had max_passengers set to a value requiring more cargo space than currently available (%u). Setting max_passengers to maximum possible value (%u).", [self name], originalMaxPassengers, max_passengers);
1326 }
1328
1329 // Do we have extra passengers?
1331 OOLogWARN(@"setCommanderDataFromDictionary.inconsistency.passengers", @"player ship %@ had more passengers (%zu) than passenger berths (%u). Removing extra passengers.", [self name], [passengers count], max_passengers);
1332 for (NSInteger i = (NSInteger)[passengers count] - 1; i >= max_passengers; i--) {
1333 [passenger_record removeObjectForKey:[[passengers oo_dictionaryAtIndex:i] oo_stringForKey:PASSENGER_KEY_NAME]];
1334 [passengers removeObjectAtIndex:i];
1335 }
1336 }
1337
1338 // too much cargo?
1339 NSInteger excessCargo = (NSInteger)[self cargoQuantityOnBoard] - (NSInteger)[self maxAvailableCargoSpace];
1340 if (excessCargo > 0) {
1341 OOLogWARN(@"setCommanderDataFromDictionary.inconsistency.cargo", @"player ship %@ had more cargo (%i) than it can hold (%u). Removing extra cargo.", [self name], [self cargoQuantityOnBoard], [self maxAvailableCargoSpace]);
1342
1343 OOCommodityType type;
1344 OOMassUnit units;
1345 OOCargoQuantity oldAmount, toRemove;
1346
1347 OOCargoQuantity remainingExcess = (OOCargoQuantity)excessCargo;
1348
1349 // manifest always contains entries for all 17 commodities, even if their quantity is 0.
1350 foreach (type, [shipCommodityData goods]) {
1351 units = [shipCommodityData massUnitForGood:type];
1352
1353 oldAmount = [shipCommodityData quantityForGood:type];
1354 BOOL roundedTon = (units != UNITS_TONS) && ((units == UNITS_KILOGRAMS && oldAmount > MAX_KILOGRAMS_IN_SAFE) || (units == UNITS_GRAMS && oldAmount > MAX_GRAMS_IN_SAFE));
1355 if (roundedTon || (units == UNITS_TONS && oldAmount > 0)) {
1356 // let's remove stuff
1357 OOCargoQuantity partAmount = oldAmount;
1358 toRemove = 0;
1359 while (remainingExcess > 0 && partAmount > 0) {
1360 if (EXPECT_NOT(roundedTon && ((units == UNITS_KILOGRAMS && partAmount > MAX_KILOGRAMS_IN_SAFE) || (units == UNITS_GRAMS && partAmount > MAX_GRAMS_IN_SAFE)))) {
1361 toRemove += (units == UNITS_KILOGRAMS) ? (partAmount > (KILOGRAMS_PER_POD + MAX_KILOGRAMS_IN_SAFE) ? KILOGRAMS_PER_POD : partAmount - MAX_KILOGRAMS_IN_SAFE)
1362 : (partAmount > (GRAMS_PER_POD + MAX_GRAMS_IN_SAFE) ? GRAMS_PER_POD : partAmount - MAX_GRAMS_IN_SAFE);
1363 partAmount = oldAmount - toRemove;
1364 remainingExcess--;
1365 } else if (!roundedTon) {
1366 toRemove++;
1367 partAmount--;
1368 remainingExcess--;
1369 } else {
1370 partAmount = 0;
1371 }
1372 }
1374 }
1375 }
1376 }
1377
1378 credits = OODeciCreditsFromObject([dict objectForKey:@"credits"]);
1379
1380 fuel = [dict oo_unsignedIntForKey:@"fuel" defaultValue:fuel];
1381 galaxy_number = [dict oo_intForKey:@"galaxy_number"];
1382 //
1383 NSDictionary* shipyard_info = [[OOShipRegistry sharedRegistry] shipyardInfoForKey:[self shipDataKey]];
1384 OOWeaponFacingSet available_facings = [shipyard_info oo_unsignedIntForKey:KEY_WEAPON_FACINGS defaultValue:[self weaponFacings]];
1385
1386 if (available_facings & WEAPON_FACING_FORWARD)
1387 forward_weapon_type = OOWeaponTypeFromEquipmentIdentifierLegacy([dict oo_stringForKey:@"forward_weapon"]);
1388 else
1390
1391 if (available_facings & WEAPON_FACING_AFT)
1392 aft_weapon_type = OOWeaponTypeFromEquipmentIdentifierLegacy([dict oo_stringForKey:@"aft_weapon"]);
1393 else
1395
1396 if (available_facings & WEAPON_FACING_PORT)
1397 port_weapon_type = OOWeaponTypeFromEquipmentIdentifierLegacy([dict oo_stringForKey:@"port_weapon"]);
1398 else
1400
1401 if (available_facings & WEAPON_FACING_STARBOARD)
1402 starboard_weapon_type = OOWeaponTypeFromEquipmentIdentifierLegacy([dict oo_stringForKey:@"starboard_weapon"]);
1403 else
1405
1406 [self setWeaponDataFromType:forward_weapon_type];
1407
1408 if (hud != nil && [hud nonlinearScanner]) {
1409 [hud setScannerZoom:[dict oo_floatForKey:@"ship_scanner_zoom" defaultValue:1.0]];
1410 }
1411
1412 weapons_online = [dict oo_boolForKey:@"weapons_online" defaultValue:YES];
1413
1414 legalStatus = [dict oo_intForKey:@"legal_status"];
1415 market_rnd = [dict oo_intForKey:@"market_rnd"];
1416 ship_kills = [dict oo_intForKey:@"ship_kills"];
1417
1418 ship_clock = [dict oo_doubleForKey:@"ship_clock" defaultValue:PLAYER_SHIP_CLOCK_START];
1420
1421 escape_pod_rescue_time = [dict oo_doubleForKey:@"escape_pod_rescue_time" defaultValue:0.0];
1422
1423 // role weights
1424 [roleWeights release];
1425 roleWeights = [[dict oo_arrayForKey:@"role_weights"] mutableCopy];
1426 NSUInteger rc = [self maxPlayerRoles];
1427 if (roleWeights == nil) {
1428 roleWeights = [[NSMutableArray alloc] initWithCapacity:rc];
1429 while (rc-- > 0) {
1430 [roleWeights addObject:@"player-unknown"];
1431 }
1432 } else {
1433 if ([roleWeights count] > rc) {
1434 [roleWeights removeObjectsInRange:(NSRange) { rc, [roleWeights count] - rc }];
1435 }
1436 }
1437
1438 roleWeightFlags = [[dict oo_dictionaryForKey:@"role_weight_flags"] mutableCopy];
1439 if (roleWeightFlags == nil) {
1440 roleWeightFlags = [[NSMutableDictionary alloc] init];
1441 }
1442
1443 roleSystemList = [[dict oo_arrayForKey:@"role_system_memory"] mutableCopy];
1444 if (roleSystemList == nil) {
1445 roleSystemList = [[NSMutableArray alloc] initWithCapacity:32];
1446 }
1447
1448 // mission_variables
1449 [mission_variables release];
1450 mission_variables = [[dict oo_dictionaryForKey:@"mission_variables"] mutableCopy];
1451 if (mission_variables == nil)
1452 mission_variables = [[NSMutableDictionary alloc] init];
1453
1454 // persistant UNIVERSE info
1455 NSDictionary* planetInfoOverrides = [dict oo_dictionaryForKey:@"scripted_planetinfo_overrides"];
1456 if (planetInfoOverrides != nil) {
1457 [[UNIVERSE systemManager] importScriptedChanges:planetInfoOverrides];
1458 } else {
1459 // no scripted overrides? What about 1.80-style local overrides?
1460 planetInfoOverrides = [dict oo_dictionaryForKey:@"local_planetinfo_overrides"];
1461 if (planetInfoOverrides != nil) {
1462 [[UNIVERSE systemManager] importLegacyScriptedChanges:planetInfoOverrides];
1463 }
1464 }
1465
1466 // communications log
1467 [commLog release];
1468 commLog = [[NSMutableArray alloc] initWithCapacity:kCommLogTrimThreshold];
1469
1470 NSArray* savedCommLog = [dict oo_arrayForKey:@"comm_log"];
1471 NSUInteger commCount = [savedCommLog count];
1472 for (NSUInteger i = 0; i < commCount; i++) {
1473 [UNIVERSE addCommsMessage:[savedCommLog objectAtIndex:i] forCount:0 andShowComms:NO logOnly:YES];
1474 }
1475
1476 /* entity_personality for scripts and shaders. If undefined, we fall back
1477 to old behaviour of using a random value each time game is loaded (set
1478 up in -setUp). Saving of entity_personality was added in 1.74.
1479 -- Ahruman 2009-09-13
1480 */
1481 entity_personality = [dict oo_unsignedShortForKey:@"entity_personality" defaultValue:entity_personality];
1482
1483 // set up missiles
1484 [self setActiveMissile:0];
1485 for (NSUInteger i = 0; i < PLAYER_MAX_MISSILES; i++) {
1486 [missile_entity[i] release];
1487 missile_entity[i] = nil;
1488 }
1489 NSArray* missileRoles = [dict oo_arrayForKey:@"missile_roles"];
1490 if (missileRoles != nil) {
1491 unsigned missileCount = 0;
1492 for (NSUInteger roleIndex = 0; roleIndex < [missileRoles count] && missileCount < max_missiles; roleIndex++) {
1493 NSString* missile_desc = [missileRoles oo_stringAtIndex:roleIndex];
1494 if (missile_desc != nil && ![missile_desc isEqualToString:@"NONE"]) {
1495 ShipEntity* amiss = [UNIVERSE newShipWithRole:missile_desc];
1496 if (amiss) {
1497 missile_list[missileCount] = [OOEquipmentType equipmentTypeWithIdentifier:missile_desc];
1498 missile_entity[missileCount] = amiss; // retain count = 1
1499 missileCount++;
1500 } else {
1501 OOLogWARN(@"load.failed.missileNotFound", @"couldn't find missile with role '%@' in [PlayerEntity setCommanderDataFromDictionary:], missile entry discarded.", missile_desc);
1502 }
1503 }
1505 }
1506 } else // no missile_roles
1507 {
1508 for (NSUInteger i = 0; i < missiles; i++) {
1510 missile_entity[i] = [UNIVERSE newShipWithRole:@"EQ_MISSILE"]; // retain count = 1 - should be okay as long as we keep a missile with this role
1511 // in the base package.
1512 }
1513 }
1514
1515 if (energyBombCompensation) {
1516 /*
1517 Compensate energy bomb with either a QC mine or the cost of an
1518 energy bomb (900 credits). This must be done after missiles are
1519 set up.
1520 */
1521 if ([self mountMissileWithRole:@"EQ_QC_MINE"]) {
1522 OOLog(@"load.upgrade.replacedEnergyBomb", @"%@", @"Replaced legacy energy bomb with Quirium cascade mine.");
1523 } else {
1524 credits += 9000;
1525 OOLog(@"load.upgrade.replacedEnergyBomb", @"%@", @"Compensated legacy energy bomb with 900 credits.");
1526 }
1527 }
1528
1529 [self setActiveMissile:0];
1530
1531 [self setHeatInsulation:1.0];
1532
1535
1538
1541
1542 // used to get current_system and target_system here,
1543 // but stores the ID in the save file instead
1544
1545 // restore subentities status
1546 [self deserializeShipSubEntitiesFrom:[dict oo_stringForKey:@"subentities_status"]];
1547
1548 // wormholes
1549 NSArray* whArray;
1550 whArray = [dict objectForKey:@"wormholes"];
1551 NSDictionary* whCurrDict;
1552 [scannedWormholes release];
1553 scannedWormholes = [[NSMutableArray alloc] initWithCapacity:[whArray count]];
1554 foreach (whCurrDict, whArray) {
1555 WormholeEntity* wh = [[WormholeEntity alloc] initWithDict:whCurrDict];
1556 [scannedWormholes addObject:wh];
1557 /* TODO - add to Universe if the wormhole hasn't expired yet; but in this case
1558 * we need to save/load position and mass as well, which we currently
1559 * don't
1560 if (equal_seeds([wh origin], system_seed))
1561 {
1562 [UNIVERSE addEntity:wh];
1563 }
1564 */
1565 }
1566
1567 // custom view no.
1568 if (_customViews != nil)
1569 _customViewIndex = [dict oo_unsignedIntForKey:@"custom_view_index"] % [_customViews count];
1570
1571 // docking clearance protocol
1572 [UNIVERSE setDockingClearanceProtocolActive:[dict oo_boolForKey:@"docking_clearance_protocol" defaultValue:NO]];
1573
1574 // trumble information
1575 [self setUpTrumbles];
1576 [self setTrumbleValueFrom:[dict objectForKey:@"trumbles"]]; // if it doesn't exist we'll check user-defaults
1577
1578 return YES;
1579}
1580
1582
1583/* Nasty initialization mechanism:
1584 PlayerEntity is alloced and inited on demand by +sharedPlayer. This
1585 initialization doesn't actually set anything up -- apart from the
1586 assertion, it's like doing a bare alloc. -deferredInit does the work
1587 that -init "should" be doing. It assumes that -[ShipEntity initWithKey:
1588 definition:] will not return an object other than self.
1589 This is necessary because we need a pointer to the PlayerEntity early in
1590 startup, when ship data hasn't been loaded yet. In particular, we need
1591 a pointer to the player to set up the JavaScript environment, we need the
1592 JavaScript environment to set up OpenGL, and we need OpenGL set up to load
1593 ships.
1594*/
1595- (id)init
1596{
1597 NSAssert(gOOPlayer == nil, @"Expected only one PlayerEntity to exist at a time.");
1598 return [super initBypassForPlayer];
1599}
1600
1602{
1603 NSAssert(gOOPlayer == self, @"Expected only one PlayerEntity to exist at a time.");
1604 NSAssert([super initWithKey:PLAYER_SHIP_DESC definition:[NSDictionary dictionary]] == self, @"PlayerEntity requires -[ShipEntity initWithKey:definition:] to return unmodified self.");
1605
1607#if OO_FOV_INFLIGHT_CONTROL_ENABLED
1608 fov_delta = 2.0; // multiply by 2 each second
1609#endif
1610
1611 compassMode = COMPASS_MODE_BASIC;
1612
1614
1615 isPlayer = YES;
1616
1617 [self setStatus:STATUS_START_GAME];
1618
1619 int i;
1620 for (i = 0; i < PLAYER_MAX_MISSILES; i++) {
1621 missile_entity[i] = nil;
1622 }
1623 [self setUpAndConfirmOK:NO];
1624
1625 save_path = nil;
1626
1627 scoopsActive = NO;
1628
1630
1632 dockingReport = [[NSMutableString alloc] init];
1633 [hud resetGuis:[NSDictionary dictionaryWithObjectsAndKeys:[NSDictionary dictionary], @"message_gui",
1634 [NSDictionary dictionary], @"comm_log_gui", nil]];
1635
1636 [self initControls];
1637}
1638
1639- (BOOL)setUpAndConfirmOK:(BOOL)stopOnError
1640{
1641 return [self setUpAndConfirmOK:stopOnError saveGame:NO];
1642}
1643
1644- (BOOL)setUpAndConfirmOK:(BOOL)stopOnError saveGame:(BOOL)saveGame
1645{
1646 fieldOfView = [[UNIVERSE gameView] fov:YES];
1647 unsigned i;
1648
1649 showDemoShips = NO;
1650 show_info_flag = NO;
1652
1653 // Reset JavaScript.
1656
1657 GameController* gc = [[UNIVERSE gameView] gameController];
1658
1659 if (![gc inFullScreenMode] && stopOnError)
1660 [gc stopAnimationTimer]; // start of critical section
1661
1662 if (EXPECT_NOT(![[OOJavaScriptEngine sharedEngine] reset] && stopOnError)) // always (try to) reset the engine, then find out if we need to stop.
1663 {
1664 /*
1665 Occasionally there's a racing condition between timers being deleted
1666 and the js engine needing to be reset: the engine reset stops the timers
1667 from being deleted, and undeleted timers don't allow the engine to reset
1668 itself properly.
1669
1670 If the engine can't reset, let's give ourselves an extra 20ms to allow the
1671 timers to delete themselves.
1672
1673 We'll piggyback performDeadUpdates: when STATUS_DEAD, the engine waits until
1674 kDeadResetTime then restarts Oolite via [UNIVERSE updateGameOver]
1675 The variable shot_time is used to keep track of how long ago we were
1676 shot.
1677
1678 If we're loading a savegame the code will try a new JS reset immediately
1679 after failing this reset...
1680 */
1681
1682 // set up STATUS_DEAD
1683 [self setDockedStation:nil]; // needed for STATUS_DEAD
1684 [self setStatus:STATUS_DEAD];
1685 OOLog(@"script.javascript.init.error", @"%@", @"Scheduling new JavaScript reset.");
1686 shot_time = kDeadResetTime - 0.02f; // schedule reinit 20 milliseconds from now.
1687
1688 if (![gc inFullScreenMode])
1689 [gc startAnimationTimer]; // keep the game ticking over.
1690 return NO;
1691 }
1692
1693 // end of critical section
1694 if (![gc inFullScreenMode] && stopOnError)
1696
1697 // Load locale script before any regular scripts.
1698 [OOJSScript jsScriptFromFileNamed:@"oolite-locale-functions.js"
1699 properties:nil];
1700
1701 [[GameController sharedController] logProgress:DESC(@"loading-scripts")];
1702
1703 [UNIVERSE setBlockJSPlayerShipProps:NO]; // full access to player.ship properties!
1707
1708#if OOLITE_WINDOWS
1709 if (saveGame) {
1710 [UNIVERSE preloadSounds];
1711 [self setUpSound];
1713 [UNIVERSE loadConditionScripts];
1714 commodityScripts = [[NSMutableDictionary alloc] init];
1715 }
1716#else
1717 /* on OSes that allow safe deletion of open files, can use sounds
1718 * on the OXZ screen and other start screens */
1719 [UNIVERSE preloadSounds];
1720 [self setUpSound];
1721 if (saveGame) {
1723 [UNIVERSE loadConditionScripts];
1724 commodityScripts = [[NSMutableDictionary alloc] init];
1725 }
1726#endif
1727
1728 // make sure extraGuiScreenKeys is clear
1730
1731 [[GameController sharedController] logProgress:OOExpandKeyRandomized(@"loading-miscellany")];
1732
1733 // if there is cargo remaining from previously (e.g. a game restart), remove it
1734 if ([self cargoList] != nil) {
1735 [self removeAllCargo:YES]; // force removal of cargo
1736 }
1737
1738 [self setShipDataKey:PLAYER_SHIP_DESC];
1740
1741 // reset HUD & default commlog behaviour
1742 [UNIVERSE setAutoCommLog:YES];
1743 [UNIVERSE setPermanentCommLog:NO];
1744
1745 [multiFunctionDisplayText release];
1747
1748 [multiFunctionDisplaySettings release];
1750
1751 [customDialSettings release];
1752 customDialSettings = [[NSMutableDictionary alloc] init];
1753
1754 [self switchHudTo:@"hud.plist"];
1755 scanner_zoom_rate = 0.0f;
1756 longRangeChartMode = OOLRC_MODE_SUNCOLOR;
1757
1758 [mission_variables release];
1759 mission_variables = [[NSMutableDictionary alloc] init];
1760
1761 [localVariables release];
1762 localVariables = [[NSMutableDictionary alloc] init];
1763
1764 [self setScriptTarget:nil];
1765 [self resetMissionChoice];
1766 [[UNIVERSE gameView] resetTypedString];
1767 found_system_id = -1;
1768
1769 [reputation release];
1770 reputation = [[NSMutableDictionary alloc] initWithCapacity:6];
1771 [reputation oo_setInteger:0 forKey:CONTRACTS_GOOD_KEY];
1772 [reputation oo_setInteger:0 forKey:CONTRACTS_BAD_KEY];
1773 [reputation oo_setInteger:MAX_CONTRACT_REP forKey:CONTRACTS_UNKNOWN_KEY];
1774 [reputation oo_setInteger:0 forKey:PASSAGE_GOOD_KEY];
1775 [reputation oo_setInteger:0 forKey:PASSAGE_BAD_KEY];
1776 [reputation oo_setInteger:MAX_CONTRACT_REP forKey:PASSAGE_UNKNOWN_KEY];
1777 [reputation oo_setInteger:0 forKey:PARCEL_GOOD_KEY];
1778 [reputation oo_setInteger:0 forKey:PARCEL_BAD_KEY];
1779 [reputation oo_setInteger:MAX_CONTRACT_REP forKey:PARCEL_UNKNOWN_KEY];
1780
1782 roleWeights = [[NSMutableArray alloc] initWithCapacity:8];
1783 for (i = 0; i < 8; i++) {
1784 [roleWeights addObject:@"player-unknown"];
1785 }
1787 roleWeightFlags = [[NSMutableDictionary alloc] init];
1788
1790 roleSystemList = [[NSMutableArray alloc] initWithCapacity:32];
1791
1792 energy = 256;
1793 weapon_temp = 0.0f;
1794 forward_weapon_temp = 0.0f;
1795 aft_weapon_temp = 0.0f;
1796 port_weapon_temp = 0.0f;
1797 starboard_weapon_temp = 0.0f;
1798 lastShot = nil;
1803 ship_temperature = 60.0f;
1804 alertFlags = 0;
1805 hyperspeed_engaged = NO;
1806 autopilot_engaged = NO;
1808
1809 flightRoll = 0.0f;
1810 flightPitch = 0.0f;
1811 flightYaw = 0.0f;
1812
1813 max_passengers = 0;
1814 [passengers release];
1815 passengers = [[NSMutableArray alloc] init];
1816 [passenger_record release];
1817 passenger_record = [[NSMutableDictionary alloc] init];
1818
1819 [contracts release];
1820 contracts = [[NSMutableArray alloc] init];
1821 [contract_record release];
1822 contract_record = [[NSMutableDictionary alloc] init];
1823
1824 [parcels release];
1825 parcels = [[NSMutableArray alloc] init];
1826 [parcel_record release];
1827 parcel_record = [[NSMutableDictionary alloc] init];
1828
1829 [missionDestinations release];
1831
1832 [shipyard_record release];
1833 shipyard_record = [[NSMutableDictionary alloc] init];
1834
1835 [target_memory release];
1836 target_memory = [[NSMutableArray alloc] initWithCapacity:PLAYER_TARGET_MEMORY_SIZE];
1837 [self clearTargetMemory]; // also does first-time initialisation
1838
1839 [self setMissionOverlayDescriptor:nil];
1841 [self setMissionBackgroundSpecial:nil];
1843 marketOffset = 0;
1845
1846 script_time = 0.0;
1849
1850 NSCalendarDate* nowDate = [NSCalendarDate calendarDate];
1852 ship_clock += [nowDate hourOfDay] * 3600.0;
1853 ship_clock += [nowDate minuteOfHour] * 60.0;
1854 ship_clock += [nowDate secondOfMinute];
1856 ship_clock_adjust = 0.0;
1858
1860#if OOLITE_ESPEAK
1861 voice_gender_m = YES;
1862 voice_no = [UNIVERSE setVoice:-1 withGenderM:voice_gender_m];
1863#endif
1864
1865 [_customViews release];
1866 _customViews = nil;
1867 _customViewIndex = 0;
1868
1869 mouse_control_on = NO;
1870
1871 // player commander data
1872 // Most of this is probably also set more than once
1873
1874 [self setCommanderName:PLAYER_DEFAULT_NAME];
1875 NSString* savedName = [[NSUserDefaults standardUserDefaults] stringForKey:@"last_savename"];
1876 if (savedName != nil) {
1877 [_lastsaveName autorelease];
1878 _lastsaveName = [savedName copy];
1879 }
1880
1881 galaxy_coordinates = NSMakePoint(0x14, 0xAD); // 20,173
1882
1883 credits = 1000;
1885 fuel_accumulator = 0.0f;
1886 fuel_leak_rate = 0.0f;
1887
1888 galaxy_number = 0;
1889 // will load real weapon data later
1895
1896 weapons_online = YES;
1897
1898 ecm_in_operation = NO;
1899 last_ecm_time = [UNIVERSE getTime];
1900 compassMode = COMPASS_MODE_BASIC;
1901 ident_engaged = NO;
1902
1903 max_cargo = 20; // will be reset later
1905
1907 shipCommodityData = [[[UNIVERSE commodities] generateManifestForPlayer] retain];
1908
1909 // set up missiles
1912
1913 [eqScripts release];
1914 eqScripts = [[NSMutableArray alloc] init];
1915 primedEquipment = 0;
1916 [self setFastEquipmentA:@"EQ_CLOAKING_DEVICE"];
1917 [self setFastEquipmentB:@"EQ_ENERGY_BOMB"]; // for compatibility purposes
1918
1919 [self setActiveMissile:0];
1920 for (i = 0; i < missiles; i++) {
1921 [missile_entity[i] release];
1922 missile_entity[i] = nil;
1923 }
1924 [self safeAllMissiles];
1925
1926 [self clearSubEntities];
1927
1928 legalStatus = 0;
1929
1930 market_rnd = 0;
1931 ship_kills = 0;
1937 chart_zoom = 1.0;
1938 target_chart_zoom = 1.0;
1939 saved_chart_zoom = 1.0;
1941
1942 scripted_misjump = NO;
1944 scoopOverride = NO;
1945
1948
1951
1954
1955 scanClass = CLASS_PLAYER;
1956
1957 [UNIVERSE clearGUIs];
1958
1961
1962 [self setDockedStation:[UNIVERSE station]];
1963
1964 [commLog release];
1965 commLog = nil;
1966
1967 [specialCargo release];
1968 specialCargo = nil;
1969
1970 // views
1976
1978 [self currentWeaponStats];
1979
1980 [save_path autorelease];
1981 save_path = nil;
1982
1983 [scannedWormholes release];
1984 scannedWormholes = [[NSMutableArray alloc] init];
1985
1986 [self setUpTrumbles];
1987
1988 suppressTargetLost = NO;
1989
1990 scoopsActive = NO;
1991
1992 [dockingReport release];
1993 dockingReport = [[NSMutableString alloc] init];
1994
1995 [shipAI release];
1996 shipAI = [[AI alloc] initWithStateMachine:PLAYER_DOCKING_AI_NAME andState:@"GLOBAL"];
1997 [self resetAutopilotAI];
1998
2000
2001 entity_personality = ranrot_rand() & 0x7FFF;
2002
2003 [self setSystemID:[UNIVERSE findSystemNumberAtCoords:[self galaxy_coordinates] withGalaxy:galaxy_number includingHidden:YES]];
2004 [UNIVERSE setGalaxyTo:galaxy_number];
2005 [UNIVERSE setSystemTo:system_id];
2006
2007 [self setUpWeaponSounds];
2008
2009 [self setGalacticHyperspaceBehaviourTo:[[UNIVERSE globalSettings] oo_stringForKey:@"galactic_hyperspace_behaviour" defaultValue:@"BEHAVIOUR_STANDARD"]];
2010 [self setGalacticHyperspaceFixedCoordsTo:[[UNIVERSE globalSettings] oo_stringForKey:@"galactic_hyperspace_fixed_coords" defaultValue:@"96 96"]];
2011
2013
2014 demoShip = nil;
2015
2017 [stickProfileScreen release];
2018 stickProfileScreen = [[StickProfileScreen alloc] init];
2019 return YES;
2020}
2021
2023{
2024 [self completeSetUpAndSetTarget:YES];
2025}
2026
2027- (void)completeSetUpAndSetTarget:(BOOL)setTarget
2028{
2030
2031 [self setDockedStation:[UNIVERSE station]];
2032 [self setLastAegisLock:[UNIVERSE planet]];
2033 // only do this if we're not in strict mode, otherwise all previously saved OXP key/joystick defs will be wiped.
2034 if (![[UNIVERSE useAddOns] isEqualToString:SCENARIO_OXP_DEFINITION_NONE]) {
2036 }
2037
2038 JSContext* context = OOJSAcquireContext();
2039 [self doWorldScriptEvent:OOJSID("startUp") inContext:context withArguments:NULL count:0 timeLimit:MAX(0.0, [[NSUserDefaults standardUserDefaults] oo_floatForKey:@"start-script-limit-value" defaultValue:kOOJSLongTimeLimit])];
2040 OOJSRelinquishContext(context);
2041}
2042
2044{
2045 JSContext* context = OOJSAcquireContext();
2046 [self doWorldScriptEvent:OOJSID("startUpComplete") inContext:context withArguments:NULL count:0 timeLimit:kOOJSLongTimeLimit];
2047 OOJSRelinquishContext(context);
2048}
2049
2050- (BOOL)setUpShipFromDictionary:(NSDictionary*)shipDict
2051{
2053 [UNIVERSE setBlockJSPlayerShipProps:NO]; // full access to player.ship properties!
2054
2055 if (![super setUpFromDictionary:shipDict])
2056 return NO;
2057
2058 DESTROY(cargo);
2059 cargo = [[NSMutableArray alloc] initWithCapacity:max_cargo];
2060
2061 // Player-only settings.
2062 //
2063 // set control factors..
2064 roll_delta = 2.0f * max_flight_roll;
2066 yaw_delta = 2.0f * max_flight_yaw;
2067
2068 energy = maxEnergy;
2069 // if (forward_weapon_type == WEAPON_NONE) [self setWeaponDataFromType:forward_weapon_type];
2071
2072 [roleSet release];
2073 roleSet = nil;
2074 [self setPrimaryRole:@"player"];
2075
2076 [self removeAllEquipment];
2077 [self addEquipmentFromCollection:[shipDict objectForKey:@"extra_equipment"]];
2078
2079 [self resetHud];
2080 [hud setHidden:NO];
2081
2082 // set up missiles
2083 // sanity check the number of missiles...
2086 if (missiles > max_missiles)
2088 // end sanity check
2089
2090 unsigned i;
2091 for (i = 0; i < PLAYER_MAX_MISSILES; i++) {
2092 [missile_entity[i] release];
2093 missile_entity[i] = nil;
2094 }
2095 for (i = 0; i < missiles; i++) {
2097 missile_entity[i] = [UNIVERSE newShipWithRole:@"EQ_MISSILE"]; // retain count = 1
2098 }
2099
2101 [self safeAllMissiles];
2102 [self setActiveMissile:0];
2103
2104 // set view offsets
2105 [self setDefaultViewOffsets];
2106
2107 if (EXPECT(_scaleFactor == 1.0f)) {
2108 forwardViewOffset = [shipDict oo_vectorForKey:@"view_position_forward" defaultValue:forwardViewOffset];
2109 aftViewOffset = [shipDict oo_vectorForKey:@"view_position_aft" defaultValue:aftViewOffset];
2110 portViewOffset = [shipDict oo_vectorForKey:@"view_position_port" defaultValue:portViewOffset];
2111 starboardViewOffset = [shipDict oo_vectorForKey:@"view_position_starboard" defaultValue:starboardViewOffset];
2112 } else {
2113 forwardViewOffset = vector_multiply_scalar([shipDict oo_vectorForKey:@"view_position_forward" defaultValue:forwardViewOffset], _scaleFactor);
2114 aftViewOffset = vector_multiply_scalar([shipDict oo_vectorForKey:@"view_position_aft" defaultValue:aftViewOffset], _scaleFactor);
2115 portViewOffset = vector_multiply_scalar([shipDict oo_vectorForKey:@"view_position_port" defaultValue:portViewOffset], _scaleFactor);
2116 starboardViewOffset = vector_multiply_scalar([shipDict oo_vectorForKey:@"view_position_starboard" defaultValue:starboardViewOffset], _scaleFactor);
2117 }
2118
2119 [self setDefaultCustomViews];
2120
2121 NSArray* customViews = [shipDict oo_arrayForKey:@"custom_views"];
2122 if (customViews != nil) {
2123 [_customViews release];
2124 _customViews = [customViews retain];
2125 _customViewIndex = 0;
2126 }
2127
2128 massLockable = [shipDict oo_boolForKey:@"mass_lockable" defaultValue:YES];
2129
2130 // Load js script
2131 [script autorelease];
2132 NSDictionary* scriptProperties = [NSDictionary dictionaryWithObject:self forKey:@"ship"];
2133 script = [OOScript jsScriptFromFileNamed:[shipDict oo_stringForKey:@"script"]
2134 properties:scriptProperties];
2135 if (script == nil) {
2136 // Do not switch to using a default value above; we want to use the default script if loading fails.
2137 script = [OOScript jsScriptFromFileNamed:@"oolite-default-player-script.js"
2138 properties:scriptProperties];
2139 }
2140 [script retain];
2141
2142 return YES;
2143}
2144
2145- (void)dealloc
2146{
2148 DESTROY(hud);
2152
2156
2159
2165
2167
2169
2183
2187
2191
2193
2196
2199
2201
2203
2204 [self destroySound];
2205
2208
2209 int i;
2210 for (i = 0; i < PLAYER_MAX_MISSILES; i++)
2212 for (i = 0; i < PLAYER_MAX_TRUMBLES; i++)
2213 DESTROY(trumble[i]);
2214
2221
2225
2227
2228 [super dealloc];
2229}
2230
2231- (NSUInteger)sessionID
2232{
2233 // The player ship always belongs to the current session.
2234 return [UNIVERSE sessionID];
2235}
2236
2238{
2239 [self playHostileWarning];
2240}
2241
2243{
2244 switch ([self status]) {
2245 case STATUS_START_GAME:
2246 case STATUS_DOCKING:
2247 case STATUS_DOCKED:
2248 case STATUS_DEAD:
2249 case STATUS_ESCAPE_SEQUENCE:
2250 return NO;
2251
2252 default:
2253 return YES;
2254 }
2255}
2256
2257- (NSComparisonResult)compareZeroDistance:(Entity*)otherEntity
2258{
2259 return NSOrderedDescending; // always the most near
2260}
2261
2263{
2264 return YES;
2265}
2266
2267- (GLfloat)lookingAtSunWithThresholdAngleCos:(GLfloat)thresholdAngleCos
2268{
2269 OOSunEntity* sun = [UNIVERSE sun];
2270 GLfloat measuredCos = 999.0f, measuredCosAbs;
2271 GLfloat sunBrightness = 0.0f;
2272 Vector relativePosition, unitRelativePosition;
2273
2274 if (EXPECT_NOT(!sun))
2275 return 0.0f;
2276
2277 // check if camera position is shadowed
2278 OOViewID vdir = [UNIVERSE viewDirection];
2279 unsigned i;
2280 unsigned ent_count = UNIVERSE->n_entities;
2281 Entity** uni_entities = UNIVERSE->sortedEntities; // grab the public sorted list
2282 for (i = 0; i < ent_count; i++) {
2283 if (uni_entities[i]->isSunlit) {
2284 if ([uni_entities[i] isPlanet] || ([uni_entities[i] isShip] && [uni_entities[i] isVisible])) {
2285 // the player ship can't shadow internal views
2286 if (EXPECT(vdir > VIEW_STARBOARD || ![uni_entities[i] isPlayer])) {
2287 float shadow = 1.5f;
2288 shadowAtPointOcclusionToValue([self viewpointPosition], 1.0f, uni_entities[i], sun, &shadow);
2289 /* BUG: if the shadowing entity is not spherical, this gives over-shadowing. True elsewhere as well, but not so obvious there. */
2290 if (shadow < 1) {
2291 return 0.0f;
2292 }
2293 }
2294 }
2295 }
2296 }
2297
2299 unitRelativePosition = vector_normal_or_zbasis(relativePosition);
2300 switch (vdir) {
2301 case VIEW_FORWARD:
2302 measuredCos = -dot_product(unitRelativePosition, v_forward);
2303 break;
2304 case VIEW_AFT:
2305 measuredCos = +dot_product(unitRelativePosition, v_forward);
2306 break;
2307 case VIEW_PORT:
2308 measuredCos = +dot_product(unitRelativePosition, v_right);
2309 break;
2310 case VIEW_STARBOARD:
2311 measuredCos = -dot_product(unitRelativePosition, v_right);
2312 break;
2313 case VIEW_CUSTOM: {
2314 Vector relativeView = [self customViewForwardVector];
2315 Vector absoluteView = quaternion_rotate_vector(quaternion_conjugate([self orientation]), relativeView);
2316 measuredCos = -dot_product(unitRelativePosition, absoluteView);
2317 } break;
2318
2319 default:
2320 break;
2321 }
2322 measuredCosAbs = fabs(measuredCos);
2323 /*
2324 Bugfix: 1.1f - floating point errors can mean the dot product of two
2325 normalised vectors can be very slightly more than 1, which can
2326 cause extreme flickering of the glare at certain ranges to the
2327 sun. The real test is just that it's not still 999 - CIM
2328 */
2329 if (thresholdAngleCos <= measuredCosAbs && measuredCosAbs <= 1.1f) // angle from viewpoint to sun <= desired threshold
2330 {
2331 sunBrightness = (measuredCos - thresholdAngleCos) / (1.0f - thresholdAngleCos);
2332 // OOLog(@"glare.debug",@"raw brightness = %f",sunBrightness);
2333 if (sunBrightness < 0.0f)
2334 sunBrightness = 0.0f;
2335 else if (sunBrightness > 1.0f)
2336 sunBrightness = 1.0f;
2337 }
2338 // OOLog(@"glare.debug",@"cos=%f, threshold = %f, brightness = %f",measuredCosAbs,thresholdAngleCos,sunBrightness);
2339 return sunBrightness * sunBrightness * sunBrightness;
2340}
2341
2343{
2344 GLfloat insideAtmoFrac = 0.0f;
2345
2346 if ([UNIVERSE airResistanceFactor] > 0.01) // player is inside planetary atmosphere
2347 {
2348 insideAtmoFrac = 1.0f - ([self dialAltitude] * (GLfloat)PLAYER_DIAL_MAX_ALTITUDE / (10.0f * (GLfloat)ATMOSPHERE_DEPTH));
2349 }
2350
2351 return insideAtmoFrac;
2352}
2353
2354#ifndef NDEBUG
2355#define STAGE_TRACKING_BEGIN \
2356 { \
2357 NSString* volatile updateStage = @"initialisation"; \
2358 @try {
2359#define STAGE_TRACKING_END \
2360 } \
2361 @catch (NSException * exception) \
2362 { \
2363 OOLog(kOOLogException, @"***** Exception during [%@] in %s : %@ : %@ *****", updateStage, __PRETTY_FUNCTION__, [exception name], [exception reason]); \
2364 @throw exception; \
2365 } \
2366 }
2367#define UPDATE_STAGE(x) \
2368 do { \
2369 updateStage = (x); \
2370 } while (0)
2371#else
2372#define STAGE_TRACKING_BEGIN {
2373#define STAGE_TRACKING_END }
2374#define UPDATE_STAGE(x) \
2375 do { \
2376 (void)(x); \
2377 } while (0);
2378#endif
2379
2380- (void)update:(OOTimeDelta)delta_t
2381{
2383
2384 UPDATE_STAGE(@"updateMovementFlags");
2385 [self updateMovementFlags];
2386 UPDATE_STAGE(@"updateAlertCondition");
2387 [self updateAlertCondition];
2388 UPDATE_STAGE(@"updateFuelScoops:");
2389 [self updateFuelScoops:delta_t];
2390
2391 UPDATE_STAGE(@"updateClocks:");
2392 [self updateClocks:delta_t];
2393
2394 // scripting
2395 UPDATE_STAGE(@"updateTimers");
2397 UPDATE_STAGE(@"checkScriptsIfAppropriate");
2399
2400 // deal with collisions
2401 UPDATE_STAGE(@"manageCollisions");
2402 [self manageCollisions];
2403
2404 UPDATE_STAGE(@"pollControls:");
2405 [self pollControls:delta_t];
2406
2407 UPDATE_STAGE(@"updateTrumbles:");
2408 [self updateTrumbles:delta_t];
2409
2410 OOEntityStatus status = [self status];
2411 /* Validate that if the status is STATUS_START_GAME we're on one
2412 * of the few GUI screens which that makes sense for */
2413 if (EXPECT_NOT(status == STATUS_START_GAME && gui_screen != GUI_SCREEN_INTRO1 && gui_screen != GUI_SCREEN_SHIPLIBRARY && gui_screen != GUI_SCREEN_GAMEOPTIONS && gui_screen != GUI_SCREEN_STICKMAPPER && gui_screen != GUI_SCREEN_STICKPROFILE && gui_screen != GUI_SCREEN_NEWGAME && gui_screen != GUI_SCREEN_OXZMANAGER && gui_screen != GUI_SCREEN_LOAD && gui_screen != GUI_SCREEN_KEYBOARD && gui_screen != GUI_SCREEN_KEYBOARD_CONFIRMCLEAR && gui_screen != GUI_SCREEN_KEYBOARD_CONFIG && gui_screen != GUI_SCREEN_KEYBOARD_ENTRY && gui_screen != GUI_SCREEN_KEYBOARD_LAYOUT)) {
2414 // and if not, do a restart of the GUI
2415 UPDATE_STAGE(@"setGuiToIntroFirstGo:");
2416 [self setGuiToIntroFirstGo:YES]; // set up demo mode
2417 }
2418
2419 if (status == STATUS_AUTOPILOT_ENGAGED || status == STATUS_ESCAPE_SEQUENCE) {
2420 UPDATE_STAGE(@"performAutopilotUpdates:");
2421 [self performAutopilotUpdates:delta_t];
2422 } else if (![self isDocked]) {
2423 UPDATE_STAGE(@"performInFlightUpdates:");
2424 [self performInFlightUpdates:delta_t];
2425 }
2426
2427 /* NOTE: status-contingent updates are not a switch since they can
2428 cascade when status changes.
2429 */
2430 if (status == STATUS_IN_FLIGHT) {
2431 UPDATE_STAGE(@"doBookkeeping:");
2432 [self doBookkeeping:delta_t];
2433 }
2434 if (status == STATUS_WITCHSPACE_COUNTDOWN) {
2435 UPDATE_STAGE(@"performWitchspaceCountdownUpdates:");
2436 [self performWitchspaceCountdownUpdates:delta_t];
2437 }
2438 if (status == STATUS_EXITING_WITCHSPACE) {
2439 UPDATE_STAGE(@"performWitchspaceExitUpdates:");
2440 [self performWitchspaceExitUpdates:delta_t];
2441 }
2442 if (status == STATUS_LAUNCHING) {
2443 UPDATE_STAGE(@"performLaunchingUpdates:");
2444 [self performLaunchingUpdates:delta_t];
2445 }
2446 if (status == STATUS_DOCKING) {
2447 UPDATE_STAGE(@"performDockingUpdates:");
2448 [self performDockingUpdates:delta_t];
2449 }
2450 if (status == STATUS_DEAD) {
2451 UPDATE_STAGE(@"performDeadUpdates:");
2452 [self performDeadUpdates:delta_t];
2453 }
2454
2455 UPDATE_STAGE(@"updateWormholes");
2456 [self updateWormholes];
2457
2459}
2460
2461- (void)doBookkeeping:(double)delta_t
2462{
2464
2465 double speed_delta = SHIP_THRUST_FACTOR * thrust;
2466
2467 static BOOL gettingInterference = NO;
2468
2469 OOSunEntity* sun = [UNIVERSE sun];
2470 double external_temp = 0;
2471 GLfloat air_friction = 0.0f;
2472 air_friction = 0.5f * [UNIVERSE airResistanceFactor];
2473 if (air_friction < 0.005f) // aRF < 0.01
2474 {
2475 // stops mysteriously overheating and exploding in the middle of empty space
2476 air_friction = 0;
2477 }
2478
2479 UPDATE_STAGE(@"updating weapon temperatures and shot times");
2480 // cool all weapons.
2481 float coolAmount = WEAPON_COOLING_FACTOR * delta_t;
2482 forward_weapon_temp = fdim(forward_weapon_temp, coolAmount);
2483 aft_weapon_temp = fdim(aft_weapon_temp, coolAmount);
2484 port_weapon_temp = fdim(port_weapon_temp, coolAmount);
2485 starboard_weapon_temp = fdim(starboard_weapon_temp, coolAmount);
2486
2487 // update shot times.
2488 forward_shot_time += delta_t;
2489 aft_shot_time += delta_t;
2490 port_shot_time += delta_t;
2491 starboard_shot_time += delta_t;
2492
2493 // copy new temp & shot time to main temp & shot time
2494 switch (currentWeaponFacing) {
2498 break;
2499 case WEAPON_FACING_AFT:
2502 break;
2503 case WEAPON_FACING_PORT:
2506 break;
2510 break;
2511
2512 case WEAPON_FACING_NONE:
2513 break;
2514 }
2515
2516 // cloaking device
2518 UPDATE_STAGE(@"updating cloaking device");
2519
2520 energy -= (float)delta_t * CLOAKING_DEVICE_ENERGY_RATE;
2523 }
2524
2525 // military_jammer
2526 if ([self hasMilitaryJammer]) {
2527 UPDATE_STAGE(@"updating military jammer");
2528
2530 energy -= (float)delta_t * MILITARY_JAMMER_ENERGY_RATE;
2533 } else {
2536 }
2537 }
2538
2539 // ecm
2540 if (ecm_in_operation) {
2541 UPDATE_STAGE(@"updating ECM");
2542
2543 if (energy > 0.0)
2544 energy -= (float)(ECM_ENERGY_DRAIN_FACTOR * delta_t); // drain energy because of the ECM
2545 else {
2546 ecm_in_operation = NO;
2547 [UNIVERSE addMessage:DESC(@"ecm-out-of-juice") forCount:3.0];
2548 }
2549 if ([UNIVERSE getTime] > ecm_start_time + ECM_DURATION) {
2550 ecm_in_operation = NO;
2551 }
2552 }
2553
2554 // ecm interference visual effect
2555 if ([UNIVERSE useShaders] && [UNIVERSE ECMVisualFXEnabled]) {
2556 // we want to start and stop the effect exactly once, not start it
2557 // or stop it on every frame
2558 if ([self scannerFuzziness] > 0.0) {
2559 if (!gettingInterference) {
2560 [UNIVERSE setCurrentPostFX:OO_POSTFX_CRTBADSIGNAL];
2561 gettingInterference = YES;
2562 }
2563 } else {
2564 if (gettingInterference) {
2565 [UNIVERSE terminatePostFX:OO_POSTFX_CRTBADSIGNAL];
2566 gettingInterference = NO;
2567 }
2568 }
2569 }
2570
2571 // Energy Banks and Shields
2572
2573 /* Shield-charging behaviour, as per Eric's proposal:
2574 1. If shields are less than a threshold, recharge with all available energy
2575 2. If energy banks are below threshold, recharge with generated energy
2576 3. Charge shields with any surplus energy
2577 */
2578 UPDATE_STAGE(@"updating energy and shield charges");
2579
2580 // 1. (Over)charge energy banks (will get normalised later)
2581 energy += [self energyRechargeRate] * delta_t;
2582
2583 // 2. Calculate shield recharge rates
2584 float fwdMax = [self maxForwardShieldLevel];
2585 float aftMax = [self maxAftShieldLevel];
2586 float shieldRechargeFwd = [self forwardShieldRechargeRate] * delta_t;
2587 float shieldRechargeAft = [self aftShieldRechargeRate] * delta_t;
2588 /* there is potential for negative rechargeFwd and rechargeAFt values here
2589 (e.g. getting shield boosters damaged while shields are full). This may
2590 lead to energy being gained rather than consumed when recharging. Leaving
2591 as-is for now, as there might be OXPs that rely in such behaviour.
2592 Boosters case example mentioned above is the only known core equipment
2593 occurrence at this time and it has been fixed inside the
2594 oolite-equipment-control.js script. - Nikos 20160104.
2595 */
2596 float rechargeFwd = MIN(shieldRechargeFwd, fwdMax - forward_shield);
2597 float rechargeAft = MIN(shieldRechargeAft, aftMax - aft_shield);
2598
2599 // Note: we've simplified this a little, so if either shield is below
2600 // the critical threshold, we allocate all energy. Ideally we
2601 // would only allocate the full recharge to the critical shield,
2602 // but doing so would add another few levels of if-then below.
2603 float energyForShields = energy;
2604 if ((forward_shield > fwdMax * 0.25) && (aft_shield > aftMax * 0.25)) {
2605 // TODO: Can this be cached anywhere sensibly (without adding another member variable)?
2606 float minEnergyBankLevel = [[UNIVERSE globalSettings] oo_floatForKey:@"shield_charge_energybank_threshold" defaultValue:0.25];
2607 energyForShields = MAX(0.0, energy - 0.1 - (maxEnergy * minEnergyBankLevel)); // NB: The - 0.1 ensures the energy value does not 'bounce' across the critical energy message and causes spurious energy-low warnings
2608 }
2609
2610 if (forward_shield < aft_shield) {
2611 rechargeFwd = MIN(rechargeFwd, energyForShields);
2612 rechargeAft = MIN(rechargeAft, energyForShields - rechargeFwd);
2613 } else {
2614 rechargeAft = MIN(rechargeAft, energyForShields);
2615 rechargeFwd = MIN(rechargeFwd, energyForShields - rechargeAft);
2616 }
2617
2618 // 3. Recharge shields, drain banks, and clamp values
2619 forward_shield += rechargeFwd;
2620 aft_shield += rechargeAft;
2621 energy -= rechargeFwd + rechargeAft;
2622
2626
2627 if (sun) {
2628 UPDATE_STAGE(@"updating sun effects");
2629
2630 // set the ambient temperature here
2631 double sun_zd = sun->zero_distance; // square of distance
2632 double sun_cr = sun->collision_radius;
2633 double alt1 = sun_cr * sun_cr / sun_zd;
2634 external_temp = SUN_TEMPERATURE * alt1;
2635
2636 if ([sun goneNova])
2637 external_temp *= 100;
2638 // fuel scooping during the nova mission very unlikely
2639 if ([sun willGoNova])
2640 external_temp *= 3;
2641
2642 // do Revised sun-skimming check here...
2643 if ([self hasFuelScoop] && alt1 > 0.75 && [self fuel] < [self fuelCapacity]) {
2644 fuel_accumulator += (float)(delta_t * flightSpeed * 0.010 / [self fuelChargeRate]);
2645 // are we fast enough to collect any fuel?
2646 scoopsActive = YES && flightSpeed > 0.1f;
2647 while (fuel_accumulator > 1.0f) {
2648 [self setFuel:[self fuel] + 1];
2649 fuel_accumulator -= 1.0f;
2650 [self doScriptEvent:OOJSID("shipScoopedFuel")];
2651 }
2652 [UNIVERSE displayCountdownMessage:DESC(@"fuel-scoop-active") forCount:1.0];
2653 }
2654 }
2655
2656 // Bug #11692 CmdrJames added Status entering witchspace
2657 OOEntityStatus status = [self status];
2658 if ((status != STATUS_ESCAPE_SEQUENCE) && (status != STATUS_ENTERING_WITCHSPACE)) {
2659 UPDATE_STAGE(@"updating cabin temperature");
2660
2661 // work on the cabin temperature
2662 float heatInsulation = [self heatInsulation]; // Optimisation, suggested by EricW
2663 float deltaInsulation = delta_t / heatInsulation;
2664 float heatThreshold = heatInsulation * 100.0f;
2665 ship_temperature += (float)(flightSpeed * air_friction * deltaInsulation); // wind_speed
2666
2667 if (external_temp > heatThreshold && external_temp > ship_temperature)
2668 ship_temperature += (float)((external_temp - ship_temperature) * SHIP_INSULATION_FACTOR * deltaInsulation);
2669 else {
2671 ship_temperature += (float)((external_temp - heatThreshold - ship_temperature) * SHIP_COOLING_FACTOR * deltaInsulation);
2672 }
2673
2675 [self takeHeatDamage:delta_t * ship_temperature];
2676 }
2677
2678 if ((status == STATUS_ESCAPE_SEQUENCE) && (shot_time > ESCAPE_SEQUENCE_TIME)) {
2679 UPDATE_STAGE(@"resetting after escape");
2680 ShipEntity* doppelganger = (ShipEntity*)[self foundTarget];
2681 // reset legal status again! Could have changed if a previously launched missile hit a clean NPC while in the escape pod.
2682 [self setBounty:0 withReason:kOOLegalStatusReasonEscapePod];
2683 bounty = 0;
2684 thrust = max_thrust; // re-enable inertialess drives
2685 // no access to all player.ship properties while inside the escape pod,
2686 // we're not supposed to be inside our ship anymore!
2687 [self doScriptEvent:OOJSID("escapePodSequenceOver")]; // allow oxps to override the escape pod target
2692 if (EXPECT_NOT(target_system_id != system_id)) // overridden: we're going to a nearby system!
2693 {
2696 [UNIVERSE setSystemTo:system_id];
2697 galaxy_coordinates = PointFromString([[UNIVERSE systemManager] getProperty:@"coordinates" forSystem:system_id inGalaxy:galaxy_number]);
2698
2699 [UNIVERSE setUpSpace];
2700 // run initial system population
2701 [UNIVERSE populateNormalSpace];
2702
2703 [self setDockTarget:[UNIVERSE station]];
2704 // send world script events to let oxps know we're in a new system.
2705 // all player.ship properties are still disabled at this stage.
2706 [UNIVERSE setWitchspaceBreakPattern:YES];
2707 [self doScriptEvent:OOJSID("shipWillExitWitchspace")];
2708 [self doScriptEvent:OOJSID("shipExitedWitchspace")];
2709
2710 [[UNIVERSE planet] update:2.34375 * market_rnd]; // from 0..10 minutes
2711 [[UNIVERSE station] update:2.34375 * market_rnd]; // from 0..10 minutes
2712 }
2713
2714 Entity* dockTargetEntity = [UNIVERSE entityForUniversalID:_dockTarget]; // main station in the original system, unless overridden.
2715 if ([dockTargetEntity isStation]) // fails if _dockTarget is NO_TARGET
2716 {
2717 [doppelganger becomeExplosion]; // blow up the doppelganger
2718 // restore player ship
2719 ShipEntity* player_ship = [UNIVERSE newShipWithName:[self shipDataKey]]; // retained
2720 if (player_ship) {
2721 // FIXME: this should use OOShipType, which should exist. -- Ahruman
2722 [self setMesh:[player_ship mesh]];
2723 [player_ship release]; // we only wanted it for its polygons!
2724 }
2725 [UNIVERSE setViewDirection:VIEW_FORWARD];
2726 [UNIVERSE setBlockJSPlayerShipProps:NO]; // re-enable player.ship!
2727 [self enterDock:(StationEntity*)dockTargetEntity];
2728 } else // no dock target? dock target is not a station? game over!
2729 {
2730 [self setStatus:STATUS_DEAD];
2731 //[self playGameOver]; // no death explosion sounds for player pods
2732 // no shipDied events for player pods, either
2733 [UNIVERSE displayMessage:DESC(@"gameoverscreen-escape-pod") forCount:kDeadResetTime];
2734 [UNIVERSE displayMessage:@"" forCount:kDeadResetTime];
2735 [self showGameOver];
2736 }
2737 }
2738
2739 // MOVED THE FOLLOWING FROM PLAYERENTITY POLLFLIGHTCONTROLS:
2741 if (hyperspeed_engaged) {
2742 UPDATE_STAGE(@"updating hyperspeed");
2743
2744 // increase speed up to maximum hyperspeed
2746 flightSpeed += (float)(speed_delta * delta_t * HYPERSPEED_FACTOR);
2749
2750 // check for mass lock
2752 // check for mass lock & external temperature?
2753 // hyperspeed_locked = flightSpeed * air_friction > 40.0f+(ship_temperature - external_temp ) * SHIP_COOLING_FACTOR || [self massLocked];
2754
2755 if (hyperspeed_locked) {
2756 [self playJumpMassLocked];
2757 [UNIVERSE addMessage:DESC(@"jump-mass-locked") forCount:4.5];
2758 hyperspeed_engaged = NO;
2759 }
2760 } else {
2761 if (afterburner_engaged) {
2762 UPDATE_STAGE(@"updating afterburner");
2763
2764 float abFactor = [self afterburnerFactor];
2765 float maxInjectionSpeed = maxFlightSpeed * abFactor;
2766 if (flightSpeed > maxInjectionSpeed) {
2767 // decellerate to maxInjectionSpeed but slower than without afterburner.
2768 flightSpeed -= (float)(speed_delta * delta_t * abFactor);
2769 } else {
2770 if (flightSpeed < maxInjectionSpeed)
2771 flightSpeed += (float)(speed_delta * delta_t * abFactor);
2772 if (flightSpeed > maxInjectionSpeed)
2773 flightSpeed = maxInjectionSpeed;
2774 }
2775 fuel_accumulator -= (float)(delta_t * afterburner_rate);
2776 while ((fuel_accumulator < 0) && (fuel > 0)) {
2777 fuel_accumulator += 1.0f;
2778 if (--fuel <= MIN_FUEL)
2780 }
2781 } else {
2782 UPDATE_STAGE(@"slowing from hyperspeed");
2783
2784 // slow back down...
2786 // decrease speed to maximum normal speed
2787 float deceleration = (speed_delta * delta_t * HYPERSPEED_FACTOR);
2789 // decelerate much quicker in masslocks
2790 // this does also apply to injector deceleration
2791 // but it's not very noticeable
2792 deceleration *= 3;
2793 }
2794 flightSpeed -= deceleration;
2797 }
2798 }
2799 }
2800
2801 // fuel leakage
2802 if ((fuel_leak_rate > 0.0) && (fuel > 0)) {
2803 UPDATE_STAGE(@"updating fuel leakage");
2804
2805 fuel_accumulator -= (float)(fuel_leak_rate * delta_t);
2806 while ((fuel_accumulator < 0) && (fuel > 0)) {
2807 fuel_accumulator += 1.0f;
2808 fuel--;
2809 }
2810 if (fuel == 0)
2811 fuel_leak_rate = 0;
2812 }
2813
2814 // smart_zoom
2815 UPDATE_STAGE(@"updating scanner zoom");
2816 if (scanner_zoom_rate) {
2817 double z = [hud scannerZoom];
2818 double z1 = z + scanner_zoom_rate * delta_t;
2819 if (scanner_zoom_rate > 0.0) {
2820 if (floor(z1) > floor(z)) {
2821 z1 = floor(z1);
2822 scanner_zoom_rate = 0.0f;
2823 }
2824 } else {
2825 if (z1 < 1.0) {
2826 z1 = 1.0;
2827 scanner_zoom_rate = 0.0f;
2828 }
2829 }
2830 [hud setScannerZoom:z1];
2831 }
2832
2833 [[UNIVERSE gameView] setFov:fieldOfView fromFraction:YES];
2834
2835 // scanner sanity check - lose any targets further than maximum scanner range
2836 ShipEntity* primeTarget = [self primaryTarget];
2837 if (primeTarget && HPdistance2([primeTarget position], [self position]) > SCANNER_MAX_RANGE2 && !autopilot_engaged) {
2838 [UNIVERSE addMessage:DESC(@"target-lost") forCount:3.0];
2839 [self removeTarget:primeTarget];
2840 }
2841 // compass sanity check and update target for changed mode
2842 [self validateCompassTarget];
2843
2844 // update subentities
2845 UPDATE_STAGE(@"updating subentities");
2846 totalBoundingBox = boundingBox; // reset totalBoundingBox
2847 ShipEntity* se = nil;
2848 foreach (se, [self subEntities]) {
2849 [se update:delta_t];
2850 if ([se isShip]) {
2854 }
2855 }
2856 // and one thing which isn't a subentity. Fixes bug with
2857 // mispositioned laser beams particularly noticeable on side view.
2858 if (lastShot != nil) {
2859 OOLaserShotEntity* lse = nil;
2860 foreach (lse, lastShot) {
2861 [lse update:0.0];
2862 }
2864 }
2865
2866 // update mousewheel status
2867 UPDATE_STAGE(@"updating mousewheel delta");
2868 MyOpenGLView* gView = [UNIVERSE gameView];
2869 float mouseWheelDelta = [gView mouseWheelDelta];
2870 if (mouseWheelDelta > 0.0f) {
2871 if (mouseWheelDelta < delta_t)
2873 else
2874 [gView setMouseWheelDelta:mouseWheelDelta - delta_t];
2875 } else if (mouseWheelDelta < 0.0f) {
2876 if (mouseWheelDelta > -delta_t)
2878 else
2879 [gView setMouseWheelDelta:mouseWheelDelta + delta_t];
2880 }
2881
2883}
2884
2886{
2887 hasMoved = !HPvector_equal(position, lastPosition);
2888 hasRotated = !quaternion_equal(orientation, lastOrientation);
2889 lastPosition = position;
2890 lastOrientation = orientation;
2891}
2892
2894{
2895 if (![self isInSpace] || [self status] == STATUS_DOCKING) {
2896 [self clearAlertFlags];
2897 // not needed while docked
2898 return;
2899 }
2900
2901 int i, ent_count = UNIVERSE->n_entities;
2902 Entity** uni_entities = UNIVERSE->sortedEntities; // grab the public sorted list
2903 Entity* my_entities[ent_count];
2904 Entity* scannedEntity = nil;
2905 for (i = 0; i < ent_count; i++) {
2906 my_entities[i] = [uni_entities[i] retain]; // retained
2907 }
2908 BOOL massLocked = NO;
2909 BOOL foundHostiles = NO;
2910#if OO_VARIABLE_TORUS_SPEED
2911 BOOL needHyperspeedNearest = YES;
2912 double hsnDistance = 0;
2913#endif
2914 for (i = 0; i < ent_count; i++) // scanner lollypops
2915 {
2916 scannedEntity = my_entities[i];
2917
2918#if OO_VARIABLE_TORUS_SPEED
2919 if (EXPECT_NOT(needHyperspeedNearest)) {
2920 // not visual effects, waypoints, ships, etc.
2921 if (scannedEntity != self && [scannedEntity canCollide] && (![scannedEntity isShip] || ![self collisionExceptedFor:(ShipEntity*)scannedEntity])) {
2922 hsnDistance = sqrt(scannedEntity->zero_distance) - [scannedEntity collisionRadius];
2923 needHyperspeedNearest = NO;
2924 }
2925 } else if ([scannedEntity isStellarObject]) {
2926 // planets, stars might be closest surface even if not
2927 // closest centre. That could be true of others, but the
2928 // error is negligible there.
2929 double thisHSN = sqrt(scannedEntity->zero_distance) - [scannedEntity collisionRadius];
2930 if (thisHSN < hsnDistance) {
2931 hsnDistance = thisHSN;
2932 }
2933 }
2934#endif
2935
2936 if (scannedEntity->zero_distance < SCANNER_MAX_RANGE2 || !scannedEntity->isShip) {
2937 int theirClass = [scannedEntity scanClass];
2938 // here we could also force masslock for higher than yellow alert, but
2939 // if we are going to hand over masslock control to scripting, might as well
2940 // hand it over fully
2941 if ([self massLockable] /*|| alertFlags > ALERT_FLAG_YELLOW_LIMIT*/) {
2942 massLocked |= [self checkEntityForMassLock:scannedEntity withScanClass:theirClass]; // we just need one masslocker..
2943 }
2944 if (theirClass != CLASS_NO_DRAW) {
2945 if (theirClass == CLASS_THARGOID || [scannedEntity isCascadeWeapon]) {
2946 foundHostiles = YES;
2947 } else if ([scannedEntity isShip]) {
2948 ShipEntity* ship = (ShipEntity*)scannedEntity;
2949 foundHostiles |= (([ship hasHostileTarget]) && ([ship primaryTarget] == self));
2950 }
2951 }
2952 }
2953 }
2954#if OO_VARIABLE_TORUS_SPEED
2955 if (EXPECT_NOT(needHyperspeedNearest)) {
2956 // this case should only occur in an otherwise empty
2957 // interstellar space - unlikely but possible
2958 hyperspeedFactor = MIN_HYPERSPEED_FACTOR;
2959 } else {
2960 // once nearest object is >4x scanner range
2961 // start increasing torus speed
2962 double factor = hsnDistance / (4 * SCANNER_MAX_RANGE);
2963 if (factor < 1.0) {
2964 hyperspeedFactor = MIN_HYPERSPEED_FACTOR;
2965 } else {
2966 hyperspeedFactor = MIN_HYPERSPEED_FACTOR * sqrt(factor);
2967 if (hyperspeedFactor > MAX_HYPERSPEED_FACTOR) {
2968 // caps out at ~10^8m from nearest object
2969 // which takes ~10 minutes of flying
2970 hyperspeedFactor = MAX_HYPERSPEED_FACTOR;
2971 }
2972 }
2973 }
2974#endif
2975
2976 [self setAlertFlag:ALERT_FLAG_MASS_LOCK
2977 to:massLocked];
2978
2979 [self setAlertFlag:ALERT_FLAG_HOSTILES to:foundHostiles];
2980
2981 for (i = 0; i < ent_count; i++) {
2982 [my_entities[i] release]; // released
2983 }
2984
2985 BOOL energyCritical = NO;
2986 if (energy < 64 && energy < maxEnergy * 0.8) {
2987 energyCritical = YES;
2988 }
2989 [self setAlertFlag:ALERT_FLAG_ENERGY to:energyCritical];
2990
2991 [self setAlertFlag:ALERT_FLAG_TEMP to:([self hullHeatLevel] > .90)];
2992
2993 [self setAlertFlag:ALERT_FLAG_ALT to:([self dialAltitude] < .10)];
2994}
2995
2996- (void)setMaxFlightPitch:(GLfloat)new
2997{
2998 max_flight_pitch = new;
2999 pitch_delta = 2.0 * new;
3000}
3001
3002- (void)setMaxFlightRoll:(GLfloat)new
3003{
3004 max_flight_roll = new;
3005 roll_delta = 2.0 * new;
3006}
3007
3008- (void)setMaxFlightYaw:(GLfloat)new
3009{
3010 max_flight_yaw = new;
3011 yaw_delta = 2.0 * new;
3012}
3013
3014- (BOOL)checkEntityForMassLock:(Entity*)ent withScanClass:(int)theirClass
3015{
3016 BOOL massLocked = NO;
3017 BOOL entIsCloakedShip = [ent isShip] && [(ShipEntity*)ent isCloaked];
3018
3019 if (EXPECT_NOT([ent isStellarObject])) {
3021 if (EXPECT([stellar planetType] != STELLAR_TYPE_MINIATURE)) {
3022 double dist = stellar->zero_distance;
3023 double rad = stellar->collision_radius;
3024 double factor = ([stellar isSun]) ? 2.0 : 4.0;
3025 // plus ensure mass lock when 25 km or less from the surface of small stellar bodies
3026 // dist is a square distance so it needs to be compared to (rad+25000) * (rad+25000)!
3027 if (dist < rad * rad * factor || dist < rad * rad + 50000 * rad + 625000000) {
3028 massLocked = YES;
3029 }
3030 }
3031 } else if (theirClass != CLASS_NO_DRAW) {
3032 if (EXPECT_NOT(entIsCloakedShip)) {
3033 theirClass = CLASS_NO_DRAW;
3034 }
3035 }
3036
3037 if (!massLocked && ent->zero_distance <= SCANNER_MAX_RANGE2) {
3038 switch (theirClass) {
3039 case CLASS_NO_DRAW:
3040 // cloaked ships do mass lock! - Nikos 20200718
3041 if (entIsCloakedShip && ![ent isPlayer]) {
3042 massLocked = YES;
3043 }
3044 break;
3045 case CLASS_PLAYER:
3046 case CLASS_BUOY:
3047 case CLASS_ROCK:
3048 case CLASS_CARGO:
3049 case CLASS_MINE:
3050 case CLASS_VISUAL_EFFECT:
3051 break;
3052
3053 case CLASS_THARGOID:
3054 case CLASS_MISSILE:
3055 case CLASS_STATION:
3056 case CLASS_POLICE:
3057 case CLASS_MILITARY:
3058 case CLASS_WORMHOLE:
3059 default:
3060 massLocked = YES;
3061 break;
3062 }
3063 }
3064
3065 return massLocked;
3066}
3067
3069{
3071 /* TODO: update alert condition once per frame. Tried this before, but
3072 there turned out to be complications. See mailing list archive.
3073 -- Ahruman 20070802
3074 */
3075 OOAlertCondition cond = [self alertCondition];
3076 OOTimeAbsolute t = [UNIVERSE getTime];
3077 if (cond != lastScriptAlertCondition) {
3078 [self doScriptEvent:OOJSID("alertConditionChanged") withArgument:[NSNumber numberWithInt:cond] andArgument:[NSNumber numberWithInt:lastScriptAlertCondition]];
3079 lastScriptAlertCondition = cond;
3080 }
3081 /* Update heuristic assessment of whether player is fleeing */
3082 if (cond == ALERT_CONDITION_DOCKED || cond == ALERT_CONDITION_GREEN || (cond == ALERT_CONDITION_YELLOW && energy == maxEnergy)) {
3083 fleeing_status = PLAYER_FLEEING_NONE;
3084 } else if (fleeing_status == PLAYER_FLEEING_UNLIKELY && (energy > maxEnergy * 0.6 || cond != ALERT_CONDITION_RED)) {
3085 fleeing_status = PLAYER_FLEEING_NONE;
3086 } else if ((fleeing_status == PLAYER_FLEEING_MAYBE || fleeing_status == PLAYER_FLEEING_UNLIKELY) && cargo_dump_time > last_shot_time) {
3087 fleeing_status = PLAYER_FLEEING_CARGO;
3088 } else if (fleeing_status == PLAYER_FLEEING_MAYBE && last_shot_time + 10 > t) {
3089 fleeing_status = PLAYER_FLEEING_NONE;
3090 } else if (fleeing_status == PLAYER_FLEEING_LIKELY && last_shot_time + 10 > t) {
3091 fleeing_status = PLAYER_FLEEING_UNLIKELY;
3092 } else if (fleeing_status == PLAYER_FLEEING_NONE && cond == ALERT_CONDITION_RED && last_shot_time + 10 < t && flightSpeed > 0.75 * maxFlightSpeed) {
3093 fleeing_status = PLAYER_FLEEING_MAYBE;
3094 } else if ((fleeing_status == PLAYER_FLEEING_MAYBE || fleeing_status == PLAYER_FLEEING_CARGO) && cond == ALERT_CONDITION_RED && last_shot_time + 10 < t && flightSpeed > 0.75 * maxFlightSpeed && energy < maxEnergy * 0.5 && (forward_shield < [self maxForwardShieldLevel] * 0.25 || aft_shield < [self maxAftShieldLevel] * 0.25)) {
3095 fleeing_status = PLAYER_FLEEING_LIKELY;
3096 }
3097}
3098
3099- (void)updateFuelScoops:(OOTimeDelta)delta_t
3100{
3101 if (scoopsActive) {
3102 [self updateFuelScoopSoundWithInterval:delta_t];
3103 if (![self scoopOverride]) {
3104 scoopsActive = NO;
3105 [self updateFuelScoopSoundWithInterval:delta_t];
3106 }
3107 }
3108}
3109
3110- (void)updateClocks:(OOTimeDelta)delta_t
3111{
3112 // shot time updates are still needed here for STATUS_DEAD!
3113 shot_time += delta_t;
3114 script_time += delta_t;
3115 unsigned prev_day = floor(ship_clock / 86400);
3116 ship_clock += delta_t;
3117 if (ship_clock_adjust > 0.0) // adjust for coming out of warp (add LY * LY hrs)
3118 {
3119 double fine_adjust = delta_t * 7200.0;
3120 if (ship_clock_adjust > 86400) // more than a day
3121 fine_adjust = delta_t * 115200.0; // 16 times faster
3122 if (ship_clock_adjust > 0) {
3123 if (fine_adjust > ship_clock_adjust)
3124 fine_adjust = ship_clock_adjust;
3125 ship_clock += fine_adjust;
3126 ship_clock_adjust -= fine_adjust;
3127 } else {
3128 if (fine_adjust < ship_clock_adjust)
3129 fine_adjust = ship_clock_adjust;
3130 ship_clock -= fine_adjust;
3131 ship_clock_adjust += fine_adjust;
3132 }
3133 } else
3134 ship_clock_adjust = 0.0;
3135
3136 unsigned now_day = floor(ship_clock / 86400.0);
3137 while (prev_day < now_day) {
3138 prev_day++;
3139 [self doScriptEvent:OOJSID("dayChanged") withArgument:[NSNumber numberWithUnsignedInt:prev_day]];
3140 // not impossible that at ultra-low frame rates two of these will
3141 // happen in a single update.
3142 }
3143
3144 // fps
3145 if (ship_clock > fps_check_time) {
3146 if (![self clockAdjusting]) {
3147 fps_counter = (int)([UNIVERSE timeAccelerationFactor] * floor([UNIVERSE framesDoneThisUpdate] / (fps_check_time - last_fps_check_time)));
3148 last_fps_check_time = fps_check_time;
3149 fps_check_time = ship_clock + MINIMUM_GAME_TICK;
3150 } else {
3151 // Good approximation for when the clock is adjusting and proper fps calculation
3152 // cannot be performed.
3153 fps_counter = (int)([UNIVERSE timeAccelerationFactor] * floor(1.0 / delta_t));
3154 fps_check_time = ship_clock + MINIMUM_GAME_TICK;
3155 }
3156 [UNIVERSE resetFramesDoneThisUpdate]; // Reset frame counter
3157 }
3158}
3159
3161{
3162 if (script_time <= script_time_check)
3163 return;
3164
3165 if ([self status] != STATUS_IN_FLIGHT) {
3166 switch (gui_screen) {
3167 // Screens where no world script tickles are performed
3168 case GUI_SCREEN_MAIN:
3169 case GUI_SCREEN_INTRO1:
3170 case GUI_SCREEN_SHIPLIBRARY:
3171 case GUI_SCREEN_KEYBOARD:
3172 case GUI_SCREEN_NEWGAME:
3173 case GUI_SCREEN_OXZMANAGER:
3174 case GUI_SCREEN_MARKET:
3175 case GUI_SCREEN_MARKETINFO:
3176 case GUI_SCREEN_OPTIONS:
3177 case GUI_SCREEN_GAMEOPTIONS:
3178 case GUI_SCREEN_LOAD:
3179 case GUI_SCREEN_SAVE:
3180 case GUI_SCREEN_SAVE_OVERWRITE:
3181 case GUI_SCREEN_STICKMAPPER:
3182 case GUI_SCREEN_STICKPROFILE:
3183 case GUI_SCREEN_MISSION:
3184 case GUI_SCREEN_REPORT:
3185 case GUI_SCREEN_KEYBOARD_CONFIRMCLEAR:
3186 case GUI_SCREEN_KEYBOARD_CONFIG:
3187 case GUI_SCREEN_KEYBOARD_ENTRY:
3188 case GUI_SCREEN_KEYBOARD_LAYOUT:
3189 return;
3190
3191 // Screens from which it's safe to jump to the mission screen
3192 // case GUI_SCREEN_CONTRACTS:
3193 case GUI_SCREEN_EQUIP_SHIP:
3194 case GUI_SCREEN_INTERFACES:
3195 case GUI_SCREEN_MANIFEST:
3196 case GUI_SCREEN_SHIPYARD:
3197 case GUI_SCREEN_LONG_RANGE_CHART:
3198 case GUI_SCREEN_SHORT_RANGE_CHART:
3199 case GUI_SCREEN_STATUS:
3200 case GUI_SCREEN_SYSTEM_DATA:
3201 // Test passed, we can run scripts. Nothing to do here.
3202 break;
3203 }
3204 }
3205
3206 // Test either passed or never ran, run scripts.
3207 [self checkScript];
3208 script_time_check += script_time_interval;
3209}
3210
3211- (void)updateTrumbles:(OOTimeDelta)delta_t
3212{
3213 OOTrumble** trumbles = [self trumbleArray];
3214 NSUInteger i;
3215
3216 for (i = [self trumbleCount]; i > 0; i--) {
3217 OOTrumble* trum = trumbles[i - 1];
3218 [trum updateTrumble:delta_t];
3219 }
3220}
3221
3222- (void)performAutopilotUpdates:(OOTimeDelta)delta_t
3223{
3224 [self processBehaviour:delta_t];
3225 [self applyVelocity:delta_t];
3226 [self doBookkeeping:delta_t];
3227}
3228
3229- (void)performDockingRequest:(StationEntity*)stationForDocking
3230{
3231 if (stationForDocking == nil)
3232 return;
3233 if (![stationForDocking isStation] || ![stationForDocking isKindOfClass:[StationEntity class]])
3234 return;
3235 if ([self isDocked])
3236 return;
3237 if (autopilot_engaged && [self targetStation] == stationForDocking)
3238 return;
3239 if (autopilot_engaged && [self targetStation] != stationForDocking) {
3240 [self disengageAutopilot];
3241 }
3242 NSString* stationDockingClearanceStatus = [stationForDocking acceptDockingClearanceRequestFrom:self];
3243 if (stationDockingClearanceStatus != nil) {
3244 [self doScriptEvent:OOJSID("playerRequestedDockingClearance") withArgument:stationDockingClearanceStatus];
3245 if ([stationDockingClearanceStatus isEqualToString:@"DOCKING_CLEARANCE_GRANTED"]) {
3246 [self doScriptEvent:OOJSID("playerDockingClearanceGranted")];
3247 }
3248 }
3249}
3250
3251- (void)requestDockingClearance:(StationEntity*)stationForDocking
3252{
3254 [self performDockingRequest:stationForDocking];
3255 }
3256}
3257
3258- (void)cancelDockingRequest:(StationEntity*)stationForDocking
3259{
3260 if (stationForDocking == nil)
3261 return;
3262 if (![stationForDocking isStation] || ![stationForDocking isKindOfClass:[StationEntity class]])
3263 return;
3264 if ([self isDocked])
3265 return;
3266 if (autopilot_engaged && [self targetStation] == stationForDocking)
3267 return;
3268 if (autopilot_engaged && [self targetStation] != stationForDocking) {
3269 [self disengageAutopilot];
3270 }
3272 NSString* stationDockingClearanceStatus = [stationForDocking acceptDockingClearanceRequestFrom:self];
3273 if (stationDockingClearanceStatus != nil && [stationDockingClearanceStatus isEqualToString:@"DOCKING_CLEARANCE_CANCELLED"]) {
3274 [self doScriptEvent:OOJSID("playerDockingClearanceCancelled")];
3275 }
3276 }
3277}
3278
3279- (BOOL)engageAutopilotToStation:(StationEntity*)stationForDocking
3280{
3281 if (stationForDocking == nil)
3282 return NO;
3283 if ([self isDocked])
3284 return NO;
3285
3286 if (autopilot_engaged && [self targetStation] == stationForDocking) {
3287 return YES;
3288 }
3289
3290 [self setTargetStation:stationForDocking];
3292 autopilot_engaged = YES;
3293 ident_engaged = NO;
3294 [self safeAllMissiles];
3296 if ([self status] == STATUS_WITCHSPACE_COUNTDOWN)
3297 [self cancelWitchspaceCountdown]; // cancel witchspace countdown properly
3298 [self setStatus:STATUS_AUTOPILOT_ENGAGED];
3299 [self resetAutopilotAI];
3300 [shipAI setState:@"BEGIN_DOCKING"]; // reboot the AI
3301 [self playAutopilotOn];
3303 [self doScriptEvent:OOJSID("playerStartedAutoPilot") withArgument:stationForDocking];
3304 [self setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_GRANTED];
3305
3306 if (afterburner_engaged) {
3309 [self stopAfterburnerSound];
3310 }
3311 return YES;
3312}
3313
3315{
3316 if (autopilot_engaged) {
3317 [self abortDocking]; // let the station know that you are no longer on approach
3318 behaviour = BEHAVIOUR_IDLE;
3319 frustration = 0.0;
3320 autopilot_engaged = NO;
3322 [self setTargetStation:nil];
3323 [self setStatus:STATUS_IN_FLIGHT];
3324 [self playAutopilotOff];
3325 [self setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_NONE];
3327 [self doScriptEvent:OOJSID("playerCancelledAutoPilot")];
3328
3329 [self resetAutopilotAI];
3330 }
3331}
3332
3334{
3335 AI* myAI = [self getAI];
3336 // JSAI: will need changing if oolite-dockingAI.js written
3337 if (![[myAI name] isEqualToString:PLAYER_DOCKING_AI_NAME]) {
3338 [self setAITo:PLAYER_DOCKING_AI_NAME];
3339 }
3341 [myAI setState:@"GLOBAL"];
3342 [myAI setNextThinkTime:[UNIVERSE getTime] + 2];
3343 [myAI setOwner:self];
3344}
3345
3346#define VELOCITY_CLEANUP_MIN 2000.0f // Minimum speed for "power braking".
3347#define VELOCITY_CLEANUP_FULL 5000.0f // Speed at which full "power braking" factor is used.
3348#define VELOCITY_CLEANUP_RATE 0.001f // Factor for full "power braking".
3349
3350#if OO_VARIABLE_TORUS_SPEED
3352{
3353 return hyperspeedFactor;
3354}
3355#endif
3356
3358{
3359 return afterburner_engaged;
3360}
3361
3363{
3364 return hyperspeed_engaged;
3365}
3366
3367- (void)performInFlightUpdates:(OOTimeDelta)delta_t
3368{
3370
3371 // do flight routines
3373 UPDATE_STAGE(@"applying newtonian drift");
3375
3376 [self applyVelocity:delta_t];
3377
3378 GLfloat thrust_factor = 1.0;
3379 if (flightSpeed > maxFlightSpeed) {
3380 if (afterburner_engaged) {
3381 thrust_factor = [self afterburnerFactor];
3382 } else {
3383 thrust_factor = HYPERSPEED_FACTOR;
3384 }
3385 }
3386
3387 GLfloat velmag = magnitude(velocity);
3388 GLfloat velmag2 = velmag - (float)delta_t * thrust * thrust_factor;
3389 if (velmag > 0) {
3390 UPDATE_STAGE(@"applying power braking");
3391
3392 if (velmag > VELOCITY_CLEANUP_MIN) {
3393 GLfloat rate;
3394 // Fix up extremely ridiculous speeds that can happen in collisions or explosions
3395 if (velmag > VELOCITY_CLEANUP_FULL)
3396 rate = VELOCITY_CLEANUP_RATE;
3397 else
3399 velmag2 -= velmag * rate;
3400 }
3401 if (velmag2 < 0.0f)
3402 velocity = kZeroVector;
3403 else
3404 velocity = vector_multiply_scalar(velocity, velmag2 / velmag);
3405 }
3406
3407 UPDATE_STAGE(@"updating joystick");
3408 [self applyRoll:(float)delta_t * flightRoll andClimb:(float)delta_t * flightPitch];
3409 if (flightYaw != 0.0) {
3410 [self applyYaw:(float)delta_t * flightYaw];
3411 }
3412
3413 UPDATE_STAGE(@"applying para-newtonian thrust");
3414 [self moveForward:delta_t * flightSpeed];
3415
3416 UPDATE_STAGE(@"updating targeting");
3417 [self updateTargeting];
3418
3420}
3421
3422- (void)performWitchspaceCountdownUpdates:(OOTimeDelta)delta_t
3423{
3425
3426 UPDATE_STAGE(@"doing bookkeeping");
3427 [self doBookkeeping:delta_t];
3428
3429 UPDATE_STAGE(@"updating countdown timer");
3430 witchspaceCountdown = fdim(witchspaceCountdown, delta_t);
3431
3432 // damaged gal drive? abort!
3433 /* TODO: this check should possibly be hasEquipmentItemProviding:,
3434 * but if it was we'd need to know which item was actually doing
3435 * the providing so it could be removed. */
3436 if (EXPECT_NOT(galactic_witchjump && ![self hasEquipmentItem:@"EQ_GAL_DRIVE"])) {
3437 galactic_witchjump = NO;
3438 [self setStatus:STATUS_IN_FLIGHT];
3439 [self playHyperspaceAborted];
3440 [self doScriptEvent:OOJSID("playerJumpFailed") withArgument:@"malfunction"];
3441 return;
3442 }
3443
3444 int seconds = round(witchspaceCountdown);
3445 if (galactic_witchjump) {
3446 [UNIVERSE displayCountdownMessage:OOExpandKey(@"witch-galactic-in-x-seconds", seconds) forCount:1.0];
3447 } else {
3448 NSString* destination = [UNIVERSE getSystemName:[self nextHopTargetSystemID]];
3449 [UNIVERSE displayCountdownMessage:OOExpandKey(@"witch-to-x-in-y-seconds", seconds, destination) forCount:1.0];
3450 }
3451
3452 if (witchspaceCountdown == 0.0) {
3453 UPDATE_STAGE(@"preloading planet textures");
3454 if (!galactic_witchjump) {
3455 /* Note: planet texture preloading is done twice for hyperspace jumps:
3456 once when starting the countdown and once at the beginning of the
3457 jump. The reason is that the preloading may have been skipped the
3458 first time because of rate limiting (see notes at
3459 -preloadPlanetTexturesForSystem:). There is no significant overhead
3460 from doing it twice thanks to the texture cache.
3461 -- Ahruman 2009-12-19
3462 */
3463 [UNIVERSE preloadPlanetTexturesForSystem:target_system_id];
3464 } else {
3465 // FIXME: preload target system for galactic jump?
3466 }
3467
3468 UPDATE_STAGE(@"JUMP!");
3469 if (galactic_witchjump)
3471 else
3472 [self enterWitchspace];
3473 galactic_witchjump = NO;
3474 }
3475
3477}
3478
3479- (void)performWitchspaceExitUpdates:(OOTimeDelta)delta_t
3480{
3481 if ([UNIVERSE breakPatternOver]) {
3482 [self resetExhaustPlumes];
3483 // time to check the script!
3484 [self checkScript];
3485 // next check in 10s
3486 [self resetScriptTimer]; // reset the in-system timer
3487
3488 // announce arrival
3489 if ([UNIVERSE planet]) {
3490 [UNIVERSE addMessage:[NSString stringWithFormat:@" %@. ", [UNIVERSE getSystemName:system_id]] forCount:3.0];
3491 // and reset the compass
3492 if ([self hasEquipmentItemProviding:@"EQ_ADVANCED_COMPASS"])
3493 compassMode = COMPASS_MODE_PLANET;
3494 else
3495 compassMode = COMPASS_MODE_BASIC;
3496 } else {
3497 if ([UNIVERSE inInterstellarSpace])
3498 [UNIVERSE addMessage:DESC(@"witch-engine-malfunction") forCount:3.0]; // if sun gone nova, print nothing
3499 }
3500
3501 [self setStatus:STATUS_IN_FLIGHT];
3502
3503 // If we are exiting witchspace after a scripted misjump. then make sure it gets reset now.
3504 // Scripted misjump situations should have a lifespan of one jump only, to keep things
3505 // simple - Nikos 20090728
3506 if ([self scriptedMisjump])
3507 [self setScriptedMisjump:NO];
3508 // similarly reset the misjump range to the traditional 0.5
3509 [self setScriptedMisjumpRange:0.5];
3510
3511 [self doScriptEvent:OOJSID("shipExitedWitchspace") withArgument:[self jumpCause]];
3512
3513 [self doBookkeeping:delta_t]; // arrival frame updates
3514
3515 suppressAegisMessages = NO;
3516 }
3517}
3518
3519- (void)performLaunchingUpdates:(OOTimeDelta)delta_t
3520{
3521 if (![UNIVERSE breakPatternHide]) {
3522 flightRoll = launchRoll; // synchronise player's & launching station's spins.
3523 [self doBookkeeping:delta_t]; // don't show ghost exhaust plumes from previous docking!
3524 }
3525
3526 if ([UNIVERSE breakPatternOver]) {
3527 // time to check the legacy scripts!
3528 [self checkScript];
3529 // next check in 10s
3530
3531 [self setStatus:STATUS_IN_FLIGHT];
3532
3533 [self setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_NONE];
3534 StationEntity* stationLaunchedFrom = [UNIVERSE nearestEntityMatchingPredicate:IsStationPredicate parameter:NULL relativeToEntity:self];
3535 [self doScriptEvent:OOJSID("shipLaunchedFromStation") withArgument:stationLaunchedFrom];
3536 }
3537}
3538
3539- (void)performDockingUpdates:(OOTimeDelta)delta_t
3540{
3541 if ([UNIVERSE breakPatternOver]) {
3542 [self docked]; // bookkeeping for docking
3543 }
3544
3545 // if cloak or ecm visual effects are playing while docking, terminate them
3546 [UNIVERSE terminatePostFX:OO_POSTFX_CLOAK];
3547 if ([UNIVERSE ECMVisualFXEnabled])
3548 [UNIVERSE terminatePostFX:OO_POSTFX_CRTBADSIGNAL];
3549}
3550
3551- (void)performDeadUpdates:(OOTimeDelta)delta_t
3552{
3553 [UNIVERSE terminatePostFX:OO_POSTFX_CLOAK];
3554 if ([UNIVERSE ECMVisualFXEnabled])
3555 [UNIVERSE terminatePostFX:OO_POSTFX_CRTBADSIGNAL];
3556
3557 [self gameOverFadeToBW];
3558
3559 if ([self shotTime] > kDeadResetTime) {
3560 BOOL was_mouse_control_on = mouse_control_on;
3561 [UNIVERSE handleGameOver]; // we restart the UNIVERSE
3562 mouse_control_on = was_mouse_control_on;
3563 }
3564}
3565
3567{
3568 float secondsToBWFadeOut = [[NSUserDefaults standardUserDefaults] oo_floatForKey:@"gameover-seconds-to-bw-fadeout" defaultValue:5.0f];
3569 if ([UNIVERSE detailLevel] >= DETAIL_LEVEL_SHADERS && secondsToBWFadeOut > 0.0f) {
3570 MyOpenGLView* gameView = [UNIVERSE gameView];
3571 static float originalColorSaturation = -1.0f;
3572 if (originalColorSaturation == -1.0f)
3573 originalColorSaturation = [gameView colorSaturation];
3574 if ([self shotTime] < secondsToBWFadeOut) {
3575 // fade to black & white within secondsToBWFadeOut, independently of
3576 // frame rate and original color saturation
3577 if (fps_counter != 0) {
3578 [gameView adjustColorSaturation:-(originalColorSaturation * (1.0f / secondsToBWFadeOut) * [UNIVERSE timeAccelerationFactor] / fps_counter)];
3579 }
3580 }
3581
3582 if ([self shotTime] > kDeadResetTime) {
3583 // make sure to subtract the current saturation because if the user presses space to skip
3584 // the game over screen before the transition to b/w has been completed, whatever is left
3585 // will be added to the original saturation, resulting in an oversaturated image
3586 [gameView adjustColorSaturation:originalColorSaturation - [gameView colorSaturation]];
3587 originalColorSaturation = -1.0f;
3588 }
3589 }
3590}
3591
3592// Target is valid if it's within Scanner range, AND
3593// Target is a ship AND is not cloaked or jamming, OR
3594// Target is a wormhole AND player has the Wormhole Scanner
3595- (BOOL)isValidTarget:(Entity*)target
3596{
3597 // Just in case we got called with a bad target.
3598 if (!target)
3599 return NO;
3600
3601 // If target is beyond scanner range, it's lost
3602 if (target->zero_distance > SCANNER_MAX_RANGE2)
3603 return NO;
3604
3605 // If target is a ship, check whether it's cloaked or is actively jamming our scanner
3606 if ([target isShip]) {
3607 ShipEntity* targetShip = (ShipEntity*)target;
3608 if ([targetShip isCloaked] || // checks for cloaked ships
3609 ([targetShip isJammingScanning] && ![self hasMilitaryScannerFilter])) // checks for activated jammer
3610 {
3611 return NO;
3612 }
3613 OOEntityStatus tstatus = [targetShip status];
3614 if (tstatus == STATUS_ENTERING_WITCHSPACE || tstatus == STATUS_IN_HOLD || tstatus == STATUS_DOCKED) { // checks for ships entering wormholes, docking, or been scooped
3615 return NO;
3616 }
3617 return YES;
3618 }
3619
3620 // If target is an unexpired wormhole and the player has bought the Wormhole Scanner and we're in ID mode
3621 if ([target isWormhole] && [target scanClass] != CLASS_NO_DRAW &&
3622 [self hasEquipmentItemProviding:@"EQ_WORMHOLE_SCANNER"] && ident_engaged) {
3623 return YES;
3624 }
3625
3626 // Target is neither a wormhole nor a ship
3627 return NO;
3628}
3629
3631{
3632 [hud resetGuis:[NSDictionary dictionaryWithObject:[NSDictionary dictionary] forKey:@"message_gui"]];
3633 NSString* scoreMS = [NSString stringWithFormat:OOExpandKey(@"gameoverscreen-score-@"),
3634 KillCountToRatingAndKillString(ship_kills)];
3635
3636 [UNIVERSE displayMessage:OOExpandKey(@"gameoverscreen-game-over") forCount:kDeadResetTime];
3637 [UNIVERSE displayMessage:@"" forCount:kDeadResetTime];
3638 [UNIVERSE displayMessage:scoreMS forCount:kDeadResetTime];
3639 [UNIVERSE displayMessage:@"" forCount:kDeadResetTime];
3640 [UNIVERSE displayMessage:OOExpandKey(@"gameoverscreen-press-space") forCount:kDeadResetTime];
3641 [UNIVERSE displayMessage:@" " forCount:kDeadResetTime];
3642 [UNIVERSE displayMessage:@"" forCount:kDeadResetTime];
3643 [self resetShotTime];
3644}
3645
3646- (void)showShipModelWithKey:(NSString*)shipKey shipData:(NSDictionary*)shipData personality:(uint16_t)personality factorX:(GLfloat)factorX factorY:(GLfloat)factorY factorZ:(GLfloat)factorZ inContext:(NSString*)context
3647{
3648 if (shipKey == nil)
3649 return;
3650 if (shipData == nil)
3651 shipData = [[OOShipRegistry sharedRegistry] shipInfoForKey:shipKey];
3652 if (shipData == nil)
3653 return;
3654
3655 Quaternion q2 = { (GLfloat)M_SQRT1_2, (GLfloat)M_SQRT1_2, (GLfloat)0.0f, (GLfloat)0.0f };
3656 // MKW - retrieve last demo ships' orientation and release it
3657 if (demoShip != nil) {
3658 q2 = [demoShip orientation];
3659 [demoShip release];
3660 }
3661
3662 ShipEntity* ship = [[ProxyPlayerEntity alloc] initWithKey:shipKey definition:shipData];
3663 if (personality != ENTITY_PERSONALITY_INVALID)
3664 [ship setEntityPersonalityInt:personality];
3665
3667
3668 if (context)
3669 OOLog(@"script.debug.note.showShipModel", @"::::: showShipModel:'%@' in context: %@.", [ship name], context);
3670
3671 GLfloat cr = [ship collisionRadius];
3672 [ship setOrientation:q2];
3673 [ship setPositionX:factorX * cr y:factorY * cr z:factorZ * cr];
3674 [ship setScanClass:CLASS_NO_DRAW];
3675 [ship setDemoShip:0.6];
3676 [ship setDemoStartTime:[UNIVERSE getTime]];
3677 if ([ship pendingEscortCount] > 0)
3679 [ship setAITo:@"nullAI.plist"];
3680 id subEntStatus = [shipData objectForKey:@"subentities_status"];
3681 // show missing subentities if there's a subentities_status key
3682 if (subEntStatus != nil)
3683 [ship deserializeShipSubEntitiesFrom:(NSString*)subEntStatus];
3684 [UNIVERSE addEntity:ship];
3685 // MKW - save demo ship for its rotation
3686 demoShip = [ship retain];
3687
3688 [ship setStatus:STATUS_COCKPIT_DISPLAY];
3689
3690 [ship release];
3691}
3692
3693// Check for lost targeting - both on the ships' main target as well as each
3694// missile.
3695// If we're actively scanning and we don't have a current target, then check
3696// to see if we've locked onto a new target.
3697// Finally, if we have a target and it's a wormhole, check whether we have more
3698// information
3700{
3702
3703 // check for lost ident target and ensure the ident system is actually scanning
3704 UPDATE_STAGE(@"checking ident target");
3705 if (ident_engaged && [self primaryTarget] != nil) {
3706 if (![self isValidTarget:[self primaryTarget]]) {
3707 if (!suppressTargetLost) {
3708 [UNIVERSE addMessage:DESC(@"target-lost") forCount:3.0];
3709 [self playTargetLost];
3710 [self noteLostTarget];
3711 } else {
3712 suppressTargetLost = NO;
3713 }
3714
3715 DESTROY(_primaryTarget);
3716 }
3717 }
3718
3719 // check each unlaunched missile's target still exists and is in-range
3720 UPDATE_STAGE(@"checking missile targets");
3721 if (missile_status != MISSILE_STATUS_SAFE) {
3722 unsigned i;
3723 for (i = 0; i < max_missiles; i++) {
3724 if ([missile_entity[i] primaryTarget] != nil && ![self isValidTarget:[missile_entity[i] primaryTarget]]) {
3725 [UNIVERSE addMessage:DESC(@"target-lost") forCount:3.0];
3726 [self playTargetLost];
3727 [missile_entity[i] removeTarget:nil];
3728 if (i == activeMissile) {
3729 [self noteLostTarget];
3730 DESTROY(_primaryTarget);
3731 missile_status = MISSILE_STATUS_ARMED;
3732 }
3733 } else if (i == activeMissile && [missile_entity[i] primaryTarget] == nil) {
3734 missile_status = MISSILE_STATUS_ARMED;
3735 }
3736 }
3737 }
3738
3739 // if we don't have a primary target, and we're scanning, then check for a new
3740 // target to lock on to
3741 UPDATE_STAGE(@"looking for new target");
3742 if ([self primaryTarget] == nil && (ident_engaged || missile_status != MISSILE_STATUS_SAFE) && ([self status] == STATUS_IN_FLIGHT || [self status] == STATUS_WITCHSPACE_COUNTDOWN)) {
3743 Entity* target = [UNIVERSE firstEntityTargetedByPlayer];
3744 if ([self isValidTarget:target]) {
3745 [self addTarget:target];
3746 }
3747 }
3748
3749 // If our primary target is a wormhole, check to see if we have additional
3750 // information
3751 UPDATE_STAGE(@"checking for additional wormhole information");
3752 if ([[self primaryTarget] isWormhole]) {
3753 WormholeEntity* wh = [self primaryTarget];
3754 switch ([wh scanInfo]) {
3755 case WH_SCANINFO_NONE:
3756 OOLog(kOOLogInconsistentState, @"%@", @"Internal Error - WH_SCANINFO_NONE reached in [PlayerEntity updateTargeting:]");
3757 [self dumpState];
3758 [wh dumpState];
3759 // Workaround a reported hit of the assert here. We really
3760 // should work out how/why this could happen though and fix
3761 // the underlying cause.
3762 // - MKW 2011.03.11
3763 // assert([wh scanInfo] != WH_SCANINFO_NONE);
3765 break;
3767 if ([self clockTimeAdjusted] > [wh scanTime] + 2) {
3768 [wh setScanInfo:WH_SCANINFO_COLLAPSE_TIME];
3769 //[UNIVERSE addCommsMessage:[NSString stringWithFormat:DESC(@"wormhole-collapse-time-computed"),
3770 // [UNIVERSE getSystemName:[wh destination]]] forCount:5.0];
3771 }
3772 break;
3774 if ([self clockTimeAdjusted] > [wh scanTime] + 4) {
3775 [wh setScanInfo:WH_SCANINFO_ARRIVAL_TIME];
3776 [UNIVERSE addCommsMessage:[NSString stringWithFormat:DESC(@"wormhole-arrival-time-computed-@"),
3777 ClockToString([wh estimatedArrivalTime], NO)]
3778 forCount:5.0];
3779 }
3780 break;
3782 if ([self clockTimeAdjusted] > [wh scanTime] + 7) {
3783 [wh setScanInfo:WH_SCANINFO_DESTINATION];
3784 [UNIVERSE addCommsMessage:[NSString stringWithFormat:DESC(@"wormhole-destination-computed-@"),
3785 [UNIVERSE getSystemName:[wh destination]]]
3786 forCount:5.0];
3787 }
3788 break;
3790 if ([self clockTimeAdjusted] > [wh scanTime] + 10) {
3791 [wh setScanInfo:WH_SCANINFO_SHIP];
3792 // TODO: Extract last ship from wormhole and display its name
3793 }
3794 break;
3795 case WH_SCANINFO_SHIP:
3796 break;
3797 }
3798 }
3799
3801}
3802
3813
3814- (void)applyAttitudeChanges:(double)delta_t
3815{
3816 [self applyRoll:flightRoll * delta_t andClimb:flightPitch * delta_t];
3817 [self applyYaw:flightYaw * delta_t];
3818}
3819
3820- (void)applyRoll:(GLfloat)roll1 andClimb:(GLfloat)climb1
3821{
3822 if (roll1 == 0.0 && climb1 == 0.0 && hasRotated == NO)
3823 return;
3824
3825 if (roll1)
3827 if (climb1)
3829
3830 /* Bugginess may put us in a state where the orientation quat is all
3831 zeros, at which point it’s impossible to move.
3832 */
3836 } else {
3838 }
3839 }
3840
3841 [self orientationChanged];
3842}
3843
3844/*
3845 * This method should not be necessary, but when I replaced the above with applyRoll:andClimb:andYaw, the
3846 * ship went crazy. Perhaps applyRoll:andClimb is called from one of the subclasses and that was messing
3847 * things up.
3848 */
3849- (void)applyYaw:(GLfloat)yaw
3850{
3852
3853 [self orientationChanged];
3854}
3855
3856- (OOMatrix)drawRotationMatrix // override to provide the 'correct' drawing matrix
3857{
3858 return playerRotMatrix;
3859}
3860
3862{
3863 OOMatrix result = playerRotMatrix;
3864 // HPVect: modify to use camera-relative positioning
3866}
3867
3872
3873- (void)setNormalOrientation:(Quaternion)quat
3874{
3875 [self setOrientation:make_quaternion(-quat.w, quat.x, quat.y, quat.z)];
3876}
3877
3878- (void)moveForward:(double)amount
3879{
3880 distanceTravelled += (float)amount;
3881 [self setPosition:HPvector_add(position, vectorToHPVector(vector_multiply_scalar(v_forward, (float)amount)))];
3882}
3883
3888
3890{
3891 // if ([UNIVERSE breakPatternHide])
3892 // return kZeroVector; // center view for break pattern
3893 // now done by positioning break pattern correctly
3894
3895 switch ([UNIVERSE viewDirection]) {
3896 case VIEW_FORWARD:
3897 return forwardViewOffset;
3898 case VIEW_AFT:
3899 return aftViewOffset;
3900 case VIEW_PORT:
3901 return portViewOffset;
3902 case VIEW_STARBOARD:
3903 return starboardViewOffset;
3904 /* GILES custom viewpoints */
3905 case VIEW_CUSTOM:
3906 return customViewOffset;
3907 /* -- */
3908
3909 default:
3910 break;
3911 }
3912
3913 return kZeroVector;
3914}
3915
3917{
3918 return aftViewOffset;
3919}
3920
3925
3927{
3928 return portViewOffset;
3929}
3930
3935
3936/* TODO post 1.78: profiling suggests this gets called often enough
3937 * that it's worth caching the result per-frame - CIM */
3939{
3940 HPVector viewpoint = position;
3941 if (showDemoShips) {
3942 viewpoint = kZeroHPVector;
3943 }
3944 Vector offset = [self viewpointOffset];
3945
3946 // FIXME: this ought to be done with matrix or quaternion functions.
3947 OOMatrix r = rotMatrix;
3948
3949 viewpoint.x += offset.x * r.m[0][0];
3950 viewpoint.y += offset.x * r.m[1][0];
3951 viewpoint.z += offset.x * r.m[2][0];
3952 viewpoint.x += offset.y * r.m[0][1];
3953 viewpoint.y += offset.y * r.m[1][1];
3954 viewpoint.z += offset.y * r.m[2][1];
3955 viewpoint.x += offset.z * r.m[0][2];
3956 viewpoint.y += offset.z * r.m[1][2];
3957 viewpoint.z += offset.z * r.m[2][2];
3958
3959 return viewpoint;
3960}
3961
3962- (void)drawImmediate:(bool)immediate translucent:(bool)translucent
3963{
3964 switch ([self status]) {
3965 case STATUS_DEAD:
3966 case STATUS_COCKPIT_DISPLAY:
3967 case STATUS_DOCKED:
3968 case STATUS_START_GAME:
3969 return;
3970
3971 default:
3972 if ([UNIVERSE breakPatternHide])
3973 return;
3974 }
3975
3976 [super drawImmediate:immediate translucent:translucent];
3977}
3978
3979- (void)setMassLockable:(BOOL)newValue
3980{
3981 massLockable = !!newValue;
3982 [self updateAlertCondition];
3983}
3984
3986{
3987 return massLockable;
3988}
3989
3991{
3992 return ((alertFlags & ALERT_FLAG_MASS_LOCK) != 0);
3993}
3994
3996{
3998}
3999
4001{
4002 return occlusion_dial;
4003}
4004
4005- (void)setOcclusionLevel:(float)level
4006{
4007 occlusion_dial = level;
4008}
4009
4011{
4012 [self setDockedStation:[UNIVERSE station]];
4013 if (_dockedStation != nil)
4014 [self setStatus:STATUS_DOCKED];
4015}
4016
4021
4022- (void)setDockedStation:(StationEntity*)station
4023{
4024 [_dockedStation release];
4026}
4027
4028- (void)setTargetDockStationTo:(StationEntity*)value
4029{
4030 targetDockStation = value;
4031}
4032
4037
4039{
4040 return hud;
4041}
4042
4044{
4045 // set up defauld HUD for the ship
4046 NSDictionary* shipDict = [[OOShipRegistry sharedRegistry] shipInfoForKey:[self shipDataKey]];
4047 NSString* hud_desc = [shipDict oo_stringForKey:@"hud" defaultValue:@"hud.plist"];
4048 if (![self switchHudTo:hud_desc])
4049 [self switchHudTo:@"hud.plist"]; // ensure we have a HUD to fall back to
4050}
4051
4052- (BOOL)switchHudTo:(NSString*)hudFileName
4053{
4054 NSDictionary* hudDict = nil;
4055 BOOL wasHidden = NO;
4056 BOOL wasCompassActive = YES;
4057 double scannerZoom = 1.0;
4058 NSUInteger lastMFD = 0;
4059 NSUInteger i;
4060
4061 if (!hudFileName)
4062 return NO;
4063
4064 // is the HUD in the process of being rendered? If yes, set it to defer state and abort the switching now
4065 if (hud != nil && [hud isUpdating]) {
4066 [hud setDeferredHudName:hudFileName];
4067 return NO;
4068 }
4069
4070 hudDict = [ResourceManager dictionaryFromFilesNamed:hudFileName inFolder:@"Config" andMerge:YES];
4071 // hud defined, but buggy?
4072 if (hudDict == nil) {
4073 OOLog(@"PlayerEntity.switchHudTo.failed", @"HUD dictionary file %@ to switch to not found or invalid.", hudFileName);
4074 return NO;
4075 }
4076
4077 if (hud != nil) {
4078 // remember these values
4079 wasHidden = [hud isHidden];
4080 wasCompassActive = [hud isCompassActive];
4081 scannerZoom = [hud scannerZoom];
4082 lastMFD = activeMFD;
4083 }
4084
4085 // buggy oxp could override hud.plist with a non-dictionary.
4086 if (hudDict != nil) {
4087 [hud setHidden:YES]; // hide the hud while rebuilding it.
4088 DESTROY(hud);
4089 hud = [[HeadUpDisplay alloc] initWithDictionary:hudDict inFile:hudFileName];
4090 [hud resetGuis:hudDict];
4091 // reset zoom & hidden to what they were before the swich
4092 [hud setScannerZoom:scannerZoom];
4093 [hud setCompassActive:wasCompassActive];
4094 [hud setHidden:wasHidden];
4095 activeMFD = 0;
4096 NSArray* savedMFDs = [NSArray arrayWithArray:multiFunctionDisplaySettings];
4097 [multiFunctionDisplaySettings removeAllObjects];
4098 for (i = 0; i < [hud mfdCount]; i++) {
4099 if ([savedMFDs count] > i) {
4100 [multiFunctionDisplaySettings addObject:[savedMFDs objectAtIndex:i]];
4101 } else {
4102 [multiFunctionDisplaySettings addObject:[NSNull null]];
4103 }
4104 }
4105 if (lastMFD < [hud mfdCount])
4106 activeMFD = lastMFD;
4107 }
4108
4109 return YES;
4110}
4111
4112- (float)dialCustomFloat:(NSString*)dialKey
4113{
4114 return [customDialSettings oo_floatForKey:dialKey defaultValue:0.0];
4115}
4116
4117- (NSString*)dialCustomString:(NSString*)dialKey
4118{
4119 return [customDialSettings oo_stringForKey:dialKey defaultValue:@""];
4120}
4121
4122- (OOColor*)dialCustomColor:(NSString*)dialKey
4123{
4124 return [OOColor colorWithDescription:[customDialSettings objectForKey:dialKey]];
4125}
4126
4127- (void)setDialCustom:(id)value forKey:(NSString*)dialKey
4128{
4129 [customDialSettings setObject:value forKey:dialKey];
4130}
4131
4132- (void)setShowDemoShips:(BOOL)value
4133{
4134 showDemoShips = value;
4135}
4136
4138{
4139 return showDemoShips;
4140}
4141
4143{
4144 return max_forward_shield;
4145}
4146
4148{
4149 return max_aft_shield;
4150}
4151
4156
4158{
4160}
4161
4162- (void)setMaxForwardShieldLevel:(float)new
4163{
4164 max_forward_shield = new;
4165}
4166
4167- (void)setMaxAftShieldLevel:(float)new
4168{
4169 max_aft_shield = new;
4170}
4171
4172- (void)setForwardShieldRechargeRate:(float)new
4173{
4175}
4176
4177- (void)setAftShieldRechargeRate:(float)new
4178{
4180}
4181
4183{
4184 return forward_shield;
4185}
4186
4188{
4189 return aft_shield;
4190}
4191
4192- (void)setForwardShieldLevel:(GLfloat)level
4193{
4195}
4196
4197- (void)setAftShieldLevel:(GLfloat)level
4198{
4200}
4201
4202- (NSDictionary*)keyConfig
4203{
4204 // return keyconfig_settings;
4205 return keyconfig2_settings;
4206}
4207
4209{
4210 return mouse_control_on;
4211}
4212
4213- (GLfloat)dialRoll
4214{
4215 GLfloat result = flightRoll / max_flight_roll;
4216 if ((result < 1.0f) && (result > -1.0f))
4217 return result;
4218 if (result > 0.0f)
4219 return 1.0f;
4220 return -1.0f;
4221}
4222
4223- (GLfloat)dialPitch
4224{
4225 GLfloat result = flightPitch / max_flight_pitch;
4226 if ((result < 1.0f) && (result > -1.0f))
4227 return result;
4228 if (result > 0.0f)
4229 return 1.0f;
4230 return -1.0f;
4231}
4232
4233- (GLfloat)dialYaw
4234{
4235 GLfloat result = -flightYaw / max_flight_yaw;
4236 if ((result < 1.0f) && (result > -1.0f))
4237 return result;
4238 if (result > 0.0f)
4239 return 1.0f;
4240 return -1.0f;
4241}
4242
4243- (GLfloat)dialSpeed
4244{
4245 GLfloat result = flightSpeed / maxFlightSpeed;
4246 return OOClamp_0_1_f(result);
4247}
4248
4250{
4251 return flightSpeed / maxFlightSpeed;
4252}
4253
4255{
4256 if (EXPECT_NOT([self maxForwardShieldLevel] <= 0)) {
4257 return 0.0;
4258 }
4259 GLfloat result = forward_shield / [self maxForwardShieldLevel];
4260 return OOClamp_0_1_f(result);
4261}
4262
4264{
4265 if (EXPECT_NOT([self maxAftShieldLevel] <= 0)) {
4266 return 0.0;
4267 }
4268 GLfloat result = aft_shield / [self maxAftShieldLevel];
4269 return OOClamp_0_1_f(result);
4270}
4271
4272- (GLfloat)dialEnergy
4273{
4274 GLfloat result = energy / maxEnergy;
4275 return OOClamp_0_1_f(result);
4276}
4277
4279{
4280 return maxEnergy;
4281}
4282
4283- (GLfloat)dialFuel
4284{
4285 if (fuel <= 0.0f)
4286 return 0.0f;
4287 if (fuel > [self fuelCapacity])
4288 return 1.0f;
4289 return (GLfloat)fuel / (GLfloat)[self fuelCapacity];
4290}
4291
4293{
4294 if (target_system_id == system_id && ![UNIVERSE inInterstellarSpace])
4295 return 0.0f;
4296 return [self fuelRequiredForJump] / (GLfloat)PLAYER_MAX_FUEL;
4297}
4298
4300{
4301 GLfloat result = (GLfloat)weapon_temp / (GLfloat)PLAYER_MAX_WEAPON_TEMP;
4302 return OOClamp_0_1_f(result);
4303}
4304
4306{
4307 GLfloat result = aft_weapon_temp / (GLfloat)PLAYER_MAX_WEAPON_TEMP;
4308 return OOClamp_0_1_f(result);
4309}
4310
4312{
4313 GLfloat result = forward_weapon_temp / (GLfloat)PLAYER_MAX_WEAPON_TEMP;
4314 // no need to check subents here
4315 return OOClamp_0_1_f(result);
4316}
4317
4319{
4320 GLfloat result = port_weapon_temp / PLAYER_MAX_WEAPON_TEMP;
4321 return OOClamp_0_1_f(result);
4322}
4323
4325{
4327 return OOClamp_0_1_f(result);
4328}
4329
4331{
4332 if ([self isDocked])
4333 return 0.0f;
4334
4335 // find nearest planet type entity...
4336 assert(UNIVERSE != nil);
4337
4338 Entity* nearestPlanet = [self findNearestStellarBody];
4339 if (nearestPlanet == nil)
4340 return 1.0f;
4341
4342 GLfloat zd = nearestPlanet->zero_distance;
4343 GLfloat cr = nearestPlanet->collision_radius;
4344 GLfloat alt = sqrt(zd) - cr;
4345
4346 return OOClamp_0_1_f(alt / (GLfloat)PLAYER_DIAL_MAX_ALTITUDE);
4347}
4348
4349- (double)clockTime
4350{
4351 return ship_clock;
4352}
4353
4355{
4357}
4358
4360{
4361 return ship_clock_adjust > 0;
4362}
4363
4364- (void)addToAdjustTime:(double)seconds
4365{
4366 ship_clock_adjust += seconds;
4367}
4368
4370{
4372}
4373
4374- (void)setEscapePodRescueTime:(double)seconds
4375{
4376 escape_pod_rescue_time = seconds;
4377}
4378
4379- (NSString*)dial_clock
4380{
4382}
4383
4385{
4387}
4388
4389- (NSString*)dial_fpsinfo
4390{
4391 unsigned fpsVal = fps_counter;
4392 return [NSString stringWithFormat:@"FPS: %3d", fpsVal];
4393}
4394
4395- (NSString*)dial_objinfo
4396{
4397 NSString* result = [NSString stringWithFormat:@"Entities: %3zu", [UNIVERSE entityCount]];
4398#ifdef OO_DEBUG_MONITOR_ENABLED
4399 result = [NSString stringWithFormat:@"%@ (%d, %zu KiB, avg %zu bytes)", result, gLiveEntityCount, gTotalEntityMemory >> 10, gTotalEntityMemory / gLiveEntityCount];
4400#endif
4401
4402 return result;
4403}
4404
4405- (unsigned)countMissiles
4406{
4407 unsigned n_missiles = 0;
4408 unsigned i;
4409 for (i = 0; i < max_missiles; i++) {
4410 if (missile_entity[i])
4411 n_missiles++;
4412 }
4413 return n_missiles;
4414}
4415
4417{
4418 if ([self weaponsOnline]) {
4419 return missile_status;
4420 } else {
4421 // Invariant/safety interlock: weapons offline implies missiles safe. -- Ahruman 2012-07-21
4423 OOLogERR(@"player.missilesUnsafe", @"%@", @"Missile state is not SAFE when weapons are offline. This is a bug, please report it.");
4424 [self safeAllMissiles];
4425 }
4426 return MISSILE_STATUS_SAFE;
4427 }
4428}
4429
4430- (BOOL)canScoop:(ShipEntity*)other
4431{
4432 if (specialCargo)
4433 return NO;
4434 return [super canScoop:other];
4435}
4436
4438{
4439 // need to account for the different ways of calculating cargo on board when docked/in-flight
4440 OOCargoQuantity cargoOnBoard = [self status] == STATUS_DOCKED ? current_cargo : (OOCargoQuantity)[cargo count];
4441 if ([self hasScoop]) {
4442 if (scoopsActive)
4443 return SCOOP_STATUS_ACTIVE;
4444 if (cargoOnBoard >= [self maxAvailableCargoSpace] || specialCargo)
4446 return SCOOP_STATUS_OKAY;
4447 } else {
4449 }
4450}
4451
4453{
4454 return fuel_leak_rate;
4455}
4456
4457- (void)setFuelLeakRate:(float)value
4458{
4459 fuel_leak_rate = fmax(value, 0.0f);
4460}
4461
4462- (NSMutableArray*)commLog
4463{
4465
4466 if (commLog != nil) {
4467 NSUInteger count = [commLog count];
4469 [commLog removeObjectsInRange:NSMakeRange(0, count - kCommLogTrimSize)];
4470 }
4471 } else {
4472 commLog = [[NSMutableArray alloc] init];
4473 }
4474
4475 return commLog;
4476}
4477
4478- (NSMutableArray*)roleWeights
4479{
4480 return roleWeights;
4481}
4482
4483- (void)addRoleForAggression:(ShipEntity*)victim
4484{
4485 if ([victim isExplicitlyUnpiloted] || [victim isHulk] || [victim hasHostileTarget] || [[victim primaryAggressor] isPlayer]) {
4486 return;
4487 }
4488 NSString* role = nil;
4489 if ([[victim primaryRole] isEqualToString:@"escape-capsule"]) {
4490 role = @"assassin-player";
4491 } else if ([victim bounty] > 0) {
4492 role = @"hunter";
4493 } else if ([victim isPirateVictim]) {
4494 role = @"pirate";
4495 } else if ([UNIVERSE role:[self primaryRole] isInCategory:@"oolite-hunter"] || [victim scanClass] == CLASS_POLICE) {
4496 role = @"pirate-interceptor";
4497 }
4498 if (role == nil) {
4499 return;
4500 }
4501 NSUInteger times = [roleWeightFlags oo_intForKey:role defaultValue:0];
4502 times++;
4503 [roleWeightFlags setObject:[NSNumber numberWithUnsignedInteger:times] forKey:role];
4504 if ((times & (times - 1)) == 0) // is power of 2
4505 {
4506 [self addRoleToPlayer:role];
4507 }
4508}
4509
4511{
4512 NSString* role = @"miner";
4513 NSUInteger times = [roleWeightFlags oo_intForKey:role defaultValue:0];
4514 times++;
4515 [roleWeightFlags setObject:[NSNumber numberWithUnsignedInteger:times] forKey:role];
4516 if ((times & (times - 1)) == 0) // is power of 2
4517 {
4518 [self addRoleToPlayer:role];
4519 }
4520}
4521
4522- (void)addRoleToPlayer:(NSString*)role
4523{
4524 NSUInteger slot = Ranrot() & ([self maxPlayerRoles] - 1);
4525 [self addRoleToPlayer:role inSlot:slot];
4526}
4527
4528- (void)addRoleToPlayer:(NSString*)role inSlot:(NSUInteger)slot
4529{
4530 if (slot >= [self maxPlayerRoles]) {
4531 slot = [self maxPlayerRoles] - 1;
4532 }
4533 if (slot >= [roleWeights count]) {
4534 [roleWeights addObject:role];
4535 } else {
4536 [roleWeights replaceObjectAtIndex:slot withObject:role];
4537 }
4538}
4539
4540- (void)clearRoleFromPlayer:(BOOL)includingLongRange
4541{
4542 NSUInteger slot = Ranrot() % [roleWeights count];
4543 if (!includingLongRange) {
4544 NSString* role = [roleWeights objectAtIndex:slot];
4545 // long range roles cleared at 1/2 normal rate
4546 if ([role hasSuffix:@"+"] && randf() > 0.5) {
4547 return;
4548 }
4549 }
4550 [roleWeights replaceObjectAtIndex:slot withObject:@"player-unknown"];
4551}
4552
4553- (void)clearRolesFromPlayer:(float)chance
4554{
4555 NSUInteger i, count = [roleWeights count];
4556 for (i = 0; i < count; i++) {
4557 if (randf() < chance) {
4558 [roleWeights replaceObjectAtIndex:i withObject:@"player-unknown"];
4559 }
4560 }
4561}
4562
4563- (NSUInteger)maxPlayerRoles
4564{
4565 if (ship_kills >= 6400) {
4566 return 32;
4567 } else if (ship_kills >= 128) {
4568 return 16;
4569 } else {
4570 return 8;
4571 }
4572}
4573
4575{
4576 OOSystemID sys = [self currentSystemID];
4577 if (sys < 0) {
4578 return;
4579 }
4580 NSUInteger memory = 4;
4581 if (ship_kills >= 6400) {
4582 memory = 32;
4583 } else if (ship_kills >= 256) {
4584 memory = 16;
4585 } else if (ship_kills >= 64) {
4586 memory = 8;
4587 }
4588 if ([roleSystemList count] >= memory) {
4589 [roleSystemList removeObjectAtIndex:0];
4590 }
4591 [roleSystemList addObject:[NSNumber numberWithInt:sys]];
4592}
4593
4595{
4597 if (result == nil) {
4599 return nil;
4600 }
4601 return result;
4602}
4603
4604- (void)setCompassTarget:(Entity*)value
4605{
4606 [compassTarget release];
4608}
4609
4611{
4612 OOSunEntity* the_sun = [UNIVERSE sun];
4613 OOPlanetEntity* the_planet = [UNIVERSE planet];
4614 StationEntity* the_station = [UNIVERSE station];
4615 Entity* the_target = [self primaryTarget];
4616 Entity<OOBeaconEntity>* beacon = [self nextBeacon];
4617 if ([self isInSpace] && the_sun && the_planet // be in a system
4618 && ![the_sun goneNova]) // and the system has not been novabombed
4619 {
4620 Entity* new_target = nil;
4621 OOAegisStatus aegis = [self checkForAegis];
4622
4623 switch ([self compassMode]) {
4624 case COMPASS_MODE_INACTIVE:
4625 break;
4626
4627 case COMPASS_MODE_BASIC:
4628 if ((aegis == AEGIS_CLOSE_TO_MAIN_PLANET || aegis == AEGIS_IN_DOCKING_RANGE) && the_station) {
4629 new_target = the_station;
4630 } else {
4631 new_target = the_planet;
4632 }
4633 break;
4634
4635 case COMPASS_MODE_PLANET:
4636 new_target = the_planet;
4637 break;
4638
4639 case COMPASS_MODE_STATION:
4640 new_target = the_station;
4641 break;
4642
4643 case COMPASS_MODE_SUN:
4644 new_target = the_sun;
4645 break;
4646
4647 case COMPASS_MODE_TARGET:
4648 new_target = the_target;
4649 break;
4650
4651 case COMPASS_MODE_BEACONS:
4652 new_target = beacon;
4653 break;
4654 }
4655
4656 if (new_target == nil || [new_target status] < STATUS_ACTIVE || [new_target status] == STATUS_IN_HOLD) {
4657 [self setCompassMode:COMPASS_MODE_PLANET];
4658 new_target = the_planet;
4659 }
4660
4661 if (EXPECT_NOT(new_target != [self compassTarget])) {
4662 [self setCompassTarget:new_target];
4663 [self doScriptEvent:OOJSID("compassTargetChanged") withArguments:[NSArray arrayWithObjects:new_target, OOStringFromCompassMode([self compassMode]), nil]];
4664 }
4665 }
4666}
4667
4669{
4670 switch (compassMode) {
4671 case COMPASS_MODE_INACTIVE:
4672 return @"";
4673 case COMPASS_MODE_BASIC:
4674 return @"";
4675 case COMPASS_MODE_BEACONS: {
4676 Entity* target = [self compassTarget];
4677 if (target) {
4678 return [(Entity<OOBeaconEntity>*)target beaconLabel];
4679 }
4680 return @"";
4681 }
4682 case COMPASS_MODE_PLANET:
4683 return [[UNIVERSE planet] name];
4684 case COMPASS_MODE_SUN:
4685 return [[UNIVERSE sun] name];
4686 case COMPASS_MODE_STATION:
4687 return [[UNIVERSE station] displayName];
4688 case COMPASS_MODE_TARGET:
4689 return DESC(@"oolite-beacon-label-target");
4690 }
4691 return @"";
4692}
4693
4695{
4696 return compassMode;
4697}
4698
4699- (void)setCompassMode:(OOCompassMode)value
4700{
4701 compassMode = value;
4702}
4703
4705{
4706 OOAegisStatus aegis = AEGIS_NONE;
4707 Entity<OOBeaconEntity>* beacon = nil;
4708
4709 switch (compassMode) {
4710 case COMPASS_MODE_INACTIVE:
4711 case COMPASS_MODE_BASIC:
4712 case COMPASS_MODE_PLANET:
4713 beacon = [UNIVERSE lastBeacon];
4714 while (beacon != nil && [beacon isJammingScanning]) {
4715 beacon = [beacon prevBeacon];
4716 }
4717 [self setNextBeacon:beacon];
4718
4719 if (beacon != nil) {
4720 [self setCompassMode:COMPASS_MODE_BEACONS];
4721 break;
4722 }
4723 // else fall through to switch to target mode.
4724
4725 case COMPASS_MODE_BEACONS:
4726 beacon = [self nextBeacon];
4727 do {
4728 beacon = [beacon prevBeacon];
4729 } while (beacon != nil && [beacon isJammingScanning]);
4730 [self setNextBeacon:beacon];
4731
4732 if (beacon == nil) {
4733 if ([self primaryTarget]) {
4734 [self setCompassMode:COMPASS_MODE_TARGET];
4735 } else {
4736 [self setCompassMode:COMPASS_MODE_SUN];
4737 }
4738 break;
4739 }
4740 break;
4741
4742 case COMPASS_MODE_TARGET:
4743 [self setCompassMode:COMPASS_MODE_SUN];
4744 break;
4745
4746 case COMPASS_MODE_SUN:
4747 aegis = [self checkForAegis];
4748 if (aegis == AEGIS_CLOSE_TO_MAIN_PLANET || aegis == AEGIS_IN_DOCKING_RANGE) {
4749 [self setCompassMode:COMPASS_MODE_STATION];
4750 } else {
4751 [self setCompassMode:COMPASS_MODE_PLANET];
4752 }
4753 break;
4754
4755 case COMPASS_MODE_STATION:
4756 [self setCompassMode:COMPASS_MODE_PLANET];
4757 break;
4758 }
4759}
4760
4762{
4763 OOAegisStatus aegis = AEGIS_NONE;
4764 Entity<OOBeaconEntity>* beacon = nil;
4765
4766 switch (compassMode) {
4767 case COMPASS_MODE_INACTIVE:
4768 case COMPASS_MODE_BASIC:
4769 case COMPASS_MODE_PLANET:
4770 aegis = [self checkForAegis];
4771 if ([UNIVERSE station] && (aegis == AEGIS_CLOSE_TO_MAIN_PLANET || aegis == AEGIS_IN_DOCKING_RANGE)) {
4772 [self setCompassMode:COMPASS_MODE_STATION];
4773 } else {
4774 [self setCompassMode:COMPASS_MODE_SUN];
4775 }
4776 break;
4777
4778 case COMPASS_MODE_STATION:
4779 [self setCompassMode:COMPASS_MODE_SUN];
4780 break;
4781
4782 case COMPASS_MODE_SUN:
4783 if ([self primaryTarget]) {
4784 [self setCompassMode:COMPASS_MODE_TARGET];
4785 break;
4786 }
4787 // else fall through to switch to beacon mode.
4788
4789 case COMPASS_MODE_TARGET:
4790 beacon = [UNIVERSE firstBeacon];
4791 while (beacon != nil && [beacon isJammingScanning]) {
4792 beacon = [beacon nextBeacon];
4793 }
4794 [self setNextBeacon:beacon];
4795
4796 if (beacon != nil)
4797 [self setCompassMode:COMPASS_MODE_BEACONS];
4798 else
4799 [self setCompassMode:COMPASS_MODE_PLANET];
4800 break;
4801
4802 case COMPASS_MODE_BEACONS:
4803 beacon = [self nextBeacon];
4804 do {
4805 beacon = [beacon nextBeacon];
4806 } while (beacon != nil && [beacon isJammingScanning]);
4807 [self setNextBeacon:beacon];
4808
4809 if (beacon == nil) {
4810 [self setCompassMode:COMPASS_MODE_PLANET];
4811 }
4812 break;
4813 }
4814}
4815
4816- (NSUInteger)activeMissile
4817{
4818 return activeMissile;
4819}
4820
4821- (void)setActiveMissile:(NSUInteger)value
4822{
4823 activeMissile = value;
4824}
4825
4826- (NSUInteger)dialMaxMissiles
4827{
4828 return max_missiles;
4829}
4830
4832{
4833 return ident_engaged;
4834}
4835
4836- (void)setDialIdentEngaged:(BOOL)newValue
4837{
4838 ident_engaged = !!newValue;
4839}
4840
4841- (NSString*)specialCargo
4842{
4843 return specialCargo;
4844}
4845
4846- (NSString*)dialTargetName
4847{
4848 Entity* target_entity = [self primaryTarget];
4849 NSString* result = nil;
4850
4851 if (target_entity == nil) {
4852 result = DESC(@"no-target-string");
4853 }
4854
4855 if ([target_entity respondsToSelector:@selector(identFromShip:)]) {
4856 result = [(ShipEntity*)target_entity identFromShip:self];
4857 }
4858
4859 if (result == nil)
4860 result = DESC(@"unknown-target");
4861
4862 return result;
4863}
4864
4866{
4868}
4869
4870- (NSString*)multiFunctionText:(NSUInteger)i
4871{
4872 NSString* key = [multiFunctionDisplaySettings oo_stringAtIndex:i defaultValue:nil];
4873 if (key == nil) {
4874 return nil;
4875 }
4876 NSString* text = [multiFunctionDisplayText oo_stringForKey:key defaultValue:nil];
4877 return text;
4878}
4879
4880- (void)setMultiFunctionText:(NSString*)text forKey:(NSString*)key
4881{
4882 if (text != nil) {
4883 [multiFunctionDisplayText setObject:text forKey:key];
4884 } else if (key != nil) {
4885 [multiFunctionDisplayText removeObjectForKey:key];
4886 // and blank any MFDs currently using it
4887 NSUInteger index;
4888 while ((index = [multiFunctionDisplaySettings indexOfObject:key]) != NSNotFound) {
4889 [multiFunctionDisplaySettings replaceObjectAtIndex:index withObject:[NSNull null]];
4890 }
4891 }
4892}
4893
4894- (BOOL)setMultiFunctionDisplay:(NSUInteger)index toKey:(NSString*)key
4895{
4896 if (index >= [hud mfdCount]) {
4897 // is first inactive display
4898 index = [multiFunctionDisplaySettings indexOfObject:[NSNull null]];
4899 if (index == NSNotFound) {
4900 return NO;
4901 }
4902 }
4903
4904 if (index < [hud mfdCount]) {
4905 if (key == nil) {
4906 [multiFunctionDisplaySettings replaceObjectAtIndex:index withObject:[NSNull null]];
4907 } else {
4908 [multiFunctionDisplaySettings replaceObjectAtIndex:index withObject:key];
4909 }
4910 return YES;
4911 } else {
4912 return NO;
4913 }
4914}
4915
4916- (void)cycleNextMultiFunctionDisplay:(NSUInteger)index
4917{
4918 if ([[self hud] mfdCount] == 0)
4919 return;
4920 NSArray* keys = [multiFunctionDisplayText allKeys];
4921 NSString* key = nil;
4922 if ([keys count] == 0) {
4923 [self setMultiFunctionDisplay:index toKey:nil];
4924 return;
4925 }
4926 id current = [multiFunctionDisplaySettings objectAtIndex:index];
4927 if (current == [NSNull null]) {
4928 key = [keys objectAtIndex:0];
4929 [self setMultiFunctionDisplay:index toKey:key];
4930 } else {
4931 NSUInteger cIndex = [keys indexOfObject:current];
4932 if (cIndex == NSNotFound || cIndex + 1 >= [keys count]) {
4933 key = nil;
4934 [self setMultiFunctionDisplay:index toKey:nil];
4935 } else {
4936 key = [keys objectAtIndex:(cIndex + 1)];
4937 [self setMultiFunctionDisplay:index toKey:key];
4938 }
4939 }
4940 JSContext* context = OOJSAcquireContext();
4941 OOJSVal keyVal = OOJSValueFromNativeObject(context, key);
4942 ShipScriptEvent(context, self, "mfdKeyChanged", OOJSValueFromDouble(context, activeMFD), keyVal);
4943 OOJSRelinquishContext(context);
4944}
4945
4946- (void)cyclePreviousMultiFunctionDisplay:(NSUInteger)index
4947{
4948 if ([[self hud] mfdCount] == 0)
4949 return;
4950 NSArray* keys = [multiFunctionDisplayText allKeys];
4951 NSString* key = nil;
4952 if ([keys count] == 0) {
4953 [self setMultiFunctionDisplay:index toKey:nil];
4954 return;
4955 }
4956 id current = [multiFunctionDisplaySettings objectAtIndex:index];
4957 if (current == [NSNull null]) {
4958 key = [keys objectAtIndex:([keys count] - 1)];
4959 [self setMultiFunctionDisplay:index toKey:key];
4960 } else {
4961 NSUInteger cIndex = [keys indexOfObject:current];
4962 if (cIndex == NSNotFound || cIndex == 0) {
4963 key = nil;
4964 [self setMultiFunctionDisplay:index toKey:nil];
4965 } else {
4966 key = [keys objectAtIndex:(cIndex - 1)];
4967 [self setMultiFunctionDisplay:index toKey:key];
4968 }
4969 }
4970 JSContext* context = OOJSAcquireContext();
4971 OOJSVal keyVal = OOJSValueFromNativeObject(context, key);
4972 ShipScriptEvent(context, self, "mfdKeyChanged", OOJSValueFromDouble(context, activeMFD), keyVal);
4973 OOJSRelinquishContext(context);
4974}
4975
4977{
4978 if ([[self hud] mfdCount] == 0)
4979 return;
4980 activeMFD = (activeMFD + 1) % [[self hud] mfdCount];
4981 NSUInteger mfdID = activeMFD + 1;
4982 [UNIVERSE addMessage:OOExpandKey(@"mfd-N-selected", mfdID) forCount:3.0];
4983 JSContext* context = OOJSAcquireContext();
4984 ShipScriptEvent(context, self, "selectedMFDChanged", OOJSValueFromDouble(context, activeMFD));
4985 OOJSRelinquishContext(context);
4986}
4987
4989{
4990 if ([[self hud] mfdCount] == 0)
4991 return;
4992 if (activeMFD == 0) {
4993 activeMFD = ([[self hud] mfdCount] - 1);
4994 } else {
4995 activeMFD = (activeMFD - 1);
4996 }
4997 NSUInteger mfdID = activeMFD + 1;
4998 [UNIVERSE addMessage:OOExpandKey(@"mfd-N-selected", mfdID) forCount:3.0];
4999 JSContext* context = OOJSAcquireContext();
5000 ShipScriptEvent(context, self, "selectedMFDChanged", OOJSValueFromDouble(context, activeMFD));
5001 OOJSRelinquishContext(context);
5002}
5003
5004- (NSUInteger)activeMFD
5005{
5006 return activeMFD;
5007}
5008
5009- (ShipEntity*)missileForPylon:(NSUInteger)value
5010{
5011 if (value < max_missiles)
5012 return missile_entity[value];
5013 return nil;
5014}
5015
5017{
5018 // sets all missile targets to NO_TARGET
5019
5020 unsigned i;
5021 for (i = 0; i < max_missiles; i++) {
5024 }
5026}
5027
5029{
5030 // Make sure there's no gaps between missiles, synchronise missile_entity & missile_list.
5031 int i, pylon = 0;
5032 OOLog(@"missile.tidying.debug", @"Tidying fitted %d of possible %d missiles", missiles, PLAYER_MAX_MISSILES);
5033 for (i = 0; i < PLAYER_MAX_MISSILES; i++) {
5034 OOLog(@"missile.tidying.debug", @"%d %@ %@", i, missile_entity[i], missile_list[i]);
5035 if (missile_entity[i] != nil) {
5038 pylon++;
5039 }
5040 }
5041
5042 // Now clean up the remainder of the pylons.
5043 for (i = pylon; i < PLAYER_MAX_MISSILES; i++) {
5044 missile_entity[i] = nil;
5045 // not strictly needed, but helps clear things up
5046 missile_list[i] = nil;
5047 }
5048}
5049
5051{
5052 if (![self weaponsOnline])
5053 return;
5054
5055 unsigned i;
5056 for (i = 1; i < max_missiles; i++) {
5057 int next_missile = (activeMissile + i) % max_missiles;
5058 if (missile_entity[next_missile]) {
5059 // If we don't have the multi-targeting module installed, clear the active missiles' target
5060 if (![self hasEquipmentItemProviding:@"EQ_MULTI_TARGET"] && [missile_entity[activeMissile] isMissile]) {
5061 [missile_entity[activeMissile] removeTarget:nil];
5062 }
5063
5064 // Set next missile to active
5065 [self setActiveMissile:next_missile];
5066
5069
5070 // If the newly active pylon contains a missile then work out its target, if any
5072 if ([self hasEquipmentItemProviding:@"EQ_MULTI_TARGET"] && ([missile_entity[next_missile] primaryTarget] != nil)) {
5073 // copy the missile's target
5076 } else if ([self primaryTarget] != nil) {
5077 // never inherit target if we have EQ_MULTI_TARGET installed! [ Bug #16221 : Targeting enhancement regression ]
5078 /* CIM: seems okay to do this when launching a
5079 * missile to stop multi-target being a bit
5080 * irritating in a fight - 20/8/2014 */
5081 if ([self hasEquipmentItemProviding:@"EQ_MULTI_TARGET"] && !launchingMissile) {
5082 [self noteLostTarget];
5084 } else {
5085 [missile_entity[activeMissile] addTarget:[self primaryTarget]];
5087 }
5088 }
5089 }
5090 }
5091 return;
5092 }
5093 }
5094}
5095
5097{
5098 alertFlags = 0;
5099}
5100
5102{
5103 return alertFlags;
5104}
5105
5106- (void)setAlertFlag:(int)flag to:(BOOL)value
5107{
5108 if (value) {
5109 alertFlags |= flag;
5110 } else {
5111 int comp = ~flag;
5112 alertFlags &= comp;
5113 }
5114}
5115
5116// used by Javascript and the distinction is important for NPCs
5118{
5119 return [self alertCondition];
5120}
5121
5123{
5124 OOAlertCondition old_alert_condition = alertCondition;
5126
5127 [self setAlertFlag:ALERT_FLAG_DOCKED to:[self status] == STATUS_DOCKED];
5128
5131 } else {
5132 if (alertFlags != 0) {
5134 }
5137 }
5138 }
5139 if ((alertCondition == ALERT_CONDITION_RED) && (old_alert_condition < ALERT_CONDITION_RED)) {
5140 [self playAlertConditionRed];
5141 }
5142
5143 return alertCondition;
5144}
5145
5150
5152
5153- (void)interpretAIMessage:(NSString*)ms
5154{
5155 if ([ms isEqual:@"HOLD_FULL"]) {
5156 [self playHoldFull];
5157 [UNIVERSE addMessage:DESC(@"hold-full") forCount:4.5];
5158 }
5159
5160 if ([ms isEqual:@"INCOMING_MISSILE"]) {
5161 if ([self primaryAggressor] != nil) {
5162 [self playIncomingMissile:HPVectorToVector([[self primaryAggressor] position])];
5163 } else {
5164 [self playIncomingMissile:kZeroVector];
5165 }
5166 [UNIVERSE addMessage:DESC(@"incoming-missile") forCount:4.5];
5167 }
5168
5169 if ([ms isEqual:@"ENERGY_LOW"]) {
5170 [UNIVERSE addMessage:DESC(@"energy-low") forCount:6.0];
5171 }
5172
5173 if ([ms isEqual:@"ECM"] && ![self isDocked])
5174 [self playHitByECMSound];
5175
5176 if ([ms isEqual:@"DOCKING_REFUSED"] && [self status] == STATUS_AUTOPILOT_ENGAGED) {
5177 [self playDockingDenied];
5178 [UNIVERSE addMessage:DESC(@"autopilot-denied") forCount:4.5];
5179 autopilot_engaged = NO;
5180 [self resetAutopilotAI];
5182 [self setStatus:STATUS_IN_FLIGHT];
5184 [self doScriptEvent:OOJSID("playerDockingRefused")];
5185 }
5186
5187 // aegis messages to advanced compass so in planet mode it behaves like the old compass
5188 if (compassMode != COMPASS_MODE_BASIC) {
5189 if ([ms isEqual:@"AEGIS_CLOSE_TO_MAIN_PLANET"] && (compassMode == COMPASS_MODE_PLANET)) {
5191 [self setCompassMode:COMPASS_MODE_STATION];
5192 }
5193 if ([ms isEqual:@"AEGIS_IN_DOCKING_RANGE"] && (compassMode == COMPASS_MODE_PLANET)) {
5195 [self setCompassMode:COMPASS_MODE_STATION];
5196 }
5197 if ([ms isEqual:@"AEGIS_NONE"] && (compassMode == COMPASS_MODE_STATION)) {
5198 [self setCompassMode:COMPASS_MODE_PLANET];
5199 }
5200 }
5201}
5202
5203- (BOOL)mountMissile:(ShipEntity*)missile
5204{
5205 if (missile == nil)
5206 return NO;
5207
5208 unsigned i;
5209 for (i = 0; i < max_missiles; i++) {
5210 if (missile_entity[i] == nil) {
5211 missile_entity[i] = [missile retain];
5213 missiles++;
5214 if (missiles == 1)
5215 [self setActiveMissile:0]; // auto select the first purchased missile
5216 return YES;
5217 }
5218 }
5219
5220 return NO;
5221}
5222
5223- (BOOL)mountMissileWithRole:(NSString*)role
5224{
5225 if ([self missileCount] >= [self missileCapacity])
5226 return NO;
5227 return [self mountMissile:[[UNIVERSE newShipWithRole:role] autorelease]];
5228}
5229
5231{
5232 ShipEntity* missile = missile_entity[activeMissile]; // retain count is 1
5233 NSString* identifier = [missile primaryRole];
5234 ShipEntity* firedMissile = nil;
5235
5236 if (missile == nil)
5237 return nil;
5238
5239 if (![self weaponsOnline])
5240 return nil;
5241
5242 // check if we were cloaked before firing the missile - can't use
5243 // cloaking_device_active directly because fireMissilewithIdentifier: andTarget:
5244 // will reset it in case passive cloak is set - Nikos 20130313
5245 BOOL cloakedPriorToFiring = cloaking_device_active;
5246
5247 launchingMissile = YES;
5248 replacingMissile = NO;
5249
5250 if ([missile isMine] && (missile_status != MISSILE_STATUS_SAFE)) {
5251 firedMissile = [self launchMine:missile];
5252 if (!replacingMissile)
5253 [self removeFromPylon:activeMissile];
5254 if (firedMissile != nil)
5255 [self playMineLaunched:[self missileLaunchPosition] weaponIdentifier:identifier];
5256 } else {
5258 return nil;
5259 // release this before creating it anew in fireMissileWithIdentifier
5260 firedMissile = [self fireMissileWithIdentifier:identifier andTarget:[missile primaryTarget]];
5261
5262 if (firedMissile != nil) {
5263 if (!replacingMissile)
5264 [self removeFromPylon:activeMissile];
5265 [self playMissileLaunched:[self missileLaunchPosition] weaponIdentifier:identifier];
5266 }
5267 }
5268
5269 if (cloakedPriorToFiring && cloakPassive) {
5270 // fireMissilewithIdentifier: andTarget: has already taken care of deactivating
5271 // the cloak in the case of missiles by the time we get here, but explicitly
5272 // calling deactivateCloakingDevice is needed in order to be covered fully with mines too
5274 }
5275
5276 replacingMissile = NO;
5277 launchingMissile = NO;
5278
5279 return firedMissile;
5280}
5281
5282- (ShipEntity*)launchMine:(ShipEntity*)mine
5283{
5284 if (!mine)
5285 return nil;
5286
5287 if (![self weaponsOnline])
5288 return nil;
5289
5290 [mine setOwner:self];
5291 [mine setBehaviour:BEHAVIOUR_IDLE];
5292 [self dumpItem:mine]; // includes UNIVERSE addEntity: CLASS_CARGO, STATUS_IN_FLIGHT, AI state GLOBAL ( the last one starts the timer !)
5293 [mine setScanClass:CLASS_MINE];
5294
5295 float mine_speed = 500.0f;
5296 Vector mvel = vector_subtract([mine velocity], vector_multiply_scalar(v_forward, mine_speed));
5297 [mine setVelocity:mvel];
5298 [self doScriptEvent:OOJSID("shipReleasedEquipment") withArgument:mine];
5299 return mine;
5300}
5301
5302- (BOOL)assignToActivePylon:(NSString*)equipmentKey
5303{
5304 if (!launchingMissile)
5305 return NO;
5306
5307 OOEquipmentType* eqType = nil;
5308
5309 if ([equipmentKey hasSuffix:@"_DAMAGED"]) {
5310 return NO;
5311 } else {
5312 eqType = [OOEquipmentType equipmentTypeWithIdentifier:equipmentKey];
5313 }
5314
5315 // missiles with techlevel above 99 (kOOVariableTechLevel) are never available to the player
5316 if (![eqType isMissileOrMine] || [eqType effectiveTechLevel] > kOOVariableTechLevel) {
5317 return NO;
5318 }
5319
5320 ShipEntity* amiss = [UNIVERSE newShipWithRole:equipmentKey];
5321
5322 if (!amiss)
5323 return NO;
5324
5325 // replace the missile now.
5326 [missile_entity[activeMissile] release];
5327 missile_entity[activeMissile] = amiss;
5328 missile_list[activeMissile] = eqType;
5329
5330 // make sure the new missile is properly activated.
5331 if (activeMissile > 0)
5332 activeMissile--;
5333 else
5335 [self selectNextMissile];
5336
5337 replacingMissile = YES;
5338
5339 return YES;
5340}
5341
5343{
5344 if (![self hasCloakingDevice])
5345 return NO;
5346
5347 if ([super activateCloakingDevice]) {
5348 [UNIVERSE setCurrentPostFX:OO_POSTFX_CLOAK];
5349 [UNIVERSE addMessage:DESC(@"cloak-on") forCount:2];
5350 [self playCloakingDeviceOn];
5351 return YES;
5352 } else {
5353 [UNIVERSE addMessage:DESC(@"cloak-low-juice") forCount:3];
5355 return NO;
5356 }
5357}
5358
5360{
5361 if (![self hasCloakingDevice])
5362 return;
5363
5365 [UNIVERSE terminatePostFX:OO_POSTFX_CLOAK];
5366 [UNIVERSE addMessage:DESC(@"cloak-off") forCount:2];
5367 [self playCloakingDeviceOff];
5368}
5369
5370/* Scanner fuzziness is entirely cosmetic - it doesn't affect the
5371 * player's actual target locks */
5373{
5374 double fuzz = 0.0;
5375
5376 /* Fuzziness from ECM bursts */
5377 if (last_ecm_time > 0.0) {
5378 double since = [UNIVERSE getTime] - last_ecm_time;
5379 if (since < SCANNER_ECM_FUZZINESS) {
5380 fuzz += (SCANNER_ECM_FUZZINESS - since) * (SCANNER_ECM_FUZZINESS - since) * 500.0;
5381 }
5382 }
5383 /* Other causes could go here */
5384
5385 return fuzz;
5386}
5387
5389{
5390 last_ecm_time = [UNIVERSE getTime];
5391}
5392
5393- (BOOL)fireECM
5394{
5395 if ([super fireECM]) {
5396 ecm_in_operation = YES;
5397 ecm_start_time = [UNIVERSE getTime];
5398 return YES;
5399 } else {
5400 return NO;
5401 }
5402}
5403
5405{
5406 if ([self hasEquipmentItem:@"EQ_NAVAL_ENERGY_UNIT"])
5407 return ENERGY_UNIT_NAVAL;
5408 if ([self hasEquipmentItem:@"EQ_ENERGY_UNIT"])
5409 return ENERGY_UNIT_NORMAL;
5410 return ENERGY_UNIT_NONE;
5411}
5412
5414{
5415 if ([self hasEquipmentItem:@"EQ_NAVAL_ENERGY_UNIT"])
5416 return ENERGY_UNIT_NAVAL;
5417 if ([self hasEquipmentItem:@"EQ_ENERGY_UNIT"])
5418 return ENERGY_UNIT_NORMAL;
5419 if ([self hasEquipmentItem:@"EQ_NAVAL_ENERGY_UNIT_DAMAGED"])
5421 if ([self hasEquipmentItem:@"EQ_ENERGY_UNIT_DAMAGED"])
5423 return ENERGY_UNIT_NONE;
5424}
5425
5427{
5429 // Did find & correct a minor mismatch between player and NPC weapon stats. This is the resulting code - Kaks 20101027
5430
5431 // Basic stats: weapon_damage & weaponRange (weapon_recharge_rate is not used by the player)
5432 [self setWeaponDataFromType:currentWeapon];
5433}
5434
5436{
5437 return weapons_online;
5438}
5439
5440- (void)setWeaponsOnline:(BOOL)newValue
5441{
5442 weapons_online = !!newValue;
5443 if (!weapons_online)
5444 [self safeAllMissiles];
5445}
5446
5448{
5449 return [self laserPortOffset:currentWeaponFacing];
5450}
5451
5453{
5454 OOWeaponType weapon_to_be_fired = [self currentWeapon];
5455
5456 if (![self weaponsOnline]) {
5457 return NO;
5458 }
5459
5461 [self playWeaponOverheated:[[self currentLaserOffset] oo_vectorAtIndex:0]];
5462 [UNIVERSE addMessage:DESC(@"weapon-overheat") forCount:3.0];
5463 return NO;
5464 }
5465
5466 if (isWeaponNone(weapon_to_be_fired)) {
5467 return NO;
5468 }
5469
5470 [self currentWeaponStats];
5471
5472 NSUInteger multiplier = 1;
5473 if (_multiplyWeapons) {
5474 // multiple fitted
5475 multiplier = [[self laserPortOffset:currentWeaponFacing] count];
5476 }
5477
5478 if (energy <= weapon_energy_use * multiplier) {
5479 [UNIVERSE addMessage:DESC(@"weapon-out-of-juice") forCount:3.0];
5480 return NO;
5481 }
5482
5484
5485 energy -= weapon_energy_use * multiplier;
5486
5487 switch (currentWeaponFacing) {
5490 forward_shot_time = 0.0;
5491 break;
5492
5493 case WEAPON_FACING_AFT:
5495 aft_shot_time = 0.0;
5496 break;
5497
5498 case WEAPON_FACING_PORT:
5500 port_shot_time = 0.0;
5501 break;
5502
5505 starboard_shot_time = 0.0;
5506 break;
5507
5508 case WEAPON_FACING_NONE:
5509 break;
5510 }
5511
5512 BOOL weaponFired = NO;
5513 if (!isWeaponNone(weapon_to_be_fired)) {
5514 if (![weapon_to_be_fired isTurretLaser]) {
5515 [self fireLaserShotInDirection:currentWeaponFacing weaponIdentifier:[[self currentWeapon] identifier]];
5516 weaponFired = YES;
5517 } else {
5518 // nothing: compatible with previous versions
5519 }
5520 }
5521
5522 if (weaponFired && cloaking_device_active && cloakPassive) {
5524 }
5525
5526 return weaponFired;
5527}
5528
5529- (OOWeaponType)weaponForFacing:(OOWeaponFacing)facing
5530{
5531 switch (facing) {
5533 return forward_weapon_type;
5534
5535 case WEAPON_FACING_AFT:
5536 return aft_weapon_type;
5537
5538 case WEAPON_FACING_PORT:
5539 return port_weapon_type;
5540
5542 return starboard_weapon_type;
5543
5544 case WEAPON_FACING_NONE:
5545 break;
5546 }
5547 return nil;
5548}
5549
5551{
5552 return [self weaponForFacing:currentWeaponFacing];
5553}
5554
5555// override ShipEntity definition to ensure that
5556// if shields are still up, always hit the main entity and take the damage
5557// on the shields
5558- (GLfloat)doesHitLine:(HPVector)v0 v1:(HPVector)v1 hitEntity:(ShipEntity**)hitEntity
5559{
5560 if (hitEntity)
5561 hitEntity[0] = (ShipEntity*)nil;
5562 Vector u0 = HPVectorToVector(HPvector_between(position, v0)); // relative to origin of model / octree
5564 Vector w0 = make_vector(dot_product(u0, v_right), dot_product(u0, v_up), dot_product(u0, v_forward)); // in ijk vectors
5566 GLfloat hit_distance = [octree isHitByLine:w0 v1:w1];
5567 if (hit_distance) {
5568 if (hitEntity)
5569 hitEntity[0] = self;
5570 }
5571
5572 bool shields = false;
5573 if ((w0.z >= 0 && forward_shield > 1) || (w0.z <= 0 && aft_shield > 1)) {
5574 shields = true;
5575 }
5576
5577 NSEnumerator* subEnum = nil;
5578 ShipEntity* se = nil;
5579 for (subEnum = [self shipSubEntityEnumerator]; (se = [subEnum nextObject]);) {
5582 u0 = HPVectorToVector(HPvector_between(p0, v0));
5583 u1 = HPVectorToVector(HPvector_between(p0, v1));
5584 w0 = resolveVectorInIJK(u0, ijk);
5585 w1 = resolveVectorInIJK(u1, ijk);
5586
5587 GLfloat hitSub = [se->octree isHitByLine:w0 v1:w1];
5588 if (hitSub && (hit_distance == 0 || hit_distance > hitSub)) {
5589 hit_distance = hitSub;
5590 if (hitEntity && !shields) {
5591 *hitEntity = se;
5592 }
5593 }
5594 }
5595
5596 return hit_distance;
5597}
5598
5599- (void)takeEnergyDamage:(double)amount from:(Entity*)ent becauseOf:(Entity*)other weaponIdentifier:(NSString*)weaponIdentifier
5600{
5601 HPVector rel_pos;
5602 OOScalar d_forward, d_right, d_up;
5603 BOOL internal_damage = NO; // base chance
5604
5605 OOLog(@"player.ship.damage", @"Player took damage from %@ becauseOf %@", ent, other);
5606
5607 if ([self status] == STATUS_DEAD)
5608 return;
5609 if ([self status] == STATUS_ESCAPE_SEQUENCE)
5610 return; // if the player has ejected, don't deal more damage
5611 if (amount == 0.0)
5612 return;
5613
5614 BOOL cascadeWeapon = [ent isCascadeWeapon];
5615 BOOL cascading = NO;
5616 if (cascadeWeapon) {
5617 cascading = [self cascadeIfAppropriateWithDamageAmount:amount cascadeOwner:[ent owner]];
5618 }
5619
5620 // make sure ent (& its position) is the attacking _ship_/missile !
5621 if (ent && [ent isSubEntity])
5622 ent = [ent owner];
5623
5624 [[ent retain] autorelease];
5625 [[other retain] autorelease];
5626
5627 rel_pos = (ent != nil) ? [ent position] : kZeroHPVector;
5628 rel_pos = HPvector_subtract(rel_pos, position);
5629
5630 [self doScriptEvent:OOJSID("shipBeingAttacked") withArgument:ent];
5631 if ([ent isShip])
5632 [(ShipEntity*)ent doScriptEvent:OOJSID("shipAttackedOther") withArgument:self];
5633
5634 d_forward = dot_product(HPVectorToVector(rel_pos), v_forward);
5635 d_right = dot_product(HPVectorToVector(rel_pos), v_right);
5636 d_up = dot_product(HPVectorToVector(rel_pos), v_up);
5637 Vector relative = make_vector(d_right, d_up, d_forward);
5638
5639 [self playShieldHit:relative weaponIdentifier:weaponIdentifier];
5640
5641 // firing on an innocent ship is an offence
5642 if ([other isShip]) {
5643 [self broadcastHitByLaserFrom:(ShipEntity*)other];
5644 }
5645
5646 if (d_forward >= 0) {
5647 forward_shield -= amount;
5648 if (forward_shield < 0.0) {
5649 amount = -forward_shield;
5650 forward_shield = 0.0f;
5651 } else {
5652 amount = 0.0;
5653 }
5654 } else {
5655 aft_shield -= amount;
5656 if (aft_shield < 0.0) {
5657 amount = -aft_shield;
5658 aft_shield = 0.0f;
5659 } else {
5660 amount = 0.0;
5661 }
5662 }
5663
5664 OOShipDamageType damageType = cascadeWeapon ? kOODamageTypeCascadeWeapon : kOODamageTypeEnergy;
5665
5666 if (amount > 0.0) {
5667 energy -= amount;
5668 [self playDirectHit:relative weaponIdentifier:weaponIdentifier];
5670 /* Heat increase from energy impacts will never directly cause
5671 * overheating - too easy for missile hits to cause an uncredited
5672 * death by overheating against NPCs, so same rules for player */
5676 }
5677 }
5678 }
5679 [self noteTakingDamage:amount from:other type:damageType];
5680 if (cascading)
5681 energy = 0.0; // explicitly set energy to zero when cascading, in case an oxp raised the energy in noteTakingDamage.
5682
5683 if (energy <= 0.0) // use normal ship temperature calculations for heat damage
5684 {
5685 if ([other isShip]) {
5687 }
5688
5689 [self getDestroyedBy:other damageType:damageType];
5690 } else {
5691 while (amount > 0.0) {
5692 internal_damage = ((ranrot_rand() & PLAYER_INTERNAL_DAMAGE_FACTOR) < amount); // base chance of damage to systems
5693 if (internal_damage) {
5694 [self takeInternalDamage];
5695 }
5696 amount -= (PLAYER_INTERNAL_DAMAGE_FACTOR + 1);
5697 }
5698 }
5699}
5700
5701- (void)takeScrapeDamage:(double)amount from:(Entity*)ent
5702{
5703 HPVector rel_pos;
5704 OOScalar d_forward, d_right, d_up;
5705 BOOL internal_damage = NO; // base chance
5706
5707 if ([self status] == STATUS_DEAD)
5708 return;
5709
5710 if (amount < 0) {
5711 OOLog(@"player.ship.damage", @"Player took negative scrape damage %.3f so we made it positive", amount);
5712 amount = -amount;
5713 }
5714 OOLog(@"player.ship.damage", @"Player took %.3f scrape damage from %@", amount, ent);
5715
5716 [[ent retain] autorelease];
5717 rel_pos = ent ? [ent position] : kZeroHPVector;
5718 rel_pos = HPvector_subtract(rel_pos, position);
5719 // rel_pos is now small
5720 d_forward = dot_product(HPVectorToVector(rel_pos), v_forward);
5721 d_right = dot_product(HPVectorToVector(rel_pos), v_right);
5722 d_up = dot_product(HPVectorToVector(rel_pos), v_up);
5723 Vector relative = make_vector(d_right, d_up, d_forward);
5724
5725 [self playScrapeDamage:relative];
5726 if (d_forward >= 0) {
5727 forward_shield -= amount;
5728 if (forward_shield < 0.0) {
5729 amount = -forward_shield;
5730 forward_shield = 0.0f;
5731 } else {
5732 amount = 0.0;
5733 }
5734 } else {
5735 aft_shield -= amount;
5736 if (aft_shield < 0.0) {
5737 amount = -aft_shield;
5738 aft_shield = 0.0f;
5739 } else {
5740 amount = 0.0;
5741 }
5742 }
5743
5744 [super takeScrapeDamage:amount from:ent];
5745
5746 while (amount > 0.0) {
5747 internal_damage = ((ranrot_rand() & PLAYER_INTERNAL_DAMAGE_FACTOR) < amount); // base chance of damage to systems
5748 if (internal_damage) {
5749 [self takeInternalDamage];
5750 }
5751 amount -= (PLAYER_INTERNAL_DAMAGE_FACTOR + 1);
5752 }
5753}
5754
5755- (void)takeHeatDamage:(double)amount
5756{
5757 if ([self status] == STATUS_DEAD || amount < 0)
5758 return;
5759
5760 // hit the shields first!
5761 float fwd_amount = (float)(0.5 * amount);
5762 float aft_amount = (float)(0.5 * amount);
5763
5764 forward_shield -= fwd_amount;
5765 if (forward_shield < 0.0) {
5766 fwd_amount = -forward_shield;
5767 forward_shield = 0.0f;
5768 } else {
5769 fwd_amount = 0.0f;
5770 }
5771
5772 aft_shield -= aft_amount;
5773 if (aft_shield < 0.0) {
5774 aft_amount = -aft_shield;
5775 aft_shield = 0.0f;
5776 } else {
5777 aft_amount = 0.0f;
5778 }
5779
5780 double residual_amount = fwd_amount + aft_amount;
5781
5782 [super takeHeatDamage:residual_amount];
5783}
5784
5786{
5787 ProxyPlayerEntity* result = (ProxyPlayerEntity*)[[UNIVERSE newShipWithName:[self shipDataKey] usePlayerProxy:YES] autorelease];
5788
5789 if (result != nil) {
5790 [result setPosition:[self position]];
5791 [result setScanClass:CLASS_NEUTRAL];
5792 [result setOrientation:[self normalOrientation]];
5793 [result setVelocity:[self velocity]];
5794 [result setSpeed:[self flightSpeed]];
5795 [result setDesiredSpeed:[self flightSpeed]];
5796 [result setRoll:flightRoll];
5797 [result setBehaviour:BEHAVIOUR_IDLE];
5798 [result switchAITo:@"nullAI.plist"]; // fly straight on
5799 [result setTemperature:[self temperature]];
5800 [result copyValuesFromPlayer:self];
5801 }
5802
5803 return result;
5804}
5805
5807{
5808 ShipEntity* doppelganger = nil;
5809 ShipEntity* escapePod = nil;
5810
5811 if ([UNIVERSE displayGUI])
5812 [self switchToMainView]; // Clear the F7 screen!
5813 [UNIVERSE setViewDirection:VIEW_FORWARD];
5814
5815 if ([self status] == STATUS_DEAD)
5816 return nil;
5817
5818 /*
5819 While inside the escape pod, we need to block access to all player.ship properties,
5820 since we're not supposed to be inside our ship anymore! -- Kaks 20101114
5821 */
5822
5823 [UNIVERSE setBlockJSPlayerShipProps:YES]; // no player.ship properties while inside the pod!
5824 // if a specific amount of time has been provided for the rescue, use it now
5825 if (escape_pod_rescue_time > 0) {
5827 escape_pod_rescue_time = 0; // reset value
5828 } else {
5829 // otherwise, use the default time calc
5830 ship_clock_adjust += 43200 + 5400 * (ranrot_rand() & 127); // add up to 8 days until rescue!
5831 }
5834
5835 doppelganger = [self createDoppelganger];
5836 if (doppelganger) {
5837 [doppelganger setVelocity:vector_multiply_scalar(v_forward, flightSpeed)];
5838 [doppelganger setSpeed:0.0];
5840 [doppelganger setRoll:0.2 * (randf() - 0.5)];
5841 [doppelganger setOwner:self];
5842 [doppelganger setThrust:0]; // drifts
5843 [UNIVERSE addEntity:doppelganger];
5844 }
5845
5846 [self setFoundTarget:doppelganger]; // must do this before setting status
5847 [self setStatus:STATUS_ESCAPE_SEQUENCE]; // now set up the escape sequence.
5848
5849 // must do this before next step or uses BBox of pod, not old ship!
5850 float sheight = (float)(boundingBox.max.y - boundingBox.min.y);
5852 float sdepth = (float)(boundingBox.max.z - boundingBox.min.z);
5854
5855 // set up you
5856 escapePod = [UNIVERSE newShipWithName:@"escape-capsule"]; // retained
5857 if (escapePod != nil) {
5858 // FIXME: this should use OOShipType, which should exist. -- Ahruman
5859 [self setMesh:[escapePod mesh]];
5860 }
5861
5862 /* These used to be non-zero, but BEHAVIOUR_IDLE levels off flight
5863 * anyway, and inertial velocity is used instead of inertialess
5864 * thrust - CIM */
5865 flightSpeed = 0.0f;
5866 flightPitch = 0.0f;
5867 flightRoll = 0.0f;
5868 flightYaw = 0.0f;
5869 // and turn off inertialess drive
5870 thrust = 0.0f;
5871
5872 /* Add an impulse upwards and backwards to the escape pod. This avoids
5873 flying straight through the doppelganger in interstellar space or when
5874 facing the main station/escape target, and generally looks cool.
5875 -- Ahruman 2011-04-02
5876 */
5877 Vector launchVector = vector_add([doppelganger velocity],
5880 [self setVelocity:launchVector];
5881
5882 // if multiple items providing escape pod, remove the first one
5883 [self removeEquipmentItem:[self equipmentItemProviding:@"EQ_ESCAPE_POD"]];
5884
5885 // set up the standard location where the escape pod will dock.
5886 target_system_id = system_id; // we're staying in this system
5888 [self setDockTarget:[UNIVERSE station]]; // we're docking at the main station, if there is one
5889
5890 [self doScriptEvent:OOJSID("shipLaunchedEscapePod") withArgument:escapePod]; // no player.ship properties should be available to script
5891
5892 // reset legal status
5893 [self setBounty:0 withReason:kOOLegalStatusReasonEscapePod];
5894 bounty = 0;
5895
5896 // new ship, so lose some memory of player actions
5897 if (ship_kills >= 6400) {
5898 [self clearRolesFromPlayer:0.1];
5899 } else if (ship_kills >= 2560) {
5900 [self clearRolesFromPlayer:0.25];
5901 } else {
5902 [self clearRolesFromPlayer:0.5];
5903 }
5904
5905 // reset trumbles
5906 if (trumbleCount != 0)
5907 trumbleCount = 1;
5908
5909 // remove cargo
5910 [cargo removeAllObjects];
5911
5912 energy = 25;
5913 [UNIVERSE addMessage:DESC(@"escape-sequence") forCount:4.5];
5914 [self resetShotTime];
5915
5916 // need to zero out all facings shot_times too, otherwise we may end up
5917 // with a broken escape pod sequence - Nikos 20100909
5918 forward_shot_time = 0.0;
5919 aft_shot_time = 0.0;
5920 port_shot_time = 0.0;
5921 starboard_shot_time = 0.0;
5922
5923 [escapePod release];
5924
5925 return doppelganger;
5926}
5927
5929{
5930 if (flightSpeed > 4.0 * maxFlightSpeed) {
5931 [UNIVERSE addMessage:OOExpandKey(@"hold-locked") forCount:3.0];
5932 return nil;
5933 }
5934
5935 OOCommodityType result = [super dumpCargo];
5936 if (result != nil) {
5937 NSString* commodity = [UNIVERSE displayNameForCommodity:result];
5938 [UNIVERSE addMessage:OOExpandKey(@"commodity-ejected", commodity) forCount:3.0 forceDisplay:YES];
5939 [self playCargoJettisioned];
5940 }
5941 return result;
5942}
5943
5945{
5946 NSInteger i, n_cargo = [cargo count];
5947 if (n_cargo == 0)
5948 return;
5949
5950 ShipEntity* pod = (ShipEntity*)[[cargo objectAtIndex:0] retain];
5951 OOCommodityType current_contents = [pod commodityType];
5952 OOCommodityType contents;
5953 NSInteger rotates = 0;
5954
5955 do {
5956 [cargo removeObjectAtIndex:0]; // take it from the eject position
5957 [cargo addObject:pod]; // move it to the last position
5958 [pod release];
5959 pod = (ShipEntity*)[[cargo objectAtIndex:0] retain];
5960 contents = [pod commodityType];
5961 rotates++;
5962 } while ([contents isEqualToString:current_contents] && (rotates < n_cargo));
5963 [pod release];
5964
5965 NSString* commodity = [UNIVERSE displayNameForCommodity:contents];
5966 [UNIVERSE addMessage:OOExpandKey(@"ready-to-eject-commodity", commodity) forCount:3.0];
5967
5968 // now scan through the remaining 1..(n_cargo - rotates) places moving similar cargo to the last place
5969 // this means the cargo gets to be sorted as it is rotated through
5970 for (i = 1; i < (n_cargo - rotates); i++) {
5971 pod = [cargo objectAtIndex:i];
5972 if ([[pod commodityType] isEqualToString:current_contents]) {
5973 [pod retain];
5974 [cargo removeObjectAtIndex:i--];
5975 [cargo addObject:pod];
5976 [pod release];
5977 rotates++;
5978 }
5979 }
5980}
5981
5982- (void)setBounty:(OOCreditsQuantity)amount
5983{
5984 [self setBounty:amount withReason:kOOLegalStatusReasonUnknown];
5985}
5986
5987- (void)setBounty:(OOCreditsQuantity)amount withReason:(OOLegalStatusReason)reason
5988{
5989 NSString* nReason = OOStringFromLegalStatusReason(reason);
5990 [self setBounty:amount withReasonAsString:nReason];
5991}
5992
5993- (void)setBounty:(OOCreditsQuantity)amount withReasonAsString:(NSString*)reason
5994{
5995 JSContext* context = OOJSAcquireContext();
5996
5997 int amountVal2 = (int)amount - (int)legalStatus;
5998 OOJSVal amountVal = OOJSValueFromDouble(context, amountVal2);
5999
6000 legalStatus = (int)amount; // can't set the new bounty until the size of the change is known
6001
6002 OOJSVal reasonVal = OOJSValueFromNativeObject(context, reason);
6003
6004 ShipScriptEvent(context, self, "shipBountyChanged", amountVal, reasonVal);
6005
6006 OOJSRelinquishContext(context);
6007}
6008
6009- (OOCreditsQuantity)bounty // overrides returning 'bounty'
6010{
6011 return legalStatus;
6012}
6013
6015{
6016 return legalStatus;
6017}
6018
6019- (void)markAsOffender:(int)offence_value
6020{
6021 [self markAsOffender:offence_value withReason:kOOLegalStatusReasonUnknown];
6022}
6023
6024- (void)markAsOffender:(int)offence_value withReason:(OOLegalStatusReason)reason
6025{
6026 if (![self isCloaked]) {
6027 JSContext* context = OOJSAcquireContext();
6028
6029 int amountVal2 = (legalStatus | offence_value) - legalStatus;
6030 OOJSVal amountVal = OOJSValueFromDouble(context, amountVal2);
6031
6032 legalStatus |= offence_value; // can't set the new bounty until the size of the change is known
6033
6034 OOJSVal reasonVal = OOJSValueFromLegalStatusReason(context, reason);
6035
6036 ShipScriptEvent(context, self, "shipBountyChanged", amountVal, reasonVal);
6037
6038 OOJSRelinquishContext(context);
6039 }
6040}
6041
6042- (void)collectBountyFor:(ShipEntity*)other
6043{
6044 if ([self status] == STATUS_DEAD)
6045 return; // no bounty if we died while trying
6046
6047 if (other == nil || [other isSubEntity])
6048 return;
6049
6050 if (other == [UNIVERSE station]) {
6051 // there is no way the player can destroy the main station
6052 // and so the explosion will be cancelled, so there shouldn't
6053 // be a kill award
6054 return;
6055 }
6056
6057 if ([self isCloaked]) {
6058 // no-one knows about it; no award
6059 return;
6060 }
6061
6063 OOScanClass killClass = [other scanClass]; // **tgape** change (+line)
6064 BOOL killAward = [other countsAsKill];
6065
6066 if ([other isPolice]) // oops, we shot a copper!
6067 {
6068 [self markAsOffender:64 withReason:kOOLegalStatusReasonAttackedPolice];
6069 }
6070
6071 BOOL killIsCargo = ((killClass == CLASS_CARGO) && ([other commodityAmount] > 0) && ![other isHulk]);
6072 if ((killIsCargo) || (killClass == CLASS_BUOY) || (killClass == CLASS_ROCK)) {
6073 // EMMSTRAN: no killaward (but full bounty) for tharglets?
6074 if (![other hasRole:@"tharglet"]) // okay, we'll count tharglets as proper kills
6075 {
6076 score /= 10; // reduce bounty awarded
6077 killAward = NO; // don't award a kill
6078 }
6079 }
6080
6081 credits += score;
6082
6083 if (score > 9) {
6084 NSString* bonusMessage = OOExpandKey(@"bounty-awarded", score, credits);
6085 [UNIVERSE addDelayedMessage:bonusMessage forCount:6 afterDelay:0.15];
6086 }
6087
6088 if (killAward) {
6089 ship_kills++;
6090 if ((ship_kills % 256) == 0) {
6091 // congratulations method needs to be delayed a fraction of a second
6092 [UNIVERSE addDelayedMessage:DESC(@"right-on-commander") forCount:4 afterDelay:0.2];
6093 }
6094 }
6095}
6096
6098{
6099 unsigned n_cargo = [self maxAvailableCargoSpace];
6100 unsigned n_mass = [self mass] / 10000;
6101 unsigned n_considered = (n_cargo + n_mass) * ship_trade_in_factor / 100; // a lower value of n_considered means more vulnerable to damage.
6102 unsigned damage_to = n_considered ? (ranrot_rand() % n_considered) : 0; // n_considered can be 0 for small ships.
6103 BOOL result = NO;
6104 // cargo damage
6105 if (damage_to < [cargo count]) {
6106 ShipEntity* pod = (ShipEntity*)[cargo objectAtIndex:damage_to];
6107 NSString* cargo_desc = [UNIVERSE displayNameForCommodity:[pod commodityType]];
6108 if (!cargo_desc)
6109 return NO;
6110 [UNIVERSE clearPreviousMessage];
6111 [UNIVERSE addMessage:[NSString stringWithFormat:DESC(@"@-destroyed"), cargo_desc] forCount:4.5];
6112 [cargo removeObject:pod];
6113 return YES;
6114 } else {
6115 damage_to = n_considered - (damage_to + 1); // reverse the die-roll
6116 }
6117 // equipment damage
6118 NSEnumerator* eqEnum = [self equipmentEnumerator];
6119 OOEquipmentType* eqType = nil;
6120 NSString* system_key;
6121 unsigned damageableCounter = 0;
6122 GLfloat damageableOdds = 0.0;
6123 while ((system_key = [eqEnum nextObject]) != nil) {
6124 eqType = [OOEquipmentType equipmentTypeWithIdentifier:system_key];
6125 if ([eqType canBeDamaged]) {
6126 damageableCounter++;
6127 damageableOdds += [eqType damageProbability];
6128 }
6129 }
6130
6131 if (damage_to < damageableCounter) {
6132 GLfloat target = randf() * damageableOdds;
6133 GLfloat accumulator = 0.0;
6134 eqEnum = [self equipmentEnumerator];
6135 while ((system_key = [eqEnum nextObject]) != nil) {
6136 eqType = [OOEquipmentType equipmentTypeWithIdentifier:system_key];
6137 accumulator += [eqType damageProbability];
6138 if (accumulator > target) {
6139 [system_key retain];
6140 break;
6141 }
6142 }
6143 if (system_key == nil) {
6144 [system_key release];
6145 return NO;
6146 }
6147
6148 NSString* system_name = [eqType name];
6149 if (![eqType canBeDamaged] || system_name == nil) {
6150 [system_key release];
6151 return NO;
6152 }
6153
6154 // set the following so removeEquipment works on the right entity
6155 [self setScriptTarget:self];
6156 [UNIVERSE clearPreviousMessage];
6157 [self removeEquipmentItem:system_key];
6158
6159 NSString* damagedKey = [NSString stringWithFormat:@"%@_DAMAGED", system_key];
6160 [self addEquipmentItem:damagedKey withValidation:NO inContext:@"damage"]; // for possible future repair.
6161 [self doScriptEvent:OOJSID("equipmentDamaged") withArgument:system_key];
6162
6163 if (![self hasEquipmentItem:system_name] && [self hasEquipmentItem:damagedKey]) {
6164 /*
6165 Display "foo damaged" message only if no script has
6166 repaired or removed the equipment item. (If a script does
6167 either of those and wants a message, it can write it
6168 itself.)
6169 */
6170 [UNIVERSE addMessage:[NSString stringWithFormat:DESC(@"@-damaged"), system_name] forCount:4.5];
6171 }
6172
6173 /* There used to be a check for docking computers here, but
6174 * that didn't cover other ways they might fail in flight, so
6175 * it has been moved to the removeEquipment method. */
6176 [system_key release];
6177 return YES;
6178 }
6179 // cosmetic damage
6180 if (((damage_to & 7) == 7) && (ship_trade_in_factor > 75)) {
6182 result = YES;
6183 }
6184 return result;
6185}
6186
6187- (void)getDestroyedBy:(Entity*)whom damageType:(OOShipDamageType)type
6188{
6189 if ([self isDocked])
6190 return; // Can't die while docked. (Doing so would cause breakage elsewhere.)
6191
6192 OOLog(@"player.ship.damage", @"Player destroyed by %@ due to %@", whom, OOStringFromShipDamageType(type));
6193
6194 if (![[UNIVERSE gameController] playerFileToLoad]) {
6195 [[UNIVERSE gameController] setPlayerFileToLoad:save_path]; // make sure we load the correct game
6196 }
6197
6198 energy = 0.0f;
6200 [self disengageAutopilot];
6201
6202 [UNIVERSE setDisplayText:NO];
6203 [UNIVERSE setViewDirection:VIEW_AFT];
6204
6205 // Let scripts know the player died.
6206 [self noteKilledBy:whom damageType:type]; // called before exploding, consistant with npc ships.
6207
6208 [self becomeLargeExplosion:4.0]; // also sets STATUS_DEAD
6209 [self moveForward:100.0];
6210
6211 flightSpeed = 160.0f;
6213 flightRoll = 0.0;
6214 flightPitch = 0.0;
6215 flightYaw = 0.0;
6216 [[UNIVERSE messageGUI] clear]; // No messages for the dead.
6217 [self suppressTargetLost]; // No target lost messages when dead.
6218 [self playGameOver];
6219 [UNIVERSE setBlockJSPlayerShipProps:YES]; // Treat JS player as stale entity.
6220 [self removeAllEquipment]; // No scooping / equipment damage when dead.
6221 [self loseTargetStatus];
6222 [self showGameOver];
6223}
6224
6226{
6227 if (!UNIVERSE)
6228 return;
6229 int ent_count = UNIVERSE->n_entities;
6230 Entity** uni_entities = UNIVERSE->sortedEntities; // grab the public sorted list
6231 Entity* my_entities[ent_count];
6232 int i;
6233 for (i = 0; i < ent_count; i++)
6234 my_entities[i] = [uni_entities[i] retain]; // retained
6235 for (i = 0; i < ent_count; i++) {
6236 Entity* thing = my_entities[i];
6237 if (thing->isShip) {
6238 ShipEntity* ship = (ShipEntity*)thing;
6239 if (self == [ship primaryTarget]) {
6241 }
6242 }
6243 }
6244 for (i = 0; i < ent_count; i++) {
6245 [my_entities[i] release]; // released
6246 }
6247}
6248
6249- (BOOL)endScenario:(NSString*)key
6250{
6251 if (scenarioKey != nil && [key isEqualToString:scenarioKey]) {
6252 [self setStatus:STATUS_RESTART_GAME];
6253 return YES;
6254 }
6255 return NO;
6256}
6257
6258- (void)enterDock:(StationEntity*)station
6259{
6260 NSParameterAssert(station != nil);
6261 if ([self status] == STATUS_DEAD)
6262 return;
6263
6264 [self setStatus:STATUS_DOCKING];
6265 [self setDockedStation:station];
6266 [self doScriptEvent:OOJSID("shipWillDockWithStation") withArgument:station];
6267
6268 if (![hud nonlinearScanner]) {
6269 [hud setScannerZoom:1.0];
6270 }
6271 ident_engaged = NO;
6273 autopilot_engaged = NO;
6274 [self resetAutopilotAI];
6275
6277 hyperspeed_engaged = NO;
6278 hyperspeed_locked = NO;
6279 [self safeAllMissiles];
6280 DESTROY(_primaryTarget); // must happen before showing break_pattern to suppress active reticule.
6281 [self clearTargetMemory];
6282
6283 scanner_zoom_rate = 0.0f;
6284 [UNIVERSE setDisplayText:NO];
6285 [[UNIVERSE gameController] setMouseInteractionModeForFlight];
6286 if ([self status] == STATUS_LAUNCHING)
6287 return; // a JS script has aborted the docking.
6288
6289 [self setOrientation:kIdentityQuaternion]; // reset orientation to dock
6290 [UNIVERSE setUpBreakPattern:[self breakPatternPosition] orientation:orientation forDocking:YES];
6291 [self playDockWithStation];
6292 [station noteDockedShip:self];
6293
6294 [[UNIVERSE gameView] clearKeys]; // try to stop key bounces
6295}
6296
6297- (void)docked
6298{
6300 if (dockedStation == nil) {
6301 [self setStatus:STATUS_IN_FLIGHT];
6302 return;
6303 }
6304
6305 [self setStatus:STATUS_DOCKED];
6306 [UNIVERSE enterGUIViewModeWithMouseInteraction:NO];
6307
6308 [self loseTargetStatus];
6309
6311 [self setOrientation:kIdentityQuaternion]; // reset orientation to dock
6312
6313 flightRoll = 0.0f;
6314 flightPitch = 0.0f;
6315 flightYaw = 0.0f;
6316 flightSpeed = 0.0f;
6317
6318 hyperspeed_engaged = NO;
6319 hyperspeed_locked = NO;
6320
6323 energy = maxEnergy;
6324 weapon_temp = 0.0f;
6325 ship_temperature = 60.0f;
6326
6327 [self setAlertFlag:ALERT_FLAG_DOCKED to:YES];
6328
6329 if ([dockedStation localMarket] == nil) {
6331 }
6332
6333 NSString* escapepodReport = [self processEscapePods];
6334 [self addMessageToReport:escapepodReport];
6335
6336 [self unloadCargoPods]; // fill up the on-ship commodities before...
6337
6338 // check import status of station
6339 // escape pods must be cleared before this happens
6340 if ([dockedStation marketMonitored]) {
6341 OOCreditsQuantity oldbounty = [self bounty];
6342 [self markAsOffender:[dockedStation legalStatusOfManifest:shipCommodityData export:NO] withReason:kOOLegalStatusReasonIllegalImports];
6343 if ([self bounty] > oldbounty) {
6344 [self addRoleToPlayer:@"trader-smuggler"];
6345 }
6346 }
6347
6348 // check contracts
6349 NSString* passengerAndCargoReport = [self checkPassengerContracts]; // Is also processing cargo and parcel contracts.
6350 [self addMessageToReport:passengerAndCargoReport];
6351
6352 [UNIVERSE setDisplayText:YES];
6353
6356
6357 // Did we fail to observe traffic control regulations? However, due to the state of emergency,
6358 // apply no unauthorized docking penalties if a nova is ongoing.
6359 if ([dockedStation requiresDockingClearance] && ![self clearedToDock] && ![[UNIVERSE sun] willGoNova]) {
6361 }
6362
6363 // apply any pending fines. (No need to check gui_screen as fines is no longer an on-screen message).
6364 if (dockedStation == [UNIVERSE station]) {
6365 // TODO: A proper system to allow some OXP stations to have a
6366 // galcop presence for fines. - CIM 18/11/2012
6367 if (being_fined && ![[UNIVERSE sun] willGoNova] && ![dockedStation suppressArrivalReports])
6368 [self getFined];
6369 }
6370
6371 // it's time to check the script - can trigger legacy missions
6372 if (gui_screen != GUI_SCREEN_MISSION)
6373 [self checkScript]; // a scripted pilot could have created a mission screen.
6374
6376 [self doScriptEvent:OOJSID("shipDockedWithStation") withArgument:dockedStation];
6378 if ([self status] == STATUS_LAUNCHING)
6379 return;
6380
6381 // if we've not switched to the mission screen yet then proceed normally..
6382 if (gui_screen != GUI_SCREEN_MISSION) {
6383 [self setGuiToStatusScreen];
6384 }
6387
6388 // When a mission screen is started, any on-screen message is removed immediately.
6389 [self doWorldEventUntilMissionScreen:OOJSID("missionScreenOpportunity")]; // also displays docking reports first.
6390}
6391
6392- (void)leaveDock:(StationEntity*)station
6393{
6394 if (station == nil)
6395 return;
6396 NSParameterAssert(station == [self dockedStation]);
6397
6398 // ensure we've not left keyboard entry on
6399 [[UNIVERSE gameView] allowStringInput:NO];
6400
6401 if (gui_screen == GUI_SCREEN_MISSION) {
6402 [[UNIVERSE gui] clearBackground];
6404 [self doMissionCallback];
6405 }
6406 // notify older scripts, but do not trigger missionScreenOpportunity.
6407 [self doWorldEventUntilMissionScreen:OOJSID("missionScreenEnded")];
6408 }
6409
6410 if ([station marketMonitored]) {
6411 // 'leaving with those guns were you sir?'
6412 OOCreditsQuantity oldbounty = [self bounty];
6413 [self markAsOffender:[station legalStatusOfManifest:shipCommodityData export:YES] withReason:kOOLegalStatusReasonIllegalExports];
6414 if ([self bounty] > oldbounty) {
6415 [self addRoleToPlayer:@"trader-smuggler"];
6416 }
6417 }
6418 OOGUIScreenID oldScreen = gui_screen;
6419 gui_screen = GUI_SCREEN_MAIN;
6420 [self noteGUIDidChangeFrom:oldScreen to:gui_screen];
6421
6422 if (![hud nonlinearScanner]) {
6423 [hud setScannerZoom:1.0];
6424 }
6425 [self loadCargoPods];
6426 // do not do anything that calls JS handlers between now and calling
6427 // [station launchShip] below, or the cargo returned by JS may be off
6428 // CIM - 3.2.2012
6429
6430 // clear the way
6433
6434 // [self setAlertFlag:ALERT_FLAG_DOCKED to:NO];
6435 [self clearAlertFlags];
6436 [self setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_NONE];
6437
6438 scanner_zoom_rate = 0.0f;
6440 [self currentWeaponStats];
6441
6442 forward_weapon_temp = 0.0f;
6443 aft_weapon_temp = 0.0f;
6444 port_weapon_temp = 0.0f;
6445 starboard_weapon_temp = 0.0f;
6446
6449
6450 [self clearTargetMemory];
6451 [self setShowDemoShips:NO];
6452 [UNIVERSE setDisplayText:NO];
6453 [[UNIVERSE gameController] setMouseInteractionModeForFlight];
6454
6455 [[UNIVERSE gameView] clearKeys]; // try to stop keybounces
6456
6457 if ([self isMouseControlOn]) {
6458 [[UNIVERSE gameView] resetMouse];
6459 }
6460
6462
6463 [UNIVERSE forceWitchspaceEntries];
6464 ship_clock_adjust += 600.0; // 10 minutes to leave dock
6465 velocity = kZeroVector; // just in case
6466
6467 [station launchShip:self];
6468
6469 launchRoll = -flightRoll; // save the station's spin. (inverted for player)
6470 flightRoll = 0; // don't spin when showing the break pattern.
6471 [UNIVERSE setUpBreakPattern:[self breakPatternPosition] orientation:orientation forDocking:YES];
6472
6473 [self setDockedStation:nil];
6474
6476 [self checkForAegis];
6478 ident_engaged = NO;
6479
6480 [UNIVERSE removeDemoShips];
6481 // MKW - ensure GUI Screen ship is removed
6482 [demoShip release];
6483 demoShip = nil;
6484
6485 [self playLaunchFromStation];
6486}
6487
6489{
6490 // chances of entering witchspace with autopilot on are very low, but as Berlios bug #18307 has shown us, entirely possible
6491 // so in such cases we need to ensure that at least the docking music stops playing
6492 if (autopilot_engaged)
6493 [self disengageAutopilot];
6494
6495 if (![hud nonlinearScanner]) {
6496 [hud setScannerZoom:1.0];
6497 }
6498 [self safeAllMissiles];
6499
6500 OOViewID previousViewDirection = [UNIVERSE viewDirection];
6501 [UNIVERSE setViewDirection:VIEW_FORWARD];
6502 [self noteSwitchToView:VIEW_FORWARD fromView:previousViewDirection]; // notifies scripts of the switch
6503
6504 currentWeaponFacing = WEAPON_FACING_FORWARD;
6505 [self currentWeaponStats];
6506
6507 [self transitionToAegisNone];
6508 suppressAegisMessages = YES;
6509 hyperspeed_engaged = NO;
6510
6511 if ([self primaryTarget] != nil) {
6512 [self noteLostTarget]; // losing target? Fire lost target event!
6513 DESTROY(_primaryTarget);
6514 }
6515
6516 scanner_zoom_rate = 0.0f;
6517 [UNIVERSE setDisplayText:NO];
6518
6519 if (![self wormhole] && !galactic_witchjump) // galactic hyperspace does not generate a wormhole
6520 {
6521 OOLog(kOOLogInconsistentState, @"%@", @"Internal Error : Player entering witchspace with no wormhole.");
6522 }
6523 [UNIVERSE allShipsDoScriptEvent:OOJSID("playerWillEnterWitchspace") andReactToAIMessage:@"PLAYER WITCHSPACE"];
6524
6525 // set the new market seed now!
6526 // reseeding the RNG should be completely unnecessary here
6527 // ranrot_srand((uint32_t)[[NSDate date] timeIntervalSince1970]); // seed randomiser by time
6528 market_rnd = ranrot_rand() & 255; // random factor for market values is reset
6529}
6530
6532{
6533 [UNIVERSE setSystemTo:system_id];
6534 galaxy_coordinates = [[UNIVERSE systemManager] getCoordinatesForSystem:system_id inGalaxy:galaxy_number];
6535
6536 [UNIVERSE setUpUniverseFromWitchspace];
6537 [[UNIVERSE planet] update:2.34375 * market_rnd]; // from 0..10 minutes
6538 [[UNIVERSE station] update:2.34375 * market_rnd]; // from 0..10 minutes
6539
6540 chart_centre_coordinates = galaxy_coordinates;
6541 target_chart_centre = chart_centre_coordinates;
6542}
6543
6544- (BOOL)witchJumpChecklist:(BOOL)isGalacticJump
6545{
6546 // Perform this check only when doing the actual jump
6547 if ([self status] == STATUS_WITCHSPACE_COUNTDOWN) {
6548 // check nearby masses
6549 // UPDATE_STAGE(@"checking for mass blockage");
6550 ShipEntity* blocker = [UNIVERSE entityForUniversalID:[self checkShipsInVicinityForWitchJumpExit]];
6551 if (blocker) {
6552 [UNIVERSE clearPreviousMessage];
6553 NSString* blockerName = [blocker name];
6554 [UNIVERSE addMessage:OOExpandKey(@"witch-blocked", blockerName) forCount:4.5];
6555 [self playWitchjumpBlocked];
6556 [self setStatus:STATUS_IN_FLIGHT];
6557 [self doScriptEvent:OOJSID("playerJumpFailed") withArgument:@"blocked"];
6558 return NO;
6559 }
6560 }
6561
6562 // For galactic hyperspace jumps we skip the remaining checks
6563 if (isGalacticJump) {
6564 return YES;
6565 }
6566
6567 // Check we're not jumping into the current system
6568 if (![UNIVERSE inInterstellarSpace] && system_id == target_system_id) {
6569 // dont allow player to hyperspace to current location.
6570 // Note interstellar space will have a system_seed place we came from
6571 [UNIVERSE clearPreviousMessage];
6572 [UNIVERSE addMessage:OOExpandKey(@"witch-no-target") forCount:4.5];
6573 if ([self status] == STATUS_WITCHSPACE_COUNTDOWN) {
6575 [self setStatus:STATUS_IN_FLIGHT];
6576 [self doScriptEvent:OOJSID("playerJumpFailed") withArgument:@"no target"];
6577 } else
6579
6580 return NO;
6581 }
6582
6583 // check max distance permitted
6584 if ([self hyperspaceJumpDistance] > [self maxHyperspaceDistance]) {
6585 [UNIVERSE clearPreviousMessage];
6586 [UNIVERSE addMessage:DESC(@"witch-too-far") forCount:4.5];
6587 if ([self status] == STATUS_WITCHSPACE_COUNTDOWN) {
6589 [self setStatus:STATUS_IN_FLIGHT];
6590 [self doScriptEvent:OOJSID("playerJumpFailed") withArgument:@"too far"];
6591 } else
6593
6594 return NO;
6595 }
6596
6597 // check fuel level
6598 if (![self hasSufficientFuelForJump]) {
6599 [UNIVERSE clearPreviousMessage];
6600 [UNIVERSE addMessage:DESC(@"witch-no-fuel") forCount:4.5];
6601 if ([self status] == STATUS_WITCHSPACE_COUNTDOWN) {
6603 [self setStatus:STATUS_IN_FLIGHT];
6604 [self doScriptEvent:OOJSID("playerJumpFailed") withArgument:@"insufficient fuel"];
6605 } else
6606 [self playHyperspaceNoFuel];
6607
6608 return NO;
6609 }
6610
6611 // All checks passed
6612 return YES;
6613}
6614
6615- (void)setJumpType:(BOOL)isGalacticJump
6616{
6617 if (isGalacticJump) {
6618 galactic_witchjump = YES;
6619 } else {
6620 galactic_witchjump = NO;
6621 }
6622}
6623
6625{
6626 NSPoint targetCoordinates = PointFromString([[UNIVERSE systemManager] getProperty:@"coordinates" forSystem:[self nextHopTargetSystemID] inGalaxy:galaxy_number]);
6627 return distanceBetweenPlanetPositions(targetCoordinates.x, targetCoordinates.y, galaxy_coordinates.x, galaxy_coordinates.y);
6628}
6629
6631{
6632 return 10.0 * MAX(0.1, [self hyperspaceJumpDistance]);
6633}
6634
6636{
6637 return fuel >= [self fuelRequiredForJump];
6638}
6639
6641{
6642 if ([[self hud] isCompassActive]) {
6643 // "the compass, it says we're lost!" :)
6644 JSContext* context = OOJSAcquireContext();
6645 OOJSVal jsmode = OOJSValueFromCompassMode(context, [self compassMode]);
6646 ShipScriptEvent(context, self, "compassTargetChanged", OOJSUndefinedValue(), jsmode);
6647 OOJSRelinquishContext(context);
6648
6649 [[self hud] setCompassActive:NO]; // ensure a target change when returning to normal space.
6650 }
6651}
6652
6654{
6655 if (![self witchJumpChecklist:true])
6656 return;
6657
6658 OOGalaxyID destGalaxy = galaxy_number + 1;
6659 if (EXPECT_NOT(destGalaxy >= OO_GALAXIES_AVAILABLE)) {
6660 destGalaxy = 0;
6661 }
6662
6663 [self setStatus:STATUS_ENTERING_WITCHSPACE];
6664 JSContext* context = OOJSAcquireContext();
6665 [self setJumpCause:@"galactic jump"];
6667 ShipScriptEvent(context, self, "shipWillEnterWitchspace", OOJSValueFromNativeObject(context, [self jumpCause]), OOJSValueFromDouble(context, destGalaxy));
6668 OOJSRelinquishContext(context);
6669
6670 [self noteCompassLostTarget];
6671
6672 [self witchStart];
6673
6674 [UNIVERSE removeAllEntitiesExceptPlayer];
6675
6676 // remove any contracts and parcels for the old galaxy
6677 if (contracts)
6678 [contracts removeAllObjects];
6679
6680 if (parcels)
6681 [parcels removeAllObjects];
6682
6683 // remove any mission destinations for the old galaxy
6685 [missionDestinations removeAllObjects];
6686
6687 // expire passenger contracts for the old galaxy
6688 if (passengers) {
6689 unsigned i;
6690 for (i = 0; i < [passengers count]; i++) {
6691 // set the expected arrival time to now, so they storm off the ship at the first port
6692 NSMutableDictionary* passenger_info = [NSMutableDictionary dictionaryWithDictionary:[passengers oo_dictionaryAtIndex:i]];
6693 [passenger_info setObject:[NSNumber numberWithDouble:ship_clock] forKey:CONTRACT_KEY_ARRIVAL_TIME];
6694 [passengers replaceObjectAtIndex:i withObject:passenger_info];
6695 }
6696 }
6697
6698 // clear a lot of memory of player actions
6699 if (ship_kills >= 6400) {
6700 [self clearRolesFromPlayer:0.25];
6701 } else if (ship_kills >= 2560) {
6702 [self clearRolesFromPlayer:0.5];
6703 } else {
6704 [self clearRolesFromPlayer:0.9];
6705 }
6706 [roleWeightFlags removeAllObjects];
6707 [roleSystemList removeAllObjects];
6708
6709 // may be more than one item providing this
6710 [self removeEquipmentItem:[self equipmentItemProviding:@"EQ_GAL_DRIVE"]];
6711
6712 galaxy_number = destGalaxy;
6713
6714 [UNIVERSE setGalaxyTo:galaxy_number];
6715
6716 // Choose the galactic hyperspace behaviour. Refers to where we may actually end up after an intergalactic jump.
6717 // The default behaviour is that the player cannot arrive on unreachable or isolated systems. The options
6718 // in planetinfo.plist, galactic_hyperspace_behaviour key can be used to allow arrival even at unreachable systems,
6719 // or at fixed coordinates on the galactic chart. The key galactic_hyperspace_fixed_coords in planetinfo.plist is
6720 // used in the fixed coordinates case and specifies the exact coordinates for the intergalactic jump.
6722 case GALACTIC_HYPERSPACE_BEHAVIOUR_FIXED_COORDINATES:
6723 system_id = [UNIVERSE findSystemNumberAtCoords:galacticHyperspaceFixedCoords withGalaxy:galaxy_number includingHidden:YES];
6724 break;
6725 case GALACTIC_HYPERSPACE_BEHAVIOUR_ALL_SYSTEMS_REACHABLE:
6726 system_id = [UNIVERSE findSystemNumberAtCoords:galaxy_coordinates withGalaxy:galaxy_number includingHidden:YES];
6727 break;
6728 case GALACTIC_HYPERSPACE_BEHAVIOUR_STANDARD:
6729 default:
6730 // instead find a system connected to system 0 near the current coordinates...
6731 system_id = [UNIVERSE findConnectedSystemAtCoords:galaxy_coordinates withGalaxy:galaxy_number];
6732 break;
6733 }
6736
6737 [self setBounty:0 withReason:kOOLegalStatusReasonNewGalaxy]; // let's make a fresh start!
6738 cursor_coordinates = PointFromString([[UNIVERSE systemManager] getProperty:@"coordinates" forSystem:system_id inGalaxy:galaxy_number]);
6739
6740 [self witchEnd]; // sets coordinates, calls exiting witchspace JS events
6741}
6742
6743// now with added misjump goodness!
6744// If the wormhole generator misjumped, the player's ship misjumps too. Kaks 20110211
6745- (void)enterWormhole:(WormholeEntity*)w_hole
6746{
6747 if ([self status] == STATUS_ENTERING_WITCHSPACE
6748 || [self status] == STATUS_EXITING_WITCHSPACE) {
6749 return; // has already entered a different wormhole
6750 }
6751 BOOL misjump = [self scriptedMisjump] || [w_hole withMisjump] || flightPitch == max_flight_pitch || randf() > 0.995;
6752 wormhole = [w_hole retain];
6753 [self addScannedWormhole:wormhole];
6754 [self setStatus:STATUS_ENTERING_WITCHSPACE];
6755 JSContext* context = OOJSAcquireContext();
6756 [self setJumpCause:@"wormhole"];
6758 ShipScriptEvent(context, self, "shipWillEnterWitchspace", OOJSValueFromNativeObject(context, [self jumpCause]), OOJSValueFromDouble(context, [w_hole destination]));
6759 OOJSRelinquishContext(context);
6760 if ([self scriptedMisjump]) {
6761 misjump = YES; // a script could just have changed this to true;
6762 }
6763#ifdef OO_DUMP_PLANETINFO
6764 misjump = NO;
6765#endif
6766 if (misjump && [self scriptedMisjumpRange] != 0.5) {
6767 [w_hole setMisjumpWithRange:[self scriptedMisjumpRange]]; // overrides wormholes, if player also had non-default scriptedMisjumpRange
6768 }
6769 [self witchJumpTo:[w_hole destination] misjump:misjump];
6770}
6771
6773{
6774 if (![self witchJumpChecklist:false])
6775 return;
6776
6777 OOSystemID jumpTarget = [self nextHopTargetSystemID];
6778
6779 // perform any check here for forced witchspace encounters
6780 unsigned malfunc_chance = 253;
6781 if (ship_trade_in_factor < 80) {
6782 malfunc_chance -= (1 + ranrot_rand() % (81 - ship_trade_in_factor)) / 2; // increase chance of misjump in worn-out craft
6783 } else if (ship_trade_in_factor >= 100) {
6784 malfunc_chance = 256; // force no misjumps on first jump
6785 }
6786
6787#ifdef OO_DUMP_PLANETINFO
6788 BOOL misjump = NO; // debugging
6789#else
6790 BOOL malfunc = ((ranrot_rand() & 0xff) > malfunc_chance);
6791 // 75% of the time a malfunction means a misjump
6792 BOOL misjump = [self scriptedMisjump] || (flightPitch == max_flight_pitch) || (malfunc && (randf() > 0.75));
6793
6794 if (malfunc && !misjump) {
6795 // some malfunctions will start fuel leaks, some will result in no witchjump at all.
6796 if ([self takeInternalDamage]) // Depending on ship type and loaded cargo, this will be true for 20 - 50% of the time.
6797 {
6798 [self playWitchjumpFailure];
6799 [self setStatus:STATUS_IN_FLIGHT];
6800 [self doScriptEvent:OOJSID("playerJumpFailed") withArgument:@"malfunction"];
6801 return;
6802 } else {
6803 [self setFuelLeak:[NSString stringWithFormat:@"%f", (randf() + randf()) * 5.0]];
6804 }
6805 }
6806#endif
6807
6808 // From this point forward we are -definitely- witchjumping
6809
6810 // burn the full fuel amount to create the wormhole
6811 fuel -= [self fuelRequiredForJump];
6812
6813 // Create the players' wormhole
6814 wormhole = [[WormholeEntity alloc] initWormholeTo:jumpTarget fromShip:self];
6815 [UNIVERSE addEntity:wormhole]; // Add new wormhole to Universe to let other ships target it. Required for ships following the player.
6816 [self addScannedWormhole:wormhole];
6817
6818 [self setStatus:STATUS_ENTERING_WITCHSPACE];
6819 JSContext* context = OOJSAcquireContext();
6820 [self setJumpCause:@"standard jump"];
6822 ShipScriptEvent(context, self, "shipWillEnterWitchspace", OOJSValueFromNativeObject(context, [self jumpCause]), OOJSValueFromDouble(context, jumpTarget));
6823 OOJSRelinquishContext(context);
6824
6825 [self updateSystemMemory];
6826 NSUInteger legality = [self legalStatusOfCargoList];
6827 OOCargoQuantity maxSpace = [self maxAvailableCargoSpace];
6828 OOCargoQuantity availSpace = [self availableCargoSpace];
6829 if ([roleWeightFlags objectForKey:@"bought-legal"]) {
6830 if (maxSpace != availSpace) {
6831 [self addRoleToPlayer:@"trader"];
6832 if (maxSpace - availSpace > 20 || availSpace == 0) {
6833 if (legality == 0) {
6834 [self addRoleToPlayer:@"trader"];
6835 }
6836 }
6837 }
6838 }
6839 if ([roleWeightFlags objectForKey:@"bought-illegal"]) {
6840 if (maxSpace != availSpace && legality > 0) {
6841 [self addRoleToPlayer:@"trader-smuggler"];
6842 if (maxSpace - availSpace > 20 || availSpace == 0) {
6843 if (legality >= 20 || legality >= maxSpace) {
6844 [self addRoleToPlayer:@"trader-smuggler"];
6845 }
6846 }
6847 }
6848 }
6849 [roleWeightFlags removeAllObjects];
6850
6851 [self noteCompassLostTarget];
6852 if ([self scriptedMisjump]) {
6853 misjump = YES; // a script could just have changed this to true;
6854 }
6855 if (misjump) {
6857 }
6858 [self witchJumpTo:jumpTarget misjump:misjump];
6859}
6860
6861- (void)witchJumpTo:(OOSystemID)sTo misjump:(BOOL)misjump
6862{
6863 [self witchStart];
6864 if (info_system_id == system_id) {
6865 [self setInfoSystemID:sTo moveChart:YES];
6866 }
6867 // wear and tear on all jumps (inc misjumps, failures, and wormholes)
6868 if (2 * market_rnd < ship_trade_in_factor) {
6869 // every eight jumps or so drop the price down towards 75%
6870 [self adjustTradeInFactorBy:-(1 + (market_rnd & 3))];
6871 }
6872
6873 // set clock after "playerWillEnterWitchspace" and before removeAllEntitiesExceptPlayer, to allow escorts time to follow their mother.
6874 NSPoint destCoords = PointFromString([[UNIVERSE systemManager] getProperty:@"coordinates" forSystem:sTo inGalaxy:galaxy_number]);
6875 double distance = distanceBetweenPlanetPositions(destCoords.x, destCoords.y, galaxy_coordinates.x, galaxy_coordinates.y);
6876
6877 // if we just escaped a system gone nova, make sure all nova parameters are reset
6878 OOSunEntity* theSun = [UNIVERSE sun];
6879 if (theSun && [theSun goneNova]) {
6880 [theSun resetNova];
6881 }
6882
6883 [UNIVERSE removeAllEntitiesExceptPlayer];
6884 if (!misjump) {
6885 ship_clock_adjust += distance * distance * 3600.0;
6886 [self setSystemID:sTo];
6887 [self setBounty:(legalStatus / 2) withReason:kOOLegalStatusReasonNewSystem]; // 'another day, another system'
6888 [self witchEnd];
6889 if (market_rnd < 8)
6890 [self erodeReputation]; // every 32 systems or so, drop back towards 'unknown'
6891 } else {
6892 // Misjump: move halfway there!
6893 // misjumps do not change legal status.
6894 if (randf() < 0.1)
6895 [self erodeReputation]; // once every 10 misjumps - should be much rarer than successful jumps!
6896
6897 [wormhole setMisjump];
6898 // just in case, but this has usually been set already
6899
6900 // and now the wormhole has travel time and coordinates calculated
6901 // so rather than duplicate the calculation we'll just ask it...
6902 NSPoint dest = [wormhole destinationCoordinates];
6903 galaxy_coordinates.x = dest.x;
6904 galaxy_coordinates.y = dest.y;
6905
6906 ship_clock_adjust += [wormhole travelTime];
6907
6908 [self playWitchjumpMisjump];
6909 [UNIVERSE setUpUniverseFromMisjump];
6910 }
6911}
6912
6914{
6915 double d1 = SCANNER_MAX_RANGE * ((Ranrot() & 255) / 256.0 - 0.5);
6916 HPVector pos = [UNIVERSE getWitchspaceExitPosition]; // no need to reset the PRNG
6917 Quaternion q1;
6918 HPVector whpos, exitpos;
6919
6920 double min_d1 = [UNIVERSE safeWitchspaceExitDistance];
6922 if (abs((int)d1) < min_d1) {
6923 d1 += ((d1 > 0.0) ? min_d1 : -min_d1); // not too close to the buoy.
6924 }
6926 exitpos = HPvector_add(pos, HPvector_multiply_scalar(v1, d1)); // randomise exit position
6927 position = exitpos;
6928 [self setOrientation:[UNIVERSE getWitchspaceExitRotation]];
6929
6930 // While setting the wormhole position to the player position looks very nice for ships following the player,
6931 // the more common case of the player following other ships, the player tends to
6932 // ram the back of the ships, or even jump on top of is when the ship jumped without initial speed, which is messy.
6933 // To avoid this problem, a small wormhole displacement is added.
6934 if (wormhole) // will be nil for galactic jump
6935 {
6936 if ([[wormhole shipsInTransit] count] > 0) {
6937 // player is not allone in his wormhole, synchronise player and wormhole position.
6938 double wh_arrival_time = ([PLAYER clockTimeAdjusted] - [wormhole arrivalTime]);
6939 if (wh_arrival_time > 0) {
6940 // Player is following other ship
6941 whpos = HPvector_add(exitpos, vectorToHPVector(vector_multiply_scalar([self forwardVector], 1000.0f)));
6943 } else {
6944 // Player is the leadship
6945 whpos = HPvector_add(exitpos, vectorToHPVector(vector_multiply_scalar([self forwardVector], -500.0f)));
6946 // so it won't contain the player by the time they exit
6947 [wormhole setExitSpeed:maxFlightSpeed * WORMHOLE_LEADER_SPEED_FACTOR];
6948 }
6949
6950 HPVector distance = HPvector_subtract(whpos, pos);
6951 if (HPmagnitude2(distance) < min_d1 * min_d1) // within safety distance from the buoy?
6952 {
6953 // the wormhole is to close to the buoy. Move both player and wormhole away from it in the x-y plane.
6954 distance.z = 0;
6956 whpos = HPvector_add(whpos, distance);
6958 }
6959 [wormhole setExitPosition:whpos];
6960 } else {
6961 // no-one else in the wormhole
6962 [wormhole setExitSpeed:maxFlightSpeed * WORMHOLE_LEADER_SPEED_FACTOR];
6963 }
6964 }
6965 /* there's going to be a slight pause at this stage anyway;
6966 * there's also going to be a lot of stale ship scripts. Force a
6967 * garbage collection while we have chance. - CIM */
6970 [wormhole release]; // OK even if nil
6971 wormhole = nil;
6972
6973 flightRoll = 0.0f;
6974 flightPitch = 0.0f;
6975 flightYaw = 0.0f;
6976
6978 [self setStatus:STATUS_EXITING_WITCHSPACE];
6979 gui_screen = GUI_SCREEN_MAIN;
6980 being_fined = NO; // until you're scanned by a copper!
6981 [self clearTargetMemory];
6982 [self setShowDemoShips:NO];
6983 [[UNIVERSE gameController] setMouseInteractionModeForFlight];
6984 [UNIVERSE setDisplayText:NO];
6985 [UNIVERSE setWitchspaceBreakPattern:YES];
6986 [self playExitWitchspace];
6987 if ([self currentSystemID] >= 0) {
6988 if (![roleSystemList containsObject:[NSNumber numberWithInt:[self currentSystemID]]]) {
6989 // going somewhere new?
6990 [self clearRoleFromPlayer:NO];
6991 }
6992 }
6993
6994 if (galactic_witchjump) {
6995 [self doScriptEvent:OOJSID("playerEnteredNewGalaxy") withArgument:[NSNumber numberWithUnsignedInt:galaxy_number]];
6996 }
6997
6998 [self doScriptEvent:OOJSID("shipWillExitWitchspace") withArgument:[self jumpCause]];
6999 [UNIVERSE setUpBreakPattern:[self breakPatternPosition] orientation:orientation forDocking:NO];
7000}
7001
7003
7005{
7006 NSString* systemName = nil;
7007 NSString* targetSystemName = nil;
7008 NSString* text = nil;
7009
7010 GuiDisplayGen* gui = [UNIVERSE gui];
7011 OOGUIScreenID oldScreen = gui_screen;
7012 if (oldScreen != GUI_SCREEN_STATUS) {
7013 [self noteGUIWillChangeTo:GUI_SCREEN_STATUS];
7014 }
7015
7016 gui_screen = GUI_SCREEN_STATUS;
7017 BOOL guiChanged = (oldScreen != gui_screen);
7018
7019 [[UNIVERSE gameController] setMouseInteractionModeForUIWithMouseInteraction:NO];
7020
7021 // Both system_seed & target_system_seed are != nil at all times when this function is called.
7022
7023 systemName = [UNIVERSE inInterstellarSpace] ? DESC(@"interstellar-space") : [UNIVERSE getSystemName:system_id];
7024 if ([self isDocked] && [self dockedStation] != [UNIVERSE station]) {
7025 systemName = [NSString stringWithFormat:@"%@ : %@", systemName, [[self dockedStation] displayName]];
7026 }
7027
7028 targetSystemName = [UNIVERSE getSystemName:target_system_id];
7029 NSDictionary* systemInfo = [[UNIVERSE systemManager] getPropertiesForSystem:target_system_id inGalaxy:galaxy_number];
7030 NSInteger concealment = [systemInfo oo_intForKey:@"concealment" defaultValue:OO_SYSTEMCONCEALMENT_NONE];
7031 if (concealment >= OO_SYSTEMCONCEALMENT_NONAME)
7032 targetSystemName = DESC(@"status-unknown-system");
7033
7034 OOSystemID nextHop = [self nextHopTargetSystemID];
7035 if (nextHop != target_system_id) {
7036 NSString* nextHopSystemName = [UNIVERSE getSystemName:nextHop];
7037 systemInfo = [[UNIVERSE systemManager] getPropertiesForSystem:nextHop inGalaxy:galaxy_number];
7038 concealment = [systemInfo oo_intForKey:@"concealment" defaultValue:OO_SYSTEMCONCEALMENT_NONE];
7039 if (concealment >= OO_SYSTEMCONCEALMENT_NONAME)
7040 nextHopSystemName = DESC(@"status-unknown-system");
7041 targetSystemName = OOExpandKey(@"status-hyperspace-system-multi", targetSystemName, nextHopSystemName);
7042 }
7043
7044 // GUI stuff
7045 {
7046 NSString* shipName = [self displayName];
7047 NSString *legal_desc = nil, *rating_desc = nil,
7048 *alert_desc = nil, *fuel_desc = nil,
7049 *credits_desc = nil;
7050
7051 OOGUIRow i;
7052 OOGUITabSettings tab_stops;
7053 tab_stops[0] = 20;
7054 tab_stops[1] = 160;
7055 tab_stops[2] = 290;
7056 [gui overrideTabs:tab_stops from:kGuiStatusTabs length:3];
7057 [gui setTabStops:tab_stops];
7058
7059 NSString* lightYearsDesc = DESC(@"status-light-years-desc");
7060
7064 fuel_desc = [NSString stringWithFormat:@"%.1f %@", fuel / 10.0, lightYearsDesc];
7065 credits_desc = OOCredits(credits);
7066
7067 [gui clearAndKeepBackground:!guiChanged];
7068 text = DESC(@"status-commander-@");
7069 [gui setTitle:[NSString stringWithFormat:text, [self commanderName]]];
7070
7071 [gui setText:shipName forRow:0 align:GUI_ALIGN_CENTER];
7072
7073 [gui setArray:[NSArray arrayWithObjects:DESC(@"status-present-system"), systemName, nil] forRow:1];
7074 if ([self hasHyperspaceMotor])
7075 [gui setArray:[NSArray arrayWithObjects:DESC(@"status-hyperspace-system"), targetSystemName, nil] forRow:2];
7076 [gui setArray:[NSArray arrayWithObjects:DESC(@"status-condition"), alert_desc, nil] forRow:3];
7077 [gui setArray:[NSArray arrayWithObjects:DESC(@"status-fuel"), fuel_desc, nil] forRow:4];
7078 [gui setArray:[NSArray arrayWithObjects:DESC(@"status-cash"), credits_desc, nil] forRow:5];
7079 [gui setArray:[NSArray arrayWithObjects:DESC(@"status-legal-status"), legal_desc, nil] forRow:6];
7080 [gui setArray:[NSArray arrayWithObjects:DESC(@"status-rating"), rating_desc, nil] forRow:7];
7081
7082 [gui setColor:[gui colorFromSetting:kGuiStatusShipnameColor defaultValue:nil] forRow:0];
7083 for (i = 1; i <= 7; ++i) {
7084 // nil default = fall back to global default colour
7085 [gui setColor:[gui colorFromSetting:kGuiStatusDataColor defaultValue:nil] forRow:i];
7086 }
7087
7088 [gui setText:DESC(@"status-equipment") forRow:9];
7089
7090 [gui setColor:[gui colorFromSetting:kGuiStatusEquipmentHeadingColor defaultValue:nil] forRow:9];
7091
7093 }
7094 /* ends */
7095
7096 if (lastTextKey) {
7097 [lastTextKey release];
7098 lastTextKey = nil;
7099 }
7100
7101 [[UNIVERSE gameView] clearMouse];
7102
7103 // Contributed by Pleb - show ship model if the appropriate user default key has been set - Nikos 20140127
7104 if (EXPECT_NOT([[NSUserDefaults standardUserDefaults] boolForKey:@"show-ship-model-in-status-screen"])) {
7105 [UNIVERSE removeDemoShips];
7107 shipData:nil
7109 factorX:2.5
7110 factorY:1.7
7111 factorZ:8.0
7112 inContext:@"GUI_SCREEN_STATUS"];
7113 [self setShowDemoShips:YES];
7114 } else {
7115 [self setShowDemoShips:NO];
7116 }
7117
7118 [UNIVERSE enterGUIViewModeWithMouseInteraction:NO];
7119
7120 if (guiChanged) {
7121 NSDictionary *fgDescriptor = nil, *bgDescriptor = nil;
7122 if ([self status] == STATUS_DOCKED) {
7123 fgDescriptor = [UNIVERSE screenTextureDescriptorForKey:@"docked_overlay"];
7124 bgDescriptor = [UNIVERSE screenTextureDescriptorForKey:@"status_docked"];
7125 } else {
7126 fgDescriptor = [UNIVERSE screenTextureDescriptorForKey:@"overlay"];
7128 bgDescriptor = [UNIVERSE screenTextureDescriptorForKey:@"status_red_alert"];
7129 else
7130 bgDescriptor = [UNIVERSE screenTextureDescriptorForKey:@"status_in_flight"];
7131 }
7132
7133 [gui setForegroundTextureDescriptor:fgDescriptor];
7134
7135 if (bgDescriptor == nil)
7136 bgDescriptor = [UNIVERSE screenTextureDescriptorForKey:@"status"];
7137 [gui setBackgroundTextureDescriptor:bgDescriptor];
7138
7139 [gui setStatusPage:0];
7140 [self noteGUIDidChangeFrom:oldScreen to:gui_screen];
7141 }
7142}
7143
7144- (NSArray*)equipmentList
7145{
7146 GuiDisplayGen* gui = [UNIVERSE gui];
7147 NSMutableArray* quip1 = [NSMutableArray array]; // damaged
7148 NSMutableArray* quip2 = [NSMutableArray array]; // working
7149 NSEnumerator* eqTypeEnum = nil;
7150 OOEquipmentType* eqType = nil;
7151 NSString* desc = nil;
7152 NSString* alldesc = nil;
7153
7154 BOOL prioritiseDamaged = [[gui userSettings] oo_boolForKey:kGuiStatusPrioritiseDamaged defaultValue:YES];
7155
7156 for (eqTypeEnum = [OOEquipmentType reverseEquipmentEnumerator]; (eqType = [eqTypeEnum nextObject]);) {
7157 if ([eqType isVisible]) {
7158 if ([eqType canCarryMultiple] && ![eqType isMissileOrMine]) {
7159 NSString* damagedIdentifier = [[eqType identifier] stringByAppendingString:@"_DAMAGED"];
7160 NSUInteger count = 0, okcount = 0;
7161 okcount = [self countEquipmentItem:[eqType identifier]];
7162 count = okcount + [self countEquipmentItem:damagedIdentifier];
7163 if (count == 0) {
7164 // do nothing
7165 }
7166 // all items okay
7167 else if (count == okcount) {
7168 // only one installed display normally
7169 if (count == 1) {
7170 [quip2 addObject:[NSArray arrayWithObjects:[eqType name], [NSNumber numberWithBool:YES], [eqType displayColor], nil]];
7171 }
7172 // display plural form
7173 else {
7174 NSString* equipmentName = [eqType name];
7175 alldesc = OOExpandKey(@"equipment-plural", count, equipmentName);
7176 [quip2 addObject:[NSArray arrayWithObjects:alldesc, [NSNumber numberWithBool:YES], [eqType displayColor], nil]];
7177 }
7178 }
7179 // all broken, only one installed
7180 else if (count == 1 && okcount == 0) {
7181 desc = [NSString stringWithFormat:DESC(@"equipment-@-not-available"), [eqType name]];
7182 if (prioritiseDamaged) {
7183 [quip1 addObject:[NSArray arrayWithObjects:desc, [NSNumber numberWithBool:NO], [eqType displayColor], nil]];
7184 } else {
7185 [quip2 addObject:[NSArray arrayWithObjects:desc, [NSNumber numberWithBool:NO], [eqType displayColor], nil]];
7186 }
7187 }
7188 // some broken, multiple installed
7189 else {
7190 NSString* equipmentName = [eqType name];
7191 alldesc = OOExpandKey(@"equipment-plural-some-na", okcount, count, equipmentName);
7192 if (prioritiseDamaged) {
7193 [quip1 addObject:[NSArray arrayWithObjects:alldesc, [NSNumber numberWithBool:NO], [eqType displayColor], nil]];
7194 } else {
7195 [quip2 addObject:[NSArray arrayWithObjects:alldesc, [NSNumber numberWithBool:NO], [eqType displayColor], nil]];
7196 }
7197 }
7198 } else if ([self hasEquipmentItem:[eqType identifier]]) {
7199 [quip2 addObject:[NSArray arrayWithObjects:[eqType name], [NSNumber numberWithBool:YES], [eqType displayColor], nil]];
7200 } else {
7201 // Check for damaged version
7202 if ([self hasEquipmentItem:[[eqType identifier] stringByAppendingString:@"_DAMAGED"]]) {
7203 desc = [NSString stringWithFormat:DESC(@"equipment-@-not-available"), [eqType name]];
7204
7205 if (prioritiseDamaged) {
7206 [quip1 addObject:[NSArray arrayWithObjects:desc, [NSNumber numberWithBool:NO], [eqType displayColor], nil]];
7207 } else {
7208 // just add in to the normal array
7209 [quip2 addObject:[NSArray arrayWithObjects:desc, [NSNumber numberWithBool:NO], [eqType displayColor], nil]];
7210 }
7211 }
7212 }
7213 }
7214 }
7215
7216 if (max_passengers > 0) {
7217 desc = [NSString stringWithFormat:DESC_PLURAL(@"equipment-pass-berth-@", max_passengers), max_passengers];
7218 [quip2 addObject:[NSArray arrayWithObjects:desc, [NSNumber numberWithBool:YES], [[OOEquipmentType equipmentTypeWithIdentifier:@"EQ_PASSENGER_BERTH"] displayColor], nil]];
7219 }
7220
7222 desc = [NSString stringWithFormat:DESC(@"equipment-fwd-weapon-@"), [forward_weapon_type name]];
7223 [quip2 addObject:[NSArray arrayWithObjects:desc, [NSNumber numberWithBool:YES], [forward_weapon_type displayColor], nil]];
7224 }
7226 desc = [NSString stringWithFormat:DESC(@"equipment-aft-weapon-@"), [aft_weapon_type name]];
7227 [quip2 addObject:[NSArray arrayWithObjects:desc, [NSNumber numberWithBool:YES], [aft_weapon_type displayColor], nil]];
7228 }
7230 desc = [NSString stringWithFormat:DESC(@"equipment-port-weapon-@"), [port_weapon_type name]];
7231 [quip2 addObject:[NSArray arrayWithObjects:desc, [NSNumber numberWithBool:YES], [port_weapon_type displayColor], nil]];
7232 }
7234 desc = [NSString stringWithFormat:DESC(@"equipment-stb-weapon-@"), [starboard_weapon_type name]];
7235 [quip2 addObject:[NSArray arrayWithObjects:desc, [NSNumber numberWithBool:YES], [starboard_weapon_type displayColor], nil]];
7236 }
7237
7238 // list damaged first, then working
7239 [quip1 addObjectsFromArray:quip2];
7240 return quip1;
7241}
7242
7244{
7245 return [eqScripts count];
7246}
7247
7248- (NSString*)primedEquipmentName:(NSInteger)offset
7249{
7250 NSUInteger c = [self primedEquipmentCount];
7251 NSUInteger idx = (primedEquipment + (c + 1) + offset) % (c + 1);
7252 if (idx == c) {
7253 return DESC(@"equipment-primed-none-hud-label");
7254 } else {
7255 return [[OOEquipmentType equipmentTypeWithIdentifier:[[eqScripts oo_arrayAtIndex:idx] oo_stringAtIndex:0]] name];
7256 }
7257}
7258
7260{
7261 NSString* result = @"";
7262 NSUInteger c = [eqScripts count];
7263 if (primedEquipment != c) {
7264 result = [[eqScripts oo_arrayAtIndex:primedEquipment] oo_stringAtIndex:0];
7265 }
7266 return result;
7267}
7268
7269- (BOOL)setPrimedEquipment:(NSString*)eqKey showMessage:(BOOL)showMsg
7270{
7271 NSUInteger c = [eqScripts count];
7272 NSUInteger current = primedEquipment;
7273 primedEquipment = [self eqScriptIndexForKey:eqKey]; // if key not found primedEquipment is set to primed-none
7274 BOOL unprimeEq = [eqKey isEqualToString:@""];
7275 BOOL result = YES;
7276
7277 if (primedEquipment == c && !unprimeEq) {
7278 primedEquipment = current;
7279 result = NO;
7280 } else {
7281 if (primedEquipment != current && showMsg == YES) {
7282 NSString* equipmentName = [[OOEquipmentType equipmentTypeWithIdentifier:[[eqScripts oo_arrayAtIndex:primedEquipment] oo_stringAtIndex:0]] name];
7283 [UNIVERSE addMessage:unprimeEq ? OOExpandKey(@"equipment-primed-none") : OOExpandKey(@"equipment-primed", equipmentName) forCount:2.0];
7284 }
7285 }
7286 return result;
7287}
7288
7289- (void)activatePrimableEquipment:(NSUInteger)index withMode:(OOPrimedEquipmentMode)mode
7290{
7291 // index == [eqScripts count] means we don't want to activate any equipment.
7292 if (index < [eqScripts count]) {
7293 OOJSScript* eqScript = [[eqScripts oo_arrayAtIndex:index] objectAtIndex:1];
7294 JSContext* context = OOJSAcquireContext();
7295 NSAssert1(mode <= OOPRIMEDEQUIP_MODE, @"Primable equipment mode %i out of range", (int)mode);
7296
7297 switch (mode) {
7298 case OOPRIMEDEQUIP_MODE:
7299 [eqScript callMethod:OOJSID("mode") inContext:context withArguments:NULL count:0 result:NULL];
7300 break;
7302 [eqScript callMethod:OOJSID("activated") inContext:context withArguments:NULL count:0 result:NULL];
7303 break;
7304 }
7305 OOJSRelinquishContext(context);
7306 }
7307}
7308
7309- (NSString*)fastEquipmentA
7310{
7311 return _fastEquipmentA;
7312}
7313
7314- (NSString*)fastEquipmentB
7315{
7316 return _fastEquipmentB;
7317}
7318
7319- (void)setFastEquipmentA:(NSString*)eqKey
7320{
7321 [_fastEquipmentA release];
7322 _fastEquipmentA = [eqKey copy];
7323}
7324
7325- (void)setFastEquipmentB:(NSString*)eqKey
7326{
7327 [_fastEquipmentB release];
7328 _fastEquipmentB = [eqKey copy];
7329}
7330
7331- (OOEquipmentType*)weaponTypeForFacing:(OOWeaponFacing)facing strict:(BOOL)strict
7332{
7333 OOWeaponType weaponType = nil;
7334
7335 switch (facing) {
7337 weaponType = forward_weapon_type;
7338 break;
7339
7340 case WEAPON_FACING_AFT:
7341 weaponType = aft_weapon_type;
7342 break;
7343
7344 case WEAPON_FACING_PORT:
7345 weaponType = port_weapon_type;
7346 break;
7347
7349 weaponType = starboard_weapon_type;
7350 break;
7351
7352 case WEAPON_FACING_NONE:
7353 break;
7354 }
7355
7356 return weaponType;
7357}
7358
7359- (NSArray*)missilesList
7360{
7361 [self tidyMissilePylons]; // just in case.
7362 return [super missilesList];
7363}
7364
7365- (NSArray*)cargoList
7366{
7367 NSMutableArray* manifest = [NSMutableArray array];
7368 NSArray* list = [self cargoListForScripting];
7369 NSDictionary* commodity;
7370
7371 if (specialCargo)
7372 [manifest addObject:specialCargo];
7373
7374 foreach (commodity, list) {
7375 NSInteger quantity = [commodity oo_integerForKey:@"quantity"];
7376 NSString* units = [commodity oo_stringForKey:@"unit"];
7377 NSString* commodityName = [commodity oo_stringForKey:@"displayName"];
7378 NSInteger containers = [commodity oo_intForKey:@"containers"];
7379 BOOL extended = ![units isEqualToString:DESC(@"cargo-tons-symbol")] && containers > 0;
7380
7381 if (extended) {
7382 [manifest addObject:OOExpandKey(@"manifest-cargo-quantity-extended", quantity, units, commodityName, containers)];
7383 } else {
7384 [manifest addObject:OOExpandKey(@"manifest-cargo-quantity", quantity, units, commodityName)];
7385 }
7386 }
7387
7388 return manifest;
7389}
7390
7392{
7393 NSMutableArray* list = [NSMutableArray array];
7394
7395 NSUInteger i, j, commodityCount = [shipCommodityData count];
7396 OOCargoQuantity quantityInHold[commodityCount];
7397 OOCargoQuantity containersInHold[commodityCount];
7398 NSArray* goods = [shipCommodityData goods];
7399
7400 // following changed to work whether docked or not
7401 for (i = 0; i < commodityCount; i++) {
7402 quantityInHold[i] = [shipCommodityData quantityForGood:[goods oo_stringAtIndex:i]];
7403 containersInHold[i] = 0;
7404 }
7405 for (i = 0; i < [cargo count]; i++) {
7406 ShipEntity* container = [cargo objectAtIndex:i];
7407 j = [goods indexOfObject:[container commodityType]];
7408 quantityInHold[j] += [container commodityAmount];
7409 ++containersInHold[j];
7410 }
7411
7412 for (i = 0; i < commodityCount; i++) {
7413 if (quantityInHold[i] > 0) {
7414 NSMutableDictionary* commodity = [NSMutableDictionary dictionaryWithCapacity:4];
7415 NSString* symName = [goods oo_stringAtIndex:i];
7416 // commodity, quantity - keep consistency between .manifest and .contracts
7417 [commodity setObject:symName forKey:@"commodity"];
7418 [commodity setObject:[NSNumber numberWithUnsignedInt:quantityInHold[i]] forKey:@"quantity"];
7419 [commodity setObject:[NSNumber numberWithUnsignedInt:containersInHold[i]] forKey:@"containers"];
7420 [commodity setObject:[shipCommodityData nameForGood:symName] forKey:@"displayName"];
7421 [commodity setObject:DisplayStringForMassUnitForCommodity(symName) forKey:@"unit"];
7422 [list addObject:commodity];
7423 }
7424 }
7425
7426 return [[list copy] autorelease]; // return an immutable copy
7427}
7428
7429// determines general export legality, not tied to a station
7431{
7432 NSString* good = nil;
7433 OOCargoQuantity amount;
7434 unsigned penalty = 0;
7435
7436 foreach (good, [shipCommodityData goods]) {
7437 amount = [shipCommodityData quantityForGood:good];
7438 penalty += [shipCommodityData exportLegalityForGood:good] * amount;
7439 }
7440 return penalty;
7441}
7442
7443- (NSArray*)contractsListForScriptingFromArray:(NSArray*)contracts_array forCargo:(BOOL)forCargo
7444{
7445 NSMutableArray* result = [NSMutableArray array];
7446 NSUInteger i;
7447
7448 for (i = 0; i < [contracts_array count]; i++) {
7449 NSMutableDictionary* contract = [NSMutableDictionary dictionaryWithCapacity:10];
7450 NSDictionary* dict = [contracts_array oo_dictionaryAtIndex:i];
7451 if (forCargo) {
7452 // commodity, quantity - keep consistency between .manifest and .contracts
7453 [contract setObject:[dict oo_stringForKey:CARGO_KEY_TYPE] forKey:@"commodity"];
7454 [contract setObject:[NSNumber numberWithUnsignedInt:[dict oo_intForKey:CARGO_KEY_AMOUNT]] forKey:@"quantity"];
7455 [contract setObject:[dict oo_stringForKey:CARGO_KEY_DESCRIPTION] forKey:@"description"];
7456 } else {
7457 [contract setObject:[dict oo_stringForKey:PASSENGER_KEY_NAME] forKey:PASSENGER_KEY_NAME];
7458 [contract setObject:[NSNumber numberWithUnsignedInt:[dict oo_unsignedIntForKey:CONTRACT_KEY_RISK]] forKey:CONTRACT_KEY_RISK];
7459 }
7460
7461 OOSystemID planet = [dict oo_intForKey:CONTRACT_KEY_DESTINATION];
7462 NSString* planetName = [UNIVERSE getSystemName:planet];
7463 [contract setObject:[NSNumber numberWithUnsignedInt:planet] forKey:CONTRACT_KEY_DESTINATION];
7464 [contract setObject:planetName forKey:@"destinationName"];
7465 planet = [dict oo_intForKey:CONTRACT_KEY_START];
7466 planetName = [UNIVERSE getSystemName:planet];
7467 [contract setObject:[NSNumber numberWithUnsignedInt:planet] forKey:CONTRACT_KEY_START];
7468 [contract setObject:planetName forKey:@"startName"];
7469
7470 int dest_eta = [dict oo_doubleForKey:CONTRACT_KEY_ARRIVAL_TIME] - ship_clock;
7471 [contract setObject:[NSNumber numberWithInt:dest_eta] forKey:@"eta"];
7472 [contract setObject:[UNIVERSE shortTimeDescription:dest_eta] forKey:@"etaDescription"];
7473 [contract setObject:[NSNumber numberWithInt:[dict oo_intForKey:CONTRACT_KEY_PREMIUM]] forKey:CONTRACT_KEY_PREMIUM];
7474 [contract setObject:[NSNumber numberWithInt:[dict oo_intForKey:CONTRACT_KEY_FEE]] forKey:CONTRACT_KEY_FEE];
7475 [result addObject:contract];
7476 }
7477
7478 return [[result copy] autorelease]; // return an immutable copy
7479}
7480
7482{
7483 return [self contractsListForScriptingFromArray:passengers forCargo:NO];
7484}
7485
7487{
7488 return [self contractsListForScriptingFromArray:parcels forCargo:NO];
7489}
7490
7492{
7493 return [self contractsListForScriptingFromArray:contracts forCargo:YES];
7494}
7495
7500
7501- (void)setGuiToSystemDataScreenRefreshBackground:(BOOL)refreshBackground
7502{
7503 NSDictionary* infoSystemData;
7504 NSString* infoSystemName;
7505
7506 infoSystemData = [[UNIVERSE generateSystemData:info_system_id] retain]; // retained
7507 NSInteger concealment = [infoSystemData oo_intForKey:@"concealment" defaultValue:OO_SYSTEMCONCEALMENT_NONE];
7508 infoSystemName = [infoSystemData oo_stringForKey:KEY_NAME];
7509
7510 BOOL sunGoneNova = ([infoSystemData oo_boolForKey:@"sun_gone_nova"]);
7511 OOGUIScreenID oldScreen = gui_screen;
7512
7513 GuiDisplayGen* gui = [UNIVERSE gui];
7514 gui_screen = GUI_SCREEN_SYSTEM_DATA;
7515 BOOL guiChanged = (oldScreen != gui_screen);
7516
7517 Random_Seed infoSystemRandomSeed = [[UNIVERSE systemManager] getRandomSeedForSystem:info_system_id
7518 inGalaxy:[self galaxyNumber]];
7519
7520 [[UNIVERSE gameController] setMouseInteractionModeForUIWithMouseInteraction:NO];
7521
7522 // GUI stuff
7523 {
7524 OOGUITabSettings tab_stops;
7525 tab_stops[0] = 0;
7526 tab_stops[1] = 96;
7527 tab_stops[2] = 144;
7528 [gui overrideTabs:tab_stops from:kGuiSystemdataTabs length:3];
7529 [gui setTabStops:tab_stops];
7530
7531 NSUInteger techLevel = [infoSystemData oo_intForKey:KEY_TECHLEVEL] + 1;
7532 int population = [infoSystemData oo_intForKey:KEY_POPULATION];
7533 int productivity = [infoSystemData oo_intForKey:KEY_PRODUCTIVITY];
7534 int radius = [infoSystemData oo_intForKey:KEY_RADIUS];
7535
7536 NSString* government_desc = [infoSystemData oo_stringForKey:KEY_GOVERNMENT_DESC
7537 defaultValue:OODisplayStringFromGovernmentID([infoSystemData oo_intForKey:KEY_GOVERNMENT])];
7538 NSString* economy_desc = [infoSystemData oo_stringForKey:KEY_ECONOMY_DESC
7539 defaultValue:OODisplayStringFromEconomyID([infoSystemData oo_intForKey:KEY_ECONOMY])];
7540 NSString* inhabitants = [infoSystemData oo_stringForKey:KEY_INHABITANTS];
7541 NSString* system_desc = [infoSystemData oo_stringForKey:KEY_DESCRIPTION];
7542
7543 NSString* populationDesc = [infoSystemData oo_stringForKey:KEY_POPULATION_DESC
7544 defaultValue:OOExpandKeyWithSeed(kNilRandomSeed, @"sysdata-pop-value", population)];
7545
7546 if (sunGoneNova) {
7547 population = 0;
7548 productivity = 0;
7549 radius = 0;
7550 techLevel = 0;
7551
7552 government_desc = OOExpandKeyWithSeed(infoSystemRandomSeed, @"nova-system-government");
7553 economy_desc = OOExpandKeyWithSeed(infoSystemRandomSeed, @"nova-system-economy");
7554 inhabitants = OOExpandKeyWithSeed(infoSystemRandomSeed, @"nova-system-inhabitants");
7555 {
7556 NSString* system = infoSystemName;
7557 system_desc = OOExpandKeyWithSeed(infoSystemRandomSeed, @"nova-system-description", system);
7558 }
7559 populationDesc = OOExpandKeyWithSeed(infoSystemRandomSeed, @"sysdata-pop-value", population);
7560 }
7561
7562 [gui clearAndKeepBackground:!refreshBackground && !guiChanged];
7563 [UNIVERSE removeDemoShips];
7564
7565 if (concealment < OO_SYSTEMCONCEALMENT_NONAME) {
7566 NSString* system = infoSystemName;
7567 [gui setTitle:OOExpandKeyWithSeed(infoSystemRandomSeed, @"sysdata-data-on-system", system)];
7568 } else {
7569 [gui setTitle:OOExpandKey(@"sysdata-data-on-system-no-name")];
7570 }
7571
7572 if (concealment >= OO_SYSTEMCONCEALMENT_NODATA) {
7573 OOGUIRow i = [gui addLongText:OOExpandKey(@"sysdata-data-on-system-no-data") startingAtRow:15 align:GUI_ALIGN_LEFT];
7574 missionTextRow = i;
7575 for (i--; i > 14; --i) {
7576 [gui setColor:[gui colorFromSetting:kGuiSystemdataDescriptionColor defaultValue:[OOColor greenColor]] forRow:i];
7577 }
7578 } else {
7579 NSPoint infoSystemCoordinates = [[UNIVERSE systemManager] getCoordinatesForSystem:info_system_id inGalaxy:galaxy_number];
7580 double distance = distanceBetweenPlanetPositions(infoSystemCoordinates.x, infoSystemCoordinates.y, galaxy_coordinates.x, galaxy_coordinates.y);
7581 if (distance == 0.0 && info_system_id != system_id) {
7582 distance = 0.1;
7583 }
7584 NSString* distanceInfo = [NSString stringWithFormat:@"%.1f ly", distance];
7585 if (ANA_mode != OPTIMIZED_BY_NONE) {
7586 NSDictionary* routeInfo = nil;
7587 routeInfo = [UNIVERSE routeFromSystem:system_id toSystem:info_system_id optimizedBy:ANA_mode];
7588 if (routeInfo != nil) {
7589 double routeDistance = [[routeInfo objectForKey:@"distance"] doubleValue];
7590 double routeTime = [[routeInfo objectForKey:@"time"] doubleValue];
7591 int routeJumps = [[routeInfo objectForKey:@"jumps"] intValue];
7592 if (routeDistance == 0.0 && info_system_id != system_id) {
7593 routeDistance = 0.1;
7594 routeTime = 0.01;
7595 routeJumps = 0;
7596 }
7597 distanceInfo = [NSString stringWithFormat:@"%.1f ly / %.1f %@ / %d %@",
7598 routeDistance,
7599 routeTime,
7600 // don't rely on DESC_PLURAL for routeTime since it is of type double
7601 routeTime > 1.05 || routeTime < 0.95 ? DESC(@"sysdata-route-hours%1") : DESC(@"sysdata-route-hours%0"),
7602 routeJumps,
7603 DESC_PLURAL(@"sysdata-route-jumps", routeJumps)];
7604 }
7605 }
7606
7607 OOGUIRow i;
7608
7609 for (i = 1; i <= 16; i++) {
7610 NSString* ln = [NSString stringWithFormat:@"sysdata-line-%ld", (long)i];
7611 NSString* line = OOExpandKeyWithSeed(infoSystemRandomSeed, ln, economy_desc, government_desc, techLevel, populationDesc, inhabitants, productivity, radius, distanceInfo);
7612 if (![line isEqualToString:@""]) {
7613 NSArray* lines = [line componentsSeparatedByString:@"\t"];
7614 if ([lines count] == 1) {
7615 [gui setArray:[NSArray arrayWithObjects:[lines objectAtIndex:0],
7616 nil]
7617 forRow:i];
7618 }
7619 if ([lines count] == 2) {
7620 [gui setArray:[NSArray arrayWithObjects:[lines objectAtIndex:0],
7621 [lines objectAtIndex:1],
7622 nil]
7623 forRow:i];
7624 }
7625 if ([lines count] == 3) {
7626 if ([[lines objectAtIndex:2] isEqualToString:@""]) {
7627 [gui setArray:[NSArray arrayWithObjects:[lines objectAtIndex:0],
7628 [lines objectAtIndex:1],
7629 nil]
7630 forRow:i];
7631 } else {
7632 [gui setArray:[NSArray arrayWithObjects:[lines objectAtIndex:0],
7633 [lines objectAtIndex:1],
7634 [lines objectAtIndex:2],
7635 nil]
7636 forRow:i];
7637 }
7638 }
7639 } else {
7640 [gui setArray:[NSArray arrayWithObjects:@"",
7641 nil]
7642 forRow:i];
7643 }
7644 }
7645
7646 i = [gui addLongText:system_desc startingAtRow:17 align:GUI_ALIGN_LEFT];
7647 missionTextRow = i;
7648 for (i--; i > 16; --i) {
7649 [gui setColor:[gui colorFromSetting:kGuiSystemdataDescriptionColor defaultValue:[OOColor greenColor]] forRow:i];
7650 }
7651 for (i = 1; i <= 14; ++i) {
7652 // nil default = fall back to global default colour
7653 [gui setColor:[gui colorFromSetting:kGuiSystemdataFactsColor defaultValue:nil] forRow:i];
7654 }
7655 }
7656
7658 }
7659 /* ends */
7660
7661 [lastTextKey release];
7662 lastTextKey = nil;
7663
7664 [[UNIVERSE gameView] clearMouse];
7665
7666 [infoSystemData release];
7667
7668 [self setShowDemoShips:NO];
7669 [UNIVERSE enterGUIViewModeWithMouseInteraction:NO];
7670
7671 // if the system has gone nova, there's no planet to display
7672 if (!sunGoneNova && concealment < OO_SYSTEMCONCEALMENT_NODATA) {
7673 // The next code is generating the miniature planets.
7674 // When normal planets are displayed, the PRNG is reset. This happens not with procedural planet display.
7675 RANROTSeed ranrotSavedSeed = RANROTGetFullSeed();
7676 RNG_Seed saved_seed = currentRandomSeed();
7677
7678 if (info_system_id == system_id) {
7679 [self setBackgroundFromDescriptionsKey:@"gui-scene-show-local-planet"];
7680 } else {
7681 [self setBackgroundFromDescriptionsKey:@"gui-scene-show-planet"];
7682 }
7683
7684 setRandomSeed(saved_seed);
7685 RANROTSetFullSeed(ranrotSavedSeed);
7686 }
7687
7688 if (refreshBackground || guiChanged) {
7689 [gui setForegroundTextureKey:[self status] == STATUS_DOCKED ? @"docked_overlay" : @"overlay"];
7690 [gui setBackgroundTextureKey:sunGoneNova ? @"system_data_nova" : @"system_data"];
7691
7692 [self noteGUIDidChangeFrom:oldScreen to:gui_screen refresh:refreshBackground];
7693 [self checkScript]; // Still needed by some OXPs?
7694 }
7695}
7696
7697- (void)prepareMarkedDestination:(NSMutableDictionary*)markers marker:(NSDictionary*)marker
7698{
7699 NSNumber* key = [NSNumber numberWithInt:[marker oo_intForKey:@"system"]];
7700 NSMutableArray* list = [markers objectForKey:key];
7701 if (list == nil) {
7702 list = [NSMutableArray arrayWithObject:marker];
7703 } else {
7704 [list addObject:marker];
7705 }
7706 [markers setObject:list forKey:key];
7707}
7708
7709- (NSDictionary*)markedDestinations
7710{
7711 // get a list of systems marked as contract destinations
7712 NSMutableDictionary* destinations = [NSMutableDictionary dictionaryWithCapacity:256];
7713 unsigned i;
7714 OOSystemID sysid;
7715 NSDictionary* marker;
7716
7717 for (i = 0; i < [passengers count]; i++) {
7718 sysid = [[passengers oo_dictionaryAtIndex:i] oo_unsignedCharForKey:CONTRACT_KEY_DESTINATION];
7719 marker = [self passengerContractMarker:sysid];
7720 [self prepareMarkedDestination:destinations marker:marker];
7721 }
7722 for (i = 0; i < [parcels count]; i++) {
7723 sysid = [[parcels oo_dictionaryAtIndex:i] oo_unsignedCharForKey:CONTRACT_KEY_DESTINATION];
7724 marker = [self parcelContractMarker:sysid];
7725 [self prepareMarkedDestination:destinations marker:marker];
7726 }
7727 for (i = 0; i < [contracts count]; i++) {
7728 sysid = [[contracts oo_dictionaryAtIndex:i] oo_unsignedCharForKey:CONTRACT_KEY_DESTINATION];
7729 marker = [self cargoContractMarker:sysid];
7730 [self prepareMarkedDestination:destinations marker:marker];
7731 }
7732
7733 NSString* key = nil;
7734
7736 {
7737 marker = [missionDestinations objectForKey:key];
7738 [self prepareMarkedDestination:destinations marker:marker];
7739 }
7740
7741 return destinations;
7742}
7743
7745{
7746 OOGUIScreenID oldScreen = gui_screen;
7747 GuiDisplayGen* gui = [UNIVERSE gui];
7749 [gui setBackgroundTextureKey:@"short_range_chart"];
7750 [self setMissionBackgroundSpecial:nil];
7751 gui_screen = GUI_SCREEN_LONG_RANGE_CHART;
7753 [self setGuiToChartScreenFrom:oldScreen];
7754}
7755
7757{
7758 OOGUIScreenID oldScreen = gui_screen;
7759 GuiDisplayGen* gui = [UNIVERSE gui];
7761 [gui setBackgroundTextureKey:@"short_range_chart"];
7762 [self setMissionBackgroundSpecial:nil];
7763 gui_screen = GUI_SCREEN_SHORT_RANGE_CHART;
7764 [self setGuiToChartScreenFrom:oldScreen];
7765}
7766
7767- (void)setGuiToChartScreenFrom:(OOGUIScreenID)oldScreen
7768{
7769 GuiDisplayGen* gui = [UNIVERSE gui];
7770
7771 BOOL guiChanged = (oldScreen != gui_screen);
7772
7773 [[UNIVERSE gameController] setMouseInteractionModeForUIWithMouseInteraction:YES];
7774
7775 target_system_id = [UNIVERSE findSystemNumberAtCoords:cursor_coordinates withGalaxy:galaxy_number includingHidden:NO];
7776
7777 [UNIVERSE preloadPlanetTexturesForSystem:target_system_id];
7778
7779 // GUI stuff
7780 {
7781 //[gui clearAndKeepBackground:!guiChanged];
7783 // refresh the short range chart cache, in case we've just loaded a save game with different local overrides, etc.
7785 //[gui setText:targetSystemName forRow:19];
7786 // distance-f & est-travel-time-f are identical between short & long range charts in standard Oolite, however can be alterered separately via OXPs
7787 //[gui setText:OOExpandKey(@"short-range-chart-distance", distance) forRow:20];
7788 // NSString *travelTimeRow = @"";
7789 // if ([self hasHyperspaceMotor] && distance > 0.0 && distance * 10.0 <= fuel)
7790 //{
7791 // double time = estimatedTravelTime;
7792 // travelTimeRow = OOExpandKey(@"short-range-chart-est-travel-time", time);
7793 //}
7794 //[gui setText:travelTimeRow forRow:21];
7795 if (gui_screen == GUI_SCREEN_LONG_RANGE_CHART) {
7796 NSString* displaySearchString = planetSearchString ? [planetSearchString capitalizedString] : (NSString*)@"";
7797 [gui setText:[NSString stringWithFormat:DESC(@"long-range-chart-find-planet-@"), displaySearchString] forRow:GUI_ROW_PLANET_FINDER];
7798 [gui setColor:[OOColor cyanColor] forRow:GUI_ROW_PLANET_FINDER];
7799 [gui setShowTextCursor:YES];
7800 [gui setCurrentRow:GUI_ROW_PLANET_FINDER];
7801 } else {
7803 }
7804 }
7805 /* ends */
7806
7807 [self setShowDemoShips:NO];
7808 [UNIVERSE enterGUIViewModeWithMouseInteraction:YES];
7809
7810 if (guiChanged) {
7811 [gui setForegroundTextureKey:[self status] == STATUS_DOCKED ? @"docked_overlay" : @"overlay"];
7812
7813 [gui setBackgroundTextureKey:@"short_range_chart"];
7814 if (found_system_id >= 0) {
7815 [UNIVERSE findSystemCoordinatesWithPrefix:[[UNIVERSE getSystemName:found_system_id] lowercaseString] exactMatch:YES];
7816 }
7817 [self noteGUIDidChangeFrom:oldScreen to:gui_screen];
7818 }
7819}
7820
7821static NSString* SliderString(NSInteger amountIn20ths)
7822{
7823 NSString* filledSlider = [@"|||||||||||||||||||||||||" substringToIndex:amountIn20ths];
7824 NSString* emptySlider = [@"........................." substringToIndex:20 - amountIn20ths];
7825 return [NSString stringWithFormat:@"%@%@", filledSlider, emptySlider];
7826}
7827
7829{
7830 MyOpenGLView* gameView = [UNIVERSE gameView];
7831
7832 [[UNIVERSE gameView] clearMouse];
7833 [[UNIVERSE gameController] setMouseInteractionModeForUIWithMouseInteraction:YES];
7834
7835 gui_screen = GUI_SCREEN_GAMEOPTIONS;
7836
7837 // GUI stuff
7838 {
7839#define OO_SETACCESSCONDITIONFORROW(condition, row) \
7840 do { \
7841 if ((condition)) { \
7842 [gui setKey:GUI_KEY_OK forRow:(row)]; \
7843 } else { \
7844 [gui setColor:[OOColor grayColor] forRow:(row)]; \
7845 } \
7846 } while (0)
7847 BOOL startingGame = [self status] == STATUS_START_GAME;
7848 GuiDisplayGen* gui = [UNIVERSE gui];
7849 GUI_ROW_INIT(gui);
7850
7851 int first_sel_row = GUI_FIRST_ROW(GAME) - 4; // repositioned menu
7852
7853 [gui clear];
7854 [gui setTitle:[NSString stringWithFormat:DESC(@"status-commander-@"), [self commanderName]]]; // Same title as status screen.
7855
7856#if OO_RESOLUTION_OPTION
7857 GameController* controller = [UNIVERSE gameController];
7858
7859 NSUInteger displayModeIndex = [controller indexOfCurrentDisplayMode];
7860 if (displayModeIndex == NSNotFound) {
7861 OOLogWARN(@"display.currentMode.notFound", @"%@", @"couldn't find current fullscreen setting, switching to default.");
7862 displayModeIndex = 0;
7863 }
7864
7865 NSArray* modeList = [controller displayModes];
7866 NSDictionary* mode = nil;
7867 if ([modeList count]) {
7868 mode = [modeList objectAtIndex:displayModeIndex];
7869 }
7870 if (mode == nil)
7871 return; // Got a better idea?
7872
7873 unsigned modeWidth = [mode oo_unsignedIntForKey:kOODisplayWidth];
7874 unsigned modeHeight = [mode oo_unsignedIntForKey:kOODisplayHeight];
7875 float modeRefresh = [mode oo_floatForKey:kOODisplayRefreshRate];
7876
7877 BOOL runningOnPrimaryDisplayDevice = [gameView isRunningOnPrimaryDisplayDevice];
7878 if (!runningOnPrimaryDisplayDevice) {
7879 [gameView getDisplayDimensions:&modeWidth height:&modeHeight];
7880 }
7881
7882 NSString* displayModeString = [self screenModeStringForWidth:modeWidth height:modeHeight refreshRate:modeRefresh];
7883
7884 [gui setText:displayModeString forRow:GUI_ROW(GAME, DISPLAY) align:GUI_ALIGN_CENTER];
7885 if (runningOnPrimaryDisplayDevice) {
7886 [gui setKey:GUI_KEY_OK forRow:GUI_ROW(GAME, DISPLAY)];
7887 } else {
7888 [gui setColor:[OOColor grayColor] forRow:GUI_ROW(GAME, DISPLAY)];
7889 }
7890#endif // OO_RESOLUTIOM_OPTION
7891
7892#if OOLITE_WINDOWS
7893 if ([gameView hdrOutput]) {
7894 NSArray* brightnesses = [[UNIVERSE descriptions] oo_arrayForKey:@"hdr_maxBrightness_array"];
7895 int brightnessIdx = [brightnesses indexOfObject:[NSString stringWithFormat:@"%d", (int)[gameView hdrMaxBrightness]]];
7896
7897 if (brightnessIdx == NSNotFound) {
7898 OOLogWARN(@"hdr.maxBrightness.notFound", @"%@", @"couldn't find current max brightness setting, switching to 400 nits.");
7899 brightnessIdx = 0;
7900 }
7901
7902 int brightnessValue = [brightnesses oo_intAtIndex:brightnessIdx];
7903 NSString* maxBrightnessString = OOExpandKey(@"gameoptions-hdr-maxbrightness", brightnessValue);
7904
7905 [gui setText:maxBrightnessString forRow:GUI_ROW(GAME, HDRMAXBRIGHTNESS) align:GUI_ALIGN_CENTER];
7906 [gui setKey:GUI_KEY_OK forRow:GUI_ROW(GAME, HDRMAXBRIGHTNESS)];
7907 }
7908#endif
7909
7910 if ([UNIVERSE autoSave])
7911 [gui setText:DESC(@"gameoptions-autosave-yes") forRow:GUI_ROW(GAME, AUTOSAVE) align:GUI_ALIGN_CENTER];
7912 else
7913 [gui setText:DESC(@"gameoptions-autosave-no") forRow:GUI_ROW(GAME, AUTOSAVE) align:GUI_ALIGN_CENTER];
7914 [gui setKey:GUI_KEY_OK forRow:GUI_ROW(GAME, AUTOSAVE)];
7915
7916 // volume control
7917 if ([OOSound respondsToSelector:@selector(masterVolume)] && [OOSound isSoundOK]) {
7918 double volume = 100.0 * [OOSound masterVolume];
7919 int vol = (volume / 5.0 + 0.5); // avoid rounding errors
7920 NSString* soundVolumeWordDesc = DESC(@"gameoptions-sound-volume");
7921 if (vol > 0)
7922 [gui setText:[NSString stringWithFormat:@"%@%@ ", soundVolumeWordDesc, SliderString(vol)] forRow:GUI_ROW(GAME, VOLUME) align:GUI_ALIGN_CENTER];
7923 else
7924 [gui setText:DESC(@"gameoptions-sound-volume-mute") forRow:GUI_ROW(GAME, VOLUME) align:GUI_ALIGN_CENTER];
7925 [gui setKey:GUI_KEY_OK forRow:GUI_ROW(GAME, VOLUME)];
7926 } else {
7927 [gui setText:DESC(@"gameoptions-volume-external-only") forRow:GUI_ROW(GAME, VOLUME) align:GUI_ALIGN_CENTER];
7928 [gui setColor:[OOColor grayColor] forRow:GUI_ROW(GAME, VOLUME)];
7929 }
7930
7931 // field of view control
7932 float fov = [gameView fov:NO];
7933 int fovTicks = (int)((fov - MIN_FOV_DEG) * 20 / (MAX_FOV_DEG - MIN_FOV_DEG));
7934 NSString* fovWordDesc = DESC(@"gameoptions-fov-value");
7935 [gui setText:[NSString stringWithFormat:@"%@%@ (%d%c) ", fovWordDesc, SliderString(fovTicks), (int)fov, 176 /*176 is the degrees symbol Unicode code point*/] forRow:GUI_ROW(GAME, FOV) align:GUI_ALIGN_CENTER];
7936 [gui setKey:GUI_KEY_OK forRow:GUI_ROW(GAME, FOV)];
7937
7938 // color blind mode
7939 int colorblindMode = [UNIVERSE colorblindMode];
7940 NSString* colorblindModeDesc = [[[UNIVERSE descriptions] oo_arrayForKey:@"colorblind_mode"] oo_stringAtIndex:[UNIVERSE useShaders] ? colorblindMode : 0];
7941 NSString* colorblindModeMsg = OOExpandKey(@"gameoptions-colorblind-mode", colorblindModeDesc);
7942 [gui setText:colorblindModeMsg forRow:GUI_ROW(GAME, COLORBLINDMODE) align:GUI_ALIGN_CENTER];
7943 if ([UNIVERSE useShaders]) {
7944 [gui setKey:GUI_KEY_OK forRow:GUI_ROW(GAME, COLORBLINDMODE)];
7945 } else {
7946 [gui setColor:[OOColor grayColor] forRow:GUI_ROW(GAME, COLORBLINDMODE)];
7947 }
7948
7949#if OOLITE_SPEECH_SYNTH
7950 // Speech control
7951 switch (isSpeechOn) {
7953 [gui setText:DESC(@"gameoptions-spoken-messages-no") forRow:GUI_ROW(GAME, SPEECH) align:GUI_ALIGN_CENTER];
7954 break;
7956 [gui setText:DESC(@"gameoptions-spoken-messages-comms") forRow:GUI_ROW(GAME, SPEECH) align:GUI_ALIGN_CENTER];
7957 break;
7959 [gui setText:DESC(@"gameoptions-spoken-messages-yes") forRow:GUI_ROW(GAME, SPEECH) align:GUI_ALIGN_CENTER];
7960 break;
7961 }
7962 OO_SETACCESSCONDITIONFORROW(!startingGame, GUI_ROW(GAME, SPEECH));
7963
7964#if OOLITE_ESPEAK
7965 {
7966 NSString* voiceName = [UNIVERSE voiceName:voice_no];
7967 NSString* message = OOExpandKey(@"gameoptions-voice-name", voiceName);
7968 [gui setText:message forRow:GUI_ROW(GAME, SPEECH_LANGUAGE) align:GUI_ALIGN_CENTER];
7969 OO_SETACCESSCONDITIONFORROW(!startingGame, GUI_ROW(GAME, SPEECH_LANGUAGE));
7970
7971 message = [NSString stringWithFormat:@"%@", DESC(voice_gender_m ? @"gameoptions-voice-M" : @"gameoptions-voice-F")];
7972 [gui setText:message forRow:GUI_ROW(GAME, SPEECH_GENDER) align:GUI_ALIGN_CENTER];
7973 OO_SETACCESSCONDITIONFORROW(!startingGame, GUI_ROW(GAME, SPEECH_GENDER));
7974 }
7975#endif
7976#endif
7977#if !OOLITE_MAC_COCOA_UI
7978 // window/fullscreen
7979 if ([gameView inFullScreenMode]) {
7980 [gui setText:DESC(@"gameoptions-play-in-window") forRow:GUI_ROW(GAME, DISPLAYSTYLE) align:GUI_ALIGN_CENTER];
7981 } else {
7982 [gui setText:DESC(@"gameoptions-play-in-fullscreen") forRow:GUI_ROW(GAME, DISPLAYSTYLE) align:GUI_ALIGN_CENTER];
7983 }
7984 [gui setKey:GUI_KEY_OK forRow:GUI_ROW(GAME, DISPLAYSTYLE)];
7985#endif
7986
7987 [gui setText:DESC(@"gameoptions-joystick-configuration")
7988 forRow:GUI_ROW(GAME, STICKMAPPER)
7989 align:GUI_ALIGN_CENTER];
7990 OO_SETACCESSCONDITIONFORROW([[OOJoystickManager sharedStickHandler] joystickCount], GUI_ROW(GAME, STICKMAPPER));
7991
7992 [gui setText:DESC(@"gameoptions-keyboard-configuration") forRow:GUI_ROW(GAME, KEYMAPPER) align:GUI_ALIGN_CENTER];
7993 [gui setKey:GUI_KEY_OK forRow:GUI_ROW(GAME, KEYMAPPER)];
7994
7995 NSString* musicMode = [UNIVERSE descriptionForArrayKey:@"music-mode" index:[[OOMusicController sharedController] mode]];
7996 NSString* message = OOExpandKey(@"gameoptions-music-mode", musicMode);
7997 [gui setText:message forRow:GUI_ROW(GAME, MUSIC) align:GUI_ALIGN_CENTER];
7998 [gui setKey:GUI_KEY_OK forRow:GUI_ROW(GAME, MUSIC)];
7999
8000 if (![gameView hdrOutput]) {
8001 if ([UNIVERSE wireframeGraphics])
8002 [gui setText:DESC(@"gameoptions-wireframe-graphics-yes") forRow:GUI_ROW(GAME, WIREFRAMEGRAPHICS) align:GUI_ALIGN_CENTER];
8003 else
8004 [gui setText:DESC(@"gameoptions-wireframe-graphics-no") forRow:GUI_ROW(GAME, WIREFRAMEGRAPHICS) align:GUI_ALIGN_CENTER];
8005 [gui setKey:GUI_KEY_OK forRow:GUI_ROW(GAME, WIREFRAMEGRAPHICS)];
8006 }
8007#if OOLITE_WINDOWS
8008 else {
8009 float paperWhite = [gameView hdrPaperWhiteBrightness];
8010 int paperWhiteTicks = (int)((paperWhite - MIN_HDR_PAPERWHITE) * 20 / (MAX_HDR_PAPERWHITE - MIN_HDR_PAPERWHITE));
8011 NSString* paperWhiteWordDesc = DESC(@"gameoptions-hdr-paperwhite");
8012 [gui setText:[NSString stringWithFormat:@"%@%@ (%d) ", paperWhiteWordDesc, SliderString(paperWhiteTicks), (int)paperWhite] forRow:GUI_ROW(GAME, HDRPAPERWHITE) align:GUI_ALIGN_CENTER];
8013 [gui setKey:GUI_KEY_OK forRow:GUI_ROW(GAME, HDRPAPERWHITE)];
8014 }
8015#endif
8016
8017#if !NEW_PLANETS
8018 if ([UNIVERSE doProcedurallyTexturedPlanets])
8019 [gui setText:DESC(@"gameoptions-procedurally-textured-planets-yes") forRow:GUI_ROW(GAME, PROCEDURALLYTEXTUREDPLANETS) align:GUI_ALIGN_CENTER];
8020 else
8021 [gui setText:DESC(@"gameoptions-procedurally-textured-planets-no") forRow:GUI_ROW(GAME, PROCEDURALLYTEXTUREDPLANETS) align:GUI_ALIGN_CENTER];
8022 [gui setKey:GUI_KEY_OK forRow:GUI_ROW(GAME, PROCEDURALLYTEXTUREDPLANETS)];
8023#endif
8024
8025 OOGraphicsDetail detailLevel = [UNIVERSE detailLevel];
8026 NSString* shaderEffectsOptionsString = OOExpand(@"gameoptions-detaillevel-[detailLevel]", detailLevel);
8027 [gui setText:OOExpandKey(shaderEffectsOptionsString) forRow:GUI_ROW(GAME, SHADEREFFECTS) align:GUI_ALIGN_CENTER];
8028 if (![[OOOpenGLExtensionManager sharedManager] shadersForceDisabled]) {
8029 [gui setKey:GUI_KEY_OK forRow:GUI_ROW(GAME, SHADEREFFECTS)];
8030 } else {
8031 // deactivate this option if shaders have been disabled from the commend line
8032 [gui setColor:[OOColor grayColor] forRow:GUI_ROW(GAME, SHADEREFFECTS)];
8033 }
8034
8035 if ([UNIVERSE dockingClearanceProtocolActive]) {
8036 [gui setText:DESC(@"gameoptions-docking-clearance-yes") forRow:GUI_ROW(GAME, DOCKINGCLEARANCE) align:GUI_ALIGN_CENTER];
8037 } else {
8038 [gui setText:DESC(@"gameoptions-docking-clearance-no") forRow:GUI_ROW(GAME, DOCKINGCLEARANCE) align:GUI_ALIGN_CENTER];
8039 }
8040 OO_SETACCESSCONDITIONFORROW(!startingGame, GUI_ROW(GAME, DOCKINGCLEARANCE));
8041
8042 // Back menu option
8043 [gui setText:DESC(@"gui-back") forRow:GUI_ROW(GAME, BACK) align:GUI_ALIGN_CENTER];
8044 [gui setKey:GUI_KEY_OK forRow:GUI_ROW(GAME, BACK)];
8045
8046 [gui setSelectableRange:NSMakeRange(first_sel_row, GUI_ROW_GAMEOPTIONS_END_OF_LIST)];
8047 [gui setSelectedRow:first_sel_row];
8048
8050 [gui setForegroundTextureKey:[self status] == STATUS_DOCKED ? @"docked_overlay" : @"paused_overlay"];
8051 [gui setBackgroundTextureKey:@"settings"];
8052 }
8053 /* ends */
8054
8055 [self setShowDemoShips:NO];
8056 [UNIVERSE enterGUIViewModeWithMouseInteraction:YES];
8057}
8058
8060{
8061 BOOL gamePaused = [[UNIVERSE gameController] isGamePaused];
8062 BOOL canLoadOrSave = NO;
8063 MyOpenGLView* gameView = [UNIVERSE gameView];
8064 OOGUIScreenID oldScreen = gui_screen;
8065
8066 [[UNIVERSE gameController] setMouseInteractionModeForUIWithMouseInteraction:YES];
8067
8068 gui_screen = GUI_SCREEN_OPTIONS;
8069
8070 if ([self status] == STATUS_DOCKED) {
8071 if ([self dockedStation] == nil)
8073 canLoadOrSave = (([self dockedStation] == [UNIVERSE station] || [[self dockedStation] allowsSaving]) && !([[UNIVERSE sun] goneNova] || [[UNIVERSE sun] willGoNova]));
8074 }
8075
8076 BOOL canQuickSave = (canLoadOrSave && ([[gameView gameController] playerFileToLoad] != nil));
8077
8078 // GUI stuff
8079 {
8080 GuiDisplayGen* gui = [UNIVERSE gui];
8081 GUI_ROW_INIT(gui);
8082
8083 int first_sel_row = (canLoadOrSave) ? GUI_ROW(, SAVE) : GUI_ROW(, GAMEOPTIONS);
8084 if (canQuickSave)
8085 first_sel_row = GUI_ROW(, QUICKSAVE);
8086
8087 [gui clear];
8088 [gui setTitle:[NSString stringWithFormat:DESC(@"status-commander-@"), [self commanderName]]]; // Same title as status screen.
8089
8090 [gui setText:DESC(@"options-quick-save") forRow:GUI_ROW(, QUICKSAVE) align:GUI_ALIGN_CENTER];
8091 if (canQuickSave)
8092 [gui setKey:GUI_KEY_OK forRow:GUI_ROW(, QUICKSAVE)];
8093 else
8094 [gui setColor:[OOColor grayColor] forRow:GUI_ROW(, QUICKSAVE)];
8095
8096 [gui setText:DESC(@"options-save-commander") forRow:GUI_ROW(, SAVE) align:GUI_ALIGN_CENTER];
8097 [gui setText:DESC(@"options-load-commander") forRow:GUI_ROW(, LOAD) align:GUI_ALIGN_CENTER];
8098 if (canLoadOrSave) {
8099 [gui setKey:GUI_KEY_OK forRow:GUI_ROW(, SAVE)];
8100 [gui setKey:GUI_KEY_OK forRow:GUI_ROW(, LOAD)];
8101 } else {
8102 [gui setColor:[OOColor grayColor] forRow:GUI_ROW(, SAVE)];
8103 [gui setColor:[OOColor grayColor] forRow:GUI_ROW(, LOAD)];
8104 }
8105
8106 [gui setText:DESC(@"options-return-to-menu") forRow:GUI_ROW(, BEGIN_NEW) align:GUI_ALIGN_CENTER];
8107 [gui setKey:GUI_KEY_OK forRow:GUI_ROW(, BEGIN_NEW)];
8108
8109 [gui setText:DESC(@"options-game-options") forRow:GUI_ROW(, GAMEOPTIONS) align:GUI_ALIGN_CENTER];
8110 [gui setKey:GUI_KEY_OK forRow:GUI_ROW(, GAMEOPTIONS)];
8111
8112#if OOLITE_SDL
8113 // GNUstep needs a quit option at present (no Cmd-Q) but
8114 // doesn't need speech.
8115
8116 // quit menu option
8117 [gui setText:DESC(@"options-exit-game") forRow:GUI_ROW(, QUIT) align:GUI_ALIGN_CENTER];
8118 [gui setKey:GUI_KEY_OK forRow:GUI_ROW(, QUIT)];
8119#endif
8120
8121 [gui setSelectableRange:NSMakeRange(first_sel_row, GUI_ROW_OPTIONS_END_OF_LIST)];
8122
8123 if (gamePaused || (!canLoadOrSave && [self status] == STATUS_DOCKED)) {
8124 [gui setSelectedRow:GUI_ROW(, GAMEOPTIONS)];
8125 } else {
8126 [gui setSelectedRow:first_sel_row];
8127 }
8128
8130
8131 if ([gui setForegroundTextureKey:[self status] == STATUS_DOCKED ? @"docked_overlay" : @"paused_overlay"] && [UNIVERSE pauseMessageVisible])
8132 [[UNIVERSE messageGUI] clear];
8133 // Graphically, this screen is analogous to the various settings screens
8134 [gui setBackgroundTextureKey:@"settings"];
8135 }
8136 /* ends */
8137
8138 [[UNIVERSE gameView] clearMouse];
8139
8140 [self setShowDemoShips:NO];
8141
8142 [UNIVERSE enterGUIViewModeWithMouseInteraction:YES];
8143
8144 if (gamePaused) {
8145 [[UNIVERSE messageGUI] clear];
8146 NSString* pauseKey = [PLAYER keyBindingDescription2:@"key_pausebutton"];
8147 [UNIVERSE addMessage:OOExpandKey(@"game-paused-docked", pauseKey) forCount:1.0 forceDisplay:YES];
8148 }
8149
8150 [self noteGUIDidChangeFrom:oldScreen to:gui_screen];
8151}
8152
8153static NSString* last_outfitting_key = nil;
8154
8155- (void)highlightEquipShipScreenKey:(NSString*)key
8156{
8157 int i = 0;
8158 OOGUIRow row;
8159 NSString* otherKey = @"";
8160 GuiDisplayGen* gui = [UNIVERSE gui];
8161 [last_outfitting_key release];
8162 last_outfitting_key = [key copy];
8163 [self setGuiToEquipShipScreen:-1];
8164 key = last_outfitting_key;
8165 // TODO: redo the equipShipScreen in a way that isn't broken. this whole method 'works'
8166 // based on the way setGuiToEquipShipScreen 'worked' on 20090913 - Kaks
8167
8168 // setGuiToEquipShipScreen doesn't take a page number, it takes an offset from the beginning
8169 // of the dictionary, the first line will show the key at that offset...
8170
8171 // try the last page first - 10 pages max.
8172 while (otherKey) {
8173 [self setGuiToEquipShipScreen:i];
8174 for (row = GUI_ROW_EQUIPMENT_START; row <= GUI_MAX_ROWS_EQUIPMENT + 2; row++) {
8175 otherKey = [gui keyForRow:row];
8176 if (!otherKey) {
8177 [self setGuiToEquipShipScreen:0];
8178 return;
8179 }
8180 if ([otherKey isEqualToString:key]) {
8181 [gui setSelectedRow:row];
8183 return;
8184 }
8185 }
8186 if ([otherKey hasPrefix:@"More:"]) {
8187 i = [[otherKey componentsSeparatedByString:@":"] oo_intAtIndex:1];
8188 } else {
8189 [self setGuiToEquipShipScreen:0];
8190 return;
8191 }
8192 }
8193}
8194
8196{
8198 NSDictionary* shipyardInfo = [registry shipyardInfoForKey:[self shipDataKey]];
8199 unsigned available_facings = [shipyardInfo oo_unsignedIntForKey:KEY_WEAPON_FACINGS defaultValue:[self weaponFacings]]; // use defaults explicitly
8200
8201 return available_facings & VALID_WEAPON_FACINGS;
8202}
8203
8204- (void)setGuiToEquipShipScreen:(int)skipParam selectingFacingFor:(NSString*)eqKeyForSelectFacing
8205{
8206 [[UNIVERSE gameController] setMouseInteractionModeForUIWithMouseInteraction:YES];
8207
8208 missiles = [self countMissiles];
8209 OOEntityStatus searchStatus; // use STATUS_TEST, STATUS_DEAD & STATUS_ACTIVE
8210 NSString* showKey = nil;
8211 unsigned skip;
8212
8213 if (skipParam < 0) {
8214 skip = 0;
8215 searchStatus = STATUS_TEST;
8216 } else {
8217 skip = skipParam;
8218 searchStatus = STATUS_ACTIVE;
8219 }
8220
8221 // don't show a "Back" item if we're only skipping one item - just show the item
8222 if (skip == 1)
8223 skip = 0;
8224
8225 double priceFactor = 1.0;
8226 OOTechLevelID techlevel = [[UNIVERSE currentSystemData] oo_intForKey:KEY_TECHLEVEL];
8227
8229 if (dockedStation) {
8230 priceFactor = [dockedStation equipmentPriceFactor];
8231 if ([dockedStation equivalentTechLevel] != NSNotFound)
8232 techlevel = [dockedStation equivalentTechLevel];
8233 }
8234
8235 // build an array of all equipment - and take away that which has been bought (or is not permitted)
8236 NSMutableArray* equipmentAllowed = [NSMutableArray array];
8237
8238 // find options that agree with this ship
8240 NSDictionary* shipyardInfo = [registry shipyardInfoForKey:[self shipDataKey]];
8241 NSMutableSet* options = [NSMutableSet setWithArray:[shipyardInfo oo_arrayForKey:KEY_OPTIONAL_EQUIPMENT]];
8242
8243 // add standard items too!
8244 [options addObjectsFromArray:[[shipyardInfo oo_dictionaryForKey:KEY_STANDARD_EQUIPMENT] oo_arrayForKey:KEY_EQUIPMENT_EXTRAS]];
8245
8246 unsigned i = 0;
8247 NSEnumerator* eqEnum = nil;
8248 OOEquipmentType* eqType = nil;
8249 unsigned available_facings = [shipyardInfo oo_unsignedIntForKey:KEY_WEAPON_FACINGS defaultValue:[self weaponFacings]]; // use defaults explicitly
8250
8251 if (eqKeyForSelectFacing != nil) // Weapons purchase subscreen.
8252 {
8253 skip = 1; // show the back button
8254 // The 3 lines below are needed by the present GUI. TODO:create a sane GUI. Kaks - 20090915 & 201005
8255 [equipmentAllowed addObject:eqKeyForSelectFacing];
8256 [equipmentAllowed addObject:eqKeyForSelectFacing];
8257 [equipmentAllowed addObject:eqKeyForSelectFacing];
8258 } else
8259 for (eqEnum = [OOEquipmentType equipmentEnumeratorOutfitting]; (eqType = [eqEnum nextObject]); i++) {
8260 NSString* eqKey = [eqType identifier];
8261 OOTechLevelID minTechLevel = [eqType effectiveTechLevel];
8262
8263 // set initial availability to NO
8264 BOOL isOK = NO;
8265
8266 // check special availability
8267 if ([eqType isAvailableToAll])
8268 [options addObject:eqKey];
8269
8270 // if you have a damaged system you can get it repaired at a tech level one less than that required to buy it
8271 if (minTechLevel != 0 && [self hasEquipmentItem:[eqType damagedIdentifier]])
8272 minTechLevel--;
8273
8274 // reduce the minimum techlevel occasionally as a bonus..
8275 if (techlevel < minTechLevel && techlevel + 3 > minTechLevel) {
8276 unsigned day = i * 13 + (unsigned)floor([UNIVERSE getTime] / 86400.0);
8277 unsigned char dayRnd = (day & 0xff) ^ (unsigned char)system_id;
8278 OOTechLevelID originalMinTechLevel = minTechLevel;
8279
8280 while (minTechLevel > 0 && minTechLevel > originalMinTechLevel - 3 && !(dayRnd & 7)) // bargain tech days every 1/8 days
8281 {
8282 dayRnd = dayRnd >> 2;
8283 minTechLevel--; // occasional bonus items according to TL
8284 }
8285 }
8286
8287 // check initial availability against options AND standard extras
8288 if ([options containsObject:eqKey]) {
8289 isOK = YES;
8290 [options removeObject:eqKey];
8291 }
8292
8293 if (isOK) {
8294 if (techlevel < minTechLevel)
8295 isOK = NO;
8296 if (![self canAddEquipment:eqKey inContext:@"purchase"])
8297 isOK = NO;
8298 if (available_facings == 0 && [eqType isPrimaryWeapon])
8299 isOK = NO;
8300 if (isOK)
8301 [equipmentAllowed addObject:eqKey];
8302 }
8303
8304 if (searchStatus == STATUS_DEAD && isOK) {
8305 showKey = eqKey;
8306 searchStatus = STATUS_ACTIVE;
8307 }
8308 if (searchStatus == STATUS_TEST) {
8309 if (isOK)
8310 showKey = eqKey;
8311 if ([eqKey isEqualToString:last_outfitting_key])
8312 searchStatus = isOK ? STATUS_ACTIVE : STATUS_DEAD;
8313 }
8314 }
8315 if (searchStatus != STATUS_TEST && showKey != nil) {
8316 [last_outfitting_key release];
8318 }
8319
8320 // GUI stuff
8321 {
8322 GuiDisplayGen* gui = [UNIVERSE gui];
8324 OOGUIRow row = start_row;
8325 unsigned facing_count = 0;
8326 BOOL displayRow = YES;
8327 BOOL weaponMounted = NO;
8328 BOOL guiChanged = (gui_screen != GUI_SCREEN_EQUIP_SHIP);
8329
8330 gui_screen = GUI_SCREEN_EQUIP_SHIP;
8331
8332 [gui clearAndKeepBackground:!guiChanged];
8333 [gui setTitle:DESC(@"equip-title")];
8334
8335 [gui setColor:[gui colorFromSetting:kGuiEquipmentCashColor defaultValue:nil] forRow:GUI_ROW_EQUIPMENT_CASH];
8336 [gui setText:OOExpandKey(@"equip-cash-value", credits) forRow:GUI_ROW_EQUIPMENT_CASH];
8337
8338 OOGUITabSettings tab_stops;
8339 tab_stops[0] = 0;
8340 tab_stops[1] = -360;
8341 tab_stops[2] = -480;
8342 [gui overrideTabs:tab_stops from:kGuiEquipmentTabs length:3];
8343 [gui setTabStops:tab_stops];
8344
8345 unsigned n_rows = GUI_MAX_ROWS_EQUIPMENT;
8346 NSUInteger count = [equipmentAllowed count];
8347
8348 if (count > 0) {
8349 if (skip > 0) // lose the first row to Back <--
8350 {
8351 unsigned previous;
8352
8353 if (count <= n_rows || skip < n_rows)
8354 previous = 0; // single page
8355 else {
8356 previous = skip - (n_rows - 2); // multi-page.
8357 if (previous < 2)
8358 previous = 0; // if only one previous item, just show it
8359 }
8360
8361 if (eqKeyForSelectFacing != nil) {
8362 previous = 0;
8363 // keep weapon selected if we go back.
8364 [gui setKey:[NSString stringWithFormat:@"More:%d:%@", previous, eqKeyForSelectFacing] forRow:row];
8365 } else {
8366 [gui setKey:[NSString stringWithFormat:@"More:%d", previous] forRow:row];
8367 }
8368 [gui setColor:[gui colorFromSetting:kGuiEquipmentScrollColor defaultValue:[OOColor greenColor]] forRow:row];
8369 [gui setArray:[NSArray arrayWithObjects:DESC(@"gui-back"), @"", @" <-- ", nil] forRow:row];
8370 row++;
8371 }
8372
8373 for (i = skip; i < count && (row - start_row < (OOGUIRow)n_rows); i++) {
8374 NSString* eqKey = [equipmentAllowed oo_stringAtIndex:i];
8376 OOCreditsQuantity pricePerUnit = [eqInfo price];
8377 NSString* desc = [NSString stringWithFormat:@" %@ ", [eqInfo name]];
8378 NSString* eq_key_damaged = [eqInfo damagedIdentifier];
8379 double price;
8380
8381 OOColor* dispCol = [eqInfo displayColor];
8382 if (dispCol == nil)
8383 dispCol = [gui colorFromSetting:kGuiEquipmentOptionColor defaultValue:nil];
8384 [gui setColor:dispCol forRow:row];
8385
8386 if ([eqKey isEqual:@"EQ_FUEL"]) {
8387 price = (PLAYER_MAX_FUEL - fuel) * pricePerUnit * [self fuelChargeRate];
8388 } else if ([eqKey isEqualToString:@"EQ_RENOVATION"]) {
8389 price = [self renovationCosts];
8390 [gui setColor:[gui colorFromSetting:kGuiEquipmentRepairColor defaultValue:[OOColor orangeColor]] forRow:row];
8391 } else {
8392 price = pricePerUnit;
8393 }
8394
8395 price = [self adjustPriceByScriptForEqKey:eqKey withCurrent:price];
8396
8397 price *= priceFactor; // increased prices at some stations
8398
8399 NSUInteger installTime = [eqInfo installTime];
8400 if (installTime == 0) {
8401 installTime = 600 + price;
8402 }
8403 // is this item damaged?
8404 if ([self hasEquipmentItem:eq_key_damaged]) {
8405 desc = [NSString stringWithFormat:DESC(@"equip-repair-@"), desc];
8406 price /= 2.0;
8407 installTime = [eqInfo repairTime];
8408 if (installTime == 0) {
8409 installTime = 600 + price;
8410 }
8411 [gui setColor:[gui colorFromSetting:kGuiEquipmentRepairColor defaultValue:[OOColor orangeColor]] forRow:row];
8412 }
8413
8414 NSString* timeString = [UNIVERSE shortTimeDescription:installTime];
8415 NSString* priceString = [NSString stringWithFormat:@" %@ ", OOCredits(price)];
8416
8417 if ([eqKeyForSelectFacing isEqualToString:eqKey]) {
8418 // Weapons purchase subscreen.
8419 while (facing_count < 5) {
8420 NSUInteger multiplier = 1;
8421 switch (facing_count) {
8422 case 0:
8423 break;
8424
8425 case 1:
8426 displayRow = available_facings & WEAPON_FACING_FORWARD;
8427 desc = FORWARD_FACING_STRING;
8428 weaponMounted = !isWeaponNone(forward_weapon_type);
8429 if (_multiplyWeapons) {
8430 multiplier = [forwardWeaponOffset count];
8431 }
8432 break;
8433
8434 case 2:
8435 displayRow = available_facings & WEAPON_FACING_AFT;
8436 desc = AFT_FACING_STRING;
8437 weaponMounted = !isWeaponNone(aft_weapon_type);
8438 if (_multiplyWeapons) {
8439 multiplier = [aftWeaponOffset count];
8440 }
8441 break;
8442
8443 case 3:
8444 displayRow = available_facings & WEAPON_FACING_PORT;
8445 desc = PORT_FACING_STRING;
8446 weaponMounted = !isWeaponNone(port_weapon_type);
8447 if (_multiplyWeapons) {
8448 multiplier = [portWeaponOffset count];
8449 }
8450 break;
8451
8452 case 4:
8453 displayRow = available_facings & WEAPON_FACING_STARBOARD;
8455 weaponMounted = !isWeaponNone(starboard_weapon_type);
8456 if (_multiplyWeapons) {
8457 multiplier = [starboardWeaponOffset count];
8458 }
8459 break;
8460 }
8461
8462 if (weaponMounted) {
8463 [gui setColor:[gui colorFromSetting:kGuiEquipmentLaserFittedColor defaultValue:[OOColor colorWithRed:0.0f green:0.6f blue:0.0f alpha:1.0f]] forRow:row];
8464 } else {
8465 [gui setColor:[gui colorFromSetting:kGuiEquipmentLaserColor defaultValue:[OOColor greenColor]] forRow:row];
8466 }
8467 if (displayRow) // Always true for the first pass. The first pass is used to display the name of the weapon being purchased.
8468 {
8469
8470 priceString = [NSString stringWithFormat:@" %@ ", OOCredits(price * multiplier)];
8471
8472 [gui setKey:eqKey forRow:row];
8473 [gui setArray:[NSArray arrayWithObjects:desc, (facing_count > 0 ? priceString : (NSString*)@""), timeString, nil] forRow:row];
8474 row++;
8475 }
8476 facing_count++;
8477 }
8478 } else {
8479 // Normal equipment list.
8480 [gui setKey:eqKey forRow:row];
8481 // check if the hidevalues property has been set
8482 if (![eqInfo hideValues]) {
8483 [gui setArray:[NSArray arrayWithObjects:desc, priceString, timeString, nil] forRow:row];
8484 } else {
8485 // if so, only output the description
8486 [gui setArray:[NSArray arrayWithObjects:desc, nil] forRow:row];
8487 }
8488 row++;
8489 }
8490 }
8491
8492 if (i < count) {
8493 // just overwrite the last item :-)
8494 [gui setColor:[gui colorFromSetting:kGuiEquipmentScrollColor defaultValue:[OOColor greenColor]] forRow:row - 1];
8495 [gui setArray:[NSArray arrayWithObjects:DESC(@"gui-more"), @"", @" --> ", nil] forRow:row - 1];
8496 [gui setKey:[NSString stringWithFormat:@"More:%d", i - 1] forRow:row - 1];
8497 }
8498
8499 [gui setSelectableRange:NSMakeRange(start_row, row - start_row)];
8500
8501 if ([gui selectedRow] != start_row)
8502 [gui setSelectedRow:start_row];
8503
8504 if (eqKeyForSelectFacing != nil) {
8505 [gui setSelectedRow:start_row + 1];
8506 [self showInformationForSelectedUpgradeWithFormatString:DESC(@"@-select-where-to-install")];
8507 } else {
8509 }
8510 } else {
8511 [gui setText:DESC(@"equip-no-equipment-available-for-purchase") forRow:GUI_ROW_NO_SHIPS align:GUI_ALIGN_CENTER];
8512 [gui setColor:[gui colorFromSetting:kGuiEquipmentUnavailableColor defaultValue:[OOColor greenColor]] forRow:GUI_ROW_NO_SHIPS];
8513
8514 [gui setSelectableRange:NSMakeRange(0, 0)];
8517 }
8518
8520
8521 // TODO: split the mount_weapon sub-screen into a separate screen, and use it for pylon mounted wepons as well?
8522 if (guiChanged) {
8523 [gui setForegroundTextureKey:@"docked_overlay"];
8524 NSDictionary* background = [UNIVERSE screenTextureDescriptorForKey:@"equip_ship"];
8525 [self setEquipScreenBackgroundDescriptor:background];
8527 } else if (eqKeyForSelectFacing != nil) // weapon purchase
8528 {
8529 NSDictionary* bgDescriptor = [UNIVERSE screenTextureDescriptorForKey:@"mount_weapon"];
8530 if (bgDescriptor != nil)
8531 [gui setBackgroundTextureDescriptor:bgDescriptor];
8532 } else // Returning from a weapon purchase. (Also called, redundantly, when paging)
8533 {
8535 }
8536 }
8537 /* ends */
8538
8540
8541 [self setShowDemoShips:NO];
8542 [UNIVERSE enterGUIViewModeWithMouseInteraction:YES];
8543}
8544
8545- (void)setGuiToEquipShipScreen:(int)skip
8546{
8548}
8549
8554
8555- (void)showInformationForSelectedUpgradeWithFormatString:(NSString*)formatString
8556{
8557 GuiDisplayGen* gui = [UNIVERSE gui];
8558 NSString* eqKey = [gui selectedRowKey];
8559 int i;
8560
8561 OOColor* descColor = [gui colorFromSetting:kGuiEquipmentDescriptionColor defaultValue:[OOColor greenColor]];
8562 for (i = GUI_ROW_EQUIPMENT_DETAIL; i < GUI_MAX_ROWS; i++) {
8563 [gui setText:@"" forRow:i];
8564 [gui setColor:descColor forRow:i];
8565 }
8566 if (eqKey) {
8567 if (![eqKey hasPrefix:@"More:"]) {
8569 NSString* eq_key_damaged = [NSString stringWithFormat:@"%@_DAMAGED", eqKey];
8571 if ([self hasEquipmentItem:eq_key_damaged]) {
8572 desc = [NSString stringWithFormat:DESC(@"upgradeinfo-@-price-is-for-repairing"), desc];
8573 } else {
8574 if ([eqKey hasSuffix:@"ENERGY_UNIT"] && ([self hasEquipmentItem:@"EQ_ENERGY_UNIT_DAMAGED"] || [self hasEquipmentItem:@"EQ_ENERGY_UNIT"] || [self hasEquipmentItem:@"EQ_NAVAL_ENERGY_UNIT_DAMAGED"]))
8575 desc = [NSString stringWithFormat:DESC(@"@-will-replace-other-energy"), desc];
8576 if (weight > 0)
8577 desc = [NSString stringWithFormat:DESC(@"upgradeinfo-@-weight-d-of-equipment"), desc, weight];
8578 }
8579 if (formatString)
8580 desc = [NSString stringWithFormat:formatString, desc];
8581 [gui addLongText:desc startingAtRow:GUI_ROW_EQUIPMENT_DETAIL align:GUI_ALIGN_LEFT];
8582 }
8583 }
8584}
8585
8586- (void)setGuiToInterfacesScreen:(int)skip
8587{
8588 [[UNIVERSE gameController] setMouseInteractionModeForUIWithMouseInteraction:YES];
8589 if (gui_screen != GUI_SCREEN_INTERFACES) {
8590 [self noteGUIWillChangeTo:GUI_SCREEN_INTERFACES];
8591 }
8592
8593 // build an array of available interfaces
8594 NSDictionary* interfaces = [[self dockedStation] localInterfaces];
8595 NSArray* interfaceKeys = [interfaces keysSortedByValueUsingSelector:@selector(interfaceCompare:)]; // sorts by category, then title
8596 int i;
8597
8598 OOGUIScreenID oldScreen = gui_screen;
8599
8600 // GUI stuff
8601 {
8602 GuiDisplayGen* gui = [UNIVERSE gui];
8604 OOGUIRow row = start_row;
8605 BOOL guiChanged = (gui_screen != GUI_SCREEN_INTERFACES);
8606
8607 [gui clearAndKeepBackground:!guiChanged];
8608 [gui setTitle:DESC(@"interfaces-title")];
8609
8610 gui_screen = GUI_SCREEN_INTERFACES;
8611
8612 OOGUITabSettings tab_stops;
8613 tab_stops[0] = 0;
8614 tab_stops[1] = -480;
8615 [gui overrideTabs:tab_stops from:kGuiInterfaceTabs length:2];
8616 [gui setTabStops:tab_stops];
8617
8618 unsigned n_rows = GUI_MAX_ROWS_INTERFACES;
8619 NSUInteger count = [interfaceKeys count];
8620
8621 if (count > 0) {
8622 if (skip > 0) // lose the first row to Back <--
8623 {
8624 unsigned previous;
8625
8626 if (count <= n_rows || skip < (NSInteger)n_rows) {
8627 previous = 0; // single page
8628 } else {
8629 previous = skip - (n_rows - 2); // multi-page.
8630 if (previous < 2) {
8631 previous = 0; // if only one previous item, just show it
8632 }
8633 }
8634
8635 [gui setKey:[NSString stringWithFormat:@"More:%d", previous] forRow:row];
8636 [gui setColor:[gui colorFromSetting:kGuiInterfaceScrollColor defaultValue:[OOColor greenColor]] forRow:row];
8637 [gui setArray:[NSArray arrayWithObjects:DESC(@"gui-back"), @" <-- ", nil] forRow:row];
8638 row++;
8639 }
8640
8641 for (i = skip; i < (NSInteger)count && (row - start_row < (OOGUIRow)n_rows); i++) {
8642 NSString* interfaceKey = [interfaceKeys objectAtIndex:i];
8643 OOJSInterfaceDefinition* definition = [interfaces objectForKey:interfaceKey];
8644
8645 [gui setColor:[gui colorFromSetting:kGuiInterfaceEntryColor defaultValue:nil] forRow:row];
8646 [gui setKey:interfaceKey forRow:row];
8647 [gui setArray:[NSArray arrayWithObjects:[definition title], [definition category], nil] forRow:row];
8648
8649 row++;
8650 }
8651
8652 if (i < (NSInteger)count) {
8653 // just overwrite the last item :-)
8654 [gui setColor:[gui colorFromSetting:kGuiInterfaceScrollColor defaultValue:[OOColor greenColor]] forRow:row - 1];
8655 [gui setArray:[NSArray arrayWithObjects:DESC(@"gui-more"), @" --> ", nil] forRow:row - 1];
8656 [gui setKey:[NSString stringWithFormat:@"More:%d", i - 1] forRow:row - 1];
8657 }
8658
8659 [gui setSelectableRange:NSMakeRange(start_row, row - start_row)];
8660
8661 if ([gui selectedRow] != start_row) {
8662 [gui setSelectedRow:start_row];
8663 }
8664
8666 } else {
8667 [gui setText:DESC(@"interfaces-no-interfaces-available-for-use") forRow:GUI_ROW_NO_INTERFACES align:GUI_ALIGN_LEFT];
8668 [gui setColor:[gui colorFromSetting:kGuiInterfaceNoneColor defaultValue:[OOColor greenColor]] forRow:GUI_ROW_NO_INTERFACES];
8669
8670 [gui setSelectableRange:NSMakeRange(0, 0)];
8672 }
8673
8675
8676 NSString* desc = [NSString stringWithFormat:DESC(@"interfaces-for-ship-@-and-station-@"), [self displayName], [[self dockedStation] displayName]];
8677 [gui setColor:[gui colorFromSetting:kGuiInterfaceHeadingColor defaultValue:nil] forRow:GUI_ROW_INTERFACES_HEADING];
8678 [gui setText:desc forRow:GUI_ROW_INTERFACES_HEADING];
8679
8680 if (guiChanged) {
8681 [gui setForegroundTextureKey:@"docked_overlay"];
8682 NSDictionary* background = [UNIVERSE screenTextureDescriptorForKey:@"interfaces"];
8684 }
8685 }
8686 /* ends */
8687
8688 [self setShowDemoShips:NO];
8689
8690 [self noteGUIDidChangeFrom:oldScreen to:gui_screen];
8691
8692 [self setShowDemoShips:NO];
8693 [UNIVERSE enterGUIViewModeWithMouseInteraction:YES];
8694}
8695
8697{
8698 GuiDisplayGen* gui = [UNIVERSE gui];
8699 NSString* interfaceKey = [gui selectedRowKey];
8700
8701 int i;
8702
8703 for (i = GUI_ROW_EQUIPMENT_DETAIL; i < GUI_MAX_ROWS; i++) {
8704 [gui setText:@"" forRow:i];
8705 [gui setColor:[gui colorFromSetting:kGuiInterfaceDescriptionColor defaultValue:[OOColor greenColor]] forRow:i];
8706 }
8707
8708 if (interfaceKey && ![interfaceKey hasPrefix:@"More:"]) {
8709 NSDictionary* interfaces = [[self dockedStation] localInterfaces];
8710 OOJSInterfaceDefinition* definition = [interfaces objectForKey:interfaceKey];
8711 if (definition) {
8712 [gui addLongText:[definition summary] startingAtRow:GUI_ROW_INTERFACES_DETAIL align:GUI_ALIGN_LEFT];
8713 }
8714 }
8715}
8716
8718{
8719 GuiDisplayGen* gui = [UNIVERSE gui];
8720 NSString* key = [gui selectedRowKey];
8721
8722 if ([key hasPrefix:@"More:"]) {
8723 int from_item = [[key componentsSeparatedByString:@":"] oo_intAtIndex:1];
8724 [self setGuiToInterfacesScreen:from_item];
8725
8726 if ([gui selectedRow] < 0)
8727 [gui setSelectedRow:GUI_ROW_INTERFACES_START];
8728 if (from_item == 0)
8729 [gui setSelectedRow:GUI_ROW_INTERFACES_START + GUI_MAX_ROWS_INTERFACES - 1];
8731
8732 return;
8733 }
8734
8735 NSDictionary* interfaces = [[self dockedStation] localInterfaces];
8736 OOJSInterfaceDefinition* definition = [interfaces objectForKey:key];
8737 if (definition) {
8738 [[UNIVERSE gameView] clearKeys];
8739 [definition runCallback:key];
8740 } else {
8741 OOLog(@"interface.missingCallback", @"Unable to find callback definition for key %@", key);
8742 }
8743}
8744
8746{
8747 GuiDisplayGen* gui = [UNIVERSE gui];
8748 NSString* text = nil;
8749
8750 [[UNIVERSE gameController] setMouseInteractionModeForUIWithMouseInteraction:YES];
8751
8752 [gui clear];
8753
8754 [gui setTitle:@"Oolite"];
8755
8756 text = DESC(@"game-copyright");
8757 [gui setText:text forRow:15 align:GUI_ALIGN_CENTER];
8758 [gui setColor:[OOColor whiteColor] forRow:15];
8759
8760 text = DESC(@"theme-music-credit");
8761 [gui setText:text forRow:17 align:GUI_ALIGN_CENTER];
8762 [gui setColor:[OOColor grayColor] forRow:17];
8763
8764 int initialRow = 22;
8765 int row = initialRow;
8766
8767 text = DESC(@"oolite-start-option-1");
8768 [gui setText:text forRow:row align:GUI_ALIGN_CENTER];
8769 [gui setColor:[OOColor yellowColor] forRow:row];
8770 [gui setKey:[NSString stringWithFormat:@"Start:%d", row] forRow:row];
8771
8772 ++row;
8773
8774 text = DESC(@"oolite-start-option-2");
8775 [gui setText:text forRow:row align:GUI_ALIGN_CENTER];
8776 [gui setColor:[OOColor yellowColor] forRow:row];
8777 [gui setKey:[NSString stringWithFormat:@"Start:%d", row] forRow:row];
8778
8779 ++row;
8780
8781 text = DESC(@"oolite-start-option-3");
8782 [gui setText:text forRow:row align:GUI_ALIGN_CENTER];
8783 [gui setColor:[OOColor yellowColor] forRow:row];
8784 [gui setKey:[NSString stringWithFormat:@"Start:%d", row] forRow:row];
8785
8786 ++row;
8787
8788 text = DESC(@"oolite-start-option-4");
8789 [gui setText:text forRow:row align:GUI_ALIGN_CENTER];
8790 [gui setColor:[OOColor yellowColor] forRow:row];
8791 [gui setKey:[NSString stringWithFormat:@"Start:%d", row] forRow:row];
8792
8793 ++row;
8794
8795 text = DESC(@"oolite-start-option-5");
8796 [gui setText:text forRow:row align:GUI_ALIGN_CENTER];
8797 [gui setColor:[OOColor yellowColor] forRow:row];
8798 [gui setKey:[NSString stringWithFormat:@"Start:%d", row] forRow:row];
8799
8800 ++row;
8801
8802 text = DESC(@"oolite-start-option-6");
8803 [gui setText:text forRow:row align:GUI_ALIGN_CENTER];
8804 [gui setColor:[OOColor yellowColor] forRow:row];
8805 [gui setKey:[NSString stringWithFormat:@"Start:%d", row] forRow:row];
8806
8807 [gui setSelectableRange:NSMakeRange(initialRow, row - initialRow + 1)];
8808 [gui setSelectedRow:initialRow];
8809
8810 [gui setBackgroundTextureKey:@"intro"];
8811}
8812
8817- (void)setGuiToIntroFirstGo:(BOOL)justCobra
8818{
8819 NSString* text = nil;
8820 GuiDisplayGen* gui = [UNIVERSE gui];
8821 OOGUIRow msgLine = 2;
8822
8823 [[UNIVERSE gameController] setMouseInteractionModeForUIWithMouseInteraction:NO];
8824 [[UNIVERSE gameView] clearMouse];
8825 [[UNIVERSE gameView] clearKeys];
8826
8827 if (justCobra) {
8828 [UNIVERSE removeDemoShips];
8829 [[OOCacheManager sharedCache] flush]; // At first startup, a lot of stuff is cached
8830 }
8831
8832 if (justCobra) {
8833 [self setupStartScreenGui];
8834
8835 // check for error messages from Resource Manager
8836 //[ResourceManager paths]; done in Universe already
8837 NSString* errors = [ResourceManager errors];
8838 if (errors != nil) {
8839 OOGUIRow ms_start = msgLine;
8840 OOGUIRow i = msgLine = [gui addLongText:errors startingAtRow:ms_start align:GUI_ALIGN_LEFT];
8841 for (i--; i >= ms_start; i--)
8842 [gui setColor:[OOColor redColor] forRow:i];
8843 msgLine++;
8844 }
8845
8846 // check for messages from OXPs
8847 NSArray* OXPsWithMessages = [ResourceManager OXPsWithMessagesFound];
8848 if ([OXPsWithMessages count] > 0) {
8849 NSString* messageToDisplay = @"";
8850
8851 // Show which OXPs were found with messages, but don't spam the screen if more than
8852 // a certain number of them exist
8853 if ([OXPsWithMessages count] < 5) {
8854 NSString* messageSourceList = [OXPsWithMessages componentsJoinedByString:@", "];
8855 messageToDisplay = OOExpandKey(@"oxp-containing-messages-list", messageSourceList);
8856 } else {
8857 messageToDisplay = OOExpandKey(@"oxp-containing-messages-found");
8858 }
8859
8860 OOGUIRow ms_start = msgLine;
8861 OOGUIRow i = msgLine = [gui addLongText:messageToDisplay startingAtRow:ms_start align:GUI_ALIGN_LEFT];
8862 for (i--; i >= ms_start; i--) {
8863 [gui setColor:[OOColor orangeColor] forRow:i];
8864 }
8865 msgLine++;
8866 }
8867
8868 // check for messages from the command line
8869 NSArray* arguments = [[NSProcessInfo processInfo] arguments];
8870 unsigned i;
8871 for (i = 0; i < [arguments count]; i++) {
8872 if (([[arguments objectAtIndex:i] isEqual:@"-message"]) && (i < [arguments count] - 1)) {
8873 OOGUIRow ms_start = msgLine;
8874 NSString* message = [arguments oo_stringAtIndex:i + 1];
8875 OOGUIRow i = msgLine = [gui addLongText:message startingAtRow:ms_start align:GUI_ALIGN_CENTER];
8876 for (i--; i >= ms_start; i--) {
8877 [gui setColor:[OOColor magentaColor] forRow:i];
8878 }
8879 }
8880 if ([[arguments objectAtIndex:i] isEqual:@"-showversion"]) {
8881 OOGUIRow ms_start = msgLine;
8882 NSString* version = @"Version " @OO_VERSION_FULL;
8883 OOGUIRow i = msgLine = [gui addLongText:version startingAtRow:ms_start align:GUI_ALIGN_CENTER];
8884 for (i--; i >= ms_start; i--) {
8885 [gui setColor:[OOColor magentaColor] forRow:i];
8886 }
8887 }
8888 }
8889 } else {
8890 [gui clear];
8891
8892 text = DESC(@"oolite-ship-library-title");
8893 [gui setTitle:text];
8894
8895 text = DESC(@"oolite-ship-library-exit");
8896 [gui setText:text forRow:27 align:GUI_ALIGN_CENTER];
8897 [gui setColor:[OOColor yellowColor] forRow:27];
8898 }
8899
8901
8902 [UNIVERSE setupIntroFirstGo:justCobra];
8903
8904 if (gui != nil) {
8905 gui_screen = justCobra ? GUI_SCREEN_INTRO1 : GUI_SCREEN_SHIPLIBRARY;
8906 }
8907 if ([self status] == STATUS_START_GAME) {
8909 }
8910
8911 [self setShowDemoShips:YES];
8912 if (justCobra) {
8913 [gui setBackgroundTextureKey:@"intro"];
8914 } else {
8915 [gui setBackgroundTextureKey:@"shiplibrary"];
8916 }
8917 [UNIVERSE enterGUIViewModeWithMouseInteraction:YES];
8918}
8919
8921{
8922
8923 [[UNIVERSE gameController] setMouseInteractionModeForUIWithMouseInteraction:NO];
8924 [[UNIVERSE gameView] clearMouse];
8925 [UNIVERSE removeDemoShips];
8926
8927 gui_screen = GUI_SCREEN_OXZMANAGER;
8928
8929 [[UNIVERSE gui] clearAndKeepBackground:NO];
8930
8932
8934 [[UNIVERSE gui] setBackgroundTextureKey:@"oxz-manager"];
8935 [UNIVERSE enterGUIViewModeWithMouseInteraction:YES];
8936}
8937
8938- (void)noteGUIWillChangeTo:(OOGUIScreenID)toScreen
8939{
8940 JSContext* context = OOJSAcquireContext();
8941 ShipScriptEvent(context, self, "guiScreenWillChange", OOJSValueFromGUIScreenID(context, toScreen), OOJSValueFromGUIScreenID(context, gui_screen));
8942 OOJSRelinquishContext(context);
8943}
8944
8945- (void)noteGUIDidChangeFrom:(OOGUIScreenID)fromScreen to:(OOGUIScreenID)toScreen
8946{
8947 [self noteGUIDidChangeFrom:fromScreen to:toScreen refresh:NO];
8948}
8949
8950- (void)noteGUIDidChangeFrom:(OOGUIScreenID)fromScreen to:(OOGUIScreenID)toScreen refresh:(BOOL)refresh
8951{
8952 // No events triggered if we're changing screens while paused, or if screen never actually changed.
8953 if (fromScreen != toScreen || refresh) {
8954 // MKW - release GUI Screen ship, if we have one
8955 switch (fromScreen) {
8956 case GUI_SCREEN_SHIPYARD:
8957 case GUI_SCREEN_LOAD:
8958 case GUI_SCREEN_SAVE:
8959 [demoShip release];
8960 demoShip = nil;
8961 break;
8962 default:
8963 // Nothing
8964 break;
8965 }
8966
8967 if (toScreen == GUI_SCREEN_SYSTEM_DATA) {
8968 // system data screen: ensure correct sun light color is used on miniature planet
8969 [[UNIVERSE sun] setSunColor:[OOColor colorWithDescription:[[UNIVERSE systemManager] getProperty:@"sun_color" forSystem:info_system_id inGalaxy:[self galaxyNumber]]]];
8970 } else {
8971 // any other screen: reset local sun light color
8972 [[UNIVERSE sun] setSunColor:[OOColor colorWithDescription:[[UNIVERSE systemManager] getProperty:@"sun_color" forSystem:system_id inGalaxy:[self galaxyNumber]]]];
8973 }
8974
8975 if (![[UNIVERSE gameController] isGamePaused]) {
8976 JSContext* context = OOJSAcquireContext();
8977 ShipScriptEvent(context, self, "guiScreenChanged", OOJSValueFromGUIScreenID(context, toScreen), OOJSValueFromGUIScreenID(context, fromScreen));
8978 OOJSRelinquishContext(context);
8979 }
8980 }
8981}
8982
8983- (void)noteViewDidChangeFrom:(OOViewID)fromView toView:(OOViewID)toView
8984{
8985 [self noteSwitchToView:toView fromView:fromView];
8986}
8987
8989{
8990 GuiDisplayGen* gui = [UNIVERSE gui];
8991 NSString* key = [gui selectedRowKey];
8992
8993 if ([key hasPrefix:@"More:"]) {
8994 int from_item = [[key componentsSeparatedByString:@":"] oo_intAtIndex:1];
8995 NSString* weaponKey = [[key componentsSeparatedByString:@":"] oo_stringAtIndex:2];
8996
8997 [self setGuiToEquipShipScreen:from_item];
8998 if (weaponKey != nil) {
8999 [self highlightEquipShipScreenKey:weaponKey];
9000 } else {
9001 if ([gui selectedRow] < 0)
9002 [gui setSelectedRow:GUI_ROW_EQUIPMENT_START];
9003 if (from_item == 0)
9004 [gui setSelectedRow:GUI_ROW_EQUIPMENT_START + GUI_MAX_ROWS_EQUIPMENT - 1];
9006 }
9007
9008 return;
9009 }
9010
9011 NSString* itemText = [gui selectedRowText];
9012
9013 // FIXME: this is nuts, should be associating lines with keys in some sensible way. --Ahruman 20080311
9014 if ([itemText isEqual:FORWARD_FACING_STRING])
9016 if ([itemText isEqual:AFT_FACING_STRING])
9018 if ([itemText isEqual:PORT_FACING_STRING])
9020 if ([itemText isEqual:STARBOARD_FACING_STRING])
9022
9023 OOCreditsQuantity old_credits = credits;
9025 BOOL isRepair = [self hasEquipmentItem:[eqInfo damagedIdentifier]];
9026 if ([self tryBuyingItem:key]) {
9027 if (credits == old_credits) {
9028 // laser pre-purchase, or free equipment
9030 } else {
9031 [self playBuyCommodity];
9032 }
9033
9034 if (credits != old_credits || ![key hasPrefix:@"EQ_WEAPON_"]) {
9035 // adjust time before playerBoughtEquipment gets to change credits dynamically
9036 // wind the clock forward by 10 minutes plus 10 minutes for every 60 credits spent
9037 NSUInteger adjust = 0;
9038 if (isRepair) {
9039 adjust = [eqInfo repairTime];
9040 } else {
9041 adjust = [eqInfo installTime];
9042 }
9043 double time_adjust = (old_credits > credits) ? (old_credits - credits) : 0.0;
9044 [UNIVERSE forceWitchspaceEntries];
9045 if (adjust == 0) {
9046 ship_clock_adjust += time_adjust + 600.0;
9047 } else {
9048 ship_clock_adjust += (double)adjust;
9049 }
9050
9051 [self doScriptEvent:OOJSID("playerBoughtEquipment") withArguments:[NSArray arrayWithObjects:key, [NSNumber numberWithLongLong:(old_credits - credits)], nil]];
9052 if (gui_screen == GUI_SCREEN_EQUIP_SHIP) // if we haven't changed gui screen inside playerBoughtEquipment
9053 {
9054 // show any change due to playerBoughtEquipment
9055 [self setGuiToEquipShipScreen:0];
9056 // then try to go back where we were
9057 [self highlightEquipShipScreenKey:key];
9058 }
9059
9060 if ([UNIVERSE autoSave])
9061 [UNIVERSE setAutoSaveNow:YES];
9062 }
9063 } else {
9064 [self playCantBuyCommodity];
9065 }
9066}
9067
9068- (OOCreditsQuantity)adjustPriceByScriptForEqKey:(NSString*)eqKey withCurrent:(OOCreditsQuantity)price
9069{
9070 NSString* condition_script = [[OOEquipmentType equipmentTypeWithIdentifier:eqKey] conditionScript];
9071 if (condition_script != nil) {
9072 OOJSScript* condScript = [UNIVERSE getConditionScript:condition_script];
9073 if (condScript != nil) // should always be non-nil, but just in case
9074 {
9075 JSContext* JScontext = OOJSAcquireContext();
9076 BOOL OK;
9077 OOJSVal result = OOJSUndefinedValue();
9078 int32_t newPrice;
9079 OOJSVal args[] = { OOJSValueFromNativeObject(JScontext, eqKey), OOJSValueFromDouble(JScontext, price) };
9080
9081 OK = [condScript callMethod:OOJSID("updateEquipmentPrice")
9082 inContext:JScontext
9083 withArguments:args
9084 count:sizeof args / sizeof *args
9085 result:&result];
9086
9087 if (OK) {
9088 OK = OOJSValueToInt32(JScontext, result, &newPrice);
9089 if (OK && newPrice >= 0) {
9090 price = (OOCreditsQuantity)newPrice;
9091 }
9092 if (!OK)
9093 OOJSReportPendingException(JScontext);
9094 }
9095 OOJSFreeValue(JScontext, result);
9096 OOJSFreeValue(JScontext, args[0]);
9097 OOJSFreeValue(JScontext, args[1]);
9098 OOJSRelinquishContext(JScontext);
9099 }
9100 }
9101 return price;
9102}
9103
9104- (BOOL)tryBuyingItem:(NSString*)eqKey
9105{
9106 // note this doesn't check the availability by tech-level
9108 OOCreditsQuantity pricePerUnit = [eqType price];
9109 NSString* eqKeyDamaged = [eqType damagedIdentifier];
9110 double price = pricePerUnit;
9111 double priceFactor = 1.0;
9112 OOCreditsQuantity tradeIn = 0;
9113 BOOL isRepair = NO;
9114
9115 // repairs cost 50%
9116 if ([self hasEquipmentItem:eqKeyDamaged]) {
9117 price /= 2.0;
9118 isRepair = YES;
9119 }
9120
9121 if ([eqKey isEqualToString:@"EQ_RENOVATION"]) {
9122 price = [self renovationCosts];
9123 }
9124
9125 price = [self adjustPriceByScriptForEqKey:eqKey withCurrent:price];
9126
9127 StationEntity* dockedStation = [self dockedStation];
9128 if (dockedStation) {
9129 priceFactor = [dockedStation equipmentPriceFactor];
9130 }
9131
9132 price *= priceFactor; // increased prices at some stations
9133
9134 if (price > credits) {
9135 return NO;
9136 }
9137
9138 if ([eqType isPrimaryWeapon]) {
9139 if (chosen_weapon_facing == WEAPON_FACING_NONE) {
9140 [self setGuiToEquipShipScreen:0 selectingFacingFor:eqKey]; // reset
9141 return YES;
9142 }
9143
9145 OOWeaponType current_weapon = nil;
9146
9147 NSUInteger multiplier = 1;
9148
9149 switch (chosen_weapon_facing) {
9151 current_weapon = forward_weapon_type;
9152 forward_weapon_type = chosen_weapon;
9153 if (_multiplyWeapons) {
9154 multiplier = [forwardWeaponOffset count];
9155 }
9156 break;
9157
9158 case WEAPON_FACING_AFT:
9159 current_weapon = aft_weapon_type;
9160 aft_weapon_type = chosen_weapon;
9161 if (_multiplyWeapons) {
9162 multiplier = [aftWeaponOffset count];
9163 }
9164 break;
9165
9166 case WEAPON_FACING_PORT:
9167 current_weapon = port_weapon_type;
9168 port_weapon_type = chosen_weapon;
9169 if (_multiplyWeapons) {
9170 multiplier = [portWeaponOffset count];
9171 }
9172 break;
9173
9175 current_weapon = starboard_weapon_type;
9176 starboard_weapon_type = chosen_weapon;
9177 if (_multiplyWeapons) {
9178 multiplier = [starboardWeaponOffset count];
9179 }
9180 break;
9181
9182 case WEAPON_FACING_NONE:
9183 break;
9184 }
9185
9186 price *= multiplier;
9187
9188 if (price > credits) {
9189 // not enough money - ensure that weapon
9190 // type is reset to what it was before
9191 // the attempt to buy took place
9192 switch (chosen_weapon_facing) {
9194 forward_weapon_type = current_weapon;
9195 break;
9196 case WEAPON_FACING_AFT:
9197 aft_weapon_type = current_weapon;
9198 break;
9199 case WEAPON_FACING_PORT:
9200 port_weapon_type = current_weapon;
9201 break;
9203 starboard_weapon_type = current_weapon;
9204 break;
9205 case WEAPON_FACING_NONE:
9206 break;
9207 }
9208 return NO;
9209 }
9210 credits -= price;
9211
9212 // Refund current_weapon
9213 if (current_weapon != nil) {
9214 tradeIn = [UNIVERSE getEquipmentPriceForKey:OOEquipmentIdentifierFromWeaponType(current_weapon)] * multiplier;
9215 }
9216
9217 [self doTradeIn:tradeIn forPriceFactor:priceFactor];
9218 // If equipped, remove damaged weapon after repairs. -- But there's no way we should get a damaged weapon. Ever.
9219 [self removeEquipmentItem:eqKeyDamaged];
9220 return YES;
9221 }
9222
9223 if ([eqType isMissileOrMine] && missiles >= max_missiles) {
9224 OOLog(@"equip.buy.mounted.failed.full", @"%@", @"rejecting missile because already full");
9225 return NO;
9226 }
9227
9228 // NSFO!
9229 // unsigned passenger_space = [[OOEquipmentType equipmentTypeWithIdentifier:@"EQ_PASSENGER_BERTH"] requiredCargoSpace];
9230 // if (passenger_space == 0) passenger_space = PASSENGER_BERTH_SPACE;
9231
9232 if ([eqKey isEqualToString:@"EQ_PASSENGER_BERTH"] && [self availableCargoSpace] < PASSENGER_BERTH_SPACE) {
9233 return NO;
9234 }
9235
9236 if ([eqKey isEqualToString:@"EQ_FUEL"]) {
9237#if MASS_DEPENDENT_FUEL_PRICES
9238 OOCreditsQuantity creditsForRefuel = ([self fuelCapacity] - [self fuel]) * pricePerUnit * [self fuelChargeRate];
9239#else
9240 OOCreditsQuantity creditsForRefuel = ([self fuelCapacity] - [self fuel]) * pricePerUnit;
9241#endif
9242 if (credits >= creditsForRefuel) // Ensure we don't overflow
9243 {
9244 credits -= creditsForRefuel;
9245 fuel = [self fuelCapacity];
9246 return YES;
9247 } else {
9248 return NO;
9249 }
9250 }
9251
9252 // check energy unit replacement
9253 if ([eqKey hasSuffix:@"ENERGY_UNIT"] && [self energyUnitType] != ENERGY_UNIT_NONE) {
9254 switch ([self energyUnitType]) {
9255 case ENERGY_UNIT_NAVAL:
9256 [self removeEquipmentItem:@"EQ_NAVAL_ENERGY_UNIT"];
9257 tradeIn = [UNIVERSE getEquipmentPriceForKey:@"EQ_NAVAL_ENERGY_UNIT"] / 2; // 50 % refund
9258 break;
9260 [self removeEquipmentItem:@"EQ_NAVAL_ENERGY_UNIT_DAMAGED"];
9261 tradeIn = [UNIVERSE getEquipmentPriceForKey:@"EQ_NAVAL_ENERGY_UNIT"] / 4; // half of the working one
9262 break;
9263 case ENERGY_UNIT_NORMAL:
9264 [self removeEquipmentItem:@"EQ_ENERGY_UNIT"];
9265 tradeIn = [UNIVERSE getEquipmentPriceForKey:@"EQ_ENERGY_UNIT"] * 3 / 4; // 75 % refund
9266 break;
9268 [self removeEquipmentItem:@"EQ_ENERGY_UNIT_DAMAGED"];
9269 tradeIn = [UNIVERSE getEquipmentPriceForKey:@"EQ_ENERGY_UNIT"] * 3 / 8; // half of the working one
9270 break;
9271
9272 default:
9273 break;
9274 }
9275 [self doTradeIn:tradeIn forPriceFactor:priceFactor];
9276 }
9277
9278 // maintain ship
9279 if ([eqKey isEqualToString:@"EQ_RENOVATION"]) {
9280 OOTechLevelID techLevel = NSNotFound;
9281 if (dockedStation != nil)
9282 techLevel = [dockedStation equivalentTechLevel];
9283 if (techLevel == NSNotFound)
9284 techLevel = [[UNIVERSE currentSystemData] oo_unsignedIntForKey:KEY_TECHLEVEL];
9285
9286 credits -= price;
9287 ship_trade_in_factor += 5 + techLevel; // you get better value at high-tech repair bases
9288 if (ship_trade_in_factor > 100)
9289 ship_trade_in_factor = 100;
9290
9291 [self clearSubEntities];
9292 [self setUpSubEntities];
9293
9294 return YES;
9295 }
9296
9297 if ([eqKey hasSuffix:@"MISSILE"] || [eqKey hasSuffix:@"MINE"]) {
9298 ShipEntity* weapon = [[UNIVERSE newShipWithRole:eqKey] autorelease];
9299 if (weapon)
9300 OOLog(kOOLogBuyMountedOK, @"Got ship for mounted weapon role %@", eqKey);
9301 else
9302 OOLog(kOOLogBuyMountedFailed, @"Could not find ship for mounted weapon role %@", eqKey);
9303
9304 BOOL mounted_okay = [self mountMissile:weapon];
9305 if (mounted_okay) {
9306 credits -= price;
9307 [self safeAllMissiles];
9308 [self tidyMissilePylons];
9309 [self setActiveMissile:0];
9310 }
9311 return mounted_okay;
9312 }
9313
9314 if ([eqKey isEqualToString:@"EQ_PASSENGER_BERTH"]) {
9315 [self changePassengerBerths:+1];
9316 credits -= price;
9317 return YES;
9318 }
9319
9320 if ([eqKey isEqualToString:@"EQ_PASSENGER_BERTH_REMOVAL"]) {
9321 [self changePassengerBerths:-1];
9322 credits -= price;
9323 return YES;
9324 }
9325
9326 if ([eqKey isEqualToString:@"EQ_MISSILE_REMOVAL"]) {
9327 credits -= price;
9328 tradeIn += [self removeMissiles];
9329 [self doTradeIn:tradeIn forPriceFactor:priceFactor];
9330 return YES;
9331 }
9332
9333 if ([self canAddEquipment:eqKey inContext:@"purchase"]) {
9334 credits -= price;
9335 [self addEquipmentItem:eqKey withValidation:NO inContext:@"purchase"]; // no need to validate twice.
9336 if (isRepair) {
9337 [self doScriptEvent:OOJSID("equipmentRepaired") withArgument:eqKey];
9338 }
9339 return YES;
9340 }
9341
9342 return NO;
9343}
9344
9345- (BOOL)setWeaponMount:(OOWeaponFacing)facing toWeapon:(NSString*)eqKey
9346{
9347 return [self setWeaponMount:facing toWeapon:eqKey inContext:@"purchase"];
9348}
9349
9350- (BOOL)setWeaponMount:(OOWeaponFacing)facing toWeapon:(NSString*)eqKey inContext:(NSString*)context
9351{
9352
9353 NSDictionary* shipyardInfo = [[OOShipRegistry sharedRegistry] shipyardInfoForKey:[self shipDataKey]];
9354 unsigned available_facings = [shipyardInfo oo_unsignedIntForKey:KEY_WEAPON_FACINGS defaultValue:[self weaponFacings]]; // use defaults explicitly
9355
9356 // facing exists?
9357 if (!(available_facings & facing)) {
9358 return NO;
9359 }
9360
9361 // weapon allowed (or NONE)?
9362 if (![eqKey isEqualToString:@"EQ_WEAPON_NONE"]) {
9363 if (![self canAddEquipment:eqKey inContext:context]) {
9364 return NO;
9365 }
9366 }
9367
9368 // sets WEAPON_NONE if not recognised
9370
9371 switch (facing) {
9373 forward_weapon_type = chosen_weapon;
9374 break;
9375
9376 case WEAPON_FACING_AFT:
9377 aft_weapon_type = chosen_weapon;
9378 break;
9379
9380 case WEAPON_FACING_PORT:
9381 port_weapon_type = chosen_weapon;
9382 break;
9383
9385 starboard_weapon_type = chosen_weapon;
9386 break;
9387
9388 case WEAPON_FACING_NONE:
9389 break;
9390 }
9391
9392 return YES;
9393}
9394
9395- (BOOL)changePassengerBerths:(int)addRemove
9396{
9397 if (addRemove == 0)
9398 return NO;
9399 addRemove = (addRemove > 0) ? 1 : -1; // change only by one berth at a time!
9400 // NSFO!
9401 // unsigned passenger_space = [[OOEquipmentType equipmentTypeWithIdentifier:@"EQ_PASSENGER_BERTH"] requiredCargoSpace];
9402 // if (passenger_space == 0) passenger_space = PASSENGER_BERTH_SPACE;
9403 if ((max_passengers < 1 && addRemove == -1) || ([self maxAvailableCargoSpace] - current_cargo < PASSENGER_BERTH_SPACE && addRemove == 1))
9404 return NO;
9405 max_passengers += addRemove;
9406 max_cargo -= PASSENGER_BERTH_SPACE * addRemove;
9407 return YES;
9408}
9409
9411{
9412 [self safeAllMissiles];
9413 OOCreditsQuantity tradeIn = 0;
9414 unsigned i;
9415 for (i = 0; i < missiles; i++) {
9416 NSString* weapon_key = [missile_list[i] identifier];
9417
9418 if (weapon_key != nil)
9419 tradeIn += (int)[UNIVERSE getEquipmentPriceForKey:weapon_key];
9420 }
9421
9422 for (i = 0; i < max_missiles; i++) {
9423 [missile_entity[i] release];
9424 missile_entity[i] = nil;
9425 }
9426
9427 missiles = 0;
9428 return tradeIn;
9429}
9430
9431- (void)doTradeIn:(OOCreditsQuantity)tradeInValue forPriceFactor:(double)priceFactor
9432{
9433 if (tradeInValue != 0) {
9434 if (priceFactor < 1.0)
9435 tradeInValue *= priceFactor;
9436 credits += tradeInValue;
9437 }
9438}
9439
9440- (OOCargoQuantity)cargoQuantityForType:(OOCommodityType)type
9441{
9443
9444 if ([self status] != STATUS_DOCKED) {
9445 NSInteger i;
9446 OOCommodityType co_type;
9447 ShipEntity* cargoItem = nil;
9448
9449 for (i = [cargo count] - 1; i >= 0; i--) {
9450 cargoItem = [cargo objectAtIndex:i];
9451 co_type = [cargoItem commodityType];
9452 if ([co_type isEqualToString:type]) {
9453 amount += [cargoItem commodityAmount];
9454 }
9455 }
9456 }
9457
9458 return amount;
9459}
9460
9461- (OOCargoQuantity)setCargoQuantityForType:(OOCommodityType)type amount:(OOCargoQuantity)amount
9462{
9464 if ([self specialCargo] && unit == UNITS_TONS)
9465 return 0; // don't do anything if we've got a special cargo...
9466
9467 OOCargoQuantity oldAmount = [self cargoQuantityForType:type];
9468 OOCargoQuantity available = [self availableCargoSpace];
9469 BOOL inPods = ([self status] != STATUS_DOCKED);
9470
9471 // check it against the max amount.
9472 if (unit == UNITS_TONS && (available + oldAmount) < amount) {
9473 amount = available + oldAmount;
9474 }
9475 // if we have 1499 kg the ship registers only 1 ton, so it's possible to exceed the max cargo:
9476 // eg: with maxAvailableCargoSpace 2 & gold 1499kg, you can still add 1 ton alloy.
9477 else if (unit == UNITS_KILOGRAMS && amount > oldAmount) {
9478 // Allow up to 0.5 ton of kg (& g) goods above the cargo capacity but respect existing quantities.
9479 OOCargoQuantity safeAmount = available * KILOGRAMS_PER_POD + MAX_KILOGRAMS_IN_SAFE;
9480 if (safeAmount < amount)
9481 amount = (safeAmount < oldAmount) ? oldAmount : safeAmount;
9482 } else if (unit == UNITS_GRAMS && amount > oldAmount) {
9483 OOCargoQuantity safeAmount = available * GRAMS_PER_POD + MAX_GRAMS_IN_SAFE;
9484 if (safeAmount < amount)
9485 amount = (safeAmount < oldAmount) ? oldAmount : safeAmount;
9486 }
9487
9488 if (inPods) {
9489 if (amount > oldAmount) // increase
9490 {
9491 [self loadCargoPodsForType:type amount:(amount - oldAmount)];
9492 } else {
9493 [self unloadCargoPodsForType:type amount:(oldAmount - amount)];
9494 }
9495 } else {
9497 }
9498
9499 [self calculateCurrentCargo];
9500 return [shipCommodityData quantityForGood:type];
9501}
9502
9507
9509{
9510 if ([self specialCargo] != nil) {
9511 return [self maxAvailableCargoSpace];
9512 }
9513
9514 /*
9515 The cargo array is nil when the player ship is docked, due to action in unloadCargopods. For
9516 this reason, we must use a slightly more complex method to determine the quantity of cargo
9517 carried in this case - Nikos 20090830
9518
9519 Optimised this method, to compensate for increased usage - Kaks 20091002
9520 */
9521 OOCargoQuantity cargoQtyOnBoard = 0;
9522 NSString* good = nil;
9523
9524 foreach (good, [shipCommodityData goods]) {
9526
9527 OOMassUnit commodityUnits = [shipCommodityData massUnitForGood:good];
9528
9529 if (commodityUnits != UNITS_TONS) {
9530 // calculate the number of pods that would be used
9531 // we're using integer math, so 99/100 = 0 , 100/100 = 1, etc...
9532
9533 assert(KILOGRAMS_PER_POD > MAX_KILOGRAMS_IN_SAFE && GRAMS_PER_POD > MAX_GRAMS_IN_SAFE); // otherwise we're in trouble!
9534
9535 if (commodityUnits == UNITS_KILOGRAMS)
9536 quantity = ((KILOGRAMS_PER_POD - MAX_KILOGRAMS_IN_SAFE - 1) + quantity) / KILOGRAMS_PER_POD;
9537 else
9538 quantity = ((GRAMS_PER_POD - MAX_GRAMS_IN_SAFE - 1) + quantity) / GRAMS_PER_POD;
9539 }
9540 cargoQtyOnBoard += quantity;
9541 }
9542 cargoQtyOnBoard += [[self cargo] count];
9543
9544 return cargoQtyOnBoard;
9545}
9546
9548{
9549 StationEntity* station = [self dockedStation];
9550 if (station == nil) {
9551 if ([[self primaryTarget] isStation] && [(StationEntity*)[self primaryTarget] marketBroadcast]) {
9552 station = [self primaryTarget];
9553 } else {
9554 station = [UNIVERSE station];
9555 }
9556 if (station == nil) {
9557 // interstellar space or similar
9558 return nil;
9559 }
9560 }
9562 if (localMarket == nil) {
9564 }
9565
9566 return localMarket;
9567}
9568
9569- (NSArray*)applyMarketFilter:(NSArray*)goods onMarket:(OOCommodityMarket*)market
9570{
9572 return goods;
9573 }
9574 NSMutableArray* filteredGoods = [NSMutableArray arrayWithCapacity:[goods count]];
9575 OOCommodityType good = nil;
9576 foreach (good, goods) {
9577 switch (marketFilterMode) {
9579 // never reached, but keeps compiler happy
9580 [filteredGoods addObject:good];
9581 break;
9583 if ([market quantityForGood:good] > 0 || [self cargoQuantityForType:good] > 0) {
9584 [filteredGoods addObject:good];
9585 }
9586 break;
9588 if ([self cargoQuantityForType:good] > 0) {
9589 [filteredGoods addObject:good];
9590 }
9591 break;
9593 if ([market quantityForGood:good] > 0) {
9594 [filteredGoods addObject:good];
9595 }
9596 break;
9598 if ([market exportLegalityForGood:good] == 0 && [market importLegalityForGood:good] == 0) {
9599 [filteredGoods addObject:good];
9600 }
9601 break;
9603 if ([market exportLegalityForGood:good] > 0 || [market importLegalityForGood:good] > 0) {
9604 [filteredGoods addObject:good];
9605 }
9606 break;
9607 }
9608 }
9609 return [[filteredGoods copy] autorelease];
9610}
9611
9612- (NSArray*)applyMarketSorter:(NSArray*)goods onMarket:(OOCommodityMarket*)market
9613{
9614 switch (marketSorterMode) {
9616 return [goods sortedArrayUsingFunction:marketSorterByName context:market];
9618 return [goods sortedArrayUsingFunction:marketSorterByPrice context:market];
9620 return [goods sortedArrayUsingFunction:marketSorterByQuantity context:market];
9622 return [goods sortedArrayUsingFunction:marketSorterByQuantity context:shipCommodityData];
9624 return [goods sortedArrayUsingFunction:marketSorterByMassUnit context:market];
9626 // keep default sort order
9627 break;
9628 }
9629 return goods;
9630}
9631
9633{
9634 GuiDisplayGen* gui = [UNIVERSE gui];
9635 OOGUITabSettings tab_stops;
9636 tab_stops[0] = 0;
9637 tab_stops[1] = 137;
9638 tab_stops[2] = 187;
9639 tab_stops[3] = 267;
9640 tab_stops[4] = 321;
9641 tab_stops[5] = 431;
9642 [gui overrideTabs:tab_stops from:kGuiMarketTabs length:6];
9643 [gui setTabStops:tab_stops];
9644
9645 [gui setColor:[gui colorFromSetting:kGuiMarketHeadingColor defaultValue:[OOColor greenColor]] forRow:GUI_ROW_MARKET_KEY];
9646 [gui setArray:[NSArray arrayWithObjects:DESC(@"commodity-column-title"), OOPadStringToEms(DESC(@"price-column-title"), 3.5),
9647 OOPadStringToEms(DESC(@"for-sale-column-title"), 3.75), OOPadStringToEms(DESC(@"in-hold-column-title"), 5.75), DESC(@"oolite-legality-column-title"), DESC(@"oolite-extras-column-title"), nil]
9648 forRow:GUI_ROW_MARKET_KEY];
9649 [gui setArray:[NSArray arrayWithObjects:DESC(@"commodity-column-title"), DESC(@"oolite-extras-column-title"), OOPadStringToEms(DESC(@"price-column-title"), 3.5),
9650 OOPadStringToEms(DESC(@"for-sale-column-title"), 3.75), OOPadStringToEms(DESC(@"in-hold-column-title"), 5.75), DESC(@"oolite-legality-column-title"), nil]
9651 forRow:GUI_ROW_MARKET_KEY];
9652}
9653
9654- (void)showMarketScreenDataLine:(OOGUIRow)row forGood:(OOCommodityType)good inMarket:(OOCommodityMarket*)localMarket holdQuantity:(OOCargoQuantity)quantity
9655{
9656 GuiDisplayGen* gui = [UNIVERSE gui];
9657 NSString* desc = [NSString stringWithFormat:@" %@ ", [shipCommodityData nameForGood:good]];
9658 OOCargoQuantity available_units = [localMarket quantityForGood:good];
9659 OOCargoQuantity units_in_hold = quantity;
9660 OOCreditsQuantity pricePerUnit = [localMarket priceForGood:good];
9661 OOMassUnit unit = [shipCommodityData massUnitForGood:good];
9662
9663 NSString* available = OOPadStringToEms(((available_units > 0) ? (NSString*)[NSString stringWithFormat:@"%d", available_units] : DESC(@"commodity-quantity-none")), 2.5);
9664
9665 NSUInteger priceDecimal = pricePerUnit % 10;
9666 NSString* price = [NSString stringWithFormat:@" %@.%zu ", OOPadStringToEms([NSString stringWithFormat:@"%zu", (pricePerUnit / 10)], 2.5), priceDecimal];
9667
9668 // this works with up to 9999 tons of gemstones. Any more than that, they deserve the formatting they get! :)
9669
9670 NSString* owned = OOPadStringToEms((units_in_hold > 0) ? (NSString*)[NSString stringWithFormat:@"%d", units_in_hold] : DESC(@"commodity-quantity-none"), 4.5);
9671 NSString* units = DisplayStringForMassUnit(unit);
9672 NSString* units_available = [NSString stringWithFormat:@" %@ %@ ", available, units];
9673 NSString* units_owned = [NSString stringWithFormat:@" %@ %@ ", owned, units];
9674
9675 NSUInteger import_legality = [localMarket importLegalityForGood:good];
9676 NSUInteger export_legality = [localMarket exportLegalityForGood:good];
9677 NSString* legaldesc = nil;
9678 if (import_legality == 0) {
9679 if (export_legality == 0) {
9680 legaldesc = DESC(@"oolite-legality-clear");
9681 } else {
9682 legaldesc = DESC(@"oolite-legality-import");
9683 }
9684 } else {
9685 if (export_legality == 0) {
9686 legaldesc = DESC(@"oolite-legality-export");
9687 } else {
9688 legaldesc = DESC(@"oolite-legality-neither");
9689 }
9690 }
9691 legaldesc = [NSString stringWithFormat:@" %@ ", legaldesc];
9692
9693 NSString* extradesc = [shipCommodityData shortCommentForGood:good];
9694
9695 [gui setKey:good forRow:row];
9696 [gui setColor:[gui colorFromSetting:kGuiMarketCommodityColor defaultValue:nil] forRow:row];
9697 [gui setArray:[NSArray arrayWithObjects:desc, extradesc, price, units_available, units_owned, legaldesc, nil] forRow:row++];
9698}
9699
9701{
9703
9704 /* Override normal behaviour if station broadcasts market */
9705 if (dockedStation == nil) {
9706 if ([[self primaryTarget] isStation] && [(StationEntity*)[self primaryTarget] marketBroadcast]) {
9708 }
9709 }
9710
9711 NSString* system = nil;
9712 if ([UNIVERSE sun] != nil)
9713 system = [UNIVERSE getSystemName:system_id];
9714
9715 if (dockedStation == nil || dockedStation == [UNIVERSE station]) {
9716 if ([UNIVERSE sun] != nil) {
9717 return OOExpandKey(@"system-commodity-market", system);
9718 } else {
9719 // Witchspace
9720 return OOExpandKey(@"commodity-market");
9721 }
9722 } else {
9723 NSString* station = [dockedStation displayName];
9724 return OOExpandKey(@"station-commodity-market", station);
9725 }
9726}
9727
9729{
9731 GuiDisplayGen* gui = [UNIVERSE gui];
9732 OOGUIScreenID oldScreen = gui_screen;
9733
9734 gui_screen = GUI_SCREEN_MARKET;
9735 BOOL guiChanged = (oldScreen != gui_screen);
9736
9737 [[UNIVERSE gameController] setMouseInteractionModeForUIWithMouseInteraction:YES];
9738
9739 // fix problems with economies in witchspace
9740 if (localMarket == nil) {
9741 localMarket = [[UNIVERSE commodities] generateBlankMarket];
9742 }
9743
9744 // following changed to work whether docked or not
9745 NSArray* goods = [self applyMarketSorter:[self applyMarketFilter:[localMarket goods] onMarket:localMarket] onMarket:localMarket];
9746 NSInteger maxOffset = 0;
9747 if ([goods count] > (GUI_ROW_MARKET_END - GUI_ROW_MARKET_START)) {
9748 maxOffset = [goods count] - (GUI_ROW_MARKET_END - GUI_ROW_MARKET_START);
9749 }
9750
9751 NSUInteger commodityCount = [shipCommodityData count];
9752 OOCargoQuantity quantityInHold[commodityCount];
9753
9754 for (NSUInteger i = 0; i < commodityCount; i++) {
9755 quantityInHold[i] = [shipCommodityData quantityForGood:[goods oo_stringAtIndex:i]];
9756 }
9757 for (NSUInteger i = 0; i < [cargo count]; i++) {
9758 ShipEntity* container = [cargo objectAtIndex:i];
9759 NSUInteger goodsIndex = [goods indexOfObject:[container commodityType]];
9760 // can happen with filters
9761 if (goodsIndex != NSNotFound) {
9762 quantityInHold[goodsIndex] += [container commodityAmount];
9763 }
9764 }
9765
9766 if (marketSelectedCommodity != nil && ([marketSelectedCommodity isEqualToString:@"<<<"] || [marketSelectedCommodity isEqualToString:@">>>"])) {
9767 // nothing?
9768 } else {
9769 if (marketSelectedCommodity == nil || [goods indexOfObject:marketSelectedCommodity] == NSNotFound) {
9771 if ([goods count] > 0) {
9772 marketSelectedCommodity = [[goods oo_stringAtIndex:0] retain];
9773 }
9774 }
9775 if (maxOffset > 0) {
9776 NSInteger goodsIndex = [goods indexOfObject:marketSelectedCommodity];
9777 // validate marketOffset when returning from infoscreen
9778 if (goodsIndex <= marketOffset) {
9779 // is off top of list, move list upwards
9780 if (goodsIndex == 0) {
9781 marketOffset = 0;
9782 } else {
9783 marketOffset = goodsIndex - 1;
9784 }
9785 } else if (goodsIndex > marketOffset + (GUI_ROW_MARKET_END - GUI_ROW_MARKET_START) - 2) {
9786 // is off bottom of list, move list downwards
9788 if (marketOffset > maxOffset) {
9789 marketOffset = maxOffset;
9790 }
9791 }
9792 }
9793 }
9794
9795 // GUI stuff
9796 {
9797 OOGUIRow start_row = GUI_ROW_MARKET_START;
9798 OOGUIRow row = start_row;
9799 OOGUIRow active_row = [gui selectedRow];
9800
9801 [gui clearAndKeepBackground:!guiChanged];
9802
9804 if (dockedStation == nil && [[self primaryTarget] isStation] && [(StationEntity*)[self primaryTarget] marketBroadcast]) {
9806 }
9807
9809
9811
9812 if (marketOffset > maxOffset) {
9813 marketOffset = 0;
9814 } else if (marketOffset < 0) {
9815 marketOffset = maxOffset;
9816 }
9817
9818 if ([goods count] > 0) {
9819 OOCommodityType good = nil;
9820 NSInteger i = 0;
9821 foreach (good, goods) {
9822 if (i < marketOffset) {
9823 ++i;
9824 continue;
9825 }
9826 [self showMarketScreenDataLine:row forGood:good inMarket:localMarket holdQuantity:quantityInHold[i++]];
9827 if ([good isEqualToString:marketSelectedCommodity]) {
9828 active_row = row;
9829 }
9830
9831 ++row;
9832 if (row >= GUI_ROW_MARKET_END) {
9833 break;
9834 }
9835 }
9836
9837 if (marketOffset < maxOffset) {
9838 if ([marketSelectedCommodity isEqualToString:@">>>"]) {
9839 active_row = GUI_ROW_MARKET_LAST;
9840 }
9841 [gui setKey:@">>>" forRow:GUI_ROW_MARKET_LAST];
9842 [gui setColor:[gui colorFromSetting:kGuiMarketScrollColor defaultValue:[OOColor greenColor]] forRow:GUI_ROW_MARKET_LAST];
9843 [gui setArray:[NSArray arrayWithObjects:DESC(@"gui-more"), @"", @"", @"", @" --> ", nil] forRow:GUI_ROW_MARKET_LAST];
9844 }
9845 if (marketOffset > 0) {
9846 if ([marketSelectedCommodity isEqualToString:@"<<<"]) {
9847 active_row = GUI_ROW_MARKET_START;
9848 }
9849 [gui setKey:@"<<<" forRow:GUI_ROW_MARKET_START];
9850 [gui setColor:[gui colorFromSetting:kGuiMarketScrollColor defaultValue:[OOColor greenColor]] forRow:GUI_ROW_MARKET_START];
9851 [gui setArray:[NSArray arrayWithObjects:DESC(@"gui-back"), @"", @"", @"", @" <-- ", nil] forRow:GUI_ROW_MARKET_START];
9852 }
9853 } else {
9854 // filter is excluding everything
9855 [gui setColor:[gui colorFromSetting:kGuiMarketFilteredAllColor defaultValue:[OOColor yellowColor]] forRow:GUI_ROW_MARKET_START];
9856 [gui setText:DESC(@"oolite-market-filtered-all") forRow:GUI_ROW_MARKET_START];
9857 active_row = -1;
9858 }
9859
9860 // actually count the containers and valuables (may be > max_cargo)
9864
9865 // filter sort info
9866 {
9867 NSString* filterMode = OOExpandKey(OOExpand(@"oolite-market-filter-[marketFilterMode]", marketFilterMode));
9868 NSString* filterText = OOExpandKey(@"oolite-market-filter-line", filterMode);
9869 NSString* sortMode = OOExpandKey(OOExpand(@"oolite-market-sorter-[marketSorterMode]", marketSorterMode));
9870 NSString* sorterText = OOExpandKey(@"oolite-market-sorter-line", sortMode);
9871 [gui setArray:[NSArray arrayWithObjects:filterText, @"", sorterText, nil] forRow:GUI_ROW_MARKET_END];
9872 }
9873 [gui setColor:[gui colorFromSetting:kGuiMarketFilterInfoColor defaultValue:[OOColor greenColor]] forRow:GUI_ROW_MARKET_END];
9874
9876
9877 [gui setSelectableRange:NSMakeRange(start_row, row - start_row)];
9878 [gui setSelectedRow:active_row];
9879
9881 }
9882
9883 [[UNIVERSE gameView] clearMouse];
9884
9885 [self setShowDemoShips:NO];
9886 [UNIVERSE enterGUIViewModeWithMouseInteraction:YES];
9887
9888 if (guiChanged) {
9889 [gui setForegroundTextureKey:[self status] == STATUS_DOCKED ? @"docked_overlay" : @"overlay"];
9890 [gui setBackgroundTextureKey:@"market"];
9891 [self noteGUIDidChangeFrom:oldScreen to:gui_screen];
9892 }
9893}
9894
9896{
9898 GuiDisplayGen* gui = [UNIVERSE gui];
9899 OOGUIScreenID oldScreen = gui_screen;
9900
9901 gui_screen = GUI_SCREEN_MARKETINFO;
9902 BOOL guiChanged = (oldScreen != gui_screen);
9903
9904 [[UNIVERSE gameController] setMouseInteractionModeForUIWithMouseInteraction:YES];
9905
9906 // fix problems with economies in witchspace
9907 if (localMarket == nil) {
9908 localMarket = [[UNIVERSE commodities] generateBlankMarket];
9909 }
9910
9911 // following changed to work whether docked or not
9912 NSArray* goods = [self applyMarketSorter:[self applyMarketFilter:[localMarket goods] onMarket:localMarket] onMarket:localMarket];
9913
9914 NSUInteger i, j, commodityCount = [shipCommodityData count];
9915 OOCargoQuantity quantityInHold[commodityCount];
9916
9917 for (i = 0; i < commodityCount; i++) {
9918 quantityInHold[i] = [shipCommodityData quantityForGood:[goods oo_stringAtIndex:i]];
9919 }
9920 for (i = 0; i < [cargo count]; i++) {
9921 ShipEntity* container = [cargo objectAtIndex:i];
9922 j = [goods indexOfObject:[container commodityType]];
9923 quantityInHold[j] += [container commodityAmount];
9924 }
9925
9926 // GUI stuff
9927 {
9929 j = NSNotFound;
9930 } else {
9931 j = [goods indexOfObject:marketSelectedCommodity];
9932 }
9933 if (j == NSNotFound) {
9935 [self setGuiToMarketScreen];
9936 return;
9937 }
9938
9939 [gui clearAndKeepBackground:!guiChanged];
9940
9941 [gui setTitle:[NSString stringWithFormat:DESC(@"oolite-commodity-information-@"), [shipCommodityData nameForGood:marketSelectedCommodity]]];
9942
9944 [self showMarketScreenDataLine:GUI_ROW_MARKET_START forGood:marketSelectedCommodity inMarket:localMarket holdQuantity:quantityInHold[j]];
9945
9946 OOCargoQuantity contracted = [self contractedVolumeForGood:marketSelectedCommodity];
9947 if (contracted > 0) {
9948 OOMassUnit unit = [shipCommodityData massUnitForGood:marketSelectedCommodity];
9949 [gui setColor:[gui colorFromSetting:kGuiMarketContractedColor defaultValue:nil] forRow:GUI_ROW_MARKET_START + 1];
9950 [gui setText:[NSString stringWithFormat:DESC(@"oolite-commodity-contracted-d-@"), contracted, DisplayStringForMassUnit(unit)] forRow:GUI_ROW_MARKET_START + 1];
9951 }
9952
9953 NSString* info = [shipCommodityData commentForGood:marketSelectedCommodity];
9954 OOGUIRow i = 0;
9955 if (info == nil || [info length] == 0) {
9956 i = [gui addLongText:DESC(@"oolite-commodity-no-comment") startingAtRow:GUI_ROW_MARKET_START + 2 align:GUI_ALIGN_LEFT];
9957 } else {
9958 i = [gui addLongText:info startingAtRow:GUI_ROW_MARKET_START + 2 align:GUI_ALIGN_LEFT];
9959 }
9960 for (i--; i > GUI_ROW_MARKET_START + 2; --i) {
9961 [gui setColor:[gui colorFromSetting:kGuiMarketDescriptionColor defaultValue:nil] forRow:i];
9962 }
9963
9965 }
9966
9967 [[UNIVERSE gameView] clearMouse];
9968
9969 [self setShowDemoShips:NO];
9970 [UNIVERSE enterGUIViewModeWithMouseInteraction:YES];
9971
9972 if (guiChanged) {
9973 [gui setForegroundTextureKey:[self status] == STATUS_DOCKED ? @"docked_overlay" : @"overlay"];
9974 [gui setBackgroundTextureKey:@"marketinfo"];
9975 [self noteGUIDidChangeFrom:oldScreen to:gui_screen];
9976 }
9977}
9978
9980{
9981 GuiDisplayGen* gui = [UNIVERSE gui];
9982 OOCargoQuantity currentCargo = current_cargo;
9983 OOCargoQuantity cargoCapacity = [self maxAvailableCargoSpace];
9984 [gui setText:OOExpandKey(@"market-cash-and-load", credits, currentCargo, cargoCapacity) forRow:GUI_ROW_MARKET_CASH];
9985 [gui setColor:[gui colorFromSetting:kGuiMarketCashColor defaultValue:[OOColor yellowColor]] forRow:GUI_ROW_MARKET_CASH];
9986}
9987
9989{
9990 return gui_screen;
9991}
9992
9993- (BOOL)tryBuyingCommodity:(OOCommodityType)index all:(BOOL)all
9994{
9995 if ([index isEqualToString:@"<<<"] || [index isEqualToString:@">>>"]) {
9996 ++marketOffset;
9997 return NO;
9998 }
9999
10000 if (![self isDocked])
10001 return NO; // can't buy if not docked.
10002
10004 OOCreditsQuantity pricePerUnit = [localMarket priceForGood:index];
10005 OOMassUnit unit = [localMarket massUnitForGood:index];
10006
10007 if (specialCargo != nil && unit == UNITS_TONS) {
10008 return NO; // can't buy tons of stuff when carrying a specialCargo
10009 }
10010 int manifest_quantity = [shipCommodityData quantityForGood:index];
10011 int market_quantity = [localMarket quantityForGood:index];
10012
10013 int purchase = 1;
10014 if (all) {
10015 // if cargo contracts, put a break point on the contract volume
10016 int contracted = [self contractedVolumeForGood:index];
10017 if (manifest_quantity >= contracted) {
10018 purchase = [localMarket capacityForGood:index];
10019 } else {
10020 purchase = contracted - manifest_quantity;
10021 }
10022 }
10023 if (purchase > market_quantity) {
10024 purchase = market_quantity; // limit to what's available
10025 }
10026 if (purchase * pricePerUnit > credits) {
10027 purchase = floor(credits / pricePerUnit); // limit to what's affordable
10028 }
10029 // TODO - fix brokenness here...
10030 if (unit == UNITS_TONS && purchase + current_cargo > [self maxAvailableCargoSpace]) {
10031 purchase = [self availableCargoSpace]; // limit to available cargo space
10032 } else {
10033 if (current_cargo == [self maxAvailableCargoSpace]) {
10034 // other cases are fine so long as buying is limited to <1000kg / <1000000g
10035 // but if this case is true, we need to see if there is more space in
10036 // the manifest (safe) or an already-accounted-for pod
10037 if (unit == UNITS_KILOGRAMS) {
10038 if (manifest_quantity % KILOGRAMS_PER_POD <= MAX_KILOGRAMS_IN_SAFE && (manifest_quantity + purchase) % KILOGRAMS_PER_POD > MAX_KILOGRAMS_IN_SAFE) {
10039 // going from < n500 to >= n500 would increase pods needed by 1
10040 purchase = MAX_KILOGRAMS_IN_SAFE - manifest_quantity; // max possible
10041 }
10042 } else // UNITS_GRAMS
10043 {
10044 if (manifest_quantity % GRAMS_PER_POD <= MAX_GRAMS_IN_SAFE && (manifest_quantity + purchase) % GRAMS_PER_POD > MAX_GRAMS_IN_SAFE) {
10045 // going from < n500000 to >= n500000 would increase pods needed by 1
10046 purchase = MAX_GRAMS_IN_SAFE - manifest_quantity; // max possible
10047 }
10048 }
10049 }
10050 }
10051 if (purchase <= 0) {
10052 return NO; // stop if that results in nothing to be bought
10053 }
10054
10055 [localMarket removeQuantity:purchase forGood:index];
10056 [shipCommodityData addQuantity:purchase forGood:index];
10057 credits -= pricePerUnit * purchase;
10058
10059 [self calculateCurrentCargo];
10060
10061 if ([UNIVERSE autoSave])
10062 [UNIVERSE setAutoSaveNow:YES];
10063
10064 [self doScriptEvent:OOJSID("playerBoughtCargo") withArguments:[NSArray arrayWithObjects:index, [NSNumber numberWithInt:purchase], [NSNumber numberWithUnsignedLongLong:pricePerUnit], nil]];
10065 if ([localMarket exportLegalityForGood:index] > 0) {
10066 [roleWeightFlags setObject:[NSNumber numberWithInt:1] forKey:@"bought-illegal"];
10067 } else {
10068 [roleWeightFlags setObject:[NSNumber numberWithInt:1] forKey:@"bought-legal"];
10069 }
10070
10071 return YES;
10072}
10073
10074- (BOOL)trySellingCommodity:(OOCommodityType)index all:(BOOL)all
10075{
10076 if ([index isEqualToString:@"<<<"] || [index isEqualToString:@">>>"]) {
10077 --marketOffset;
10078 return NO;
10079 }
10080
10081 if (![self isDocked])
10082 return NO; // can't sell if not docked.
10083
10085 int available_units = [shipCommodityData quantityForGood:index];
10086 OOCreditsQuantity pricePerUnit = [localMarket priceForGood:index];
10087
10088 if (available_units == 0)
10089 return NO;
10090
10091 int market_quantity = [localMarket quantityForGood:index];
10092
10093 int capacity = [localMarket capacityForGood:index];
10094 int sell = 1;
10095 if (all) {
10096 // if cargo contracts, put a break point on the contract volume
10097 int contracted = [self contractedVolumeForGood:index];
10098 if (available_units <= contracted) {
10099 sell = capacity;
10100 } else {
10101 sell = available_units - contracted;
10102 }
10103 }
10104
10105 if (sell > available_units)
10106 sell = available_units; // limit to what's in the hold
10107 if (sell + market_quantity > capacity)
10108 sell = capacity - market_quantity; // avoid flooding the market
10109 if (sell <= 0)
10110 return NO; // stop if that results in nothing to be sold
10111
10112 [localMarket addQuantity:sell forGood:index];
10114 credits += pricePerUnit * sell;
10115
10116 [self calculateCurrentCargo];
10117
10118 if ([UNIVERSE autoSave])
10119 [UNIVERSE setAutoSaveNow:YES];
10120
10121 [self doScriptEvent:OOJSID("playerSoldCargo") withArguments:[NSArray arrayWithObjects:index, [NSNumber numberWithInt:sell], [NSNumber numberWithUnsignedLongLong:pricePerUnit], nil]];
10122
10123 return YES;
10124}
10125
10127{
10128 return using_mining_laser;
10129}
10130
10132{
10133 return isSpeechOn;
10134}
10135
10136- (BOOL)canAddEquipment:(NSString*)equipmentKey inContext:(NSString*)context
10137{
10138 if ([equipmentKey isEqualToString:@"EQ_RENOVATION"] && !(ship_trade_in_factor < 85 || [[[self shipSubEntityEnumerator] allObjects] count] < [self maxShipSubEntities]))
10139 return NO;
10140 if (![super canAddEquipment:equipmentKey inContext:context])
10141 return NO;
10142
10143 NSArray* conditions = [[OOEquipmentType equipmentTypeWithIdentifier:equipmentKey] conditions];
10144 if (conditions != nil && ![self scriptTestConditions:conditions])
10145 return NO;
10146
10147 return YES;
10148}
10149
10150- (BOOL)addEquipmentItem:(NSString*)equipmentKey inContext:(NSString*)context
10151{
10152 return [self addEquipmentItem:equipmentKey withValidation:YES inContext:context];
10153}
10154
10155- (BOOL)addEquipmentItem:(NSString*)equipmentKey withValidation:(BOOL)validateAddition inContext:(NSString*)context
10156{
10157 // deal with trumbles..
10158 if ([equipmentKey isEqualToString:@"EQ_TRUMBLE"]) {
10159 /* Bug fix: must return here if eqKey == @"EQ_TRUMBLE", even if
10160 trumbleCount >= 1. Otherwise, the player becomes immune to
10161 trumbles. See comment in -setCommanderDataFromDictionary: for more
10162 details.
10163 -- Ahruman 2008-12-04
10164 */
10165 // the old trumbles will kill the new one if there are enough of them.
10166 if ((trumbleCount < PLAYER_MAX_TRUMBLES / 6) || (trumbleCount < PLAYER_MAX_TRUMBLES / 3 && ranrot_rand() % 2 > 0)) {
10167 [self addTrumble:trumble[ranrot_rand() % PLAYER_MAX_TRUMBLES]]; // randomise its looks.
10168 return YES;
10169 }
10170 return NO;
10171 }
10172
10173 BOOL OK = [super addEquipmentItem:equipmentKey withValidation:validateAddition inContext:context];
10174
10175 if (OK) {
10176 if ([self hasEquipmentItemProviding:@"EQ_ADVANCED_COMPASS"] && [self compassMode] == COMPASS_MODE_BASIC) {
10177 [self setCompassMode:COMPASS_MODE_PLANET];
10178 }
10179
10180 [self addEqScriptForKey:equipmentKey];
10181 [self addEquipmentWithScriptToCustomKeyArray:equipmentKey];
10182 }
10183 return OK;
10184}
10185
10187{
10188 return customEquipActivation;
10189}
10190
10191- (void)addEquipmentWithScriptToCustomKeyArray:(NSString*)equipmentKey
10192{
10193 NSDictionary* item;
10194 NSUInteger i, j;
10195 NSArray* object;
10196
10197 for (i = 0; i < [eqScripts count]; i++) {
10198 if ([[[eqScripts oo_arrayAtIndex:i] oo_stringAtIndex:0] isEqualToString:equipmentKey]) {
10199 // check if this equipment item is already in the array
10200 for (j = 0; j < [customEquipActivation count]; j++) {
10201 item = [customEquipActivation objectAtIndex:j];
10202 if ([[item oo_stringForKey:CUSTOMEQUIP_EQUIPKEY] isEqualToString:equipmentKey])
10203 return;
10204 }
10205 // if we get here, this item is new
10206 // add the basic info at this point (equipkey and name only)
10208 NSMutableDictionary* customKey = [[NSMutableDictionary alloc] initWithObjectsAndKeys:equipmentKey, CUSTOMEQUIP_EQUIPKEY, [eq name], CUSTOMEQUIP_EQUIPNAME, nil];
10209
10210 // grab any default keys from the equipment item
10211 // default activate
10212 object = [eq defaultActivateKey];
10213 if ((object != nil && [object count] > 0))
10214 [customKey setObject:object forKey:CUSTOMEQUIP_KEYACTIVATE];
10215 // default mode
10216 object = [eq defaultModeKey];
10217 if ((object != nil && [object count] > 0))
10218 [customKey setObject:object forKey:CUSTOMEQUIP_KEYMODE];
10219
10220 [customEquipActivation addObject:customKey];
10221 [customKey release];
10222 // keep the keypress arrays in sync
10223 [customActivatePressed addObject:[NSNumber numberWithBool:NO]];
10224 [customModePressed addObject:[NSNumber numberWithBool:NO]];
10225
10226 NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
10227 [defaults setObject:customEquipActivation forKey:KEYCONFIG_CUSTOMEQUIP];
10228 return;
10229 }
10230 }
10231}
10232
10234{
10235 int i;
10236 bool update = NO;
10237 NSString* equipmentKey;
10238 if ([customEquipActivation count] == 0)
10239 return;
10240 for (i = [customEquipActivation count] - 1; i >= 0; i--) {
10241 equipmentKey = [[customEquipActivation objectAtIndex:i] oo_stringForKey:CUSTOMEQUIP_EQUIPKEY];
10243 if (!eq) {
10244 [customEquipActivation removeObjectAtIndex:i];
10245 [customActivatePressed removeObjectAtIndex:i];
10246 [customModePressed removeObjectAtIndex:i];
10247 update = YES;
10248 }
10249 }
10250 if (update) {
10251 NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
10252 [defaults setObject:customEquipActivation forKey:KEYCONFIG_CUSTOMEQUIP];
10253 }
10254}
10255
10256- (void)removeEquipmentItem:(NSString*)equipmentKey
10257{
10258 if (![self hasEquipmentItemProviding:@"EQ_ADVANCED_COMPASS"] && [self compassMode] != COMPASS_MODE_BASIC) {
10259 [self setCompassMode:COMPASS_MODE_BASIC];
10260 }
10261 [super removeEquipmentItem:equipmentKey];
10262 if (![self hasEquipmentItem:equipmentKey]) {
10263 // removed the last one
10264 [self removeEqScriptForKey:equipmentKey];
10265 }
10266}
10267
10268- (void)addEquipmentFromCollection:(id)equipment
10269{
10270 NSDictionary* dict = nil;
10271 NSEnumerator* eqEnum = nil;
10272 NSString* eqDesc = nil;
10273 NSUInteger i, count;
10274
10275 // Pass 1: Load the entire collection.
10276 if ([equipment isKindOfClass:[NSDictionary class]]) {
10277 dict = equipment;
10278 eqEnum = [equipment keyEnumerator];
10279 } else if ([equipment isKindOfClass:[NSArray class]] || [equipment isKindOfClass:[NSSet class]]) {
10280 eqEnum = [equipment objectEnumerator];
10281 } else if ([equipment isKindOfClass:[NSString class]]) {
10282 eqEnum = [[NSArray arrayWithObject:equipment] objectEnumerator];
10283 } else {
10284 return;
10285 }
10286
10287 while ((eqDesc = [eqEnum nextObject])) {
10288 /* Bug workaround: extra_equipment should never contain EQ_TRUMBLE,
10289 which is basically a magic flag passed to awardEquipment: to infect
10290 the player. However, prior to Oolite 1.70.1, if the player had a
10291 trumble infection and awardEquipment:EQ_TRUMBLE was called, an
10292 EQ_TRUMBLE would be added to the equipment list. Subsequent calls
10293 to awardEquipment:EQ_TRUMBLE would exit early because there was an
10294 EQ_TRUMBLE in the equipment list. as a result, it would no longer
10295 be possible to infect the player after the current infection ended.
10296
10297 The bug is fixed in 1.70.1. The following line is to fix old saved
10298 games which had been "corrupted" by the bug.
10299 -- Ahruman 2007-12-04
10300 */
10301 if ([eqDesc isEqualToString:@"EQ_TRUMBLE"])
10302 continue;
10303
10304 // Traditional form is a dictionary of booleans; we only accept those where the value is true.
10305 if (dict != nil && ![dict oo_boolForKey:eqDesc])
10306 continue;
10307
10308 // We need to add the entire collection without validation first and then remove the items that are
10309 // not compliant (like items that do not satisfy the requiresEquipment criterion). This is to avoid
10310 // unintentionally excluding valid equipment, just because the required equipment existed but had
10311 // not been yet added to the equipment list at the time of the canAddEquipment validation check.
10312 // Nikos, 20080817.
10313 count = [dict oo_unsignedIntegerForKey:eqDesc];
10314 for (i = 0; i < count; i++) {
10315 [self addEquipmentItem:eqDesc withValidation:NO inContext:@"loading"];
10316 }
10317 }
10318
10319 // Pass 2: Remove items that do not satisfy validation criteria (like requires_equipment etc.).
10320 if ([equipment isKindOfClass:[NSDictionary class]]) {
10321 eqEnum = [equipment keyEnumerator];
10322 } else if ([equipment isKindOfClass:[NSArray class]] || [equipment isKindOfClass:[NSSet class]]) {
10323 eqEnum = [equipment objectEnumerator];
10324 } else if ([equipment isKindOfClass:[NSString class]]) {
10325 eqEnum = [[NSArray arrayWithObject:equipment] objectEnumerator];
10326 }
10327 // Now remove items that should not be in the equipment list.
10328 while ((eqDesc = [eqEnum nextObject])) {
10329 if (![self equipmentValidToAdd:eqDesc whileLoading:YES inContext:@"loading"]) {
10330 [self removeEquipmentItem:eqDesc];
10331 }
10332 }
10333}
10334
10335- (BOOL)hasOneEquipmentItem:(NSString*)itemKey includeMissiles:(BOOL)includeMissiles
10336{
10337 // Check basic equipment the normal way.
10338 if ([super hasOneEquipmentItem:itemKey includeMissiles:NO whileLoading:NO])
10339 return YES;
10340
10341 // Custom handling for player missiles.
10342 if (includeMissiles) {
10343 unsigned i;
10344 for (i = 0; i < max_missiles; i++) {
10345 if ([[self missileForPylon:i] hasPrimaryRole:itemKey])
10346 return YES;
10347 }
10348 }
10349
10350 if ([itemKey isEqualToString:@"EQ_TRUMBLE"]) {
10351 return [self trumbleCount] > 0;
10352 }
10353
10354 return NO;
10355}
10356
10357- (BOOL)hasPrimaryWeapon:(OOWeaponType)weaponType
10358{
10359 if ([[forward_weapon_type identifier] isEqualToString:[weaponType identifier]] ||
10360 [[aft_weapon_type identifier] isEqualToString:[weaponType identifier]] ||
10361 [[port_weapon_type identifier] isEqualToString:[weaponType identifier]] ||
10362 [[starboard_weapon_type identifier] isEqualToString:[weaponType identifier]]) {
10363 return YES;
10364 }
10365
10366 return [super hasPrimaryWeapon:weaponType];
10367}
10368
10369- (BOOL)removeExternalStore:(OOEquipmentType*)eqType
10370{
10371 NSString* identifier = [eqType identifier];
10372
10373 // Look for matching missile.
10374 unsigned i;
10375 for (i = 0; i < max_missiles; i++) {
10376 if ([[self missileForPylon:i] hasPrimaryRole:identifier]) {
10377 [self removeFromPylon:i];
10378
10379 // Just remove one at a time.
10380 return YES;
10381 }
10382 }
10383 return NO;
10384}
10385
10386- (BOOL)removeFromPylon:(NSUInteger)pylon
10387{
10388 if (pylon >= max_missiles)
10389 return NO;
10390
10391 if (missile_entity[pylon] != nil) {
10392 NSString* identifier = [missile_entity[pylon] primaryRole];
10394
10395 // Remove the missile (must wait until we've finished with its identifier string!)
10396 [missile_entity[pylon] release];
10398
10399 [self tidyMissilePylons];
10400
10401 // This should be the currently selected missile, deselect it.
10402 if (pylon <= activeMissile) {
10403 if (activeMissile == missiles && missiles > 0)
10404 activeMissile--;
10405 if (activeMissile > 0)
10406 activeMissile--;
10407 else
10409
10410 [self selectNextMissile];
10411 }
10412
10413 return YES;
10414 }
10415
10416 return NO;
10417}
10418
10419- (NSUInteger)parcelCount
10420{
10421 return [parcels count];
10422}
10423
10424- (NSUInteger)passengerCount
10425{
10426 return [passengers count];
10427}
10428
10430{
10431 return max_passengers;
10432}
10433
10435{
10436 ShipEntity* playersTarget = [self primaryTarget];
10437 return ([playersTarget isShip] && [playersTarget hasHostileTarget] && [playersTarget primaryTarget] == self);
10438}
10439
10440- (void)receiveCommsMessage:(NSString*)message_text from:(ShipEntity*)other
10441{
10442 if ([self status] == STATUS_DEAD || [self status] == STATUS_DOCKED) {
10443 // only when in flight
10444 return;
10445 }
10446 [UNIVERSE addCommsMessage:[NSString stringWithFormat:@"%@:\n %@", [other displayName], message_text] forCount:4.5];
10447 [super receiveCommsMessage:message_text from:other];
10448}
10449
10451{
10452 if (legalStatus == 0)
10453 return; // nothing to pay for
10454
10455 OOGovernmentID local_gov = [[UNIVERSE currentSystemData] oo_intForKey:KEY_GOVERNMENT];
10456 if ([UNIVERSE inInterstellarSpace])
10457 local_gov = 1; // equivalent to Feudal. I'm assuming any station in interstellar space is military. -- Ahruman 2008-05-29
10458 OOCreditsQuantity fine = 500 + ((local_gov < 2 || local_gov > 5) ? 500 : 0);
10459 fine *= legalStatus;
10460 if (fine > credits) {
10461 int payback = (int)(legalStatus * credits / fine);
10462 [self setBounty:(legalStatus - payback) withReason:kOOLegalStatusReasonPaidFine];
10463 credits = 0;
10464 } else {
10465 [self setBounty:0 withReason:kOOLegalStatusReasonPaidFine];
10466 credits -= fine;
10467 }
10468
10469 // one of the fined-@-credits strings includes expansion tokens
10470 NSString* fined_message = [NSString stringWithFormat:OOExpandKey(@"fined-@-credits"), OOCredits(fine)];
10471 [self addMessageToReport:fined_message];
10472 [UNIVERSE forceWitchspaceEntries];
10473 ship_clock_adjust += 24 * 3600; // take up a day
10474}
10475
10476- (void)adjustTradeInFactorBy:(int)value
10477{
10478 ship_trade_in_factor += value;
10479 if (ship_trade_in_factor < 75)
10481 if (ship_trade_in_factor > 100)
10483}
10484
10486{
10487 return ship_trade_in_factor;
10488}
10489
10491{
10492 // 5% of value of ships wear + correction for missing subentities.
10493 OOCreditsQuantity shipValue = [UNIVERSE tradeInValueForCommanderDictionary:[self commanderDataDictionary]];
10494
10495 double costs = 0.005 * (100 - ship_trade_in_factor) * shipValue;
10496 costs += 0.01 * shipValue * [self missingSubEntitiesAdjustment];
10497 costs *= [self renovationFactor];
10498 return cunningFee(costs, 0.05);
10499}
10500
10502{
10504 NSDictionary* shipyardInfo = [registry shipyardInfoForKey:[self shipDataKey]];
10505 return [shipyardInfo oo_doubleForKey:KEY_RENOVATION_MULTIPLIER defaultValue:1.0];
10506}
10507
10509{
10510 float halfLength = 0.5f * (boundingBox.max.z - boundingBox.min.z);
10511 float halfWidth = 0.5f * (boundingBox.max.x - boundingBox.min.x);
10512
10513 forwardViewOffset = make_vector(0.0f, 0.0f, boundingBox.max.z - halfLength);
10514 aftViewOffset = make_vector(0.0f, 0.0f, boundingBox.min.z + halfLength);
10515 portViewOffset = make_vector(boundingBox.min.x + halfWidth, 0.0f, 0.0f);
10516 starboardViewOffset = make_vector(boundingBox.max.x - halfWidth, 0.0f, 0.0f);
10518}
10519
10521{
10522 NSArray* customViews = [[[OOShipRegistry sharedRegistry] shipInfoForKey:PLAYER_SHIP_DESC] oo_arrayForKey:@"custom_views"];
10523
10524 [_customViews release];
10525 _customViews = nil;
10526 _customViewIndex = 0;
10527 if (customViews != nil) {
10528 _customViews = [customViews retain];
10529 }
10530}
10531
10533{
10534 switch (currentWeaponFacing) {
10536 return forwardViewOffset;
10537 case WEAPON_FACING_AFT:
10538 return aftViewOffset;
10539 case WEAPON_FACING_PORT:
10540 return portViewOffset;
10542 return starboardViewOffset;
10543
10544 case WEAPON_FACING_NONE:
10545 // N.b.: this case should never happen.
10546 return customViewOffset;
10547 }
10548 return kZeroVector;
10549}
10550
10552{
10553 NSMutableString* trumbleDigrams = [NSMutableString stringWithCapacity:256];
10554 unichar xchar = (unichar)0;
10555 unichar digramchars[2];
10556
10557 while ([trumbleDigrams length] < PLAYER_MAX_TRUMBLES + 2) {
10558 NSString* commanderName = [self commanderName];
10559 if ([commanderName length] > 0) {
10560 [trumbleDigrams appendFormat:@"%@%@", commanderName, [[self mesh] modelName]];
10561 } else {
10562 [trumbleDigrams appendString:@"Some Random Text!"];
10563 }
10564 }
10565 int i;
10566 for (i = 0; i < PLAYER_MAX_TRUMBLES; i++) {
10567 digramchars[0] = ([trumbleDigrams characterAtIndex:i] & 0x007f) | 0x0020;
10568 digramchars[1] = (([trumbleDigrams characterAtIndex:i + 1] ^ xchar) & 0x007f) | 0x0020;
10569 xchar = digramchars[0];
10570 NSString* digramstring = [NSString stringWithCharacters:digramchars length:2];
10571 [trumble[i] release];
10572 trumble[i] = [[OOTrumble alloc] initForPlayer:self digram:digramstring];
10573 }
10574
10575 trumbleCount = 0;
10576
10578}
10579
10580- (void)addTrumble:(OOTrumble*)papaTrumble
10581{
10583 return;
10584 }
10585 OOTrumble* trumblePup = trumble[trumbleCount];
10586 [trumblePup spawnFrom:papaTrumble];
10587 trumbleCount++;
10588}
10589
10590- (void)removeTrumble:(OOTrumble*)deadTrumble
10591{
10592 if (trumbleCount <= 0) {
10593 return;
10594 }
10595 NSUInteger trumble_index = NSNotFound;
10596 NSUInteger i;
10597
10598 for (i = 0; (trumble_index == NSNotFound) && (i < trumbleCount); i++) {
10599 if (trumble[i] == deadTrumble)
10600 trumble_index = i;
10601 }
10602 if (trumble_index == NSNotFound) {
10603 OOLog(@"trumble.zombie", @"DEBUG can't get rid of inactive trumble %@", deadTrumble);
10604 return;
10605 }
10606 trumbleCount--; // reduce number of trumbles
10607 trumble[trumble_index] = trumble[trumbleCount]; // swap with the current last trumble
10608 trumble[trumbleCount] = deadTrumble; // swap with the current last trumble
10609}
10610
10612{
10613 return trumble;
10614}
10615
10616- (NSUInteger)trumbleCount
10617{
10618 return trumbleCount;
10619}
10620
10622{
10623 NSString* namekey = [NSString stringWithFormat:@"%@-humbletrash", [self commanderName]];
10624 int trumbleHash;
10625
10630 trumbleHash = munge_checksum(trumbleCount);
10631
10632 [[NSUserDefaults standardUserDefaults] setInteger:trumbleHash forKey:namekey];
10633
10634 int i;
10635 NSMutableArray* trumbleArray = [NSMutableArray arrayWithCapacity:PLAYER_MAX_TRUMBLES];
10636 for (i = 0; i < PLAYER_MAX_TRUMBLES; i++) {
10637 [trumbleArray addObject:[trumble[i] dictionary]];
10638 }
10639
10640 return [NSArray arrayWithObjects:[NSNumber numberWithUnsignedInteger:trumbleCount], [NSNumber numberWithInt:trumbleHash], trumbleArray, nil];
10641}
10642
10643- (void)setTrumbleValueFrom:(NSObject*)trumbleValue
10644{
10645 BOOL info_failed = NO;
10646 int trumbleHash;
10647 int putativeHash = 0;
10648 int putativeNTrumbles = 0;
10649 NSArray* putativeTrumbleArray = nil;
10650 int i;
10651 NSString* namekey = [NSString stringWithFormat:@"%@-humbletrash", [self commanderName]];
10652
10653 [self setUpTrumbles];
10654
10655 if (trumbleValue) {
10656 BOOL possible_cheat = NO;
10657 if (![trumbleValue isKindOfClass:[NSArray class]])
10658 info_failed = YES;
10659 else {
10660 NSArray* values = (NSArray*)trumbleValue;
10661 if ([values count] >= 1)
10662 putativeNTrumbles = [values oo_intAtIndex:0];
10663 if ([values count] >= 2)
10664 putativeHash = [values oo_intAtIndex:1];
10665 if ([values count] >= 3)
10666 putativeTrumbleArray = [values oo_arrayAtIndex:2];
10667 }
10668 // calculate a hash for the putative values
10673 trumbleHash = munge_checksum(putativeNTrumbles);
10674
10675 if (putativeHash != trumbleHash)
10676 info_failed = YES;
10677
10678 if (info_failed) {
10679 OOLog(@"cheat.tentative", @"%@", @"POSSIBLE CHEAT DETECTED");
10680 possible_cheat = YES;
10681 }
10682
10683 for (i = 1; (info_failed) && (i < PLAYER_MAX_TRUMBLES); i++) {
10684 // try to determine trumbleCount from the key in the saved game
10689 trumbleHash = munge_checksum(i);
10690 if (putativeHash == trumbleHash) {
10691 info_failed = NO;
10692 putativeNTrumbles = i;
10693 }
10694 }
10695
10696 if (possible_cheat && !info_failed)
10697 OOLog(@"cheat.verified", @"%@", @"CHEAT DEFEATED - that's not the way to get rid of trumbles!");
10698 } else
10699 // if trumbleValue comes in as nil, then probably someone has toyed with the save file
10700 // by removing the entire trumbles array
10701 {
10702 OOLog(@"cheat.tentative", @"%@", @"POSSIBLE CHEAT DETECTED");
10703 info_failed = YES;
10704 }
10705
10706 if (info_failed && [[NSUserDefaults standardUserDefaults] objectForKey:namekey]) {
10707 // try to determine trumbleCount from the key in user defaults
10708 putativeHash = (int)[[NSUserDefaults standardUserDefaults] integerForKey:namekey];
10709 for (i = 1; (info_failed) && (i < PLAYER_MAX_TRUMBLES); i++) {
10714 trumbleHash = munge_checksum(i);
10715 if (putativeHash == trumbleHash) {
10716 info_failed = NO;
10717 putativeNTrumbles = i;
10718 }
10719 }
10720
10721 if (!info_failed)
10722 OOLog(@"cheat.verified", @"%@", @"CHEAT DEFEATED - that's not the way to get rid of trumbles!");
10723 }
10724 // at this stage we've done the best we can to stop cheaters
10725 trumbleCount = putativeNTrumbles;
10726
10727 if ((putativeTrumbleArray != nil) && ([putativeTrumbleArray count] == PLAYER_MAX_TRUMBLES)) {
10728 for (i = 0; i < PLAYER_MAX_TRUMBLES; i++)
10729 [trumble[i] setFromDictionary:[putativeTrumbleArray oo_dictionaryAtIndex:i]];
10730 }
10731
10736 trumbleHash = munge_checksum(trumbleCount);
10737
10738 [[NSUserDefaults standardUserDefaults] setInteger:trumbleHash forKey:namekey];
10739}
10740
10742{
10744}
10745
10746- (void)setTrumbleAppetiteAccumulator:(float)value
10747{
10749}
10750
10751- (void)mungChecksumWithNSString:(NSString*)str
10752{
10753 if (str == nil)
10754 return;
10755
10756 NSUInteger i, length = [str length];
10757 for (i = 0; i < length; i++) {
10758 munge_checksum([str characterAtIndex:i]);
10759 }
10760}
10761
10762- (NSString*)screenModeStringForWidth:(unsigned)width height:(unsigned)height refreshRate:(float)refreshRate
10763{
10764 if (0.0f != refreshRate) {
10765 return OOExpandKey(@"gameoptions-fullscreen-with-refresh-rate", width, height, refreshRate);
10766 } else {
10767 return OOExpandKey(@"gameoptions-fullscreen", width, height);
10768 }
10769}
10770
10772{
10773 suppressTargetLost = YES;
10774}
10775
10777{
10778 scoopsActive = YES;
10779}
10780
10781// override shipentity to stop foundTarget being changed during escape sequence
10782- (void)setFoundTarget:(Entity*)targetEntity
10783{
10784 /* Rare, but can happen, e.g. if a Q-mine goes off nearby during
10785 * the sequence */
10786 if ([self status] == STATUS_ESCAPE_SEQUENCE) {
10787 return;
10788 }
10789 [_foundTarget release];
10791}
10792
10793// override shipentity addTarget to implement target_memory
10794- (void)addTarget:(Entity*)targetEntity
10795{
10796 if ([self status] != STATUS_IN_FLIGHT && [self status] != STATUS_WITCHSPACE_COUNTDOWN)
10797 return;
10798 if (targetEntity == self)
10799 return;
10800
10801 [super addTarget:targetEntity];
10802
10803 if ([targetEntity isWormhole]) {
10804 assert([self hasEquipmentItemProviding:@"EQ_WORMHOLE_SCANNER"]);
10805 [self addScannedWormhole:(WormholeEntity*)targetEntity];
10806 }
10807 // wormholes don't go in target memory
10808 else if ([self hasEquipmentItemProviding:@"EQ_TARGET_MEMORY"] && targetEntity != nil) {
10809 OOWeakReference* targetRef = [targetEntity weakSelf];
10810 NSUInteger i = [target_memory indexOfObject:targetRef];
10811 // if already in target memory, preserve that and just change the index
10812 if (i != NSNotFound) {
10814 } else {
10815 i = [target_memory indexOfObject:[NSNull null]];
10816 // find and use a blank space in memory
10817 if (i != NSNotFound) {
10818 [target_memory replaceObjectAtIndex:i withObject:targetRef];
10820 } else {
10821 // use the next memory space
10823 [target_memory replaceObjectAtIndex:target_memory_index withObject:targetRef];
10824 }
10825 }
10826 }
10827
10828 if (ident_engaged) {
10829 [self playIdentLockedOn];
10831 } else if ([targetEntity isShip] && [self weaponsOnline]) // Only let missiles target-lock onto ships
10832 {
10835 [missile_entity[activeMissile] addTarget:targetEntity];
10836 [self playMissileLockedOn];
10838 } else // It's a mine or something
10839 {
10841 [self playIdentLockedOn];
10843 }
10844 }
10845}
10846
10848{
10849 NSUInteger memoryCount = [target_memory count];
10850 for (NSUInteger i = 0; i < PLAYER_TARGET_MEMORY_SIZE; i++) {
10851 if (i < memoryCount) {
10852 [target_memory replaceObjectAtIndex:i withObject:[NSNull null]];
10853 } else {
10854 [target_memory addObject:[NSNull null]];
10855 }
10856 }
10858}
10859
10860- (NSMutableArray*)targetMemory
10861{
10862 return target_memory;
10863}
10864
10865- (BOOL)moveTargetMemoryBy:(NSInteger)delta
10866{
10867 unsigned i = 0;
10868 while (i++ < PLAYER_TARGET_MEMORY_SIZE) // limit loops
10869 {
10870 NSInteger idx = (NSInteger)target_memory_index + delta;
10871 while (idx < 0)
10873 while (idx >= PLAYER_TARGET_MEMORY_SIZE)
10875 target_memory_index = idx;
10876
10877 id targ_id = [target_memory objectAtIndex:target_memory_index];
10878 if ([targ_id isProxy]) {
10880
10881 if ((potential_target) && (potential_target->isShip) && ([potential_target isInSpace])) {
10882 if (potential_target->zero_distance < SCANNER_MAX_RANGE2 && (![potential_target isCloaked])) {
10883 [super addTarget:potential_target];
10886 [missile_entity[activeMissile] addTarget:potential_target];
10889 } else {
10891 [self playIdentLockedOn];
10893 }
10894 } else {
10895 ident_engaged = YES;
10897 }
10898 [self playTargetSwitched];
10899 return YES;
10900 }
10901 } else {
10902 [target_memory replaceObjectAtIndex:target_memory_index withObject:[NSNull null]];
10903 }
10904 }
10905 }
10906
10907 [self playNoTargetInMemory];
10908 return NO;
10909}
10910
10911- (void)printIdentLockedOnForMissile:(BOOL)missile
10912{
10913 if ([self primaryTarget] == nil)
10914 return;
10915
10916 NSString* fmt = missile ? @"missile-locked-onto-target" : @"ident-locked-onto-target";
10917 NSString* target = [[self primaryTarget] identFromShip:self];
10918 [UNIVERSE addMessage:OOExpandKey(fmt, target) forCount:4.5];
10919}
10920
10925
10926- (void)setCustomViewQuaternion:(Quaternion)q
10927{
10929 [self setCustomViewData];
10930}
10931
10933{
10934 return customViewMatrix;
10935}
10936
10938{
10939 return customViewOffset;
10940}
10941
10942- (void)setCustomViewOffset:(Vector)offset
10943{
10945}
10946
10951
10952- (void)setCustomViewRotationCenter:(Vector)center
10953{
10954 customViewRotationCenter = center;
10955}
10956
10967
10978
10989
11000
11011
11022
11033
11044
11051
11058
11065
11072
11077
11079{
11080 return customViewUpVector;
11081}
11082
11087
11089{
11090 return customViewDescription;
11091}
11092
11094{
11095 [self setCustomViewDataFromDictionary:[_customViews oo_dictionaryAtIndex:_customViewIndex] withScaling:NO];
11096}
11097
11108
11109- (void)setCustomViewDataFromDictionary:(NSDictionary*)viewDict withScaling:(BOOL)withScaling
11110{
11113 if (viewDict == nil)
11114 return;
11115
11116 customViewQuaternion = [viewDict oo_quaternionForKey:@"view_orientation"];
11117 [self setCustomViewData];
11118
11119 // easier to do the multiplication at this point than at load time
11120 if (withScaling) {
11121 customViewOffset = vector_multiply_scalar([viewDict oo_vectorForKey:@"view_position"], _scaleFactor);
11122 } else {
11123 // but don't do this when the custom view is set through JS
11124 customViewOffset = [viewDict oo_vectorForKey:@"view_position"];
11125 }
11127 customViewDescription = [viewDict oo_stringForKey:@"view_description"];
11128
11129 NSString* facing = [[viewDict oo_stringForKey:@"weapon_facing"] lowercaseString];
11130 if ([facing isEqual:@"aft"]) {
11132 } else if ([facing isEqual:@"port"]) {
11134 } else if ([facing isEqual:@"starboard"]) {
11136 } else if ([facing isEqual:@"forward"]) {
11138 }
11139 // if the weapon facing is unset / unknown,
11140 // don't change current weapon facing!
11141}
11142
11144{
11145 return show_info_flag;
11146}
11147
11149{
11151}
11152
11154{
11155 NSDictionary* result = [self missionOverlayDescriptor];
11156 if (result == nil) {
11157 if ([[self missionTitle] length] == 0) {
11158 result = [UNIVERSE screenTextureDescriptorForKey:@"mission_overlay_no_title"];
11159 } else {
11160 result = [UNIVERSE screenTextureDescriptorForKey:@"mission_overlay_with_title"];
11161 }
11162 }
11163
11164 return result;
11165}
11166
11167- (void)setMissionOverlayDescriptor:(NSDictionary*)descriptor
11168{
11169 if (descriptor != _missionOverlayDescriptor) {
11170 [_missionOverlayDescriptor autorelease];
11172 }
11173}
11174
11176{
11178}
11179
11181{
11182 NSDictionary* result = [self missionBackgroundDescriptor];
11183 if (result == nil) {
11184 result = [UNIVERSE screenTextureDescriptorForKey:@"mission"];
11185 }
11186
11187 return result;
11188}
11189
11190- (void)setMissionBackgroundDescriptor:(NSDictionary*)descriptor
11191{
11192 if (descriptor != _missionBackgroundDescriptor) {
11193 [_missionBackgroundDescriptor autorelease];
11195 }
11196}
11197
11202
11203- (void)setMissionBackgroundSpecial:(NSString*)special
11204{
11205 if (special == nil) {
11207 } else if ([special isEqualToString:@"SHORT_RANGE_CHART"]) {
11209 } else if ([special isEqualToString:@"SHORT_RANGE_CHART_SHORTEST"]) {
11210 if ([self hasEquipmentItemProviding:@"EQ_ADVANCED_NAVIGATIONAL_ARRAY"]) {
11212 } else {
11214 }
11215 } else if ([special isEqualToString:@"SHORT_RANGE_CHART_QUICKEST"]) {
11216 if ([self hasEquipmentItemProviding:@"EQ_ADVANCED_NAVIGATIONAL_ARRAY"]) {
11218 } else {
11220 }
11221 } else if ([special isEqualToString:@"CUSTOM_CHART"]) {
11223 } else if ([special isEqualToString:@"CUSTOM_CHART_SHORTEST"]) {
11224 if ([self hasEquipmentItemProviding:@"EQ_ADVANCED_NAVIGATIONAL_ARRAY"]) {
11226 } else {
11228 }
11229 } else if ([special isEqualToString:@"CUSTOM_CHART_QUICKEST"]) {
11230 if ([self hasEquipmentItemProviding:@"EQ_ADVANCED_NAVIGATIONAL_ARRAY"]) {
11232 } else {
11234 }
11235 } else if ([special isEqualToString:@"LONG_RANGE_CHART"]) {
11237 } else if ([special isEqualToString:@"LONG_RANGE_CHART_SHORTEST"]) {
11238 if ([self hasEquipmentItemProviding:@"EQ_ADVANCED_NAVIGATIONAL_ARRAY"]) {
11240 } else {
11242 }
11243 } else if ([special isEqualToString:@"LONG_RANGE_CHART_QUICKEST"]) {
11244 if ([self hasEquipmentItemProviding:@"EQ_ADVANCED_NAVIGATIONAL_ARRAY"]) {
11246 } else {
11248 }
11249 } else {
11251 }
11252}
11253
11254- (void)setMissionExitScreen:(OOGUIScreenID)screen
11255{
11256 _missionExitScreen = screen;
11257}
11258
11263
11265{
11267}
11268
11269- (void)setEquipScreenBackgroundDescriptor:(NSDictionary*)descriptor
11270{
11271 if (descriptor != _equipScreenBackgroundDescriptor) {
11272 [_equipScreenBackgroundDescriptor autorelease];
11274 }
11275}
11276
11278{
11279 return worldScripts != nil && [worldScripts count] > 0;
11280}
11281
11283{
11284 return [worldScripts allKeys];
11285}
11286
11287- (NSDictionary*)worldScriptsByName
11288{
11289 return [[worldScripts copy] autorelease];
11290}
11291
11292- (OOScript*)commodityScriptNamed:(NSString*)scriptName
11293{
11294 if (scriptName == nil) {
11295 return nil;
11296 }
11297 OOScript* cscript = nil;
11298 if ((cscript = [commodityScripts objectForKey:scriptName])) {
11299 return cscript;
11300 }
11301 cscript = [OOScript jsScriptFromFileNamed:scriptName properties:nil];
11302 if (cscript != nil) {
11303 // storing it in here retains it
11304 [commodityScripts setObject:cscript forKey:scriptName];
11305 } else {
11306 OOLog(@"script.commodityScript.load", @"Could not load script %@", scriptName);
11307 }
11308 return cscript;
11309}
11310
11311- (void)doScriptEvent:(OOJSPropID)message inContext:(JSContext*)context withArguments:(OOJSVal*)argv count:(int)argc
11312{
11313 [super doScriptEvent:message inContext:context withArguments:argv count:argc];
11314 [self doWorldScriptEvent:message inContext:context withArguments:argv count:argc timeLimit:0.0];
11315}
11316
11317- (BOOL)doWorldEventUntilMissionScreen:(OOJSPropID)message
11318{
11319 NSEnumerator* scriptEnum = [worldScripts objectEnumerator];
11320 OOScript* theScript;
11321
11322 // Check for the presence of report messages first.
11323 if (gui_screen != GUI_SCREEN_MISSION && [dockingReport length] > 0 && [self isDocked] && ![[self dockedStation] suppressArrivalReports]) {
11324 [self setGuiToDockingReportScreen]; // go here instead!
11325 [[UNIVERSE messageGUI] clear];
11326 return YES;
11327 }
11328
11329 JSContext* context = OOJSAcquireContext();
11330 while ((theScript = [scriptEnum nextObject]) && gui_screen != GUI_SCREEN_MISSION && [self isDocked]) {
11331 [theScript callMethod:message inContext:context withArguments:NULL count:0 result:NULL];
11332 }
11333 OOJSRelinquishContext(context);
11334
11335 if (gui_screen == GUI_SCREEN_MISSION) {
11336 // remove any comms/console messages from the screen!
11337 [[UNIVERSE messageGUI] clear];
11338 return YES;
11339 }
11340
11341 return NO;
11342}
11343
11344- (void)doWorldScriptEvent:(OOJSPropID)message inContext:(JSContext*)context withArguments:(OOJSVal*)argv count:(int)argc timeLimit:(OOTimeDelta)limit
11345{
11346#if OOJS_QUICKJS
11347 NSParameterAssert(context != NULL);
11348#else
11349 NSParameterAssert(context != NULL && JS_IsInRequest(context));
11350#endif
11351
11352 OOScript* theScript = nil;
11353
11354 foreach (theScript, [worldScripts allValues]) {
11356 [theScript callMethod:message inContext:context withArguments:argv count:argc result:NULL];
11358 }
11359}
11360
11361- (void)setGalacticHyperspaceBehaviour:(OOGalacticHyperspaceBehaviour)inBehaviour
11362{
11363 if (GALACTIC_HYPERSPACE_BEHAVIOUR_UNKNOWN < inBehaviour && inBehaviour <= GALACTIC_HYPERSPACE_MAX) {
11364 galacticHyperspaceBehaviour = inBehaviour;
11365 }
11366}
11367
11372
11373- (void)setGalacticHyperspaceFixedCoords:(NSPoint)point
11374{
11375 return [self setGalacticHyperspaceFixedCoordsX:OOClamp_0_max_f(round(point.x), 255.0f) y:OOClamp_0_max_f(round(point.y), 255.0f)];
11376}
11377
11378- (void)setGalacticHyperspaceFixedCoordsX:(unsigned char)x y:(unsigned char)y
11379{
11382}
11383
11385{
11387}
11388
11389- (void)setWitchspaceCountdown:(int)spin_time
11390{
11391 witchspaceCountdown = spin_time;
11392}
11393
11398
11399- (void)setLongRangeChartMode:(OOLongRangeChartMode)mode
11400{
11402}
11403
11405{
11406 return scoopOverride;
11407}
11408
11409- (void)setScoopOverride:(BOOL)newValue
11410{
11411 scoopOverride = !!newValue;
11412 if (scoopOverride)
11413 [self setScoopsActive];
11414}
11415
11416#if MASS_DEPENDENT_FUEL_PRICES
11418{
11419 GLfloat rate = 1.0; // Standard charge rate.
11420
11421 rate = [super fuelChargeRate];
11422
11423 // Experimental: the state of repair affects the fuel charge rate - more fuel needed for jumps, etc...
11424 if (EXPECT(ship_trade_in_factor <= 90 && ship_trade_in_factor >= 75)) {
11425 rate *= 2.0 - (ship_trade_in_factor / 100); // between 1.1x and 1.25x
11426 // OOLog(@"fuelPrices", @"\"%@\" - repair status: %d%%, adjusted rate to:%.2f)", [self shipDataKey], ship_trade_in_factor, rate);
11427 }
11428
11429 return rate;
11430}
11431#endif
11432
11433- (void)setDockTarget:(ShipEntity*)entity
11434{
11435 if ([entity isStation])
11437 else
11439 //_dockTarget = [entity isStation] ? [entity universalID]: NO_TARGET;
11440}
11441
11442- (NSString*)jumpCause
11443{
11444 return _jumpCause;
11445}
11446
11447- (void)setJumpCause:(NSString*)value
11448{
11449 NSParameterAssert(value != nil);
11450 [_jumpCause autorelease];
11451 _jumpCause = [value copy];
11452}
11453
11454- (NSString*)commanderName
11455{
11456 return _commanderName;
11457}
11458
11459- (NSString*)lastsaveName
11460{
11461 return _lastsaveName;
11462}
11463
11464- (void)setCommanderName:(NSString*)value
11465{
11466 NSParameterAssert(value != nil);
11467 [_commanderName autorelease];
11468 _commanderName = [value copy];
11469}
11470
11471- (void)setLastsaveName:(NSString*)value
11472{
11473 NSParameterAssert(value != nil);
11474 [_lastsaveName autorelease];
11475 _lastsaveName = [value copy];
11476 [[NSUserDefaults standardUserDefaults] setObject:_lastsaveName forKey:@"last_savename"];
11477}
11478
11480{
11481 BOOL isDockedStatus = NO;
11482
11483 switch ([self status]) {
11484 case STATUS_DOCKED:
11485 case STATUS_DOCKING:
11486 case STATUS_START_GAME:
11487 isDockedStatus = YES;
11488 break;
11489 // special case - can be either docked or not, so avoid safety check below
11490 case STATUS_RESTART_GAME:
11491 return NO;
11492 case STATUS_EFFECT:
11493 case STATUS_ACTIVE:
11494 case STATUS_COCKPIT_DISPLAY:
11495 case STATUS_TEST:
11496 case STATUS_INACTIVE:
11497 case STATUS_DEAD:
11498 case STATUS_IN_FLIGHT:
11499 case STATUS_AUTOPILOT_ENGAGED:
11500 case STATUS_LAUNCHING:
11501 case STATUS_WITCHSPACE_COUNTDOWN:
11502 case STATUS_ENTERING_WITCHSPACE:
11503 case STATUS_EXITING_WITCHSPACE:
11504 case STATUS_ESCAPE_SEQUENCE:
11505 case STATUS_IN_HOLD:
11506 case STATUS_BEING_SCOOPED:
11507 case STATUS_HANDLING_ERROR:
11508 break;
11509 // no default, so that we get notified by the compiler if something is missing
11510 }
11511
11512#ifndef NDEBUG
11513 // Sanity check
11514 if (isDockedStatus) {
11515 if ([self dockedStation] == nil) {
11516 // there are a number of possible current statuses, not just STATUS_DOCKED
11517 OOLogERR(kOOLogInconsistentState, @"status is %@, but dockedStation is nil; treating as not docked. %@", OOStringFromEntityStatus([self status]), @"This is an internal error, please report it.");
11518 [self setStatus:STATUS_IN_FLIGHT];
11519 isDockedStatus = NO;
11520 }
11521 } else {
11522 if ([self dockedStation] != nil && [self status] != STATUS_LAUNCHING) {
11523 OOLogERR(kOOLogInconsistentState, @"status is %@, but dockedStation is not nil; treating as docked. %@", OOStringFromEntityStatus([self status]), @"This is an internal error, please report it.");
11524 [self setStatus:STATUS_DOCKED];
11525 isDockedStatus = YES;
11526 }
11527 }
11528#endif
11529
11530 return isDockedStatus;
11531}
11532
11537
11538- (void)setDockingClearanceStatus:(OODockingClearanceStatus)newValue
11539{
11540 dockingClearanceStatus = newValue;
11544 if ([[self primaryTarget] isStation]) {
11546 } else {
11547 OOLog(@"player.badDockingTarget", @"Attempt to dock at %@.", [self primaryTarget]);
11550 }
11551 }
11552}
11553
11558
11560{
11561 OOCreditsQuantity amountToPay = 0;
11562 OOCreditsQuantity calculatedFine = credits * 0.05;
11563 OOCreditsQuantity maximumFine = 50000ULL;
11564
11565 if ([self clearedToDock])
11566 return;
11567
11568 amountToPay = MIN(maximumFine, calculatedFine);
11569 credits -= amountToPay;
11570 [self addMessageToReport:[NSString stringWithFormat:DESC(@"station-docking-clearance-fined-@-cr"), OOCredits(amountToPay)]];
11571}
11572
11573//
11574// Wormhole Scanner support functions
11575//
11576- (void)addScannedWormhole:(WormholeEntity*)whole
11577{
11578 assert(scannedWormholes != nil);
11579 assert(whole != nil);
11580
11581 // Only add if we don't have it already!
11582 WormholeEntity* wh = nil;
11583 foreach (wh, scannedWormholes) {
11584 if (wh == whole)
11585 return;
11586 }
11588 [scannedWormholes addObject:whole];
11589}
11590
11591// Checks through our array of wormholes for any which have expired
11592// If it is in the current system, spawn ships
11593// Else remove it
11595{
11596 assert(scannedWormholes != nil);
11597
11598 if ([scannedWormholes count] == 0)
11599 return;
11600
11601 double now = [self clockTimeAdjusted];
11602
11603 NSMutableArray* savedWormholes = [[NSMutableArray alloc] initWithCapacity:[scannedWormholes count]];
11604 WormholeEntity* wh;
11605
11606 foreach (wh, scannedWormholes) {
11607 // TODO: Start drawing wormhole exit a few seconds before the first
11608 // ship is disgorged.
11609 if ([wh arrivalTime] > now) {
11610 [savedWormholes addObject:wh];
11611 } else if (NSEqualPoints(galaxy_coordinates, [wh destinationCoordinates])) {
11612 [wh disgorgeShips];
11613 if ([[wh shipsInTransit] count] > 0) {
11614 [savedWormholes addObject:wh];
11615 }
11616 }
11617 // Else wormhole has expired in another system, let it expire
11618 }
11619
11620 [scannedWormholes release];
11621 scannedWormholes = savedWormholes;
11622}
11623
11625{
11626 return [NSArray arrayWithArray:scannedWormholes];
11627}
11628
11629- (void)initialiseMissionDestinations:(NSDictionary*)destinations andLegacy:(NSArray*)legacy
11630{
11631 NSString* key = nil;
11632 id value = nil;
11633
11634 /* same need to make inner objects mutable as in localPlanetInfoOverrides */
11635
11636 [missionDestinations release];
11638
11639 foreachkey(key, destinations)
11640 {
11641 value = [destinations objectForKey:key];
11642 if (value != nil) {
11643 if ([value isKindOfClass:[NSDictionary class]]) {
11644 value = [value mutableCopy];
11645 [missionDestinations setObject:value forKey:key];
11646 [value release];
11647 }
11648 }
11649 }
11650
11651 if (legacy != nil) {
11652 OOSystemID dest;
11653 NSNumber* legacyMarker;
11654 foreach (legacyMarker, legacy) {
11655 dest = [legacyMarker intValue];
11656 [self addMissionDestinationMarker:[self defaultMarker:dest]];
11657 }
11658 }
11659}
11660
11661- (NSString*)markerKey:(NSDictionary*)marker
11662{
11663 return [NSString stringWithFormat:@"%d-%@", [marker oo_intForKey:@"system"], [marker oo_stringForKey:@"name"]];
11664}
11665
11666- (void)addMissionDestinationMarker:(NSDictionary*)marker
11667{
11668 NSDictionary* validated = [self validatedMarker:marker];
11669 if (validated == nil) {
11670 return;
11671 }
11672
11673 [missionDestinations setObject:validated forKey:[self markerKey:validated]];
11674}
11675
11676- (BOOL)removeMissionDestinationMarker:(NSDictionary*)marker
11677{
11678 NSDictionary* validated = [self validatedMarker:marker];
11679 if (validated == nil) {
11680 return NO;
11681 }
11682 BOOL result = NO;
11683 if ([missionDestinations objectForKey:[self markerKey:validated]] != nil) {
11684 result = YES;
11685 }
11686 [missionDestinations removeObjectForKey:[self markerKey:validated]];
11687 return result;
11688}
11689
11690- (NSMutableDictionary*)getMissionDestinations
11691{
11692 return missionDestinations;
11693}
11694
11695- (NSMutableDictionary*)shipyardRecord
11696{
11697 return shipyard_record;
11698}
11699
11700- (void)setLastShot:(NSArray*)shot
11701{
11702 lastShot = [shot retain];
11703}
11704
11706{
11707 [extraMissionKeys release];
11709}
11710
11711- (void)setExtraMissionKeys:(NSDictionary*)keys
11712{
11713 NSString* key = nil;
11714 NSMutableDictionary* final = [[NSMutableDictionary alloc] init];
11715 foreach (key, [keys allKeys]) {
11716 [final setObject:[self processKeyCode:[keys oo_arrayForKey:key]] forKey:key];
11717 }
11718 extraMissionKeys = [final copy];
11719 [final release];
11720}
11721
11722- (void)clearExtraGuiScreenKeys:(OOGUIScreenID)gui key:(NSString*)key
11723{
11724 NSMutableArray* keydefs = [extraGuiScreenKeys objectForKey:[NSString stringWithFormat:@"%d", gui]];
11725 NSInteger i = [keydefs count];
11726 NSDictionary* def = nil;
11727 while (i--) {
11728 def = [keydefs objectAtIndex:i];
11729 if (def && [[def oo_stringForKey:@"name"] isEqualToString:key]) {
11730 [keydefs removeObjectAtIndex:i];
11731 break;
11732 }
11733 }
11734 // do we have to put the array back, or does the reference update the source?
11735}
11736
11737- (BOOL)setExtraGuiScreenKeys:(OOGUIScreenID)gui definition:(OOJSGuiScreenKeyDefinition*)definition
11738{
11739 // process all the keys in the definition
11740 BOOL result = YES;
11741 NSMutableArray* newarray = nil;
11742 NSString* key = nil;
11743 NSMutableDictionary* final = [[NSMutableDictionary alloc] init];
11744 NSDictionary* keys = [definition registerKeys];
11745 NSMutableArray* checklist = [[NSMutableArray alloc] init];
11746
11747 foreach (key, [keys allKeys]) {
11748 NSArray* item = [self processKeyCode:[keys oo_arrayForKey:key]];
11749 [checklist addObject:item];
11750 [final setObject:item forKey:key];
11751 }
11752 [definition setRegisterKeys:[final copy]];
11753 [final release];
11754
11756 if (!extraGuiScreenKeys) {
11757 extraGuiScreenKeys = [[NSMutableDictionary alloc] init];
11758 }
11759
11760 if (![extraGuiScreenKeys objectForKey:[NSString stringWithFormat:@"%d", gui]]) {
11761 // brand new - just add
11762 newarray = [[NSMutableArray alloc] init];
11763 } else {
11764 newarray = [[extraGuiScreenKeys objectForKey:[NSString stringWithFormat:@"%d", gui]] mutableCopy];
11765 NSInteger i = [newarray count];
11766 NSInteger j = 0;
11767 OOJSGuiScreenKeyDefinition* def_existing = nil;
11768 while (i--) {
11769 def_existing = [newarray objectAtIndex:i];
11770 // if we find this name already in the array, remove it
11771 if (def_existing && [[def_existing name] isEqualToString:[definition name]]) {
11772 [newarray removeObjectAtIndex:i];
11773 } else {
11774 // check whether any of those keycodes is already in use on this screen
11775 NSDictionary* keydefs = [def_existing registerKeys];
11776
11777 foreach (key, [keydefs allKeys]) {
11778 j = [checklist count];
11779 while (j--) {
11780 if ([[NSString stringWithFormat:@"%@", [keydefs objectForKey:key]] isEqualToString:[NSString stringWithFormat:@"%@", [checklist objectAtIndex:j]]]) {
11781 result = NO;
11782 OOLog(kOOLogException, @"***** Exception in setExtraGuiScreenKeys: %@ : %@ (%@)", @"invalid key settings", @"key already in use", key);
11783 }
11784 }
11785 }
11786 }
11787 }
11788 }
11789 [newarray addObject:definition];
11790 // only add the item if there were no errors
11791 if (result)
11792 [extraGuiScreenKeys setObject:[newarray mutableCopy] forKey:[NSString stringWithFormat:@"%d", gui]];
11793 [newarray release];
11794 return result;
11795}
11796
11797#ifdef OO_DEBUG_MONITOR_ENABLED
11798- (void)dumpSelfState
11799{
11800 NSMutableArray* flags = nil;
11801 NSString* flagsString = nil;
11802
11803 [super dumpSelfState];
11804
11805 OOLog(@"dumpState.playerEntity", @"Script time: %g", script_time);
11806 OOLog(@"dumpState.playerEntity", @"Script time check: %g", script_time_check);
11807 OOLog(@"dumpState.playerEntity", @"Script time interval: %g", script_time_interval);
11808 OOLog(@"dumpState.playerEntity", @"Roll/pitch/yaw delta: %g, %g, %g", roll_delta, pitch_delta, yaw_delta);
11809 OOLog(@"dumpState.playerEntity", @"Shield: %g fore, %g aft", forward_shield, aft_shield);
11810 OOLog(@"dumpState.playerEntity", @"Alert level: %u, flags: %#x", alertFlags, alertCondition);
11811 OOLog(@"dumpState.playerEntity", @"Missile status: %i", missile_status);
11812 OOLog(@"dumpState.playerEntity", @"Energy unit: %@", EnergyUnitTypeToString([self installedEnergyUnitType]));
11813 OOLog(@"dumpState.playerEntity", @"Fuel leak rate: %g", fuel_leak_rate);
11814 OOLog(@"dumpState.playerEntity", @"Trumble count: %zu", trumbleCount);
11815
11816 flags = [NSMutableArray array];
11817#define ADD_FLAG_IF_SET(x) \
11818 if (x) { \
11819 [flags addObject:@ #x]; \
11820 }
11821 ADD_FLAG_IF_SET(found_equipment);
11822 ADD_FLAG_IF_SET(pollControls);
11823 ADD_FLAG_IF_SET(suppressTargetLost);
11824 ADD_FLAG_IF_SET(scoopsActive);
11825 ADD_FLAG_IF_SET(game_over);
11826 ADD_FLAG_IF_SET(finished);
11827 ADD_FLAG_IF_SET(bomb_detonated);
11828 ADD_FLAG_IF_SET(autopilot_engaged);
11829 ADD_FLAG_IF_SET(afterburner_engaged);
11830 ADD_FLAG_IF_SET(afterburnerSoundLooping);
11831 ADD_FLAG_IF_SET(hyperspeed_engaged);
11832 ADD_FLAG_IF_SET(travelling_at_hyperspeed);
11833 ADD_FLAG_IF_SET(hyperspeed_locked);
11834 ADD_FLAG_IF_SET(ident_engaged);
11835 ADD_FLAG_IF_SET(galactic_witchjump);
11836 ADD_FLAG_IF_SET(ecm_in_operation);
11837 ADD_FLAG_IF_SET(show_info_flag);
11838 ADD_FLAG_IF_SET(showDemoShips);
11839 ADD_FLAG_IF_SET(rolling);
11840 ADD_FLAG_IF_SET(pitching);
11841 ADD_FLAG_IF_SET(yawing);
11842 ADD_FLAG_IF_SET(using_mining_laser);
11843 ADD_FLAG_IF_SET(mouse_control_on);
11844 // ADD_FLAG_IF_SET(isSpeechOn);
11845 ADD_FLAG_IF_SET(keyboardRollOverride); // Handle keyboard roll...
11846 ADD_FLAG_IF_SET(keyboardPitchOverride); // ...and pitch override separately - (fix for BUG #17490)
11847 ADD_FLAG_IF_SET(keyboardYawOverride);
11848 ADD_FLAG_IF_SET(waitingForStickCallback);
11849 flagsString = [flags count] ? [flags componentsJoinedByString:@", "] : (NSString*)@"none";
11850 OOLog(@"dumpState.playerEntity", @"Flags: %@", flagsString);
11851}
11852
11853/* This method exists purely to suppress Clang static analyzer warnings that
11854 these ivars are unused (but may be used by categories, which they are).
11855 FIXME: there must be a feature macro we can use to avoid actually building
11856 this into the app, but I can't find it in docs.
11857
11858 Mind you, we could suppress some of this by using civilized accessors.
11859*/
11860- (BOOL)suppressClangStuff
11861{
11862 return missionChoice && commanderNameString && cdrDetailArray && currentPage && n_key_roll_left && n_key_roll_right && n_key_pitch_forward && n_key_pitch_back && n_key_yaw_left && n_key_yaw_right && n_key_view_forward && n_key_view_aft && n_key_view_port && n_key_view_starboard && n_key_launch_ship && n_key_gui_screen_options && n_key_gui_screen_equipship && n_key_gui_screen_interfaces && n_key_gui_screen_status && n_key_gui_chart_screens && n_key_gui_system_data && n_key_gui_market && n_key_gui_arrow_left && n_key_gui_arrow_right && n_key_gui_arrow_up && n_key_gui_arrow_down && n_key_gui_page_up && n_key_gui_page_down && n_key_gui_select && n_key_increase_speed && n_key_decrease_speed && n_key_inject_fuel && n_key_fire_lasers && n_key_launch_missile && n_key_next_missile && n_key_ecm && n_key_prime_next_equipment && n_key_prime_previous_equipment && n_key_activate_equipment && n_key_mode_equipment && n_key_fastactivate_equipment_a && n_key_fastactivate_equipment_b && n_key_target_missile && n_key_untarget_missile && n_key_target_incoming_missile && n_key_ident_system && n_key_scanner_zoom && n_key_scanner_unzoom && n_key_launch_escapepod && n_key_galactic_hyperspace && n_key_hyperspace && n_key_jumpdrive && n_key_dump_cargo && n_key_rotate_cargo && n_key_autopilot && n_key_autodock && n_key_snapshot && n_key_docking_music && n_key_advanced_nav_array_next && n_key_advanced_nav_array_previous && n_key_info_next_system && n_key_info_previous_system && n_key_map_home && n_key_map_end && n_key_map_next_system && n_key_map_previous_system && n_key_map_info && n_key_map_zoom_in && n_key_map_zoom_out && n_key_system_home && n_key_system_end && n_key_system_next_system && n_key_system_previous_system && n_key_pausebutton && n_key_show_fps && n_key_bloom_toggle && n_key_mouse_control_roll && n_key_mouse_control_yaw && n_key_hud_toggle && n_key_comms_log && n_key_prev_compass_mode && n_key_next_compass_mode && n_key_chart_highlight && n_key_market_filter_cycle && n_key_market_sorter_cycle && n_key_market_buy_one && n_key_market_sell_one && n_key_market_buy_max && n_key_market_sell_max && n_key_next_target && n_key_previous_target && n_key_custom_view && n_key_custom_view_zoom_out && n_key_custom_view_zoom_in && n_key_custom_view_roll_left && n_key_custom_view_pan_left && n_key_custom_view_roll_right && n_key_custom_view_pan_right && n_key_custom_view_rotate_up && n_key_custom_view_pan_up && n_key_custom_view_rotate_down && n_key_custom_view_pan_down && n_key_custom_view_rotate_left && n_key_custom_view_rotate_right && n_key_docking_clearance_request && n_key_weapons_online_toggle && n_key_cycle_next_mfd && n_key_cycle_previous_mfd && n_key_switch_next_mfd && n_key_switch_previous_mfd && n_key_oxzmanager_setfilter && n_key_oxzmanager_showinfo && n_key_oxzmanager_copyurl && n_key_oxzmanager_extract &&
11863#if OO_FOV_INFLIGHT_CONTROL_ENABLED
11864 n_key_inc_field_of_view && n_key_dec_field_of_view &&
11865#endif
11866 n_key_dump_target_state && n_key_dump_entity_list && n_key_debug_full && n_key_debug_collision && n_key_debug_console_connect && n_key_debug_bounding_boxes && n_key_debug_shaders && n_key_debug_off && _sysInfoLight.x && selFunctionIdx && stickFunctions && keyFunctions && customEquipActivation && customActivatePressed && customModePressed && kbdLayouts && showingLongRangeChart && _missionAllowInterrupt && _missionScreenID && _missionTitle && _missionTextEntry;
11867}
11868#endif
11869
11870@end
11871
11872NSComparisonResult marketSorterByName(id a, id b, void* context)
11873{
11874 OOCommodityMarket* market = (OOCommodityMarket*)context;
11875 return [[market nameForGood:(OOCommodityType)a] compare:[market nameForGood:(OOCommodityType)b]];
11876}
11877
11878NSComparisonResult marketSorterByPrice(id a, id b, void* context)
11879{
11880 OOCommodityMarket* market = (OOCommodityMarket*)context;
11881 int result = (int)[market priceForGood:(OOCommodityType)a] - (int)[market priceForGood:(OOCommodityType)b];
11882 if (result < 0) {
11883 return NSOrderedAscending;
11884 } else if (result > 0) {
11885 return NSOrderedDescending;
11886 } else {
11887 return NSOrderedSame;
11888 }
11889}
11890
11891NSComparisonResult marketSorterByQuantity(id a, id b, void* context)
11892{
11893 OOCommodityMarket* market = (OOCommodityMarket*)context;
11894 int result = (int)[market quantityForGood:(OOCommodityType)a] - (int)[market quantityForGood:(OOCommodityType)b];
11895 if (result < 0) {
11896 return NSOrderedAscending;
11897 } else if (result > 0) {
11898 return NSOrderedDescending;
11899 } else {
11900 return NSOrderedSame;
11901 }
11902}
11903
11904NSComparisonResult marketSorterByMassUnit(id a, id b, void* context)
11905{
11906 OOCommodityMarket* market = (OOCommodityMarket*)context;
11907 int result = (int)[market massUnitForGood:(OOCommodityType)a] - (int)[market massUnitForGood:(OOCommodityType)b];
11908 if (result < 0) {
11909 return NSOrderedAscending;
11910 } else if (result > 0) {
11911 return NSOrderedDescending;
11912 } else {
11913 return NSOrderedSame;
11914 }
11915}
BOOL shadowAtPointOcclusionToValue(HPVector e1pos, GLfloat e1rad, Entity *e2, OOSunEntity *the_sun, float *outValue)
OOEntityStatus
Definition Entity.h:60
OOScanClass
Definition Entity.h:69
NSString * OOStringFromEntityStatus(OOEntityStatus status) CONST_FUNC
#define SCANNER_MAX_RANGE
Definition Entity.h:53
#define SCANNER_MAX_RANGE2
Definition Entity.h:54
#define ADD_FLAG_IF_SET(x)
#define MINIMUM_GAME_TICK
#define GUI_MAX_ROWS
OOGUIBackgroundSpecial
@ GUI_BACKGROUND_SPECIAL_CUSTOM_ANA_QUICKEST
@ GUI_BACKGROUND_SPECIAL_SHORT_ANA_SHORTEST
@ GUI_BACKGROUND_SPECIAL_LONG
@ GUI_BACKGROUND_SPECIAL_LONG_ANA_SHORTEST
@ GUI_BACKGROUND_SPECIAL_SHORT
@ GUI_BACKGROUND_SPECIAL_NONE
@ GUI_BACKGROUND_SPECIAL_SHORT_ANA_QUICKEST
@ GUI_BACKGROUND_SPECIAL_LONG_ANA_QUICKEST
@ GUI_BACKGROUND_SPECIAL_CUSTOM
@ GUI_BACKGROUND_SPECIAL_CUSTOM_ANA_SHORTEST
OOGUITabStop OOGUITabSettings[GUI_MAX_COLUMNS]
NSInteger OOGUIRow
#define MAX_FOV
#define MIN_HDR_PAPERWHITE
#define MIN_FOV_DEG
#define MAX_FOV_DEG
#define MAX_HDR_PAPERWHITE
OOINLINE void bounding_box_add_vector(BoundingBox *box, Vector vec) ALWAYS_INLINE_FUNC NONNULL_FUNC
OOINLINE jsval OOJSValueFromLegalStatusReason(JSContext *context, OOLegalStatusReason value)
OOINLINE jsval OOJSValueFromCompassMode(JSContext *context, OOCompassMode value)
OOINLINE jsval OOJSValueFromGUIScreenID(JSContext *context, OOGUIScreenID value)
NSString * EnergyUnitTypeToString(OOEnergyUnitType unit) CONST_FUNC
NSString * DisplayStringForMassUnit(OOMassUnit unit)
NSString * OOStringFromLegalStatusReason(OOLegalStatusReason reason)
OOINLINE float OOClamp_0_max_f(float value, float max) INLINE_CONST_FUNC
OOINLINE float OOClamp_0_1_f(float value) INLINE_CONST_FUNC
#define DESTROY(x)
#define foreachkey(VAR, DICT)
#define EXPECT_NOT(x)
#define EXPECT(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 Vector HPVectorToVector(HPVector v) INLINE_CONST_FUNC
Definition OOHPVector.h:175
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
#define HPvector_between(a, b)
Definition OOHPVector.h:83
OOINLINE OOHPScalar HPmagnitude2(HPVector vec) INLINE_CONST_FUNC
Definition OOHPVector.h:255
#define OOJSStopTimeLimiter()
#define kOOJSLongTimeLimit
#define OOJSStartTimeLimiterWithTimeLimit(limit)
jsid OOJSPropID
Definition OOJSPropID.h:31
OOINLINE jsval OOJSValueFromDouble(JSContext *context, double value)
jsval OOJSVal
#define OOJSFreeValue(context, value)
#define JS_IsInRequest(context)
#define OOJSUndefinedValue()
OOINLINE jsval OOJSValueFromNativeObject(JSContext *context, id object)
OOINLINE BOOL OOJSValueToInt32(JSContext *context, jsval value, int32_t *outValue)
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
NSString *const kOOLogException
Definition OOLogging.m:600
NSString *const kOOLogInconsistentState
Definition OOLogging.m:599
#define OOLog(class, format,...)
Definition OOLogging.h:84
#define M_SQRT1_2
Definition OOMaths.h:75
#define MAX(A, B)
Definition OOMaths.h:94
#define MIN(A, B)
Definition OOMaths.h:91
GLfloat OOScalar
Definition OOMaths.h:49
OOINLINE void OOMatrixGetBasisVectors(OOMatrix m, Vector *outRight, Vector *outUp, Vector *outForward) NONNULL_FUNC ALWAYS_INLINE_FUNC
Definition OOMatrix.h:318
const OOMatrix kIdentityMatrix
Definition OOMatrix.m:28
OOINLINE OOMatrix OOMatrixTranslate(OOMatrix m, Vector offset) INLINE_CONST_FUNC
Definition OOMatrix.h:254
OOMatrix OOMatrixForQuaternionRotation(Quaternion orientation)
Definition OOMatrix.m:56
unsigned count
return nil
OOINLINE bool quaternion_equal(Quaternion a, Quaternion b) INLINE_CONST_FUNC
void quaternion_rotate_about_x(Quaternion *quat, OOScalar angle) NONNULL_FUNC
Vector vector_forward_from_quaternion(Quaternion quat) CONST_FUNC
Vector quaternion_rotate_vector(Quaternion q, Vector vector) CONST_FUNC
OOINLINE Quaternion make_quaternion(OOScalar qw, OOScalar qx, OOScalar qy, OOScalar qz) INLINE_CONST_FUNC
OOINLINE Quaternion quaternion_conjugate(Quaternion q) INLINE_CONST_FUNC
void quaternion_rotate_about_axis(Quaternion *quat, Vector axis, OOScalar angle) NONNULL_FUNC
const Quaternion kIdentityQuaternion
void quaternion_rotate_about_z(Quaternion *quat, OOScalar angle) NONNULL_FUNC
OOINLINE void quaternion_normalize(Quaternion *quat) NONNULL_FUNC ALWAYS_INLINE_FUNC
Vector vector_up_from_quaternion(Quaternion quat) CONST_FUNC
void quaternion_rotate_about_y(Quaternion *quat, OOScalar angle) NONNULL_FUNC
const Quaternion kZeroQuaternion
HPVector HPvector_forward_from_quaternion(Quaternion quat) CONST_FUNC
void quaternion_set_random(Quaternion *quat) NONNULL_FUNC
Vector vector_right_from_quaternion(Quaternion quat) CONST_FUNC
float y
float x
#define ATMOSPHERE_DEPTH
@ STELLAR_TYPE_MINIATURE
#define OOExpandKey(key,...)
#define OOExpandKeyWithSeed(seed, key,...)
#define OOExpand(string,...)
NSMutableArray * ScanTokensFromString(NSString *values)
NSString * ClockToString(double clock, BOOL adjusting)
OOINLINE NSString * OOCredits(OOCreditsQuantity tenthsOfCredits)
NSPoint PointFromString(NSString *xyString)
NSString * OOPadStringToEms(NSString *string, float numEms)
#define OO_GALAXIES_AVAILABLE
@ OO_SYSTEMCONCEALMENT_NODATA
@ OO_SYSTEMCONCEALMENT_NONAME
#define OO_SYSTEMS_PER_GALAXY
OOINLINE Vector resolveVectorInIJK(Vector v0, Triangle ijk)
Definition OOTriangle.h:58
@ NO_TARGET
Definition OOTypes.h:169
OOLongRangeChartMode
Definition OOTypes.h:45
uint16_t OOFuelQuantity
Definition OOTypes.h:158
uint8_t OOWeaponFacingSet
Definition OOTypes.h:204
NSString * OOCommodityType
Definition OOTypes.h:97
OOAegisStatus
Definition OOTypes.h:53
@ AEGIS_IN_DOCKING_RANGE
Definition OOTypes.h:57
@ AEGIS_CLOSE_TO_MAIN_PLANET
Definition OOTypes.h:56
@ AEGIS_NONE
Definition OOTypes.h:54
OORouteType
Definition OOTypes.h:31
@ OPTIMIZED_BY_NONE
Definition OOTypes.h:32
OOGraphicsDetail
Definition OOTypes.h:208
@ DETAIL_LEVEL_SHADERS
Definition OOTypes.h:211
OOLegalStatusReason
Definition OOTypes.h:139
OOViewID
Definition OOTypes.h:39
uint64_t OOCreditsQuantity
Definition OOTypes.h:160
#define VALID_WEAPON_FACINGS
Definition OOTypes.h:206
NSUInteger OOTechLevelID
Definition OOTypes.h:177
@ kOOVariableTechLevel
Definition OOTypes.h:175
int16_t OOSystemID
Definition OOTypes.h:183
OOCompassMode
Definition OOTypes.h:129
uint8_t OOGalaxyID
Definition OOTypes.h:182
uint32_t OOCargoQuantity
Definition OOTypes.h:155
OOMassUnit
Definition OOTypes.h:111
@ UNITS_TONS
Definition OOTypes.h:112
@ UNITS_GRAMS
Definition OOTypes.h:114
@ UNITS_KILOGRAMS
Definition OOTypes.h:113
double OOTimeDelta
Definition OOTypes.h:193
uint8_t OOGovernmentID
Definition OOTypes.h:179
OODockingClearanceStatus
Definition OOTypes.h:147
@ 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
double OOTimeAbsolute
Definition OOTypes.h:192
OOWeaponFacing
Definition OOTypes.h:195
@ WEAPON_FACING_FORWARD
Definition OOTypes.h:196
@ WEAPON_FACING_NONE
Definition OOTypes.h:201
@ WEAPON_FACING_AFT
Definition OOTypes.h:197
@ WEAPON_FACING_PORT
Definition OOTypes.h:198
@ WEAPON_FACING_STARBOARD
Definition OOTypes.h:199
OOEnergyUnitType
Definition OOTypes.h:117
@ ENERGY_UNIT_NORMAL
Definition OOTypes.h:123
@ ENERGY_UNIT_NAVAL_DAMAGED
Definition OOTypes.h:120
@ ENERGY_UNIT_NAVAL
Definition OOTypes.h:124
@ OLD_ENERGY_UNIT_NORMAL
Definition OOTypes.h:121
@ ENERGY_UNIT_NONE
Definition OOTypes.h:118
@ OLD_ENERGY_UNIT_NAVAL
Definition OOTypes.h:122
@ ENERGY_UNIT_NORMAL_DAMAGED
Definition OOTypes.h:119
uint8_t OOEconomyID
Definition OOTypes.h:180
OOINLINE Vector vector_flip(Vector v) INLINE_CONST_FUNC
Definition OOVector.h:227
OOINLINE Vector vector_add(Vector a, Vector b) INLINE_CONST_FUNC
Definition OOVector.h:195
OOINLINE Vector vector_subtract(Vector a, Vector b) INLINE_CONST_FUNC
Definition OOVector.h:218
OOINLINE OOScalar magnitude(Vector vec) INLINE_CONST_FUNC
Definition OOVector.h:242
OOINLINE Vector vector_normal_or_zbasis(Vector vec) INLINE_CONST_FUNC
Definition OOVector.h:265
OOINLINE Vector make_vector(OOScalar vx, OOScalar vy, OOScalar vz) INLINE_CONST_FUNC
Definition OOVector.h:149
OOINLINE OOScalar dot_product(Vector first, Vector second) INLINE_CONST_FUNC
Definition OOVector.h:299
const Vector kZeroVector
Definition OOVector.m:27
OOINLINE void scale_vector(Vector *outVector, OOScalar factor) ALWAYS_INLINE_FUNC NONNULL_FUNC
Definition OOVector.h:166
OOINLINE OOScalar distance(Vector v1, Vector v2) INLINE_CONST_FUNC
Definition OOVector.h:280
OOINLINE Vector vector_multiply_scalar(Vector v, OOScalar s) INLINE_CONST_FUNC
Definition OOVector.h:180
#define CARGO_KEY_TYPE
#define MAX_CONTRACT_REP
OOCreditsQuantity OODeciCreditsFromObject(id object)
OOGalacticHyperspaceBehaviour
@ GALACTIC_HYPERSPACE_MAX
#define MAX_KILOGRAMS_IN_SAFE
#define PLAYER_STARTING_MISSILES
OOPlayerFleeingStatus
@ PLAYER_FLEEING_MAYBE
@ PLAYER_FLEEING_LIKELY
@ PLAYER_FLEEING_NONE
@ PLAYER_FLEEING_CARGO
@ PLAYER_FLEEING_UNLIKELY
@ ALERT_FLAG_DOCKED
@ ALERT_FLAG_MASS_LOCK
@ ALERT_FLAG_YELLOW_LIMIT
#define ESCAPE_SEQUENCE_TIME
#define CUSTOM_VIEW_MAX_ZOOM_IN
OOPrimedEquipmentMode
@ OOPRIMEDEQUIP_ACTIVATED
@ OOPRIMEDEQUIP_MODE
#define CHART_WIDTH_AT_MAX_ZOOM
#define PLAYER_MAX_WEAPON_TEMP
#define PORT_FACING_STRING
#define PLAYER_INTERNAL_DAMAGE_FACTOR
@ MARKET_FILTER_MODE_HOLD
@ MARKET_FILTER_MODE_RESTRICTED
@ MARKET_FILTER_MODE_STOCK
@ MARKET_FILTER_MODE_TRADE
@ MARKET_FILTER_MODE_OFF
@ MARKET_FILTER_MODE_LEGAL
#define MAX_GRAMS_IN_SAFE
OOSpeechSettings
@ OOSPEECHSETTINGS_ALL
@ OOSPEECHSETTINGS_OFF
@ OOSPEECHSETTINGS_COMMS
#define HYPERSPEED_FACTOR
#define KILOGRAMS_PER_POD
#define CHART_MAX_ZOOM
#define PLAYER_DIAL_MAX_ALTITUDE
#define MAX_HYPERSPEED_FACTOR
#define FORWARD_FACING_STRING
#define AFT_FACING_STRING
OOGUIScreenID
#define GUI_ROW_INIT(GUI)
OOFuelScoopStatus
@ SCOOP_STATUS_FULL_HOLD
@ SCOOP_STATUS_NOT_INSTALLED
@ SCOOP_STATUS_ACTIVE
@ SCOOP_STATUS_OKAY
#define CHART_HEIGHT_AT_MAX_ZOOM
#define CUSTOM_VIEW_MAX_ZOOM_OUT
#define MIN_HYPERSPEED_FACTOR
#define GUI_ROW(GROUP, ITEM)
@ GUI_ROW_EQUIPMENT_DETAIL
@ GUI_MAX_ROWS_EQUIPMENT
@ GUI_ROW_EQUIPMENT_START
@ GUI_ROW_MARKET_START
@ GUI_ROW_MARKET_END
@ GUI_ROW_MARKET_LAST
@ GUI_ROW_INTERFACES_START
@ GUI_MAX_ROWS_INTERFACES
#define STARBOARD_FACING_STRING
#define CUSTOMEQUIP_EQUIPKEY
#define CHART_SCROLL_AT_Y
#define SCANNER_ECM_FUZZINESS
#define GRAMS_PER_POD
#define CHART_SCROLL_AT_X
#define PLAYER_MAX_FUEL
#define SCRIPT_TIMER_INTERVAL
#define PLAYER_DOCKING_AI_NAME
OOMissileStatus
@ MISSILE_STATUS_TARGET_LOCKED
@ MISSILE_STATUS_ARMED
@ MISSILE_STATUS_SAFE
#define PLAYER_SHIP_DESC
@ MARKET_SORTER_MODE_PRICE
@ MARKET_SORTER_MODE_OFF
@ MARKET_SORTER_MODE_STOCK
@ MARKET_SORTER_MODE_ALPHA
@ MARKET_SORTER_MODE_UNIT
@ MARKET_SORTER_MODE_HOLD
#define ECM_DURATION
#define ECM_ENERGY_DRAIN_FACTOR
NSString * OODisplayStringFromLegalStatus(int legalStatus)
#define GUI_FIRST_ROW(GROUP)
NSString * KillCountToRatingAndKillString(unsigned kills)
#define PLAYER_SHIP_CLOCK_START
#define PLAYER_TARGET_MEMORY_SIZE
#define PLAYER_STARTING_MAX_MISSILES
#define PLAYER_MAX_TRUMBLES
#define PLAYER_MAX_MISSILES
static NSString *const kOOLogBuyMountedOK
static NSString *const kOOLogBuyMountedFailed
#define VELOCITY_CLEANUP_MIN
#define STAGE_TRACKING_END
#define UPDATE_STAGE(x)
PlayerEntity * gOOPlayer
NSComparisonResult marketSorterByName(id a, id b, void *market)
NSComparisonResult marketSorterByPrice(id a, id b, void *market)
NSComparisonResult marketSorterByQuantity(id a, id b, void *market)
static NSString * last_outfitting_key
static float const kDeadResetTime
#define VELOCITY_CLEANUP_RATE
#define STAGE_TRACKING_BEGIN
NSComparisonResult marketSorterByMassUnit(id a, id b, void *market)
#define VELOCITY_CLEANUP_FULL
@ kCommLogTrimSize
@ kCommLogTrimThreshold
static GLfloat sBaseMass
#define OO_SETACCESSCONDITIONFORROW(condition, row)
#define SCENARIO_OXP_DEFINITION_NONE
#define SCENARIO_OXP_DEFINITION_ALL
#define OO_VERSION_FULL
Definition main.m:63
#define MIN_FUEL
Definition ShipEntity.h:104
#define INITIAL_SHOT_TIME
Definition ShipEntity.h:102
OOEquipmentType * OOWeaponType
Definition ShipEntity.h:164
BOOL isWeaponNone(OOWeaponType weapon)
#define SHIP_COOLING_FACTOR
Definition ShipEntity.h:63
#define CLOAKING_DEVICE_MIN_ENERGY
Definition ShipEntity.h:50
OOAlertCondition
Definition ShipEntity.h:166
@ ALERT_CONDITION_GREEN
Definition ShipEntity.h:170
@ ALERT_CONDITION_RED
Definition ShipEntity.h:172
@ ALERT_CONDITION_YELLOW
Definition ShipEntity.h:171
@ ALERT_CONDITION_DOCKED
Definition ShipEntity.h:169
OOWeaponType OOWeaponTypeFromEquipmentIdentifierStrict(NSString *string) PURE_FUNC
#define ENTITY_PERSONALITY_INVALID
Definition ShipEntity.h:113
OOWeaponType OOWeaponTypeFromEquipmentIdentifierLegacy(NSString *string)
#define SHIP_MIN_CABIN_TEMP
Definition ShipEntity.h:70
#define MILITARY_JAMMER_ENERGY_RATE
Definition ShipEntity.h:53
#define CLOAKING_DEVICE_ENERGY_RATE
Definition ShipEntity.h:49
#define WEAPON_COOLING_FACTOR
Definition ShipEntity.h:115
#define SHIP_MAX_CABIN_TEMP
Definition ShipEntity.h:69
#define MILITARY_JAMMER_MIN_ENERGY
Definition ShipEntity.h:54
NSString * OOStringFromShipDamageType(OOShipDamageType type) CONST_FUNC
#define SUN_TEMPERATURE
Definition ShipEntity.h:74
NSString * OODisplayStringFromAlertCondition(OOAlertCondition alertCondition)
OOWeaponType OOWeaponTypeFromEquipmentIdentifierSloppy(NSString *string) PURE_FUNC
#define BASELINE_SHIELD_LEVEL
Definition ShipEntity.h:101
OOShipDamageType
Definition ShipEntity.h:175
#define SHIP_THRUST_FACTOR
Definition ShipEntity.h:46
#define ShipScriptEvent(context, ship, event,...)
#define WEAPON_COOLING_CUTOUT
Definition ShipEntity.h:117
#define SHIP_INSULATION_FACTOR
Definition ShipEntity.h:68
#define SHIP_ENERGY_DAMAGE_TO_HEAT_FACTOR
Definition ShipEntity.h:67
#define UNIVERSE
Definition Universe.h:827
#define PASSENGER_BERTH_SPACE
Definition Universe.h:143
#define DESC(key)
Definition Universe.h:832
@ WH_SCANINFO_NONE
@ WH_SCANINFO_SCANNED
@ WH_SCANINFO_SHIP
@ WH_SCANINFO_ARRIVAL_TIME
@ WH_SCANINFO_DESTINATION
@ WH_SCANINFO_COLLAPSE_TIME
OOFuelQuantity fuelRequiredForJump()
void setGuiToIntroFirstGo:(BOOL justCobra)
Definition AI.h:35
void setNextThinkTime:(OOTimeAbsolute ntt)
Definition AI.m:581
void setOwner:(ShipEntity *ship)
Definition AI.m:175
void clearAllData()
Definition AI.m:609
void setState:(NSString *stateName)
Definition AI.m:303
unsigned hasRotated
Definition Entity.h:93
GLfloat collision_radius
Definition Entity.h:107
GLfloat maxEnergy
Definition Entity.m:763
OOUniversalID universalID
Definition Entity.m:522
HPVector absolutePositionForSubentity()
Definition Entity.m:627
void dumpState()
Definition Entity.m:903
void setVelocity:(Vector vel)
Definition Entity.m:703
Quaternion orientation
Definition Entity.m:682
unsigned isSubEntity
Definition Entity.m:140
BOOL isSun()
Definition Entity.m:155
void setOrientation:(Quaternion quat)
Definition Entity.m:676
GLfloat energy
Definition Entity.m:753
GLfloat zero_distance
Definition Entity.h:104
unsigned isShip
Definition Entity.m:125
GLfloat collisionRadius()
Definition Entity.m:830
OOScanClass scanClass
Definition Entity.m:743
BOOL isInSpace()
Definition Entity.m:1033
void setScanClass:(OOScanClass sClass)
Definition Entity.m:738
OOEntityStatus status()
Definition Entity.m:733
unsigned isWormhole
Definition Entity.m:175
GLfloat distanceTravelled
Definition Entity.m:718
void setPositionX:y:z:(OOHPScalar x,[y] OOHPScalar y,[z] OOHPScalar z)
Definition Entity.m:614
BoundingBox boundingBox
Definition Entity.m:666
unsigned isStation
Definition Entity.m:135
unsigned isPlayer
Definition Entity.m:145
HPVector position
Definition Entity.m:576
Quaternion lastOrientation
Definition Entity.h:130
BOOL isPlanet()
Definition Entity.m:150
OOMatrix rotMatrix
Definition Entity.h:134
Vector relativePosition()
Definition Entity.m:598
id owner()
Definition Entity.m:548
void applyVelocity:(OOTimeDelta delta_t)
Definition Entity.m:878
unsigned isSunlit
Definition Entity.m:160
GLfloat mass
Definition Entity.m:671
void setPosition:(HPVector posn)
Definition Entity.m:608
NSString * playerFileToLoad
GameController * sharedController()
NSArray * displayModes()
void logProgress:(NSString *message)
NSUInteger indexOfCurrentDisplayMode()
BOOL setBackgroundTextureKey:(NSString *key)
OOColor * colorFromSetting:defaultValue:(NSString *setting,[defaultValue] OOColor *def)
BOOL setSelectedRow:(OOGUIRow row)
OOGUIRow addLongText:startingAtRow:align:(NSString *str,[startingAtRow] OOGUIRow row,[align] OOGUIAlignment alignment)
BOOL setForegroundTextureKey:(NSString *key)
void setStatusPage:(NSInteger pageNum)
NSString * selectedRowText()
void setText:forRow:(NSString *str,[forRow] OOGUIRow row)
void setText:forRow:align:(NSString *str,[forRow] OOGUIRow row,[align] OOGUIAlignment alignment)
void clearAndKeepBackground:(BOOL keepBackground)
BOOL setForegroundTextureDescriptor:(NSDictionary *descriptor)
OOGUIRow selectedRow
void overrideTabs:from:length:(OOGUITabSettings stops,[from] NSString *setting,[length] NSUInteger len)
NSDictionary * userSettings()
void setSelectableRange:(NSRange range)
void setColor:forRow:(OOColor *color,[forRow] OOGUIRow row)
NSString * selectedRowKey()
void setTitle:(NSString *str)
void setTabStops:(OOGUITabSettings stops)
NSString * keyForRow:(OOGUIRow row)
void setShowTextCursor:(BOOL yesno)
void setCurrentRow:(OOGUIRow value)
BOOL setBackgroundTextureDescriptor:(NSDictionary *descriptor)
void setArray:forRow:(NSArray *arr,[forRow] OOGUIRow row)
void setKey:forRow:(NSString *str,[forRow] OOGUIRow row)
void setHidden:(BOOL newValue)
void setScannerZoom:(GLfloat value)
void setCompassActive:(BOOL newValue)
NSUInteger mfdCount()
void setDeferredHudName:(NSString *newDeferredHudName)
void resetGuis:(NSDictionary *info)
GLfloat scannerZoom()
void setMouseWheelDelta:(float newWheelDelta)
void getDisplayDimensions:height:(unsigned *width,[height] unsigned *height)
BOOL isRunningOnPrimaryDisplayDevice()
float fov:(BOOL inFraction)
void adjustColorSaturation:(float colorSaturationAdjustment)
float colorSaturation()
GameController * gameController
OOCacheManager * sharedCache()
void setObject:forKey:(id value,[forKey] id key)
Definition OOCache.m:256
OOColor * cyanColor()
Definition OOColor.m:274
OOColor * colorWithRed:green:blue:alpha:(float red,[green] float green,[blue] float blue,[alpha] float alpha)
Definition OOColor.m:107
OOColor * orangeColor()
Definition OOColor.m:289
OOColor * colorWithDescription:(id description)
Definition OOColor.m:135
OOColor * redColor()
Definition OOColor.m:259
OOColor * greenColor()
Definition OOColor.m:264
OOColor * grayColor()
Definition OOColor.m:254
OOColor * whiteColor()
Definition OOColor.m:249
OOColor * yellowColor()
Definition OOColor.m:279
OOColor * magentaColor()
Definition OOColor.m:284
OOCommodityType legacyCommodityType:(NSUInteger i)
NSUInteger exportLegalityForGood:(OOCommodityType good)
OOMassUnit massUnitForGood:(OOCommodityType good)
void loadPlayerAmounts:(NSArray *amounts)
NSUInteger importLegalityForGood:(OOCommodityType good)
BOOL removeQuantity:forGood:(OOCargoQuantity quantity,[forGood] OOCommodityType good)
OOCargoQuantity capacityForGood:(OOCommodityType good)
BOOL setQuantity:forGood:(OOCargoQuantity quantity,[forGood] OOCommodityType good)
OOCargoQuantity quantityForGood:(OOCommodityType good)
BOOL addQuantity:forGood:(OOCargoQuantity quantity,[forGood] OOCommodityType good)
OOCreditsQuantity priceForGood:(OOCommodityType good)
NSString * nameForGood:(OOCommodityType good)
NSString * commentForGood:(OOCommodityType good)
NSString * conditionScript()
NSUInteger repairTime()
NSString * damagedIdentifier()
OOColor * displayColor()
NSArray * defaultActivateKey()
NSArray * defaultModeKey()
OOTechLevelID effectiveTechLevel()
OOCargoQuantity requiredCargoSpace()
OOEquipmentType * equipmentTypeWithIdentifier:(NSString *identifier)
OOCreditsQuantity price()
NSUInteger installTime()
GLfloat damageProbability()
NSString * identifier()
NSString * descriptiveText()
BOOL callMethod:inContext:withArguments:count:result:(jsid methodID,[inContext] JSContext *context,[withArguments] jsval *argv,[count] intN argc,[result] jsval *outResult)
Definition OOJSScript.m:328
OOJavaScriptEngine * sharedEngine()
void garbageCollectionOpportunity:(BOOL force)
void update:(OOTimeDelta delta_t)
NSString * modelName()
Definition OOMesh.m:353
OOMusicController * sharedController()
OOOXZManager * sharedManager()
id jsScriptFromFileNamed:properties:(NSString *fileName,[properties] NSDictionary *properties)
Definition OOScript.m:177
BOOL callMethod:inContext:withArguments:count:result:(jsid methodID,[inContext] JSContext *context,[withArguments] jsval *argv,[count] intN argc,[result] jsval *outResult)
Definition OOJSScript.m:600
NSDictionary * shipyardInfoForKey:(NSString *key)
OOShipRegistry * sharedRegistry()
NSDictionary * shipInfoForKey:(NSString *key)
float masterVolume()
Definition OOALSound.m:75
NSDictionary * dictionary()
Definition OOTrumble.m:906
void spawnFrom:(OOTrumble *parentTrumble)
Definition OOTrumble.m:217
void updateTrumble:(double delta_t)
Definition OOTrumble.m:490
OOWeakReference * weakSelf
GLfloat isHitByLine:v1:(Vector v0,[v1] Vector v1)
Definition Octree.m:457
OOWeaponFacingSet availableFacings()
BOOL addEquipmentItem:withValidation:inContext:(NSString *equipmentKey, [withValidation] BOOL validateAddition, [inContext] NSString *context)
NSMutableDictionary * roleWeightFlags
OOTimeDelta forward_shot_time
void addRoleToPlayer:(NSString *role)
NSMutableDictionary * passenger_record
NSString * _jumpCause
void setGuiToSystemDataScreen()
double script_time_check
unsigned mouse_control_on
NSString * dial_fpsinfo()
void updateTrumbles:(OOTimeDelta delta_t)
NSUInteger sessionID()
OOWeaponType currentWeapon()
void setMissionBackgroundDescriptor:(NSDictionary *descriptor)
OOScalar saved_chart_zoom
GLfloat aft_shield
NSDictionary * passengerContractMarker:(OOSystemID system)
void doTradeIn:forPriceFactor:(OOCreditsQuantity tradeInValue, [forPriceFactor] double priceFactor)
unsigned launchingMissile
BOOL hyperspeedEngaged()
NSDictionary * keyconfig2_settings
void setBounty:withReasonAsString:(OOCreditsQuantity amount, [withReasonAsString] NSString *reason)
NSInteger marketOffset
void getDestroyedBy:damageType:(Entity *whom, [damageType] OOShipDamageType type)
OOSystemID info_system_id
void noteGUIDidChangeFrom:to:refresh:(OOGUIScreenID fromScreen,[to] OOGUIScreenID toScreen,[refresh] BOOL refresh)
unsigned autopilot_engaged
Vector viewpointOffsetAft()
void showShipModelWithKey:shipData:personality:factorX:factorY:factorZ:inContext:(NSString *shipKey,[shipData] NSDictionary *shipData,[personality] uint16_t personality,[factorX] GLfloat factorX,[factorY] GLfloat factorY,[factorZ] GLfloat factorZ,[inContext] NSString *context)
BOOL dialIdentEngaged()
NSDictionary * keyConfig()
void playWeaponOverheated:(Vector weaponOffset)
OOEnergyUnitType installedEnergyUnitType()
BOOL hasSufficientFuelForJump()
void setActiveMissile:(NSUInteger value)
void setNextCompassMode()
void setGuiToLongRangeChartScreen()
GLfloat roll_delta
float _trumbleAppetiteAccumulator
void addTrumble:(OOTrumble *papaTrumble)
NSMutableDictionary * missionDestinations
NSArray * cargoList()
GLfloat dialHyperSpeed()
void setAlertFlag:to:(int flag,[to] BOOL value)
void setGuiToLoadSaveScreen()
NSMutableArray * parcels
NSString * markerKey:(NSDictionary *marker)
GLfloat aftShieldLevel()
ShipEntity * launchEscapeCapsule()
void setGuiToChartScreenFrom:(OOGUIScreenID oldScreen)
void activateSelectedInterface()
NSArray * kbdLayouts
StickProfileScreen * stickProfileScreen
void setBounty:withReason:(OOCreditsQuantity amount, [withReason] OOLegalStatusReason reason)
void setGuiToMarketScreen()
void setGuiToGameOptionsScreen()
OODockingClearanceStatus getDockingClearanceStatus()
GLfloat max_forward_shield
NSDictionary * equipScreenBackgroundDescriptor()
void deactivateCloakingDevice()
void addRoleForMining()
void setGuiToEquipShipScreen:selectingFacingFor:(int skip,[selectingFacingFor] NSString *eqKeyForSelectFacing)
OOMarketSorterMode marketSorterMode
void playMissileLaunched:weaponIdentifier:(Vector weaponOffset,[weaponIdentifier] NSString *weaponIdentifier)
void unloadAllCargoPodsForType:toManifest:(OOCommodityType type,[toManifest] OOCommodityMarket *manifest)
GLfloat pitch_delta
OOCargoQuantity current_cargo
void performDeadUpdates:(OOTimeDelta delta_t)
BOOL injectorsEngaged()
NSString * commanderName()
StationEntity * getTargetDockStation()
BOOL setMultiFunctionDisplay:toKey:(NSUInteger index,[toKey] NSString *key)
NSUInteger trumbleCount
Vector starboardViewOffset
GLfloat max_aft_shield
GLfloat laserHeatLevelForward()
void setFoundTarget:(Entity *targetEntity)
OOPlayerFleeingStatus fleeing_status
GLfloat dialAftShield()
void updateMovementFlags()
void setGuiToInterfacesScreen:(int skip)
NSDictionary * worldScriptsByName()
OOAlertCondition realAlertCondition()
OOMatrix drawRotationMatrix()
NSMutableArray * contracts
unsigned ident_engaged
void checkScriptsIfAppropriate()
OODockingClearanceStatus dockingClearanceStatus
void enterGalacticWitchspace()
GLfloat forwardShieldLevel()
double fps_check_time
void setCompassTarget:(Entity *value)
NSArray * _customViews
OOGUIScreenID missionExitScreen()
NSMutableDictionary * localVariables
void performLaunchingUpdates:(OOTimeDelta delta_t)
float trumbleAppetiteAccumulator()
NSInteger missingSubEntitiesAdjustment()
void performInFlightUpdates:(OOTimeDelta delta_t)
void showMarketCashAndLoadLine()
BOOL checkEntityForMassLock:withScanClass:(Entity *ent, [withScanClass] int theirClass)
NSString * keyShiftText
OOCreditsQuantity adjustPriceByScriptForEqKey:withCurrent:(NSString *eqKey,[withCurrent] OOCreditsQuantity price)
Vector forwardViewOffset
BOOL removeFromPylon:(NSUInteger pylon)
void performWitchspaceExitUpdates:(OOTimeDelta delta_t)
void setMissionBackgroundSpecial:(NSString *special)
unsigned massLockable
NSArray * parcelListForScripting()
double renovationFactor()
OOSystemID previousSystemID()
void setPrevCompassMode()
void setSystemID:(OOSystemID sid)
void addEquipmentWithScriptToCustomKeyArray:(NSString *equipmentKey)
unsigned ship_kills
GLfloat dialAltitude()
OOWeakReference * _dockedStation
void unloadCargoPods()
void tidyMissilePylons()
NSString * screenModeStringForWidth:height:refreshRate:(unsigned inWidth,[height] unsigned inHeight,[refreshRate] float inRate)
void setGuiToStatusScreen()
void witchJumpTo:misjump:(OOSystemID sTo, [misjump] BOOL misjump)
OOGalaxyID galaxy_number
Vector weaponViewOffset()
NSMutableDictionary * customDialSettings
int ship_trade_in_factor
OOWeakReference * compassTarget
double scannerFuzziness()
void playScrapeDamage:(Vector attackVector)
NSDictionary * _missionOverlayDescriptor
NSString * _fastEquipmentB
void noteCompassLostTarget()
NSMutableArray * roleSystemList
GLfloat launchRoll
void setGuiToMarketInfoScreen()
BOOL mountMissile:(ShipEntity *missile)
Vector viewpointOffsetStarboard()
OOLongRangeChartMode longRangeChartMode
double renovationCosts()
OOGalaxyID galaxyNumber()
NSDictionary * validatedMarker:(NSDictionary *marker)
NSUInteger passengerCount()
void markAsOffender:withReason:(int offence_value, [withReason] OOLegalStatusReason reason)
NSMutableDictionary * contract_record
unsigned travelling_at_hyperspeed
unsigned replacingMissile
StationEntity * dockedStation()
NSMutableString * dockingReport
void setShowDemoShips:(BOOL value)
void targetInfoSystem()
void playWitchjumpInsufficientFuel()
NSString * checkPassengerContracts()
void playWitchjumpDistanceTooGreat()
ShipEntity * demoShip
NSString * _lastsaveName
NSMutableArray * target_memory
NSString * specialCargo
double ecm_start_time
NSInteger missionTextRow
OOMatrix drawTransformationMatrix()
unsigned hyperspeed_engaged
void updateAlertConditionForNearbyEntities()
void updateClocks:(OOTimeDelta delta_t)
OOCreditsQuantity deciCredits()
void penaltyForUnauthorizedDocking()
float occlusion_dial
Quaternion normalOrientation()
unsigned scoopOverride
OOSystemID previous_system_id
NSMutableArray * roleWeights
OOGUIScreenID _missionExitScreen
BOOL switchHudTo:(NSString *hudFileName)
GLfloat laserHeatLevelPort()
NSPoint custom_chart_centre_coordinates
NSUInteger dialMaxMissiles()
OOCargoQuantity contractedVolumeForGood:(OOCommodityType good)
BOOL changePassengerBerths:(int addRemove)
void prepareMarkedDestination:marker:(NSMutableDictionary *markers, [marker] NSDictionary *marker)
NSString * scenarioKey
BOOL doWorldEventUntilMissionScreen:(OOJSPropID message)
void removeEqScriptForKey:(NSString *eq_key)
OOAlertFlags alertFlags
void pollControls:(double delta_t)
GLfloat laserHeatLevelStarboard()
double fieldOfView
NSDictionary * commanderDataDictionary()
double escapePodRescueTime()
OOCreditsQuantity bounty()
void clearExtraMissionKeys()
OOMarketFilterMode marketFilterMode
OOTimeDelta witchspaceCountdown
NSMutableArray * passengers
void playDirectHit:weaponIdentifier:(Vector attackVector,[weaponIdentifier] NSString *weaponIdentifier)
void addScannedWormhole:(WormholeEntity *wormhole)
void setDockingClearanceStatus:(OODockingClearanceStatus newValue)
ShipEntity * launchMine:(ShipEntity *mine)
void setFastEquipmentA:(NSString *eqKey)
OOCreditsQuantity removeMissiles()
NSArray * worldScriptNames()
NSDictionary * cargoContractMarker:(OOSystemID system)
unsigned afterburnerSoundLooping
unsigned afterburner_engaged
unsigned scoopsActive
NSString * compassTargetLabel()
NSDictionary * extraMissionKeys
NSArray * equipmentList()
double script_time
void setDockTarget:(ShipEntity *entity)
OOCommodityMarket * shipCommodityData
OORouteType ANA_mode
NSMutableDictionary * shipyardRecord()
OORouteType ANAMode()
NSArray * contractsListForScriptingFromArray:forCargo:(NSArray *contracts_array, [forCargo] BOOL forCargo)
void setFastEquipmentB:(NSString *eqKey)
NSMutableDictionary * reputation
NSPoint galaxy_coordinates
GLfloat laserHeatLevel()
NSArray * lastShot
NSUInteger eqScriptIndexForKey:(NSString *eq_key)
NSArray * applyMarketFilter:onMarket:(NSArray *goods,[onMarket] OOCommodityMarket *market)
void warnAboutHostiles()
NSString * planetSearchString
void setLastsaveName:(NSString *value)
void addMissionDestinationMarker:(NSDictionary *marker)
BOOL addEqScriptForKey:(NSString *eq_key)
void nextInfoSystem()
OOAlertCondition lastScriptAlertCondition
NSMutableDictionary * commodityScripts
void clearRolesFromPlayer:(float chance)
Vector portViewOffset
NSDictionary * defaultMarker:(OOSystemID system)
NSDictionary * _equipScreenBackgroundDescriptor
BOOL setWeaponMount:toWeapon:inContext:(OOWeaponFacing facing,[toWeapon] NSString *eqKey,[inContext] NSString *context)
NSMutableArray * commLog
void completeSetUpAndSetTarget:(BOOL setTarget)
OOTrumble * trumble[PLAYER_MAX_TRUMBLES]
BOOL isMouseControlOn()
GLfloat dialEnergy()
NSString * lastTextKey
NSString * dial_objinfo()
void showMarketScreenHeaders()
void calculateCurrentCargo()
GLfloat dialYaw()
float maxForwardShieldLevel()
void setupStartScreenGui()
NSString * keyMod1Text
double ship_clock
void loseTargetStatus()
double escape_pod_rescue_time
void performWitchspaceCountdownUpdates:(OOTimeDelta delta_t)
NSString * processEscapePods()
OOWeaponType weaponForFacing:(OOWeaponFacing facing)
void updateAlertCondition()
GLfloat fuelChargeRate()
void showMarketScreenDataLine:forGood:inMarket:holdQuantity:(OOGUIRow row, [forGood] OOCommodityType good, [inMarket] OOCommodityMarket *localMarket, [holdQuantity] OOCargoQuantity quantity)
void gameOverFadeToBW()
unsigned showDemoShips
void setInfoSystemID:moveChart:(OOSystemID sid,[moveChart] BOOL moveChart)
void setTrumbleValueFrom:(NSObject *trumbleValue)
void addEquipmentFromCollection:(id equipment)
NSUInteger target_memory_index
void validateCustomEquipActivationArray()
BOOL takeInternalDamage()
void unloadCargoPodsForType:amount:(OOCommodityType type,[amount] OOCargoQuantity quantity)
OOFuelScoopStatus dialFuelScoopStatus()
NSUInteger parcelCount()
GLfloat hyperspeedFactor
void noteGUIWillChangeTo:(OOGUIScreenID toScreen)
NSString * dialTargetName()
void takeHeatDamage:(double amount)
NSPoint target_chart_focus
void playHyperspaceDistanceTooGreat()
void playMineLaunched:weaponIdentifier:(Vector weaponOffset,[weaponIdentifier] NSString *weaponIdentifier)
Vector viewpointOffsetPort()
OOSystemID system_id
void doBookkeeping:(double delta_t)
BOOL addEquipmentItem:inContext:(NSString *equipmentKey, [inContext] NSString *context)
NSMutableDictionary * getMissionDestinations()
void showInformationForSelectedInterface()
OOEnergyUnitType energyUnitType()
Quaternion customViewQuaternion
void applyRoll:andClimb:(GLfloat roll1, [andClimb] GLfloat climb1)
NSMutableArray * targetMemory()
BOOL validForAddToUniverse()
OOScalar target_chart_zoom
void playIncomingMissile:(Vector missileVector)
NSString * fastEquipmentA()
void moveForward:(double amount)
NSString * keyMod2Text
Vector customViewRightVector
void setDefaultCustomViews()
GLfloat fuel_leak_rate
ShipEntity * missile_entity[PLAYER_MAX_MISSILES]
BOOL activateCloakingDevice()
OOCommodityType dumpCargo()
NSArray * stickFunctions
OOMatrix playerRotMatrix
NSDictionary * worldScriptsRequiringTickle
NSMutableArray * customEquipmentActivation()
NSString * _commanderName
NSMutableDictionary * mission_variables
NSString * currentPrimedEquipment()
NSMutableDictionary * parcel_record
void doWorldScriptEvent:inContext:withArguments:count:timeLimit:(OOJSPropID message,[inContext] JSContext *context,[withArguments] jsval *argv,[count] int argc,[timeLimit] OOTimeDelta limit)
unsigned weapons_online
NSArray * multiFunctionDisplayList()
Vector customViewOffset
NSUInteger primedEquipmentCount()
OOGUIBackgroundSpecial missionBackgroundSpecial()
void previousInfoSystem()
BOOL setUpAndConfirmOK:(BOOL stopOnError)
BOOL setUpAndConfirmOK:saveGame:(BOOL stopOnError,[saveGame] BOOL loadingGame)
void showInformationForSelectedUpgradeWithFormatString:(NSString *extraString)
HPVector breakPatternPosition()
OOCreditsQuantity credits
NSDictionary * _missionBackgroundDescriptor
OOCargoQuantity cargoQuantityOnBoard()
NSArray * passengerListForScripting()
OOTimeDelta aft_shot_time
OOGalacticHyperspaceBehaviour galacticHyperspaceBehaviour
NSPoint cursor_coordinates
HeadUpDisplay * hud
static NSString * SliderString(NSInteger amountIn20ths)
ShipEntity * fireMissile()
NSUInteger _customViewIndex
void setCompassMode:(OOCompassMode value)
void highlightEquipShipScreenKey:(NSString *key)
void selectNextMissile()
NSMutableArray * eqScripts
void setJumpCause:(NSString *value)
OOGUIScreenID gui_screen
OOScalar chart_zoom
OOCargoQuantity cargoQuantityForType:(OOCommodityType type)
GLfloat dialForwardShield()
void setDockedAtMainStation()
Vector viewpointOffsetForward()
void loadCargoPodsForType:amount:(OOCommodityType type,[amount] OOCargoQuantity quantity)
void setGuiToSystemDataScreenRefreshBackground:(BOOL refreshBackground)
NSDictionary * missionOverlayDescriptor()
void setDefaultViewOffsets()
OOTrumble ** trumbleArray()
void mungChecksumWithNSString:(NSString *str)
void setPreviousSystemID:(OOSystemID sid)
double last_ecm_time
void removeEquipmentItem:(NSString *equipmentKey)
NSArray * keyFunctions
void selectPreviousMultiFunctionDisplay()
OOSystemID infoSystemID()
GLfloat scanner_zoom_rate
unsigned max_passengers
OOSpeechSettings isSpeechOn
void setGuiToShortRangeChartScreen()
NSString * fastEquipmentB()
NSPoint adjusted_chart_centre()
OOUniversalID _dockTarget
GLfloat dialMaxEnergy()
void setDockedStation:(StationEntity *station)
OOScalar custom_chart_zoom
NSArray * missilesList()
void currentWeaponStats()
double hyperspaceJumpDistance()
NSMutableDictionary * multiFunctionDisplayText
NSMutableArray * multiFunctionDisplaySettings
unsigned show_info_flag
void setGuiToOXZManager()
void performDockingRequest:(StationEntity *stationForDocking)
void playCloakingDeviceInsufficientEnergy()
OOMatrix customViewMatrix
NSString * lastsaveName()
NSArray * contractListForScripting()
void addMessageToReport:(NSString *report)
void homeInfoSystem()
OOMissileStatus dialMissileStatus()
NSString * _fastEquipmentA
void disengageAutopilot()
OOSystemID found_system_id
unsigned using_mining_laser
NSUInteger activeMissile
Vector customViewUpVector
void loadCargoPodsForType:fromManifest:(OOCommodityType type,[fromManifest] OOCommodityMarket *manifest)
void initialiseMissionDestinations:andLegacy:(NSDictionary *destinations,[andLegacy] NSArray *legacy)
NSArray * cargoListForScripting()
unsigned hyperspeed_locked
void applyYaw:(GLfloat yaw)
NSUInteger passengerCapacity()
void setScriptTarget:(ShipEntity *ship)
OOAlertCondition alertCondition
Vector aftViewOffset
void validateCompassTarget()
NSPoint galacticHyperspaceFixedCoords
NSDictionary * markedDestinations()
GLfloat dialFuel()
void setGalacticHyperspaceFixedCoordsTo:(NSString *galacticHyperspaceFixedCoordsString)
OOTimeDelta starboard_shot_time
unsigned galactic_witchjump
void printIdentLockedOnForMissile:(BOOL missile)
float forwardShieldRechargeRate()
NSString * marketScreenTitle()
NSMutableDictionary * shipyard_record
NSUInteger maxPlayerRoles()
void performDockingUpdates:(OOTimeDelta delta_t)
Vector customViewForwardVector
void addTarget:(Entity *targetEntity)
OOGUIScreenID guiScreen()
Vector viewpointOffset()
void setGalacticHyperspaceBehaviourTo:(NSString *galacticHyperspaceBehaviourString)
float occlusionLevel()
void updateFuelScoopSoundWithInterval:(OOTimeDelta delta_t)
GLfloat dialSpeed()
void noteGUIDidChangeFrom:to:(OOGUIScreenID fromScreen,[to] OOGUIScreenID toScreen)
void setMissionOverlayDescriptor:(NSDictionary *descriptor)
NSMutableArray * customModePressed
HPVector viewpointPosition()
float aftShieldRechargeRate()
OOSystemID systemID()
GLfloat baseMass()
void enterDock:(StationEntity *station)
void updateFuelScoops:(OOTimeDelta delta_t)
NSDictionary * worldScripts
NSUInteger activeMFD
OOMissileStatus missile_status
OOPlayerFleeingStatus fleeingStatus()
void setCustomViewDataFromDictionary:withScaling:(NSDictionary *viewDict,[withScaling] BOOL withScaling)
GLfloat yaw_delta
float maxAftShieldLevel()
GLfloat forward_shield_recharge_rate
GLfloat dialRoll()
BOOL _missionWithCallback
GLfloat dialHyperRange()
WormholeEntity * wormhole
GLfloat insideAtmosphereFraction()
void addRoleToPlayer:inSlot:(NSString *role,[inSlot] NSUInteger slot)
OOSystemID nextHopTargetSystemID()
void setTrumbleAppetiteAccumulator:(float value)
NSMutableArray * scannedWormholes
NSDictionary * parcelContractMarker:(OOSystemID system)
double maxFieldOfView
double ship_clock_adjust
void setBackgroundFromDescriptionsKey:(NSString *d_key)
void setEquipScreenBackgroundDescriptor:(NSDictionary *descriptor)
unsigned legalStatusOfCargoList()
NSMutableArray * customActivatePressed
double script_time_interval
NSString * jumpCause()
void createCargoPodWithType:andAmount:(OOCommodityType type, [andAmount] OOCargoQuantity amount)
NSArray * applyMarketSorter:onMarket:(NSArray *goods,[onMarket] OOCommodityMarket *market)
GLfloat dialPitch()
OOCommodityType marketSelectedCommodity
void noteSwitchToView:fromView:(OOViewID toView,[fromView] OOViewID fromView)
void adjustTradeInFactorBy:(int value)
void removeAllCargo:(BOOL forceRemoval)
GLfloat laserHeatLevelAft()
NSPoint chart_focus_coordinates
NSDictionary * missionBackgroundDescriptorOrDefault()
NSPoint target_chart_centre
NSString * save_path
void playShieldHit:weaponIdentifier:(Vector attackVector,[weaponIdentifier] NSString *weaponIdentifier)
void orientationChanged()
void showInformationForSelectedUpgrade()
OOFuelQuantity fuelRequiredForJump()
NSString * dial_clock()
NSMutableArray * customEquipActivation
GLfloat aft_shield_recharge_rate
OOTimeDelta port_shot_time
unsigned countMissiles()
OOCompassMode compassMode
void selectNextMultiFunctionDisplay()
OOGUIBackgroundSpecial _missionBackgroundSpecial
void setGuiToEquipShipScreen:(int skip)
NSString * dial_clock_adjusted()
NSUInteger primedEquipment
NSDictionary * missionOverlayDescriptorOrDefault()
OOCommodityMarket * localMarket()
unsigned suppressTargetLost
NSMutableDictionary * extraGuiScreenKeys
unsigned ecm_in_operation
NSArray * processKeyCode:(NSArray *key_def)
double clockTimeAdjusted()
NSString * customViewDescription
void setCommanderName:(NSString *value)
GLfloat forward_shield
OOSystemID target_system_id
PlayerEntity * sharedPlayer()
OOWeaponFacing chosen_weapon_facing
void resetAutopilotAI()
NSPoint chart_centre_coordinates
Vector customViewRotationCenter
ProxyPlayerEntity * createDoppelganger()
StationEntity * targetDockStation
OOSystemID targetSystemID()
BOOL infoSystemOnRoute()
NSArray * currentLaserOffset()
NSDictionary * missionBackgroundDescriptor()
void setFuelLeak:(NSString *value)
void updateSystemMemory()
void clearRoleFromPlayer:(BOOL includingLongRange)
void setGalacticHyperspaceFixedCoordsX:y:(unsigned char x,[y] unsigned char y)
void performAutopilotUpdates:(OOTimeDelta delta_t)
NSDictionary * loadScripts()
NSArray * OXPsWithMessagesFound()
NSDictionary * dictionaryFromFilesNamed:inFolder:andMerge:(NSString *fileName,[inFolder] NSString *folderName,[andMerge] BOOL mergeFiles)
BOOL isExplicitlyUnpiloted()
BOOL hasScoop()
void setDemoStartTime:(OOTimeAbsolute time)
Vector forwardVector()
void doScriptEvent:(OOJSPropID message)
void setMesh:(OOMesh *mesh)
BOOL hasMilitaryJammer()
void setTargetStation:(Entity *targetEntity)
NSMutableArray * cargo
void setLastAegisLock:(Entity< OOStellarBody > *lastAegisLock)
void noteLostTarget()
unsigned isMissile
void deserializeShipSubEntitiesFrom:(NSString *string)
Definition ShipEntity.m:771
void setNextBeacon:(Entity< OOBeaconEntity > *beaconShip)
BOOL isJammingScanning()
void transitionToAegisNone()
void addTarget:(Entity *targetEntity)
Vector v_forward
Definition ShipEntity.h:189
void noteKilledBy:damageType:(Entity *whom,[damageType] OOShipDamageType type)
BOOL hasPrimaryWeapon:(OOWeaponType weaponType)
void broadcastHitByLaserFrom:(ShipEntity *aggressor_ship)
void setDesiredSpeed:(double amount)
NSDictionary * shipInfoDictionary()
void removeEquipmentItem:(NSString *equipmentKey)
void doScriptEvent:withArguments:(OOJSPropID message,[withArguments] NSArray *arguments)
void setFuel:(OOFuelQuantity amount)
void removeTarget:(Entity *targetEntity)
GLfloat scriptedMisjumpRange()
OOTimeAbsolute cargo_dump_time
Definition ShipEntity.h:347
GLfloat frustration
OOWeaponFacing currentWeaponFacing
void manageCollisions()
void setStatus:(OOEntityStatus stat)
GLfloat weapon_energy_use
Definition ShipEntity.h:303
BOOL addEquipmentItem:withValidation:inContext:(NSString *equipmentKey,[withValidation] BOOL validateAddition,[inContext] NSString *context)
GLfloat aft_weapon_temp
Definition ShipEntity.h:304
void setRoll:(double amount)
void setThrust:(double amount)
GLfloat _scriptedMisjumpRange
Definition ShipEntity.h:273
GLfloat max_flight_pitch
Definition ShipEntity.h:230
BOOL hasFuelScoop()
void setSpeed:(double amount)
void takeScrapeDamage:from:(double amount,[from] Entity *ent)
unsigned suppressAegisMessages
Definition ShipEntity.h:261
NSString * shipDataKey()
int checkShipsInVicinityForWitchJumpExit()
NSUInteger missileCount()
OORoleSet * roleSet
NSString * primaryRole
BOOL fireLaserShotInDirection:weaponIdentifier:(OOWeaponFacing direction,[weaponIdentifier] NSString *weaponIdentifier)
GLfloat port_weapon_temp
Definition ShipEntity.h:304
OOCargoQuantity availableCargoSpace()
unsigned missiles
Definition ShipEntity.h:308
void receiveCommsMessage:from:(NSString *message_text,[from] ShipEntity *other)
unsigned being_fined
Definition ShipEntity.h:248
NSString * name
unsigned max_missiles
Definition ShipEntity.h:309
void wasAddedToUniverse()
OOCargoType dumpItem:(ShipEntity *jetto)
GLint entityPersonalityInt()
NSString * shipClassName
GLfloat flightPitch
BOOL isPolice()
Entity * primaryAggressor()
void setPrimaryRole:(NSString *role)
GLfloat flightSpeed
OOWeaponType aft_weapon_type
Definition ShipEntity.h:295
void deactivateCloakingDevice()
BOOL countsAsKill()
BoundingBox totalBoundingBox
Vector v_up
Definition ShipEntity.h:189
BOOL isPirateVictim()
BOOL hasEquipmentItem:(id equipmentKeys)
BOOL removeExternalStore:(OOEquipmentType *eqType)
GLfloat _scaleFactor
Definition ShipEntity.h:377
OOWeakReference * _primaryTarget
Definition ShipEntity.h:425
NSEnumerator * equipmentEnumerator()
void drawImmediate:translucent:(bool immediate, [translucent] bool translucent)
GLfloat temperature()
void setHeatInsulation:(GLfloat value)
void abortDocking()
void resetExhaustPlumes()
OOFuelQuantity fuel
OOFuelQuantity fuelCapacity()
OOEquipmentType * missile_list[SHIPENTITY_MAX_MISSILES]
Definition ShipEntity.h:422
OOCreditsQuantity bounty
OOScanClass scanClass()
BOOL hasMilitaryScannerFilter()
StationEntity * targetStation()
uint16_t entity_personality
Definition ShipEntity.h:418
NSString * serializeShipSubEntities()
Definition ShipEntity.m:753
NSString * identFromShip:(ShipEntity *otherShip)
GLfloat forward_weapon_temp
Definition ShipEntity.h:304
BOOL cascadeIfAppropriateWithDamageAmount:cascadeOwner:(double amount,[cascadeOwner] Entity *owner)
void doScriptEvent:withArgument:andArgument:(OOJSPropID message,[withArgument] id argument1,[andArgument] id argument2)
void removeAllEquipment()
NSString * shipUniqueName
NSUInteger missileCapacity()
void setShipDataKey:(NSString *key)
id initBypassForPlayer()
Definition ShipEntity.m:184
GLfloat thrust
OOCommodityType dumpCargo()
GLfloat starboard_weapon_temp
Definition ShipEntity.h:304
void setAITo:(NSString *aiString)
OOTimeDelta shot_time
Definition ShipEntity.h:186
void becomeLargeExplosion:(double factor)
float energyRechargeRate()
void setWeaponDataFromType:(OOWeaponType weapon_type)
NSArray * missilesList()
NSEnumerator * shipSubEntityEnumerator()
void noteTargetDestroyed:(ShipEntity *target)
Vector missileLaunchPosition()
NSArray * laserPortOffset:(OOWeaponFacing direction)
void doScriptEvent:inContext:withArguments:count:(OOJSPropID message,[inContext] JSContext *context,[withArguments] jsval *argv,[count] int argc)
Entity< OOStellarBody > * findNearestStellarBody()
void setPendingEscortCount:(uint8_t count)
NSString * equipmentItemProviding:(NSString *equipmentType)
OOWeaponFacingSet weaponFacings()
HPVector destination()
GLfloat weapon_temp
Definition ShipEntity.h:303
OOBehaviour behaviour
unsigned cloakPassive
OOWeaponType starboard_weapon_type
Definition ShipEntity.h:297
OOJSScript * script
void setScriptedMisjumpRange:(GLfloat newValue)
Vector velocity()
unsigned scripted_misjump
Definition ShipEntity.h:267
float ship_temperature
Definition ShipEntity.h:398
void setEntityPersonalityInt:(uint16_t value)
GLfloat heatInsulation()
BOOL canScoop:(ShipEntity *other)
BOOL hasHostileTarget()
unsigned military_jammer_active
Definition ShipEntity.h:238
void clearSubEntities()
OOCargoQuantity commodityAmount()
GLfloat weapon_shot_temperature
Definition ShipEntity.h:303
GLfloat max_flight_yaw
Definition ShipEntity.h:231
OOCargoQuantity maxAvailableCargoSpace()
void update:(OOTimeDelta delta_t)
uint8_t pendingEscortCount()
BOOL setUpSubEntities()
Definition ShipEntity.m:790
void noteTakingDamage:from:type:(double amount,[from] Entity *entity,[type] OOShipDamageType type)
GLfloat max_thrust
Definition ShipEntity.h:234
void setScriptedMisjump:(BOOL newValue)
GLfloat max_flight_roll
Definition ShipEntity.h:229
void takeHeatDamage:(double amount)
ShipEntity * fireMissileWithIdentifier:andTarget:(NSString *identifier,[andTarget] Entity *target)
float afterburnerFactor()
BOOL _multiplyWeapons
Definition ShipEntity.h:379
void doScriptEvent:withArgument:(OOJSPropID message,[withArgument] id argument)
void resetShotTime()
GLfloat afterburner_rate
Definition ShipEntity.h:280
void processBehaviour:(OOTimeDelta delta_t)
float volume()
OOWeaponType port_weapon_type
Definition ShipEntity.h:296
Entity< OOBeaconEntity > * nextBeacon()
double maxHyperspaceDistance()
BOOL isVisible()
OOCargoQuantity max_cargo
Definition ShipEntity.h:284
void setDemoShip:(OOScalar demoRate)
void dealloc()
Definition ShipEntity.m:986
void setBehaviour:(OOBehaviour cond)
NSUInteger maxShipSubEntities()
Definition ShipEntity.m:734
BOOL hasHyperspaceMotor()
OOAegisStatus checkForAegis()
unsigned isHulk
OOMesh * mesh()
GLfloat fuelChargeRate()
Triangle absoluteIJKForSubentity()
BOOL scriptedMisjump()
void becomeExplosion()
GLfloat fuel_accumulator
Definition ShipEntity.h:278
void setCommodity:andAmount:(OOCommodityType co_type,[andAmount] OOCargoQuantity co_amount)
OOWeaponType forward_weapon_type
Definition ShipEntity.h:294
unsigned cloaking_device_active
Definition ShipEntity.h:254
GLfloat flightRoll
OOCargoQuantity extra_cargo
Definition ShipEntity.h:285
NSMutableArray * subEntities
GLfloat scannerRange
GLfloat maxFlightSpeed
BOOL isCloaked()
OOCommodityType commodityType()
void setOwner:(Entity *who_owns_entity)
BoundingBox findSubentityBoundingBox()
BOOL hasExpandedCargoBay()
NSString * displayName
NSUInteger countEquipmentItem:(NSString *eqkey)
OOWeakReference * _foundTarget
Definition ShipEntity.h:428
BOOL hasCloakingDevice()
Entity * foundTarget()
GLfloat hullHeatLevel()
GLfloat flightYaw
void setShipUniqueName:(NSString *inName)
Vector v_right
Definition ShipEntity.h:189
void setShipClassName:(NSString *inName)
OOCommodityMarket * localMarket
OOCommodityMarket * initialiseLocalMarket()
void autoDockShipsOnApproach()
OOCreditsQuantity legalStatusOfManifest:export:(OOCommodityMarket *manifest,[export] BOOL export)
void launchShip:(ShipEntity *ship)
NSMutableDictionary * localInterfaces
NSString * acceptDockingClearanceRequestFrom:(ShipEntity *other)
OOTechLevelID equivalentTechLevel
unsigned allowsSaving
void noteDockedShip:(ShipEntity *ship)
float equipmentPriceFactor
void clearDockingCorridor()
double estimatedArrivalTime()
OOSystemID destination
void setContainsPlayer:(BOOL val)
void setExitPosition:(HPVector pos)
void setMisjumpWithRange:(GLfloat range)
NSDictionary * getDict()
void setScannedAt:(double time)
void setExitSpeed:(double speed)
void setScanInfo:(WORMHOLE_SCANINFO scanInfo)
voidpf uLong offset
Definition ioapi.h:132
typedef int(ZCALLBACK *close_file_func) OF((voidpf opaque
const char int mode
Definition ioapi.h:125
float randf(void)
void clear_checksum()
RANROTSeed RANROTGetFullSeed(void)
void setRandomSeed(RNG_Seed a_seed)
int16_t munge_checksum(long long value_)
RNG_Seed currentRandomSeed(void)
void RANROTSetFullSeed(RANROTSeed seed)
double cunningFee(double value, double precision)
unsigned Ranrot(void)
#define ranrot_rand()
OOINLINE double distanceBetweenPlanetPositions(int x1, int y1, int x2, int y2) INLINE_CONST_FUNC
OOHPScalar x
Definition OOHPVector.h:36
OOHPScalar y
Definition OOHPVector.h:37
OOHPScalar z
Definition OOHPVector.h:38
OOScalar m[4][4]
Definition OOMatrix.h:31
OOScalar w
OOScalar z
Definition OOVector.h:34