Oolite
Loading...
Searching...
No Matches
PlayerEntityContracts.m
Go to the documentation of this file.
1/*
2
3PlayerEntityContracts.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
26#import "HeadUpDisplay.h"
27#import "PlayerEntity.h"
30#import "ProxyPlayerEntity.h"
31
32#import "AI.h"
33#import "GuiDisplayGen.h"
34#import "MyOpenGLView.h"
36#import "OOCharacter.h"
38#import "OOColor.h"
39#import "OOConstToString.h"
40#import "OOEquipmentType.h"
41#import "OOJavaScriptEngine.h"
42#import "OOShipRegistry.h"
43#import "OOStringExpander.h"
44#import "OOStringParsing.h"
45#import "OOTexture.h"
46#import "ShipEntityAI.h"
47#import "StationEntity.h"
48#import "Universe.h"
49
50static unsigned RepForRisk(unsigned risk);
51
52@interface PlayerEntity (ContractsPrivate)
53
55- (NSArray*)contractsListFromArray:(NSArray*)contracts_array forCargo:(BOOL)forCargo forParcels:(BOOL)forParcels;
56
57@end
58
59@implementation PlayerEntity (Contracts)
60
61- (NSString*)processEscapePods // removes pods from cargo bay and treats categories of characters carried
62{
63 unsigned i;
64 BOOL added_entry = NO; // to prevent empty lines for slaves and the rare empty report.
65 NSMutableString* result = [NSMutableString string];
66 NSMutableArray* rescuees = [NSMutableArray array];
67 OOGovernmentID government = [[[UNIVERSE currentSystemData] objectForKey:KEY_GOVERNMENT] intValue];
68 if ([UNIVERSE inInterstellarSpace])
69 government = 1; // equivalent to Feudal. I'm assuming any station in interstellar space is military. -- Ahruman 2008-05-29
70
71 // step through the cargo removing crew from any escape pods
72 // No enumerator because we're mutating the array -- Ahruman
73 for (i = 0; i < [cargo count]; i++) {
74 ShipEntity* cargoItem = [cargo objectAtIndex:i];
75 NSArray* podCrew = [cargoItem crew];
76
77 if (podCrew != nil) {
78 // Has crew -> is escape pod.
79 [rescuees addObjectsFromArray:podCrew];
80 [cargoItem setCrew:nil];
81 [cargo removeObjectAtIndex:i];
82 i--;
83 }
84 }
85
86 // step through the rescuees awarding insurance or bounty or adding to slaves
87 for (i = 0; i < [rescuees count]; i++) {
88 OOCharacter* rescuee = [rescuees objectAtIndex:i];
89
90 if ([rescuee script]) {
91 [rescuee doScriptEvent:OOJSID("unloadCharacter")];
92 } else if ([rescuee legacyScript]) {
95 withContextName:[NSString stringWithFormat:@"<character \"%@\" script>", [rescuee name]]
96 forTarget:nil];
97 } else if ([rescuee insuranceCredits] && [rescuee legalStatus]) {
98 float reward = (5.0 + government) * [rescuee legalStatus];
99 float insurance = 10 * [rescuee insuranceCredits];
100 if (government > (Ranrot() & 7) || reward >= insurance) {
101 // claim bounty for capture, ignore insurance
102 [result appendFormat:DESC(@"capture-reward-for-@@-@-credits-@-alt"),
103 [rescuee name], [rescuee shortDescription], OOStringFromDeciCredits(reward, YES, NO),
104 OOStringFromDeciCredits(insurance, YES, NO)];
105 [self doScriptEvent:OOJSID("playerRescuedEscapePod") withArguments:[NSArray arrayWithObjects:[NSNumber numberWithUnsignedInteger:reward], @"bounty", [rescuee infoForScripting], nil]];
106 } else {
107 // claim insurance reward with reduction of bounty
108 [result appendFormat:DESC(@"rescue-reward-for-@@-@-credits-@-alt"),
109 [rescuee name], [rescuee shortDescription], OOStringFromDeciCredits(insurance - reward, YES, NO),
110 OOStringFromDeciCredits(reward, YES, NO)];
111 reward = insurance - reward;
112 [self doScriptEvent:OOJSID("playerRescuedEscapePod") withArguments:[NSArray arrayWithObjects:[NSNumber numberWithUnsignedInteger:reward], @"insurance", [rescuee infoForScripting], nil]];
113 }
114 credits += reward;
115 added_entry = YES;
116 } else if ([rescuee insuranceCredits]) {
117 // claim insurance reward
118 [result appendFormat:DESC(@"rescue-reward-for-@@-@-credits"),
119 [rescuee name], [rescuee shortDescription], OOStringFromDeciCredits([rescuee insuranceCredits] * 10, YES, NO)];
120 credits += 10 * [rescuee insuranceCredits];
121 [self doScriptEvent:OOJSID("playerRescuedEscapePod") withArguments:[NSArray arrayWithObjects:[NSNumber numberWithUnsignedInteger:(10 * [rescuee insuranceCredits])], @"insurance", [rescuee infoForScripting], nil]];
122
123 added_entry = YES;
124 } else if ([rescuee legalStatus]) {
125 // claim bounty for capture
126 float reward = (5.0 + government) * [rescuee legalStatus];
127 [result appendFormat:DESC(@"capture-reward-for-@@-@-credits"),
128 [rescuee name], [rescuee shortDescription], OOStringFromDeciCredits(reward, YES, NO)];
129 credits += reward;
130 [self doScriptEvent:OOJSID("playerRescuedEscapePod") withArguments:[NSArray arrayWithObjects:[NSNumber numberWithUnsignedInteger:reward], @"bounty", [rescuee infoForScripting], nil]];
131 added_entry = YES;
132 } else {
133 // sell as slave - increase no. of slaves in manifest
134 [shipCommodityData addQuantity:1 forGood:@"slaves"];
135 [self doScriptEvent:OOJSID("playerRescuedEscapePod") withArguments:[NSArray arrayWithObjects:[NSNumber numberWithUnsignedInteger:0], @"slave", [rescuee infoForScripting], nil]];
136 }
137 if ((i < [rescuees count] - 1) && added_entry)
138 [result appendString:@"\n"];
139 added_entry = NO;
140 }
141
143
144 return result;
145}
146
147- (NSString*)checkPassengerContracts // returns messages from any passengers whose status have changed
148{
149 if ([self dockedStation] != [UNIVERSE station]) // only drop off passengers or fulfil contracts at main station
150 return nil;
151
152 // check escape pods...
153 // TODO
154
155 NSMutableString* result = [NSMutableString string];
156 unsigned i;
157
158 // check passenger contracts
159 for (i = 0; i < [passengers count]; i++) {
160 NSDictionary* passenger_info = [[passengers oo_dictionaryAtIndex:i] retain];
161 NSString* passenger_name = [passenger_info oo_stringForKey:PASSENGER_KEY_NAME];
162 int dest = [passenger_info oo_intForKey:CONTRACT_KEY_DESTINATION];
163 // the system name can change via script
164 NSString* passenger_dest_name = [UNIVERSE getSystemName:dest];
165 int dest_eta = [passenger_info oo_doubleForKey:CONTRACT_KEY_ARRIVAL_TIME] - ship_clock;
166
167 if (system_id == dest) {
168 // we've arrived in system!
169 if (dest_eta > 0) {
170 // and in good time
171 long long fee = [passenger_info oo_longLongForKey:CONTRACT_KEY_FEE];
172 while ((randf() < 0.75) && (dest_eta > 3600)) // delivered with more than an hour to spare and a decent customer?
173 {
174 fee *= 110; // tip + 10%
175 fee /= 100;
176 dest_eta *= 0.5;
177 }
178 credits += 10 * fee;
179
180 [result appendFormatLine:DESC(@"passenger-delivered-okay-@-@-@"), passenger_name, OOIntCredits(fee), passenger_dest_name];
181 if ([passenger_info oo_unsignedIntForKey:CONTRACT_KEY_RISK defaultValue:0] > 0) {
182 [self addRoleToPlayer:@"trader-courier+"];
183 }
184
185 [self increasePassengerReputation:RepForRisk([passenger_info oo_unsignedIntForKey:CONTRACT_KEY_RISK defaultValue:0])];
186 [passengers removeObjectAtIndex:i--];
187 [self doScriptEvent:OOJSID("playerCompletedContract") withArguments:[NSArray arrayWithObjects:@"passenger", @"success", [NSNumber numberWithUnsignedInteger:(10 * fee)], passenger_info, nil]];
188 } else {
189 // but we're late!
190 long long fee = [passenger_info oo_longLongForKey:CONTRACT_KEY_FEE] / 2; // halve fare
191 while (randf() < 0.5) // maybe halve fare a few times!
192 fee /= 2;
193 credits += 10 * fee;
194
195 [result appendFormatLine:DESC(@"passenger-delivered-late-@-@-@"), passenger_name, OOIntCredits(fee), passenger_dest_name];
196 if ([passenger_info oo_unsignedIntForKey:CONTRACT_KEY_RISK defaultValue:0] > 0) {
197 [self addRoleToPlayer:@"trader-courier+"];
198 }
199
200 [passengers removeObjectAtIndex:i--];
201 [self doScriptEvent:OOJSID("playerCompletedContract") withArguments:[NSArray arrayWithObjects:@"passenger", @"late", [NSNumber numberWithUnsignedInteger:10 * fee], passenger_info, nil]];
202 }
203 } else {
204 if (dest_eta < 0) {
205 // we've run out of time!
206 [result appendFormatLine:DESC(@"passenger-failed-@"), passenger_name];
207
208 [self decreasePassengerReputation:RepForRisk([passenger_info oo_unsignedIntForKey:CONTRACT_KEY_RISK defaultValue:0])];
209 [passengers removeObjectAtIndex:i--];
210 [self doScriptEvent:OOJSID("playerCompletedContract") withArguments:[NSArray arrayWithObjects:@"passenger", @"failed", [NSNumber numberWithUnsignedInteger:0], passenger_info, nil]];
211 }
212 }
213 [passenger_info release];
214 }
215
216 // check parcel contracts
217 for (i = 0; i < [parcels count]; i++) {
218 NSDictionary* parcel_info = [[parcels oo_dictionaryAtIndex:i] retain];
219 NSString* parcel_name = [parcel_info oo_stringForKey:PASSENGER_KEY_NAME];
220 int dest = [parcel_info oo_intForKey:CONTRACT_KEY_DESTINATION];
221 int dest_eta = [parcel_info oo_doubleForKey:CONTRACT_KEY_ARRIVAL_TIME] - ship_clock;
222
223 if (system_id == dest) {
224 // we've arrived in system!
225 if (dest_eta > 0) {
226 // and in good time
227 long long fee = [parcel_info oo_longLongForKey:CONTRACT_KEY_FEE];
228 while ((randf() < 0.75) && (dest_eta > 86400)) // delivered with more than a day to spare and a decent customer?
229 {
230 // lower tips than passengers
231 fee *= 110; // tip + 10%
232 fee /= 100;
233 dest_eta *= 0.5;
234 }
235 credits += 10 * fee;
236
237 [result appendFormatLine:DESC(@"parcel-delivered-okay-@-@"), parcel_name, OOIntCredits(fee)];
238
239 [self increaseParcelReputation:RepForRisk([parcel_info oo_unsignedIntForKey:CONTRACT_KEY_RISK defaultValue:0])];
240
241 [parcels removeObjectAtIndex:i--];
242 if ([parcel_info oo_unsignedIntForKey:CONTRACT_KEY_RISK defaultValue:0] > 0) {
243 [self addRoleToPlayer:@"trader-courier+"];
244 }
245 [self doScriptEvent:OOJSID("playerCompletedContract") withArguments:[NSArray arrayWithObjects:@"parcel", @"success", [NSNumber numberWithUnsignedInteger:10 * fee], parcel_info, nil]];
246
247 } else {
248 // but we're late!
249 long long fee = [parcel_info oo_longLongForKey:CONTRACT_KEY_FEE] / 2; // halve fare
250 while (randf() < 0.5) // maybe halve fare a few times!
251 fee /= 2;
252 credits += 10 * fee;
253
254 [result appendFormatLine:DESC(@"parcel-delivered-late-@-@"), parcel_name, OOIntCredits(fee)];
255 if ([parcel_info oo_unsignedIntForKey:CONTRACT_KEY_RISK defaultValue:0] > 0) {
256 [self addRoleToPlayer:@"trader-courier+"];
257 }
258 [parcels removeObjectAtIndex:i--];
259 [self doScriptEvent:OOJSID("playerCompletedContract") withArguments:[NSArray arrayWithObjects:@"parcel", @"late", [NSNumber numberWithUnsignedInteger:10 * fee], parcel_info, nil]];
260 }
261 } else {
262 if (dest_eta < 0) {
263 // we've run out of time!
264 [result appendFormatLine:DESC(@"parcel-failed-@"), parcel_name];
265
266 [self decreaseParcelReputation:RepForRisk([parcel_info oo_unsignedIntForKey:CONTRACT_KEY_RISK defaultValue:0])];
267 [parcels removeObjectAtIndex:i--];
268 [self doScriptEvent:OOJSID("playerCompletedContract") withArguments:[NSArray arrayWithObjects:@"parcel", @"failed", [NSNumber numberWithUnsignedInteger:0], parcel_info, nil]];
269 }
270 }
271 [parcel_info release];
272 }
273
274 // check cargo contracts
275 for (i = 0; i < [contracts count]; i++) {
276 NSDictionary* contract_info = [[contracts oo_dictionaryAtIndex:i] retain];
277 NSString* contract_cargo_desc = [contract_info oo_stringForKey:CARGO_KEY_DESCRIPTION];
278 int dest = [contract_info oo_intForKey:CONTRACT_KEY_DESTINATION];
279 int dest_eta = [contract_info oo_doubleForKey:CONTRACT_KEY_ARRIVAL_TIME] - ship_clock;
280
281 if (system_id == dest) {
282 // no longer needed
283 // int premium = 10 * [contract_info oo_floatForKey:CONTRACT_KEY_PREMIUM];
284 int fee = 10 * [contract_info oo_floatForKey:CONTRACT_KEY_FEE];
285
286 OOCommodityType contract_cargo_type = [contract_info oo_stringForKey:CARGO_KEY_TYPE];
287 int contract_amount = [contract_info oo_intForKey:CARGO_KEY_AMOUNT];
288
289 int quantity_on_hand = [shipCommodityData quantityForGood:contract_cargo_type];
290
291 // we've arrived in system!
292 if (dest_eta > 0) {
293 // and in good time
294 if (quantity_on_hand >= contract_amount) {
295 // with the goods too!
296
297 // remove the goods...
298 [shipCommodityData removeQuantity:contract_amount forGood:contract_cargo_type];
299
300 // pay the premium and fee
301 // credits += fee + premium;
302 // not any more: all contracts initially awarded by JS, so fee
303 // is now all that needs to be paid - CIM
304
305 if ([shipCommodityData exportLegalityForGood:contract_cargo_type] > 0) {
306 [self addRoleToPlayer:@"trader-smuggler"];
307 } else {
308 [self addRoleToPlayer:@"trader"];
309 }
310
311 credits += fee;
312 [result appendFormatLine:DESC(@"cargo-delivered-okay-@-@"), contract_cargo_desc, OOCredits(fee)];
313
314 [contracts removeObjectAtIndex:i--];
315 // repute++
316 // +10 as cargo contracts don't have risk modifiers
318 [self doScriptEvent:OOJSID("playerCompletedContract") withArguments:[NSArray arrayWithObjects:@"cargo", @"success", [NSNumber numberWithUnsignedInteger:fee], contract_info, nil]];
319
320 } else {
321 // see if the amount of goods delivered is acceptable
322
323 float percent_delivered = 100.0 * (float)quantity_on_hand / (float)contract_amount;
324 float acceptable_ratio = 100.0 - 10.0 * system_id / 256.0; // down to 90%
325
326 if (percent_delivered >= acceptable_ratio) {
327 // remove the goods...
328 [shipCommodityData setQuantity:0 forGood:contract_cargo_type];
329
330 // pay the fee
331 int shortfall = 100 - percent_delivered;
332 int payment = percent_delivered * (fee) / 100.0;
333 credits += payment;
334
335 if ([shipCommodityData exportLegalityForGood:contract_cargo_type] > 0) {
336 [self addRoleToPlayer:@"trader-smuggler"];
337 } else {
338 [self addRoleToPlayer:@"trader"];
339 }
340
341 [result appendFormatLine:DESC(@"cargo-delivered-short-@-@-d"), contract_cargo_desc, OOCredits(payment), shortfall];
342
343 [contracts removeObjectAtIndex:i--];
344 // repute unchanged
345 [self doScriptEvent:OOJSID("playerCompletedContract") withArguments:[NSArray arrayWithObjects:@"cargo", @"short", [NSNumber numberWithUnsignedInteger:payment], contract_info, nil]];
346
347 } else {
348 [result appendFormatLine:DESC(@"cargo-refused-short-%@"), contract_cargo_desc];
349 // The player has still time to buy the missing goods elsewhere and fulfil the contract.
350 }
351 }
352 } else {
353 // but we're late!
354 [result appendFormatLine:DESC(@"cargo-delivered-late-@"), contract_cargo_desc];
355
356 [contracts removeObjectAtIndex:i--];
357 // repute--
359 [self doScriptEvent:OOJSID("playerCompletedContract") withArguments:[NSArray arrayWithObjects:@"cargo", @"late", [NSNumber numberWithUnsignedInteger:0], contract_info, nil]];
360 }
361 } else {
362 if (dest_eta < 0) {
363 // we've run out of time!
364 [result appendFormatLine:DESC(@"cargo-failed-@"), contract_cargo_desc];
365
366 [contracts removeObjectAtIndex:i--];
367 // repute--
369 [self doScriptEvent:OOJSID("playerCompletedContract") withArguments:[NSArray arrayWithObjects:@"cargo", @"failed", [NSNumber numberWithUnsignedInteger:0], contract_info, nil]];
370 }
371 }
372 [contract_info release];
373 }
374
375 // check passenger_record for expired contracts
376 NSArray* names = [passenger_record allKeys];
377 for (i = 0; i < [names count]; i++) {
378 double dest_eta = [passenger_record oo_doubleForKey:[names objectAtIndex:i]] - ship_clock;
379 if (dest_eta < 0) {
380 // check they're not STILL on board
381 BOOL on_board = NO;
382 unsigned j;
383 for (j = 0; j < [passengers count]; j++) {
384 NSDictionary* passenger_info = [passengers oo_dictionaryAtIndex:j];
385 if ([[passenger_info objectForKey:PASSENGER_KEY_NAME] isEqual:[names objectAtIndex:i]])
386 on_board = YES;
387 }
388 if (!on_board) {
389 [passenger_record removeObjectForKey:[names objectAtIndex:i]];
390 }
391 }
392 }
393
394 // check contract_record for expired contracts
395 NSArray* ids = [contract_record allKeys];
396 for (i = 0; i < [ids count]; i++) {
397 double dest_eta = [(NSNumber*)[contract_record objectForKey:[ids objectAtIndex:i]] doubleValue] - ship_clock;
398 if (dest_eta < 0) {
399 [contract_record removeObjectForKey:[ids objectAtIndex:i]];
400 }
401 }
402
403 // check parcel_record for expired deliveries
404 ids = [parcel_record allKeys];
405 for (i = 0; i < [ids count]; i++) {
406 double dest_eta = [(NSNumber*)[parcel_record objectForKey:[ids objectAtIndex:i]] doubleValue] - ship_clock;
407 if (dest_eta < 0) {
408 [parcel_record removeObjectForKey:[ids objectAtIndex:i]];
409 }
410 }
411
412 if ([result length] == 0) {
413 result = nil;
414 } else {
415 // Should have a trailing \n
416 [result deleteCharacterAtIndex:[result length] - 1];
417 }
418
419 return result;
420}
421
422- (OOCargoQuantity)contractedVolumeForGood:(OOCommodityType)good
423{
424 OOCargoQuantity total = 0;
425 for (unsigned i = 0; i < [contracts count]; i++) {
426 NSDictionary* contract_info = [contracts oo_dictionaryAtIndex:i];
427 OOCommodityType contract_cargo_type = [contract_info oo_stringForKey:CARGO_KEY_TYPE];
428 if ([good isEqualToString:contract_cargo_type]) {
429 total += [contract_info oo_unsignedIntegerForKey:CARGO_KEY_AMOUNT];
430 }
431 }
432 return total;
433}
434
435- (void)addMessageToReport:(NSString*)report
436{
437 if ([report length] != 0) {
438 if ([dockingReport length] == 0)
439 [dockingReport appendString:report];
440 else
441 [dockingReport appendFormat:@"\n\n%@", report];
442 }
443}
444
445- (NSDictionary*)reputation
446{
447 return reputation;
448}
449
451{
452 int good = [reputation oo_intForKey:PASSAGE_GOOD_KEY];
453 int bad = [reputation oo_intForKey:PASSAGE_BAD_KEY];
454 int unknown = [reputation oo_intForKey:PASSAGE_UNKNOWN_KEY];
455
456 if (unknown > 0)
457 unknown = MAX_CONTRACT_REP - (((2 * unknown) + (market_rnd % unknown)) / 3);
458 else
459 unknown = MAX_CONTRACT_REP;
460
461 return (good + unknown - 3 * bad) / 2; // return a number from -MAX_CONTRACT_REP to +MAX_CONTRACT_REP
462}
463
464- (void)increasePassengerReputation:(unsigned)amount
465{
466 int good = [reputation oo_intForKey:PASSAGE_GOOD_KEY];
467 int bad = [reputation oo_intForKey:PASSAGE_BAD_KEY];
468 int unknown = [reputation oo_intForKey:PASSAGE_UNKNOWN_KEY];
469
470 for (unsigned i = 0; i < amount; i++) {
471 if (bad > 0) {
472 // shift a bean from bad to unknown
473 bad--;
474 if (unknown < MAX_CONTRACT_REP)
475 unknown++;
476 } else {
477 // shift a bean from unknown to good
478 if (unknown > 0)
479 unknown--;
480 if (good < MAX_CONTRACT_REP)
481 good++;
482 }
483 }
484 [reputation oo_setInteger:good forKey:PASSAGE_GOOD_KEY];
485 [reputation oo_setInteger:bad forKey:PASSAGE_BAD_KEY];
486 [reputation oo_setInteger:unknown forKey:PASSAGE_UNKNOWN_KEY];
487}
488
489- (void)decreasePassengerReputation:(unsigned)amount
490{
491 int good = [reputation oo_intForKey:PASSAGE_GOOD_KEY];
492 int bad = [reputation oo_intForKey:PASSAGE_BAD_KEY];
493 int unknown = [reputation oo_intForKey:PASSAGE_UNKNOWN_KEY];
494
495 for (unsigned i = 0; i < amount; i++) {
496 if (good > 0) {
497 // shift a bean from good to bad
498 good--;
499 if (bad < MAX_CONTRACT_REP)
500 bad++;
501 } else {
502 // shift a bean from unknown to bad
503 if (unknown > 0)
504 unknown--;
505 if (bad < MAX_CONTRACT_REP)
506 bad++;
507 }
508 }
509 [reputation oo_setInteger:good forKey:PASSAGE_GOOD_KEY];
510 [reputation oo_setInteger:bad forKey:PASSAGE_BAD_KEY];
511 [reputation oo_setInteger:unknown forKey:PASSAGE_UNKNOWN_KEY];
512}
513
515{
516 int good = [reputation oo_intForKey:PARCEL_GOOD_KEY];
517 int bad = [reputation oo_intForKey:PARCEL_BAD_KEY];
518 int unknown = [reputation oo_intForKey:PARCEL_UNKNOWN_KEY];
519
520 if (unknown > 0)
521 unknown = MAX_CONTRACT_REP - (((2 * unknown) + (market_rnd % unknown)) / 3);
522 else
523 unknown = MAX_CONTRACT_REP;
524
525 return (good + unknown - 3 * bad) / 2; // return a number from -MAX_CONTRACT_REP to +MAX_CONTRACT_REP
526}
527
528- (void)increaseParcelReputation:(unsigned)amount
529{
530 int good = [reputation oo_intForKey:PARCEL_GOOD_KEY];
531 int bad = [reputation oo_intForKey:PARCEL_BAD_KEY];
532 int unknown = [reputation oo_intForKey:PARCEL_UNKNOWN_KEY];
533
534 for (unsigned i = 0; i < amount; i++) {
535 if (bad > 0) {
536 // shift a bean from bad to unknown
537 bad--;
538 if (unknown < MAX_CONTRACT_REP)
539 unknown++;
540 } else {
541 // shift a bean from unknown to good
542 if (unknown > 0)
543 unknown--;
544 if (good < MAX_CONTRACT_REP)
545 good++;
546 }
547 }
548 [reputation oo_setInteger:good forKey:PARCEL_GOOD_KEY];
549 [reputation oo_setInteger:bad forKey:PARCEL_BAD_KEY];
550 [reputation oo_setInteger:unknown forKey:PARCEL_UNKNOWN_KEY];
551}
552
553- (void)decreaseParcelReputation:(unsigned)amount
554{
555 int good = [reputation oo_intForKey:PARCEL_GOOD_KEY];
556 int bad = [reputation oo_intForKey:PARCEL_BAD_KEY];
557 int unknown = [reputation oo_intForKey:PARCEL_UNKNOWN_KEY];
558
559 for (unsigned i = 0; i < amount; i++) {
560 if (good > 0) {
561 // shift a bean from good to bad
562 good--;
563 if (bad < MAX_CONTRACT_REP)
564 bad++;
565 } else {
566 // shift a bean from unknown to bad
567 if (unknown > 0)
568 unknown--;
569 if (bad < MAX_CONTRACT_REP)
570 bad++;
571 }
572 }
573 [reputation oo_setInteger:good forKey:PARCEL_GOOD_KEY];
574 [reputation oo_setInteger:bad forKey:PARCEL_BAD_KEY];
575 [reputation oo_setInteger:unknown forKey:PARCEL_UNKNOWN_KEY];
576}
577
579{
580 int good = [reputation oo_intForKey:CONTRACTS_GOOD_KEY];
581 int bad = [reputation oo_intForKey:CONTRACTS_BAD_KEY];
582 int unknown = [reputation oo_intForKey:CONTRACTS_UNKNOWN_KEY];
583
584 if (unknown > 0)
585 unknown = MAX_CONTRACT_REP - (((2 * unknown) + (market_rnd % unknown)) / 3);
586 else
587 unknown = MAX_CONTRACT_REP;
588
589 return (good + unknown - 3 * bad) / 2; // return a number from -MAX_CONTRACT_REP to +MAX_CONTRACT_REP
590}
591
592- (void)increaseContractReputation:(unsigned)amount
593{
594 int good = [reputation oo_intForKey:CONTRACTS_GOOD_KEY];
595 int bad = [reputation oo_intForKey:CONTRACTS_BAD_KEY];
596 int unknown = [reputation oo_intForKey:CONTRACTS_UNKNOWN_KEY];
597
598 for (unsigned i = 0; i < amount; i++) {
599 if (bad > 0) {
600 // shift a bean from bad to unknown
601 bad--;
602 if (unknown < MAX_CONTRACT_REP)
603 unknown++;
604 } else {
605 // shift a bean from unknown to good
606 if (unknown > 0)
607 unknown--;
608 if (good < MAX_CONTRACT_REP)
609 good++;
610 }
611 }
612 [reputation oo_setInteger:good forKey:CONTRACTS_GOOD_KEY];
613 [reputation oo_setInteger:bad forKey:CONTRACTS_BAD_KEY];
614 [reputation oo_setInteger:unknown forKey:CONTRACTS_UNKNOWN_KEY];
615}
616
617- (void)decreaseContractReputation:(unsigned)amount
618{
619 int good = [reputation oo_intForKey:CONTRACTS_GOOD_KEY];
620 int bad = [reputation oo_intForKey:CONTRACTS_BAD_KEY];
621 int unknown = [reputation oo_intForKey:CONTRACTS_UNKNOWN_KEY];
622
623 for (unsigned i = 0; i < amount; i++) {
624 if (good > 0) {
625 // shift a bean from good to bad
626 good--;
627 if (bad < MAX_CONTRACT_REP)
628 bad++;
629 } else {
630 // shift a bean from unknown to bad
631 if (unknown > 0)
632 unknown--;
633 if (bad < MAX_CONTRACT_REP)
634 bad++;
635 }
636 }
637 [reputation oo_setInteger:good forKey:CONTRACTS_GOOD_KEY];
638 [reputation oo_setInteger:bad forKey:CONTRACTS_BAD_KEY];
639 [reputation oo_setInteger:unknown forKey:CONTRACTS_UNKNOWN_KEY];
640}
641
643{
644 int c_good = [reputation oo_intForKey:CONTRACTS_GOOD_KEY];
645 int c_bad = [reputation oo_intForKey:CONTRACTS_BAD_KEY];
646 int c_unknown = [reputation oo_intForKey:CONTRACTS_UNKNOWN_KEY];
647 int p_good = [reputation oo_intForKey:PASSAGE_GOOD_KEY];
648 int p_bad = [reputation oo_intForKey:PASSAGE_BAD_KEY];
649 int p_unknown = [reputation oo_intForKey:PASSAGE_UNKNOWN_KEY];
650 int pl_good = [reputation oo_intForKey:PARCEL_GOOD_KEY];
651 int pl_bad = [reputation oo_intForKey:PARCEL_BAD_KEY];
652 int pl_unknown = [reputation oo_intForKey:PARCEL_UNKNOWN_KEY];
653
654 if (c_unknown < MAX_CONTRACT_REP) {
655 if (c_bad > 0)
656 c_bad--;
657 else {
658 if (c_good > 0)
659 c_good--;
660 }
661 c_unknown++;
662 }
663
664 if (p_unknown < MAX_CONTRACT_REP) {
665 if (p_bad > 0)
666 p_bad--;
667 else {
668 if (p_good > 0)
669 p_good--;
670 }
671 p_unknown++;
672 }
673
674 if (pl_unknown < MAX_CONTRACT_REP) {
675 if (pl_bad > 0)
676 pl_bad--;
677 else {
678 if (pl_good > 0)
679 pl_good--;
680 }
681 pl_unknown++;
682 }
683
684 [reputation setObject:[NSNumber numberWithInt:c_good] forKey:CONTRACTS_GOOD_KEY];
685 [reputation setObject:[NSNumber numberWithInt:c_bad] forKey:CONTRACTS_BAD_KEY];
686 [reputation setObject:[NSNumber numberWithInt:c_unknown] forKey:CONTRACTS_UNKNOWN_KEY];
687 [reputation setObject:[NSNumber numberWithInt:p_good] forKey:PASSAGE_GOOD_KEY];
688 [reputation setObject:[NSNumber numberWithInt:p_bad] forKey:PASSAGE_BAD_KEY];
689 [reputation setObject:[NSNumber numberWithInt:p_unknown] forKey:PASSAGE_UNKNOWN_KEY];
690 [reputation setObject:[NSNumber numberWithInt:pl_good] forKey:PARCEL_GOOD_KEY];
691 [reputation setObject:[NSNumber numberWithInt:pl_bad] forKey:PARCEL_BAD_KEY];
692 [reputation setObject:[NSNumber numberWithInt:pl_unknown] forKey:PARCEL_UNKNOWN_KEY];
693}
694
695/* Update reputation levels in case of change in MAX_CONTRACT_REP */
697{
698 int c_good = [reputation oo_intForKey:CONTRACTS_GOOD_KEY];
699 int c_bad = [reputation oo_intForKey:CONTRACTS_BAD_KEY];
700 int c_unknown = [reputation oo_intForKey:CONTRACTS_UNKNOWN_KEY];
701 int p_good = [reputation oo_intForKey:PASSAGE_GOOD_KEY];
702 int p_bad = [reputation oo_intForKey:PASSAGE_BAD_KEY];
703 int p_unknown = [reputation oo_intForKey:PASSAGE_UNKNOWN_KEY];
704 int pl_good = [reputation oo_intForKey:PARCEL_GOOD_KEY];
705 int pl_bad = [reputation oo_intForKey:PARCEL_BAD_KEY];
706 int pl_unknown = [reputation oo_intForKey:PARCEL_UNKNOWN_KEY];
707
708 int c = c_good + c_bad + c_unknown;
709 if (c == 0) {
710 c_unknown = MAX_CONTRACT_REP;
711 } else if (c != MAX_CONTRACT_REP) {
712 c_good = c_good * MAX_CONTRACT_REP / c;
713 c_bad = c_bad * MAX_CONTRACT_REP / c;
714 c_unknown = MAX_CONTRACT_REP - c_good - c_bad;
715 }
716
717 int p = p_good + p_bad + p_unknown;
718 if (p == 0) {
719 p_unknown = MAX_CONTRACT_REP;
720 } else if (p != MAX_CONTRACT_REP) {
721 p_good = p_good * MAX_CONTRACT_REP / p;
722 p_bad = p_bad * MAX_CONTRACT_REP / p;
723 p_unknown = MAX_CONTRACT_REP - p_good - p_bad;
724 }
725
726 int pl = pl_good + pl_bad + pl_unknown;
727 if (pl == 0) {
728 pl_unknown = MAX_CONTRACT_REP;
729 } else if (pl != MAX_CONTRACT_REP) {
730 pl_good = pl_good * MAX_CONTRACT_REP / pl;
731 pl_bad = pl_bad * MAX_CONTRACT_REP / pl;
732 pl_unknown = MAX_CONTRACT_REP - pl_good - pl_bad;
733 }
734
735 [reputation setObject:[NSNumber numberWithInt:c_good] forKey:CONTRACTS_GOOD_KEY];
736 [reputation setObject:[NSNumber numberWithInt:c_bad] forKey:CONTRACTS_BAD_KEY];
737 [reputation setObject:[NSNumber numberWithInt:c_unknown] forKey:CONTRACTS_UNKNOWN_KEY];
738 [reputation setObject:[NSNumber numberWithInt:p_good] forKey:PASSAGE_GOOD_KEY];
739 [reputation setObject:[NSNumber numberWithInt:p_bad] forKey:PASSAGE_BAD_KEY];
740 [reputation setObject:[NSNumber numberWithInt:p_unknown] forKey:PASSAGE_UNKNOWN_KEY];
741 [reputation setObject:[NSNumber numberWithInt:pl_good] forKey:PARCEL_GOOD_KEY];
742 [reputation setObject:[NSNumber numberWithInt:pl_bad] forKey:PARCEL_BAD_KEY];
743 [reputation setObject:[NSNumber numberWithInt:pl_unknown] forKey:PARCEL_UNKNOWN_KEY];
744}
745
746- (BOOL)addPassenger:(NSString*)Name start:(unsigned)start destination:(unsigned)Destination eta:(double)eta fee:(double)fee advance:(double)advance risk:(unsigned)risk
747{
748 NSDictionary* passenger_info = [NSDictionary dictionaryWithObjectsAndKeys:
749 Name, PASSENGER_KEY_NAME,
750 [NSNumber numberWithInt:start], CONTRACT_KEY_START,
751 [NSNumber numberWithInt:Destination], CONTRACT_KEY_DESTINATION,
752 [NSNumber numberWithDouble:[PLAYER clockTime]], CONTRACT_KEY_DEPARTURE_TIME,
753 [NSNumber numberWithDouble:eta], CONTRACT_KEY_ARRIVAL_TIME,
754 [NSNumber numberWithDouble:fee], CONTRACT_KEY_FEE,
755 [NSNumber numberWithDouble:advance], CONTRACT_KEY_PREMIUM,
756 [NSNumber numberWithUnsignedInt:risk], CONTRACT_KEY_RISK,
757
758 NULL];
759
760 // extra checks, just in case.
761 if ([passengers count] >= max_passengers || [passenger_record objectForKey:Name] != nil)
762 return NO;
763
764 if (risk > 1) {
765 [self addRoleToPlayer:@"trader-courier+"];
766 }
767
768 [passengers addObject:passenger_info];
769 [passenger_record setObject:[NSNumber numberWithDouble:eta] forKey:Name];
770
771 [self doScriptEvent:OOJSID("playerEnteredContract") withArguments:[NSArray arrayWithObjects:@"passenger", passenger_info, nil]];
772
773 return YES;
774}
775
776- (BOOL)removePassenger:(NSString*)Name // removes the first passenger that answers to Name, returns NO if none found
777{
778 // extra check, just in case.
779 if ([passengers count] == 0)
780 return NO;
781
782 unsigned i;
783
784 for (i = 0; i < [passengers count]; i++) {
785 NSString* this_name = [[passengers oo_dictionaryAtIndex:i] oo_stringForKey:PASSENGER_KEY_NAME];
786
787 if ([Name isEqualToString:this_name]) {
788 [passengers removeObjectAtIndex:i];
789 [passenger_record removeObjectForKey:Name];
790 return YES;
791 }
792 }
793
794 return NO;
795}
796
797- (BOOL)addParcel:(NSString*)Name start:(unsigned)start destination:(unsigned)Destination eta:(double)eta fee:(double)fee premium:(double)premium risk:(unsigned)risk
798{
799 NSDictionary* parcel_info = [NSDictionary dictionaryWithObjectsAndKeys:
800 Name, PASSENGER_KEY_NAME,
801 [NSNumber numberWithInt:start], CONTRACT_KEY_START,
802 [NSNumber numberWithInt:Destination], CONTRACT_KEY_DESTINATION,
803 [NSNumber numberWithDouble:[PLAYER clockTime]], CONTRACT_KEY_DEPARTURE_TIME,
804 [NSNumber numberWithDouble:eta], CONTRACT_KEY_ARRIVAL_TIME,
805 [NSNumber numberWithDouble:fee], CONTRACT_KEY_FEE,
806 [NSNumber numberWithDouble:premium], CONTRACT_KEY_PREMIUM,
807 [NSNumber numberWithUnsignedInt:risk], CONTRACT_KEY_RISK,
808 NULL];
809
810 // extra checks, just in case.
811 // FIXME: do we absolutely need this check? can we live
812 // with parcels of senders who happen to have the same
813 // name? - Nikos 20160527
814 // if ([parcel_record objectForKey:Name] != nil) return NO;
815
816 if (risk > 1) {
817 [self addRoleToPlayer:@"trader-courier+"];
818 }
819
820 [parcels addObject:parcel_info];
821 [parcel_record setObject:[NSNumber numberWithDouble:eta] forKey:Name];
822
823 [self doScriptEvent:OOJSID("playerEnteredContract") withArguments:[NSArray arrayWithObjects:@"parcel", parcel_info, nil]];
824
825 return YES;
826}
827
828- (BOOL)removeParcel:(NSString*)Name // removes the first parcel that answers to Name, returns NO if none found
829{
830 // extra check, just in case.
831 if ([parcels count] == 0)
832 return NO;
833
834 unsigned i;
835
836 for (i = 0; i < [parcels count]; i++) {
837 NSString* this_name = [[parcels oo_dictionaryAtIndex:i] oo_stringForKey:PASSENGER_KEY_NAME];
838
839 if ([Name isEqualToString:this_name]) {
840 [parcels removeObjectAtIndex:i];
841 [parcel_record removeObjectForKey:Name];
842 return YES;
843 }
844 }
845
846 return NO;
847}
848
849- (BOOL)awardContract:(unsigned)qty commodity:(OOCommodityType)type start:(unsigned)start
850 destination:(unsigned)Destination
851 eta:(double)eta
852 fee:(double)fee
853 premium:(double)premium
854{
855
856 unsigned sr1 = Ranrot() & 0x111111;
857 int sr2 = Ranrot() & 0x111111;
858
859 NSString* cargo_ID = [NSString stringWithFormat:@"%06x-%06x", sr1, sr2];
860
861 if (![[UNIVERSE commodities] goodDefined:type])
862 return NO;
863 if (qty < 1)
864 return NO;
865
866 // avoid duplicate cargo_IDs
867 while ([contract_record objectForKey:cargo_ID] != nil) {
868 sr2++;
869 cargo_ID = [NSString stringWithFormat:@"%06x-%06x", sr1, sr2];
870 }
871
872 NSDictionary* cargo_info = [NSDictionary dictionaryWithObjectsAndKeys:
873 cargo_ID, CARGO_KEY_ID,
874 type, CARGO_KEY_TYPE,
875 [NSNumber numberWithInt:qty], CARGO_KEY_AMOUNT,
876 [UNIVERSE describeCommodity:type
877 amount:qty],
878 CARGO_KEY_DESCRIPTION,
879 [NSNumber numberWithInt:start], CONTRACT_KEY_START,
880 [NSNumber numberWithInt:Destination], CONTRACT_KEY_DESTINATION,
881 [NSNumber numberWithDouble:[PLAYER clockTime]], CONTRACT_KEY_DEPARTURE_TIME,
882 [NSNumber numberWithDouble:eta], CONTRACT_KEY_ARRIVAL_TIME,
883 [NSNumber numberWithDouble:fee], CONTRACT_KEY_FEE,
884 [NSNumber numberWithDouble:premium], CONTRACT_KEY_PREMIUM,
885 NULL];
886
887 // check available space
888
889 OOCargoQuantity cargoSpaceRequired = qty;
890 OOMassUnit contractCargoUnits = [shipCommodityData massUnitForGood:type];
891
892 if (contractCargoUnits == UNITS_KILOGRAMS)
893 cargoSpaceRequired /= 1000;
894 if (contractCargoUnits == UNITS_GRAMS)
895 cargoSpaceRequired /= 1000000;
896
897 if (cargoSpaceRequired > [self availableCargoSpace])
898 return NO;
899
900 [shipCommodityData addQuantity:qty forGood:type];
901
902 current_cargo = [self cargoQuantityOnBoard];
903
904 if ([shipCommodityData exportLegalityForGood:type] > 0) {
905 [self addRoleToPlayer:@"trader-smuggler"];
906 [roleWeightFlags setObject:[NSNumber numberWithInt:1] forKey:@"bought-illegal"];
907 } else {
908 [self addRoleToPlayer:@"trader"];
909 [roleWeightFlags setObject:[NSNumber numberWithInt:1] forKey:@"bought-legal"];
910 }
911
912 [contracts addObject:cargo_info];
913 [contract_record setObject:[NSNumber numberWithDouble:eta] forKey:cargo_ID];
914
915 [self doScriptEvent:OOJSID("playerEnteredContract") withArguments:[NSArray arrayWithObjects:@"cargo", cargo_info, nil]];
916
917 return YES;
918}
919
920- (BOOL)removeContract:(OOCommodityType)type destination:(unsigned)dest // removes the first match found, returns NO if none found
921{
922 if ([contracts count] == 0 || dest > 255)
923 return NO;
924
925 if (![[UNIVERSE commodities] goodDefined:type])
926 return NO;
927
928 unsigned i;
929
930 for (i = 0; i < [contracts count]; i++) {
931 NSDictionary* contractInfo = [contracts oo_dictionaryAtIndex:i];
932 unsigned cargoDest = [contractInfo oo_intForKey:CONTRACT_KEY_DESTINATION];
933 OOCommodityType cargoType = [contractInfo oo_stringForKey:CARGO_KEY_TYPE];
934
935 if ([cargoType isEqualToString:type] && cargoDest == dest) {
936 [contract_record removeObjectForKey:[contractInfo oo_stringForKey:CARGO_KEY_ID]];
937 [contracts removeObjectAtIndex:i];
938 return YES;
939 }
940 }
941
942 return NO;
943}
944
945- (NSArray*)passengerList
946{
947 return [self contractsListFromArray:passengers forCargo:NO forParcels:NO];
948}
949
950- (NSArray*)parcelList
951{
952 return [self contractsListFromArray:parcels forCargo:NO forParcels:YES];
953}
954
955- (NSArray*)contractList
956{
957 return [self contractsListFromArray:contracts forCargo:YES forParcels:NO];
958}
959
960- (NSArray*)contractsListFromArray:(NSArray*)contracts_array forCargo:(BOOL)forCargo forParcels:(BOOL)forParcels
961{
962 // check contracts
963 NSMutableArray* result = [NSMutableArray arrayWithCapacity:5];
964 NSString* formatString = (forCargo || forParcels) ? @"oolite-manifest-item-delivery" : @"oolite-manifest-person-travelling";
965 unsigned i;
966 for (i = 0; i < [contracts_array count]; i++) {
967 NSDictionary* contract_info = (NSDictionary*)[contracts_array objectAtIndex:i];
968 NSString* label = [contract_info oo_stringForKey:forCargo ? CARGO_KEY_DESCRIPTION : PASSENGER_KEY_NAME];
969 // the system name can change via script. The following PASSENGER_KEYs are identical to the corresponding CONTRACT_KEYs
970 NSString* destination = [UNIVERSE getSystemName:[contract_info oo_intForKey:CONTRACT_KEY_DESTINATION]];
971 int dest_eta = [contract_info oo_doubleForKey:CONTRACT_KEY_ARRIVAL_TIME] - ship_clock;
972 NSString* deadline = [UNIVERSE shortTimeDescription:dest_eta];
973
974 OOCreditsQuantity fee = [contract_info oo_intForKey:CONTRACT_KEY_FEE];
975 NSString* feeDesc = OOIntCredits(fee);
976
977 [result addObject:OOExpandKey(formatString, label, destination, deadline, feeDesc)];
978 }
979
980 return result;
981}
982
983// only use within setGuiToManifestScreen
984#define SET_MANIFEST_ROW(obj, color, row) ([self setManifestScreenRow:obj inColor:color forRow:row ofRows:max_rows andOffset:page_offset inMultipage:multi_page])
985
987{
988 OOGUIScreenID oldScreen = gui_screen;
989
990 GuiDisplayGen* gui = [UNIVERSE gui];
991 gui_screen = GUI_SCREEN_MANIFEST;
992 BOOL guiChanged = (oldScreen != gui_screen);
993 if (guiChanged) {
994 [gui setStatusPage:0]; // need to do this earlier than the rest
995 }
996
997 // GUI stuff
998 {
999 NSInteger current, max;
1000 OOColor* subheadColor = [gui colorFromSetting:kGuiManifestSubheadColor defaultValue:[OOColor greenColor]];
1001 OOColor* entryColor = [gui colorFromSetting:kGuiManifestEntryColor defaultValue:nil];
1002 OOColor* scrollColor = [gui colorFromSetting:kGuiManifestScrollColor defaultValue:[OOColor greenColor]];
1003 OOColor* noScrollColor = [gui colorFromSetting:kGuiManifestNoScrollColor defaultValue:[OOColor darkGrayColor]];
1004
1005 NSArray* cargoManifest = [self cargoList];
1006 NSArray* missionsManifest = [self missionsList];
1007
1008 NSUInteger i = 0;
1009 NSUInteger max_rows = 20;
1010 NSUInteger manifestCount = [cargoManifest count];
1011 NSUInteger cargoRowCount = (manifestCount + 1) / 2;
1012 OOGUIRow cargoRow = 2;
1013 OOGUIRow missionsRow = 2;
1014
1015 OOGUIRow nextPageRow = MANIFEST_SCREEN_ROW_NEXT;
1016 // show extra lines if no HUD is displayed.
1017 if ([[self hud] isHidden] || [[self hud] allowBigGui]) {
1018 max_rows += 7;
1019 nextPageRow += 7;
1020 }
1021
1022 NSUInteger mmRows = 0;
1023 id mmEntry = nil;
1024 foreach (mmEntry, missionsManifest) {
1025 if ([mmEntry isKindOfClass:[NSString class]]) {
1026 ++mmRows;
1027 } else if ([mmEntry isKindOfClass:[NSArray class]]) {
1028 mmRows += [(NSArray*)mmEntry count];
1029 }
1030 }
1031
1032 NSInteger page_offset = 0;
1033 BOOL multi_page = NO;
1034 // NSUInteger total_rows = cargoRowCount + MAX(1U,[passengerManifest count]) + MAX(1U,[contractManifest count]) + mmRows + MAX(1U,[parcelManifest count]) + 5;
1035 NSUInteger total_rows = cargoRowCount + mmRows + 5;
1036 if (total_rows > max_rows) {
1037 max_rows -= 2;
1038 page_offset = ([gui statusPage] - 1) * max_rows;
1039 if (page_offset < 0 || (NSUInteger)page_offset >= total_rows) {
1040 [gui setStatusPage:0];
1041 page_offset = 0;
1042 }
1043 multi_page = YES;
1044 }
1045
1046 OOGUITabSettings tab_stops;
1047 tab_stops[0] = 0;
1048 tab_stops[1] = 256;
1049 [gui overrideTabs:tab_stops from:kGuiManifestTabs length:3];
1050 [gui setTabStops:tab_stops];
1051
1052 // Cargo Manifest
1053 current_cargo = [self cargoQuantityOnBoard];
1054
1055 [gui clearAndKeepBackground:!guiChanged];
1056 [gui setTitle:DESC(@"manifest-title")];
1057
1058 current = current_cargo;
1059 max = [self maxAvailableCargoSpace];
1060 NSString* cargoString = OOExpandKey(@"oolite-manifest-cargo", current, max);
1061 current = [[self passengerList] count];
1062 max = max_passengers;
1063 NSString* cabinString = OOExpandKey(@"oolite-manifest-cabins", current, max);
1064 NSArray* manifestHeader = [NSArray arrayWithObjects:cargoString, cabinString, nil];
1065
1066 SET_MANIFEST_ROW(manifestHeader, entryColor, cargoRow - 1);
1067
1068 if (manifestCount > 0) {
1069 for (i = 0; i < cargoRowCount; i++) {
1070 NSMutableArray* row_info = [NSMutableArray arrayWithCapacity:3];
1071 // i is always smaller than manifest_count, no need to test.
1072 [row_info addObject:[cargoManifest objectAtIndex:i]];
1073 if (i + cargoRowCount < manifestCount) {
1074 [row_info addObject:[cargoManifest objectAtIndex:i + cargoRowCount]];
1075 } else {
1076 [row_info addObject:@""];
1077 }
1078 SET_MANIFEST_ROW((NSArray*)row_info, subheadColor, cargoRow + i);
1079 }
1080 } else {
1081 SET_MANIFEST_ROW((DESC(@"manifest-none")), subheadColor, cargoRow);
1082 cargoRowCount = 1;
1083 }
1084
1085 missionsRow = cargoRow + cargoRowCount + 1;
1086
1087 // Missions Manifest
1088 manifestCount = [missionsManifest count];
1089
1090 if (manifestCount > 0) {
1091 if ([[missionsManifest objectAtIndex:0] isKindOfClass:[NSString class]]) {
1092 // then there's at least one without its own heading
1093 // to go under the generic 'missions' heading
1094 SET_MANIFEST_ROW((DESC(@"manifest-missions")), entryColor, missionsRow - 1);
1095 } else {
1096 missionsRow--;
1097 }
1098
1099 NSUInteger mmRow = 0;
1100 for (i = 0; i < manifestCount; i++) {
1101 NSString* mmItem = nil;
1102 mmEntry = [missionsManifest objectAtIndex:i];
1103 if ([mmEntry isKindOfClass:[NSString class]]) {
1104 mmItem = [NSString stringWithFormat:@"\t%@", (NSString*)mmEntry];
1105 SET_MANIFEST_ROW((mmItem), subheadColor, missionsRow + mmRow);
1106 ++mmRow;
1107 } else if ([mmEntry isKindOfClass:[NSArray class]]) {
1108 BOOL isHeading = YES;
1109 foreach (mmItem, mmEntry) {
1110 if (isHeading) {
1111 SET_MANIFEST_ROW(((NSString*)mmItem), entryColor, missionsRow + mmRow);
1112 } else {
1113 mmItem = [NSString stringWithFormat:@"\t%@", (NSString*)mmItem];
1114 SET_MANIFEST_ROW(((NSString*)mmItem), subheadColor, missionsRow + mmRow);
1115 }
1116 isHeading = NO;
1117 ++mmRow;
1118 }
1119 }
1120 }
1121 }
1122
1123 if (multi_page) {
1125 OOGUIRow r_end = nextPageRow;
1126 if (page_offset > 0) {
1127 [gui setColor:scrollColor forRow:MANIFEST_SCREEN_ROW_BACK];
1128 [gui setKey:GUI_KEY_OK forRow:MANIFEST_SCREEN_ROW_BACK];
1129 } else {
1130 [gui setColor:noScrollColor forRow:MANIFEST_SCREEN_ROW_BACK];
1131 r_start = nextPageRow;
1132 }
1133 [gui setArray:[NSArray arrayWithObjects:DESC(@"gui-back"), @" <-- ", nil] forRow:MANIFEST_SCREEN_ROW_BACK];
1134
1135 if (total_rows > max_rows + page_offset) {
1136 [gui setColor:scrollColor forRow:nextPageRow];
1137 [gui setKey:GUI_KEY_OK forRow:nextPageRow];
1138 } else {
1139 [gui setColor:noScrollColor forRow:nextPageRow];
1141 }
1142 [gui setArray:[NSArray arrayWithObjects:DESC(@"gui-more"), @" --> ", nil] forRow:nextPageRow];
1143
1144 [gui setSelectableRange:NSMakeRange(r_start, r_end + 1 - r_start)];
1145 [gui setSelectedRow:r_start];
1146 }
1147
1149 }
1150 /* ends */
1151
1152 if (lastTextKey) {
1153 [lastTextKey release];
1154 lastTextKey = nil;
1155 }
1156
1157 [self setShowDemoShips:NO];
1158 [UNIVERSE enterGUIViewModeWithMouseInteraction:NO];
1159
1160 if (guiChanged) {
1161 [gui setForegroundTextureKey:[self status] == STATUS_DOCKED ? @"docked_overlay" : @"overlay"];
1162 [gui setBackgroundTextureKey:@"manifest"];
1163 [self noteGUIDidChangeFrom:oldScreen to:gui_screen];
1164 }
1165}
1166
1167- (void)setManifestScreenRow:(id)object inColor:(OOColor*)color forRow:(OOGUIRow)row ofRows:(OOGUIRow)max_rows andOffset:(OOGUIRow)offset inMultipage:(BOOL)multi
1168{
1169 OOGUIRow disp_row = row - offset;
1170 if (disp_row < 1 || disp_row > max_rows)
1171 return;
1172 if (multi)
1173 disp_row++;
1174 GuiDisplayGen* gui = [UNIVERSE gui];
1175 if ([object isKindOfClass:[NSString class]]) {
1176 [gui setText:(NSString*)object forRow:disp_row];
1177 } else if ([object isKindOfClass:[NSArray class]]) {
1178 [gui setArray:(NSArray*)object forRow:disp_row];
1179 }
1180 [gui setColor:color forRow:disp_row];
1181}
1182
1184{
1185 GuiDisplayGen* gui = [UNIVERSE gui];
1186
1187 OOGUIScreenID oldScreen = gui_screen;
1188 gui_screen = GUI_SCREEN_REPORT;
1189 BOOL guiChanged = (oldScreen != gui_screen);
1190
1191 OOGUIRow i, text_row = 1;
1192
1193 [dockingReport setString:[dockingReport stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
1194
1195 // GUI stuff
1196 {
1197 [gui clearAndKeepBackground:!guiChanged];
1198 [gui setTitle:OOExpandKey(@"arrival-report-title")];
1199
1200 for (i = 1; i <= 18; i++) {
1201 [gui setColor:[gui colorFromSetting:kGuiDockingReportColor defaultValue:nil] forRow:21];
1202 }
1203
1204 // dockingReport might be a multi-line message
1205
1206 while (([dockingReport length] > 0) && (text_row < 18)) {
1207 if ([dockingReport rangeOfString:@"\n"].location != NSNotFound) {
1208 while (([dockingReport rangeOfString:@"\n"].location != NSNotFound) && (text_row < 18)) {
1209 NSUInteger line_break = [dockingReport rangeOfString:@"\n"].location;
1210 NSString* line = [dockingReport substringToIndex:line_break];
1211 [dockingReport deleteCharactersInRange:NSMakeRange(0, line_break + 1)];
1212 text_row = [gui addLongText:line startingAtRow:text_row align:GUI_ALIGN_LEFT];
1213 }
1214 [dockingReport setString:[dockingReport stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
1215 } else {
1216 text_row = [gui addLongText:[NSString stringWithString:dockingReport] startingAtRow:text_row align:GUI_ALIGN_LEFT];
1217 [dockingReport setString:@""];
1218 }
1219 }
1220
1221 [gui setText:[NSString stringWithFormat:DESC_PLURAL(@"contracts-cash-@-load-d-of-d-passengers-d-of-d-berths", max_passengers), OOCredits(credits), current_cargo, [self maxAvailableCargoSpace], [passengers count], max_passengers] forRow:GUI_ROW_MARKET_CASH];
1222 [gui setColor:[gui colorFromSetting:kGuiDockingSummaryColor defaultValue:nil] forRow:GUI_ROW_MARKET_CASH];
1223
1224 [gui setText:DESC(@"press-space-commander") forRow:21 align:GUI_ALIGN_CENTER];
1225 [gui setColor:[gui colorFromSetting:kGuiDockingContinueColor defaultValue:nil] forRow:21];
1227 }
1228 /* ends */
1229
1230 if (lastTextKey) {
1231 [lastTextKey release];
1232 lastTextKey = nil;
1233 }
1234
1235 [self setShowDemoShips:NO];
1236 [UNIVERSE enterGUIViewModeWithMouseInteraction:NO];
1237
1238 if (guiChanged) {
1239 [gui setForegroundTextureKey:@"docked_overlay"]; // has to be docked!
1240
1241 NSDictionary* bgDescriptor = [UNIVERSE screenTextureDescriptorForKey:@"report"];
1242 if (bgDescriptor == nil)
1243 bgDescriptor = [UNIVERSE screenTextureDescriptorForKey:@"status_docked"];
1244 if (bgDescriptor == nil)
1245 bgDescriptor = [UNIVERSE screenTextureDescriptorForKey:@"status"];
1246 [gui setBackgroundTextureDescriptor:bgDescriptor];
1247 [self noteGUIDidChangeFrom:oldScreen to:gui_screen];
1248 }
1249}
1250
1251// ----------------------------------------------------------------------
1252
1253static NSMutableDictionary* currentShipyard = nil;
1254
1255- (OOCreditsQuantity)priceForShipKey:(NSString*)key
1256{
1257 NSDictionary* shipInfo = [currentShipyard oo_dictionaryForKey:key];
1258 return [shipInfo oo_unsignedLongLongForKey:SHIPYARD_KEY_PRICE];
1259}
1260
1261- (void)setGuiToShipyardScreen:(NSUInteger)skip
1262{
1263 OOGUIScreenID oldScreen = gui_screen;
1264
1265 GuiDisplayGen* gui = [UNIVERSE gui];
1266 gui_screen = GUI_SCREEN_SHIPYARD;
1267 BOOL guiChanged = (oldScreen != gui_screen);
1268
1269 unsigned i;
1270
1271 // set up initial market if there is none
1272 OOTechLevelID stationTechLevel;
1273 StationEntity* station = [self dockedStation];
1274
1275 if (station != nil) {
1276 stationTechLevel = [station equivalentTechLevel];
1277 } else {
1278 station = [UNIVERSE station];
1279 stationTechLevel = NSNotFound;
1280 }
1281 if ([station localShipyard] == nil) {
1282 [station generateShipyard:stationTechLevel];
1283 }
1284
1285 NSMutableArray* shipyard = [station localShipyard];
1286
1287 [currentShipyard release];
1288 currentShipyard = [[NSMutableDictionary alloc] initWithCapacity:[shipyard count]];
1289
1290 for (i = 0; i < [shipyard count]; i++) {
1291 [currentShipyard setObject:[shipyard objectAtIndex:i]
1292 forKey:[[shipyard oo_dictionaryAtIndex:i] oo_stringForKey:SHIPYARD_KEY_ID]];
1293 }
1294
1295 NSUInteger shipCount = [shipyard count];
1296
1297 // error check
1298 if (skip >= shipCount)
1299 skip = shipCount - 1;
1300 if (skip < 2)
1301 skip = 0;
1302
1303 // GUI stuff
1304 {
1305 [gui clearAndKeepBackground:!guiChanged];
1306 NSString* system = [UNIVERSE getSystemName:system_id];
1307 [gui setTitle:OOExpandKey(@"shipyard-title", system)];
1308
1309 OOGUITabSettings tab_stops;
1310 tab_stops[0] = 0;
1311 tab_stops[1] = -258;
1312 tab_stops[2] = 270;
1313 tab_stops[3] = 370;
1314 tab_stops[4] = 450;
1315 [gui overrideTabs:tab_stops from:kGuiShipyardTabs length:5];
1316 [gui setTabStops:tab_stops];
1317
1318 int rowCount = MAX_ROWS_SHIPS_FOR_SALE;
1319 int startRow = GUI_ROW_SHIPYARD_START;
1320 NSInteger previous = 0;
1321
1322 if (shipCount <= MAX_ROWS_SHIPS_FOR_SALE)
1323 skip = 0;
1324 else {
1325 if (skip > 0) {
1326 rowCount -= 1;
1327 startRow += 1;
1328 previous = skip - MAX_ROWS_SHIPS_FOR_SALE + 2;
1329 if (previous < 2)
1330 previous = 0;
1331 }
1332 if (skip + rowCount < shipCount)
1333 rowCount -= 1;
1334 }
1335
1336 if (shipCount > 0) {
1337 [gui setColor:[gui colorFromSetting:kGuiShipyardHeadingColor defaultValue:[OOColor greenColor]] forRow:GUI_ROW_SHIPYARD_LABELS];
1338 [gui setArray:[NSArray arrayWithObjects:DESC(@"shipyard-shiptype"), DESC(@"shipyard-price-label"),
1339 DESC(@"shipyard-cargo-label"), DESC(@"shipyard-speed-label"), nil]
1340 forRow:GUI_ROW_SHIPYARD_LABELS];
1341
1342 if (skip > 0) {
1343 [gui setColor:[gui colorFromSetting:kGuiShipyardScrollColor defaultValue:[OOColor greenColor]] forRow:GUI_ROW_SHIPYARD_START];
1344 [gui setArray:[NSArray arrayWithObjects:DESC(@"gui-back"), @" <-- ", nil] forRow:GUI_ROW_SHIPYARD_START];
1345 [gui setKey:[NSString stringWithFormat:@"More:%zd", previous] forRow:GUI_ROW_SHIPYARD_START];
1346 }
1347 for (i = 0; i < (shipCount - skip) && (int)i < rowCount; i++) {
1348 NSDictionary* ship_info = [shipyard oo_dictionaryAtIndex:i + skip];
1349 OOCreditsQuantity ship_price = [ship_info oo_unsignedLongLongForKey:SHIPYARD_KEY_PRICE];
1350 [gui setColor:[gui colorFromSetting:kGuiShipyardEntryColor defaultValue:nil] forRow:startRow + i];
1351 [gui setArray:[NSArray arrayWithObjects:
1352 [NSString stringWithFormat:@" %@ ", [[ship_info oo_dictionaryForKey:SHIPYARD_KEY_SHIP] oo_stringForKey:@"display_name" defaultValue:[[ship_info oo_dictionaryForKey:SHIPYARD_KEY_SHIP] oo_stringForKey:KEY_NAME]]],
1353 OOIntCredits(ship_price),
1354 nil]
1355 forRow:startRow + i];
1356 [gui setKey:(NSString*)[ship_info objectForKey:SHIPYARD_KEY_ID] forRow:startRow + i];
1357 }
1358 if (i < shipCount - skip) {
1359 [gui setColor:[gui colorFromSetting:kGuiShipyardScrollColor defaultValue:[OOColor greenColor]] forRow:startRow + i];
1360 [gui setArray:[NSArray arrayWithObjects:DESC(@"gui-more"), @" --> ", nil] forRow:startRow + i];
1361 [gui setKey:[NSString stringWithFormat:@"More:%zu", rowCount + skip] forRow:startRow + i];
1362 i++;
1363 }
1364
1365 [gui setSelectableRange:NSMakeRange(GUI_ROW_SHIPYARD_START, i + startRow - GUI_ROW_SHIPYARD_START)];
1366 // ensure that at least one row is selected at all times
1367 if (shipCount == 1)
1370 } else {
1371 [gui setText:DESC(@"shipyard-no-ships-available-for-purchase") forRow:GUI_ROW_NO_SHIPS align:GUI_ALIGN_CENTER];
1372 [gui setColor:[gui colorFromSetting:kGuiShipyardNoshipColor defaultValue:[OOColor greenColor]] forRow:GUI_ROW_NO_SHIPS];
1373
1375 }
1376
1378
1380 }
1381
1382 // the following are necessary...
1383
1384 [self setShowDemoShips:(shipCount > 0)];
1385 [UNIVERSE enterGUIViewModeWithMouseInteraction:YES];
1386
1387 if (guiChanged) {
1388 [gui setForegroundTextureKey:@"docked_overlay"];
1389 [gui setBackgroundTextureKey:@"shipyard"];
1390 }
1391}
1392
1394{
1395 NSUInteger i;
1396 GuiDisplayGen* gui = [UNIVERSE gui];
1397 OOGUIRow sel_row = [gui selectedRow];
1398
1399 if (sel_row <= 0)
1400 return;
1401
1402 NSMutableArray* row_info = [NSMutableArray arrayWithArray:(NSArray*)[gui objectForRow:GUI_ROW_SHIPYARD_LABELS]];
1403 while ([row_info count] < 4) {
1404 [row_info addObject:@""];
1405 }
1406
1407 NSString* key = [gui keyForRow:sel_row];
1408
1409 NSDictionary* info = [currentShipyard oo_dictionaryForKey:key];
1410
1411 // clean up the display ready for the newly-selected ship (if there is one)
1412 [row_info replaceObjectAtIndex:2 withObject:@""];
1413 [row_info replaceObjectAtIndex:3 withObject:@""];
1414 for (i = GUI_ROW_SHIPYARD_INFO_START; i < GUI_ROW_MARKET_CASH - 1; i++) {
1415 [gui setText:@"" forRow:i];
1416 [gui setColor:[gui colorFromSetting:kGuiShipyardDescriptionColor defaultValue:[OOColor greenColor]] forRow:i];
1417 }
1418 [UNIVERSE removeDemoShips];
1419
1420 if (info) {
1421 // the key is a particular ship - show the details
1422 NSString* salesPitch = [info oo_stringForKey:KEY_SHORT_DESCRIPTION];
1423 NSDictionary* shipDict = [info oo_dictionaryForKey:SHIPYARD_KEY_SHIP];
1424
1425 int cargoRating = [shipDict oo_intForKey:@"max_cargo"];
1426 int cargo_extra;
1427 cargo_extra = [shipDict oo_intForKey:@"extra_cargo" defaultValue:15];
1428 float speedRating = 0.001 * [shipDict oo_intForKey:@"max_flight_speed"];
1429
1430 NSArray* shipExtras = [info oo_arrayForKey:KEY_EQUIPMENT_EXTRAS];
1431 for (i = 0; i < [shipExtras count]; i++) {
1432 if ([[shipExtras oo_stringAtIndex:i] isEqualToString:@"EQ_CARGO_BAY"]) {
1433 cargoRating += cargo_extra;
1434 } else if ([[shipExtras oo_stringAtIndex:i] isEqualToString:@"EQ_PASSENGER_BERTH"]) {
1435 cargoRating -= PASSENGER_BERTH_SPACE;
1436 }
1437 }
1438
1439 [row_info replaceObjectAtIndex:2 withObject:OOExpandKey(@"shipyard-cargo-value", cargoRating)];
1440 [row_info replaceObjectAtIndex:3 withObject:OOExpandKey(@"shipyard-speed-value", speedRating)];
1441
1442 // Show footer first. It'll be overwritten by the sales_pitch if that text is longer than usual.
1444 i = [gui addLongText:salesPitch startingAtRow:GUI_ROW_SHIPYARD_INFO_START align:GUI_ALIGN_LEFT];
1445 if (i - 1 >= GUI_ROW_MARKET_CASH - 1) {
1446 [gui setColor:[gui colorFromSetting:kGuiShipyardDescriptionColor defaultValue:[OOColor greenColor]] forRow:i - 1];
1447 [gui setColor:[gui colorFromSetting:kGuiShipyardDescriptionColor defaultValue:[OOColor greenColor]] forRow:GUI_ROW_MARKET_CASH - 1];
1448 }
1449
1450 // now display the ship
1451 [self showShipyardModel:[info oo_stringForKey:SHIPYARD_KEY_SHIPDATA_KEY]
1452 shipData:shipDict
1453 personality:[info oo_unsignedShortForKey:SHIPYARD_KEY_PERSONALITY]];
1454 } else {
1455 // the key is a particular model of ship which we must expand...
1456 // build an array from the entries for that model in the currentShipyard TODO
1457 //
1458 }
1459
1460 [gui setArray:[NSArray arrayWithArray:row_info] forRow:GUI_ROW_SHIPYARD_LABELS];
1461}
1462
1464{
1465 GuiDisplayGen* gui = [UNIVERSE gui];
1466 OOCreditsQuantity tradeIn = [self tradeInValue];
1467 OOCreditsQuantity total = tradeIn + credits;
1468 NSString* shipType = [self displayName];
1469
1470 [gui setColor:[gui colorFromSetting:kGuiShipyardTradeinColor defaultValue:nil] forRow:GUI_ROW_MARKET_CASH - 1];
1471 [gui setColor:[gui colorFromSetting:kGuiShipyardTradeinColor defaultValue:nil] forRow:GUI_ROW_MARKET_CASH];
1472 [gui setText:OOExpandKey(@"shipyard-trade-in-value", shipType, tradeIn) forRow:GUI_ROW_MARKET_CASH - 1];
1473 [gui setText:OOExpandKey(@"shipyard-total-available-with-trade-in", shipType, total, credits, tradeIn) forRow:GUI_ROW_MARKET_CASH];
1474}
1475
1476- (void)showShipyardModel:(NSString*)shipKey shipData:(NSDictionary*)shipData personality:(uint16_t)personality
1477{
1478 if (shipKey == nil || [self dockedStation] == nil)
1479 return;
1480 [self showShipModelWithKey:shipKey shipData:shipData personality:personality factorX:1.2 factorY:0.8 factorZ:6.4 inContext:@"shipyard"];
1481}
1482
1484{
1485 // each missing subentity depreciates the ship by 5%, up to a maximum of 35% depreciation.
1486 NSUInteger percent = 5 * ([self maxShipSubEntities] - [[[self shipSubEntityEnumerator] allObjects] count]);
1487 return (percent > 35 ? 35 : percent);
1488}
1489
1491{
1492 // returns down to ship_trade_in_factor% of the full credit value of your ship
1493
1494 /* FIXME: the trade-in value can be more than the sale value, and
1495 ship_trade_in_factor starts at 100%, so it can be profitable to sit
1496 and buy the same ship over and over again. This bug predates Oolite
1497 1.65.
1498 Partial fix: make effective trade-in value 75% * ship_trade_in_factor%
1499 of the "raw" trade-in value. This still allows profitability! A better
1500 solution would be to unify the price calculation for trade-in and
1501 for-sale ships.
1502 -- Ahruman 20070707, fix applied 20070708
1503 */
1504 unsigned long long value = [UNIVERSE tradeInValueForCommanderDictionary:[self commanderDataDictionary]];
1505 value -= value * 0.006 * [self missingSubEntitiesAdjustment]; // TODO: 0.006 might need rethinking.
1506 value = cunningFee(((value * 75 * ship_trade_in_factor) + 5000) / 10000, 0.005); // Multiply by two percentages, divide by 100*100. The +5000 is to get normal rounding.
1507 return value * 10;
1508}
1509
1511{
1512 GuiDisplayGen* gui = [UNIVERSE gui];
1513 OOGUIRow selectedRow = [gui selectedRow];
1514
1515 if (selectedRow <= 0)
1516 return NO;
1517
1518 NSString* key = [gui keyForRow:selectedRow];
1519
1520 if ([key hasPrefix:@"More:"]) {
1521 NSInteger fromShip = [[key componentsSeparatedByString:@":"] oo_integerAtIndex:1];
1522 if (fromShip < 0)
1523 fromShip = 0;
1524
1525 [self setGuiToShipyardScreen:fromShip];
1526 if ([[UNIVERSE gui] selectedRow] < 0) {
1527 [[UNIVERSE gui] setSelectedRow:GUI_ROW_SHIPYARD_START];
1528 }
1529 if (fromShip == 0) {
1530 [[UNIVERSE gui] setSelectedRow:GUI_ROW_SHIPYARD_START + MAX_ROWS_SHIPS_FOR_SALE - 1];
1531 }
1532 // next bit or the first ship on the list gets wrongly previewed
1533 // clean up the display
1534 NSMutableArray* row_info = [NSMutableArray arrayWithArray:(NSArray*)[gui objectForRow:GUI_ROW_SHIPYARD_LABELS]];
1535 while ([row_info count] < 4) {
1536 [row_info addObject:@""];
1537 }
1538 [row_info replaceObjectAtIndex:2 withObject:@""];
1539 [row_info replaceObjectAtIndex:3 withObject:@""];
1540 NSUInteger i;
1541 for (i = GUI_ROW_SHIPYARD_INFO_START; i < GUI_ROW_MARKET_CASH - 1; i++) {
1542 [gui setText:@"" forRow:i];
1543 [gui setColor:[gui colorFromSetting:kGuiShipyardDescriptionColor defaultValue:[OOColor greenColor]] forRow:i];
1544 }
1545 [gui setArray:[NSArray arrayWithArray:row_info] forRow:GUI_ROW_SHIPYARD_LABELS];
1546 [UNIVERSE removeDemoShips];
1547 return YES;
1548 }
1549
1550 // first check you can afford it!
1551 NSDictionary* shipInfo = [currentShipyard oo_dictionaryForKey:key];
1552 OOCreditsQuantity price = [shipInfo oo_unsignedLongLongForKey:SHIPYARD_KEY_PRICE];
1553 OOCreditsQuantity tradeIn = [self tradeInValue];
1554
1555 if (credits + tradeIn < price * 10)
1556 return NO; // you can't afford it!
1557
1558 // from this point, the player is committed to buying - raise a pre-buy script event
1559 [self doScriptEvent:OOJSID("playerWillBuyNewShip")
1560 withArguments:[NSArray arrayWithObjects:[shipInfo oo_stringForKey:SHIPYARD_KEY_SHIPDATA_KEY],
1561 [[[self dockedStation] localShipyard] objectAtIndex:selectedRow - GUI_ROW_SHIPYARD_START],
1562 [NSNumber numberWithUnsignedLongLong:price],
1563 [NSNumber numberWithUnsignedLongLong:(tradeIn / 10)], nil]];
1564
1565 // sell all the commodities carried
1566 NSString* good = nil;
1567 foreach (good, [shipCommodityData goods]) {
1568 [self trySellingCommodity:good all:YES];
1569 }
1570 // We tried to sell everything. If there are still items present in our inventory, it
1571 // means that the market got saturated (quantity in station > 127 t) before we could sell
1572 // it all. Everything that could not be sold will be lost. -- Nikos 20083012
1573
1574 // pay over the mazoolah
1575 credits -= 10 * price - tradeIn;
1576
1577 NSDictionary* shipDict = [shipInfo oo_dictionaryForKey:SHIPYARD_KEY_SHIP];
1578 [self newShipCommonSetup:[shipInfo oo_stringForKey:SHIPYARD_KEY_SHIPDATA_KEY] yardInfo:shipInfo baseInfo:shipDict];
1579
1580 // this ship has a clean record
1581 legalStatus = 0;
1582
1583 NSArray* extras = [shipInfo oo_arrayForKey:KEY_EQUIPMENT_EXTRAS];
1584 for (NSUInteger i = 0; i < [extras count]; i++) {
1585 NSString* eq_key = [extras oo_stringAtIndex:i];
1586 if ([eq_key isEqualToString:@"EQ_PASSENGER_BERTH"]) {
1587 max_passengers++;
1588 max_cargo -= PASSENGER_BERTH_SPACE;
1589 } else {
1590 [self addEquipmentItem:eq_key withValidation:YES inContext:@"newShip"];
1591 }
1592 }
1593
1594 // add bought ship to shipyard_record
1595 [shipyard_record setObject:[self shipDataKey] forKey:[shipInfo objectForKey:SHIPYARD_KEY_ID]];
1596
1597 // remove the ship from the localShipyard
1598 [[[self dockedStation] localShipyard] removeObjectAtIndex:selectedRow - GUI_ROW_SHIPYARD_START];
1599
1600 // perform the transformation
1601 NSDictionary* cmdr_dict = [self commanderDataDictionary]; // gather up all the info
1602 if (![self setCommanderDataFromDictionary:cmdr_dict])
1603 return NO;
1604
1605 [self setStatus:STATUS_DOCKED];
1606 [self setEntityPersonalityInt:[shipInfo oo_unsignedShortForKey:SHIPYARD_KEY_PERSONALITY]];
1607
1608 // adjust the clock forward by an hour
1609 ship_clock_adjust += 3600.0;
1610
1611 // finally we can get full hock if we sell it back
1612 ship_trade_in_factor = 100;
1613
1614 if ([UNIVERSE autoSave])
1615 [UNIVERSE setAutoSaveNow:YES];
1616
1617 return YES;
1618}
1619
1620- (BOOL)replaceShipWithNamedShip:(NSString*)shipKey
1621{
1622
1623 NSDictionary* ship_info = [[OOShipRegistry sharedRegistry] shipyardInfoForKey:shipKey];
1624
1625 NSDictionary* ship_base_dict = [[OOShipRegistry sharedRegistry] shipInfoForKey:shipKey];
1626
1627 if (ship_info == nil || ship_base_dict == nil) {
1628 return NO;
1629 }
1630
1631 // from this point, the player is committed to replacing - raise a pre-replace script event
1632 [self doScriptEvent:OOJSID("playerWillReplaceShip") withArgument:shipKey];
1633
1634 [self newShipCommonSetup:shipKey yardInfo:ship_info baseInfo:ship_base_dict];
1635
1636 // perform the transformation
1637 NSDictionary* cmdr_dict = [self commanderDataDictionary]; // gather up all the info
1638 if (![self setCommanderDataFromDictionary:cmdr_dict])
1639 return NO;
1640
1641 // refill from ship_info
1642 NSArray* extras = [NSMutableArray arrayWithArray:[[ship_info oo_dictionaryForKey:KEY_STANDARD_EQUIPMENT] oo_arrayForKey:KEY_EQUIPMENT_EXTRAS]];
1643 for (unsigned i = 0; i < [extras count]; i++) {
1644 NSString* eq_key = [extras oo_stringAtIndex:i];
1645 if ([eq_key isEqualToString:@"EQ_PASSENGER_BERTH"]) {
1646 max_passengers++;
1647 max_cargo -= PASSENGER_BERTH_SPACE;
1648 } else {
1649 [self addEquipmentItem:eq_key withValidation:YES inContext:@"newShip"];
1650 }
1651 }
1652
1653 [self setEntityPersonalityInt:[ship_info oo_unsignedShortForKey:SHIPYARD_KEY_PERSONALITY]];
1654
1655 return YES;
1656}
1657
1658- (void)newShipCommonSetup:(NSString*)shipKey yardInfo:(NSDictionary*)ship_info baseInfo:(NSDictionary*)ship_base_dict
1659{
1660 // Zero out our manifest.
1661 [shipCommodityData removeAllGoods];
1662 current_cargo = 0;
1663
1664 // drop all passengers
1665 [passengers removeAllObjects];
1666 [passenger_record removeAllObjects];
1667
1668 // parcels stay the same; easy to transfer between ships
1669 // contracts stay the same, so if you default - tough!
1670 // okay we need to switch the model used, lots of the stats, and add all the extras
1671
1672 [self clearSubEntities];
1673
1674 [self setShipDataKey:shipKey];
1675
1676 NSDictionary* shipDict = ship_base_dict;
1677
1678 // get a full tank for free
1679 [self setFuel:[self fuelCapacity]];
1680
1681 // get forward_weapon aft_weapon port_weapon starboard_weapon from ship_info
1682 int base_facings = [shipDict oo_unsignedIntForKey:KEY_WEAPON_FACINGS defaultValue:15];
1683 int available_facings = [ship_info oo_unsignedIntForKey:KEY_WEAPON_FACINGS defaultValue:base_facings];
1684
1685 // not retained - weapon types are references to the objects in OOEquipmentType's cache
1686 if (available_facings & WEAPON_FACING_AFT)
1687 aft_weapon_type = OOWeaponTypeFromEquipmentIdentifierSloppy([shipDict oo_stringForKey:@"aft_weapon_type"]);
1688 else
1689 aft_weapon_type = OOWeaponTypeFromEquipmentIdentifierSloppy(@"EQ_WEAPON_NONE");
1690
1691 if (available_facings & WEAPON_FACING_PORT)
1692 port_weapon_type = OOWeaponTypeFromEquipmentIdentifierSloppy([shipDict oo_stringForKey:@"port_weapon_type"]);
1693 else
1694 port_weapon_type = OOWeaponTypeFromEquipmentIdentifierSloppy(@"EQ_WEAPON_NONE");
1695
1696 if (available_facings & WEAPON_FACING_STARBOARD)
1697 starboard_weapon_type = OOWeaponTypeFromEquipmentIdentifierSloppy([shipDict oo_stringForKey:@"starboard_weapon_type"]);
1698 else
1699 starboard_weapon_type = OOWeaponTypeFromEquipmentIdentifierSloppy(@"EQ_WEAPON_NONE");
1700
1701 if (available_facings & WEAPON_FACING_FORWARD)
1702 forward_weapon_type = OOWeaponTypeFromEquipmentIdentifierSloppy([shipDict oo_stringForKey:@"forward_weapon_type"]);
1703 else
1704 forward_weapon_type = OOWeaponTypeFromEquipmentIdentifierSloppy(@"EQ_WEAPON_NONE");
1705
1706 // new ships start with weapons online
1707 weapons_online = 1;
1708
1709 // get basic max_cargo
1710 max_cargo = [UNIVERSE maxCargoForShip:[self shipDataKey]];
1711
1712 // ensure all missiles are tidied up and start at pylon 0
1713 [self tidyMissilePylons];
1714
1715 // get missiles from ship_info
1716 missiles = [shipDict oo_unsignedIntForKey:@"missiles"];
1717
1718 // reset max_passengers
1719 max_passengers = 0;
1720
1721 // reset and refill extra_equipment then set flags from it
1722
1723 // keep track of portable equipment..
1724
1725 NSMutableSet* portable_equipment = [NSMutableSet set];
1726 NSEnumerator* eqEnum = nil;
1727 NSString* eq_desc = nil;
1728 OOEquipmentType* item = nil;
1729
1730 for (eqEnum = [self equipmentEnumerator]; (eq_desc = [eqEnum nextObject]);) {
1732 if ([item isPortableBetweenShips])
1733 [portable_equipment addObject:eq_desc];
1734 }
1735
1736 // remove ALL
1737 [self removeAllEquipment];
1738
1739 // restore portable equipment
1740 for (eqEnum = [portable_equipment objectEnumerator]; (eq_desc = [eqEnum nextObject]);) {
1741 [self addEquipmentItem:eq_desc withValidation:NO inContext:@"portable"];
1742 }
1743
1744 // set up subentities from scratch; new ship could carry more or fewer than the old one
1745 [self setUpSubEntities];
1746
1747 // clear old ship names
1748 [self setShipClassName:[shipDict oo_stringForKey:@"name"]];
1749 [self setShipUniqueName:@""];
1750
1751 // new ship, so lose some memory of actions
1752 // new ship, so lose some memory of player actions
1753 if (ship_kills >= 6400) {
1754 [self clearRolesFromPlayer:0.1];
1755 } else if (ship_kills >= 2560) {
1756 [self clearRolesFromPlayer:0.25];
1757 } else {
1758 [self clearRolesFromPlayer:0.5];
1759 }
1760}
1761
1762@end
1763
1764static unsigned RepForRisk(unsigned risk)
1765{
1766 switch (risk) {
1767 case 0:
1768 return 1;
1769 case 1:
1770 return 2;
1771 case 2:
1772 default:
1773 return 4;
1774 }
1775}
OOGUITabStop OOGUITabSettings[GUI_MAX_COLUMNS]
NSInteger OOGUIRow
unsigned count
return nil
#define OOExpandKey(key,...)
OOINLINE NSString * OOIntCredits(OOCreditsQuantity integerCredits)
NSString * OOCommodityType
Definition OOTypes.h:97
uint64_t OOCreditsQuantity
Definition OOTypes.h:160
NSUInteger OOTechLevelID
Definition OOTypes.h:177
uint32_t OOCargoQuantity
Definition OOTypes.h:155
OOMassUnit
Definition OOTypes.h:111
@ UNITS_GRAMS
Definition OOTypes.h:114
@ UNITS_KILOGRAMS
Definition OOTypes.h:113
uint8_t OOGovernmentID
Definition OOTypes.h:179
@ WEAPON_FACING_FORWARD
Definition OOTypes.h:196
@ WEAPON_FACING_AFT
Definition OOTypes.h:197
@ WEAPON_FACING_PORT
Definition OOTypes.h:198
@ WEAPON_FACING_STARBOARD
Definition OOTypes.h:199
#define MAX_CONTRACT_REP
#define MAX_ROWS_SHIPS_FOR_SALE
#define GUI_ROW_SHIPYARD_START
#define CONTRACT_KEY_RISK
#define PASSENGER_KEY_NAME
#define GUI_ROW_SHIPYARD_INFO_START
#define SET_MANIFEST_ROW(obj, color, row)
static unsigned RepForRisk(unsigned risk)
static NSMutableDictionary * currentShipyard
#define MANIFEST_SCREEN_ROW_BACK
OOGUIScreenID
#define MANIFEST_SCREEN_ROW_NEXT
@ GUI_ROW_MARKET_CASH
OOWeaponType OOWeaponTypeFromEquipmentIdentifierSloppy(NSString *string) PURE_FUNC
#define UNIVERSE
Definition Universe.h:827
#define PASSENGER_BERTH_SPACE
Definition Universe.h:143
#define DESC(key)
Definition Universe.h:832
OOEntityStatus status()
Definition Entity.m:733
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)
void setText:forRow:(NSString *str,[forRow] OOGUIRow row)
void setText:forRow:align:(NSString *str,[forRow] OOGUIRow row,[align] OOGUIAlignment alignment)
void clearAndKeepBackground:(BOOL keepBackground)
OOGUIRow selectedRow
void overrideTabs:from:length:(OOGUITabSettings stops,[from] NSString *setting,[length] NSUInteger len)
void setSelectableRange:(NSRange range)
void setColor:forRow:(OOColor *color,[forRow] OOGUIRow row)
id objectForRow:(OOGUIRow row)
void setTitle:(NSString *str)
void setTabStops:(OOGUITabSettings stops)
NSString * keyForRow:(OOGUIRow row)
NSUInteger statusPage
void setShowTextCursor:(BOOL yesno)
BOOL setFirstSelectableRow()
BOOL setBackgroundTextureDescriptor:(NSDictionary *descriptor)
void setArray:forRow:(NSArray *arr,[forRow] OOGUIRow row)
void setKey:forRow:(NSString *str,[forRow] OOGUIRow row)
void doScriptEvent:(OOJSPropID message)
OOCreditsQuantity insuranceCredits()
NSString * name()
NSDictionary * infoForScripting()
NSString * shortDescription()
NSArray * legacyScript()
OOColor * darkGrayColor()
Definition OOColor.m:239
OOColor * greenColor()
Definition OOColor.m:264
OOEquipmentType * equipmentTypeWithIdentifier:(NSString *identifier)
NSDictionary * shipyardInfoForKey:(NSString *key)
OOShipRegistry * sharedRegistry()
NSDictionary * shipInfoForKey:(NSString *key)
BOOL addEquipmentItem:withValidation:inContext:(NSString *equipmentKey, [withValidation] BOOL validateAddition, [inContext] NSString *context)
void addRoleToPlayer:(NSString *role)
void showShipyardModel:shipData:personality:(NSString *shipKey,[shipData] NSDictionary *shipDict,[personality] uint16_t personality)
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)
NSArray * cargoList()
void decreaseParcelReputation:(unsigned amount)
void decreaseContractReputation:(unsigned amount)
OOCreditsQuantity tradeInValue()
void increaseParcelReputation:(unsigned amount)
NSInteger missingSubEntitiesAdjustment()
void increaseContractReputation:(unsigned amount)
void tidyMissilePylons()
void newShipCommonSetup:yardInfo:baseInfo:(NSString *shipKey,[yardInfo] NSDictionary *ship_info,[baseInfo] NSDictionary *ship_base_dict)
void setGuiToShipyardScreen:(NSUInteger skip)
BOOL trySellingCommodity:all:(OOCommodityType type,[all] BOOL all)
StationEntity * dockedStation()
void setShowDemoShips:(BOOL value)
NSDictionary * commanderDataDictionary()
void clearRolesFromPlayer:(float chance)
void calculateCurrentCargo()
void decreasePassengerReputation:(unsigned amount)
NSArray * contractsListFromArray:forCargo:forParcels:(NSArray *contracts_array, [forCargo] BOOL forCargo, [forParcels] BOOL forParcels)
void increasePassengerReputation:(unsigned amount)
OOCargoQuantity cargoQuantityOnBoard()
void runUnsanitizedScriptActions:allowingAIMethods:withContextName:forTarget:(NSArray *unsanitizedActions,[allowingAIMethods] BOOL allowAIMethods,[withContextName] NSString *contextName,[forTarget] ShipEntity *target)
void noteGUIDidChangeFrom:to:(OOGUIScreenID fromScreen,[to] OOGUIScreenID toScreen)
void doScriptEvent:withArguments:(OOJSPropID message,[withArguments] NSArray *arguments)
void setFuel:(OOFuelQuantity amount)
void setStatus:(OOEntityStatus stat)
NSString * shipDataKey()
OOFuelQuantity fuelCapacity()
void removeAllEquipment()
void setShipDataKey:(NSString *key)
NSEnumerator * shipSubEntityEnumerator()
void setEntityPersonalityInt:(uint16_t value)
void clearSubEntities()
OOCargoQuantity maxAvailableCargoSpace()
BOOL setUpSubEntities()
Definition ShipEntity.m:790
void doScriptEvent:withArgument:(OOJSPropID message,[withArgument] id argument)
void setCrew:(NSArray *crewArray)
NSUInteger maxShipSubEntities()
Definition ShipEntity.m:734
NSArray * crew
NSString * displayName
void setShipUniqueName:(NSString *inName)
void setShipClassName:(NSString *inName)
NSMutableArray * localShipyard
void generateShipyard:(OOTechLevelID stationTechLevel)
OOTechLevelID equivalentTechLevel
voidpf uLong offset
Definition ioapi.h:132
typedef int(ZCALLBACK *close_file_func) OF((voidpf opaque
float randf(void)
double cunningFee(double value, double precision)
unsigned Ranrot(void)