Oolite
Loading...
Searching...
No Matches
ShipEntity.m
Go to the documentation of this file.
1/*
2
3ShipEntity.m
4
5
6Oolite
7Copyright (C) 2004-2013 Giles C Williams and contributors
8
9This program is free software; you can redistribute it and/or
10modify it under the terms of the GNU General Public License
11as published by the Free Software Foundation; either version 2
12of the License, or (at your option) any later version.
13
14This program is distributed in the hope that it will be useful,
15but WITHOUT ANY WARRANTY; without even the impllied warranty of
16MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17GNU General Public License for more details.
18
19You should have received a copy of the GNU General Public License
20along with this program; if not, write to the Free Software
21Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22MA 02110-1301, USA.
23
24*/
25
26#import "ShipEntity.h"
27#import "ShipEntityAI.h"
29
30#import "OOMaths.h"
32#import "OOShaderMaterial.h"
33#import "Universe.h"
34
35#import "AI.h"
36#import "GameController.h"
37#import "MyOpenGLView.h"
39#import "OOCharacter.h"
41#import "OOConstToJSString.h"
42#import "OOConstToString.h"
45#import "OORoleSet.h"
46#import "OOShipGroup.h"
47#import "OOStringExpander.h"
48#import "OOStringParsing.h"
50#import "OOWeakSet.h"
51#import "ResourceManager.h"
52
53#import "OOMesh.h"
54#import "OOPlanetDrawable.h"
55
56#import "OOColor.h"
57#import "OOPolygonSprite.h"
58#import "Octree.h"
59
60#import "DockEntity.h"
61#import "OOECMBlastEntity.h"
65#import "OOFlasherEntity.h"
66#import "OOLaserShotEntity.h"
67#import "OOParticleSystem.h"
68#import "OOPlanetEntity.h"
72#import "OOSparkEntity.h"
73#import "OOSunEntity.h"
74#import "PlanetEntity.h"
75#import "PlayerEntity.h"
76#import "ProxyPlayerEntity.h"
77#import "StationEntity.h"
78#import "WormholeEntity.h"
79
80#import "GuiDisplayGen.h"
81#import "HeadUpDisplay.h"
83#import "OOEquipmentType.h"
84#import "OOShipRegistry.h"
86#import "PlayerEntitySound.h"
87
88#import "OODebugFlags.h"
89#import "OODebugGLDrawing.h"
90#import "OODebugStandards.h"
91
92#import "OOJSEngineTimeManagement.h"
93#import "OOJSScript.h"
94#import "OOJSVector.h"
95
96#define USEMASC 1
97
98static NSString* const kOOLogSyntaxAddShips = @"script.debug.syntax.addShips";
99#ifdef OO_DEBUG_MONITOR_ENABLED
100static NSString* const kOOLogEntityBehaviourChanged = @"entity.behaviour.changed";
101#endif
102
103#if MASS_DEPENDENT_FUEL_PRICES
104static GLfloat calcFuelChargeRate(GLfloat myMass)
105{
106#define kMassCharge 0.65 // the closer to 1 this number is, the more the fuel price changes from ship to ship.
107#define kBaseCharge (1.0 - kMassCharge) // proportion of price that doesn't change with ship's mass.
108
109 GLfloat baseMass = [PLAYER baseMass];
110 // if anything is wrong, use 1 (the default charge rate).
111 if (myMass <= 0.0 || baseMass <= 0.0)
112 return 1.0;
113
114 GLfloat result = (kMassCharge * myMass / baseMass) + kBaseCharge;
115
116 // round the result to the second decimal digit.
117 result = roundf(result * 100.0f) / 100.0f;
118
119 // Make sure that the rate is clamped to between three times and a third of the standard charge rate.
120 if (result > 3.0f)
121 result = 3.0f;
122 else if (result < 0.33f)
123 result = 0.33f;
124
125 return result;
126
127#undef kMassCharge
128#undef kBaseCharge
129}
130#endif
131
132@interface ShipEntity (Private)
133
134- (void)subEntityDied:(ShipEntity*)sub;
135- (void)subEntityReallyDied:(ShipEntity*)sub;
136
137#ifndef NDEBUG
139#endif
140
141- (void)rescaleBy:(GLfloat)factor;
142- (void)rescaleBy:(GLfloat)factor writeToCache:(BOOL)writeToCache;
143
144- (BOOL)setUpOneSubentity:(NSDictionary*)subentDict;
145- (BOOL)setUpOneFlasher:(NSDictionary*)subentDict;
146
147- (Entity<OOStellarBody>*)lastAegisLock;
148
149- (void)addSubEntity:(Entity<OOSubEntity>*)subent;
150
152- (HPVector)coordinatesForEscortPosition:(unsigned)idx;
153- (void)setUpMixedEscorts;
154- (void)setUpOneEscort:(ShipEntity*)escorter inGroup:(OOShipGroup*)escortGroup withRole:(NSString*)escortRole atPosition:(HPVector)ex_pos andCount:(uint8_t)currentEscortCount;
155
156- (void)addSubentityToCollisionRadius:(Entity<OOSubEntity>*)subent;
157- (ShipEntity*)launchPodWithCrew:(NSArray*)podCrew;
158
159// equipment
160- (OOEquipmentType*)generateMissileEquipmentTypeFrom:(NSString*)role;
161
162- (void)setShipHitByLaser:(ShipEntity*)ship;
163
164- (void)noteFrustration:(NSString*)context;
165
166- (BOOL)cloakPassive;
167
168@end
169
171
172@implementation ShipEntity
173
174- (id)init
175{
176 /* -init used to set up a bunch of defaults that were different from
177 those in -reinit and -setUpShipFromDictionary:. However, it seems that
178 no ships are ever used which are not -setUpShipFromDictionary: (which
179 is as it should be), so these different defaults were meaningless.
180 */
181 return [self initWithKey:@"" definition:nil];
182}
183
185{
186 return [super init];
187}
188
189// Designated initializer
190- (id)initWithKey:(NSString*)key definition:(NSDictionary*)dict
191{
193
194 NSParameterAssert(dict != nil);
195
196 self = [super init];
197 if (self == nil)
198 return nil;
199
200 _shipKey = [key retain];
201
202 isShip = YES;
204 [self setStatus:STATUS_IN_FLIGHT];
205
210 weapon_temp = 0.0f;
212 forward_weapon_temp = 0.0f;
213 aft_weapon_temp = 0.0f;
214 port_weapon_temp = 0.0f;
216
217 _nextAegisCheck = -0.1f;
219
220 if (![self setUpShipFromDictionary:dict]) {
221 [self release];
222 self = nil;
223 }
224
225 // Problem observed in testing -- Ahruman
226 if (self != nil && !isfinite(maxFlightSpeed)) {
227 OOLog(@"ship.sanityCheck.failed", @"Ship %@ %@ infinite top speed, clamped to 300.", self, @"generated with");
228 maxFlightSpeed = 300;
229 }
230 return self;
231
233}
234
235- (BOOL)setUpFromDictionary:(NSDictionary*)shipDict
236{
238
239 // Settings shared by players & NPCs.
240 //
241 // In order for default values to work and float values to not be junk,
242 // replace nil with empty dictionary. -- Ahruman 2008-04-28
244 if (shipinfoDictionary == nil)
245 shipinfoDictionary = [[NSDictionary alloc] init];
246 shipDict = shipinfoDictionary; // Ensure no mutation.
247
248 // set these flags explicitly.
250 haveStartedJSAI = NO;
251 scripted_misjump = NO;
253 being_fined = NO;
255 suppressAegisMessages = NO;
256 isMissile = NO;
257 suppressExplosion = NO;
258 _lightsActive = YES;
259
260 // set things from dictionary from here out - default values might require adjustment -- Kaks 20091130
261 _scaleFactor = [shipDict oo_floatForKey:@"model_scale_factor" defaultValue:1.0f];
262
263 float defaultSpeed = isStation ? 0.0f : 160.0f;
264 maxFlightSpeed = [shipDict oo_floatForKey:@"max_flight_speed" defaultValue:defaultSpeed];
265 max_flight_roll = [shipDict oo_floatForKey:@"max_flight_roll" defaultValue:2.0f];
266 max_flight_pitch = [shipDict oo_floatForKey:@"max_flight_pitch" defaultValue:1.0f];
267 max_flight_yaw = [shipDict oo_floatForKey:@"max_flight_yaw" defaultValue:max_flight_pitch]; // Note by default yaw == pitch
268 cruiseSpeed = maxFlightSpeed * 0.8f;
269
270 max_thrust = [shipDict oo_floatForKey:@"thrust" defaultValue:15.0f];
271 thrust = max_thrust;
272
273 afterburner_rate = [shipDict oo_floatForKey:@"injector_burn_rate" defaultValue:AFTERBURNER_BURNRATE];
274 afterburner_speed_factor = [shipDict oo_floatForKey:@"injector_speed_factor" defaultValue:7.0f];
275 if (afterburner_speed_factor < 1.0) {
276 OOLog(@"ship.setup.injectorSpeed", @"injector_speed_factor cannot be lower than 1.0 for %@", self);
277 afterburner_speed_factor = 1.0;
278 }
279#if OO_VARIABLE_TORUS_SPEED
280 else if (afterburner_speed_factor > MIN_HYPERSPEED_FACTOR) {
281 OOLog(@"ship.setup.injectorSpeed", @"injector_speed_factor cannot be higher than minimum torus speed factor (%f) for %@.", MIN_HYPERSPEED_FACTOR, self);
282 afterburner_speed_factor = MIN_HYPERSPEED_FACTOR;
283 }
284#else
285 else if (afterburner_speed_factor > HYPERSPEED_FACTOR) {
286 OOLog(@"ship.setup.injectorSpeed", @"injector_speed_factor cannot be higher than torus speed factor (%f) for %@.", HYPERSPEED_FACTOR, self);
287 afterburner_speed_factor = HYPERSPEED_FACTOR;
288 }
289#endif
290
291 maxEnergy = [shipDict oo_floatForKey:@"max_energy" defaultValue:200.0f];
292 energy_recharge_rate = [shipDict oo_floatForKey:@"energy_recharge_rate" defaultValue:1.0f];
293
294 _showDamage = [shipDict oo_boolForKey:@"show_damage" defaultValue:(energy_recharge_rate > 0)];
295 // Each new ship should start in seemingly good operating condition, unless specifically told not to - this does not affect the ship's energy levels
296 [self setThrowSparks:[shipDict oo_boolForKey:@"throw_sparks" defaultValue:NO]];
297
298 weapon_facings = [shipDict oo_intForKey:@"weapon_facings" defaultValue:VALID_WEAPON_FACINGS] & VALID_WEAPON_FACINGS;
299 if (weapon_facings & WEAPON_FACING_FORWARD)
300 forward_weapon_type = OOWeaponTypeFromString([shipDict oo_stringForKey:@"forward_weapon_type" defaultValue:@"EQ_WEAPON_NONE"]);
301 if (weapon_facings & WEAPON_FACING_AFT)
302 aft_weapon_type = OOWeaponTypeFromString([shipDict oo_stringForKey:@"aft_weapon_type" defaultValue:@"EQ_WEAPON_NONE"]);
303 if (weapon_facings & WEAPON_FACING_PORT)
304 port_weapon_type = OOWeaponTypeFromString([shipDict oo_stringForKey:@"port_weapon_type" defaultValue:@"EQ_WEAPON_NONE"]);
305 if (weapon_facings & WEAPON_FACING_STARBOARD)
306 starboard_weapon_type = OOWeaponTypeFromString([shipDict oo_stringForKey:@"starboard_weapon_type" defaultValue:@"EQ_WEAPON_NONE"]);
307
308 cloaking_device_active = NO;
309 military_jammer_active = NO;
310 cloakPassive = [shipDict oo_boolForKey:@"cloak_passive" defaultValue:YES]; // Nikos - switched passive cloak default to YES 20120523
311 cloakAutomatic = [shipDict oo_boolForKey:@"cloak_automatic" defaultValue:YES];
312
313 missiles = [shipDict oo_intForKey:@"missiles" defaultValue:0];
314 /* TODO: The following initializes the missile list to be blank, which prevents a crash caused by hasOneEquipmentItem trying to access a missile list
315 previously initialized but then released. See issue #204. We need to investigate further the cause of the missile list being released.
316 - kanthoney 10/03/2017
317 Update 20170818: The issue seems to have been resolved properly using the fix below and the problem was apparently an access of the
318 missile_list array elements before their initialization and while we were checking whether equipment can be added or not. There is
319 probably not much more that can be done here, unless someone would like to have a go at refactoring the entire ship initialization
320 code. In any case, the crash is no more and the applied solution is both simple and logical - Nikos
321 */
322 unsigned i;
323 for (i = 0; i < missiles; i++) {
324 missile_list[i] = nil;
325 }
326 max_missiles = [shipDict oo_intForKey:@"max_missiles" defaultValue:missiles];
327 if (max_missiles > SHIPENTITY_MAX_MISSILES)
328 max_missiles = SHIPENTITY_MAX_MISSILES;
329 if (missiles > max_missiles)
330 missiles = max_missiles;
331 missile_load_time = fmax(0.0, [shipDict oo_doubleForKey:@"missile_load_time" defaultValue:0.0]); // no negative load times
332 missile_launch_time = [UNIVERSE getTime] + missile_load_time;
333
334 // upgrades:
335 equipment_weight = 0;
336 if ([shipDict oo_fuzzyBooleanForKey:@"has_ecm"])
337 [self addEquipmentItem:@"EQ_ECM" inContext:@"npc"];
338 if ([shipDict oo_fuzzyBooleanForKey:@"has_scoop"])
339 [self addEquipmentItem:@"EQ_FUEL_SCOOPS" inContext:@"npc"];
340 if ([shipDict oo_fuzzyBooleanForKey:@"has_escape_pod"])
341 [self addEquipmentItem:@"EQ_ESCAPE_POD" inContext:@"npc"];
342 if ([shipDict oo_fuzzyBooleanForKey:@"has_cloaking_device"])
343 [self addEquipmentItem:@"EQ_CLOAKING_DEVICE" inContext:@"npc"];
344 if ([shipDict oo_floatForKey:@"has_energy_bomb"] > 0) {
345 /* NOTE: has_energy_bomb actually refers to QC mines.
346
347 max_missiles for NPCs is a newish addition, and ships have
348 traditionally not needed to reserve a slot for a Q-mine added this
349 way. If has_energy_bomb is possible, and max_missiles is not
350 explicit, we add an extra missile slot to compensate.
351 -- Ahruman 2011-03-25
352 */
353 if ([shipDict oo_fuzzyBooleanForKey:@"has_energy_bomb"]) {
354 if (max_missiles == missiles && max_missiles < SHIPENTITY_MAX_MISSILES && [shipDict objectForKey:@"max_missiles"] == nil) {
355 max_missiles++;
356 }
357 [self addEquipmentItem:@"EQ_QC_MINE" inContext:@"npc"];
358 }
359 }
360
361 if ([shipDict oo_fuzzyBooleanForKey:@"has_fuel_injection"])
362 [self addEquipmentItem:@"EQ_FUEL_INJECTION" inContext:@"npc"];
363
364#if USEMASC
365 if ([shipDict oo_fuzzyBooleanForKey:@"has_military_jammer"])
366 [self addEquipmentItem:@"EQ_MILITARY_JAMMER" inContext:@"npc"];
367 if ([shipDict oo_fuzzyBooleanForKey:@"has_military_scanner_filter"])
368 [self addEquipmentItem:@"EQ_MILITARY_SCANNER_FILTER" inContext:@"npc"];
369#endif
370
371 // can it be 'mined' for alloys?
372 canFragment = [shipDict oo_fuzzyBooleanForKey:@"fragment_chance" defaultValue:0.9];
373 isWreckage = NO;
374
375 // can subentities be destroyed separately?
376 isFrangible = [shipDict oo_boolForKey:@"frangible" defaultValue:YES];
377
378 max_cargo = [shipDict oo_unsignedIntForKey:@"max_cargo"];
379 extra_cargo = [shipDict oo_unsignedIntForKey:@"extra_cargo" defaultValue:15];
380
381 hyperspaceMotorSpinTime = [shipDict oo_floatForKey:@"hyperspace_motor_spin_time" defaultValue:DEFAULT_HYPERSPACE_SPIN_TIME];
382 if (![shipDict oo_boolForKey:@"hyperspace_motor" defaultValue:YES])
383 hyperspaceMotorSpinTime = -1;
384
385 [name autorelease];
386 name = [[shipDict oo_stringForKey:@"name" defaultValue:@"?"] copy];
387
388 [shipUniqueName autorelease];
389 shipUniqueName = [[shipDict oo_stringForKey:@"ship_name" defaultValue:@""] copy];
390
391 [shipClassName autorelease];
392 shipClassName = [[shipDict oo_stringForKey:@"ship_class_name" defaultValue:name] copy];
393
394 [displayName autorelease];
395 displayName = [[shipDict oo_stringForKey:@"display_name" defaultValue:nil] copy];
396
397 // Load the model (must be before subentities)
398 NSString* modelName = [shipDict oo_stringForKey:@"model"];
399 if (modelName != nil) {
400 OOMesh* mesh = nil;
401
402 mesh = [OOMesh meshWithName:modelName
403 cacheKey:[NSString stringWithFormat:@"%@-%.3f", _shipKey, _scaleFactor]
404 materialDictionary:[shipDict oo_dictionaryForKey:@"materials"]
405 shadersDictionary:[shipDict oo_dictionaryForKey:@"shaders"]
406 smooth:[shipDict oo_boolForKey:@"smooth" defaultValue:NO]
407 shaderMacros:OODefaultShipShaderMacros()
409 scaleFactor:_scaleFactor
410 cacheWriteable:YES];
411
412 if (mesh == nil)
413 return NO;
414 [self setMesh:mesh];
415 }
416
417 float density = [shipDict oo_floatForKey:@"density" defaultValue:1.0f];
418 if (octree)
419 mass = (GLfloat)(density * 20.0f * [octree volume]);
420
421 DESTROY(default_laser_color);
422 default_laser_color = [[OOColor brightColorWithDescription:[shipDict objectForKey:@"laser_color"]] retain];
423
424 if (default_laser_color == nil) {
425 [self setLaserColor:[OOColor redColor]];
426 } else {
427 [self setLaserColor:default_laser_color];
428 }
429 // exhaust emissive color
430 OORGBAComponents defaultExhaustEmissiveColorComponents; // pale blue is exhaust default color
431 defaultExhaustEmissiveColorComponents.r = 0.7f;
432 defaultExhaustEmissiveColorComponents.g = 0.9f;
433 defaultExhaustEmissiveColorComponents.b = 1.0f;
434 defaultExhaustEmissiveColorComponents.a = 0.9f;
435 OOColor* color = [OOColor brightColorWithDescription:[shipDict objectForKey:@"exhaust_emissive_color"]];
436 if (color == nil)
437 color = [OOColor colorWithRGBAComponents:defaultExhaustEmissiveColorComponents];
438 [self setExhaustEmissiveColor:color];
439
440 [self clearSubEntities];
441 [self setUpSubEntities];
442
443 // correctly initialise weaponRange, etc. (must be after subentity setup)
444 if (isWeaponNone(forward_weapon_type)) {
445 OOWeaponType weapon_type = nil;
446 BOOL hasTurrets = NO;
447 NSEnumerator* subEnum = [self shipSubEntityEnumerator];
448 ShipEntity* se = nil;
449 while (isWeaponNone(weapon_type) && (se = [subEnum nextObject])) {
450 weapon_type = se->forward_weapon_type;
451 if (se->behaviour == BEHAVIOUR_TRACK_AS_TURRET) {
452 hasTurrets = YES;
453 }
454 }
455 if (isWeaponNone(weapon_type) && hasTurrets) { /* safety for ships only equipped with turrets
456 note: this was hard-coded to 10000.0, although turrets have a notably
457 shorter range. We are using a multiplier of 1.667 in order to not change
458 something that already works, but probably it would be best to use
459 TURRET_SHOT_RANGE * COMBAT_WEAPON_RANGE_FACTOR here
460 */
461 weaponRange = TURRET_SHOT_RANGE * 1.667;
462 } else {
463 [self setWeaponDataFromType:weapon_type];
464 }
465 } else {
466 [self setWeaponDataFromType:forward_weapon_type];
467 }
468
469 // rotating subentities
470 subentityRotationalVelocity = kIdentityQuaternion;
471 if ([shipDict objectForKey:@"rotational_velocity"]) {
472 subentityRotationalVelocity = [shipDict oo_quaternionForKey:@"rotational_velocity"];
473 }
474
475 // set weapon offsets
476 NSString* weaponMountMode = [shipDict oo_stringForKey:@"weapon_mount_mode" defaultValue:@"single"];
477 _multiplyWeapons = [weaponMountMode isEqualToString:@"multiply"];
478 forwardWeaponOffset = [[self getWeaponOffsetFrom:shipDict withKey:@"weapon_position_forward" inMode:weaponMountMode] retain];
479 aftWeaponOffset = [[self getWeaponOffsetFrom:shipDict withKey:@"weapon_position_aft" inMode:weaponMountMode] retain];
480 portWeaponOffset = [[self getWeaponOffsetFrom:shipDict withKey:@"weapon_position_port" inMode:weaponMountMode] retain];
481 starboardWeaponOffset = [[self getWeaponOffsetFrom:shipDict withKey:@"weapon_position_starboard" inMode:weaponMountMode] retain];
482
483 tractor_position = vector_multiply_scalar([shipDict oo_vectorForKey:@"scoop_position"], _scaleFactor);
484
485 // sun glare filter - default is high filter, both for HDR and SDR
486 [self setSunGlareFilter:[shipDict oo_floatForKey:@"sun_glare_filter" defaultValue:0.97f]];
487
488 // Get scriptInfo dictionary, containing arbitrary stuff scripts might be interested in.
489 scriptInfo = [[shipDict oo_dictionaryForKey:@"script_info" defaultValue:nil] retain];
490
491 explosionType = [[shipDict oo_arrayForKey:@"explosion_type" defaultValue:nil] retain];
492
493 isDemoShip = NO;
494
495 return YES;
496
498}
499
500- (BOOL)setUpShipFromDictionary:(NSDictionary*)shipDict
501{
503
504 if (![self setUpFromDictionary:shipDict])
505 return NO;
506
507 // NPC-only settings.
508 //
514 reference = v_forward; // reference vector for (* turrets *)
515
516 isShip = YES;
517
518 // scan class settings. 'scanClass' is in common usage, but we could also have a more standard 'scan_class' key with higher precedence. Kaks 20090810
519 // let's see if scan_class is set...
520 scanClass = OOScanClassFromString([shipDict oo_stringForKey:@"scan_class" defaultValue:@"CLASS_NOT_SET"]);
521
522 // if not, try 'scanClass'. NOTE: non-standard capitalization is documented and entrenched.
523 if (scanClass == CLASS_NOT_SET) {
524 scanClass = OOScanClassFromString([shipDict oo_stringForKey:@"scanClass" defaultValue:@"CLASS_NOT_SET"]);
525 }
526
527 [scan_description autorelease];
528 scan_description = [[shipDict oo_stringForKey:@"scan_description" defaultValue:nil] copy];
529
530 // FIXME: give NPCs shields instead.
531
532 if ([shipDict oo_fuzzyBooleanForKey:@"has_shield_booster"])
533 [self addEquipmentItem:@"EQ_SHIELD_BOOSTER" inContext:@"npc"];
534 if ([shipDict oo_fuzzyBooleanForKey:@"has_shield_enhancer"])
535 [self addEquipmentItem:@"EQ_SHIELD_ENHANCER" inContext:@"npc"];
536
537 // Start with full energy banks.
539 weapon_temp = 0.0f;
540 forward_weapon_temp = 0.0f;
541 aft_weapon_temp = 0.0f;
542 port_weapon_temp = 0.0f;
544
545 // setWeaponDataFromType inside setUpFromDictionary should set weapon_damage from the front laser.
546 // no weapon_damage? It's a missile: set weapon_damage from shipdata!
547 if (weapon_damage == 0.0) {
548 weapon_damage_override = weapon_damage = [shipDict oo_floatForKey:@"weapon_energy" defaultValue:0]; // any damage value for missiles/bombs
549 } else {
551 }
552
553 scannerRange = [shipDict oo_floatForKey:@"scanner_range" defaultValue:(float)SCANNER_MAX_RANGE];
554
555 fuel = [shipDict oo_unsignedShortForKey:@"fuel"]; // Does it make sense that this defaults to 0? Should it not be 70? -- Ahruman
556
557 fuel_accumulator = 1.0;
558
559 [self setBounty:[shipDict oo_unsignedIntForKey:@"bounty" defaultValue:0] withReason:kOOLegalStatusReasonSetup];
560
561 [shipAI autorelease];
562 shipAI = [[AI alloc] init];
563 [shipAI setOwner:self];
564 [self setAITo:[shipDict oo_stringForKey:@"ai_type" defaultValue:@"nullAI.plist"]];
565
566 likely_cargo = [shipDict oo_unsignedIntForKey:@"likely_cargo"];
567 noRocks = [shipDict oo_fuzzyBooleanForKey:@"no_boulders"];
568
571 NSString* cargoString = [shipDict oo_stringForKey:@"cargo_carried"];
572 if (cargoString != nil) {
573 if ([cargoString isEqualToString:@"SCARCE_GOODS"]) {
575 } else if ([cargoString isEqualToString:@"PLENTIFUL_GOODS"]) {
577 } else {
579
580 OOCommodityType c_commodity = nil;
581 int c_amount = 1;
582 NSScanner* scanner = [NSScanner scannerWithString:cargoString];
583 if ([scanner scanInt:&c_amount]) {
584 [scanner ooliteScanCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString:NULL]; // skip whitespace
585 c_commodity = [[scanner string] substringFromIndex:[scanner scanLocation]];
586 if ([[UNIVERSE commodities] goodDefined:c_commodity]) {
587 [self setCommodityForPod:c_commodity andAmount:c_amount];
588 } else {
589 c_commodity = [[UNIVERSE commodities] goodNamed:c_commodity];
590 if ([[UNIVERSE commodities] goodDefined:c_commodity]) {
591 [self setCommodityForPod:c_commodity andAmount:c_amount];
592 }
593 }
594 } else {
595 c_amount = 1;
596 c_commodity = [shipDict oo_stringForKey:@"cargo_carried"];
597 if ([[UNIVERSE commodities] goodDefined:c_commodity]) {
598 [self setCommodityForPod:c_commodity andAmount:c_amount];
599 } else {
600 c_commodity = [[UNIVERSE commodities] goodNamed:c_commodity];
601 if ([[UNIVERSE commodities] goodDefined:c_commodity]) {
602 [self setCommodityForPod:c_commodity andAmount:c_amount];
603 }
604 }
605 }
606 }
607 }
608
609 cargoString = [shipDict oo_stringForKey:@"cargo_type"];
610 if (cargoString) {
611 if (cargo != nil)
612 [cargo autorelease];
613 cargo = [[NSMutableArray alloc] initWithCapacity:max_cargo]; // alloc retains;
614
615 [self setUpCargoType:cargoString];
616 } else if (scanClass != CLASS_CARGO) {
617 if (cargo != nil)
618 [cargo autorelease];
619 cargo = [[NSMutableArray alloc] initWithCapacity:max_cargo]; // alloc retains;
620 // if not CLASS_CARGO, and no cargo type set, default to CARGO_NOT_CARGO
622 }
623
624 hasScoopMessage = [shipDict oo_boolForKey:@"has_scoop_message" defaultValue:YES];
625
626 [roleSet release];
627 roleSet = [[[OORoleSet roleSetWithString:[shipDict oo_stringForKey:@"roles"]] roleSetWithRemovedRole:@"player"] retain];
628 [primaryRole release];
630
631 [self setOwner:self];
632 [self setHulk:[shipDict oo_boolForKey:@"is_hulk"]];
633
634 // these are the colors used for the "lollipop" of the ship. Any of the two (or both, for flash effect) can be defined. nil means use default from shipData.
635 [self setScannerDisplayColor1:nil];
636 [self setScannerDisplayColor2:nil];
637 // and the same for the "hostile" colours
640
641 // Populate the missiles here. Must come after scanClass.
642 _missileRole = [shipDict oo_stringForKey:@"missile_role"];
643 unsigned i, j;
644 for (i = 0, j = 0; i < missiles; i++) {
645 missile_list[i] = [self selectMissile];
646 // could loop forever (if missile_role is badly defined, selectMissile might return nil in some cases) . Try 3 times, and if no luck, skip
647 if (missile_list[i] == nil && j < 3) {
648 j++;
649 i--;
650 } else {
651 j = 0;
652 if (missile_list[i] == nil) {
653 missiles--;
654 }
655 }
656 }
657
658 // accuracy. Must come after scanClass, because we are using scanClass to determine if this is a missile.
659
660 // missiles: range 0 to +10
661 // ships: range -5 to +10, but randomly only -5 <= accuracy < +5
662 // enables "better" AIs at +5 and above
663 // police and military always have positive accuracy
664
665 accuracy = [shipDict oo_floatForKey:@"accuracy" defaultValue:-100.0f]; // Out-of-range default
666 if (accuracy < -5.0f || accuracy > 10.0f) {
667 accuracy = (randf() * 10.0) - 5.0;
668
669 if (accuracy < 0.0f && (scanClass == CLASS_MILITARY || scanClass == CLASS_POLICE)) { // police and military pilots have a better average skill.
671 }
672 }
673 if (scanClass == CLASS_MISSILE) { // missile accuracy range is 0 to 10
675 }
676 [self setAccuracy:accuracy]; // set derived variables
677 _missed_shots = 0;
678
679 // escorts
680 _maxEscortCount = MIN([shipDict oo_unsignedCharForKey:@"escorts" defaultValue:0], (uint8_t)MAX_ESCORTS);
682 if (_pendingEscortCount == 0 && [shipDict oo_arrayForKey:@"escort_roles" defaultValue:nil] != nil) {
683 // mostly ignored by setUpMixedEscorts, but needs to be high
684 // enough that it doesn't end up at zero (e.g. by governmental
685 // reductions in [Universe addShipAt]
687 }
688
689 // beacons
690 [self setBeaconCode:[shipDict oo_stringForKey:@"beacon"]];
691 [self setBeaconLabel:[shipDict oo_stringForKey:@"beacon_label" defaultValue:[shipDict oo_stringForKey:@"beacon"]]];
692
693 // contact tracking entities
694 [self setTrackCloseContacts:[shipDict oo_boolForKey:@"track_contacts" defaultValue:NO]];
695
696 // ship skin insulation factor (1.0 is normal)
697 [self setHeatInsulation:[shipDict oo_floatForKey:@"heat_insulation" defaultValue:[self hasHeatShield] ? 2.0 : 1.0]];
698
699 // unpiloted (like missiles asteroids etc.)
700 _explicitlyUnpiloted = [shipDict oo_fuzzyBooleanForKey:@"unpiloted"];
702 [self setCrew:nil];
703 } else {
704 // crew and passengers
705 NSDictionary* cdict = [[UNIVERSE characters] objectForKey:[shipDict oo_stringForKey:@"pilot"]];
706 if (cdict != nil) {
708 [self setCrew:[NSArray arrayWithObject:pilot]];
709 }
710 }
711
712 [self setShipScript:[shipDict oo_stringForKey:@"script"]];
713
714 home_system = [UNIVERSE currentSystemID];
715 destination_system = [UNIVERSE currentSystemID];
716
717 reactionTime = [shipDict oo_floatForKey:@"reaction_time" defaultValue:COMBAT_AI_STANDARD_REACTION_TIME];
718
719 return YES;
720
722}
723
724- (void)setSubIdx:(NSUInteger)value
725{
726 _subIdx = value;
727}
728
729- (NSUInteger)subIdx
730{
731 return _subIdx;
732}
733
735{
736 return _maxShipSubIdx;
737}
738
739- (NSString*)repeatString:(NSString*)str times:(NSUInteger)times
740{
741 if (times == 0)
742 return @"";
743
744 NSMutableString* result = [NSMutableString stringWithCapacity:[str length] * times];
745
746 for (NSUInteger i = 0; i < times; i++) {
747 [result appendString:str];
748 }
749
750 return result;
751}
752
754{
755 NSMutableString* result = [NSMutableString stringWithCapacity:4];
756 NSEnumerator* subEnum = nil;
757 ShipEntity* se = nil;
758 NSUInteger diff, i = 0;
759
760 for (subEnum = [self shipSubEntityEnumerator]; (se = [subEnum nextObject]);) {
761 diff = [se subIdx] - i;
762 i += diff + 1;
763 [result appendString:[self repeatString:@"0" times:diff]];
764 [result appendString:@"1"];
765 }
766 // add trailing zeroes
767 [result appendString:[self repeatString:@"0" times:[self maxShipSubEntities] - i]];
768 return result;
769}
770
771- (void)deserializeShipSubEntitiesFrom:(NSString*)string
772{
773 NSArray* subEnts = [[self shipSubEntityEnumerator] allObjects];
774 NSInteger i, idx, start = [subEnts count] - 1;
775 NSInteger strMaxIdx = [string length] - 1;
776
777 ShipEntity* se = nil;
778
779 for (i = start; i >= 0; i--) {
780 se = (ShipEntity*)[subEnts objectAtIndex:i];
781 idx = [se subIdx]; // should be identical to i, but better safe than sorry...
782 if (idx <= strMaxIdx && [[string substringWithRange:NSMakeRange(idx, 1)] isEqualToString:@"0"]) {
784 [se setEnergy:1];
785 [se takeEnergyDamage:500000000.0 from:nil becauseOf:nil weaponIdentifier:@""];
786 }
787 }
788}
789
791{
793
794 unsigned int i;
795 NSDictionary* shipDict = [self shipInfoDictionary];
796 NSArray* plumes = [shipDict oo_arrayForKey:@"exhaust"];
797
799 _maxShipSubIdx = 0;
800
801 for (i = 0; i < [plumes count]; i++) {
802 NSArray* definition = ScanTokensFromString([plumes oo_stringAtIndex:i]);
803 OOExhaustPlumeEntity* exhaust = [OOExhaustPlumeEntity exhaustForShip:self withDefinition:definition andScale:_scaleFactor];
804 [self addSubEntity:exhaust];
805 }
806
807 NSArray* subs = [shipDict oo_arrayForKey:@"subentities"];
808
810
811 for (i = 0; i < [subs count]; i++) {
812 [self setUpOneSubentity:[subs oo_dictionaryAtIndex:i]];
813 }
814
816
817 return YES;
818
820}
821
823{
824 OOScalar exhaust_length = 0;
825 NSEnumerator* exEnum = nil;
826 OOExhaustPlumeEntity* exEnt = nil;
827 for (exEnum = [self exhaustEnumerator]; (exEnt = [exEnum nextObject]);) {
828 if ([exEnt findCollisionRadius] > exhaust_length) {
829 exhaust_length = [exEnt findCollisionRadius];
830 }
831 }
832 return _profileRadius + exhaust_length;
833}
834
835- (BOOL)setUpOneSubentity:(NSDictionary*)subentDict
836{
838
839 NSString* type = nil;
840
841 type = [subentDict oo_stringForKey:@"type"];
842 if ([type isEqualToString:@"flasher"]) {
843 return [self setUpOneFlasher:subentDict];
844 } else {
845 return [self setUpOneStandardSubentity:subentDict asTurret:[type isEqualToString:@"ball_turret"]];
846 }
847
849}
850
851- (BOOL)setUpOneFlasher:(NSDictionary*)subentDict
852{
854 [flasher setPosition:HPvector_multiply_scalar([subentDict oo_hpvectorForKey:@"position"], _scaleFactor)];
855 [flasher rescaleBy:_scaleFactor];
856 [self addSubEntity:flasher];
857 return YES;
858}
859
860- (BOOL)setUpOneStandardSubentity:(NSDictionary*)subentDict asTurret:(BOOL)asTurret
861{
862 ShipEntity* subentity = nil;
863 NSString* subentKey = nil;
864 HPVector subPosition;
865 Quaternion subOrientation;
866
867 subentKey = [subentDict oo_stringForKey:@"subentity_key"];
868 if (subentKey == nil) {
869 OOLog(@"setup.ship.badEntry.subentities", @"Failed to set up entity - no subentKey in %@", subentDict);
870 return NO;
871 }
872
873 if (!asTurret && [self isStation] && [subentDict oo_boolForKey:@"is_dock"]) {
874 subentity = [UNIVERSE newDockWithName:subentKey andScaleFactor:_scaleFactor];
875 } else {
876 subentity = [UNIVERSE newSubentityWithName:subentKey andScaleFactor:_scaleFactor];
877 }
878 if (subentity == nil) {
879 OOLog(@"setup.ship.badEntry.subentities", @"Failed to set up entity %@", subentKey);
880 return NO;
881 }
882
883 subPosition = HPvector_multiply_scalar([subentDict oo_hpvectorForKey:@"position"], _scaleFactor);
884 subOrientation = [subentDict oo_quaternionForKey:@"orientation"];
885
886 [subentity setPosition:subPosition];
887 [subentity setOrientation:subOrientation];
888 [subentity setReference:vector_forward_from_quaternion(subOrientation)];
889 // subentities inherit parent personality
891
892 if (asTurret) {
893 [subentity setBehaviour:BEHAVIOUR_TRACK_AS_TURRET];
894 [subentity setWeaponRechargeRate:[subentDict oo_floatForKey:@"fire_rate" defaultValue:TURRET_SHOT_FREQUENCY]];
895 [subentity setWeaponEnergy:[subentDict oo_floatForKey:@"weapon_energy" defaultValue:TURRET_TYPICAL_ENERGY]];
896 [subentity setWeaponRange:[subentDict oo_floatForKey:@"weapon_range" defaultValue:TURRET_SHOT_RANGE]];
897 [subentity setStatus:STATUS_ACTIVE];
898 } else {
899 [subentity setStatus:STATUS_INACTIVE];
900 }
901
902 [subentity overrideScriptInfo:[subentDict oo_dictionaryForKey:@"script_info"]];
903
904 [self addSubEntity:subentity];
905 [subentity setSubIdx:_maxShipSubIdx];
907
908 // update subentities
912
913 if (!asTurret && [self isStation] && [subentDict oo_boolForKey:@"is_dock"]) {
914 BOOL allow_docking = [subentDict oo_boolForKey:@"allow_docking" defaultValue:YES];
915 BOOL ddc = [subentDict oo_boolForKey:@"disallowed_docking_collides" defaultValue:NO];
916 BOOL allow_launching = [subentDict oo_boolForKey:@"allow_launching" defaultValue:YES];
917 // do not include this key in OOShipRegistry; should never be set by shipdata
918 BOOL virtual_dock = [subentDict oo_boolForKey:@"_is_virtual_dock" defaultValue:NO];
919 if (virtual_dock) {
921 }
922
923 [(DockEntity*)subentity setDimensionsAndCorridor:allow_docking ddc:ddc launching:allow_launching];
924 [subentity setDisplayName:[subentDict oo_stringForKey:@"dock_label" defaultValue:@"the docking bay"]];
925 }
926
927 [subentity release];
928
929 return YES;
930}
931
933{
934 return [[self primaryRole] isEqualToString:@"oolite-template-cargopod"];
935}
936
937- (void)setUpCargoType:(NSString*)cargoString
938{
939 cargo_type = StringToCargoType(cargoString);
940
941 switch (cargo_type) {
942 case CARGO_SLAVES:
945 commodity_type = @"slaves";
946 cargo_type = CARGO_RANDOM; // not realy random, but it tells that cargo is selected.
947 break;
948
949 case CARGO_ALLOY:
952 commodity_type = @"alloys";
954 break;
955
956 case CARGO_MINERALS:
959 commodity_type = @"minerals";
961 break;
962
963 case CARGO_THARGOID:
966 commodity_type = @"alien_items";
968 break;
969
971 commodity_amount = 1; // value > 0 is needed to be recognised as cargo by scripts;
972 DESTROY(commodity_type); // will be defined elsewhere when needed.
973 break;
974
975 case CARGO_RANDOM:
976 // Could already be set by the cargo_carried key. If not, ensure at least one.
977 if (commodity_amount == 0)
979 break;
980
981 default:
982 break;
983 }
984}
985
986- (void)dealloc
987{
988 /* NOTE: we guarantee that entityDestroyed is sent immediately after the
989 JS ship becomes invalid (as a result of dropping the weakref), i.e.
990 with no intervening script activity.
991 It has to be after the invalidation so that scripts can't directly or
992 indirectly cause the ship to become strong-referenced. (Actually, we
993 could handle that situation by breaking out of dealloc, but that's a
994 nasty abuse of framework semantics and would require special-casing in
995 subclasses.)
996 -- Ahruman 2011-02-27
997 */
999 weakSelf = nil;
1000 [self doScriptEvent:OOJSID("entityDestroyed")];
1001
1002 [self setTrackCloseContacts:NO]; // deallocs tracking dictionary
1003 [[self parentEntity] subEntityReallyDied:self]; // Will do nothing if we're not really a subentity
1004 [self clearSubEntities];
1005
1008 DESTROY(shipAI);
1009 DESTROY(cargo);
1010 DESTROY(name);
1024 DESTROY(script);
1028 DESTROY(crew);
1030 DESTROY(octree);
1033
1038
1040
1041 [self setSubEntityTakingDamage:nil];
1042 [self removeAllEquipment];
1043
1044 [_group removeShip:self];
1045 DESTROY(_group);
1046 [_escortGroup removeShip:self];
1048
1050
1054
1056
1057 [super dealloc];
1058}
1059
1061{
1062 [script autorelease];
1063 script = nil;
1064}
1065
1067{
1068 [subEntities makeObjectsPerformSelector:@selector(setOwner:) withObject:nil]; // Ensure backlinks are broken
1069 [subEntities release];
1070 subEntities = nil;
1071
1072 // reset size & mass!
1075 float density = [[self shipInfoDictionary] oo_floatForKey:@"density" defaultValue:1.0f];
1076 if (octree)
1077 mass = (GLfloat)(density * 20.0f * [octree volume]);
1078}
1079
1084
1085- (void)setSubEntityRotationalVelocity:(Quaternion)rv
1086{
1088}
1089
1091{
1092 if (![self isSubEntity]) {
1093 return [NSString stringWithFormat:@"\"%@\" %@", [self name], [super descriptionComponents]];
1094 } else {
1095 // ID, scanClass and status are of no interest for subentities.
1096 NSString* subtype = nil;
1097 if ([self behaviour] == BEHAVIOUR_TRACK_AS_TURRET)
1098 subtype = @"(turret)";
1099 else
1100 subtype = @"(subentity)";
1101
1102 return [NSString stringWithFormat:@"\"%@\" position: %@ %@", [self name], HPVectorDescription([self position]), subtype];
1103 }
1104}
1105
1107{
1108 return [NSString stringWithFormat:@"\"%@\"", [self name]];
1109}
1110
1112{
1113 return sunGlareFilter;
1114}
1115
1116- (void)setSunGlareFilter:(GLfloat)newValue
1117{
1118 sunGlareFilter = OOClamp_0_1_f(newValue);
1119}
1120
1121- (GLfloat)accuracy
1122{
1123 return accuracy;
1124}
1125
1126- (void)setAccuracy:(GLfloat)new_accuracy
1127{
1128 if (new_accuracy < 0.0f && scanClass == CLASS_MISSILE) {
1129 new_accuracy = 0.0;
1130 } else if (new_accuracy < -5.0f) {
1131 new_accuracy = -5.0;
1132 } else if (new_accuracy > 10.0f) {
1133 new_accuracy = 10.0;
1134 }
1135 accuracy = new_accuracy;
1136 pitch_tolerance = 0.01 * (85.0f + accuracy);
1137 // especially against small targets, less good pilots will waste some shots
1138 aim_tolerance = 240.0 - (18.0f * accuracy);
1139
1141 missile_load_time = 2.0; // smart enough not to waste all missiles on 1 ECM!
1142 }
1143}
1144
1146{
1147 return (OOMesh*)[self drawable];
1148}
1149
1150- (void)setMesh:(OOMesh*)mesh
1151{
1152 if (mesh != [self mesh]) {
1153 [self setDrawable:mesh];
1154 [octree autorelease];
1155 octree = [[mesh octree] retain];
1156 }
1157}
1158
1163
1165{
1166 return v_forward;
1167}
1168
1170{
1171 return v_up;
1172}
1173
1175{
1176 return v_right;
1177}
1178
1180{
1181 return scripted_misjump;
1182}
1183
1184- (void)setScriptedMisjump:(BOOL)newValue
1185{
1186 scripted_misjump = !!newValue;
1187}
1188
1190{
1191 return _scriptedMisjumpRange;
1192}
1193
1194- (void)setScriptedMisjumpRange:(GLfloat)newValue
1195{
1196 _scriptedMisjumpRange = newValue;
1197}
1198
1199- (NSArray*)subEntities
1200{
1201 return [[subEntities copy] autorelease];
1202}
1203
1204- (NSUInteger)subEntityCount
1205{
1206 return [subEntities count];
1207}
1208
1209- (BOOL)hasSubEntity:(Entity<OOSubEntity>*)sub
1210{
1211 return [subEntities containsObject:sub];
1212}
1213
1214- (NSEnumerator*)subEntityEnumerator
1215{
1216 return [[self subEntities] objectEnumerator];
1217}
1218
1220{
1221 return [[self subEntities] objectEnumeratorFilteredWithSelector:@selector(isShip)];
1222}
1223
1224- (NSEnumerator*)flasherEnumerator
1225{
1226 return [[self subEntities] objectEnumeratorFilteredWithSelector:@selector(isFlasher)];
1227}
1228
1229- (NSEnumerator*)exhaustEnumerator
1230{
1231 return [[self subEntities] objectEnumeratorFilteredWithSelector:@selector(isExhaust)];
1232}
1233
1235{
1237
1238#ifndef NDEBUG
1239 // Sanity check - there have been problems here, see fireLaserShotInDirection:
1240 // -parentEntity will take care of reporting insanity.
1241 if ([result parentEntity] != self)
1242 result = nil;
1243#endif
1244
1245 // Clear the weakref if the subentity is dead.
1246 if (result == nil)
1247 [self setSubEntityTakingDamage:nil];
1248
1249 return result;
1250}
1251
1252- (void)setSubEntityTakingDamage:(ShipEntity*)sub
1253{
1254#ifndef NDEBUG
1255 // Sanity checks: sub must be a ship subentity of self, or nil.
1256 if (sub != nil) {
1257 if (![self hasSubEntity:sub]) {
1258 OOLog(@"ship.subentity.sanityCheck.failed.details", @"Attempt to set subentity taking damage of %@ to %@, which is not a subentity.", [self shortDescription], sub);
1259 sub = nil;
1260 } else if (![sub isShip]) {
1261 OOLog(@"ship.subentity.sanityCheck.failed", @"Attempt to set subentity taking damage of %@ to %@, which is not a ship.", [self shortDescription], sub);
1262 sub = nil;
1263 }
1264 }
1265#endif
1266
1267 [_subEntityTakingDamage release];
1269}
1270
1272{
1273 return script;
1274}
1275
1277{
1278 return aiScript;
1279}
1280
1285
1286- (void)setAIScriptWakeTime:(OOTimeAbsolute)t
1287{
1288 aiScriptWakeTime = t;
1289}
1290
1291- (BoundingBox)findBoundingBoxRelativeToPosition:(HPVector)opv i:(Vector)i j:(Vector)j k:(Vector)k
1292{
1293 // HPVect: check that this conversion doesn't lose needed precision
1294 return [[self mesh] findBoundingBoxRelativeToPosition:HPVectorToVector(opv)
1295 ri:i
1296 rj:j
1297 rk:k
1298 selfPosition:HPVectorToVector(position)
1299 si:v_right
1300 sj:v_up
1301 sk:v_forward];
1302}
1303
1305{
1306 return octree;
1307}
1308
1309- (float)volume
1310{
1311 return [octree volume];
1312}
1313
1314- (GLfloat)doesHitLine:(HPVector)v0 v1:(HPVector)v1
1315{
1316 Vector u0 = HPVectorToVector(HPvector_between(position, v0)); // relative to origin of model / octree
1318 Vector w0 = make_vector(dot_product(u0, v_right), dot_product(u0, v_up), dot_product(u0, v_forward)); // in ijk vectors
1320 return [octree isHitByLine:w0 v1:w1];
1321}
1322
1323- (GLfloat)doesHitLine:(HPVector)v0 v1:(HPVector)v1 hitEntity:(ShipEntity**)hitEntity
1324{
1325 if (hitEntity)
1326 hitEntity[0] = (ShipEntity*)nil;
1327 Vector u0 = HPVectorToVector(HPvector_between(position, v0)); // relative to origin of model / octree
1329 Vector w0 = make_vector(dot_product(u0, v_right), dot_product(u0, v_up), dot_product(u0, v_forward)); // in ijk vectors
1331 GLfloat hit_distance = [octree isHitByLine:w0 v1:w1];
1332 if (hit_distance) {
1333 if (hitEntity)
1334 hitEntity[0] = self;
1335 }
1336
1337 NSEnumerator* subEnum = nil;
1338 ShipEntity* se = nil;
1339 for (subEnum = [self shipSubEntityEnumerator]; (se = [subEnum nextObject]);) {
1342 u0 = HPVectorToVector(HPvector_between(p0, v0));
1343 u1 = HPVectorToVector(HPvector_between(p0, v1));
1344 w0 = resolveVectorInIJK(u0, ijk);
1345 w1 = resolveVectorInIJK(u1, ijk);
1346
1347 GLfloat hitSub = [se->octree isHitByLine:w0 v1:w1];
1348 if (hitSub && (hit_distance == 0 || hit_distance > hitSub)) {
1349 hit_distance = hitSub;
1350 if (hitEntity) {
1351 *hitEntity = se;
1352 }
1353 }
1354 }
1355
1356 return hit_distance;
1357}
1358
1359- (GLfloat)doesHitLine:(HPVector)v0 v1:(HPVector)v1 withPosition:(HPVector)o i:(Vector)i j:(Vector)j k:(Vector)k
1360{
1361 Vector u0 = HPVectorToVector(HPvector_between(o, v0)); // relative to origin of model / octree
1363 Vector w0 = make_vector(dot_product(u0, i), dot_product(u0, j), dot_product(u0, k)); // in ijk vectors
1364 Vector w1 = make_vector(dot_product(u1, j), dot_product(u1, j), dot_product(u1, k));
1365 return [octree isHitByLine:w0 v1:w1];
1366}
1367
1369{
1370 [super wasAddedToUniverse];
1371
1372 // if we have a universal id then we can proceed to set up any
1373 // stuff that happens when we get added to the UNIVERSE
1374 if (universalID != NO_TARGET) {
1375 // set up escorts
1376 if (([self status] == STATUS_IN_FLIGHT || [self status] == STATUS_LAUNCHING) && _pendingEscortCount != 0) // just popped into existence
1377 {
1378 [self setUpEscorts];
1379 } else {
1380 /* Earlier there was a silly log message here because I thought
1381 this would never happen, but wasn't entirely sure. Turns out
1382 it did!
1383 -- Ahruman 2009-09-13
1384 */
1386 }
1387 }
1388
1389 // Tell subentities, too
1390 [subEntities makeObjectsPerformSelector:@selector(wasAddedToUniverse)];
1391
1392 [self resetExhaustPlumes];
1393}
1394
1396{
1397 [subEntities makeObjectsPerformSelector:@selector(wasRemovedFromUniverse)];
1398}
1399
1404
1405- (NSString*)beaconCode
1406{
1407 return _beaconCode;
1408}
1409
1410- (void)setBeaconCode:(NSString*)bcode
1411{
1412 if ([bcode length] == 0)
1413 bcode = nil;
1414
1415 if (_beaconCode != bcode) {
1416 [_beaconCode release];
1417 _beaconCode = [bcode copy];
1418
1420 }
1421 // if not blanking code and label is currently blank, default label to code
1422 if (bcode != nil && (_beaconLabel == nil || [_beaconLabel length] == 0)) {
1423 [self setBeaconLabel:bcode];
1424 }
1425}
1426
1427- (NSString*)beaconLabel
1428{
1429 return _beaconLabel;
1430}
1431
1432- (void)setBeaconLabel:(NSString*)blabel
1433{
1434 if ([blabel length] == 0)
1435 blabel = nil;
1436
1437 if (_beaconLabel != blabel) {
1438 [_beaconLabel release];
1439 _beaconLabel = [OOExpand(blabel) retain];
1440 }
1441}
1442
1444{
1446}
1447
1449{
1450 return [self beaconCode] != nil;
1451}
1452
1453- (id<OOHUDBeaconIcon>)beaconDrawable
1454{
1455 if (_beaconDrawable == nil) {
1456 NSString* beaconCode = [self beaconCode];
1457 NSUInteger length = [beaconCode length];
1458
1459 if (length > 1) {
1460 NSArray* iconData = [[UNIVERSE descriptions] oo_arrayForKey:beaconCode];
1461 if (iconData != nil)
1462 _beaconDrawable = [[OOPolygonSprite alloc] initWithDataArray:iconData outlineWidth:0.5 name:beaconCode];
1463 }
1464
1465 if (_beaconDrawable == nil) {
1466 if (length > 0)
1467 _beaconDrawable = [[beaconCode substringToIndex:1] retain];
1468 else
1469 _beaconDrawable = @"";
1470 }
1471 }
1472
1473 return _beaconDrawable;
1474}
1475
1476- (Entity<OOBeaconEntity>*)prevBeacon
1477{
1479}
1480
1481- (Entity<OOBeaconEntity>*)nextBeacon
1482{
1484}
1485
1486- (void)setPrevBeacon:(Entity<OOBeaconEntity>*)beaconShip
1487{
1488 if (beaconShip != [self prevBeacon]) {
1489 [_prevBeacon release];
1490 _prevBeacon = [beaconShip weakRetain];
1491 }
1492}
1493
1494- (void)setNextBeacon:(Entity<OOBeaconEntity>*)beaconShip
1495{
1496 if (beaconShip != [self nextBeacon]) {
1497 [_nextBeacon release];
1498 _nextBeacon = [beaconShip weakRetain];
1499 }
1500}
1501
1502#define kBoulderRole (@"boulder")
1503
1504- (void)setIsBoulder:(BOOL)flag
1505{
1506 if (flag)
1507 [self addRole:kBoulderRole];
1508 else
1509 [self removeRole:kBoulderRole];
1510}
1511
1513{
1514 return [roleSet hasRole:kBoulderRole];
1515}
1516
1518{
1519 if ([self hasRole:@"asteroid"] || [self isBoulder]) {
1520 if (!noRocks) {
1521 return YES;
1522 }
1523 }
1524 return NO;
1525}
1526
1528{
1529 return [[self shipInfoDictionary] oo_boolForKey:@"counts_as_kill" defaultValue:YES];
1530}
1531
1533{
1534 // Ensure that we do not try to create escorts if we are an escort ship ourselves.
1535 // This could lead to circular reference memory overflows (e.g. "boa-mk2" trying to create 4 "boa-mk2"
1536 // escorts or the case of two ships specifying eachother as escorts) - Nikos 20090510
1537 if ([self isEscort]) {
1538 OOLogWARN(@"ship.setUp.escortShipCircularReference",
1539 @"Ship %@ requested escorts, when it is an escort ship itself. Avoiding possible circular reference overflow by ignoring escort setup.", self);
1540 return;
1541 }
1542
1543 if ([shipinfoDictionary objectForKey:@"escort_roles"] != nil) {
1544 [self setUpMixedEscorts];
1545 return;
1546 }
1547
1548 NSString* defaultRole = @"escort";
1549 NSString* escortRole = nil;
1550 NSString* escortShipKey = nil;
1551
1552 if (_pendingEscortCount == 0)
1553 return;
1554
1556 if ([self hasPrimaryRole:@"police"] || [self hasPrimaryRole:@"hunter"]) {
1557 _maxEscortCount = MAX_ESCORTS; // police and hunters get up to MAX_ESCORTS, overriding the 'escorts' key.
1558 [self updateEscortFormation];
1559 } else {
1560 _pendingEscortCount = _maxEscortCount; // other ships can only get what's defined inside their 'escorts' key.
1561 }
1562 }
1563
1564 if ([self isPolice])
1565 defaultRole = @"wingman";
1566
1567 escortRole = [shipinfoDictionary oo_stringForKey:@"escort_role" defaultValue:nil];
1568 if (escortRole == nil)
1569 escortRole = [shipinfoDictionary oo_stringForKey:@"escort-role" defaultValue:defaultRole];
1570 if (![escortRole isEqualToString:defaultRole]) {
1571 if (![[UNIVERSE newShipWithRole:escortRole] autorelease]) {
1572 escortRole = defaultRole;
1573 }
1574 }
1575
1576 escortShipKey = [shipinfoDictionary oo_stringForKey:@"escort_ship" defaultValue:nil];
1577 if (escortShipKey == nil)
1578 escortShipKey = [shipinfoDictionary oo_stringForKey:@"escort-ship"];
1579
1580 if (escortShipKey != nil) {
1581 if (![[UNIVERSE newShipWithName:escortShipKey] autorelease]) {
1582 escortShipKey = nil;
1583 } else {
1584 escortRole = [NSString stringWithFormat:@"[%@]", escortShipKey];
1585 }
1586 }
1587
1589 if ([self group] == nil) {
1590 [self setGroup:escortGroup]; // should probably become a copy of the escortGroup post NMSR.
1591 }
1592 [escortGroup setLeader:self];
1593
1595
1596 uint8_t currentEscortCount = [escortGroup count] - 1; // always at least 0.
1597
1598 while (_pendingEscortCount > 0 && ([self isThargoid] || currentEscortCount < _maxEscortCount)) {
1599 // The following line adds escort 1 in position 1, etc... up to MAX_ESCORTS.
1600 HPVector ex_pos = [self coordinatesForEscortPosition:currentEscortCount];
1601
1602 ShipEntity* escorter = nil;
1603
1604 escorter = [UNIVERSE newShipWithRole:escortRole]; // retained
1605
1606 if (escorter == nil)
1607 break;
1608 [self setUpOneEscort:escorter inGroup:escortGroup withRole:escortRole atPosition:ex_pos andCount:currentEscortCount];
1609
1610 [escorter release];
1611
1613 currentEscortCount = [escortGroup count] - 1;
1614 }
1615 // done assigning escorts
1617}
1618
1620{
1621 NSArray* escortRoles = [shipinfoDictionary oo_arrayForKey:@"escort_roles" defaultValue:nil];
1622 if (escortRoles == nil) {
1623 OOLogWARN(@"eship.setUp.escortShipRoles",
1624 @"Ship %@ has bad escort_roles definition.", self);
1625 return;
1626 }
1627 NSDictionary* escortDefinition = nil;
1628 NSDictionary* systeminfo = nil;
1629 OOGovernmentID government;
1630
1631 systeminfo = [UNIVERSE currentSystemData];
1632 government = [systeminfo oo_unsignedCharForKey:KEY_GOVERNMENT];
1633
1634 OOShipGroup* escortGroup = [self escortGroup];
1635 if ([self group] == nil) {
1636 [self setGroup:escortGroup]; // should probably become a copy of the escortGroup post NMSR.
1637 }
1638 [escortGroup setLeader:self];
1639 _maxEscortCount = MAX_ESCORTS;
1641
1642 uint8_t currentEscortCount = [escortGroup count] - 1; // always at least 0
1643
1644 _maxEscortCount = 0;
1645 int8_t i = 0;
1646 foreach (escortDefinition, escortRoles) {
1647 if (currentEscortCount >= MAX_ESCORTS) {
1648 break;
1649 }
1650 // int rather than uint because, at least for min, there is a
1651 // use to giving a negative value
1652 int8_t min = [escortDefinition oo_intForKey:@"min" defaultValue:0];
1653 int8_t max = [escortDefinition oo_intForKey:@"max" defaultValue:2];
1654 NSString* escortRole = [escortDefinition oo_stringForKey:@"role" defaultValue:@"escort"];
1655 int8_t desired = max;
1656 if (min < desired) {
1657 for (i = min; i < max; i++) {
1658 if (Ranrot() % 11 < government + 2) {
1659 desired--;
1660 }
1661 }
1662 }
1663 for (i = 0; i < desired; i++) {
1664 if (currentEscortCount >= MAX_ESCORTS) {
1665 break;
1666 }
1667 if (![escortRole isEqualToString:@""]) {
1668 HPVector ex_pos = [self coordinatesForEscortPosition:currentEscortCount];
1669 ShipEntity* escorter = [UNIVERSE newShipWithRole:escortRole]; // retained
1670 if (escorter == nil) {
1671 break;
1672 }
1673 [self setUpOneEscort:escorter inGroup:escortGroup withRole:escortRole atPosition:ex_pos andCount:currentEscortCount];
1674 [escorter release];
1675 }
1676 currentEscortCount++;
1677 _maxEscortCount++;
1678 }
1679 }
1680 // done assigning escorts
1681 _pendingEscortCount = 0;
1682}
1683
1684- (void)setUpOneEscort:(ShipEntity*)escorter inGroup:(OOShipGroup*)escortGroup withRole:(NSString*)escortRole atPosition:(HPVector)ex_pos andCount:(uint8_t)currentEscortCount
1685{
1686 NSString* autoAI = nil;
1687 NSString* pilotRole = nil;
1688 NSDictionary* autoAIMap = nil;
1689 NSDictionary* escortShipDict = nil;
1690 AI* escortAI = nil;
1691 NSString* defaultRole = @"escort";
1692
1693 if ([self isPolice]) {
1694 defaultRole = @"wingman";
1695 pilotRole = @"police"; // police are always insured.
1696 } else {
1697 pilotRole = bounty ? @"pirate" : @"hunter"; // hunters have insurancies, pirates not.
1698 }
1699
1700 double dd = escorter->collision_radius;
1701
1702 if (EXPECT(currentEscortCount < (uint8_t)MAX_ESCORTS)) {
1703 // spread them around a little randomly
1704 ex_pos.x += dd * 6.0 * (randf() - 0.5);
1705 ex_pos.y += dd * 6.0 * (randf() - 0.5);
1706 ex_pos.z += dd * 6.0 * (randf() - 0.5);
1707 } else {
1708 // Thargoid armada(!) Add more distance between the 'escorts'.
1709 ex_pos.x += dd * 12.0 * (randf() - 0.5);
1710 ex_pos.y += dd * 12.0 * (randf() - 0.5);
1711 ex_pos.z += dd * 12.0 * (randf() - 0.5);
1712 }
1713
1714 [escorter setPosition:ex_pos]; // minimise lollipop flash
1715
1716 if ([escorter crew] == nil) {
1717 [escorter setSingleCrewWithRole:pilotRole];
1718 }
1719
1720 [escorter setPrimaryRole:defaultRole]; // for mothership
1721 // in case this hasn't yet been set, make sure escorts get a real scan class
1722 // shouldn't happen very often, but is possible
1723 if (scanClass == CLASS_NOT_SET) {
1724 scanClass = CLASS_NEUTRAL;
1725 }
1726 [escorter setScanClass:scanClass]; // you are the same as I
1727
1728 if ([self bounty] == 0)
1729 [escorter setBounty:0 withReason:kOOLegalStatusReasonSetup]; // Avoid dirty escorts for clean mothers
1730
1731 // find the right autoAI.
1732 escortShipDict = [escorter shipInfoDictionary];
1733 autoAIMap = [ResourceManager dictionaryFromFilesNamed:@"autoAImap.plist" inFolder:@"Config" andMerge:YES];
1734 autoAI = [autoAIMap oo_stringForKey:defaultRole];
1735 if (autoAI == nil) // no 'wingman' defined in autoAImap?
1736 {
1737 autoAI = [autoAIMap oo_stringForKey:@"escort" defaultValue:@"nullAI.plist"];
1738 }
1739
1740 escortAI = [escorter getAI];
1741
1742 // Let the populator decide which AI to use, unless we have a working alternative AI & we specify auto_ai = NO !
1743 if ((escortRole && [escortShipDict oo_fuzzyBooleanForKey:@"auto_ai" defaultValue:YES])
1744 || ([[escortAI name] isEqualToString:@"nullAI.plist"] && ![autoAI isEqualToString:@"nullAI.plist"])) {
1745 [escorter switchAITo:autoAI];
1746 }
1747
1748 [escorter setGroup:escortGroup];
1749 [escorter setOwner:self]; // mark self as group leader
1750
1751 if ([self status] == STATUS_DOCKED) {
1752 [[self owner] addShipToLaunchQueue:escorter withPriority:NO];
1753 } else {
1754 [UNIVERSE addEntity:escorter]; // STATUS_IN_FLIGHT, AI state GLOBAL
1755 [escortAI setState:@"FLYING_ESCORT"]; // Begin escort flight. (If the AI doesn't define FLYING_ESCORT, this has no effect.)
1756 [escorter doScriptEvent:OOJSID("spawnedAsEscort") withArgument:self];
1757 }
1758
1759 if ([escorter heatInsulation] < [self heatInsulation])
1760 [escorter setHeatInsulation:[self heatInsulation]]; // give escorts same protection as mother.
1761 if (([escorter maxFlightSpeed] < cruiseSpeed) && ([escorter maxFlightSpeed] > cruiseSpeed * 0.3))
1762 cruiseSpeed = [escorter maxFlightSpeed] * 0.99; // adapt patrolSpeed to the slowest escort but ignore the very slow ones.
1763
1764 if (bounty) {
1765 int extra = 1 | (ranrot_rand() & 15);
1766 // if mothership is offender, make sure escorter is too.
1767 [escorter markAsOffender:extra withReason:kOOLegalStatusReasonSetup];
1768 } else {
1769 // otherwise force the escort to be clean
1770 [escorter setBounty:0 withReason:kOOLegalStatusReasonSetup];
1771 }
1772}
1773
1774- (NSString*)shipDataKey
1775{
1776 return _shipKey;
1777}
1778
1780{
1781 return [[[NSString alloc] initWithFormat:@"[%@]", [self shipDataKey]] autorelease];
1782}
1783
1784- (void)setShipDataKey:(NSString*)key
1785{
1787 _shipKey = [key copy];
1788}
1789
1790- (NSDictionary*)shipInfoDictionary
1791{
1792 return shipinfoDictionary;
1793}
1794
1795#define MAKE_VECTOR_ARRAY(v) [[[OONativeVector alloc] initWithVector:v] autorelease]
1796
1797- (NSArray*)getWeaponOffsetFrom:(NSDictionary*)dict withKey:(NSString*)key inMode:(NSString*)mode
1798{
1799 Vector offset;
1800 if ([mode isEqualToString:@"single"]) {
1801 offset = vector_multiply_scalar([dict oo_vectorForKey:key defaultValue:kZeroVector], _scaleFactor);
1802 return [NSArray arrayWithObject:MAKE_VECTOR_ARRAY(offset)];
1803 } else {
1804 NSArray* offsets = [dict oo_arrayForKey:key defaultValue:nil];
1805 if (offsets == nil) {
1807 return [NSArray arrayWithObject:MAKE_VECTOR_ARRAY(offset)];
1808 }
1809 NSMutableArray* output = [NSMutableArray arrayWithCapacity:[offsets count]];
1810 NSUInteger i;
1811 for (i = 0; i < [offsets count]; i++) {
1812 offset = vector_multiply_scalar([offsets oo_vectorAtIndex:i defaultValue:kZeroVector], _scaleFactor);
1813 [output addObject:MAKE_VECTOR_ARRAY(offset)];
1814 }
1815 return [NSArray arrayWithArray:output];
1816 }
1817}
1818
1820{
1821 return aftWeaponOffset;
1822}
1823
1825{
1826 return forwardWeaponOffset;
1827}
1828
1830{
1831 return portWeaponOffset;
1832}
1833
1835{
1836 return starboardWeaponOffset;
1837}
1838
1840{
1841 return isFrangible;
1842}
1843
1848
1850{
1852 return CLASS_NO_DRAW;
1853 return scanClass;
1854}
1855
1857
1859{
1860 int status = [self status];
1861 if (status == STATUS_COCKPIT_DISPLAY || status == STATUS_DEAD || status == STATUS_BEING_SCOOPED) {
1862 return NO;
1863 }
1864
1865 if (isWreckage) {
1866 // wreckage won't collide
1867 return NO;
1868 }
1869
1870 if (isMissile && [self shotTime] < 0.25) // not yet fused
1871 {
1872 return NO;
1873 }
1874
1875 return YES;
1876}
1877
1879{
1880 // octree check
1881 Octree* prime_octree = prime->octree;
1882 Octree* other_octree = other->octree;
1883
1884 HPVector prime_position = [prime absolutePositionForSubentity];
1886 HPVector other_position = [other absolutePositionForSubentity];
1888
1889 Vector relative_position_of_other = resolveVectorInIJK(HPVectorToVector(HPvector_between(prime_position, other_position)), prime_ijk);
1890 Triangle relative_ijk_of_other;
1891 relative_ijk_of_other.v[0] = resolveVectorInIJK(other_ijk.v[0], prime_ijk);
1892 relative_ijk_of_other.v[1] = resolveVectorInIJK(other_ijk.v[1], prime_ijk);
1893 relative_ijk_of_other.v[2] = resolveVectorInIJK(other_ijk.v[2], prime_ijk);
1894
1895 // check hull octree against other hull octree
1896 if ([prime_octree isHitByOctree:other_octree
1897 withOrigin:relative_position_of_other
1898 andIJK:relative_ijk_of_other]) {
1899 return other;
1900 }
1901
1902 // check prime subentities against the other's hull
1903 NSArray* prime_subs = prime->subEntities;
1904 if (prime_subs) {
1905 NSUInteger i, n_subs = [prime_subs count];
1906 for (i = 0; i < n_subs; i++) {
1907 Entity* se = [prime_subs objectAtIndex:i];
1908 if ([se isShip] && [se canCollide] && doOctreesCollide((ShipEntity*)se, other))
1909 return other;
1910 }
1911 }
1912
1913 // check prime hull against the other's subentities
1914 NSArray* other_subs = other->subEntities;
1915 if (other_subs) {
1916 NSUInteger i, n_subs = [other_subs count];
1917 for (i = 0; i < n_subs; i++) {
1918 Entity* se = [other_subs objectAtIndex:i];
1919 if ([se isShip] && [se canCollide] && doOctreesCollide(prime, (ShipEntity*)se))
1920 return (ShipEntity*)se;
1921 }
1922 }
1923
1924 // check prime subenties against the other's subentities
1925 if ((prime_subs) && (other_subs)) {
1926 NSUInteger i, n_osubs = [other_subs count];
1927 for (i = 0; i < n_osubs; i++) {
1928 Entity* oe = [other_subs objectAtIndex:i];
1929 if ([oe isShip] && [oe canCollide]) {
1930 NSUInteger j, n_psubs = [prime_subs count];
1931 for (j = 0; j < n_psubs; j++) {
1932 Entity* pe = [prime_subs objectAtIndex:j];
1933 if ([pe isShip] && [pe canCollide] && doOctreesCollide((ShipEntity*)pe, (ShipEntity*)oe))
1934 return (ShipEntity*)oe;
1935 }
1936 }
1937 }
1938 }
1939
1940 // fall through => no collision
1941 return nil;
1942}
1943
1944- (BOOL)checkCloseCollisionWith:(Entity*)other
1945{
1946 if (other == nil)
1947 return NO;
1948 if ([collidingEntities containsObject:other])
1949 return NO; // we know about this already!
1950
1951 ShipEntity* otherShip = nil;
1952 if ([other isShip])
1953 otherShip = (ShipEntity*)other;
1954
1955 if ([self canScoop:otherShip])
1956 return YES; // quick test - could this improve scooping for small ships? I think so!
1957
1958 if (otherShip != nil && trackCloseContacts) {
1959 // in update we check if close contacts have gone out of touch range (origin within our collision_radius)
1960 // here we check if something has come within that range
1961 HPVector otherPos = [otherShip position];
1963 NSString* other_key = [NSString stringWithFormat:@"%d", otherID];
1964
1965 if (![closeContactsInfo objectForKey:other_key] && HPdistance2(position, otherPos) < collision_radius * collision_radius) {
1966 // calculate position with respect to our own position and orientation
1969 [closeContactsInfo setObject:[NSString stringWithFormat:@"%f %f %f", rpos.x, rpos.y, rpos.z] forKey:other_key];
1970
1971 // send AI a message about the touch
1974 [self doScriptEvent:OOJSID("shipCloseContact") withArgument:otherShip andReactToAIMessage:@"CLOSE CONTACT"];
1975 _primaryTarget = temp;
1976 }
1977 }
1978
1979 /* This does not appear to save a significant amount of time in
1980 * most situations. No significant change in frame rate with a
1981 * 350-segment planetary ring at 1400 collision candidates, even
1982 * on old hardware. There are perhaps situations in which it could
1983 * be a significant optimisation, but those are likely to also be
1984 * the situations where the effect of adding hundreds of extra
1985 * false-positive collisions leaves the player returning to a
1986 * mess... So, commented out: CIM 21 Jan 2014
1987 if (zero_distance > CLOSE_COLLISION_CHECK_MAX_RANGE2) // don't work too hard on entities that are far from the player
1988 return YES;
1989 */
1990
1991 if (otherShip != nil) {
1992 // check hull octree versus other hull octree
1993 collider = doOctreesCollide(self, otherShip);
1994 return (collider != nil);
1995 }
1996
1997 // default at this stage is to say YES they've collided!
1998 collider = other;
1999 return YES;
2000}
2001
2003{
2004 return [[self mesh] findSubentityBoundingBoxWithPosition:HPVectorToVector(position) rotMatrix:rotMatrix];
2005}
2006
2008{
2010 Entity* last = nil;
2011 Entity* father = self;
2012 OOMatrix r_mat;
2013
2014 while ((father) && (father != last) && (father != NO_TARGET)) {
2015 r_mat = [father drawRotationMatrix];
2016 result.v[0] = OOVectorMultiplyMatrix(result.v[0], r_mat);
2017 result.v[1] = OOVectorMultiplyMatrix(result.v[1], r_mat);
2018 result.v[2] = OOVectorMultiplyMatrix(result.v[2], r_mat);
2019
2020 last = father;
2021 if (![last isSubEntity])
2022 break;
2023 father = [father owner];
2024 }
2025 return result;
2026}
2027
2028- (void)addSubentityToCollisionRadius:(Entity<OOSubEntity>*)subent
2029{
2030 if (!subent)
2031 return;
2032
2033 double distance = HPmagnitude([subent position]) + [subent findCollisionRadius];
2034 if ([subent isKindOfClass:[ShipEntity class]]) // Solid subentity
2035 {
2036 if (distance > collision_radius) {
2037 collision_radius = distance;
2038 }
2039
2040 mass += [subent mass];
2041 }
2042 if (distance > _profileRadius) {
2043 _profileRadius = distance;
2044 }
2045}
2046
2047- (ShipEntity*)launchPodWithCrew:(NSArray*)podCrew
2048{
2049 ShipEntity* pod = nil;
2050
2051 pod = [UNIVERSE newShipWithRole:[shipinfoDictionary oo_stringForKey:@"escape_pod_role"]]; // or nil
2052 if (!pod) {
2053 // _role not defined? it might have _model defined;
2054 pod = [UNIVERSE newShipWithRole:[shipinfoDictionary oo_stringForKey:@"escape_pod_model" defaultValue:@"escape-capsule"]];
2055 if (!pod) {
2056 pod = [UNIVERSE newShipWithRole:@"escape-capsule"];
2057 OOLog(@"shipEntity.noEscapePod", @"Ship %@ has no correct escape_pod_role defined. Now using default capsule.", self);
2058 }
2059 }
2060
2061 if (pod) {
2062 [pod setOwner:self];
2064 [pod setCommodity:@"slaves" andAmount:1];
2065 [pod setCrew:podCrew];
2066 [pod switchAITo:@"oolite-shuttleAI.js"];
2067 [self dumpItem:pod]; // CLASS_CARGO, STATUS_IN_FLIGHT, AI state GLOBAL
2068 [pod release]; // release
2069 }
2070
2071 return pod;
2072}
2073
2075{
2076 if (shipinfoDictionary == nil) {
2077 OOLog(@"shipEntity.notDict", @"Ship %@ was not set up from dictionary.", self);
2078 return NO;
2079 }
2080 return [super validForAddToUniverse];
2081}
2082
2083- (void)update:(OOTimeDelta)delta_t
2084{
2085 if (shipinfoDictionary == nil) {
2086 OOLog(@"shipEntity.notDict", @"Ship %@ was not set up from dictionary.", self);
2087 [UNIVERSE removeEntity:self];
2088 return;
2089 }
2090
2091 if (!isfinite(maxFlightSpeed)) {
2092 OOLog(@"ship.sanityCheck.failed", @"Ship %@ %@ infinite top speed, clamped to 300.", self, @"had");
2093 maxFlightSpeed = 300;
2094 }
2095
2096 bool isSubEnt = [self isSubEntity];
2097
2098 if (isDemoShip) {
2099 if (demoRate > 0) {
2100 OOScalar cos1 = cos(M_PI * ([UNIVERSE getTime] - demoStartTime) * demoRate / 11);
2101 OOScalar sin1 = sin(M_PI * ([UNIVERSE getTime] - demoStartTime) * demoRate / 11);
2102 OOScalar cos2 = cos(-M_PI * ([UNIVERSE getTime] - demoStartTime) * demoRate / 15);
2103 OOScalar sin2 = sin(-M_PI * ([UNIVERSE getTime] - demoStartTime) * demoRate / 15);
2104 Quaternion q1 = make_quaternion(cos1, sin1 * sqrt(3) / 2, sin1 / 2, 0);
2105 Quaternion q2 = make_quaternion(cos2, -sin2 * sqrt(4) / sqrt(5), 0, sin2 * sqrt(1) / sqrt(5));
2106 [self setOrientation:quaternion_multiply(q2, quaternion_multiply(q1, demoStartOrientation))];
2107 }
2108
2109 [super update:delta_t];
2110 if ([self subEntityCount] > 0) {
2111 // only copy the subent array if there are subentities
2112 ShipEntity* se = nil;
2113 foreach (se, [self subEntities]) {
2114 [se update:delta_t];
2115 if ([se isShip]) {
2119 }
2120 }
2121 }
2122 return;
2123 }
2124
2125 if (!isSubEnt) {
2126 if (scanClass == CLASS_NOT_SET) {
2127 scanClass = CLASS_NEUTRAL;
2128 OOLog(@"ship.sanityCheck.failed", @"Ship %@ %@ with scanClass CLASS_NOT_SET; forced to CLASS_NEUTRAL.", self, [self primaryRole]);
2129 }
2130
2131 [self updateTrackingCurve];
2132
2133 //
2134 // deal with collisions
2135 //
2136 [self manageCollisions];
2137
2138 // subentity collisions managed via parent entity
2139
2140 //
2141 // reset any inadvertant legal mishaps
2142 //
2143 if (scanClass == CLASS_POLICE) {
2144 if (bounty > 0) {
2145 [self setBounty:0 withReason:kOOLegalStatusReasonPoliceAreClean];
2146 }
2147 ShipEntity* target = [self primaryTarget];
2148 if ((target) && ([target scanClass] == CLASS_POLICE)) {
2149 [self noteLostTarget];
2150 }
2151 }
2152
2153 if (trackCloseContacts) {
2154 // in checkCloseCollisionWith: we check if some thing has come within touch range (origin within our collision_radius)
2155 // here we check if it has gone outside that range
2156 NSString* other_key = nil;
2157
2158 // create a temp copy to iterate over, since we may want to
2159 // change the original
2160 NSDictionary* closeContactsTemp = [[NSDictionary alloc] initWithDictionary:closeContactsInfo];
2161 foreachkey(other_key, closeContactsTemp)
2162 {
2163 ShipEntity* other = [UNIVERSE entityForUniversalID:[other_key intValue]];
2164 if ((other != nil) && (other->isShip)) {
2165 if (HPdistance2(position, other->position) > collision_radius * collision_radius) // moved beyond our sphere!
2166 {
2167 // calculate position with respect to our own position and orientation
2170 Vector pos0 = { 0, 0, 0 };
2171 ScanVectorFromString([closeContactsInfo objectForKey:other_key], &pos0);
2172 // send AI messages about the contact
2175 if ((pos0.x < 0.0) && (pos1.x > 0.0)) {
2176 [self doScriptEvent:OOJSID("shipTraversePositiveX") withArgument:other andReactToAIMessage:@"POSITIVE X TRAVERSE"];
2177 }
2178 if ((pos0.x > 0.0) && (pos1.x < 0.0)) {
2179 [self doScriptEvent:OOJSID("shipTraverseNegativeX") withArgument:other andReactToAIMessage:@"NEGATIVE X TRAVERSE"];
2180 }
2181 if ((pos0.y < 0.0) && (pos1.y > 0.0)) {
2182 [self doScriptEvent:OOJSID("shipTraversePositiveY") withArgument:other andReactToAIMessage:@"POSITIVE Y TRAVERSE"];
2183 }
2184 if ((pos0.y > 0.0) && (pos1.y < 0.0)) {
2185 [self doScriptEvent:OOJSID("shipTraverseNegativeY") withArgument:other andReactToAIMessage:@"NEGATIVE Y TRAVERSE"];
2186 }
2187 if ((pos0.z < 0.0) && (pos1.z > 0.0)) {
2188 [self doScriptEvent:OOJSID("shipTraversePositiveZ") withArgument:other andReactToAIMessage:@"POSITIVE Z TRAVERSE"];
2189 }
2190 if ((pos0.z > 0.0) && (pos1.z < 0.0)) {
2191 [self doScriptEvent:OOJSID("shipTraverseNegativeZ") withArgument:other andReactToAIMessage:@"NEGATIVE Z TRAVERSE"];
2192 }
2193 _primaryTarget = temp;
2194 [closeContactsInfo removeObjectForKey:other_key];
2195 }
2196 } else {
2197 [closeContactsInfo removeObjectForKey:other_key];
2198 }
2199 }
2200 [closeContactsTemp release];
2201 } // end if trackCloseContacts
2202
2203 } // end if !isSubEntity
2204
2205#ifdef OO_DEBUG_MONITOR_ENABLED
2206 // DEBUGGING
2207 if (reportAIMessages && (debugLastBehaviour != behaviour)) {
2208 OOLog(kOOLogEntityBehaviourChanged, @"%@ behaviour is now %@", self, OOStringFromBehaviour(behaviour));
2209 debugLastBehaviour = behaviour;
2210 }
2211#endif
2212
2213 // cool all weapons.
2214 weapon_temp = fmaxf(weapon_temp - (float)(WEAPON_COOLING_FACTOR * delta_t), 0.0f);
2215 forward_weapon_temp = fmaxf(forward_weapon_temp - (float)(WEAPON_COOLING_FACTOR * delta_t), 0.0f);
2216 aft_weapon_temp = fmaxf(aft_weapon_temp - (float)(WEAPON_COOLING_FACTOR * delta_t), 0.0f);
2217 port_weapon_temp = fmaxf(port_weapon_temp - (float)(WEAPON_COOLING_FACTOR * delta_t), 0.0f);
2218 starboard_weapon_temp = fmaxf(starboard_weapon_temp - (float)(WEAPON_COOLING_FACTOR * delta_t), 0.0f);
2219
2220 // update time between shots
2221 shot_time += delta_t;
2222
2223 // handle radio message effects
2224 if (messageTime > 0.0) {
2225 messageTime -= delta_t;
2226 if (messageTime < 0.0)
2227 messageTime = 0.0;
2228 }
2229
2230 // temperature factors
2231 if (!isSubEnt) {
2232 double external_temp = 0.0;
2233 OOSunEntity* sun = [UNIVERSE sun];
2234 if (sun != nil) {
2235 // set the ambient temperature here
2236 double sun_zd = HPdistance2(position, [sun position]); // square of distance
2237 double sun_cr = sun->collision_radius;
2238 double alt1 = sun_cr * sun_cr / sun_zd;
2239 external_temp = SUN_TEMPERATURE * alt1;
2240 if ([sun goneNova])
2241 external_temp *= 100;
2242
2243 if ([self hasFuelScoop] && alt1 > 0.75 && [self fuel] < [self fuelCapacity]) {
2244 fuel_accumulator += (float)(delta_t * flightSpeed * 0.010 / [self fuelChargeRate]);
2245 // are we fast enough to collect any fuel?
2246 while (fuel_accumulator > 1.0f) {
2247 [self setFuel:[self fuel] + 1];
2248 fuel_accumulator -= 1.0f;
2249 [self doScriptEvent:OOJSID("shipScoopedFuel")];
2250 }
2251 }
2252 }
2253
2254 // work on the ship temperature
2255 //
2256 float heatThreshold = [self heatInsulation] * 100.0f;
2257 if (external_temp > heatThreshold && external_temp > ship_temperature)
2258 ship_temperature += (external_temp - ship_temperature) * delta_t * SHIP_INSULATION_FACTOR / [self heatInsulation];
2259 else {
2261 ship_temperature += (external_temp - heatThreshold - ship_temperature) * delta_t * SHIP_COOLING_FACTOR / [self heatInsulation];
2264 }
2265 }
2266 } else // subents
2267 {
2269 }
2270
2272 [self takeHeatDamage:delta_t * ship_temperature];
2273
2274 // are we burning due to low energy
2275 if ((energy < maxEnergy * 0.20) && _showDamage) // prevents asteroid etc. from burning
2276 throw_sparks = YES;
2277
2278 // burning effects
2279 if (throw_sparks) {
2280 next_spark_time -= delta_t;
2281 if (next_spark_time < 0.0) {
2282 [self throwSparks];
2283 throw_sparks = NO; // until triggered again
2284 }
2285 }
2286
2287 if (!isSubEnt) {
2288
2289 // cloaking device
2290 if ([self hasCloakingDevice]) {
2295 if (energy < 0)
2296 energy = 0;
2297 }
2298 }
2299 }
2300
2301 // military_jammer
2302 if ([self hasMilitaryJammer]) {
2307 if (energy < 0)
2308 energy = 0;
2309 }
2310 } else {
2313 }
2314 }
2315
2316 // check outside factors
2317 /* aegis checks are expensive, so only do them once every km or so of flight
2318 * unlikely to be important otherwise. (every 100m if already close to
2319 * planet, to watch for surface)
2320
2321 * if have non-zero inertial velocity, need to check every frame,
2322 * as distanceTravelled does not include this component - CIM */
2324 aegis_status = [self checkForAegis]; // is a station or something nearby??
2325 if (aegis_status == AEGIS_NONE) {
2326 // in open space: check every km
2328 } else {
2329 // near planets: check every 100m
2331 }
2332 }
2333 } // end if !isSubEntity
2334
2335 // scripting
2337 // When crashing into a boulder, STATUS_LAUNCHING is sometimes skipped on scooping the resulting splinters.
2338 OOEntityStatus status = [self status];
2339 if (script != nil && (status == STATUS_IN_FLIGHT || status == STATUS_LAUNCHING || status == STATUS_BEING_SCOOPED || (status == STATUS_ACTIVE && self == [UNIVERSE station]))) {
2340 [PLAYER setScriptTarget:self];
2341 [self doScriptEvent:OOJSID("shipSpawned")];
2342 if ([self status] != STATUS_DEAD)
2343 [PLAYER doScriptEvent:OOJSID("shipSpawned") withArgument:self];
2344 }
2346 }
2347 /* No point in starting the AI if still launching */
2348 if (!haveStartedJSAI && [self status] != STATUS_LAUNCHING) {
2349 haveStartedJSAI = YES;
2350 [self doScriptEvent:OOJSID("aiStarted")];
2351 }
2352
2353 // behaviours according to status and behaviour
2354 //
2355 if ([self status] == STATUS_LAUNCHING) {
2356 if ([UNIVERSE getTime] > launch_time + launch_delay) // move for while before thinking
2357 {
2358 StationEntity* stationLaunchedFrom = [UNIVERSE nearestEntityMatchingPredicate:IsStationPredicate parameter:NULL relativeToEntity:self];
2359 [self setStatus:STATUS_IN_FLIGHT];
2360 // awaken JS-based AIs
2361 haveStartedJSAI = YES;
2362 [self doScriptEvent:OOJSID("aiStarted")];
2363 [self doScriptEvent:OOJSID("shipLaunchedFromStation") withArgument:stationLaunchedFrom];
2364 [shipAI reactToMessage:@"LAUNCHED OKAY" context:@"launched"];
2365 } else {
2366 // ignore behaviour just keep moving...
2367 flightYaw = 0.0;
2368 [self applyAttitudeChanges:delta_t];
2369 [self applyThrust:delta_t];
2370 if (energy < maxEnergy) {
2371 energy += energy_recharge_rate * delta_t;
2372 if (energy > maxEnergy) {
2373 energy = maxEnergy;
2374 [self doScriptEvent:OOJSID("shipEnergyBecameFull")];
2375 [shipAI message:@"ENERGY_FULL"];
2376 }
2377 }
2378
2379 if ([self subEntityCount] > 0) {
2380 // only copy the subent array if there are subentities
2381 ShipEntity* se = nil;
2382 foreach (se, [self subEntities]) {
2383 [se update:delta_t];
2384 }
2385 }
2386 // super update
2387 [super update:delta_t];
2388
2389 return;
2390 }
2391 }
2392 //
2393 // double check scooped behaviour
2394 //
2395 if ([self status] == STATUS_BEING_SCOOPED) {
2396 // if we are being tractored, but we have no owner, then we have a problem
2397 if (behaviour != BEHAVIOUR_TRACTORED || [self owner] == nil || [self owner] == self || [self owner] == NO_TARGET) {
2398 // escaped tractor beam
2399 [self setStatus:STATUS_IN_FLIGHT]; // should correct 'uncollidable objects' bug
2400 behaviour = BEHAVIOUR_IDLE;
2401 frustration = 0.0;
2402 [self setOwner:self];
2403 [shipAI exitStateMachineWithMessage:nil]; // Escapepods and others should continue their old AI here.
2404 }
2405 }
2406
2407 if ([self status] == STATUS_COCKPIT_DISPLAY) {
2408 flightYaw = 0.0;
2409 [self applyAttitudeChanges:delta_t];
2410 GLfloat range2 = 0.1 * HPdistance2(position, _destination) / (collision_radius * collision_radius);
2411 if ((range2 > 1.0) || (velocity.z > 0.0))
2412 range2 = 1.0;
2414 } else {
2415 [self processBehaviour:delta_t];
2416
2417 // manage energy
2418 if (energy < maxEnergy) {
2419 energy += energy_recharge_rate * delta_t;
2420 if (energy > maxEnergy) {
2421 energy = maxEnergy;
2422 [self doScriptEvent:OOJSID("shipEnergyBecameFull")];
2423 [shipAI message:@"ENERGY_FULL"];
2424 }
2425 }
2426
2427 if (!isSubEnt) {
2428 // update destination position for escorts
2430 if ([self hasEscorts]) {
2431 ShipEntity* escort = nil;
2432 unsigned i = 0;
2433 // Note: works on escortArray rather than escortEnumerator because escorts may be mutated.
2434 foreach (escort, [self escortArray]) {
2436 }
2437
2438 ShipEntity* leader = [[self escortGroup] leader];
2439 if (leader != nil && ([leader scanClass] != [self scanClass])) {
2440 OOLog(@"ship.sanityCheck.failed", @"Ship %@ escorting %@ with wrong scanclass!", self, leader);
2441 [[self escortGroup] removeShip:self];
2442 [self setEscortGroup:nil];
2443 }
2444 }
2445 }
2446 }
2447
2448 // rotational velocity
2451 qf.w *= (1.0 - delta_t);
2452 qf.x *= delta_t;
2453 qf.y *= delta_t;
2454 qf.z *= delta_t;
2455 [self setOrientation:quaternion_multiply(qf, orientation)];
2456 }
2457
2458 // reset totalBoundingBox
2460
2461 // super update
2462 [super update:delta_t];
2463
2464 // update subentities
2465
2466 if ([self subEntityCount] > 0) {
2467 // only copy the subent array if there are subentities
2468 ShipEntity* se = nil;
2469 foreach (se, [self subEntities]) {
2470 [se update:delta_t];
2471 if ([se isShip]) {
2475 }
2476 }
2477 }
2478
2479 if (aiScriptWakeTime > 0 && [PLAYER clockTimeAdjusted] > aiScriptWakeTime) {
2480 aiScriptWakeTime = 0;
2481 [self doScriptEvent:OOJSID("aiAwoken")];
2482 }
2483}
2484
2485- (void)processBehaviour:(OOTimeDelta)delta_t
2486{
2487 BOOL applyThrust = YES;
2488 switch (behaviour) {
2489 case BEHAVIOUR_TUMBLE:
2490 [self behaviour_tumble:delta_t];
2491 break;
2492
2493 case BEHAVIOUR_STOP_STILL:
2494 case BEHAVIOUR_STATION_KEEPING:
2495 [self behaviour_stop_still:delta_t];
2496 break;
2497
2498 case BEHAVIOUR_IDLE:
2499 if ([self isSubEntity]) {
2500 applyThrust = NO;
2501 }
2502 [self behaviour_idle:delta_t];
2503 break;
2504
2505 case BEHAVIOUR_TRACTORED:
2506 [self behaviour_tractored:delta_t];
2507 break;
2508
2509 case BEHAVIOUR_TRACK_TARGET:
2510 [self behaviour_track_target:delta_t];
2511 break;
2512
2513 case BEHAVIOUR_INTERCEPT_TARGET:
2514 case BEHAVIOUR_COLLECT_TARGET:
2515 [self behaviour_intercept_target:delta_t];
2516 break;
2517
2518 case BEHAVIOUR_ATTACK_TARGET:
2519 [self behaviour_attack_target:delta_t];
2520 break;
2521
2522 case BEHAVIOUR_ATTACK_FLY_TO_TARGET_SIX:
2523 case BEHAVIOUR_ATTACK_FLY_TO_TARGET_TWELVE:
2524 [self behaviour_fly_to_target_six:delta_t];
2525 break;
2526
2527 case BEHAVIOUR_ATTACK_MINING_TARGET:
2528 [self behaviour_attack_mining_target:delta_t];
2529 break;
2530
2531 case BEHAVIOUR_ATTACK_FLY_TO_TARGET:
2532 [self behaviour_attack_fly_to_target:delta_t];
2533 break;
2534
2535 case BEHAVIOUR_ATTACK_FLY_FROM_TARGET:
2536 [self behaviour_attack_fly_from_target:delta_t];
2537 break;
2538
2539 case BEHAVIOUR_ATTACK_BREAK_OFF_TARGET:
2540 [self behaviour_attack_break_off_target:delta_t];
2541 break;
2542
2543 case BEHAVIOUR_ATTACK_SLOW_DOGFIGHT:
2544 [self behaviour_attack_slow_dogfight:delta_t];
2545 break;
2546
2547 case BEHAVIOUR_RUNNING_DEFENSE:
2548 [self behaviour_running_defense:delta_t];
2549 break;
2550
2551 case BEHAVIOUR_ATTACK_BROADSIDE:
2552 [self behaviour_attack_broadside:delta_t];
2553 break;
2554
2555 case BEHAVIOUR_ATTACK_BROADSIDE_LEFT:
2556 [self behaviour_attack_broadside_left:delta_t];
2557 break;
2558
2559 case BEHAVIOUR_ATTACK_BROADSIDE_RIGHT:
2560 [self behaviour_attack_broadside_right:delta_t];
2561 break;
2562
2563 case BEHAVIOUR_CLOSE_TO_BROADSIDE_RANGE:
2565 break;
2566
2567 case BEHAVIOUR_CLOSE_WITH_TARGET:
2568 [self behaviour_close_with_target:delta_t];
2569 break;
2570
2571 case BEHAVIOUR_ATTACK_SNIPER:
2572 [self behaviour_attack_sniper:delta_t];
2573 break;
2574
2575 case BEHAVIOUR_EVASIVE_ACTION:
2576 case BEHAVIOUR_FLEE_EVASIVE_ACTION:
2577 [self behaviour_evasive_action:delta_t];
2578 break;
2579
2580 case BEHAVIOUR_FLEE_TARGET:
2581 [self behaviour_flee_target:delta_t];
2582 break;
2583
2584 case BEHAVIOUR_FLY_RANGE_FROM_DESTINATION:
2586 break;
2587
2588 case BEHAVIOUR_FACE_DESTINATION:
2589 [self behaviour_face_destination:delta_t];
2590 break;
2591
2592 case BEHAVIOUR_LAND_ON_PLANET:
2593 [self behaviour_land_on_planet:delta_t];
2594 break;
2595
2596 case BEHAVIOUR_FORMATION_FORM_UP:
2597 [self behaviour_formation_form_up:delta_t];
2598 break;
2599
2600 case BEHAVIOUR_FLY_TO_DESTINATION:
2601 [self behaviour_fly_to_destination:delta_t];
2602 break;
2603
2604 case BEHAVIOUR_FLY_FROM_DESTINATION:
2605 case BEHAVIOUR_FORMATION_BREAK:
2606 [self behaviour_fly_from_destination:delta_t];
2607 break;
2608
2609 case BEHAVIOUR_AVOID_COLLISION:
2610 [self behaviour_avoid_collision:delta_t];
2611 break;
2612
2613 case BEHAVIOUR_TRACK_AS_TURRET:
2614 applyThrust = NO;
2615 [self behaviour_track_as_turret:delta_t];
2616 break;
2617
2618 case BEHAVIOUR_FLY_THRU_NAVPOINTS:
2619 [self behaviour_fly_thru_navpoints:delta_t];
2620 break;
2621
2622 case BEHAVIOUR_SCRIPTED_AI:
2623 case BEHAVIOUR_SCRIPTED_ATTACK_AI:
2624 [self behaviour_scripted_ai:delta_t];
2625 break;
2626
2627 case BEHAVIOUR_ENERGY_BOMB_COUNTDOWN:
2628 applyThrust = NO;
2629 // Do nothing
2630 break;
2631 }
2632
2633 // generally the checks above should be turning this *off* for subents
2634 if (applyThrust) {
2635 [self applyAttitudeChanges:delta_t];
2636 [self applyThrust:delta_t];
2637 }
2638}
2639
2640// called when behaviour is unable to improve position
2641- (void)noteFrustration:(NSString*)context
2642{
2643 [shipAI reactToMessage:@"FRUSTRATED" context:context];
2644 [self doScriptEvent:OOJSID("shipAIFrustrated") withArgument:context];
2645}
2646
2647- (void)respondToAttackFrom:(Entity*)from becauseOf:(Entity*)other
2648{
2649 Entity* source = nil;
2650
2651 if ([other isKindOfClass:[ShipEntity class]]) {
2652 source = other;
2653
2654 // JSAIs handle friendly fire themselves
2655 if (![self hasNewAI]) {
2656
2657 ShipEntity* hunter = (ShipEntity*)other;
2658 // if we are in the same group, then we have to be careful about how we handle things
2659 if ([self isPolice] && [hunter isPolice]) {
2660 // police never get into a fight with each other
2661 return;
2662 }
2663
2664 OOShipGroup* group = [self group];
2665
2666 if (group != nil && group == [hunter group]) {
2667 // we are in the same group, do we forgive you?
2668 // criminals are less likely to forgive
2669 if (randf() < (0.8 - (bounty / 100))) {
2670 // it was an honest mistake, lets get on with it
2671 return;
2672 }
2673
2674 ShipEntity* groupLeader = [group leader];
2675 if (hunter == groupLeader) {
2676 // oops we were attacked by our leader, desert him
2677 [group removeShip:self];
2678 } else {
2679 // evict them from our group
2680 [group removeShip:hunter];
2681
2685 }
2686 }
2687 }
2688 } else {
2689 source = from;
2690 }
2691
2692 [self doScriptEvent:OOJSID("shipBeingAttacked") withArgument:source andReactToAIMessage:@"ATTACKED"];
2693 if ([source isShip])
2694 [(ShipEntity*)source doScriptEvent:OOJSID("shipAttackedOther") withArgument:self];
2695}
2696
2697// Equipment
2698
2699- (BOOL)hasOneEquipmentItem:(NSString*)itemKey includeWeapons:(BOOL)includeWeapons whileLoading:(BOOL)loading
2700{
2701 if ([self hasOneEquipmentItem:itemKey includeMissiles:includeWeapons whileLoading:loading])
2702 return YES;
2703
2704 if (loading) {
2705 NSString* damaged = [itemKey stringByAppendingString:@"_DAMAGED"];
2706 if ([_equipment containsObject:damaged])
2707 return YES;
2708 }
2709
2710 if (includeWeapons) {
2711 // Check for primary weapon
2713 if (!isWeaponNone(weaponType)) {
2714 if ([self hasPrimaryWeapon:weaponType])
2715 return YES;
2716 }
2717 }
2718
2719 return NO;
2720}
2721
2722- (BOOL)hasOneEquipmentItem:(NSString*)itemKey includeMissiles:(BOOL)includeMissiles whileLoading:(BOOL)loading
2723{
2724 if ([_equipment containsObject:itemKey])
2725 return YES;
2726
2727 if (loading) {
2728 NSString* damaged = [itemKey stringByAppendingString:@"_DAMAGED"];
2729 if ([_equipment containsObject:damaged])
2730 return YES;
2731 }
2732
2733 if (includeMissiles && missiles > 0) {
2734 unsigned i;
2735 if ([itemKey isEqualToString:@"thargon"])
2736 itemKey = @"EQ_THARGON";
2737 for (i = 0; i < missiles; i++) {
2738 if (missile_list[i] != nil && [[missile_list[i] identifier] isEqualTo:itemKey])
2739 return YES;
2740 }
2741 }
2742
2743 return NO;
2744}
2745
2746- (BOOL)hasPrimaryWeapon:(OOWeaponType)weaponType
2747{
2748 NSEnumerator* subEntEnum = nil;
2749 ShipEntity* subEntity = nil;
2750
2751 if ([[forward_weapon_type identifier] isEqualToString:[weaponType identifier]] ||
2752 [[aft_weapon_type identifier] isEqualToString:[weaponType identifier]] ||
2753 [[port_weapon_type identifier] isEqualToString:[weaponType identifier]] ||
2754 [[starboard_weapon_type identifier] isEqualToString:[weaponType identifier]]) {
2755 return YES;
2756 }
2757
2758 for (subEntEnum = [self shipSubEntityEnumerator]; (subEntity = [subEntEnum nextObject]);) {
2759 if ([subEntity hasPrimaryWeapon:weaponType])
2760 return YES;
2761 }
2762
2763 return NO;
2764}
2765
2766- (NSUInteger)countEquipmentItem:(NSString*)eqkey
2767{
2768 NSString* eq = nil;
2769 NSUInteger count = 0;
2770 foreach (eq, _equipment) {
2771 if ([eqkey isEqualToString:eq]) {
2772 ++count;
2773 }
2774 }
2775 return count;
2776}
2777
2778- (BOOL)hasEquipmentItem:(id)equipmentKeys includeWeapons:(BOOL)includeWeapons whileLoading:(BOOL)loading
2779{
2780 // this method is also used internally to find out if an equipped item is undamaged.
2781 if ([equipmentKeys isKindOfClass:[NSString class]]) {
2782 return [self hasOneEquipmentItem:equipmentKeys includeWeapons:includeWeapons whileLoading:loading];
2783 } else {
2784 NSParameterAssert([equipmentKeys isKindOfClass:[NSArray class]] || [equipmentKeys isKindOfClass:[NSSet class]]);
2785
2786 id key = nil;
2787 foreach (key, equipmentKeys) {
2788 if ([self hasOneEquipmentItem:key includeWeapons:includeWeapons whileLoading:loading])
2789 return YES;
2790 }
2791 }
2792
2793 return NO;
2794}
2795
2796- (BOOL)hasEquipmentItem:(id)equipmentKeys
2797{
2798 return [self hasEquipmentItem:equipmentKeys includeWeapons:NO whileLoading:NO];
2799}
2800
2801/* allows OXP equipment to provide core functions (or indeed OXP
2802 * functions, potentially) */
2803- (BOOL)hasEquipmentItemProviding:(NSString*)equipmentType
2804{
2805 NSString* key = nil;
2806 foreach (key, _equipment) {
2807 if ([key isEqualToString:equipmentType]) {
2808 // equipment always provides itself
2809 return YES;
2810 } else {
2812 if (et != nil && [et provides:equipmentType]) {
2813 return YES;
2814 }
2815 }
2816 }
2817 return NO;
2818}
2819
2820- (NSString*)equipmentItemProviding:(NSString*)equipmentType
2821{
2822 NSString* key = nil;
2823 foreach (key, _equipment) {
2824 if ([key isEqualToString:equipmentType]) {
2825 // equipment always provides itself
2826 return [[key copy] autorelease];
2827 } else {
2829 if (et != nil && [et provides:equipmentType]) {
2830 return [[key copy] autorelease];
2831 }
2832 }
2833 }
2834 return nil;
2835}
2836
2837- (BOOL)hasAllEquipment:(id)equipmentKeys includeWeapons:(BOOL)includeWeapons whileLoading:(BOOL)loading
2838{
2839 NSEnumerator* keyEnum = nil;
2840 id key = nil;
2841
2842 if (_equipment == nil)
2843 return NO;
2844
2845 // Make sure it's an array or set, using a single-object set if it's a string.
2846 if ([equipmentKeys isKindOfClass:[NSString class]])
2847 equipmentKeys = [NSArray arrayWithObject:equipmentKeys];
2848 else if (![equipmentKeys isKindOfClass:[NSArray class]] && ![equipmentKeys isKindOfClass:[NSSet class]])
2849 return NO;
2850
2851 for (keyEnum = [equipmentKeys objectEnumerator]; (key = [keyEnum nextObject]);) {
2852 if (![self hasOneEquipmentItem:key includeWeapons:includeWeapons whileLoading:loading])
2853 return NO;
2854 }
2855
2856 return YES;
2857}
2858
2859- (BOOL)hasAllEquipment:(id)equipmentKeys
2860{
2861 return [self hasAllEquipment:equipmentKeys includeWeapons:NO whileLoading:NO];
2862}
2863
2865{
2866 return hyperspaceMotorSpinTime >= 0;
2867}
2868
2870{
2872}
2873
2874- (void)setHyperspaceSpinTime:(float)new
2875{
2877}
2878
2879- (BOOL)canAddEquipment:(NSString*)equipmentKey inContext:(NSString*)context
2880{
2881 if ([equipmentKey hasSuffix:@"_DAMAGED"]) {
2882 equipmentKey = [equipmentKey substringToIndex:[equipmentKey length] - [@"_DAMAGED" length]];
2883 }
2884
2885 NSString* lcEquipmentKey = [equipmentKey lowercaseString];
2886 if ([equipmentKey hasSuffix:@"MISSILE"] || [equipmentKey hasSuffix:@"MINE"] || ([self isThargoid] && ([lcEquipmentKey hasPrefix:@"thargon"] || [lcEquipmentKey hasSuffix:@"thargon"]))) {
2887 if (missiles >= max_missiles)
2888 return NO;
2889 }
2890
2892
2893 if (![eqType canCarryMultiple] && [self hasEquipmentItem:equipmentKey])
2894 return NO;
2895 if (![self equipmentValidToAdd:equipmentKey inContext:context])
2896 return NO;
2897
2898 return YES;
2899}
2900
2905
2906- (OOWeaponType)weaponTypeIDForFacing:(OOWeaponFacing)facing strict:(BOOL)strict
2907{
2908 OOWeaponType weaponType = nil;
2909
2910 if (facing & weapon_facings) {
2911 switch (facing) {
2913 weaponType = forward_weapon_type;
2914 // if no forward weapon, and not carrying out a strict check, see if subentities have forward weapons, return the first one found.
2915 if (isWeaponNone(weaponType) && !strict) {
2916 NSEnumerator* subEntEnum = [self shipSubEntityEnumerator];
2917 ShipEntity* subEntity = nil;
2918 while (isWeaponNone(weaponType) && (subEntity = [subEntEnum nextObject])) {
2919 weaponType = subEntity->forward_weapon_type;
2920 }
2921 }
2922 break;
2923
2924 case WEAPON_FACING_AFT:
2925 weaponType = aft_weapon_type;
2926 break;
2927
2928 case WEAPON_FACING_PORT:
2929 weaponType = port_weapon_type;
2930 break;
2931
2933 weaponType = starboard_weapon_type;
2934 break;
2935
2936 case WEAPON_FACING_NONE:
2937 break;
2938 }
2939 }
2940 return weaponType;
2941}
2942
2943- (OOEquipmentType*)weaponTypeForFacing:(OOWeaponFacing)facing strict:(BOOL)strict
2944{
2945 // OOWeaponType weaponType = [self weaponTypeIDForFacing:facing strict:strict];
2946 // return [OOEquipmentType equipmentTypeWithIdentifier:OOEquipmentIdentifierFromWeaponType(weaponType)];
2947 return [self weaponTypeIDForFacing:facing strict:strict];
2948}
2949
2950- (NSArray*)missilesList
2951{
2952 // if missile_list is empty, avoid exception and return empty NSArray instead
2953 return missile_list[0] != nil ? [NSArray arrayWithObjects:missile_list count:missiles] : [NSArray array];
2954}
2955
2957{
2958 return [NSArray array];
2959}
2960
2962{
2963 return [NSArray array];
2964}
2965
2967{
2968 return [NSArray array];
2969}
2970
2971- (OOEquipmentType*)generateMissileEquipmentTypeFrom:(NSString*)role
2972{
2973 /* The generated missile equipment type provides for backward compatibility with pre-1.74 OXPs missile_roles
2974 and follows this template:
2975
2976 //NPC equipment, incompatible with player ship. Not buyable because of its TL.
2977 (
2978 100, 100000, "Missile",
2979 "EQ_X_MISSILE",
2980 "Unidentified missile type.",
2981 {
2982 is_external_store = true;
2983 }
2984 )
2985 */
2986 NSArray* itemInfo = [NSArray arrayWithObjects:@"100", @"100000", @"Missile", role, @"Unidentified missile type.",
2987 [NSDictionary dictionaryWithObjectsAndKeys:@"true", @"is_external_store", nil], nil];
2988
2991}
2992
2994{
2995 NSArray* eqTypes = [OOEquipmentType allEquipmentTypes];
2996 NSMutableArray* quip = [NSMutableArray arrayWithCapacity:[eqTypes count]];
2997 OOEquipmentType* eqType = nil;
2998 BOOL isDamaged;
2999
3000 foreach (eqType, eqTypes) {
3001 // Equipment list, consistent with the rest of the API - Kaks
3002 if ([eqType canCarryMultiple]) {
3003 NSString* damagedIdentifier = [[eqType identifier] stringByAppendingString:@"_DAMAGED"];
3004 NSUInteger i, count = 0;
3006 count += [self countEquipmentItem:damagedIdentifier];
3007 for (i = 0; i < count; i++) {
3008 [quip addObject:eqType];
3009 }
3010 } else {
3011 isDamaged = [self hasEquipmentItem:[[eqType identifier] stringByAppendingString:@"_DAMAGED"]];
3012 if ([self hasEquipmentItem:[eqType identifier]] || isDamaged) {
3013 [quip addObject:eqType];
3014 }
3015 }
3016 }
3017
3018 // Passengers - not supported yet for NPCs, but it's here for genericity.
3019 if ([self passengerCapacity] > 0) {
3020 eqType = [OOEquipmentType equipmentTypeWithIdentifier:@"EQ_PASSENGER_BERTH"];
3021 //[quip addObject:[self eqDictionaryWithType:eqType isDamaged:NO]];
3022 [quip addObject:eqType];
3023 }
3024
3025 return [[quip copy] autorelease];
3026}
3027
3028- (BOOL)equipmentValidToAdd:(NSString*)equipmentKey inContext:(NSString*)context
3029{
3030 return [self equipmentValidToAdd:equipmentKey whileLoading:NO inContext:context];
3031}
3032
3033- (BOOL)equipmentValidToAdd:(NSString*)equipmentKey whileLoading:(BOOL)loading inContext:(NSString*)context
3034{
3035 OOEquipmentType* eqType = nil;
3036 BOOL validationForDamagedEquipment = NO;
3037
3038 if ([equipmentKey hasSuffix:@"_DAMAGED"]) {
3039 equipmentKey = [equipmentKey substringToIndex:[equipmentKey length] - [@"_DAMAGED" length]];
3040 }
3041
3042 eqType = [OOEquipmentType equipmentTypeWithIdentifier:equipmentKey];
3043 if (eqType == nil)
3044 return NO;
3045
3046 // need to know if we are trying to add a Repair version of the equipment. In some cases
3047 // (e.g. available cargo space required), it makes sense to deny installation of equipment
3048 // if the condition is not satisfied, but it doesn't make sense to deny repair when the
3049 // equipment is already installed. For now, we are checking only the cargo space condition,
3050 // but other conditions might need to be revised too. - Nikos, 20151115
3051 if ([self hasEquipmentItem:[eqType damagedIdentifier]]) {
3052 validationForDamagedEquipment = YES;
3053 }
3054
3055 // not all conditions make sence checking while loading a game with already purchaged equipment.
3056 // while loading, we mainly need to catch changes when the installed oxps set has changed since saving.
3057 if ([eqType requiresEmptyPylon] && [self missileCount] >= [self missileCapacity] && !loading)
3058 return NO;
3059 if ([eqType requiresMountedPylon] && [self missileCount] == 0 && !loading)
3060 return NO;
3061 if ([self availableCargoSpace] < [eqType requiredCargoSpace] && !validationForDamagedEquipment && !loading)
3062 return NO;
3063 if ([eqType requiresEquipment] != nil && ![self hasAllEquipment:[eqType requiresEquipment] includeWeapons:YES whileLoading:loading])
3064 return NO;
3065 if ([eqType requiresAnyEquipment] != nil && ![self hasEquipmentItem:[eqType requiresAnyEquipment] includeWeapons:YES whileLoading:loading])
3066 return NO;
3067 if ([eqType incompatibleEquipment] != nil && [self hasEquipmentItem:[eqType incompatibleEquipment] includeWeapons:YES whileLoading:loading])
3068 return NO;
3069 if ([eqType requiresCleanLegalRecord] && [self legalStatus] != 0 && !loading)
3070 return NO;
3071 if ([eqType requiresNonCleanLegalRecord] && [self legalStatus] == 0 && !loading)
3072 return NO;
3073 if ([eqType requiresFreePassengerBerth] && [self passengerCount] >= [self passengerCapacity])
3074 return NO;
3075 if ([eqType requiresFullFuel] && [self fuel] < [self fuelCapacity] && !loading)
3076 return NO;
3077 if ([eqType requiresNonFullFuel] && [self fuel] >= [self fuelCapacity] && !loading)
3078 return NO;
3079
3080 if (!loading) {
3081 NSString* condition_script = [eqType conditionScript];
3082 if (condition_script != nil) {
3083 OOJSScript* condScript = [UNIVERSE getConditionScript:condition_script];
3084 if (condScript != nil) // should always be non-nil, but just in case
3085 {
3086 JSContext* JScontext = OOJSAcquireContext();
3087 BOOL OK;
3088 BOOL allow_addition = NO;
3089 OOJSVal result = OOJSUndefinedValue();
3090 OOJSVal args[] = { OOJSValueFromNativeObject(JScontext, equipmentKey), OOJSValueFromNativeObject(JScontext, self), OOJSValueFromNativeObject(JScontext, context) };
3091
3092 OK = [condScript callMethod:OOJSID("allowAwardEquipment")
3093 inContext:JScontext
3094 withArguments:args
3095 count:sizeof args / sizeof *args
3096 result:&result];
3097
3098 if (OK)
3099 allow_addition = OOJSValueToBOOL(JScontext, result);
3100
3101 OOJSFreeValue(JScontext, result);
3102 OOJSFreeValue(JScontext, args[0]);
3103 OOJSFreeValue(JScontext, args[1]);
3104 OOJSFreeValue(JScontext, args[2]);
3105 OOJSRelinquishContext(JScontext);
3106
3107 if (OK && !allow_addition) {
3108 /* if the script exists, the function exists, the function
3109 * returns a bool, and that bool is false, block
3110 * addition. Otherwise allow it as default */
3111 return NO;
3112 }
3113 }
3114 }
3115 }
3116
3117 if ([self isPlayer]) {
3118 if (![eqType isAvailableToPlayer])
3119 return NO;
3120 if (![eqType isAvailableToAll]) {
3121 // find options that agree with this ship. Only player ships have these options.
3123 NSDictionary* shipyardInfo = [registry shipyardInfoForKey:[self shipDataKey]];
3124 NSMutableSet* options = [NSMutableSet setWithArray:[shipyardInfo oo_arrayForKey:KEY_OPTIONAL_EQUIPMENT]];
3125 [options addObjectsFromArray:[[shipyardInfo oo_dictionaryForKey:KEY_STANDARD_EQUIPMENT] oo_arrayForKey:KEY_EQUIPMENT_EXTRAS]];
3126 if (![options containsObject:equipmentKey])
3127 return NO;
3128 }
3129 } else {
3130 if (![eqType isAvailableToNPCs])
3131 return NO;
3132 }
3133
3134 return YES;
3135}
3136
3137- (BOOL)setWeaponMount:(OOWeaponFacing)facing toWeapon:(NSString*)eqKey
3138{
3139 // sets WEAPON_NONE if not recognised
3140 if (weapon_facings & facing) {
3142 switch (facing) {
3144 forward_weapon_type = chosen_weapon;
3145 break;
3146
3147 case WEAPON_FACING_AFT:
3148 aft_weapon_type = chosen_weapon;
3149 break;
3150
3151 case WEAPON_FACING_PORT:
3152 port_weapon_type = chosen_weapon;
3153 break;
3154
3156 starboard_weapon_type = chosen_weapon;
3157 break;
3158
3159 case WEAPON_FACING_NONE:
3160 break;
3161 }
3162
3163 return YES;
3164 } else {
3165 return NO;
3166 }
3167}
3168
3169- (BOOL)addEquipmentItem:(NSString*)equipmentKey inContext:(NSString*)context
3170{
3171 return [self addEquipmentItem:equipmentKey withValidation:YES inContext:context];
3172}
3173
3174- (BOOL)addEquipmentItem:(NSString*)equipmentKey withValidation:(BOOL)validateAddition inContext:(NSString*)context
3175{
3176 OOEquipmentType* eqType = nil;
3177 NSString* lcEquipmentKey = [equipmentKey lowercaseString];
3178 NSString* damagedKey;
3179 BOOL isEqThargon = [lcEquipmentKey hasSuffix:@"thargon"] || [lcEquipmentKey hasPrefix:@"thargon"];
3180 BOOL isRepairedEquipment = NO;
3181
3182 if ([lcEquipmentKey isEqualToString:@"thargon"])
3183 equipmentKey = @"EQ_THARGON";
3184
3185 // canAddEquipment always checks if the undamaged version is equipped.
3186 if (validateAddition == YES && ![self canAddEquipment:equipmentKey inContext:context])
3187 return NO;
3188
3189 if ([equipmentKey hasSuffix:@"_DAMAGED"]) {
3190 eqType = [OOEquipmentType equipmentTypeWithIdentifier:[equipmentKey substringToIndex:[equipmentKey length] - [@"_DAMAGED" length]]];
3191 } else {
3192 eqType = [OOEquipmentType equipmentTypeWithIdentifier:equipmentKey];
3193 // in case we have the damaged version!
3194 if (![eqType canCarryMultiple]) {
3195 damagedKey = [equipmentKey stringByAppendingString:@"_DAMAGED"];
3196 if ([_equipment containsObject:damagedKey]) {
3197 [_equipment removeObject:damagedKey];
3198 isRepairedEquipment = YES;
3199 }
3200 }
3201 }
3202
3203 // does this equipment actually exist?
3204 if (eqType == nil)
3205 return NO;
3206
3207 // special cases
3208 if ([eqType isMissileOrMine] || ([self isThargoid] && isEqThargon)) {
3209 if (missiles >= max_missiles)
3210 return NO;
3211
3212 missile_list[missiles] = eqType;
3213 missiles++;
3214 return YES;
3215 }
3216
3217 // don't add any thargons to non-thargoid ships.
3218 if (isEqThargon)
3219 return NO;
3220
3221 // we can theoretically add a damaged weapon, but not a working one.
3222 if ([equipmentKey hasPrefix:@"EQ_WEAPON"] && ![equipmentKey hasSuffix:@"_DAMAGED"]) {
3223 return NO;
3224 }
3225 // end special cases
3226
3227 if (_equipment == nil)
3228 _equipment = [[NSMutableArray alloc] init];
3229
3230 if (![equipmentKey isEqualToString:@"EQ_PASSENGER_BERTH"] && !isRepairedEquipment) {
3231 // Add to equipment_weight with all other equipment.
3234 // should not even happen with old save games. Reject equipment now.
3236 return NO;
3237 }
3238 }
3239
3240 if (!isPlayer) {
3241 if ([equipmentKey isEqual:@"EQ_CARGO_BAY"]) {
3243 } else if ([equipmentKey isEqualToString:@"EQ_SHIELD_BOOSTER"]) {
3244 maxEnergy += 256.0f;
3245 }
3246 if ([equipmentKey isEqualToString:@"EQ_SHIELD_ENHANCER"]) {
3247 maxEnergy += 256.0f;
3248 energy_recharge_rate *= 1.5;
3249 }
3250 }
3251 // add the equipment
3252 [_equipment addObject:equipmentKey];
3253 [self doScriptEvent:OOJSID("equipmentAdded") withArgument:equipmentKey];
3254 return YES;
3255}
3256
3257- (NSEnumerator*)equipmentEnumerator
3258{
3259 return [_equipment objectEnumerator];
3260}
3261
3262- (NSUInteger)equipmentCount
3263{
3264 return [_equipment count];
3265}
3266
3267- (void)removeEquipmentItem:(NSString*)equipmentKey
3268{
3269 NSString* equipmentTypeCheckKey = equipmentKey;
3270 NSString* lcEquipmentKey = [equipmentKey lowercaseString];
3271 NSUInteger equipmentIndex = NSNotFound;
3272 // determine the equipment type and make sure it works also in the case of damaged equipment
3273 if ([equipmentKey hasSuffix:@"_DAMAGED"]) {
3274 equipmentTypeCheckKey = [equipmentKey substringToIndex:[equipmentKey length] - [@"_DAMAGED" length]];
3275 }
3276 OOEquipmentType* eqType = [OOEquipmentType equipmentTypeWithIdentifier:equipmentTypeCheckKey];
3277 if (eqType == nil)
3278 return;
3279
3280 if ([eqType isMissileOrMine] || ([self isThargoid] && ([lcEquipmentKey hasSuffix:@"thargon"] || [lcEquipmentKey hasPrefix:@"thargon"]))) {
3281 [self removeExternalStore:eqType];
3282 } else {
3283 if ([_equipment containsObject:equipmentKey]) {
3284 if (![equipmentKey isEqualToString:@"EQ_PASSENGER_BERTH"]) {
3285 equipment_weight -= [eqType requiredCargoSpace]; // all other cases;
3286 }
3287
3288 if ([equipmentKey isEqualToString:@"EQ_CLOAKING_DEVICE"]) {
3289 if ([self isCloaked])
3290 [self setCloaked:NO];
3291 }
3292
3293 if (!isPlayer) {
3294 if ([equipmentKey isEqualToString:@"EQ_SHIELD_BOOSTER"]) {
3295 maxEnergy -= 256.0f;
3296 if (maxEnergy < energy)
3297 energy = maxEnergy;
3298 } else if ([equipmentKey isEqualToString:@"EQ_SHIELD_ENHANCER"]) {
3299 maxEnergy -= 256.0f;
3300 energy_recharge_rate /= 1.5;
3301 if (maxEnergy < energy)
3302 energy = maxEnergy;
3303 } else if ([equipmentKey isEqual:@"EQ_CARGO_BAY"]) {
3305 }
3306 }
3307 }
3308
3309 if (![equipmentKey hasSuffix:@"_DAMAGED"] && ![eqType canCarryMultiple]) {
3310 NSString* damagedKey = [equipmentKey stringByAppendingString:@"_DAMAGED"];
3311 if ([_equipment containsObject:damagedKey]) {
3312 equipmentIndex = [_equipment indexOfObject:damagedKey];
3313 if (equipmentIndex != NSNotFound) {
3314 // remove damaged counterpart
3315 [_equipment removeObjectAtIndex:equipmentIndex];
3316 }
3318 }
3319 }
3320 equipmentIndex = [_equipment indexOfObject:equipmentKey];
3321 if (equipmentIndex != NSNotFound) {
3322 [_equipment removeObjectAtIndex:equipmentIndex];
3323 }
3324 // this event must come after the item is actually removed
3325 [self doScriptEvent:OOJSID("equipmentRemoved") withArgument:equipmentKey];
3326
3327 // if all docking computers are damaged while active
3328 if ([self isPlayer] && [self status] == STATUS_AUTOPILOT_ENGAGED && ![self hasDockingComputer]) {
3330 }
3331
3332 if ([_equipment count] == 0)
3333 [self removeAllEquipment];
3334 }
3335}
3336
3337- (BOOL)removeExternalStore:(OOEquipmentType*)eqType
3338{
3339 NSString* identifier = [eqType identifier];
3340 unsigned i;
3341
3342 for (i = 0; i < missiles; i++) {
3343 if ([[missile_list[i] identifier] isEqualTo:identifier]) {
3344 // now 'delete' [i] by compacting the array
3345 while (++i < missiles)
3346 missile_list[i - 1] = missile_list[i];
3347
3348 missiles--;
3349 return YES;
3350 }
3351 }
3352 return NO;
3353}
3354
3355- (OOEquipmentType*)verifiedMissileTypeFromRole:(NSString*)role
3356{
3357 NSString* eqRole = nil;
3358 NSString* shipKey = nil;
3359 ShipEntity* missile = nil;
3360 OOEquipmentType* missileType = nil;
3361 BOOL isRandomMissile = [role isEqualToString:@"missile"];
3362
3363 if (isRandomMissile) {
3364 while (!shipKey) {
3365 shipKey = [UNIVERSE randomShipKeyForRoleRespectingConditions:role];
3366 if (!shipKey) {
3367 OOLogWARN(@"ship.setUp.missiles", @"%@ \"%@\" used in ship \"%@\" needs a valid %@.plist entry.%@", @"random missile", shipKey, [self name], @"shipdata", @"Trying another missile.");
3368 }
3369 }
3370 } else {
3371 shipKey = [UNIVERSE randomShipKeyForRoleRespectingConditions:role];
3372 if (!shipKey) {
3373 OOLogWARN(@"ship.setUp.missiles", @"%@ \"%@\" used in ship \"%@\" needs a valid %@.plist entry.%@", @"missile_role", role, [self name], @"shipdata", @" Using defaults instead.");
3374 return nil;
3375 }
3376 }
3377
3378 eqRole = [OOEquipmentType getMissileRegistryRoleForShip:shipKey]; // eqRole != role for generic missiles.
3379
3380 if (eqRole == nil) {
3381 missile = [UNIVERSE newShipWithName:shipKey];
3382 if (!missile) {
3383 if (isRandomMissile)
3384 OOLogWARN(@"ship.setUp.missiles", @"%@ \"%@\" used in ship \"%@\" needs a valid %@.plist entry.%@", @"random missile", shipKey, [self name], @"shipdata", @"Trying another missile.");
3385 else
3386 OOLogWARN(@"ship.setUp.missiles", @"%@ \"%@\" used in ship \"%@\" needs a valid %@.plist entry.%@", @"missile_role", role, [self name], @"shipdata", @" Using defaults instead.");
3387
3388 [OOEquipmentType setMissileRegistryRole:@"" forShip:shipKey]; // no valid role for this shipKey
3389 if (isRandomMissile)
3390 return [self verifiedMissileTypeFromRole:role];
3391 else
3392 return nil;
3393 }
3394
3395 if (isRandomMissile) {
3396 id value;
3397
3398 foreach (value, [[missile roleSet] roles]) {
3399 role = (NSString*)value;
3400 missileType = [OOEquipmentType equipmentTypeWithIdentifier:role];
3401 // ensure that we have a missile or mine
3402 if ([missileType isMissileOrMine])
3403 break;
3404 }
3405
3406 if (![missileType isMissileOrMine]) {
3407 role = shipKey; // unique identifier to use in lieu of a valid equipment type if none are defined inside the generic missile roleset.
3408 }
3409 }
3410
3411 missileType = [OOEquipmentType equipmentTypeWithIdentifier:role];
3412
3413 if (!missileType) {
3414 OOLogWARN(@"ship.setUp.missiles", @"%@ \"%@\" used in ship \"%@\" needs a valid %@.plist entry.%@", (isRandomMissile ? @"random missile" : @"missile_role"), role, [self name], @"equipment", @" Enabling compatibility mode.");
3415 missileType = [self generateMissileEquipmentTypeFrom:role];
3416 }
3417
3419 [missile release];
3420 } else {
3421 if ([eqRole isEqualToString:@""]) {
3422 // wrong ship definition, already written to the log in a previous call.
3423 if (isRandomMissile)
3424 return [self verifiedMissileTypeFromRole:role]; // try and find a valid missile with role 'missile'.
3425 return nil;
3426 }
3427 missileType = [OOEquipmentType equipmentTypeWithIdentifier:eqRole];
3428 }
3429
3430 return missileType;
3431}
3432
3434{
3435 OOEquipmentType* missileType = nil;
3436 NSString* role = nil;
3437 double chance = randf();
3438 BOOL thargoidMissile = NO;
3439
3440 if ([self isThargoid]) {
3441 if (_missileRole != nil)
3442 missileType = [self verifiedMissileTypeFromRole:_missileRole];
3443 if (missileType == nil) {
3444 _missileRole = @"EQ_THARGON"; // no valid missile_role defined, use thargoid fallback from now on.
3445 missileType = [self verifiedMissileTypeFromRole:_missileRole];
3446 }
3447 } else {
3448 // All other ships: random role 10% of the cases when auto weapons is set, if a missile_role is defined.
3449 // Without auto weapons, never random.
3450 float randomSelectionChance = chance;
3451 if (![self hasAutoWeapons])
3452 randomSelectionChance = 0.0f;
3453 if (randomSelectionChance < 0.9f && _missileRole != nil) {
3454 missileType = [self verifiedMissileTypeFromRole:_missileRole];
3455 }
3456
3457 if (missileType == nil) // the random 10% , or no valid missile_role defined
3458 {
3459 if (chance < 0.9f && _missileRole != nil) // no valid missile_role defined?
3460 {
3461 _missileRole = nil; // use generic ship fallback from now on.
3462 }
3463
3464 // assign random missiles 20% of the time without missile_role (or 10% with valid missile_role)
3465 if (chance > 0.8f)
3466 role = @"missile";
3467 // otherwise use the standard role
3468 else
3469 role = @"EQ_MISSILE";
3470
3471 missileType = [self verifiedMissileTypeFromRole:role];
3472 }
3473 }
3474
3475 if (missileType == nil)
3476 OOLogERR(@"ship.setUp.missiles", @"could not resolve missile / mine type for ship \"%@\". Original missile role:\"%@\".", [self name], _missileRole);
3477
3478 role = [[missileType identifier] lowercaseString];
3479 thargoidMissile = [self isThargoid] && ([role hasSuffix:@"thargon"] || [role hasPrefix:@"thargon"]);
3480
3481 if (thargoidMissile || (!thargoidMissile && [missileType isMissileOrMine])) {
3482 return missileType;
3483 } else {
3484 OOLogWARN(@"ship.setUp.missiles", @"missile_role \"%@\" is not a valid missile / mine type for ship \"%@\".%@", [missileType identifier], [self name], @" No missile selected.");
3485 return nil;
3486 }
3487}
3488
3490{
3491 [_equipment release];
3492 _equipment = nil;
3493}
3494
3496{
3497 missiles = 0;
3498 return 0;
3499}
3500
3501- (NSUInteger)parcelCount
3502{
3503 return 0;
3504}
3505
3506- (NSUInteger)passengerCount
3507{
3508 return 0;
3509}
3510
3512{
3513 return 0;
3514}
3515
3516- (NSUInteger)missileCount
3517{
3518 return missiles;
3519}
3520
3521- (NSUInteger)missileCapacity
3522{
3523 return max_missiles;
3524}
3525
3526- (NSUInteger)extraCargo
3527{
3528 return extra_cargo;
3529}
3530
3531/* This is used for e.g. displaying the HUD icon */
3533{
3534 return [self hasEquipmentItemProviding:@"EQ_FUEL_SCOOPS"] || [self hasEquipmentItemProviding:@"EQ_CARGO_SCOOPS"];
3535}
3536
3538{
3539 return [self hasEquipmentItemProviding:@"EQ_FUEL_SCOOPS"];
3540}
3541
3542/* No such core equipment item, but EQ_FUEL_SCOOPS provides it */
3544{
3545 return [self hasEquipmentItemProviding:@"EQ_CARGO_SCOOPS"];
3546}
3547
3548- (BOOL)hasECM
3549{
3550 return [self hasEquipmentItemProviding:@"EQ_ECM"];
3551}
3552
3554{
3555 /* TODO: Checks above stop this being 'providing'. */
3556 return [self hasEquipmentItem:@"EQ_CLOAKING_DEVICE"];
3557}
3558
3560{
3561#if USEMASC
3562 return [self hasEquipmentItemProviding:@"EQ_MILITARY_SCANNER_FILTER"];
3563#else
3564 return NO;
3565#endif
3566}
3567
3569{
3570#if USEMASC
3571 return [self hasEquipmentItemProviding:@"EQ_MILITARY_JAMMER"];
3572#else
3573 return NO;
3574#endif
3575}
3576
3578{
3579 /* Not 'providing' - controlled through scripts */
3580 return [self hasEquipmentItem:@"EQ_CARGO_BAY"];
3581}
3582
3584{
3585 /* Not 'providing' - controlled through scripts */
3586 return [self hasEquipmentItem:@"EQ_SHIELD_BOOSTER"];
3587}
3588
3590{
3591 /* Not 'providing' - controlled through scripts */
3592 return [self hasEquipmentItem:@"EQ_NAVAL_SHIELD_BOOSTER"];
3593}
3594
3596{
3597 return [self hasEquipmentItemProviding:@"EQ_HEAT_SHIELD"];
3598}
3599
3601{
3602 return [self hasEquipmentItemProviding:@"EQ_FUEL_INJECTION"];
3603}
3604
3606{
3607 /* TODO: this could be providing since theoretically OXP
3608 * deployable mines could also do cascade effects, but there are
3609 * probably better ways to manage OXP pylon AI */
3610 return [self hasEquipmentItem:@"EQ_QC_MINE" includeWeapons:YES whileLoading:NO];
3611}
3612
3614{
3615 return [self hasEquipmentItemProviding:@"EQ_ESCAPE_POD"];
3616}
3617
3619{
3620 return [self hasEquipmentItemProviding:@"EQ_DOCK_COMP"];
3621}
3622
3624{
3625 return [self hasEquipmentItemProviding:@"EQ_GAL_DRIVE"];
3626}
3627
3629{
3630 float boostFactor = 1.0f;
3631 if ([self hasShieldBooster])
3632 boostFactor += 1.0f;
3633 if ([self hasMilitaryShieldEnhancer])
3634 boostFactor += 1.0f;
3635
3636 return boostFactor;
3637}
3638
3639/* These next three are never called as of 12/12/2014, as NPCs don't
3640 * have shields and PlayerEntity overrides these. */
3642{
3644}
3645
3647{
3649}
3650
3652{
3653 return [self hasMilitaryShieldEnhancer] ? 3.0f : 2.0f;
3654}
3655
3657{
3658 return MAX_JUMP_RANGE;
3659}
3660
3662{
3664}
3665
3667{
3668 return afterburner_rate;
3669}
3670
3671- (void)setAfterburnerFactor:(GLfloat)new
3672{
3674}
3675
3676- (void)setAfterburnerRate:(GLfloat)new
3677{
3678 afterburner_rate = new;
3679}
3680
3682{
3683 return max_thrust;
3684}
3685
3686- (void)setMaxThrust:(GLfloat)new
3687{
3688 max_thrust = new;
3689}
3690
3691- (float)thrust
3692{
3693 return thrust;
3694}
3695
3697// //
3698// behaviours //
3699// //
3700- (void)behaviour_stop_still:(double)delta_t
3701{
3702 stick_roll = 0.0;
3703 stick_pitch = 0.0;
3704 stick_yaw = 0.0;
3705 [self applySticks:delta_t];
3706}
3707
3708- (void)behaviour_idle:(double)delta_t
3709{
3710 stick_yaw = 0.0;
3711 if ((!isStation) && (scanClass != CLASS_BUOY)) {
3712 stick_roll = 0.0;
3713 } else {
3715 }
3716 if (scanClass != CLASS_BUOY) {
3717 stick_pitch = 0.0;
3718 } else {
3720 }
3721 [self applySticks:delta_t];
3722}
3723
3724- (void)behaviour_tumble:(double)delta_t
3725{
3726 [self applySticks:delta_t];
3727}
3728
3729- (void)behaviour_tractored:(double)delta_t
3730{
3732 ShipEntity* hauler = (ShipEntity*)[self owner];
3733 if ((hauler) && ([hauler isShip])) {
3735 double distance = [self rangeToDestination];
3736 if (distance < desired_range) {
3737 [self performTumble];
3738 [self setStatus:STATUS_IN_FLIGHT];
3739 [hauler scoopUp:self];
3740 return;
3741 }
3742 GLfloat tf = TRACTOR_FORCE / mass;
3743 // adjust for difference in velocity (spring rule)
3744 Vector dv = vector_between([self velocity], [hauler velocity]);
3745 GLfloat moment = delta_t * 0.25 * tf;
3746 velocity.x += moment * dv.x;
3747 velocity.y += moment * dv.y;
3748 velocity.z += moment * dv.z;
3749 // acceleration = force / mass
3750 // force proportional to distance (spring rule)
3752 moment = delta_t * 0.5 * tf;
3753 velocity.x += moment * dp.x;
3754 velocity.y += moment * dp.y;
3755 velocity.z += moment * dp.z;
3756 // force inversely proportional to distance
3757 GLfloat d2 = HPmagnitude2(dp);
3758 moment = (d2 > 0.0) ? delta_t * 5.0 * tf / d2 : 0.0;
3759 if (d2 > 0.0) {
3760 velocity.x += moment * dp.x;
3761 velocity.y += moment * dp.y;
3762 velocity.z += moment * dp.z;
3763 }
3764 //
3765 if ([self status] == STATUS_BEING_SCOOPED) {
3766 BOOL lost_contact = (distance > hauler->collision_radius + collision_radius + 250.0f); // 250m range for tractor beam
3767 if ([hauler isPlayer]) {
3768 switch ([(PlayerEntity*)hauler dialFuelScoopStatus]) {
3771 lost_contact = YES; // don't draw
3772 break;
3773
3774 case SCOOP_STATUS_OKAY:
3776 break;
3777 }
3778 }
3779
3780 if (lost_contact) // 250m range for tractor beam
3781 {
3782 // escaped tractor beam
3783 [self setStatus:STATUS_IN_FLIGHT];
3784 behaviour = BEHAVIOUR_IDLE;
3785 [self setThrust:[self maxThrust]]; // restore old thrust.
3786 frustration = 0.0;
3787 [self setOwner:self];
3788 [shipAI exitStateMachineWithMessage:nil]; // exit nullAI.plist
3789 return;
3790 } else if ([hauler isPlayer]) {
3792 }
3793 }
3794 }
3795
3796 // being tractored; sticks ignored - CIM
3797 flightYaw = 0.0;
3798
3799 desired_speed = 0.0;
3800 thrust = 25.0; // used to damp velocity (must be less than hauler thrust)
3801
3802 thrust = 0.0; // must reset thrust now
3803}
3804
3805- (void)behaviour_track_target:(double)delta_t
3806{
3807 if ([self primaryTarget] == nil) {
3809 return;
3810 }
3811 [self trackPrimaryTarget:delta_t retreat:NO]; // applies sticks
3812 if ([self hasProximityAlertIgnoringTarget:YES]) {
3813 [self avoidCollision];
3814 }
3815}
3816
3817- (void)behaviour_intercept_target:(double)delta_t
3818{
3819 double range = [self rangeToPrimaryTarget];
3820 if (behaviour == BEHAVIOUR_INTERCEPT_TARGET) {
3822 if (range < desired_range) {
3823 [shipAI reactToMessage:@"DESIRED_RANGE_ACHIEVED" context:@"BEHAVIOUR_INTERCEPT_TARGET"];
3824 [self doScriptEvent:OOJSID("shipAchievedDesiredRange")];
3825 }
3827 } else {
3828 // = BEHAVIOUR_COLLECT_TARGET
3829 ShipEntity* target = [self primaryTarget];
3830 // if somehow ended up in this state but target is not cargo, stop
3831 // trying to scoop it
3832 if (!target || [target scanClass] != CLASS_CARGO || [target cargoType] == CARGO_NOT_CARGO) {
3834 return;
3835 }
3836 double target_speed = [target speed];
3837 double eta = range / (flightSpeed - target_speed);
3838 double last_success_factor = success_factor;
3839 double last_distance = last_success_factor;
3840 double distance = [self rangeToDestination];
3842 //
3843 double slowdownTime = 96.0 / (thrust * SHIP_THRUST_FACTOR); // more thrust implies better slowing
3844 double minTurnSpeedFactor = 0.005 * max_flight_pitch * max_flight_roll; // faster turning implies higher speeds
3845
3846 if ((eta < slowdownTime) && (flightSpeed > maxFlightSpeed * minTurnSpeedFactor))
3847 desired_speed = flightSpeed * 0.75; // cut speed by 50% to a minimum minTurnSpeedFactor of speed
3848 else
3850
3851 if (desired_speed < target_speed) {
3852 desired_speed += target_speed;
3853 if (target_speed > maxFlightSpeed) {
3855 return;
3856 }
3857 }
3858 if (desired_speed > maxFlightSpeed) { // never use injectors for scooping
3860 }
3861
3862 _destination = target->position;
3863 desired_range = 0.5 * target->collision_radius;
3864 [self trackDestination:delta_t retreat:NO];
3865
3866 //
3867 if (distance < last_distance) // improvement
3868 {
3869 frustration -= delta_t;
3870 if (frustration < 0.0)
3871 frustration = 0.0;
3872 } else {
3873 frustration += delta_t * 0.9;
3874 if (frustration > 10.0) // 10s of frustration
3875 {
3876 [self noteFrustration:@"BEHAVIOUR_INTERCEPT_TARGET"];
3877 frustration -= 5.0; // repeat after another five seconds' frustration
3878 }
3879 }
3880 }
3881 if ([self hasProximityAlertIgnoringTarget:YES]) {
3882 [self avoidCollision];
3883 }
3884}
3885
3886- (void)behaviour_attack_break_off_target:(double)delta_t
3887{
3888 if (![self canStillTrackPrimaryTarget]) {
3890 return;
3891 }
3892 BOOL canBurn = [self hasFuelInjection] && (fuel > MIN_FUEL);
3893 float max_available_speed = maxFlightSpeed;
3894 double range = [self rangeToPrimaryTarget];
3895 if (canBurn)
3896 max_available_speed *= [self afterburnerFactor];
3897
3898 desired_speed = max_available_speed;
3899
3900 Entity* target = [self primaryTarget];
3901
3903 double target_speed = [target speed];
3904 if (desired_speed > target_speed * 3.0) {
3905 desired_speed = maxFlightSpeed; // don't overuse the injectors
3906 }
3907 }
3908
3909 if (cloakAutomatic)
3911 if ([self hasProximityAlertIgnoringTarget:NO]) {
3912 [self avoidCollision];
3913 return;
3914 }
3915
3916 frustration += delta_t;
3917 if (frustration > 15.0 && accuracy >= COMBAT_AI_DOGFIGHTER && !canBurn) {
3919 }
3920 double aspect = [self approachAspectToPrimaryTarget];
3921 if (range > 3000.0 || ([target isShip] && [(ShipEntity*)target primaryTarget] != self) || frustration - floor(frustration) > fmin(1.6 / max_flight_roll, aspect)) {
3922 [self trackPrimaryTarget:delta_t retreat:YES];
3923 } else {
3924 // less useful at long range if not under direct fire
3925 [self evasiveAction:delta_t];
3926 }
3927
3928 if (range > COMBAT_OUT_RANGE_FACTOR * weaponRange) {
3929 behaviour = BEHAVIOUR_ATTACK_TARGET;
3930 } else if (aspect < -0.75 && accuracy >= COMBAT_AI_DOGFIGHTER) {
3931 behaviour = BEHAVIOUR_ATTACK_SLOW_DOGFIGHT;
3933 frustration = 0.0;
3935 behaviour = BEHAVIOUR_ATTACK_SLOW_DOGFIGHT;
3936 } else {
3937 behaviour = BEHAVIOUR_ATTACK_FLY_TO_TARGET;
3938 }
3939 }
3940
3941 flightYaw = 0.0;
3942}
3943
3944- (void)behaviour_attack_slow_dogfight:(double)delta_t
3945{
3946 if (![self canStillTrackPrimaryTarget]) {
3948 return;
3949 }
3950 if ([self hasProximityAlertIgnoringTarget:YES]) {
3951 [self avoidCollision];
3952 return;
3953 }
3954 double range = [self rangeToPrimaryTarget];
3955 ShipEntity* target = [self primaryTarget];
3956 double aspect = [self approachAspectToPrimaryTarget];
3957 if (range < 2.5 * (collision_radius + target->collision_radius) && [self proximityAlert] == target && aspect > 0) {
3959 [self avoidCollision];
3960 return;
3961 }
3962 if (aspect < -0.5 && range > COMBAT_IN_RANGE_FACTOR * weaponRange * 2.0) {
3963 behaviour = BEHAVIOUR_ATTACK_TARGET;
3964 } else if (aspect < -0.5) {
3965 // mostly behind target - try to stay there and keep up
3966 desired_speed = fmin(maxFlightSpeed * 0.5, [target speed] * 0.5);
3967 } else if (aspect < 0.3) {
3968 // to side of target - slow right down
3970 } else {
3971 // coming to front of target - accelerate for a quick getaway
3972 desired_speed = maxFlightSpeed * fmin(aspect * 2.5, 1.0);
3973 }
3974 if (aspect > 0.85) {
3975 behaviour = BEHAVIOUR_ATTACK_BREAK_OFF_TARGET;
3976 }
3977 if (aspect > 0.0) {
3978 frustration += delta_t;
3979 } else {
3980 frustration -= delta_t;
3981 }
3982 if (frustration > 10.0) {
3983 desired_speed /= 2.0;
3984 } else if (frustration < 0.0)
3985 frustration = 0.0;
3986
3987 [self trackPrimaryTarget:delta_t retreat:NO];
3988
3989 if (missiles)
3990 [self considerFiringMissile:delta_t];
3991
3992 if (cloakAutomatic)
3994}
3995
3996- (void)behaviour_evasive_action:(double)delta_t
3997{
3998 BOOL canBurn = [self hasFuelInjection] && (fuel > MIN_FUEL);
3999 float max_available_speed = maxFlightSpeed;
4000 // double range = [self rangeToPrimaryTarget];
4001 if (canBurn)
4002 max_available_speed *= [self afterburnerFactor];
4003 desired_speed = max_available_speed;
4005 ShipEntity* target = [self primaryTarget];
4006 double target_speed = [target speed];
4007 if (desired_speed > target_speed) {
4008 desired_speed = maxFlightSpeed; // don't overuse the injectors
4009 }
4010 }
4011
4012 if (cloakAutomatic)
4014 if ([self proximityAlert] != nil) {
4015 [self avoidCollision];
4016 return;
4017 }
4018
4019 [self evasiveAction:delta_t];
4020
4021 frustration += delta_t;
4022
4023 if (frustration > 0.5) {
4024 if (behaviour == BEHAVIOUR_FLEE_EVASIVE_ACTION) {
4025 [self setEvasiveJink:400.0];
4026 behaviour = BEHAVIOUR_FLEE_TARGET;
4027 } else {
4028 behaviour = BEHAVIOUR_ATTACK_TARGET;
4029 }
4030 }
4031
4032 flightYaw = 0.0;
4033
4034 // probably only useful for Thargoids, except for the occasional opportunist
4036}
4037
4038- (void)behaviour_attack_target:(double)delta_t
4039{
4040 double range = [self rangeToPrimaryTarget];
4041
4042 if (cloakAutomatic)
4044
4045 /* Start of behaviour selection:
4046 * Anything beyond the basics should require accuracy >= COMBAT_AI_ISNT_AWFUL
4047 * Anything fancy should require accuracy >= COMBAT_AI_IS_SMART
4048 * If precise aim is required, behaviour should have accuracy >= COMBAT_AI_TRACKS_CLOSER
4049 * - CIM
4050 */
4051
4052 OOWeaponType forward_weapon_real_type = forward_weapon_type;
4053 GLfloat forward_weapon_real_temp = forward_weapon_temp;
4054
4055 // if forward weapon is actually on a subent
4056 if (isWeaponNone(forward_weapon_real_type)) {
4057 BOOL hasTurrets = NO;
4058 NSEnumerator* subEnum = [self shipSubEntityEnumerator];
4059 ShipEntity* se = nil;
4060 while (isWeaponNone(forward_weapon_real_type) && (se = [subEnum nextObject])) {
4061 forward_weapon_real_type = se->forward_weapon_type;
4062 forward_weapon_real_temp = se->forward_weapon_temp;
4063 if (se->behaviour == BEHAVIOUR_TRACK_AS_TURRET) {
4064 hasTurrets = YES;
4065 }
4066 }
4067 if (isWeaponNone(forward_weapon_real_type) && hasTurrets) { // safety for ships only equipped with turrets
4068 forward_weapon_real_type = OOWeaponTypeFromEquipmentIdentifierSloppy(@"EQ_WEAPON_PULSE_LASER");
4069 forward_weapon_real_temp = COMBAT_AI_WEAPON_TEMP_USABLE * 0.9;
4070 }
4071 }
4072
4073 if ([forward_weapon_real_type isTurretLaser]) {
4074 behaviour = BEHAVIOUR_ATTACK_FLY_TO_TARGET_TWELVE;
4075 } else {
4076 BOOL in_good_range = aim_tolerance * range < COMBAT_AI_CONFIDENCE_FACTOR;
4077
4078 BOOL aft_weapon_ready = !isWeaponNone(aft_weapon_type) && (aft_weapon_temp < COMBAT_AI_WEAPON_TEMP_READY) && in_good_range;
4079 BOOL forward_weapon_ready = !isWeaponNone(forward_weapon_real_type) && (forward_weapon_real_temp < COMBAT_AI_WEAPON_TEMP_READY); // does not require in_good_range
4080 BOOL port_weapon_ready = !isWeaponNone(port_weapon_type) && (port_weapon_temp < COMBAT_AI_WEAPON_TEMP_READY) && in_good_range;
4081 BOOL starboard_weapon_ready = !isWeaponNone(starboard_weapon_type) && (starboard_weapon_temp < COMBAT_AI_WEAPON_TEMP_READY) && in_good_range;
4082 // if no weapons cool enough to be good choices, be less picky
4083 BOOL weapons_heating = NO;
4084 if (!forward_weapon_ready && !aft_weapon_ready && !port_weapon_ready && !starboard_weapon_ready) {
4085 weapons_heating = YES;
4086 aft_weapon_ready = !isWeaponNone(aft_weapon_type) && (aft_weapon_temp < COMBAT_AI_WEAPON_TEMP_USABLE) && in_good_range;
4087 forward_weapon_ready = !isWeaponNone(forward_weapon_real_type) && (forward_weapon_real_temp < COMBAT_AI_WEAPON_TEMP_USABLE); // does not require in_good_range
4088 port_weapon_ready = !isWeaponNone(port_weapon_type) && (port_weapon_temp < COMBAT_AI_WEAPON_TEMP_USABLE) && in_good_range;
4089 starboard_weapon_ready = !isWeaponNone(starboard_weapon_type) && (starboard_weapon_temp < COMBAT_AI_WEAPON_TEMP_USABLE) && in_good_range;
4090 }
4091
4092 Entity* target = [self primaryTarget];
4093 double aspect = [self approachAspectToPrimaryTarget];
4094
4095 if (!forward_weapon_ready && !aft_weapon_ready && !port_weapon_ready && !starboard_weapon_ready) { // no usable weapons! Either not fitted or overheated
4096
4097 // if unarmed
4099 behaviour = BEHAVIOUR_ATTACK_FLY_FROM_TARGET;
4100 } else if (aspect > 0) {
4101 if (in_good_range) {
4102 if (accuracy >= COMBAT_AI_IS_SMART && randf() < 0.75) {
4103 behaviour = BEHAVIOUR_EVASIVE_ACTION;
4104 } else {
4105 behaviour = BEHAVIOUR_ATTACK_FLY_FROM_TARGET;
4106 }
4107 } else {
4108 // ready to get more accurate shots later
4109 behaviour = BEHAVIOUR_ATTACK_FLY_TO_TARGET;
4110 }
4111 } else {
4112 // if target is running away, stay on target
4113 // unless too close for safety
4114 if (range < COMBAT_IN_RANGE_FACTOR * weaponRange) {
4115 behaviour = BEHAVIOUR_ATTACK_FLY_FROM_TARGET;
4116 } else {
4117 behaviour = BEHAVIOUR_ATTACK_FLY_TO_TARGET;
4118 }
4119 }
4120 }
4121 // if our current target isn't targeting us, and we have some idea of how to fight, and our weapons are running hot, and we're fairly nearby
4122 else if (weapons_heating && accuracy >= COMBAT_AI_ISNT_AWFUL && [target isShip] && [(ShipEntity*)target primaryTarget] != self && range < COMBAT_OUT_RANGE_FACTOR * weaponRange) {
4123 // then back off a bit for weapons to cool so we get a good attack run later, rather than weaving closer
4124 float relativeSpeed = magnitude(vector_subtract([self velocity], [target velocity]));
4125 [self setEvasiveJink:(range + COMBAT_JINK_OFFSET - relativeSpeed / max_flight_pitch)];
4126 behaviour = BEHAVIOUR_ATTACK_FLY_FROM_TARGET;
4127 } else {
4130
4131 if (nearby && aft_weapon_ready) {
4132 jink = kZeroVector; // almost all behaviours
4133 behaviour = BEHAVIOUR_RUNNING_DEFENSE;
4134 } else if (nearby && (port_weapon_ready || starboard_weapon_ready)) {
4135 jink = kZeroVector; // almost all behaviours
4136 behaviour = BEHAVIOUR_ATTACK_BROADSIDE;
4137 } else if (nearby) {
4138 if (!pitching_over) // don't change jink in the middle of a sharp turn.
4139 {
4140 /*
4141 For most AIs, is behaviour_attack_target called as starting behaviour on every hit.
4142 Target can both fly towards or away from ourselves here. Both situations
4143 need a different jink.z for optimal collision avoidance at high speed approach and low speed dogfighting.
4144 The COMBAT_JINK_OFFSET intentionally over-compensates the range for collision radii to send ships towards
4145 the target at low speeds.
4146 */
4147 float relativeSpeed = magnitude(vector_subtract([self velocity], [target velocity]));
4148 [self setEvasiveJink:(range + COMBAT_JINK_OFFSET - relativeSpeed / max_flight_pitch)];
4149 }
4150 // good pilots use behaviour_attack_break_off_target instead
4152 behaviour = BEHAVIOUR_ATTACK_BREAK_OFF_TARGET;
4153 } else {
4154 behaviour = BEHAVIOUR_ATTACK_FLY_FROM_TARGET;
4155 }
4156 } else if (forward_weapon_ready) {
4157 jink = kZeroVector; // almost all behaviours
4158
4159 // TODO: good pilots use behaviour_attack_sniper sometimes
4160 if (getWeaponRangeFromType(forward_weapon_real_type) > 12500 && range > 12500) {
4161 behaviour = BEHAVIOUR_ATTACK_SNIPER;
4162 }
4163 // generally not good tactics the next two
4164 else if (accuracy < COMBAT_AI_ISNT_AWFUL && aspect < 0) {
4165 behaviour = BEHAVIOUR_ATTACK_FLY_TO_TARGET_SIX;
4166 } else if (accuracy < COMBAT_AI_ISNT_AWFUL) {
4167 behaviour = BEHAVIOUR_ATTACK_FLY_TO_TARGET_TWELVE;
4168 } else {
4169 behaviour = BEHAVIOUR_ATTACK_FLY_TO_TARGET;
4170 }
4171 } else if (port_weapon_ready || starboard_weapon_ready) {
4172 jink = kZeroVector; // almost all behaviours
4173 behaviour = BEHAVIOUR_ATTACK_BROADSIDE;
4174 } else if (aft_weapon_ready && midrange) {
4175 jink = kZeroVector; // almost all behaviours
4176 behaviour = BEHAVIOUR_RUNNING_DEFENSE;
4177 } else {
4178 jink = kZeroVector; // almost all behaviours
4179 behaviour = BEHAVIOUR_ATTACK_FLY_TO_TARGET;
4180 }
4181 }
4182 }
4183
4184 frustration = 0.0; // behaviour changed, so reset frustration
4185}
4186
4187- (void)behaviour_attack_broadside:(double)delta_t
4188{
4189 BOOL canBurn = [self hasFuelInjection] && (fuel > MIN_FUEL);
4190 float max_available_speed = maxFlightSpeed;
4191 double range = [self rangeToPrimaryTarget];
4192 if (canBurn)
4193 max_available_speed *= [self afterburnerFactor];
4194
4195 if (cloakAutomatic)
4197
4198 if (![self canStillTrackPrimaryTarget]) {
4200 return;
4201 }
4202
4203 desired_speed = max_available_speed;
4205 behaviour = BEHAVIOUR_ATTACK_TARGET;
4206 } else {
4209 behaviour = BEHAVIOUR_ATTACK_BROADSIDE_RIGHT;
4210 [self setWeaponDataFromType:starboard_weapon_type];
4211 } else {
4212 behaviour = BEHAVIOUR_ATTACK_BROADSIDE_LEFT;
4213 [self setWeaponDataFromType:port_weapon_type];
4214 }
4215 } else {
4217 behaviour = BEHAVIOUR_ATTACK_BROADSIDE_RIGHT;
4218 [self setWeaponDataFromType:starboard_weapon_type];
4219 } else {
4220 behaviour = BEHAVIOUR_ATTACK_BROADSIDE_LEFT;
4221 [self setWeaponDataFromType:port_weapon_type];
4222 }
4223 }
4224 jink = kZeroVector;
4225 if (weapon_damage == 0.0) { // safety in case side lasers no longer exist
4226 behaviour = BEHAVIOUR_ATTACK_TARGET;
4227 } else if (range > 0.9 * weaponRange) {
4228 behaviour = BEHAVIOUR_CLOSE_TO_BROADSIDE_RANGE;
4229 }
4230 }
4231
4232 frustration = 0.0; // behaviour changed, so reset frustration
4233}
4234
4235- (void)behaviour_attack_broadside_left:(double)delta_t
4236{
4238}
4239
4240- (void)behaviour_attack_broadside_right:(double)delta_t
4241{
4243}
4244
4245- (void)behaviour_attack_broadside_target:(double)delta_t leftside:(BOOL)leftside
4246{
4247 BOOL canBurn = [self hasFuelInjection] && (fuel > MIN_FUEL);
4248 float max_available_speed = maxFlightSpeed;
4249 double range = [self rangeToPrimaryTarget];
4250 if (canBurn)
4251 max_available_speed *= [self afterburnerFactor];
4252 if ([self primaryTarget] == nil) {
4254 return;
4255 }
4256 GLfloat currentWeaponRange = getWeaponRangeFromType(leftside ? port_weapon_type : starboard_weapon_type);
4257 if (range > COMBAT_BROADSIDE_RANGE_FACTOR * currentWeaponRange) {
4258 behaviour = BEHAVIOUR_CLOSE_TO_BROADSIDE_RANGE;
4259 return;
4260 }
4261
4262 // can get closer on broadsides since there's less risk of a collision
4263 if ((range < COMBAT_BROADSIDE_IN_RANGE_FACTOR * currentWeaponRange) || ([self proximityAlert] != nil)) {
4264 if (![self hasProximityAlertIgnoringTarget:YES]) {
4265 behaviour = BEHAVIOUR_ATTACK_TARGET;
4266 } else {
4267 [self avoidCollision];
4268 return;
4269 }
4270 } else {
4271 if (![self canStillTrackPrimaryTarget]) {
4273 return;
4274 }
4275 }
4276 // control speed
4277 //
4278 BOOL isUsingAfterburner = canBurn && (flightSpeed > maxFlightSpeed);
4279 double slow_down_range = currentWeaponRange * COMBAT_WEAPON_RANGE_FACTOR * ((isUsingAfterburner) ? 3.0 * [self afterburnerFactor] : 1.0);
4280 // double target_speed = [target speed];
4281 if (range <= slow_down_range)
4282 desired_speed = fmin(0.8 * maxFlightSpeed, fmax((2.0 - frustration) * maxFlightSpeed, 0.1 * maxFlightSpeed)); // within the weapon's range slow down to aim
4283 else
4284 desired_speed = max_available_speed; // use afterburner to approach
4285
4286 double last_success_factor = success_factor;
4287 success_factor = [self trackSideTarget:delta_t leftside:leftside]; // do the actual piloting
4288 if (weapon_temp > COMBAT_AI_WEAPON_TEMP_USABLE) { // will probably have more luck with the other laser or picking a different attack method
4289 if (leftside) {
4291 behaviour = BEHAVIOUR_ATTACK_BROADSIDE_RIGHT;
4292 } else {
4293 behaviour = BEHAVIOUR_ATTACK_TARGET;
4294 }
4295 } else {
4297 behaviour = BEHAVIOUR_ATTACK_BROADSIDE_LEFT;
4298 } else {
4299 behaviour = BEHAVIOUR_ATTACK_TARGET;
4300 }
4301 }
4302 }
4303
4304 /* FIXME: again, basically all of this next bit common with standard attack */
4305 if ((success_factor > 0.999) || (success_factor > last_success_factor)) {
4306 frustration -= delta_t;
4307 if (frustration < 0.0)
4308 frustration = 0.0;
4309 } else {
4310 frustration += delta_t;
4311 if (frustration > 3.0) // 3s of frustration
4312 {
4313
4314 [self noteFrustration:@"BEHAVIOUR_ATTACK_BROADSIDE"];
4315 [self setEvasiveJink:1000.0];
4316 behaviour = BEHAVIOUR_ATTACK_FLY_FROM_TARGET;
4317 frustration = 0.0;
4319 }
4320 }
4321
4322 if (missiles)
4323 [self considerFiringMissile:delta_t];
4324
4325 if (cloakAutomatic)
4327 if (leftside) {
4328 [self firePortWeapon:range];
4329 } else {
4330 [self fireStarboardWeapon:range];
4331 }
4332
4334 behaviour = BEHAVIOUR_ATTACK_TARGET;
4335 }
4336}
4337
4338- (void)behaviour_close_to_broadside_range:(double)delta_t
4339{
4340 double range = [self rangeToPrimaryTarget];
4341 if ([self proximityAlert] != nil) {
4342 if ([self proximityAlert] == [self primaryTarget]) {
4343 behaviour = BEHAVIOUR_ATTACK_FLY_TO_TARGET; // this behaviour will handle proximity_alert.
4344 [self behaviour_attack_fly_from_target:delta_t]; // do it now.
4345 } else {
4346 [self avoidCollision];
4347 }
4348 return;
4349 }
4350 if (![self canStillTrackPrimaryTarget]) {
4352 return;
4353 }
4354
4355 behaviour = BEHAVIOUR_ATTACK_FLY_TO_TARGET_TWELVE;
4356 [self behaviour_fly_to_target_six:delta_t];
4358 [self setWeaponDataFromType:port_weapon_type];
4359 } else {
4360 [self setWeaponDataFromType:starboard_weapon_type];
4361 }
4363 behaviour = BEHAVIOUR_ATTACK_BROADSIDE;
4364 } else {
4365 behaviour = BEHAVIOUR_CLOSE_TO_BROADSIDE_RANGE;
4366 }
4367}
4368
4369- (void)behaviour_close_with_target:(double)delta_t
4370{
4371 double range = [self rangeToPrimaryTarget];
4372 if ([self proximityAlert] != nil) {
4373 if ([self proximityAlert] == [self primaryTarget]) {
4374 behaviour = BEHAVIOUR_ATTACK_FLY_TO_TARGET; // this behaviour will handle proximity_alert.
4375 [self behaviour_attack_fly_from_target:delta_t]; // do it now.
4376 } else {
4377 [self avoidCollision];
4378 }
4379 return;
4380 }
4381 if (![self canStillTrackPrimaryTarget]) {
4383 return;
4384 }
4385 behaviour = BEHAVIOUR_ATTACK_FLY_TO_TARGET_TWELVE;
4386 double saved_frustration = frustration;
4387 [self behaviour_fly_to_target_six:delta_t];
4388 frustration = saved_frustration; // ignore fly-to-12 frustration
4389 frustration += delta_t;
4390 if (range <= COMBAT_IN_RANGE_FACTOR * weaponRange || frustration > 5.0) {
4391 behaviour = BEHAVIOUR_ATTACK_TARGET;
4392 } else {
4393 behaviour = BEHAVIOUR_CLOSE_WITH_TARGET;
4394 }
4395}
4396
4397- (void)behaviour_attack_sniper:(double)delta_t
4398{
4399 if (![self canStillTrackPrimaryTarget]) {
4401 return;
4402 }
4403 Entity* rawTarget = [self primaryTarget];
4404 if (![rawTarget isShip]) {
4405 // can't attack a wormhole
4407 return;
4408 }
4409 ShipEntity* target = (ShipEntity*)rawTarget;
4410
4411 double range = [self rangeToPrimaryTarget];
4412 float max_available_speed = maxFlightSpeed;
4413
4414 if (range < 15000) {
4415 behaviour = BEHAVIOUR_ATTACK_TARGET;
4416 } else {
4417 if (range > weaponRange || range > scannerRange * 0.8) {
4418 BOOL canBurn = [self hasFuelInjection] && (fuel > MIN_FUEL);
4419 if (canBurn && [target weaponRange] > weaponRange && range > weaponRange) {
4420 // if outside maximum weapon range, but inside target weapon range
4421 // close to fight ASAP!
4422 max_available_speed *= [self afterburnerFactor];
4423 }
4424 desired_speed = max_available_speed;
4425 } else {
4426 desired_speed = max_available_speed / 10.0f;
4427 }
4428
4429 double last_success_factor = success_factor;
4430 success_factor = [self trackPrimaryTarget:delta_t retreat:NO];
4431
4432 if ((success_factor > 0.999) || (success_factor > last_success_factor)) {
4433 frustration -= delta_t;
4434 if (frustration < 0.0)
4435 frustration = 0.0;
4436 } else {
4437 frustration += delta_t;
4438 if (frustration > 3.0) // 3s of frustration
4439 {
4440 [self noteFrustration:@"BEHAVIOUR_ATTACK_SNIPER"];
4441 [self setEvasiveJink:1000.0];
4442 behaviour = BEHAVIOUR_ATTACK_TARGET;
4443 frustration = 0.0;
4445 }
4446 }
4447 }
4448
4449 if (missiles)
4450 [self considerFiringMissile:delta_t];
4451
4452 if (cloakAutomatic)
4454 [self fireMainWeapon:range];
4455
4457 behaviour = BEHAVIOUR_ATTACK_TARGET;
4458 }
4459}
4460
4461- (void)behaviour_fly_to_target_six:(double)delta_t
4462{
4463 BOOL canBurn = [self hasFuelInjection] && (fuel > MIN_FUEL);
4464 float max_available_speed = maxFlightSpeed;
4465 double range = [self rangeToPrimaryTarget];
4466 if (canBurn)
4467 max_available_speed *= [self afterburnerFactor];
4468
4469 // deal with collisions and lost targets
4470 if ([self proximityAlert] != nil) {
4471 if ([self proximityAlert] == [self primaryTarget]) {
4472 behaviour = BEHAVIOUR_ATTACK_FLY_TO_TARGET; // this behaviour will handle proximity_alert.
4473 [self behaviour_attack_fly_from_target:delta_t]; // do it now.
4474 } else {
4475 [self avoidCollision];
4476 }
4477 return;
4478 }
4479 if (![self canStillTrackPrimaryTarget]) {
4481 return;
4482 }
4483
4484 // control speed
4485 BOOL isUsingAfterburner = canBurn && (flightSpeed > maxFlightSpeed);
4486 BOOL closeQuickly = (canBurn && range > weaponRange);
4487 double slow_down_range = weaponRange * COMBAT_WEAPON_RANGE_FACTOR * ((isUsingAfterburner) ? 3.0 * [self afterburnerFactor] : 1.0);
4488 if (closeQuickly) {
4489 slow_down_range = weaponRange * COMBAT_OUT_RANGE_FACTOR;
4490 }
4491 double back_off_range = weaponRange * COMBAT_OUT_RANGE_FACTOR * ((isUsingAfterburner) ? 3.0 * [self afterburnerFactor] : 1.0);
4492 Entity* rawTarget = [self primaryTarget];
4493 if (![rawTarget isShip]) {
4495 return;
4496 }
4497 ShipEntity* target = (ShipEntity*)rawTarget;
4498 double target_speed = [target speed];
4499 double last_success_factor = success_factor;
4500 double distance = [self rangeToDestination];
4502
4503 if (range < slow_down_range && (behaviour == BEHAVIOUR_ATTACK_FLY_TO_TARGET_SIX)) {
4504 if (range < back_off_range) {
4505 desired_speed = fmax(0.9 * target_speed, 0.4 * maxFlightSpeed);
4506 } else {
4507 desired_speed = fmax(target_speed * 1.2, maxFlightSpeed);
4508 }
4509
4510 // avoid head-on collision
4511 if ((range < 0.5 * distance) && (behaviour == BEHAVIOUR_ATTACK_FLY_TO_TARGET_SIX))
4512 behaviour = BEHAVIOUR_ATTACK_FLY_TO_TARGET_TWELVE;
4513 } else {
4514 if (range < back_off_range) {
4515 desired_speed = fmax(0.9 * target_speed, 0.8 * maxFlightSpeed);
4516 } else {
4517 desired_speed = max_available_speed; // use afterburner to approach
4518 }
4519 }
4520
4521 // if within 0.75km of the target's six or twelve, or if target almost at standstill for 62.5% of non-thargoid ships (!),
4522 // then vector in attack.
4523 if (distance < 750.0 || (target_speed < 0.2 && ![self isThargoid] && ([self universalID] & 14) > 4)) {
4524 behaviour = BEHAVIOUR_ATTACK_FLY_TO_TARGET;
4525 frustration = 0.0;
4526 desired_speed = fmax(target_speed, 0.4 * maxFlightSpeed); // within the weapon's range don't use afterburner
4527 }
4528
4529 // target-six
4530 if (behaviour == BEHAVIOUR_ATTACK_FLY_TO_TARGET_SIX) {
4531 // head for a point weapon-range * 0.5 to the six of the target
4532 //
4533 _destination = [target distance_six:0.5 * weaponRange];
4534 }
4535 // target-twelve
4536 if (behaviour == BEHAVIOUR_ATTACK_FLY_TO_TARGET_TWELVE) {
4537 if ([forward_weapon_type isTurretLaser]) {
4538 // head for a point near the target, avoiding common Galcop weapon mount locations
4539 // TODO: this should account for weapon ranges
4540 GLfloat offset = 1000.0;
4541 GLfloat spacing = 2000.0;
4542 if (accuracy > 0.0) {
4543 offset = accuracy * 750.0;
4544 spacing = 2000.0 + (accuracy * 500.0);
4545 }
4546 if (entity_personality & 1) { // half at random
4547 offset = -offset;
4548 }
4549 _destination = [target distance_twelve:spacing withOffset:offset];
4550 } else {
4551 // head for a point 1.25km above the target
4552 _destination = [target distance_twelve:1250 withOffset:0];
4553 }
4554 }
4555
4556 pitching_over = NO; // in case it's set from elsewhere
4557 double confidenceFactor = [self trackDestination:delta_t retreat:NO];
4558
4559 if (success_factor > last_success_factor || confidenceFactor < 0.85)
4560 frustration += delta_t;
4561 else if (frustration > 0.0)
4562 frustration -= delta_t * 0.75;
4563
4564 double aspect = [self approachAspectToPrimaryTarget];
4565 if (![forward_weapon_type isTurretLaser] && (frustration > 10 || aspect > 0.75)) {
4566 behaviour = BEHAVIOUR_ATTACK_FLY_TO_TARGET;
4567 }
4568
4569 // use weaponry
4570 if (missiles)
4571 [self considerFiringMissile:delta_t];
4572
4573 if (cloakAutomatic)
4575 [self fireMainWeapon:range];
4576
4578 behaviour = BEHAVIOUR_ATTACK_TARGET;
4579 }
4580}
4581
4582- (void)behaviour_attack_mining_target:(double)delta_t
4583{
4584 double range = [self rangeToPrimaryTarget];
4585 if (![self canStillTrackPrimaryTarget]) {
4587 desired_speed = maxFlightSpeed * 0.375;
4588 return;
4589 } else if ((range < 650) || ([self proximityAlert] != nil)) {
4590 if ([self proximityAlert] == NO_TARGET) {
4591 desired_speed = range * maxFlightSpeed / (650.0 * 16.0);
4592 } else {
4593 [self avoidCollision];
4594 }
4595 } else {
4596 // we have a target, its within scanner range, and outside 650
4597 desired_speed = maxFlightSpeed * 0.875;
4598 }
4599
4600 [self trackPrimaryTarget:delta_t retreat:NO];
4601
4602 /* Don't open fire until within 3km - it doesn't take many mining
4603 * laser shots to destroy an asteroid, but some of these mining
4604 * ships are way too slow to effectively chase down the debris:
4605 * wait until reasonably close before trying to split it. */
4606 if (range < 3000) {
4607 [self fireMainWeapon:range];
4608 }
4609}
4610
4611- (void)behaviour_attack_fly_to_target:(double)delta_t
4612{
4613 BOOL canBurn = [self hasFuelInjection] && (fuel > MIN_FUEL);
4614 float max_available_speed = maxFlightSpeed;
4615 double range = [self rangeToPrimaryTarget];
4616 if (canBurn)
4617 max_available_speed *= [self afterburnerFactor];
4618 if ([self primaryTarget] == nil) {
4620 return;
4621 }
4622 Entity* rawTarget = [self primaryTarget];
4623 if (![rawTarget isShip]) {
4624 // can't attack a wormhole
4626 return;
4627 }
4628
4629 ShipEntity* target = (ShipEntity*)rawTarget;
4630 if ((range < COMBAT_IN_RANGE_FACTOR * weaponRange) || ([self proximityAlert] != nil)) {
4631 if (![self hasProximityAlertIgnoringTarget:YES]) {
4632 behaviour = BEHAVIOUR_ATTACK_TARGET;
4633 } else {
4634 [self avoidCollision];
4635 return;
4636 }
4637 } else {
4638 if (![self canStillTrackPrimaryTarget]) {
4640 return;
4641 }
4642 }
4643
4644 // control speed
4645 //
4646 BOOL isUsingAfterburner = canBurn && (flightSpeed > maxFlightSpeed);
4647 BOOL closeQuickly = (canBurn && [target weaponRange] > weaponRange && range > weaponRange);
4648 double slow_down_range = weaponRange * COMBAT_WEAPON_RANGE_FACTOR * ((isUsingAfterburner) ? 3.0 * [self afterburnerFactor] : 1.0);
4649 if (closeQuickly) {
4650 slow_down_range = weaponRange * COMBAT_OUT_RANGE_FACTOR;
4651 }
4652 double back_off_range = 10000 * COMBAT_OUT_RANGE_FACTOR * ((isUsingAfterburner) ? 3.0 * [self afterburnerFactor] : 1.0);
4653 double target_speed = [target speed];
4654 double aspect = [self approachAspectToPrimaryTarget];
4655
4656 if (range <= slow_down_range) {
4657 if (range < back_off_range) {
4658 if (accuracy < COMBAT_AI_IS_SMART || ([target primaryTarget] == self && aspect > 0.8) || aim_tolerance * range > COMBAT_AI_CONFIDENCE_FACTOR) {
4659 if (accuracy >= COMBAT_AI_FLEES_BETTER && aspect > 0.8) {
4660 desired_speed = fmax(target_speed * 1.25, 0.8 * maxFlightSpeed);
4661 // stay at high speed if might be taking return fire
4662 } else {
4663 desired_speed = fmax(target_speed * 1.05, 0.25 * maxFlightSpeed); // within the weapon's range match speed
4664 }
4665 } else { // smart, and not being shot at right now - slow down to attack
4666 desired_speed = fmax(0.1 * target_speed, 0.1 * maxFlightSpeed);
4667 }
4668 } else {
4669 if (accuracy < COMBAT_AI_IS_SMART || ([target isShip] && [(ShipEntity*)target primaryTarget] == self) || range > weaponRange / 2.0) {
4670 desired_speed = fmax(target_speed * 1.5, maxFlightSpeed);
4671 } else { // smart, and not being shot at right now - slow down to attack
4672 if (aspect > -0.25) {
4673 desired_speed = fmax(0.5 * target_speed, 0.5 * maxFlightSpeed);
4674 } else {
4675 desired_speed = fmax(1.25 * target_speed, 0.5 * maxFlightSpeed);
4676 }
4677 }
4678 }
4679 } else {
4680 if (closeQuickly) {
4681 desired_speed = max_available_speed; // use afterburner to approach
4682 } else {
4683 desired_speed = fmax(maxFlightSpeed, fmin(3.0 * target_speed, max_available_speed)); // possibly use afterburner to approach
4684 }
4685 }
4686
4687 double last_success_factor = success_factor;
4688 success_factor = [self trackPrimaryTarget:delta_t retreat:NO]; // do the actual piloting
4689
4690 if ((success_factor > 0.999) || (success_factor > last_success_factor)) {
4691 frustration -= delta_t;
4692 if (frustration < 0.0)
4693 frustration = 0.0;
4694 } else {
4695 frustration += delta_t;
4696 if (frustration > 3.0) // 3s of frustration
4697 {
4698 [self noteFrustration:@"BEHAVIOUR_ATTACK_FLY_TO_TARGET"];
4699 [self setEvasiveJink:1000.0];
4700 behaviour = BEHAVIOUR_ATTACK_TARGET;
4701 frustration = 0.0;
4703 }
4704 }
4705
4706 if (missiles)
4707 [self considerFiringMissile:delta_t];
4708
4709 if (cloakAutomatic)
4711 [self fireMainWeapon:range];
4712
4714 // don't do this if the target is fleeing and the front laser is
4715 // the only weapon, or if we're too far away to use non-front
4716 // lasers effectively
4718 frustration = 0.0;
4719 behaviour = BEHAVIOUR_ATTACK_TARGET;
4720 }
4721 } else if (accuracy >= COMBAT_AI_FLEES_BETTER_2) {
4722 // if we're right in their gunsights, dodge!
4723 // need to dodge sooner if in aft sights
4724 if ([target behaviour] != BEHAVIOUR_FLEE_TARGET && [target behaviour] != BEHAVIOUR_FLEE_EVASIVE_ACTION) {
4725 if ((aspect > 0.99999 && !isWeaponNone([target weaponTypeForFacing:WEAPON_FACING_FORWARD strict:NO])) || (aspect < -0.999 && !isWeaponNone([target weaponTypeForFacing:WEAPON_FACING_AFT strict:NO]))) {
4726 frustration = 0.0;
4727 behaviour = BEHAVIOUR_EVASIVE_ACTION;
4728 }
4729 }
4730 }
4731}
4732
4733- (void)behaviour_attack_fly_from_target:(double)delta_t
4734{
4735 double range = [self rangeToPrimaryTarget];
4736 double last_success_factor = success_factor;
4737 success_factor = range;
4738
4739 if ([self primaryTarget] == nil) {
4741 return;
4742 }
4743 if (last_success_factor > success_factor) // our target is closing in.
4744 {
4745 frustration += delta_t;
4746 } else { // not getting away fast enough?
4747 frustration += delta_t / 4.0;
4748 }
4749
4750 if (frustration > 10.0) {
4751 if (randf() < 0.3) {
4753 } else if (range > COMBAT_IN_RANGE_FACTOR * weaponRange && randf() < 0.3) {
4754 behaviour = BEHAVIOUR_ATTACK_TARGET;
4755 }
4756 GLfloat z = jink.z;
4757 if (randf() < 0.3) {
4758 z /= 2; // move the z-offset closer to the target to let him fly away from the target.
4759 desired_speed = flightSpeed * 2; // increase speed a bit.
4760 }
4761 [self setEvasiveJink:z];
4762
4763 frustration /= 2.0;
4764 }
4766 ShipEntity* target = [self primaryTarget];
4767 double target_speed = [target speed];
4768 if (desired_speed > target_speed * 2.0) {
4769 desired_speed = maxFlightSpeed; // don't overuse the injectors
4770 }
4771 } else if (desired_speed < maxFlightSpeed * 0.5) {
4773 }
4774
4775 if (range > COMBAT_OUT_RANGE_FACTOR * weaponRange + 15.0 * jink.x || flightSpeed > (scannerRange - range) * max_flight_pitch / 6.28) {
4776 jink = kZeroVector;
4777 behaviour = BEHAVIOUR_ATTACK_TARGET;
4778 frustration = 0.0;
4779 }
4780 [self trackPrimaryTarget:delta_t retreat:YES];
4781
4782 if (missiles)
4783 [self considerFiringMissile:delta_t];
4784
4785 if (cloakAutomatic)
4787 if ([self hasProximityAlertIgnoringTarget:YES])
4788 [self avoidCollision];
4789
4791 double aspect = [self approachAspectToPrimaryTarget];
4792 // if we're right in their gunsights, dodge!
4793 // need to dodge sooner if in aft sights
4794 if (aspect > 0.99999 || aspect < -0.999) {
4795 frustration = 0.0;
4796 behaviour = BEHAVIOUR_EVASIVE_ACTION;
4797 }
4798 }
4799}
4800
4801- (void)behaviour_running_defense:(double)delta_t
4802{
4803 if (![self canStillTrackPrimaryTarget]) {
4805 return;
4806 }
4807
4808 double range = [self rangeToPrimaryTarget];
4809 desired_speed = maxFlightSpeed; // not injectors
4810 jink = kZeroVector;
4811 if (range > weaponRange || range > 0.8 * scannerRange || range == 0) {
4812 behaviour = BEHAVIOUR_CLOSE_WITH_TARGET;
4813 if ([forward_weapon_type isTurretLaser]) {
4814 behaviour = BEHAVIOUR_ATTACK_FLY_TO_TARGET_TWELVE;
4815 }
4816 frustration = 0.0;
4817 }
4818 [self trackPrimaryTarget:delta_t retreat:YES];
4819 if ([forward_weapon_type isTurretLaser]) {
4820 // most Thargoids will only have the forward weapon
4821 [self fireMainWeapon:range];
4822 } else {
4823 [self fireAftWeapon:range];
4824 }
4825 if (cloakAutomatic)
4827 if ([self hasProximityAlertIgnoringTarget:YES])
4828 [self avoidCollision];
4829
4830 if (behaviour != BEHAVIOUR_CLOSE_WITH_TARGET && weapon_temp > COMBAT_AI_WEAPON_TEMP_USABLE) {
4831 behaviour = BEHAVIOUR_ATTACK_TARGET;
4832 }
4833
4834 // remember to look where you're going?
4835 if (accuracy >= COMBAT_AI_ISNT_AWFUL && [self hasProximityAlertIgnoringTarget:YES]) {
4836 [self avoidCollision];
4837 }
4838}
4839
4840- (void)behaviour_flee_target:(double)delta_t
4841{
4842 BOOL canBurn = [self hasFuelInjection] && (fuel > MIN_FUEL);
4843 float max_available_speed = maxFlightSpeed;
4844 double range = [self rangeToPrimaryTarget];
4845 if ([self primaryTarget] == nil) {
4847 return;
4848 }
4849 if (canBurn)
4850 max_available_speed *= [self afterburnerFactor];
4851
4852 double last_range = success_factor;
4853 success_factor = range;
4854
4855 if (range > desired_range || range == 0)
4856 [shipAI message:@"REACHED_SAFETY"];
4857 else
4858 desired_speed = max_available_speed;
4859
4860 if (range > last_range) // improvement
4861 {
4862 frustration -= 0.25 * delta_t;
4863 if (frustration < 0.0)
4864 frustration = 0.0;
4865 } else {
4866 frustration += delta_t;
4867 if (frustration > 15.0) // 15s of frustration
4868 {
4869 [self noteFrustration:@"BEHAVIOUR_FLEE_TARGET"];
4870 frustration = 0.0;
4871 }
4872 }
4873
4874 [self trackPrimaryTarget:delta_t retreat:YES];
4875
4876 Entity* target = [self primaryTarget];
4877
4878 if (missiles && [target isShip] && [(ShipEntity*)target primaryTarget] == self) {
4879 [self considerFiringMissile:delta_t];
4880 }
4881
4882 if (([self hasCascadeMine]) && (range < 10000.0) && canBurn) {
4883 float qbomb_chance = 0.01 * delta_t;
4884 if (randf() < qbomb_chance) {
4885 [self launchCascadeMine];
4886 }
4887 }
4888
4889 // thargoids won't normally be fleeing, but if they do, they can still shoot
4890 if ([forward_weapon_type isTurretLaser]) {
4891 [self fireMainWeapon:range];
4892 }
4893
4894 if (cloakAutomatic)
4896
4897 // remember to look where you're going?
4898 if (accuracy >= COMBAT_AI_ISNT_AWFUL && [self hasProximityAlertIgnoringTarget:YES]) {
4899 [self avoidCollision];
4900 }
4901}
4902
4903- (void)behaviour_fly_range_from_destination:(double)delta_t
4904{
4905 double distance = [self rangeToDestination];
4906 if (distance < desired_range) {
4907 behaviour = BEHAVIOUR_FLY_FROM_DESTINATION;
4909 desired_speed = maxFlightSpeed; // Not all AI define speed when flying away. Start with max speed to stay compatible with such AI's, but allow faster flight if it's (e.g.) used to flee from coordinates rather than entity
4910 }
4911 } else {
4912 behaviour = BEHAVIOUR_FLY_TO_DESTINATION;
4913 }
4914 if ([self hasProximityAlertIgnoringTarget:YES]) {
4915 [self avoidCollision];
4916 }
4917 frustration = 0.0;
4918}
4919
4920- (void)behaviour_face_destination:(double)delta_t
4921{
4922 double max_cos = MAX_COS;
4923 double distance = [self rangeToDestination];
4924 double old_pitch = flightPitch;
4925 desired_speed = 0.0;
4926 if (desired_range > 1.0 && distance > desired_range) {
4927 max_cos = sqrt(1 - 0.90 * desired_range * desired_range / (distance * distance)); // Head for a point within 95% of desired_range (must match the value in trackDestination)
4928 }
4929 double confidenceFactor = [self trackDestination:delta_t retreat:NO];
4930 if (confidenceFactor >= max_cos && flightPitch == 0.0) {
4931 // desired facing achieved and movement stabilised.
4932 [shipAI message:@"FACING_DESTINATION"];
4933 [self doScriptEvent:OOJSID("shipNowFacingDestination")];
4934 frustration = 0.0;
4935 if (docking_match_rotation) // IDLE stops rotating while docking
4936 {
4937 behaviour = BEHAVIOUR_FLY_TO_DESTINATION;
4938 } else {
4939 behaviour = BEHAVIOUR_IDLE;
4940 }
4941 }
4942
4943 if (flightSpeed == 0)
4944 frustration += delta_t;
4945 if (frustration > 15.0 / max_flight_pitch) // allow more time for slow ships.
4946 {
4947 frustration = 0.0;
4948 [self noteFrustration:@"BEHAVIOUR_FACE_DESTINATION"];
4949 if (flightPitch == old_pitch)
4950 flightPitch = 0.5 * max_flight_pitch; // hack to get out of frustration.
4951 }
4952
4953 /* 2009-7-18 Eric: the condition check below is intended to eliminate the flippering between two positions for fast turning ships
4954 during low FPS conditions. This flippering is particular frustrating on slow computers during docking. But with my current computer I can't
4955 induce those low FPS conditions so I can't properly test if it helps.
4956 I did try with the TAF time acceleration that also generated larger frame jumps and than it seemed to help.
4957 */
4958 if (flightSpeed == 0 && frustration > 5 && confidenceFactor > 0.5 && ((flightPitch > 0 && old_pitch < 0) || (flightPitch < 0 && old_pitch > 0))) {
4959 flightPitch += 0.5 * old_pitch; // damping with last pitch value.
4960 }
4961
4962 if ([self hasProximityAlertIgnoringTarget:YES]) {
4963 [self avoidCollision];
4964 }
4965}
4966
4967- (void)behaviour_land_on_planet:(double)delta_t
4968{
4969 double max_cos = MAX_COS2; // trackDestination returns the squared confidence in reverse mode.
4970 desired_speed = 0.0;
4971
4972 OOPlanetEntity* planet = [UNIVERSE entityForUniversalID:planetForLanding];
4973
4974 if (![planet isPlanet]) {
4975 behaviour = BEHAVIOUR_IDLE;
4976 aiScriptWakeTime = 1; // reconsider JSAI
4977 [shipAI message:@"NO_PLANET_NEARBY"];
4978 return;
4979 }
4980
4981 if (HPdistance(position, [planet position]) + [self collisionRadius] < [planet radius]) {
4982 // we have landed. (completely disappeared inside planet)
4983 [self landOnPlanet:planet];
4984 return;
4985 }
4986
4987 double confidenceFactor = [self trackDestination:delta_t retreat:YES]; // turn away from destination
4988
4989 if (confidenceFactor >= max_cos && flightSpeed == 0.0) {
4990 // We are now turned away from planet. Start landing by flying backward.
4991 thrust = 0.0; // stop forward acceleration.
4993 [self adjustVelocity:vector_multiply_scalar([self forwardVector], -max_thrust * delta_t)];
4994 }
4995 }
4996
4997 if ([self hasProximityAlertIgnoringTarget:YES]) {
4998 [self avoidCollision];
4999 }
5000}
5001
5002- (void)behaviour_formation_form_up:(double)delta_t
5003{
5004 // destination for each escort is set in update() from owner.
5005 ShipEntity* leadShip = [self owner];
5006 double distance = [self rangeToDestination];
5007 double eta = (distance - desired_range) / flightSpeed;
5008 if (eta < 0)
5009 eta = 0;
5010 if ((eta < 5.0) && (leadShip) && (leadShip->isShip))
5011 desired_speed = [leadShip flightSpeed] * (1 + eta * 0.05);
5012 else
5014
5015 double last_distance = success_factor;
5017
5018 // do the actual piloting!!
5019 [self trackDestination:delta_t retreat:NO];
5020
5021 eta = eta / 0.51; // 2% safety margin assuming an average of half current speed
5022 GLfloat slowdownTime = (thrust > 0.0) ? flightSpeed / (thrust) : 4.0;
5023 GLfloat minTurnSpeedFactor = 0.05 * max_flight_pitch * max_flight_roll; // faster turning implies higher speeds
5024
5025 if ((eta < slowdownTime) && (flightSpeed > maxFlightSpeed * minTurnSpeedFactor))
5026 desired_speed = flightSpeed * 0.50; // cut speed by 50% to a minimum minTurnSpeedFactor of speed
5027
5028 if (distance < last_distance) // improvement
5029 {
5030 frustration -= 0.25 * delta_t;
5031 if (frustration < 0.0)
5032 frustration = 0.0;
5033 } else {
5034 frustration += delta_t;
5035 if (frustration > 15.0) {
5036 if (!leadShip)
5037 [self noteFrustration:@"BEHAVIOUR_FORMATION_FORM_UP"]; // escorts never reach their destination when following leader.
5038 else if (distance > 0.5 * scannerRange && !pitching_over) {
5039 pitching_over = YES; // Force the ship in a 180 degree turn. Do it here to allow escorts to break out formation for some seconds.
5040 }
5041 frustration = 0;
5042 }
5043 }
5044 if ([self hasProximityAlertIgnoringTarget:YES]) {
5045 [self avoidCollision];
5046 }
5047}
5048
5049- (void)behaviour_fly_to_destination:(double)delta_t
5050{
5051 double distance = [self rangeToDestination];
5052 // double desiredRange = (dockingInstructions != nil) ? 1.2 * desired_range : desired_range; // stop a bit earlyer when docking.
5053 if (distance < desired_range) // + collision_radius)
5054 {
5055 // desired range achieved
5056 [shipAI message:@"DESIRED_RANGE_ACHIEVED"];
5057 [self doScriptEvent:OOJSID("shipAchievedDesiredRange")];
5058
5059 if (!docking_match_rotation) // IDLE stops rotating while docking
5060 {
5061 behaviour = BEHAVIOUR_IDLE;
5062 desired_speed = 0.0;
5063 }
5064 frustration = 0.0;
5065 } else {
5066 double last_distance = success_factor;
5068
5069 // do the actual piloting!!
5070 double confidenceFactor = [self trackDestination:delta_t retreat:NO];
5071 if (confidenceFactor < 0.2)
5072 confidenceFactor = 0.2; // don't allow small or negative values.
5073
5074 /* 2009-07-19 Eric: Estimated Time of Arrival (eta) should also take the "angle to target" into account (confidenceFactor = cos(angle to target))
5075 and should not fuss about that last meter and use "distance + 1" instead of just "distance".
5076 trackDestination already did pitch regulation, use confidence here only for cutting down to high speeds.
5077 This should prevent ships crawling to their destination when they try to pull up close to their destination.
5078
5079 To prevent ships circling around their target without reaching destination I added a limitation based on turnrate,
5080 speed and distance to target. Formula based on satelite orbit:
5081 orbitspeed = turnrate (rad/sec) * radius (m) or flightSpeed = max_flight_pitch * 2 Pi * distance
5082 Speed must be significant lower when not flying in direction of target (low confidenceFactor) or it can never approach its destination
5083 and the ships runs the risk flying in circles around the target. (exclude active escorts)
5084 */
5085 GLfloat eta = ((distance + 1) - desired_range) / (0.51 * flightSpeed * confidenceFactor); // 2% safety margin assuming an average of half current speed
5086 GLfloat slowdownTime = (thrust > 0.0) ? flightSpeed / (thrust) : 4.0;
5087 GLfloat minTurnSpeedFactor = 0.05 * max_flight_pitch * max_flight_roll; // faster turning implies higher speeds
5088 if (dockingInstructions != nil) {
5089 minTurnSpeedFactor /= 10.0;
5090 if (minTurnSpeedFactor * maxFlightSpeed > 20.0) {
5091 minTurnSpeedFactor /= 10.0;
5092 }
5093 }
5094
5095 if (((eta < slowdownTime) && (flightSpeed > maxFlightSpeed * minTurnSpeedFactor)) || (flightSpeed > max_flight_pitch * 5 * confidenceFactor * distance)) {
5096 desired_speed = flightSpeed * 0.50; // cut speed by 50% to a minimum minTurnSpeedFactor of speed
5097 }
5098
5099 /* Flight correction block to prevent one possible form of
5100 * crashes in late docking process */
5101 if (docking_match_rotation && confidenceFactor >= MAX_COS && dockingInstructions != nil && [dockingInstructions oo_intForKey:@"docking_stage"] >= 7) {
5102 // then at this point should be rotating to match the station
5103 StationEntity* station_for_docking = (StationEntity*)[self targetStation];
5104
5105 if ((station_for_docking) && (station_for_docking->isStation)) {
5106 float rollMatch = dot_product([station_for_docking portUpVectorForShip:self], [self upVector]);
5107 if (rollMatch < MAX_COS && rollMatch > -MAX_COS) {
5108 // not matching rotating - stop until corrected
5109 desired_speed = 0.1;
5110 } else if (desired_speed <= 0.2) {
5111 // had previously paused, so return to normal speed
5112 desired_speed = [dockingInstructions oo_floatForKey:@"speed"];
5113 }
5114 }
5115 }
5116
5117 if (distance < last_distance) // improvement
5118 {
5119 frustration -= 0.25 * delta_t;
5120 if (frustration < 0.0)
5121 frustration = 0.0;
5122 } else {
5123 frustration += delta_t;
5124 if ((frustration > slowdownTime * 10.0 && slowdownTime > 0) || (frustration > 15.0)) // 10x slowdownTime or 15s of frustration
5125 {
5126 [self noteFrustration:@"BEHAVIOUR_FLY_TO_DESTINATION"];
5127 frustration -= slowdownTime * 5.0; // repeat after another five units of frustration
5128 }
5129 }
5130 }
5131 if ([self hasProximityAlertIgnoringTarget:YES]) {
5132 [self avoidCollision];
5133 }
5134}
5135
5136- (void)behaviour_fly_from_destination:(double)delta_t
5137{
5138 double distance = [self rangeToDestination];
5139 if (distance > desired_range) {
5140 // desired range achieved
5141 [shipAI message:@"DESIRED_RANGE_ACHIEVED"];
5142 [self doScriptEvent:OOJSID("shipAchievedDesiredRange")];
5143
5144 behaviour = BEHAVIOUR_IDLE;
5145 frustration = 0.0;
5146 desired_speed = 0.0;
5147 }
5148
5149 [self trackDestination:delta_t retreat:YES];
5150 if ([self hasProximityAlertIgnoringTarget:YES]) {
5151 [self avoidCollision];
5152 }
5153}
5154
5155- (void)behaviour_avoid_collision:(double)delta_t
5156{
5157 double distance = [self rangeToDestination];
5158 if (distance > desired_range) {
5160 } else {
5161 ShipEntity* prox_ship = (ShipEntity*)[self proximityAlert];
5162 if (prox_ship) {
5164 _destination = prox_ship->position;
5165 }
5166 double dq = [self trackDestination:delta_t retreat:YES]; // returns 0 when heading towards prox_ship
5167 // Heading towards target with desired_speed > 0, avoids collisions better than setting desired_speed to zero.
5168 // (tested with boa class cruiser on collisioncourse with buoy)
5169 desired_speed = maxFlightSpeed * (0.5 * dq + 0.5);
5170 }
5171}
5172
5173- (void)behaviour_track_as_turret:(double)delta_t
5174{
5175 double aim = -2.0;
5176 ShipEntity* turret_owner = (ShipEntity*)[self owner];
5177 ShipEntity* turret_target = (ShipEntity*)[turret_owner primaryTarget];
5178 if (turret_owner && turret_target && [turret_owner hasHostileTarget]) {
5179 aim = [self ballTrackLeadingTarget:delta_t atTarget:turret_target];
5180 if (aim > -1.0) // potential target
5181 {
5182 HPVector p = HPvector_subtract([turret_target position], [turret_owner position]);
5183 double cr = [turret_owner collisionRadius];
5184
5185 if (aim > .95) {
5186 [self fireTurretCannon:HPmagnitude(p) - cr];
5187 }
5188 return;
5189 }
5190 }
5191
5192 // can't fire on primary target; track secondary targets instead
5193 NSEnumerator* targetEnum = [turret_owner defenseTargetEnumerator];
5194 Entity* target = nil;
5195 while ((target = [[targetEnum nextObject] weakRefUnderlyingObject])) {
5196 // defense targets cannot be tracked while cloaked
5197 if ([target scanClass] == CLASS_NO_DRAW || [(ShipEntity*)target isCloaked] || [target energy] <= 0.0) {
5199 } else {
5200 double range = [turret_owner rangeToSecondaryTarget:target];
5201 if (range < weaponRange) {
5202 aim = [self ballTrackLeadingTarget:delta_t atTarget:target];
5203 if (aim > -1.0) { // tracking...
5204 HPVector p = HPvector_subtract([target position], [turret_owner position]);
5205 double cr = [turret_owner collisionRadius];
5206
5207 if (aim > .95) { // fire!
5208 [self fireTurretCannon:HPmagnitude(p) - cr];
5209 }
5210 return;
5211 }
5212 // else that target is out of range, try the next priority defense target
5213 } else if (range > scannerRange) {
5215 }
5216 }
5217 }
5218
5219 // turrets now don't return to neutral facing if no suitable target
5220 // better for shooting at targets that are on edge of fire arc
5221}
5222
5223- (void)behaviour_fly_thru_navpoints:(double)delta_t
5224{
5225 int navpoint_plus_index = (next_navpoint_index + 1) % number_of_navpoints;
5226 HPVector d1 = navpoints[next_navpoint_index]; // head for this one
5227 HPVector d2 = navpoints[navpoint_plus_index]; // but be facing this one
5228
5229 HPVector rel = HPvector_between(d1, position); // vector from d1 to position
5230 HPVector ref = HPvector_between(d2, d1); // vector from d2 to d1
5231 ref = HPvector_normal(ref);
5232
5233 HPVector xp = make_HPvector(ref.y * rel.z - ref.z * rel.y, ref.z * rel.x - ref.x * rel.z, ref.x * rel.y - ref.y * rel.x);
5234
5235 GLfloat v0 = 0.0;
5236
5237 GLfloat r0 = HPdot_product(rel, ref); // proportion of rel in direction ref
5238
5239 // if r0 is negative then we're the wrong side of things
5240
5241 GLfloat r1 = HPmagnitude(xp); // distance of position from line
5242
5243 BOOL in_cone = (r0 > 0.5 * r1);
5244
5245 if (!in_cone) // are we in the approach cone ?
5246 r1 = 25.0 * flightSpeed; // aim a few km out!
5247 else
5248 r1 *= 2.0;
5249
5250 GLfloat dist2 = HPmagnitude2(rel);
5251
5252 if (dist2 < desired_range * desired_range) {
5253 // desired range achieved
5254 [self doScriptEvent:OOJSID("shipReachedNavPoint") andReactToAIMessage:@"NAVPOINT_REACHED"];
5255 if (navpoint_plus_index == 0) {
5256 [self doScriptEvent:OOJSID("shipReachedEndPoint") andReactToAIMessage:@"ENDPOINT_REACHED"];
5257 behaviour = BEHAVIOUR_IDLE;
5258 }
5259 next_navpoint_index = navpoint_plus_index; // loop as required
5260 } else {
5261 double last_success_factor = success_factor;
5262 double last_dist2 = last_success_factor;
5263 success_factor = dist2;
5264
5265 // set destination spline point from r1 and ref
5266 _destination = make_HPvector(d1.x + r1 * ref.x, d1.y + r1 * ref.y, d1.z + r1 * ref.z);
5267
5268 // do the actual piloting!!
5269 //
5270 // aim to within 1m
5271 GLfloat temp = desired_range;
5272 if (in_cone)
5273 desired_range = 1.0;
5274 else
5275 desired_range = 100.0;
5276 v0 = [self trackDestination:delta_t retreat:NO];
5277 desired_range = temp;
5278
5279 if (dist2 < last_dist2) // improvement
5280 {
5281 frustration -= 0.25 * delta_t;
5282 if (frustration < 0.0)
5283 frustration = 0.0;
5284 } else {
5285 frustration += delta_t;
5286 if (frustration > 15.0) // 15s of frustration
5287 {
5288 [self noteFrustration:@"BEHAVIOUR_FLY_THRU_NAVPOINTS"];
5289 frustration -= 15.0; // repeat after another 15s of frustration
5290 }
5291 }
5292 }
5293
5294 GLfloat temp = desired_speed;
5295 desired_speed *= v0 * v0;
5296
5297 desired_speed = temp;
5298}
5299
5300- (void)behaviour_scripted_ai:(double)delta_t
5301{
5302
5303 JSContext* context = OOJSAcquireContext();
5304 OOJSVal rval = OOJSUndefinedValue();
5305 OOJSVal deltaJS = OOJSValueFromDouble(context, delta_t);
5306 NSDictionary* result = nil;
5307
5308 BOOL OK = [[self script] callMethod:OOJSID("scriptedAI")
5309 inContext:context
5310 withArguments:&deltaJS
5311 count:1
5312 result:&rval];
5313 OOJSFreeValue(context, deltaJS);
5314
5315 if (!OK) {
5316 OOLog(@"ai.error", @"Could not call scriptedAI in ship script of %@, reverting to idle", self);
5317 behaviour = BEHAVIOUR_IDLE;
5318 OOJSFreeValue(context, rval);
5319 OOJSRelinquishContext(context);
5320 return;
5321 }
5322
5323#if OOJS_QUICKJS
5324 // SpiderMonkey's JSVAL_IS_OBJECT() is also true for null.
5325 if (!JS_IsObject(rval) && !JS_IsNull(rval)) {
5326#else
5327 if (!JSVAL_IS_OBJECT(rval)) {
5328#endif
5329 OOLog(@"ai.error", @"Invalid return value of scriptedAI in ship script of %@, reverting to idle", self);
5330 behaviour = BEHAVIOUR_IDLE;
5331 OOJSFreeValue(context, rval);
5332 OOJSRelinquishContext(context);
5333 return;
5334 }
5335
5336#if OOJS_QUICKJS
5337 result = OOJSNativeObjectFromJSObject(context, rval);
5338#else
5339 result = OOJSNativeObjectFromJSObject(context, JSVAL_TO_OBJECT(rval));
5340#endif
5341 OOJSFreeValue(context, rval);
5342 OOJSRelinquishContext(context);
5343
5344 // roll or roll factor
5345 if ([result objectForKey:@"stickRollFactor"] != nil) {
5346 stick_roll = [result oo_floatForKey:@"stickRollFactor"] * max_flight_roll;
5347 } else {
5348 stick_roll = [result oo_floatForKey:@"stickRoll"];
5349 }
5352 } else if (stick_roll < -max_flight_roll) {
5354 }
5355
5356 // pitch or pitch factor
5357 if ([result objectForKey:@"stickPitchFactor"] != nil) {
5358 stick_pitch = [result oo_floatForKey:@"stickPitchFactor"] * max_flight_pitch;
5359 } else {
5360 stick_pitch = [result oo_floatForKey:@"stickPitch"];
5361 }
5364 } else if (stick_pitch < -max_flight_pitch) {
5366 }
5367
5368 // yaw or yaw factor
5369 if ([result objectForKey:@"stickYawFactor"] != nil) {
5370 stick_yaw = [result oo_floatForKey:@"stickYawFactor"] * max_flight_yaw;
5371 } else {
5372 stick_yaw = [result oo_floatForKey:@"stickYaw"];
5373 }
5374 if (stick_yaw > max_flight_yaw) {
5376 } else if (stick_yaw < -max_flight_yaw) {
5378 }
5379
5380 // apply sticks to current flight profile
5381 [self applySticks:delta_t];
5382
5383 // desired speed
5384 if ([result objectForKey:@"desiredSpeedFactor"] != nil) {
5385 desired_speed = [result oo_floatForKey:@"desiredSpeedFactor"] * maxFlightSpeed;
5386 } else {
5387 desired_speed = [result oo_floatForKey:@"desiredSpeed"];
5388 }
5389
5390 if (desired_speed < 0.0) {
5391 desired_speed = 0.0;
5392 }
5393 // overspeed and injector use is handled by applyThrust
5394
5395 if (behaviour == BEHAVIOUR_SCRIPTED_ATTACK_AI) {
5396 NSString* chosen_weapon = [result oo_stringForKey:@"chosenWeapon" defaultValue:@"FORWARD"];
5397 double range = [self rangeToPrimaryTarget];
5398
5399 if ([chosen_weapon isEqualToString:@"FORWARD"]) {
5400 [self fireMainWeapon:range];
5401 } else if ([chosen_weapon isEqualToString:@"AFT"]) {
5402 [self fireAftWeapon:range];
5403 } else if ([chosen_weapon isEqualToString:@"PORT"]) {
5404 [self firePortWeapon:range];
5405 } else if ([chosen_weapon isEqualToString:@"STARBOARD"]) {
5406 [self fireStarboardWeapon:range];
5407 }
5408 }
5409}
5410
5412{
5413 return reactionTime;
5414}
5415
5416- (void)setReactionTime:(float)newReactionTime
5417{
5418 reactionTime = newReactionTime;
5419}
5420
5422{
5423 Entity* target = [self primaryTarget];
5424 if (target == nil) {
5425 return kZeroHPVector;
5426 }
5427 if (reactionTime <= 0.0) {
5428 return [target position];
5429 }
5430 double t = [UNIVERSE getTime] - trackingCurveTimes[1];
5432}
5433
5435{
5436 Entity* target = [self primaryTarget];
5437 if (target == nil) {
5438 return;
5439 }
5440 OOTimeAbsolute now = [UNIVERSE getTime];
5445 trackingCurveTimes[0] = now;
5446 trackingCurveTimes[1] = now - reactionTime / 3.0;
5447 trackingCurveTimes[2] = now - reactionTime * 2.0 / 3.0;
5450 return;
5451}
5452
5454{
5455 Entity* target = [self primaryTarget];
5456 OOTimeAbsolute now = [UNIVERSE getTime];
5457 if (target == nil || reactionTime <= 0.0 || trackingCurveTimes[0] + reactionTime / 3.0 > now)
5458 return;
5462 if (EXPECT_NOT([target isShip] && [(ShipEntity*)target isCloaked])) {
5463 // if target is cloaked, introduce some more inaccuracy
5464 // 0.02 seems to be enough to give them slight difficulty on
5465 // a straight-line target and real trouble on anything better
5467 } else {
5469 }
5473 trackingCurveTimes[0] = now;
5475 return;
5476}
5477
5479{
5480 if (reactionTime <= 0.0) {
5484 return;
5485 }
5486 double t1 = trackingCurveTimes[2] - trackingCurveTimes[1],
5490 HPvector_multiply_scalar(trackingCurvePositions[1], -(t1 + t2) / (t1 * t2)),
5491 HPvector_multiply_scalar(trackingCurvePositions[2], -t2 / (t1 * (t1 - t2)))),
5492 HPvector_multiply_scalar(trackingCurvePositions[3], t1 / (t2 * (t1 - t2))));
5495 HPvector_multiply_scalar(trackingCurvePositions[2], 1 / (t1 * (t1 - t2)))),
5496 HPvector_multiply_scalar(trackingCurvePositions[3], -1 / (t2 * (t1 - t2))));
5497 return;
5498}
5499
5500- (void)drawImmediate:(bool)immediate translucent:(bool)translucent
5501{
5502 if ((no_draw_distance < cam_zero_distance) || // Done redundantly to skip subentities
5503 (cloaking_device_active && randf() > 0.10)) {
5504 // Don't draw.
5505 return;
5506 }
5507
5508 // Draw self.
5509 [super drawImmediate:immediate translucent:translucent];
5510
5511#ifdef OO_DEBUG_MONITOR_ENABLED
5512 // Draw bounding boxes if we have to before going for the subentities.
5513 // TODO: the translucent flag here makes very little sense. Something's wrong with the matrices.
5514 if (translucent)
5515 [self drawDebugStuff];
5516 else if (gDebugFlags & DEBUG_BOUNDING_BOXES && ![self isSubEntity]) {
5518 OODebugDrawColoredBoundingBox(totalBoundingBox, [OOColor purpleColor]);
5519 }
5520#endif
5521
5522 // Draw subentities.
5523 if (!immediate) // TODO: is this relevant any longer?
5524 {
5525 // save time by not copying the subentity array if it's empty - CIM
5526 if ([self subEntityCount] > 0) {
5527 Entity<OOSubEntity>* subEntity = nil;
5528 foreach (subEntity, [self subEntities]) {
5529 NSAssert3([subEntity owner] == self, @"Subentity ownership broke - %@ should be owned by %@ but is owned by %@.", subEntity, self, [subEntity owner]);
5530 [subEntity drawSubEntityImmediate:immediate translucent:translucent];
5531 }
5532 }
5533 }
5534}
5535
5536#ifdef OO_DEBUG_MONITOR_ENABLED
5537- (void)drawDebugStuff
5538{
5539 // HPVect: imprecise here - needs camera relative
5540 if (0 && reportAIMessages) {
5541 OODebugDrawPoint(HPVectorToVector(_destination), [OOColor blueColor]);
5542 OODebugDrawColoredLine(HPVectorToVector([self position]), HPVectorToVector(_destination), [OOColor colorWithWhite:0.15 alpha:1.0]);
5543
5544 Entity* pTarget = [self primaryTarget];
5545 if (pTarget != nil) {
5546 OODebugDrawPoint(HPVectorToVector([pTarget position]), [OOColor redColor]);
5547 OODebugDrawColoredLine(HPVectorToVector([self position]), HPVectorToVector([pTarget position]), [OOColor colorWithRed:0.2 green:0.0 blue:0.0 alpha:1.0]);
5548 }
5549
5550 Entity* sTarget = [self targetStation];
5551 if (sTarget != pTarget && [sTarget isStation]) {
5552 OODebugDrawPoint(HPVectorToVector([sTarget position]), [OOColor cyanColor]);
5553 }
5554
5555 Entity* fTarget = [self foundTarget];
5556 if (fTarget != nil && fTarget != pTarget && fTarget != sTarget) {
5557 OODebugDrawPoint(HPVectorToVector([fTarget position]), [OOColor magentaColor]);
5558 }
5559 }
5560}
5561#endif
5562
5563- (void)drawSubEntityImmediate:(bool)immediate translucent:(bool)translucent
5564{
5566
5567 if (cam_zero_distance > no_draw_distance) // this test provides an opportunity to do simple LoD culling
5568 {
5569 return; // TOO FAR AWAY
5570 }
5572
5573 // HPVect: need to make camera-relative
5576 [self drawImmediate:immediate translucent:translucent];
5577
5578#ifdef OO_DEBUG_MONITOR_ENABLED
5581 }
5582#endif
5583
5585
5587}
5588
5589static GLfloat cargo_color[4] = { 0.9, 0.9, 0.9, 1.0 }; // gray
5590static GLfloat hostile_color[4] = { 1.0, 0.25, 0.0, 1.0 }; // red/orange
5591static GLfloat neutral_color[4] = { 1.0, 1.0, 0.0, 1.0 }; // yellow
5592static GLfloat friendly_color[4] = { 0.0, 1.0, 0.0, 1.0 }; // green
5593static GLfloat missile_color[4] = { 0.0, 1.0, 1.0, 1.0 }; // cyan
5594static GLfloat police_color1[4] = { 0.5, 0.0, 1.0, 1.0 }; // purpley-blue
5595static GLfloat police_color2[4] = { 1.0, 0.0, 0.5, 1.0 }; // purpley-red
5596static GLfloat jammed_color[4] = { 0.0, 0.0, 0.0, 0.0 }; // clear black
5597static GLfloat mascem_color1[4] = { 0.3, 0.3, 0.3, 1.0 }; // dark gray
5598static GLfloat mascem_color2[4] = { 0.4, 0.1, 0.4, 1.0 }; // purple
5599static GLfloat scripted_color[4] = { 0.0, 0.0, 0.0, 0.0 }; // to be defined by script
5600
5601- (GLfloat*)scannerDisplayColorForShip:(ShipEntity*)otherShip isHostile:(BOOL)isHostile flash:(BOOL)flash scannerDisplayColor1:(OOColor*)scannerDisplayColor1 scannerDisplayColor2:(OOColor*)scannerDisplayColor2 scannerDisplayColorH1:(OOColor*)scannerDisplayColorH1 scannerDisplayColorH2:(OOColor*)scannerDisplayColorH2
5602{
5603 if (isHostile) {
5604 /* if there are any scripted scanner hostile display colours
5605 * for the ship, use them - otherwise fall through to the
5606 * normal scripted colours, then the scan class colours */
5607 if (scannerDisplayColorH1 || scannerDisplayColorH2) {
5608 if (scannerDisplayColorH1 && !scannerDisplayColorH2) {
5609 [scannerDisplayColorH1 getRed:&scripted_color[0] green:&scripted_color[1] blue:&scripted_color[2] alpha:&scripted_color[3]];
5610 }
5611
5612 if (!scannerDisplayColorH1 && scannerDisplayColorH2) {
5613 [scannerDisplayColorH2 getRed:&scripted_color[0] green:&scripted_color[1] blue:&scripted_color[2] alpha:&scripted_color[3]];
5614 }
5615
5616 if (scannerDisplayColorH1 && scannerDisplayColorH2) {
5617 if (flash)
5618 [scannerDisplayColorH1 getRed:&scripted_color[0] green:&scripted_color[1] blue:&scripted_color[2] alpha:&scripted_color[3]];
5619 else
5620 [scannerDisplayColorH2 getRed:&scripted_color[0] green:&scripted_color[1] blue:&scripted_color[2] alpha:&scripted_color[3]];
5621 }
5622
5623 return scripted_color;
5624 }
5625 }
5626
5627 // if there are any scripted scanner display colors for the ship, use them
5630 [scannerDisplayColor1 getRed:&scripted_color[0] green:&scripted_color[1] blue:&scripted_color[2] alpha:&scripted_color[3]];
5631 }
5632
5634 [scannerDisplayColor2 getRed:&scripted_color[0] green:&scripted_color[1] blue:&scripted_color[2] alpha:&scripted_color[3]];
5635 }
5636
5638 if (flash)
5639 [scannerDisplayColor1 getRed:&scripted_color[0] green:&scripted_color[1] blue:&scripted_color[2] alpha:&scripted_color[3]];
5640 else
5641 [scannerDisplayColor2 getRed:&scripted_color[0] green:&scripted_color[1] blue:&scripted_color[2] alpha:&scripted_color[3]];
5642 }
5643
5644 return scripted_color;
5645 }
5646
5647 // no scripted scanner display colors defined, proceed as per standard
5648 if ([self isJammingScanning]) {
5649 if (![otherShip hasMilitaryScannerFilter])
5650 return jammed_color;
5651 else {
5652 if (flash)
5653 return mascem_color1;
5654 else {
5655 if (isHostile)
5656 return hostile_color;
5657 else
5658 return mascem_color2;
5659 }
5660 }
5661 }
5662
5663 switch (scanClass) {
5664 case CLASS_ROCK:
5665 case CLASS_CARGO:
5666 return cargo_color;
5667 case CLASS_THARGOID:
5668 if (flash)
5669 return hostile_color;
5670 else
5671 return friendly_color;
5672 case CLASS_MISSILE:
5673 return missile_color;
5674 case CLASS_STATION:
5675 return friendly_color;
5676 case CLASS_BUOY:
5677 if (flash)
5678 return friendly_color;
5679 else
5680 return neutral_color;
5681 case CLASS_POLICE:
5682 case CLASS_MILITARY:
5683 if ((isHostile) && (flash))
5684 return police_color2;
5685 else
5686 return police_color1;
5687 case CLASS_MINE:
5688 if (flash)
5689 return neutral_color;
5690 else
5691 return hostile_color;
5692 default:
5693 if (isHostile)
5694 return hostile_color;
5695 }
5696 return neutral_color;
5697}
5698
5699- (void)setScannerDisplayColor1:(OOColor*)color
5700{
5702
5703 if (color == nil)
5704 color = [OOColor colorWithDescription:[[self shipInfoDictionary] objectForKey:@"scanner_display_color1"]];
5705 scanner_display_color1 = [color retain];
5706}
5707
5708- (void)setScannerDisplayColor2:(OOColor*)color
5709{
5711
5712 if (color == nil)
5713 color = [OOColor colorWithDescription:[[self shipInfoDictionary] objectForKey:@"scanner_display_color2"]];
5714 scanner_display_color2 = [color retain];
5715}
5716
5718{
5719 return [[scanner_display_color1 retain] autorelease];
5720}
5721
5723{
5724 return [[scanner_display_color2 retain] autorelease];
5725}
5726
5727- (void)setScannerDisplayColorHostile1:(OOColor*)color
5728{
5730
5731 if (color == nil)
5732 color = [OOColor colorWithDescription:[[self shipInfoDictionary] objectForKey:@"scanner_hostile_display_color1"]];
5734}
5735
5736- (void)setScannerDisplayColorHostile2:(OOColor*)color
5737{
5739
5740 if (color == nil)
5741 color = [OOColor colorWithDescription:[[self shipInfoDictionary] objectForKey:@"scanner_hostile_display_color2"]];
5743}
5744
5746{
5747 return [[scanner_display_color_hostile1 retain] autorelease];
5748}
5749
5751{
5752 return [[scanner_display_color_hostile2 retain] autorelease];
5753}
5754
5756{
5758}
5759
5761{
5762 return cloakPassive;
5763}
5764
5765- (void)setCloaked:(BOOL)cloak
5766{
5767 if (cloak)
5769 else
5771}
5772
5774{
5775 return cloakAutomatic;
5776}
5777
5778- (void)setAutoCloak:(BOOL)automatic
5779{
5780 cloakAutomatic = !!automatic;
5781}
5782
5784{
5785 return ([self hasMilitaryJammer] && military_jammer_active);
5786}
5787
5788- (void)addSubEntity:(Entity<OOSubEntity>*)sub
5789{
5790 if (sub == nil)
5791 return;
5792
5793 if (subEntities == nil)
5794 subEntities = [[NSMutableArray alloc] init];
5795 sub->isSubEntity = YES;
5796 // Order matters - need consistent state in setOwner:. -- Ahruman 2008-04-20
5797 [subEntities addObject:sub];
5798 [sub setOwner:self];
5799
5801}
5802
5803- (void)setOwner:(Entity*)who_owns_entity
5804{
5805 [super setOwner:who_owns_entity];
5806
5807 /* Reset shader binding target so that bind-to-super works.
5808 This is necessary since we don't know about the owner in
5809 setUpShipFromDictionary:, when the mesh is initially set up.
5810 -- Ahruman 2008-04-19
5811 */
5812 if (isSubEntity) {
5813 [[self drawable] setBindingTarget:self];
5814 }
5815}
5816
5817- (void)applyThrust:(double)delta_t
5818{
5819 GLfloat dt_thrust = SHIP_THRUST_FACTOR * thrust * delta_t;
5820 BOOL canBurn = [self hasFuelInjection] && (fuel > MIN_FUEL);
5821 BOOL isUsingAfterburner = (canBurn && (flightSpeed > maxFlightSpeed) && (desired_speed >= flightSpeed));
5822 float max_available_speed = maxFlightSpeed;
5823 if (canBurn)
5824 max_available_speed *= [self afterburnerFactor];
5825
5826 if (thrust) {
5827 // If we have Newtonian (non-thrust) velocity, brake it.
5828 GLfloat velmag = magnitude(velocity);
5829 if (velmag) {
5830 GLfloat vscale = fmaxf((velmag - dt_thrust) / velmag, 0.0f);
5831 scale_vector(&velocity, vscale);
5832 }
5833 }
5834
5835 if (behaviour == BEHAVIOUR_TUMBLE)
5836 return;
5837
5838 // check for speed
5839 if (desired_speed > max_available_speed)
5840 desired_speed = max_available_speed;
5841
5842 if (flightSpeed > desired_speed) {
5843 [self decrease_flight_speed:dt_thrust];
5846 }
5847 if (flightSpeed < desired_speed) {
5848 [self increase_flight_speed:dt_thrust];
5851 }
5852 [self moveForward:delta_t * flightSpeed];
5853
5854 // burn fuel at the appropriate rate
5855 if (isUsingAfterburner) // no fuelconsumption on slowdown
5856 {
5858 while (fuel_accumulator < 0.0) {
5859 fuel--;
5860 fuel_accumulator += 1.0;
5861 }
5862 }
5863}
5864
5873
5874- (void)applyRoll:(GLfloat)roll1 andClimb:(GLfloat)climb1
5875{
5877
5878 if (!roll1 && !climb1 && !hasRotated)
5879 return;
5880
5881 if (roll1)
5882 quaternion_rotate_about_z(&q1, -roll1);
5883 if (climb1)
5884 quaternion_rotate_about_x(&q1, -climb1);
5885
5887 [self orientationChanged];
5888}
5889
5890- (void)applyRoll:(GLfloat)roll1 climb:(GLfloat)climb1 andYaw:(GLfloat)yaw1
5891{
5892 if ((roll1 == 0.0) && (climb1 == 0.0) && (yaw1 == 0.0) && (!hasRotated))
5893 return;
5894
5896
5897 if (roll1)
5898 quaternion_rotate_about_z(&q1, -roll1);
5899 if (climb1)
5900 quaternion_rotate_about_x(&q1, -climb1);
5901 if (yaw1)
5902 quaternion_rotate_about_y(&q1, -yaw1);
5903
5905 [self orientationChanged];
5906}
5907
5908- (void)applyAttitudeChanges:(double)delta_t
5909{
5910 [self applyRoll:flightRoll * delta_t climb:flightPitch * delta_t andYaw:flightYaw * delta_t];
5911}
5912
5914{
5915 if (scanClass == CLASS_MISSILE)
5916 return; // missiles are SUPPOSED to collide!
5917
5918 ShipEntity* prox_ship = (ShipEntity*)[self proximityAlert];
5919
5920 if (prox_ship) {
5921 if (previousCondition) {
5922 [previousCondition release];
5924 }
5925
5926 previousCondition = [[NSMutableDictionary dictionaryWithCapacity:5] retain];
5927
5928 [previousCondition oo_setInteger:behaviour forKey:@"behaviour"];
5929 if ([self primaryTarget] != nil) {
5930 // must use the weak ref here to prevent potential over-retention
5931 [previousCondition setObject:[[self primaryTarget] weakSelf] forKey:@"primaryTarget"];
5932 }
5933 [previousCondition oo_setFloat:desired_range forKey:@"desired_range"];
5934 [previousCondition oo_setFloat:desired_speed forKey:@"desired_speed"];
5935 [previousCondition oo_setHPVector:_destination forKey:@"destination"];
5936
5938 _destination = OOHPVectorInterpolate(position, [prox_ship position], 0.5); // point between us and them
5939
5941
5942 behaviour = BEHAVIOUR_AVOID_COLLISION;
5943 pitching_over = YES;
5944 }
5945}
5946
5948{
5949 if (!previousCondition)
5950 return;
5951
5952 behaviour = [previousCondition oo_intForKey:@"behaviour"];
5953 [_primaryTarget release];
5954 _primaryTarget = [[previousCondition objectForKey:@"primaryTarget"] weakRetain];
5955 [self startTrackingCurve];
5956 desired_range = [previousCondition oo_floatForKey:@"desired_range"];
5957 desired_speed = [previousCondition oo_floatForKey:@"desired_speed"];
5958 _destination = [previousCondition oo_hpvectorForKey:@"destination"];
5959
5960 [previousCondition release];
5962 frustration = 0.0;
5963
5965
5966 //[shipAI message:@"RESTART_DOCKING"]; // if docking, start over, other AIs will ignore this message
5967}
5968
5970{
5971 return messageTime;
5972}
5973
5974- (void)setMessageTime:(double)value
5975{
5976 messageTime = value;
5977}
5978
5980{
5981 return _group;
5982}
5983
5984- (void)setGroup:(OOShipGroup*)group
5985{
5986 if (group != _group) {
5987 if (_escortGroup != _group) {
5988 if (self == [_group leader])
5989 [_group setLeader:nil];
5990 [_group removeShip:self];
5991 }
5992 [_group release];
5993 [group addShip:self];
5994 _group = [group retain];
5995
5997 }
5998}
5999
6001{
6002 if (_escortGroup == nil) {
6003 _escortGroup = [[OOShipGroup alloc] initWithName:@"escort group"];
6004 [_escortGroup setLeader:self];
6005 }
6006
6007 return _escortGroup;
6008}
6009
6010- (void)setEscortGroup:(OOShipGroup*)group
6011{
6012 if (group != _escortGroup) {
6013 [_escortGroup release];
6014 _escortGroup = [group retain];
6015 [group setLeader:self]; // A ship is always leader of its own escort group.
6016 [self updateEscortFormation];
6017 }
6018}
6019
6020#ifdef OO_DEBUG_MONITOR_ENABLED
6021- (OOShipGroup*)rawEscortGroup
6022{
6023 return _escortGroup;
6024}
6025#endif
6026
6028{
6029 if (_group == nil) {
6030 _group = [[OOShipGroup alloc] initWithName:@"station group"];
6031 [_group setLeader:self];
6032 }
6033
6034 return _group;
6035}
6036
6038{
6039 if (_escortGroup == nil)
6040 return NO;
6041 return [_escortGroup count] > 1; // If only one member, it's self.
6042}
6043
6044- (NSEnumerator*)escortEnumerator
6045{
6046 if (_escortGroup == nil)
6047 return [[NSArray array] objectEnumerator];
6048 return [[_escortGroup mutationSafeEnumerator] ooExcludingObject:self];
6049}
6050
6051- (NSArray*)escortArray
6052{
6053 if (_escortGroup == nil)
6054 return [NSArray array];
6055 return [[self escortEnumerator] allObjects];
6056}
6057
6058- (uint8_t)escortCount
6059{
6060 if (_escortGroup == nil)
6061 return 0;
6062 return [_escortGroup count] - 1;
6063}
6064
6066{
6067 return _pendingEscortCount;
6068}
6069
6070- (void)setPendingEscortCount:(uint8_t)count
6071{
6073}
6074
6076{
6077 return _maxEscortCount;
6078}
6079
6080- (void)setMaxEscortCount:(uint8_t)newCount
6081{
6082 _maxEscortCount = newCount;
6083}
6084
6085- (NSUInteger)turretCount
6086{
6087 NSUInteger count = 0;
6088 NSEnumerator* subEnum = [self shipSubEntityEnumerator];
6089 ShipEntity* se = nil;
6090 while ((se = [subEnum nextObject])) {
6091 if ([se isTurret]) {
6092 count++;
6093 }
6094 }
6095 return count;
6096}
6097
6099{
6101 if (prox == nil) {
6103 }
6104 return prox;
6105}
6106
6107- (void)setProximityAlert:(ShipEntity*)other
6108{
6109 if (!other) {
6111 return;
6112 }
6113
6114 if ([other mass] < 2000) // we are not alerted by small objects. (a cargopod has a mass of about 1000)
6115 return;
6116
6117 if (isStation) // stations don't worry about colliding with things
6118 return;
6119
6120 /* Ignore station collision warnings if launching or docking */
6121 if ((other->isStation) && ([self status] == STATUS_LAUNCHING || dockingInstructions != nil)) {
6122 return;
6123 }
6124
6125 if (!crew) // Ships without pilot (cargo, rocks, missiles, buoys etc) will not get alarmed. (escape-pods have pilots)
6126 return;
6127
6128 // check vectors
6130 GLfloat d_forward = dot_product(vdiff, v_forward);
6131 GLfloat d_up = dot_product(vdiff, v_up);
6132 GLfloat d_right = dot_product(vdiff, v_right);
6133 if ((d_forward > 0.0) && (flightSpeed > 0.0)) // it's ahead of us and we're moving forward
6134 d_forward *= 0.25 * maxFlightSpeed / flightSpeed; // extend the collision zone forward up to 400%
6135 double d2 = d_forward * d_forward + d_up * d_up + d_right * d_right;
6136 double cr2 = collision_radius * 2.0 + other->collision_radius;
6137 cr2 *= cr2; // check with twice the combined radius
6138
6139 if (d2 > cr2) // we're okay
6140 return;
6141
6142 if (behaviour == BEHAVIOUR_AVOID_COLLISION) // already avoiding something
6143 {
6144 ShipEntity* prox = (ShipEntity*)[self proximityAlert];
6145 if ((prox) && (prox != other)) {
6146 // check which subtends the greatest angle
6147 GLfloat sa_prox = prox->collision_radius * prox->collision_radius / HPdistance2(position, prox->position);
6148 GLfloat sa_other = other->collision_radius * other->collision_radius / HPdistance2(position, other->position);
6149 if (sa_prox < sa_other)
6150 return;
6151 }
6152 }
6153 [_proximityAlert release];
6155}
6156
6157- (NSString*)name
6158{
6159 return name;
6160}
6161
6162- (NSString*)shipUniqueName
6163{
6164 return shipUniqueName;
6165}
6166
6167- (NSString*)shipClassName
6168{
6169 return shipClassName;
6170}
6171
6172- (NSString*)displayName
6173{
6174 if (displayName == nil || [displayName length] == 0) {
6175 if ([shipUniqueName length] == 0) {
6176 if (shipClassName == nil) {
6177 return name;
6178 } else {
6179 return shipClassName;
6180 }
6181 } else {
6182 if (shipClassName == nil) {
6183 return [NSString stringWithFormat:@"%@: %@", name, shipUniqueName];
6184 } else {
6185 return [NSString stringWithFormat:@"%@: %@", shipClassName, shipUniqueName];
6186 }
6187 }
6188 }
6189 return displayName;
6190}
6191
6192// needed so that scan_description = scan_description doesn't have odd effects
6194{
6195 return scan_description;
6196}
6197
6199{
6200 if (scan_description != nil) {
6201 return scan_description;
6202 } else {
6203 NSString* desc = nil;
6204 switch ([self scanClass]) {
6205 case CLASS_NEUTRAL: {
6206 int legal = [self legalStatus];
6207 int legal_i = 0;
6208 if (legal > 0) {
6209 legal_i = (legal <= 50) ? 1 : 2;
6210 }
6211 desc = [[[UNIVERSE descriptions] oo_arrayForKey:@"legal_status"] oo_stringAtIndex:legal_i];
6212 } break;
6213
6214 case CLASS_THARGOID:
6215 desc = DESC(@"legal-desc-alien");
6216 break;
6217
6218 case CLASS_POLICE:
6219 desc = DESC(@"legal-desc-system-vessel");
6220 break;
6221
6222 case CLASS_MILITARY:
6223 desc = DESC(@"legal-desc-military-vessel");
6224 break;
6225
6226 default:
6227 break;
6228 }
6229 return desc;
6230 }
6231}
6232
6233- (void)setName:(NSString*)inName
6234{
6235 [name release];
6236 name = [inName copy];
6237}
6238
6239- (void)setShipUniqueName:(NSString*)inName
6240{
6241 [shipUniqueName release];
6242 shipUniqueName = [inName copy];
6243}
6244
6245- (void)setShipClassName:(NSString*)inName
6246{
6247 [shipClassName release];
6248 shipClassName = [inName copy];
6249}
6250
6251- (void)setDisplayName:(NSString*)inName
6252{
6253 [displayName release];
6254 displayName = [inName copy];
6255}
6256
6257- (void)setScanDescription:(NSString*)inName
6258{
6259 [scan_description release];
6260 scan_description = [inName copy];
6261}
6262
6263- (NSString*)identFromShip:(ShipEntity*)otherShip
6264{
6265 if ([self isJammingScanning] && ![otherShip hasMilitaryScannerFilter]) {
6266 return DESC(@"unknown-target");
6267 }
6268 return [self displayName];
6269}
6270
6271- (BOOL)hasRole:(NSString*)role
6272{
6273 return [roleSet hasRole:role] || [role isEqual:primaryRole] || [role isEqual:[self shipDataKeyAutoRole]];
6274}
6275
6277{
6278 if (roleSet == nil)
6279 roleSet = [[OORoleSet alloc] initWithRoleString:primaryRole];
6281}
6282
6283- (void)addRole:(NSString*)role
6284{
6285 [self addRole:role withProbability:0.0f];
6286}
6287
6288- (void)addRole:(NSString*)role withProbability:(float)probability
6289{
6290 if (![self hasRole:role]) {
6291 OORoleSet* newRoles = nil;
6292 if (roleSet != nil)
6293 newRoles = [roleSet roleSetWithAddedRole:role probability:probability];
6294 else
6295 newRoles = [OORoleSet roleSetWithRole:role probability:probability];
6296 if (newRoles != nil) {
6297 [roleSet release];
6298 roleSet = [newRoles retain];
6299 }
6300 }
6301}
6302
6303- (void)removeRole:(NSString*)role
6304{
6305 if ([self hasRole:role]) {
6306 OORoleSet* newRoles = [roleSet roleSetWithRemovedRole:role];
6307 if (newRoles != nil) {
6308 [roleSet release];
6309 roleSet = [newRoles retain];
6310 }
6311 }
6312}
6313
6314- (NSString*)primaryRole
6315{
6316 if (primaryRole == nil) {
6318 if (primaryRole == nil)
6319 primaryRole = @"trader";
6320 [primaryRole retain];
6321 OOLog(@"ship.noPrimaryRole", @"%@ had no primary role, randomly selected \"%@\".", [self name], primaryRole);
6322 }
6323
6324 return primaryRole;
6325}
6326
6327// Exposed to AI.
6328- (void)setPrimaryRole:(NSString*)role
6329{
6330 if (![role isEqual:primaryRole]) {
6331 [primaryRole release];
6332 primaryRole = [role copy];
6333 }
6334}
6335
6336- (BOOL)hasPrimaryRole:(NSString*)role
6337{
6338 return [[self primaryRole] isEqual:role];
6339}
6340
6342{
6343 // bounty hunters have a police role, but are not police, so we must test by scan class, not by role
6344 return [self scanClass] == CLASS_POLICE;
6345}
6346
6348{
6349 return [self scanClass] == CLASS_THARGOID;
6350}
6351
6353{
6354 return [UNIVERSE role:[self primaryRole] isInCategory:@"oolite-trader"];
6355}
6356
6358{
6359 return [UNIVERSE role:[self primaryRole] isInCategory:@"oolite-pirate"];
6360}
6361
6363{
6364 return ([[self primaryRole] hasSuffix:@"MISSILE"] || [self hasPrimaryRole:@"missile"]);
6365}
6366
6367- (BOOL)isMine
6368{
6369 return [[self primaryRole] hasSuffix:@"MINE"];
6370}
6371
6373{
6374 return [self isMissile] || [self isMine];
6375}
6376
6378{
6379 return [UNIVERSE role:[self primaryRole] isInCategory:@"oolite-escort"];
6380}
6381
6383{
6384 return [UNIVERSE role:[self primaryRole] isInCategory:@"oolite-shuttle"];
6385}
6386
6388{
6389 return behaviour == BEHAVIOUR_TRACK_AS_TURRET;
6390}
6391
6393{
6394 return [UNIVERSE roleIsPirateVictim:[self primaryRole]];
6395}
6396
6398{
6399 return _explicitlyUnpiloted;
6400}
6401
6403{
6404 return [self isExplicitlyUnpiloted] || [self isHulk] || [self scanClass] == CLASS_ROCK || [self scanClass] == CLASS_CARGO;
6405}
6406
6408{
6409 switch (behaviour) {
6410 case BEHAVIOUR_ATTACK_TARGET:
6411 case BEHAVIOUR_ATTACK_FLY_TO_TARGET:
6412 case BEHAVIOUR_ATTACK_FLY_FROM_TARGET:
6413 case BEHAVIOUR_RUNNING_DEFENSE:
6414 case BEHAVIOUR_FLEE_TARGET:
6415 case BEHAVIOUR_ATTACK_BREAK_OFF_TARGET:
6416 case BEHAVIOUR_ATTACK_SLOW_DOGFIGHT:
6417 case BEHAVIOUR_EVASIVE_ACTION:
6418 case BEHAVIOUR_FLEE_EVASIVE_ACTION:
6419 case BEHAVIOUR_ATTACK_FLY_TO_TARGET_SIX:
6420 // case BEHAVIOUR_ATTACK_MINING_TARGET:
6421 case BEHAVIOUR_ATTACK_FLY_TO_TARGET_TWELVE:
6422 case BEHAVIOUR_ATTACK_BROADSIDE:
6423 case BEHAVIOUR_ATTACK_BROADSIDE_LEFT:
6424 case BEHAVIOUR_ATTACK_BROADSIDE_RIGHT:
6425 case BEHAVIOUR_CLOSE_TO_BROADSIDE_RANGE:
6426 case BEHAVIOUR_CLOSE_WITH_TARGET:
6427 case BEHAVIOUR_ATTACK_SNIPER:
6428 case BEHAVIOUR_SCRIPTED_ATTACK_AI:
6429 return YES;
6430
6431 default:
6432 return NO;
6433 }
6434
6435 return 100 < behaviour && behaviour < 120;
6436}
6437
6438// Exposed to shaders.
6440{
6441 Entity* t = [self primaryTarget];
6442 if (t == nil || ![t isShip]) {
6443 return NO;
6444 }
6445 if ([self isMissile]) {
6446 return YES; // missiles are always fired against a hostile target
6447 }
6448 if ((behaviour == BEHAVIOUR_AVOID_COLLISION) && (previousCondition)) {
6449 int old_behaviour = [previousCondition oo_intForKey:@"behaviour"];
6450 return IsBehaviourHostile(old_behaviour);
6451 }
6453}
6454
6455- (BOOL)isHostileTo:(Entity*)entity
6456{
6457 return ([self hasHostileTarget] && [self primaryTarget] == entity);
6458}
6459
6460- (GLfloat)weaponRange
6461{
6462 return weaponRange;
6463}
6464
6465- (void)setWeaponRange:(GLfloat)value
6466{
6467 weaponRange = value;
6468}
6469
6470- (void)setWeaponDataFromType:(OOWeaponType)weapon_type
6471{
6472 weaponRange = getWeaponRangeFromType(weapon_type);
6477
6478 if (default_laser_color == nil) {
6480 if (wcol != nil) {
6481 [self setLaserColor:wcol];
6482 }
6483 }
6484}
6485
6487{
6488 return energy_recharge_rate;
6489}
6490
6491- (void)setEnergyRechargeRate:(GLfloat)new
6492{
6494}
6495
6497{
6498 return weapon_recharge_rate;
6499}
6500
6501- (void)setWeaponRechargeRate:(float)value
6502{
6503 weapon_recharge_rate = value;
6504}
6505
6506- (void)setWeaponEnergy:(float)value
6507{
6508 weapon_damage = value;
6509}
6510
6515
6517{
6518 return scannerRange;
6519}
6520
6521- (void)setScannerRange:(GLfloat)value
6522{
6523 scannerRange = value;
6524}
6525
6527{
6528 return reference;
6529}
6530
6531- (void)setReference:(Vector)v
6532{
6533 reference = v;
6534}
6535
6537{
6538 return reportAIMessages;
6539}
6540
6541- (void)setReportAIMessages:(BOOL)yn
6542{
6543 reportAIMessages = yn;
6544}
6545
6547{
6550 if (lastAegisLock != nil) {
6551 [self doScriptEvent:OOJSID("shipExitedPlanetaryVicinity") withArgument:lastAegisLock];
6552
6553 if (lastAegisLock == [UNIVERSE sun]) {
6554 [shipAI message:@"AWAY_FROM_SUN"];
6555 } else {
6556 [shipAI message:@"AWAY_FROM_PLANET"];
6557 }
6558 }
6559
6561 [shipAI message:@"AEGIS_NONE"];
6562 }
6563 }
6565}
6566
6568{
6569 float centerDistance = HPmagnitude2(HPvector_subtract([stellar position], reference));
6570 float r = [stellar radius];
6571 /* 1.35: empirical value used to help determine proximity when non-nested
6572 planets are close to each other
6573 */
6574 return centerDistance - 1.35 * r * r;
6575}
6576
6578{
6579 return SurfaceDistanceSqaredV([reference position], stellar);
6580}
6581
6582NSComparisonResult ComparePlanetsBySurfaceDistance(id i1, id i2, void* context)
6583{
6585 OOPlanetEntity* e1 = i1;
6586 OOPlanetEntity* e2 = i2;
6587
6588 float p1 = SurfaceDistanceSqaredV(p, e1);
6589 float p2 = SurfaceDistanceSqaredV(p, e2);
6590
6591 if (p1 < p2)
6592 return NSOrderedAscending;
6593 if (p1 > p2)
6594 return NSOrderedDescending;
6595
6596 return NSOrderedSame;
6597}
6598
6599- (OOPlanetEntity*)findNearestPlanet
6600{
6601 /*
6602 Performance note: this method is called every frame by every ship, and
6603 has a significant profiler presence.
6604 -- Ahruman 2012-09-13
6605 */
6606 OOPlanetEntity *planet = nil, *bestPlanet = nil;
6607 float bestRange = INFINITY;
6608 HPVector myPosition = [self position];
6609
6610 // valgrind complains about this line here. Might be compiler/GNUstep bug?
6611 // should we go back to a traditional enumerator? - CIM
6612 // similar complaints about the other foreach() in this file
6613 foreach (planet, [UNIVERSE planets]) {
6614 // Ignore miniature planets.
6615 if ([planet planetType] == STELLAR_TYPE_MINIATURE)
6616 continue;
6617
6618 float range = SurfaceDistanceSqaredV(myPosition, planet);
6619 if (range < bestRange) {
6620 bestPlanet = planet;
6621 bestRange = range;
6622 }
6623 }
6624
6625 return bestPlanet;
6626}
6627
6629{
6631 OOSunEntity* sun = [UNIVERSE sun];
6632
6633 if (sun != nil) {
6634 if (match == nil || SurfaceDistanceSqared(self, sun) < SurfaceDistanceSqared(self, match)) {
6635 match = sun;
6636 }
6637 }
6638
6639 return match;
6640}
6641
6643{
6644 OOPlanetEntity* result = nil;
6645 OOPlanetEntity* planet = nil;
6646 NSArray* bodies = nil;
6647 NSArray* planets = nil;
6648 unsigned i;
6649
6650 bodies = [UNIVERSE planets];
6651 planets = [NSMutableArray arrayWithCapacity:[bodies count]];
6652
6653 for (i = 0; i < [bodies count]; i++) {
6654 planet = [bodies objectAtIndex:i];
6655 if ([planet planetType] == STELLAR_TYPE_NORMAL_PLANET)
6656 planets = [planets arrayByAddingObject:planet];
6657 }
6658
6659 if ([planets count] == 0)
6660 return nil;
6661
6662 planets = [planets sortedArrayUsingFunction:ComparePlanetsBySurfaceDistance context:self];
6663 result = [planets objectAtIndex:0];
6664
6665 return result;
6666}
6667
6669{
6671 BOOL sunGoneNova = [[UNIVERSE sun] goneNova];
6672
6673 if (nearest == nil) {
6674 if (aegis_status != AEGIS_NONE) {
6675 // Planet disappeared!
6676 [self transitionToAegisNone];
6677 }
6678 return AEGIS_NONE;
6679 }
6680 // check planet
6681 float cr = [nearest radius];
6682 float cr2 = cr * cr;
6683 OOAegisStatus result = AEGIS_NONE;
6684 float d2 = HPmagnitude2(HPvector_subtract([nearest position], [self position]));
6685 // not scannerRange: aegis shouldn't depend on that
6686 float sd2 = SCANNER_MAX_RANGE2 * 10.0f;
6687
6688 // check if nearing a surface
6689 unsigned wasNearPlanetSurface = isNearPlanetSurface; // isNearPlanetSurface is a bit flag, not an actual BOOL
6690 isNearPlanetSurface = (d2 - cr2) < (250000.0f + 1000.0f * cr); // less than 500m from the surface: (a+b)*(a+b) = a*a+b*b +2*a*b
6691
6692 if (EXPECT_NOT((wasNearPlanetSurface != isNearPlanetSurface) && !suppressAegisMessages)) {
6693 if (isNearPlanetSurface) {
6694 [self doScriptEvent:OOJSID("shipApproachingPlanetSurface") withArgument:nearest];
6695 [shipAI reactToMessage:@"APPROACHING_SURFACE" context:@"flight update"];
6696 } else {
6697 [self doScriptEvent:OOJSID("shipLeavingPlanetSurface") withArgument:nearest];
6698 [shipAI reactToMessage:@"LEAVING_SURFACE" context:@"flight update"];
6699 }
6700 }
6701
6702 // being close to the station takes precedence over planets
6703 StationEntity* the_station = [UNIVERSE station];
6704 if (the_station) {
6705 sd2 = HPmagnitude2(HPvector_subtract([the_station position], [self position]));
6706 }
6707 // again, notional scanner range is intentional
6708 if (sd2 < SCANNER_MAX_RANGE2 * 4.0f) // double scanner range
6709 {
6710 result = AEGIS_IN_DOCKING_RANGE;
6711 } else if (EXPECT_NOT(isNearPlanetSurface || d2 < cr2 * 9.0f)) // to 3x radius of any planet/moon - or 500m of tiny ones,
6712 {
6714 if (EXPECT((OOPlanetEntity*)nearest == [UNIVERSE planet])) {
6716 }
6717 }
6718 // need to do this check separately from above case to avoid oddity where
6719 // main planet and small moon are at just the wrong distance. - CIM
6720 if (result != AEGIS_CLOSE_TO_MAIN_PLANET && result != AEGIS_IN_DOCKING_RANGE && !sunGoneNova) {
6721 // are we also close to the main planet?
6722 OOPlanetEntity* mainPlanet = [UNIVERSE planet];
6723 d2 = HPmagnitude2(HPvector_subtract([mainPlanet position], [self position]));
6724 cr2 = [mainPlanet radius];
6725 cr2 *= cr2;
6726 if (d2 < cr2 * 9.0f) {
6727 nearest = mainPlanet;
6729 }
6730 }
6731
6732 /* Rewrote aegis stuff and tested it against redux.oxp that adds multiple planets and moons.
6733 Made sure AI scripts can differentiate between MAIN and NON-MAIN planets so they can decide
6734 if they can dock at the systemStation or just any station.
6735 Added sun detection so route2Patrol can turn before they heat up in the sun.
6736 -- Eric 2009-07-11
6737
6738 More rewriting of the aegis stuff, it's now a bit faster and works properly when moving
6739 from one secondary planet/moon vicinity to another one. -- Kaks 20120917
6740 */
6742 // script/AI messages on change in status
6744 [self doScriptEvent:OOJSID("shipExitedStationAegis") withArgument:the_station];
6745 [shipAI message:@"AEGIS_LEAVING_DOCKING_RANGE"];
6746 }
6747
6748 if (EXPECT_NOT(result == AEGIS_IN_DOCKING_RANGE && aegis_status != result)) {
6749 [self doScriptEvent:OOJSID("shipEnteredStationAegis") withArgument:the_station];
6750 [shipAI message:@"AEGIS_IN_DOCKING_RANGE"];
6751
6752 if ([self lastAegisLock] == nil && !sunGoneNova) // With small main planets the station aegis can come before planet aegis
6753 {
6754 [self doScriptEvent:OOJSID("shipEnteredPlanetaryVicinity") withArgument:[UNIVERSE planet]];
6755 [self setLastAegisLock:[UNIVERSE planet]];
6756 }
6757 } else if (EXPECT_NOT(result == AEGIS_NONE && aegis_status != result)) {
6758 if ([self lastAegisLock] == nil && !sunGoneNova) {
6759 [self setLastAegisLock:[UNIVERSE planet]]; // in case of a first launch from a near-planet station.
6760 }
6761 [self transitionToAegisNone];
6762 }
6763 // approaching..
6764 else if (EXPECT_NOT((result == AEGIS_CLOSE_TO_ANY_PLANET || result == AEGIS_CLOSE_TO_MAIN_PLANET) && [self lastAegisLock] != nearest)) {
6765 if (aegis_status != AEGIS_NONE && [self lastAegisLock] != nil) // we were close to another stellar body
6766 {
6767 [self doScriptEvent:OOJSID("shipExitedPlanetaryVicinity") withArgument:[self lastAegisLock]];
6768 [shipAI message:@"AWAY_FROM_PLANET"]; // fires for suns, planets and moons.
6769 }
6770 [self doScriptEvent:OOJSID("shipEnteredPlanetaryVicinity") withArgument:nearest];
6771 [self setLastAegisLock:nearest];
6772
6773 if (EXPECT_NOT([nearest isSun])) {
6774 [shipAI message:@"CLOSE_TO_SUN"];
6775 } else {
6776 [shipAI message:@"CLOSE_TO_PLANET"];
6777
6778 if (EXPECT(result == AEGIS_CLOSE_TO_MAIN_PLANET)) {
6779 // It's been years since 1.71 - it should be safe enough to comment out the line below for 1.77/1.78 -- Kaks 20120917
6780 //[shipAI message:@"AEGIS_CLOSE_TO_PLANET"]; // fires only for main planets, kept for compatibility with pre-1.72 AI plists.
6781 [shipAI message:@"AEGIS_CLOSE_TO_MAIN_PLANET"]; // fires only for main planet.
6782 } else if (EXPECT_NOT([nearest planetType] == STELLAR_TYPE_MOON)) {
6783 [shipAI message:@"CLOSE_TO_MOON"];
6784 } else {
6785 [shipAI message:@"CLOSE_TO_SECONDARY_PLANET"];
6786 }
6787 }
6788 }
6789 }
6790 if (result == AEGIS_NONE) {
6791 [self setLastAegisLock:nil];
6792 }
6793
6794 aegis_status = result; // put this here
6795 return result;
6796}
6797
6799{
6800 _nextAegisCheck = -1.0f;
6801}
6802
6804{
6806}
6807
6808- (Entity<OOStellarBody>*)lastAegisLock
6809{
6810 Entity<OOStellarBody>* stellar = [_lastAegisLock weakRefUnderlyingObject];
6811 if (stellar == nil) {
6812 [_lastAegisLock release];
6813 _lastAegisLock = nil;
6814 }
6815
6816 return stellar;
6817}
6818
6819- (void)setLastAegisLock:(Entity<OOStellarBody>*)lastAegisLock
6820{
6821 [_lastAegisLock release];
6822 _lastAegisLock = [lastAegisLock weakRetain];
6823}
6824
6826{
6827 return home_system;
6828}
6829
6834
6835- (void)setHomeSystem:(OOSystemID)s
6836{
6837 home_system = s;
6838}
6839
6840- (void)setDestinationSystem:(OOSystemID)s
6841{
6843}
6844
6845- (void)setStatus:(OOEntityStatus)stat
6846{
6847 if ([self status] == stat)
6848 return;
6849 [super setStatus:stat];
6850 if (stat == STATUS_LAUNCHING) {
6851 launch_time = [UNIVERSE getTime];
6852 }
6853}
6854
6855- (void)setLaunchDelay:(double)delay
6856{
6857 launch_delay = delay;
6858}
6859
6860- (NSArray*)crew
6861{
6862 return crew;
6863}
6864
6865- (void)setCrew:(NSArray*)crewArray
6866{
6867 if ([self isExplicitlyUnpiloted]) {
6868 // unpiloted ships cannot have crew
6869 // but may have crew before isExplicitlyUnpiloted set, so force *that* to clear too
6870 [crew autorelease];
6871 crew = nil;
6872 return;
6873 }
6874 // do not set to hulk here when crew is nil (or 0). Some things like missiles have no crew.
6875 [crew autorelease];
6876 crew = [crewArray copy];
6877}
6878
6879- (void)setSingleCrewWithRole:(NSString*)crewRole
6880{
6881 if (![self isUnpiloted]) {
6882 OOCharacter* crewMember = [OOCharacter randomCharacterWithRole:crewRole
6884 [self setCrew:[NSArray arrayWithObject:crewMember]];
6885 }
6886}
6887
6889{
6890 if (crew == nil) {
6891 return nil;
6892 }
6893 OOCharacter* crewMember = nil;
6894 NSMutableArray* result = [NSMutableArray arrayWithCapacity:4];
6895 foreach (crewMember, crew) {
6896 NSDictionary* crewDict = [crewMember infoForScripting];
6897 [result addObject:crewDict];
6898 }
6899 return result;
6900}
6901
6902- (void)setStateMachine:(NSString*)smName
6903{
6904 [self setAITo:smName];
6905}
6906
6907- (void)setAI:(AI*)ai
6908{
6909 [ai retain];
6910 if (shipAI) {
6912 [shipAI autorelease];
6913 }
6914 shipAI = ai;
6915}
6916
6918{
6919 return shipAI;
6920}
6921
6923{
6924 return [[self shipInfoDictionary] oo_fuzzyBooleanForKey:@"auto_ai" defaultValue:YES];
6925}
6926
6928{
6929 return [[[self getAI] name] isEqualToString:@"nullAI.plist"];
6930}
6931
6933{
6934 return [[self shipInfoDictionary] oo_fuzzyBooleanForKey:@"auto_weapons" defaultValue:NO];
6935}
6936
6937- (void)setShipScript:(NSString*)script_name
6938{
6939 NSMutableDictionary* properties = nil;
6940 NSArray* actions = nil;
6941
6942 properties = [NSMutableDictionary dictionary];
6943 [properties setObject:self forKey:@"ship"];
6944
6945 [script autorelease];
6946 script = [OOScript jsScriptFromFileNamed:script_name properties:properties];
6947
6948 if (script == nil) {
6949 actions = [shipinfoDictionary oo_arrayForKey:@"launch_actions"];
6950 if (actions) {
6951 OOStandardsDeprecated([NSString stringWithFormat:@"The launch_actions ship key is deprecated on %@.", [self displayName]]);
6952 if (!OOEnforceStandards()) {
6953 [properties setObject:actions forKey:@"legacy_launchActions"];
6954 }
6955 }
6956
6957 actions = [shipinfoDictionary oo_arrayForKey:@"script_actions"];
6958 if (actions) {
6959 OOStandardsDeprecated([NSString stringWithFormat:@"The script_actions ship key is deprecated on %@.", [self displayName]]);
6960 if (!OOEnforceStandards()) {
6961 [properties setObject:actions forKey:@"legacy_scriptActions"];
6962 }
6963 }
6964
6965 actions = [shipinfoDictionary oo_arrayForKey:@"death_actions"];
6966 if (actions) {
6967 OOStandardsDeprecated([NSString stringWithFormat:@"The death_actions ship key is deprecated on %@.", [self displayName]]);
6968 if (!OOEnforceStandards()) {
6969 [properties setObject:actions forKey:@"legacy_deathActions"];
6970 }
6971 }
6972
6973 actions = [shipinfoDictionary oo_arrayForKey:@"setup_actions"];
6974 if (actions) {
6975 OOStandardsDeprecated([NSString stringWithFormat:@"The setup_actions ship key is deprecated on %@.", [self displayName]]);
6976 if (!OOEnforceStandards()) {
6977 [properties setObject:actions forKey:@"legacy_setupActions"];
6978 }
6979 }
6980
6981 script = [OOScript jsScriptFromFileNamed:@"oolite-default-ship-script.js"
6982 properties:properties];
6983 }
6984 [script retain];
6985}
6986
6988{
6989 return frustration;
6990}
6991
6993{
6994 return fuel;
6995}
6996
6997- (void)setFuel:(OOFuelQuantity)amount
6998{
6999 if (amount > [self fuelCapacity])
7000 amount = [self fuelCapacity];
7001
7002 fuel = amount;
7003}
7004
7006{
7007 // FIXME: shipdata.plist can allow greater fuel quantities (without extending hyperspace range). Need some consistency here.
7008 return PLAYER_MAX_FUEL;
7009}
7010
7012{
7013 GLfloat rate = 1.0; // Standard (& strict play) charge rate.
7014
7015#if MASS_DEPENDENT_FUEL_PRICES
7016
7017 if (EXPECT(PLAYER != nil && mass > 0 && mass != [PLAYER baseMass])) {
7018 rate = calcFuelChargeRate(mass);
7019 }
7020
7021 OOLog(@"fuelPrices", @"\"%@\" fuel charge rate: %.2f (mass ratio: %.2f/%.2f)", [self shipDataKey], rate, mass, [PLAYER baseMass]);
7022#endif
7023
7024 return rate;
7025}
7026
7027- (void)applySticks:(double)delta_t
7028{
7029
7030 double rate1 = 2.0 * delta_t; // roll
7031 double rate2 = 4.0 * delta_t; // pitch
7032 double rate3 = 4.0 * delta_t; // yaw
7033
7034 if (((stick_roll > 0.0) && (flightRoll < 0.0)) || ((stick_roll < 0.0) && (flightRoll > 0.0)))
7035 rate1 *= 4.0; // much faster correction
7036 if (((stick_pitch > 0.0) && (flightPitch < 0.0)) || ((stick_pitch < 0.0) && (flightPitch > 0.0)))
7037 rate2 *= 4.0; // much faster correction
7038 if (((stick_yaw > 0.0) && (flightYaw < 0.0)) || ((stick_yaw < 0.0) && (flightYaw > 0.0)))
7039 rate3 *= 4.0; // much faster correction
7040
7042 if (stick_roll == 0.0)
7043 rate1 *= 2.0; // faster correction
7044 if (stick_pitch == 0.0)
7045 rate2 *= 2.0; // faster correction
7046 if (stick_yaw == 0.0)
7047 rate3 *= 2.0; // faster correction
7048 }
7049
7050 // apply stick movement limits
7051 if (flightRoll < stick_roll - rate1) {
7052 flightRoll = flightRoll + rate1;
7053 } else if (flightRoll > stick_roll + rate1) {
7054 flightRoll = flightRoll - rate1;
7055 } else {
7057 }
7058
7059 if (flightPitch < stick_pitch - rate2) {
7060 flightPitch = flightPitch + rate2;
7061 } else if (flightPitch > stick_pitch + rate2) {
7062 flightPitch = flightPitch - rate2;
7063 } else {
7065 }
7066
7067 if (flightYaw < stick_yaw - rate3) {
7068 flightYaw = flightYaw + rate3;
7069 } else if (flightYaw > stick_yaw + rate3) {
7070 flightYaw = flightYaw - rate3;
7071 } else {
7073 }
7074}
7075
7076- (void)setRoll:(double)amount
7077{
7078 flightRoll = amount * M_PI / 2.0;
7079}
7080
7081- (void)setRawRoll:(double)amount
7082{
7083 flightRoll = amount;
7084}
7085
7086- (void)setPitch:(double)amount
7087{
7088 flightPitch = amount * M_PI / 2.0;
7089}
7090
7091- (void)setYaw:(double)amount
7092{
7093 flightYaw = amount * M_PI / 2.0;
7094}
7095
7096- (void)setThrust:(double)amount
7097{
7098 thrust = amount;
7099}
7100
7101- (void)setThrustForDemo:(float)factor
7102{
7103 flightSpeed = factor * maxFlightSpeed;
7104}
7105
7106- (void)setBounty:(OOCreditsQuantity)amount
7107{
7108 [self setBounty:amount withReason:kOOLegalStatusReasonUnknown];
7109}
7110
7111- (void)setBounty:(OOCreditsQuantity)amount withReason:(OOLegalStatusReason)reason
7112{
7113 if ([self isSubEntity]) {
7114 [[self parentEntity] setBounty:amount withReason:reason];
7115 } else {
7116 if ((scanClass == CLASS_THARGOID || scanClass == CLASS_STATION) && reason != kOOLegalStatusReasonSetup && reason != kOOLegalStatusReasonByScript) {
7117 return; // no standard bounties for Thargoids / Stations
7118 }
7119 if (scanClass == CLASS_POLICE && amount != 0) {
7120 return; // police never have bounties
7121 }
7122 NSString* nReason = OOStringFromLegalStatusReason(reason);
7123 [self setBounty:amount withReasonAsString:nReason];
7124 }
7125}
7126
7127- (void)setBounty:(OOCreditsQuantity)amount withReasonAsString:(NSString*)reason
7128{
7129 if ([self isSubEntity]) {
7130 [[self parentEntity] setBounty:amount withReasonAsString:reason];
7131 } else {
7132 JSContext* context = OOJSAcquireContext();
7133
7134 OOJSVal amountVal = OOJSValueFromDouble(context, (int)amount - (int)bounty);
7135
7136 bounty = amount; // can't set the new bounty until the size of the change is known
7137
7138 OOJSVal reasonVal = OOJSValueFromNativeObject(context, reason);
7139
7140 ShipScriptEvent(context, self, "shipBountyChanged", amountVal, reasonVal);
7141
7142 OOJSRelinquishContext(context);
7143 }
7144}
7145
7147{
7148 if ([self isSubEntity]) {
7149 return [[self parentEntity] bounty];
7150 } else {
7151 return bounty;
7152 }
7153}
7154
7156{
7157 if (scanClass == CLASS_THARGOID)
7158 return 5 * collision_radius;
7159 if (scanClass == CLASS_ROCK)
7160 return 0;
7161 return (int)[self bounty];
7162}
7163
7164- (void)setCommodity:(OOCommodityType)co_type andAmount:(OOCargoQuantity)co_amount
7165{
7166 if (co_type != nil) {
7167 /* The tmp variable is needed as scoopUp can cause the method
7168 * to be passed a reference to self.commodity_type, so DESTROY
7169 * then copying the parameter segfaults */
7170 NSString* tmp = [co_type copy];
7172 commodity_type = tmp;
7173 commodity_amount = co_amount;
7174 }
7175}
7176
7177- (void)setCommodityForPod:(OOCommodityType)co_type andAmount:(OOCargoQuantity)co_amount
7178{
7179 // can be nil for pods
7180 if (co_type == nil) {
7182 commodity_amount = 0;
7183 return;
7184 }
7185 // pod content should never be greater than 1 ton or this will give cargo counting problems elsewhere in the code.
7186 // so do first a mass check for cargo added by script/plist.
7187 OOMassUnit unit = [[UNIVERSE commodityMarket] massUnitForGood:co_type];
7188 if (unit == UNITS_TONS && co_amount > 1)
7189 co_amount = 1;
7190 else if (unit == UNITS_KILOGRAMS && co_amount > 1000)
7191 co_amount = 1000;
7192 else if (unit == UNITS_GRAMS && co_amount > 1000000)
7193 co_amount = 1000000;
7194 [self setCommodity:co_type andAmount:co_amount];
7195}
7196
7201
7206
7211
7212- (void)setMaxAvailableCargoSpace:(OOCargoQuantity)new
7213{
7215}
7216
7218{
7219 // OOCargoQuantity is unsigned, we need to check for underflows.
7221 return 0;
7222 return [self maxAvailableCargoSpace] - [self cargoQuantityOnBoard];
7223}
7224
7226{
7227 NSUInteger result = [[self cargo] count];
7228 NSAssert(result < UINT32_MAX, @"Cargo quantity out of bounds.");
7229 return (OOCargoQuantity)result;
7230}
7231
7233{
7234 return cargo_type;
7235}
7236
7237/* Note: this array probably contains some template cargo pods. Do not
7238 * pass it to Javascript without reifying them first. */
7239- (NSMutableArray*)cargo
7240{
7241 return cargo;
7242}
7243
7245{
7246 NSMutableArray* list = [NSMutableArray array];
7247
7248 OOCommodityType good = nil;
7249 NSArray* goods = [[UNIVERSE commodityMarket] goods];
7250 NSUInteger i, j, commodityCount = [goods count];
7251 OOCargoQuantity quantityInHold[commodityCount];
7252
7253 for (i = 0; i < commodityCount; i++) {
7254 quantityInHold[i] = 0;
7255 }
7256 for (i = 0; i < [cargo count]; i++) {
7257 ShipEntity* container = [cargo objectAtIndex:i];
7258 j = [goods indexOfObject:[container commodityType]];
7259 quantityInHold[j] += [container commodityAmount];
7260 }
7261
7262 for (i = 0; i < commodityCount; i++) {
7263 if (quantityInHold[i] > 0) {
7264 NSMutableDictionary* commodity = [NSMutableDictionary dictionaryWithCapacity:4];
7265 good = [goods objectAtIndex:i];
7266 // commodity, quantity - keep consistency between .manifest and .contracts
7267 [commodity setObject:good forKey:@"commodity"];
7268 [commodity setObject:[NSNumber numberWithUnsignedInt:quantityInHold[i]] forKey:@"quantity"];
7269 [commodity setObject:[[UNIVERSE commodityMarket] nameForGood:good] forKey:@"displayName"];
7270 [commodity setObject:DisplayStringForMassUnitForCommodity(good) forKey:@"unit"];
7271 [list addObject:commodity];
7272 }
7273 }
7274
7275 return [[list copy] autorelease]; // return an immutable copy
7276}
7277
7278- (void)setCargo:(NSArray*)some_cargo
7279{
7280 [cargo removeAllObjects];
7281 [cargo addObjectsFromArray:some_cargo];
7282}
7283
7284- (BOOL)addCargo:(NSArray*)some_cargo
7285{
7286 if ([cargo count] + [some_cargo count] > [self maxAvailableCargoSpace]) {
7287 return NO;
7288 } else {
7289 [cargo addObjectsFromArray:some_cargo];
7290 return YES;
7291 }
7292}
7293
7294- (BOOL)removeCargo:(OOCommodityType)commodity amount:(OOCargoQuantity)amount
7295{
7296 OOCargoQuantity found = 0;
7297 ShipEntity* pod = nil;
7298 foreach (pod, cargo) {
7299 if ([[pod commodityType] isEqualToString:commodity]) {
7300 found++;
7301 }
7302 }
7303 if (found < amount) {
7304 // don't remove any if there aren't enough to remove the full amount
7305 return NO;
7306 }
7307
7308 NSUInteger i = [cargo count] - 1;
7309 // iterate downwards to be safe removing during iteration
7310 while (amount > 0) {
7311 if ([[[cargo objectAtIndex:i] commodityType] isEqualToString:commodity]) {
7312 amount--;
7313 [cargo removeObjectAtIndex:i];
7314 }
7315 // check above means array index can't underflow here
7316 i--;
7317 }
7318
7319 return YES;
7320}
7321
7323{
7324 return hasScoopMessage;
7325}
7326
7328{
7329 return cargo_flag;
7330}
7331
7332- (void)setCargoFlag:(OOCargoFlag)flag
7333{
7334 if (cargo_flag != flag) {
7335 cargo_flag = flag;
7336 NSArray* newCargo = nil;
7337 unsigned num = 0;
7338 if (likely_cargo > 0) {
7339 num = likely_cargo * (0.5 + randf());
7340 if (num > [self maxAvailableCargoSpace]) {
7341 num = [self maxAvailableCargoSpace];
7342 }
7343 } else {
7344 num = [self maxAvailableCargoSpace];
7345 }
7346 if (num > 200) {
7347 num = 200;
7348 /* no core NPC ship carries this much when generated (the
7349 * Anaconda could, but doesn't): let's not waste time generating
7350 * thousands of pods - even if they are semi-virtual - for some
7351 * massive OXP ship */
7352 }
7353 if (num > 0) {
7354 switch (cargo_flag) {
7356 newCargo = [UNIVERSE getContainersOfCommodity:[shipinfoDictionary oo_stringForKey:@"cargo_carried"] how_much:num];
7357 break;
7359 newCargo = [UNIVERSE getContainersOfGoods:num scarce:NO legal:YES];
7360 break;
7362 newCargo = [UNIVERSE getContainersOfGoods:num scarce:YES legal:YES];
7363 break;
7365 newCargo = [UNIVERSE getContainersOfCommodity:@"Narcotics" how_much:num];
7366 break;
7368 newCargo = [UNIVERSE getContainersOfGoods:num scarce:YES legal:NO];
7369 break;
7370 case CARGO_FLAG_PIRATE:
7371 newCargo = [UNIVERSE getContainersOfGoods:(Ranrot() % (1 + num / 2)) scarce:YES legal:NO];
7372 break;
7374 // TODO: allow passengers to survive
7375 case CARGO_FLAG_NONE:
7376 default:
7377 break;
7378 }
7379 }
7380 [self setCargo:newCargo];
7381 }
7382}
7383
7384- (void)setSpeed:(double)amount
7385{
7386 flightSpeed = amount;
7387}
7388
7389- (void)setDesiredSpeed:(double)amount
7390{
7391 desired_speed = amount;
7392}
7393
7395{
7396 return desired_speed;
7397}
7398
7400{
7401 return desired_range;
7402}
7403
7404- (void)setDesiredRange:(double)amount
7405{
7406 desired_range = amount;
7407}
7408
7410{
7411 return cruiseSpeed;
7412}
7413
7414- (void)increase_flight_speed:(double)delta
7415{
7416 double factor = 1.0;
7418 factor = [self afterburnerFactor];
7419
7420 if (flightSpeed < maxFlightSpeed * factor)
7421 flightSpeed += delta * factor;
7422 else
7423 flightSpeed = maxFlightSpeed * factor;
7424}
7425
7426- (void)decrease_flight_speed:(double)delta
7427{
7428 double factor = 1.0;
7430 factor = MIN_HYPERSPEED_FACTOR;
7431 }
7432
7433 if (flightSpeed > factor * delta) {
7434 flightSpeed -= factor * delta;
7435 } else {
7436 flightSpeed = 0;
7437 }
7438}
7439
7440- (void)increase_flight_roll:(double)delta
7441{
7442 flightRoll += delta;
7445 else if (flightRoll < -max_flight_roll)
7447}
7448
7449- (void)decrease_flight_roll:(double)delta
7450{
7451 flightRoll -= delta;
7454 else if (flightRoll < -max_flight_roll)
7456}
7457
7458- (void)increase_flight_pitch:(double)delta
7459{
7460 flightPitch += delta;
7463 else if (flightPitch < -max_flight_pitch)
7465}
7466
7467- (void)decrease_flight_pitch:(double)delta
7468{
7469 flightPitch -= delta;
7472 else if (flightPitch < -max_flight_pitch)
7474}
7475
7476- (void)increase_flight_yaw:(double)delta
7477{
7478 flightYaw += delta;
7481 else if (flightYaw < -max_flight_yaw)
7483}
7484
7485- (void)decrease_flight_yaw:(double)delta
7486{
7487 flightYaw -= delta;
7490 else if (flightYaw < -max_flight_yaw)
7492}
7493
7494- (GLfloat)flightRoll
7495{
7496 return flightRoll;
7497}
7498
7499- (GLfloat)flightPitch
7500{
7501 return flightPitch;
7502}
7503
7504- (GLfloat)flightYaw
7505{
7506 return flightYaw;
7507}
7508
7509- (GLfloat)flightSpeed
7510{
7511 return flightSpeed;
7512}
7513
7515{
7516 return max_flight_pitch;
7517}
7518
7520{
7521 return maxFlightSpeed;
7522}
7523
7525{
7526 return max_flight_roll;
7527}
7528
7530{
7531 return max_flight_yaw;
7532}
7533
7534- (void)setMaxFlightPitch:(GLfloat)new
7535{
7536 max_flight_pitch = new;
7537}
7538
7539- (void)setMaxFlightSpeed:(GLfloat)new
7540{
7541 maxFlightSpeed = new;
7542}
7543
7544- (void)setMaxFlightRoll:(GLfloat)new
7545{
7546 max_flight_roll = new;
7547}
7548
7549- (void)setMaxFlightYaw:(GLfloat)new
7550{
7551 max_flight_yaw = new;
7552}
7553
7554- (GLfloat)speedFactor
7555{
7556 if (maxFlightSpeed <= 0.0)
7557 return 0.0;
7558 return flightSpeed / maxFlightSpeed;
7559}
7560
7561- (GLfloat)temperature
7562{
7563 return ship_temperature;
7564}
7565
7566- (void)setTemperature:(GLfloat)value
7567{
7568 ship_temperature = value;
7569}
7570
7572{
7573 return [self randomEjectaTemperatureWithMaxFactor:0.99f];
7574}
7575
7576- (float)randomEjectaTemperatureWithMaxFactor:(float)factor
7577{
7578 const float kRange = 0.02f;
7579 factor -= kRange;
7580
7581 float parentTemp = [self temperature];
7582 float adjusted = parentTemp * (bellf(5) * (kRange * 2.0f) - kRange + factor);
7583 if (adjusted > SHIP_MAX_CABIN_TEMP) {
7584 adjusted = SHIP_MAX_CABIN_TEMP;
7585 }
7586
7587 // Interpolate so that result == parentTemp when parentTemp is SHIP_MIN_CABIN_TEMP
7588 float interp = OOClamp_0_1_f((parentTemp - SHIP_MIN_CABIN_TEMP) / (SHIP_MAX_CABIN_TEMP - SHIP_MIN_CABIN_TEMP));
7589
7590 return OOLerp(SHIP_MIN_CABIN_TEMP, adjusted, interp);
7591}
7592
7594{
7595 return _heatInsulation;
7596}
7597
7598- (void)setHeatInsulation:(GLfloat)value
7599{
7600 _heatInsulation = value;
7601}
7602
7604{
7605 return (int)(100 - (100 * energy / maxEnergy));
7606}
7607
7608- (void)dealEnergyDamage:(GLfloat)baseDamage atRange:(GLfloat)range withBias:(GLfloat)velocityBias
7609{
7610 // this is limited to the player's scanner range
7611 GLfloat maxRange = fmin(range * sqrt(baseDamage), SCANNER_MAX_RANGE);
7612
7613 OOLog(@"missile.damage.calc", @"Range: %f | Damage: %f | MaxRange: %f", range, baseDamage, maxRange);
7614
7615 NSArray* targets = [UNIVERSE entitiesWithinRange:maxRange ofEntity:self];
7616 if ([targets count] > 0) {
7617 unsigned i;
7618 for (i = 0; i < [targets count]; i++) {
7619 Entity* e2 = [targets objectAtIndex:i];
7620 Vector p2 = [self vectorTo:e2];
7621 double ecr = [e2 collisionRadius];
7622 double d = (magnitude(p2) - ecr) / range;
7623 // base damage within defined range, inverse-square falloff outside
7624 double localDamage = baseDamage;
7625 OOLog(@"missile.damage.calc", @"Base damage: %f", baseDamage);
7626 if (velocityBias > 0) {
7627 Vector v2 = vector_subtract([self velocity], [e2 velocity]);
7628 double vSign = dot_product(vector_normal([self velocity]), vector_normal(p2));
7629 // vSign should always be positive for the missile's actual target
7630 // but might be negative for other nearby ships which are
7631 // actually moving further away from the missile
7632 // double vMag = vSign > 0.0 ? magnitude(v2) : -magnitude(v2);
7633 double vMag = vSign * magnitude(v2);
7634 if (vMag > 1000.0) {
7635 vMag = 1000.0;
7636 // cap effective closing speed to 1.0LM or injector-collisions can still do
7637 // ridiculous damage
7638 }
7639
7640 localDamage += vMag * velocityBias;
7641 OOLog(@"missile.damage.calc", @"Velocity magnitude + sign: %f , %f", magnitude(v2), vSign);
7642 OOLog(@"missile.damage.calc", @"Velocity magnitude factor: %f", vMag);
7643 OOLog(@"missile.damage.calc", @"Velocity corrected damage: %f", localDamage);
7644 }
7645 double damage = (d > 1) ? localDamage / (d * d) : localDamage;
7646 OOLog(@"missile.damage.calc", @"%f at range %f (d=%f)", damage, magnitude(p2) - ecr, d);
7647 if (damage > 0.0) {
7648 if ([self owner]) {
7650 } else {
7652 }
7653 }
7654 }
7655 }
7656
7657 /* the actual damage can't go more than S_M_R, so cap the range
7658 * for exploding purposes so that the visual appearance isn't
7659 * larger than that */
7660 if (range > SCANNER_MAX_RANGE / 4.0) {
7661 range = SCANNER_MAX_RANGE / 4.0;
7662 }
7663 // and a visual sign of the explosion
7664 // "fireball" explosion effect
7665 NSDictionary* explosion = [UNIVERSE explosionSetting:@"oolite-default-ship-explosion"];
7666 [UNIVERSE addEntity:[OOExplosionCloudEntity explosionCloudFromEntity:self withSize:range * 3.0 andSettings:explosion]];
7667}
7668
7669// dealEnergyDamage preferred
7670// Exposed to AI
7672{
7673 OOStandardsDeprecated([NSString stringWithFormat:@"dealEnergyDamageWithinDesiredRange is deprecated for %@", self]);
7674 // not over scannerRange
7675 NSArray* targets = [UNIVERSE entitiesWithinRange:(desired_range < SCANNER_MAX_RANGE ? desired_range : SCANNER_MAX_RANGE) ofEntity:self];
7676 if ([targets count] > 0) {
7677 unsigned i;
7678 for (i = 0; i < [targets count]; i++) {
7679 Entity* e2 = [targets objectAtIndex:i];
7680 Vector p2 = [self vectorTo:e2];
7681 double ecr = [e2 collisionRadius];
7682 double d = (magnitude(p2) - ecr) * 2.6; // 2.6 is a correction constant to stay in limits of the old code.
7683 double damage = (d > 0) ? weapon_damage * desired_range / (d * d) : weapon_damage;
7685 }
7686 }
7687}
7688
7689- (void)dealMomentumWithinDesiredRange:(double)amount
7690{
7691 NSArray* targets = [UNIVERSE entitiesWithinRange:desired_range ofEntity:self];
7692 if ([targets count] > 0) {
7693 unsigned i;
7694 for (i = 0; i < [targets count]; i++) {
7695 ShipEntity* e2 = (ShipEntity*)[targets objectAtIndex:i];
7696 if ([e2 isShip] && [e2 isInSpace]) {
7697 Vector p2 = [self vectorTo:e2];
7698 double ecr = [e2 collisionRadius];
7699 double d2 = magnitude2(p2) - ecr * ecr;
7700 // limit momentum transfer to relatively sensible levels
7701 if (d2 < 0.1) {
7702 d2 = 0.1;
7703 }
7704 double moment = amount * desired_range / d2;
7705 [e2 addImpactMoment:vector_normal(p2) fraction:moment];
7706 }
7707 }
7708 }
7709}
7710
7711- (BOOL)isHulk
7712{
7713 return isHulk;
7714}
7715
7716- (void)setHulk:(BOOL)isNowHulk
7717{
7718 if (![self isSubEntity]) {
7719 isHulk = isNowHulk;
7720 }
7721}
7722
7723- (void)noteTakingDamage:(double)amount from:(Entity*)entity type:(OOShipDamageType)type
7724{
7725 if (amount < 0 || (amount == 0 && [[UNIVERSE gameController] isGamePaused]))
7726 return;
7727
7728 JSContext* context = OOJSAcquireContext();
7729
7730 OOJSVal amountVal = OOJSValueFromDouble(context, amount);
7731 OOJSVal entityVal = OOJSValueFromNativeObject(context, entity);
7732 OOJSVal typeVal = OOJSValueFromShipDamageType(context, type);
7733
7734 ShipScriptEvent(context, self, "shipTakingDamage", amountVal, entityVal, typeVal);
7735 OOJSRelinquishContext(context);
7736
7737 if ([entity isShip]) {
7738 // ShipEntity* attacker = (ShipEntity *)entity;
7739 if ([self hasHostileTarget] && accuracy >= COMBAT_AI_IS_SMART && (randf() * 10.0 < accuracy || desired_speed < 0.5 * maxFlightSpeed) && behaviour != BEHAVIOUR_EVASIVE_ACTION && behaviour != BEHAVIOUR_FLEE_EVASIVE_ACTION && behaviour != BEHAVIOUR_SCRIPTED_ATTACK_AI) {
7740 if (behaviour == BEHAVIOUR_FLEE_TARGET) {
7741 // jink should be sufficient to avoid being hit most of the time
7742 // if not, this will make a sharp turn and then select a new jink position
7743 behaviour = BEHAVIOUR_FLEE_EVASIVE_ACTION;
7744 } else {
7745 behaviour = BEHAVIOUR_EVASIVE_ACTION;
7746 }
7747 frustration = 0.0;
7748 }
7749 }
7750}
7751
7752- (void)noteKilledBy:(Entity*)whom damageType:(OOShipDamageType)type
7753{
7754 if ([self status] == STATUS_DEAD)
7755 return;
7756
7757 [PLAYER setScriptTarget:self];
7758
7759 JSContext* context = OOJSAcquireContext();
7760
7761 OOJSVal whomVal = OOJSValueFromNativeObject(context, whom);
7762 OOJSVal typeVal = OOJSValueFromShipDamageType(context, type);
7763 OOEntityStatus originalStatus = [self status];
7764 [self setStatus:STATUS_DEAD];
7765
7766 ShipScriptEvent(context, self, "shipDied", whomVal, typeVal); // Frees whomVal and typeVal.
7767 if ([whom isShip]) {
7768 OOJSVal selfVal = OOJSValueFromNativeObject(context, self);
7769 typeVal = OOJSValueFromShipDamageType(context, type);
7770 ShipScriptEvent(context, (ShipEntity*)whom, "shipKilledOther", selfVal, typeVal);
7771 }
7772
7773 [self setStatus:originalStatus];
7774 OOJSRelinquishContext(context);
7775}
7776
7777- (void)getDestroyedBy:(Entity*)whom damageType:(OOShipDamageType)type
7778{
7779 [self noteKilledBy:whom damageType:type];
7780 [self abortDocking];
7781 [self becomeExplosion];
7782}
7783
7784- (void)rescaleBy:(GLfloat)factor
7785{
7786 [self rescaleBy:factor writeToCache:YES];
7787}
7788
7789- (void)rescaleBy:(GLfloat)factor writeToCache:(BOOL)writeToCache
7790{
7791 _scaleFactor *= factor;
7792 OOMesh* mesh = nil;
7793
7794 NSDictionary* shipDict = [self shipInfoDictionary];
7795 NSString* modelName = [shipDict oo_stringForKey:@"model"];
7796 if (modelName != nil) {
7797 mesh = [OOMesh meshWithName:modelName
7798 cacheKey:[NSString stringWithFormat:@"%@-%.3f", _shipKey, _scaleFactor]
7799 materialDictionary:[shipDict oo_dictionaryForKey:@"materials"]
7800 shadersDictionary:[shipDict oo_dictionaryForKey:@"shaders"]
7801 smooth:[shipDict oo_boolForKey:@"smooth" defaultValue:NO]
7802 shaderMacros:OODefaultShipShaderMacros()
7804 scaleFactor:factor
7805 cacheWriteable:writeToCache];
7806
7807 if (mesh == nil)
7808 return;
7809 [self setMesh:mesh];
7810 }
7811
7812 // rescale subentities
7814 foreach (se, [self subEntities]) {
7815 [se setPosition:HPvector_multiply_scalar([se position], factor)];
7816 [se rescaleBy:factor writeToCache:writeToCache];
7817 }
7818
7819 // rescale mass
7820 mass *= factor * factor * factor;
7821}
7822
7824{
7825 HPVector xposition = position;
7826 NSUInteger i;
7827 Vector v;
7828 Quaternion q;
7829 int speed_low = 200;
7830
7831 NSArray* jetsam = nil; // this will contain the stuff to get thrown out
7832 unsigned cargo_chance = 70;
7833 jetsam = [NSArray arrayWithArray:cargo]; // what the ship is carrying
7834 [cargo removeAllObjects]; // dispense with it!
7835 unsigned limit = 15;
7836 // Throw out cargo
7837 NSUInteger n_jetsam = [jetsam count];
7838
7839 for (i = 0; i < n_jetsam; i++) {
7840 if (Ranrot() % 100 < cargo_chance) // chance of any given piece of cargo surviving decompression
7841 {
7842 // a higher chance of getting at least a couple of bits of cargo out
7843 if (cargo_chance > 10) {
7844 if (EXPECT_NOT([self isPlayer])) {
7845 cargo_chance -= 20;
7846 } else {
7847 cargo_chance -= 30;
7848 }
7849 }
7850 limit--;
7851 ShipEntity* cargoObj = [jetsam objectAtIndex:i];
7852 ShipEntity* container = [UNIVERSE reifyCargoPod:cargoObj];
7853 /* TODO: this debris position/velocity setting code is
7854 * duplicated - sometimes not very cleanly - all over the
7855 * place. Unify to a single function - CIM */
7856 HPVector rpos = xposition;
7858 rpos.x += rrand.x;
7859 rpos.y += rrand.y;
7860 rpos.z += rrand.z;
7861 rpos.x += (ranrot_rand() % 7) - 3;
7862 rpos.y += (ranrot_rand() % 7) - 3;
7863 rpos.z += (ranrot_rand() % 7) - 3;
7864 [container setPosition:rpos];
7865 v.x = 0.1 * ((ranrot_rand() % speed_low) - speed_low / 2);
7866 v.y = 0.1 * ((ranrot_rand() % speed_low) - speed_low / 2);
7867 v.z = 0.1 * ((ranrot_rand() % speed_low) - speed_low / 2);
7868 [container setVelocity:vector_add(v, [self velocity])];
7871
7873 [container setScanClass:CLASS_CARGO];
7874 [UNIVERSE addEntity:container]; // STATUS_IN_FLIGHT, AI state GLOBAL
7875
7876 AI* containerAI = [container getAI];
7877 if ([containerAI hasSuspendedStateMachines]) // check if new or recycled cargo.
7878 {
7880 [container setThrust:[container maxThrust]]; // restore old value. Was set to zero on previous scooping.
7881 [container setOwner:container];
7882 }
7883 }
7884 if (limit <= 0) {
7885 break; // even really big ships won't have too much cargo survive an explosion
7886 }
7887 }
7888}
7889
7890- (void)setIsWreckage:(BOOL)isw
7891{
7892 isWreckage = isw;
7893}
7894
7896{
7897 return _showDamage;
7898}
7899
7901{
7902
7903 // check if we're destroying a subentity
7904 ShipEntity* parent = [self parentEntity];
7905 if (parent != nil) {
7906 ShipEntity* this_ship = [self retain];
7907 HPVector this_pos = [self absolutePositionForSubentity];
7908
7909 // remove this ship from its parent's subentity list
7910 [parent subEntityDied:self];
7911 [UNIVERSE addEntity:this_ship];
7912 [this_ship setPosition:this_pos];
7913 [this_ship release];
7914 if ([parent isPlayer]) {
7915 // make the parent ship less reliable.
7916 [(PlayerEntity*)parent adjustTradeInFactorBy:-PLAYER_SHIP_SUBENTITY_TRADE_IN_VALUE];
7917 }
7918 }
7919
7920 HPVector xposition = position;
7921 NSUInteger i;
7922 Vector v;
7923 Quaternion q;
7924 int speed_low = 200;
7925 GLfloat n_alloys = sqrtf(sqrtf(mass / 6000.0f));
7926 NSUInteger numAlloys = 0;
7927 BOOL canReleaseSubWreckage = isWreckage && ([UNIVERSE detailLevel] >= DETAIL_LEVEL_EXTRAS);
7928
7929 if ([self status] == STATUS_DEAD) {
7930 [UNIVERSE removeEntity:self];
7931 return;
7932 }
7933 [self setStatus:STATUS_DEAD];
7934
7935 @try {
7936 if ([self isThargoid] && [roleSet hasRole:@"thargoid-mothership"])
7938
7940 if (!isWreckage && mass > 500000.0f && randf() < 0.25f) // big!
7941 {
7942 // draw an expanding ring
7944 [ring setVelocity:vector_multiply_scalar([self velocity], 0.25f)];
7945 [UNIVERSE addEntity:ring];
7946 }
7947
7948 BOOL add_debris = (UNIVERSE->n_entities < 0.95 * UNIVERSE_MAX_ENTITIES) && ([UNIVERSE getTimeDelta] < 0.125); // FPS > 8
7949
7950 // There are several parts to explosions, show only the main
7951 // explosion effect if UNIVERSE is almost full.
7952
7953 if (add_debris) {
7954 if ([UNIVERSE reducedDetail]) {
7955 // Quick explosion effects for reduced detail mode
7956
7957 // 1. fast sparks
7958 [UNIVERSE addEntity:[OOSmallFragmentBurstEntity fragmentBurstFromEntity:self]];
7959 // 2. slow clouds
7960 [UNIVERSE addEntity:[OOBigFragmentBurstEntity fragmentBurstFromEntity:self]];
7961 // 3. flash
7962 [UNIVERSE addEntity:[OOFlashEffectEntity explosionFlashFromEntity:self]];
7963 /* This mode used to be the default for
7964 * cargo/munitions but this now must be explicitly
7965 * specified. */
7966 } else {
7967 NSString* explosionKey = @"oolite-default-ship-explosion";
7968 NSDictionary* explosion = nil;
7969 if (explosionType == nil) {
7970 explosion = [UNIVERSE explosionSetting:explosionKey];
7971 [UNIVERSE addEntity:[OOExplosionCloudEntity explosionCloudFromEntity:self withSettings:explosion]];
7972 // 3. flash
7973 [UNIVERSE addEntity:[OOFlashEffectEntity explosionFlashFromEntity:self]];
7974 }
7975 for (NSUInteger i = 0; i < [explosionType count]; i++) {
7976 explosionKey = [explosionType oo_stringAtIndex:i defaultValue:nil];
7977 if (explosionKey != nil) {
7978 // three special-case builtins
7979 if ([explosionKey isEqualToString:@"oolite-builtin-flash"]) {
7980 [UNIVERSE addEntity:[OOFlashEffectEntity explosionFlashFromEntity:self]];
7981 } else if ([explosionKey isEqualToString:@"oolite-builtin-slowcloud"]) {
7982 [UNIVERSE addEntity:[OOBigFragmentBurstEntity fragmentBurstFromEntity:self]];
7983 } else if ([explosionKey isEqualToString:@"oolite-builtin-fastspark"]) {
7984 [UNIVERSE addEntity:[OOSmallFragmentBurstEntity fragmentBurstFromEntity:self]];
7985 } else {
7986 explosion = [UNIVERSE explosionSetting:explosionKey];
7987 [UNIVERSE addEntity:[OOExplosionCloudEntity explosionCloudFromEntity:self withSettings:explosion]];
7988 }
7989 }
7990 }
7991 // "fireball" explosion effect
7992 }
7993 }
7994
7995 // If UNIVERSE is nearing limit for entities don't add to it!
7996 if (add_debris) {
7997 // we need to throw out cargo at this point.
7999
8000 // Throw out rocks and alloys to be scooped up
8001 if ([self hasRole:@"asteroid"] || [self isBoulder]) {
8002 if (!noRocks && (being_mined || randf() < 0.20)) {
8003 NSString* defaultRole = @"boulder";
8004 float defaultSpeed = 50.0;
8005 if ([self isBoulder]) {
8006 defaultRole = @"splinter";
8007 defaultSpeed = 20.0;
8008 if (likely_cargo == 0) {
8009 likely_cargo = 4; // compatibility with older boulders
8010 }
8011 } else if ([[self primaryAggressor] isPlayer]) {
8012 [PLAYER addRoleForMining];
8013 }
8014 NSUInteger n_rocks = 2 + (Ranrot() % (likely_cargo + 1));
8015
8016 NSString* debrisRole = [[self shipInfoDictionary] oo_stringForKey:@"debris_role" defaultValue:defaultRole];
8017 for (i = 0; i < n_rocks; i++) {
8018 ShipEntity* rock = [UNIVERSE newShipWithRole:debrisRole]; // retain count = 1
8019 if (rock) {
8020 float r_speed = [rock maxFlightSpeed] > 0 ? 2.0 * [rock maxFlightSpeed] : defaultSpeed;
8021 float cr = (collision_radius < rock->collision_radius) ? collision_radius : 2 * rock->collision_radius;
8022 v.x = ((randf() * r_speed) - r_speed / 2);
8023 v.y = ((randf() * r_speed) - r_speed / 2);
8024 v.z = ((randf() * r_speed) - r_speed / 2);
8025 [rock setVelocity:vector_add(v, [self velocity])];
8027 [rock setPosition:rpos];
8028
8030 [rock setOrientation:q];
8031
8033 if ([self isBoulder]) {
8034 [rock setScanClass:CLASS_CARGO];
8035 [rock setBounty:0 withReason:kOOLegalStatusReasonSetup];
8036 // only make the rock have minerals if something isn't already defined for the rock
8037 if ([[rock shipInfoDictionary] oo_stringForKey:@"cargo_carried"] == nil)
8038 [rock setCommodity:@"minerals" andAmount:1];
8039 } else {
8040 [rock setScanClass:CLASS_ROCK];
8041 [rock setIsBoulder:YES];
8042 }
8043 [UNIVERSE addEntity:rock]; // STATUS_IN_FLIGHT, AI state GLOBAL
8044 [rock release];
8045 }
8046 }
8047 }
8048 return;
8049 }
8050
8051 // throw out burning chunks of wreckage
8052 //
8053 if ((n_alloys && canFragment) || canReleaseSubWreckage) {
8054 NSUInteger n_wreckage = 0;
8055
8056 if (UNIVERSE->n_entities < 0.50 * UNIVERSE_MAX_ENTITIES) {
8057 // Create wreckage only when UNIVERSE is less than half full.
8058 // (condition set in r906 - was < 0.75 before) --Kaks 2011.10.17
8059 NSUInteger maxWrecks = 3;
8060 if (n_alloys == 0) {
8061 // must be sub-wreckage here
8062 n_wreckage = (mass > 600.0 && randf() < 0.2) ? 2 : 0;
8063 } else {
8064 n_wreckage = (n_alloys < maxWrecks) ? floorf(randf() * (n_alloys + 2)) : maxWrecks;
8065 }
8066 }
8067
8068 for (i = 0; i < n_wreckage; i++) {
8069 Vector r1 = [octree randomPoint];
8071 HPVector rpos = HPvector_add(vectorToHPVector(dir), xposition);
8072 GLfloat lifetime = 750.0 * randf() + 250.0 * i + 100.0;
8073 ShipEntity* wreck = [UNIVERSE addWreckageFrom:self withRole:@"wreckage" at:rpos scale:1.0 lifetime:lifetime / 2];
8074
8075 [wreck setVelocity:vector_add([wreck velocity], vector_multiply_scalar(vector_normal(dir), randf() * [wreck collisionRadius]))];
8076 }
8077 n_alloys = randf() * n_alloys;
8078 }
8079 }
8080
8081 if (!canFragment) {
8082 n_alloys = 0.0;
8083 }
8084 // If UNIVERSE is almost full, don't create more than 1 piece of scrap metal.
8085 else if (!add_debris) {
8086 n_alloys = (n_alloys > 1.0) ? 1.0 : 0.0;
8087 }
8088
8089 // now convert to uint
8090 numAlloys = floorf(n_alloys);
8091
8092 // Throw out scrap metal
8093 //
8094 for (i = 0; i < numAlloys; i++) {
8095 ShipEntity* plate = [UNIVERSE newShipWithRole:@"alloy"]; // retain count = 1
8096 if (plate) {
8097 HPVector rpos = xposition;
8099 rpos.x += rrand.x;
8100 rpos.y += rrand.y;
8101 rpos.z += rrand.z;
8102 rpos.x += (ranrot_rand() % 7) - 3;
8103 rpos.y += (ranrot_rand() % 7) - 3;
8104 rpos.z += (ranrot_rand() % 7) - 3;
8105 [plate setPosition:rpos];
8106 v.x = 0.1 * ((ranrot_rand() % speed_low) - speed_low / 2);
8107 v.y = 0.1 * ((ranrot_rand() % speed_low) - speed_low / 2);
8108 v.z = 0.1 * ((ranrot_rand() % speed_low) - speed_low / 2);
8109 [plate setVelocity:vector_add(v, [self velocity])];
8112
8114 [plate setScanClass:CLASS_CARGO];
8115 [plate setCommodity:@"alloys" andAmount:1];
8116 [UNIVERSE addEntity:plate]; // STATUS_IN_FLIGHT, AI state GLOBAL
8117
8118 [plate release];
8119 }
8120 }
8121 }
8122
8123 // Explode subentities.
8124 ShipEntity* se = nil;
8125 foreach (se, [self shipSubEntityEnumerator]) {
8126 [se setSuppressExplosion:suppressExplosion];
8128 }
8129 [self clearSubEntities];
8130
8131 // momentum from explosions
8132 if (!suppressExplosion) {
8134 [self dealMomentumWithinDesiredRange:0.125f * mass];
8135 }
8136
8137 if (self != PLAYER) // was if !isPlayer - but I think this may cause ghosts (Who's "I"? -- Ahruman)
8138 {
8139 if (isPlayer) {
8140#ifndef NDEBUG
8141 OOLog(@"becomeExplosion.suspectedGhost.confirm", @"%@", @"Ship spotted with isPlayer set when not actually the player.");
8142#endif
8143 isPlayer = NO;
8144 }
8145 }
8146 }
8147 @finally {
8148 if (self != PLAYER) {
8149 [UNIVERSE removeEntity:self];
8150 }
8151 }
8152}
8153
8154// Exposed to AI
8156{
8157 [UNIVERSE addEntity:[OOQuiriumCascadeEntity quiriumCascadeFromShip:self]];
8159 [self noteKilledBy:nil damageType:kOODamageTypeCascadeWeapon];
8160 [UNIVERSE removeEntity:self];
8161}
8162
8163// Exposed to AI
8165{
8166 // anyone further away than typical scanner range probably doesn't need to hear
8167 NSArray* targets = [UNIVERSE entitiesWithinRange:SCANNER_MAX_RANGE ofEntity:self];
8168 if ([targets count] > 0) {
8169 unsigned i;
8170 for (i = 0; i < [targets count]; i++) {
8171 Entity* e2 = [targets objectAtIndex:i];
8172 if ([e2 isShip]) {
8173 ShipEntity* se = (ShipEntity*)e2;
8174 [se setFoundTarget:self];
8175 [se reactToAIMessage:@"CASCADE_WEAPON_DETECTED" context:@"nearby Q-mine"];
8176 [se doScriptEvent:OOJSID("cascadeWeaponDetected") withArgument:self];
8177 }
8178 }
8179 }
8180}
8181
8182- (void)removeExhaust:(OOExhaustPlumeEntity*)exhaust
8183{
8184 [subEntities removeObject:exhaust];
8185 [exhaust setOwner:nil];
8186}
8187
8188- (void)removeFlasher:(OOFlasherEntity*)flasher
8189{
8190 [subEntities removeObject:flasher];
8191 [flasher setOwner:nil];
8192}
8193
8194- (void)subEntityDied:(ShipEntity*)sub
8195{
8196 if ([self subEntityTakingDamage] == sub)
8197 [self setSubEntityTakingDamage:nil];
8198
8199 [sub setOwner:nil];
8200 // TODO? Recalculating collision radius should increase collision testing efficiency,
8201 // but for most ship models the difference would be marginal. -- Kaks 20110429
8202 mass -= [sub mass]; // missing subents affect fuel charge rate, etc..
8203 [subEntities removeObject:sub];
8204}
8205
8206- (void)subEntityReallyDied:(ShipEntity*)sub
8207{
8208 if ([self subEntityTakingDamage] == sub)
8209 [self setSubEntityTakingDamage:nil];
8210
8211 if ([self hasSubEntity:sub]) {
8212 OOLogERR(@"shipEntity.bug.subEntityRetainUnderflow", @"Subentity of %@ died while still in subentity list! This is bad. Leaking subentity list to avoid crash. %@", self, @"This is an internal error, please report it.");
8213
8214 // Leak subentity list.
8215 subEntities = nil;
8216 }
8217}
8218
8219- (Vector)positionOffsetForAlignment:(NSString*)align
8220{
8221 NSString* padAlign = [NSString stringWithFormat:@"%@---", align];
8222 Vector result = kZeroVector;
8223 switch ([padAlign characterAtIndex:0]) {
8224 case (unichar)'c':
8225 case (unichar)'C':
8226 result.x = 0.5 * (boundingBox.min.x + boundingBox.max.x);
8227 break;
8228 case (unichar)'M':
8229 result.x = boundingBox.max.x;
8230 break;
8231 case (unichar)'m':
8232 result.x = boundingBox.min.x;
8233 break;
8234 }
8235 switch ([padAlign characterAtIndex:1]) {
8236 case (unichar)'c':
8237 case (unichar)'C':
8238 result.y = 0.5 * (boundingBox.min.y + boundingBox.max.y);
8239 break;
8240 case (unichar)'M':
8241 result.y = boundingBox.max.y;
8242 break;
8243 case (unichar)'m':
8244 result.y = boundingBox.min.y;
8245 break;
8246 }
8247 switch ([padAlign characterAtIndex:2]) {
8248 case (unichar)'c':
8249 case (unichar)'C':
8250 result.z = 0.5 * (boundingBox.min.z + boundingBox.max.z);
8251 break;
8252 case (unichar)'M':
8253 result.z = boundingBox.max.z;
8254 break;
8255 case (unichar)'m':
8256 result.z = boundingBox.min.z;
8257 break;
8258 }
8259 return result;
8260}
8261
8263{
8264 NSString* padAlign = [NSString stringWithFormat:@"%@---", align];
8268 BoundingBox arbb = [ship findBoundingBoxRelativeToPosition:kZeroHPVector i:i j:j k:k];
8269 Vector result = kZeroVector;
8270 switch ([padAlign characterAtIndex:0]) {
8271 case (unichar)'c':
8272 case (unichar)'C':
8273 result.x = 0.5 * (arbb.min.x + arbb.max.x);
8274 break;
8275 case (unichar)'M':
8276 result.x = arbb.max.x;
8277 break;
8278 case (unichar)'m':
8279 result.x = arbb.min.x;
8280 break;
8281 }
8282 switch ([padAlign characterAtIndex:1]) {
8283 case (unichar)'c':
8284 case (unichar)'C':
8285 result.y = 0.5 * (arbb.min.y + arbb.max.y);
8286 break;
8287 case (unichar)'M':
8288 result.y = arbb.max.y;
8289 break;
8290 case (unichar)'m':
8291 result.y = arbb.min.y;
8292 break;
8293 }
8294 switch ([padAlign characterAtIndex:2]) {
8295 case (unichar)'c':
8296 case (unichar)'C':
8297 result.z = 0.5 * (arbb.min.z + arbb.max.z);
8298 break;
8299 case (unichar)'M':
8300 result.z = arbb.max.z;
8301 break;
8302 case (unichar)'m':
8303 result.z = arbb.min.z;
8304 break;
8305 }
8306 return result;
8307}
8308
8309- (void)becomeLargeExplosion:(double)factor
8310{
8311
8312 if ([self status] == STATUS_DEAD)
8313 return;
8314 [self setStatus:STATUS_DEAD];
8315
8316 @try {
8317 // two parts to the explosion:
8318 // 1. fast sparks
8319 float how_many = factor;
8320 while (how_many > 0.5f) {
8321 [UNIVERSE addEntity:[OOSmallFragmentBurstEntity fragmentBurstFromEntity:self]];
8322 how_many -= 1.0f;
8323 }
8324 // 2. slow clouds
8325 how_many = factor;
8326 while (how_many > 0.5f) {
8327 [UNIVERSE addEntity:[OOBigFragmentBurstEntity fragmentBurstFromEntity:self]];
8328 how_many -= 1.0f;
8329 }
8330
8332
8333 ShipEntity* se = nil;
8334 foreach (se, [self shipSubEntityEnumerator]) {
8335 [se setSuppressExplosion:suppressExplosion];
8337 }
8338 [self clearSubEntities];
8339
8340 }
8341 @finally {
8342 if (!isPlayer)
8343 [UNIVERSE removeEntity:self];
8344 }
8345}
8346
8347- (void)collectBountyFor:(ShipEntity*)other
8348{
8349 if ([other isPolice]) // oops, we shot a copper!
8350 {
8351 [self markAsOffender:64 withReason:kOOLegalStatusReasonAttackedPolice];
8352 }
8353}
8354
8355- (NSComparisonResult)compareBeaconCodeWith:(Entity<OOBeaconEntity>*)other
8356{
8357 return [[self beaconCode] compare:[other beaconCode] options:NSCaseInsensitiveSearch];
8358}
8359
8360// for shaders, equivalent to 1.76's NPC laserHeatLevel
8362{
8363 float result = (weapon_recharge_rate - [self shotTime]) / weapon_recharge_rate;
8364 return OOClamp_0_1_f(result);
8365}
8366
8368{
8369 GLfloat result = weapon_temp / NPC_MAX_WEAPON_TEMP;
8370 return OOClamp_0_1_f(result);
8371}
8372
8374{
8375 GLfloat result = aft_weapon_temp / NPC_MAX_WEAPON_TEMP;
8376 return OOClamp_0_1_f(result);
8377}
8378
8380{
8381 GLfloat result = forward_weapon_temp / NPC_MAX_WEAPON_TEMP;
8382 if (isWeaponNone(forward_weapon_type)) { // must check subents
8383 OOWeaponType forward_weapon_real_type = nil;
8384 NSEnumerator* subEnum = [self shipSubEntityEnumerator];
8385 ShipEntity* se = nil;
8386 while (isWeaponNone(forward_weapon_real_type) && (se = [subEnum nextObject])) {
8388 forward_weapon_real_type = se->forward_weapon_type;
8390 }
8391 }
8392 }
8393 return OOClamp_0_1_f(result);
8394}
8395
8397{
8398 GLfloat result = port_weapon_temp / NPC_MAX_WEAPON_TEMP;
8399 return OOClamp_0_1_f(result);
8400}
8401
8403{
8404 GLfloat result = starboard_weapon_temp / NPC_MAX_WEAPON_TEMP;
8405 return OOClamp_0_1_f(result);
8406}
8407
8409{
8410 GLfloat result = (GLfloat)ship_temperature / (GLfloat)SHIP_MAX_CABIN_TEMP;
8411 return OOClamp_0_1_f(result);
8412}
8413
8415{
8417}
8418
8420{
8421 return entity_personality;
8422}
8423
8425{
8426 return entity_personality * 0x00010001;
8427}
8428
8429- (void)setEntityPersonalityInt:(uint16_t)value
8430{
8431 if (value <= ENTITY_PERSONALITY_MAX) {
8432 entity_personality = value;
8433 [[self mesh] rebindMaterials];
8434 }
8435}
8436
8437- (void)setSuppressExplosion:(BOOL)suppress
8438{
8439 suppressExplosion = !!suppress;
8440}
8441
8443{
8444 OOExhaustPlumeEntity* exEnt = nil;
8445
8446 foreach (exEnt, [self exhaustEnumerator]) {
8447 [exEnt resetPlume];
8448 }
8449}
8450
8451/*-----------------------------------------
8452
8453 AI piloting methods
8454
8455-----------------------------------------*/
8456
8458{
8459 Entity* scan;
8460 n_scanned_ships = 0;
8461 //
8462 scan = z_previous;
8463 while ((scan) && (scan->isShip == NO))
8464 scan = scan->z_previous; // skip non-ships
8465 GLfloat scannerRange2 = scannerRange * scannerRange;
8466 while ((scan) && (scan->position.z > position.z - scannerRange) && (n_scanned_ships < MAX_SCAN_NUMBER)) {
8467 // can't scan cloaked ships
8468 if (scan->isShip && ![(ShipEntity*)scan isCloaked] && [self isValidTarget:scan]) {
8469 distance2_scanned_ships[n_scanned_ships] = HPdistance2(position, scan->position);
8470 if (distance2_scanned_ships[n_scanned_ships] < scannerRange2)
8471 scanned_ships[n_scanned_ships++] = (ShipEntity*)scan;
8472 }
8473 scan = scan->z_previous;
8474 while ((scan) && (scan->isShip == NO))
8475 scan = scan->z_previous;
8476 }
8477 //
8478 scan = z_next;
8479 while ((scan) && (scan->isShip == NO))
8480 scan = scan->z_next; // skip non-ships
8481 while ((scan) && (scan->position.z < position.z + scannerRange) && (n_scanned_ships < MAX_SCAN_NUMBER)) {
8482 if (scan->isShip && ![(ShipEntity*)scan isCloaked] && [self isValidTarget:scan]) {
8483 distance2_scanned_ships[n_scanned_ships] = HPdistance2(position, scan->position);
8484 if (distance2_scanned_ships[n_scanned_ships] < scannerRange2)
8485 scanned_ships[n_scanned_ships++] = (ShipEntity*)scan;
8486 }
8487 scan = scan->z_next;
8488 while ((scan) && (scan->isShip == NO))
8489 scan = scan->z_next; // skip non-ships
8490 }
8491 //
8492 scanned_ships[n_scanned_ships] = nil; // terminate array
8493}
8494
8496{
8497 Entity* scan;
8498 n_scanned_ships = 0;
8499 //
8500 GLfloat scannerRange2 = scannerRange * scannerRange;
8501 scan = z_previous;
8502 while ((scan) && ((scan->isShip == NO) || (scan->scanClass == CLASS_ROCK) || (scan->scanClass == CLASS_CARGO))) {
8503 scan = scan->z_previous; // skip non-ships
8504 }
8505 while ((scan) && (scan->position.z > position.z - scannerRange) && (n_scanned_ships < MAX_SCAN_NUMBER)) {
8506 if (scan->isShip && ![(ShipEntity*)scan isCloaked]) {
8507 distance2_scanned_ships[n_scanned_ships] = HPdistance2(position, scan->position);
8508 if (distance2_scanned_ships[n_scanned_ships] < scannerRange2)
8509 scanned_ships[n_scanned_ships++] = (ShipEntity*)scan;
8510 }
8511 scan = scan->z_previous;
8512 while ((scan) && ((scan->isShip == NO) || (scan->scanClass == CLASS_ROCK) || (scan->scanClass == CLASS_CARGO))) {
8513 scan = scan->z_previous; // skip non-ships
8514 }
8515 }
8516 //
8517 scan = z_next;
8518 while ((scan) && ((scan->isShip == NO) || (scan->scanClass == CLASS_ROCK) || (scan->scanClass == CLASS_CARGO))) {
8519 scan = scan->z_next; // skip non-ships
8520 }
8521
8522 while ((scan) && (scan->position.z < position.z + scannerRange) && (n_scanned_ships < MAX_SCAN_NUMBER)) {
8523 if (scan->isShip && ![(ShipEntity*)scan isCloaked]) {
8524 distance2_scanned_ships[n_scanned_ships] = HPdistance2(position, scan->position);
8525 if (distance2_scanned_ships[n_scanned_ships] < scannerRange2)
8526 scanned_ships[n_scanned_ships++] = (ShipEntity*)scan;
8527 }
8528 scan = scan->z_next;
8529 while ((scan) && ((scan->isShip == NO) || (scan->scanClass == CLASS_ROCK) || (scan->scanClass == CLASS_CARGO))) {
8530 scan = scan->z_next; // skip non-ships
8531 }
8532 }
8533 //
8534 scanned_ships[n_scanned_ships] = nil; // terminate array
8535}
8536
8538{
8539 scanned_ships[n_scanned_ships] = nil; // terminate array
8540 return scanned_ships;
8541}
8542
8544{
8545 return n_scanned_ships;
8546}
8547
8549{
8551 if (result == nil || ![self isValidTarget:result]) {
8553 return nil;
8554 }
8555 return result;
8556}
8557
8558- (void)setFoundTarget:(Entity*)targetEntity
8559{
8560 [_foundTarget release];
8562}
8563
8565{
8567 if (result == nil || ![self isValidTarget:result]) {
8569 return nil;
8570 }
8571 return result;
8572}
8573
8574- (void)setPrimaryAggressor:(Entity*)targetEntity
8575{
8576 [_primaryAggressor release];
8578}
8579
8581{
8583 if (result == nil || ![self isValidTarget:result]) {
8585 return nil;
8586 }
8587 return result;
8588}
8589
8590- (void)setLastEscortTarget:(Entity*)targetEntity
8591{
8592 [_lastEscortTarget release];
8594}
8595
8597{
8599 if (result == nil || ![self isValidTarget:result]) {
8601 return nil;
8602 }
8603 return result;
8604}
8605
8606- (void)setThankedShip:(Entity*)targetEntity
8607{
8608 [_thankedShip release];
8610}
8611
8613{
8615 if (result == nil || ![self isValidTarget:result]) {
8617 return nil;
8618 }
8619 return result;
8620}
8621
8622- (void)setRememberedShip:(Entity*)targetEntity
8623{
8624 [_rememberedShip release];
8626}
8627
8629{
8631 if (result == nil || ![self isValidTarget:result]) {
8633 return nil;
8634 }
8635 return result;
8636}
8637
8638- (void)setTargetStation:(Entity*)targetEntity
8639{
8640 [_targetStation release];
8642}
8643
8644/* Now we use weakrefs rather than universal ID this function checks
8645 * for targets which may have a valid reference but are not currently
8646 * targetable. */
8647- (BOOL)isValidTarget:(Entity*)target
8648{
8649 if (target == nil) {
8650 return NO;
8651 }
8652 if ([target isShip]) {
8653 OOEntityStatus tstatus = [target status];
8654 if (tstatus == STATUS_ENTERING_WITCHSPACE || tstatus == STATUS_IN_HOLD || tstatus == STATUS_DOCKED || tstatus == STATUS_DEAD)
8655 // 2013-01-13, Eric: added STATUS_DEAD because I keep seeing ships locked on dead ships in attack mode.
8656 {
8657 return NO;
8658 }
8659 return YES;
8660 }
8661 if ([target isWormhole] && [target scanClass] != CLASS_NO_DRAW) {
8662 return YES;
8663 }
8664 return NO;
8665}
8666
8667- (void)addTarget:(Entity*)targetEntity
8668{
8669 if (targetEntity == self)
8670 return;
8671 if (targetEntity != nil) {
8674 [self startTrackingCurve];
8675 }
8676
8677 [[self shipSubEntityEnumerator] makeObjectsPerformSelector:@selector(addTarget:) withObject:targetEntity];
8678 if (![self isSubEntity])
8679 [self doScriptEvent:OOJSID("shipTargetAcquired") withArgument:targetEntity];
8680}
8681
8682- (void)removeTarget:(Entity*)targetEntity
8683{
8684 if (targetEntity != nil)
8685 [self noteLostTarget];
8686 else
8688 // targetEntity == nil is currently only true for mounted player missiles.
8689 // we don't want to send lostTarget messages while the missile is mounted.
8690
8691 [[self shipSubEntityEnumerator] makeObjectsPerformSelector:@selector(removeTarget:) withObject:targetEntity];
8692}
8693
8694/* Checks if the primary target is still trackable.
8695 *
8696 * 1.80 behaviour: still exists, is in scanner range, is not cloaked
8697 *
8698 * 1.81 (planned) behaviour:
8699 * - track cloaked ships once primary targeted (but no missiles, and can't keep as a mere defense target, and probably some other penalties)
8700 * - track ships at 120% scanner range *if* they are also primary aggressor
8701 *
8702 * But first, just switch over to this method on 1.80 behaviour and check
8703 * that things still work.
8704 */
8706{
8708 if (target == nil) {
8709 return NO;
8710 }
8711 if (![self isValidTarget:target]) {
8712 return NO;
8713 }
8714 double range2 = HPmagnitude2(HPvector_subtract([target position], position));
8715 if (range2 > scannerRange * scannerRange * 1.5625) {
8716 // 1.5625 = 1.25*1.25
8717 return NO;
8718 }
8719 // 1.81: can retain cloaked ships as a *primary* target now
8720 /* if ([target isShip] && [(ShipEntity*)target isCloaked])
8721 {
8722 return NO;
8723 } */
8724 return YES;
8725}
8726
8728{
8730 if ((result == nil && _primaryTarget != nil)
8731 || ![self isValidTarget:result]) {
8733 return nil;
8734 } else if (EXPECT_NOT(result == self)) {
8735 /* Added in response to a crash report showing recursion in
8736 [PlayerEntity hasHostileTarget].
8737 -- Ahruman 2009-12-17
8738 */
8740 }
8741 return result;
8742}
8743
8744// used when we need to check the target - perhaps for a potential
8745// noteTargetLost - without invalidating the target first
8747{
8749 if (EXPECT_NOT(result == self)) {
8750 // just in case
8752 return nil;
8753 }
8754 return result;
8755}
8756
8757- (BOOL)isFriendlyTo:(ShipEntity*)otherShip
8758{
8759 BOOL isFriendly = NO;
8760 OOShipGroup* myGroup = [self group];
8761 OOShipGroup* otherGroup = [otherShip group];
8762
8763 if ((otherShip == self) || ([self isPolice] && [otherShip isPolice]) || ([self isThargoid] && [otherShip isThargoid]) || (myGroup != nil && otherGroup != nil && (myGroup == otherGroup || [otherGroup leader] == self)) || ([self scanClass] == CLASS_MILITARY && [otherShip scanClass] == CLASS_MILITARY)) {
8764 isFriendly = YES;
8765 }
8766
8767 return isFriendly;
8768}
8769
8774
8775- (void)setShipHitByLaser:(ShipEntity*)ship
8776{
8777 if (ship != [self shipHitByLaser]) {
8778 [_shipHitByLaser release];
8779 _shipHitByLaser = [ship weakRetain];
8780 }
8781}
8782
8784{
8785 id target = nil;
8786 if ([self primaryTarget] != nil) {
8787 ShipEntity* ship = [self primaryTarget];
8788 if ([self isDefenseTarget:ship]) {
8789 [self removeDefenseTarget:ship];
8790 }
8791 // for compatibility with 1.76 behaviour of this function, only pass
8792 // the target as a function parameter if the target is still a potential
8793 // valid target (e.g. not scooped, docked, hyperspaced, etc.)
8794 target = (ship && ship->isShip && [self isValidTarget:ship]) ? (id)ship : nil;
8795 if ([self primaryAggressor] == ship) {
8797 }
8799 }
8800 // always do target lost
8801 [self doScriptEvent:OOJSID("shipTargetLost") withArgument:target];
8802 if (target == nil)
8803 [shipAI message:@"TARGET_LOST"]; // stale target? no major urgency.
8804 else
8805 [shipAI reactToMessage:@"TARGET_LOST" context:@"flight updates"]; // execute immediately otherwise.
8806}
8807
8809{
8810 behaviour = BEHAVIOUR_IDLE;
8811 frustration = 0.0;
8812 [self noteLostTarget];
8813}
8814
8815- (void)noteTargetDestroyed:(ShipEntity*)target
8816{
8817 [self collectBountyFor:(ShipEntity*)target];
8818 if ([self primaryTarget] == target) {
8819 [self removeTarget:target];
8820 [self doScriptEvent:OOJSID("shipTargetDestroyed") withArgument:target];
8821 [shipAI message:@"TARGET_DESTROYED"];
8822 }
8823 if ([self isDefenseTarget:target]) {
8824 [self removeDefenseTarget:target];
8825 [shipAI message:@"DEFENSE_TARGET_DESTROYED"];
8826 [self doScriptEvent:OOJSID("defenseTargetDestroyed") withArgument:target];
8827 }
8828}
8829
8831{
8832 return behaviour;
8833}
8834
8835- (void)setBehaviour:(OOBehaviour)cond
8836{
8837 if (cond != behaviour) {
8838 frustration = 0.0; // change is a GOOD thing
8839 behaviour = cond;
8840 }
8841}
8842
8844{
8845 return _destination;
8846}
8847
8849{
8850 return coordinates;
8851}
8852
8853- (void)setCoordinate:(HPVector)coord // The name "setCoordinates" is already used by AI scripting.
8854{
8855 coordinates = coord;
8856}
8857
8858- (HPVector)distance_six:(GLfloat)dist
8859{
8860 HPVector six = position;
8861 six.x -= dist * v_forward.x;
8862 six.y -= dist * v_forward.y;
8863 six.z -= dist * v_forward.z;
8864 return six;
8865}
8866
8867- (HPVector)distance_twelve:(GLfloat)dist withOffset:(GLfloat)offset
8868{
8869 HPVector twelve = position;
8870 twelve.x += dist * v_up.x;
8871 twelve.y += dist * v_up.y;
8872 twelve.z += dist * v_up.z;
8873 twelve.x += offset * v_right.x;
8874 twelve.y += offset * v_right.y;
8875 twelve.z += offset * v_right.z;
8876 return twelve;
8877}
8878
8879- (void)trackOntoTarget:(double)delta_t withDForward:(GLfloat)dp
8880{
8881 Vector vector_to_target;
8882 Quaternion q_minarc;
8883 //
8884 Entity* target = [self primaryTarget];
8885 //
8886 if (!target)
8887 return;
8888
8889 vector_to_target = [self vectorTo:target];
8890 //
8891 GLfloat range2 = magnitude2(vector_to_target);
8892 GLfloat targetRadius = 0.75 * target->collision_radius;
8893 GLfloat max_cos = sqrt(1 - targetRadius * targetRadius / range2);
8894
8895 if (dp > max_cos)
8896 return; // ON TARGET!
8897
8898 if (vector_to_target.x || vector_to_target.y || vector_to_target.z)
8899 vector_to_target = vector_normal(vector_to_target);
8900 else
8901 vector_to_target.z = 1.0;
8902
8903 q_minarc = quaternion_rotation_between(v_forward, vector_to_target);
8904
8906 [self orientationChanged];
8907
8908 flightRoll = 0.0;
8909 flightPitch = 0.0;
8910 flightYaw = 0.0;
8911 stick_roll = 0.0;
8912 stick_pitch = 0.0;
8913 stick_yaw = 0.0;
8914}
8915
8916- (double)ballTrackLeadingTarget:(double)delta_t atTarget:(Entity*)target
8917{
8918 if (!target) {
8919 return -2.0; // no target
8920 }
8921
8922 Vector vector_to_target;
8923 Vector axis_to_track_by;
8925 Vector my_ref = reference;
8926 double aim_cos, ref_cos;
8927 Vector leading = [target velocity];
8928
8929 // need to get vector to target in terms of this entities coordinate system
8930 HPVector my_position = [self absolutePositionForSubentity];
8931 vector_to_target = HPVectorToVector(HPvector_subtract([target position], my_position));
8932 // this is in absolute coordinates, so now rotate it
8933
8934 Entity* last = nil;
8935 Entity* father = [self parentEntity];
8936
8938 while ((father) && (father != last) && (father != NO_TARGET)) {
8939 /* Fix orientation */
8941 fo.w = -fo.w;
8942 /* The below code works for player turrets where the
8943 * orientation is different, but not for NPC turrets. Taking
8944 * the normal orientation with -w works: there is probably a
8945 * neater way which someone who understands quaternions can
8946 * find, but this works well enough for 1.82 - CIM */
8948 last = father;
8949 if (![last isSubEntity])
8950 break;
8951 father = [father owner];
8952 }
8953 q = quaternion_conjugate(q);
8954 // q now contains the rotation to the turret's reference system
8955
8956 vector_to_target = quaternion_rotate_vector(q, vector_to_target);
8957
8958 leading = quaternion_rotate_vector(q, leading);
8959 // rotate the vector to target and its velocity
8960
8961 if (magnitude(vector_to_target) > weaponRange * 1.01) {
8962 return -2.0; // out of range
8963 }
8964
8965 float lead = magnitude(vector_to_target) / TURRET_SHOT_SPEED;
8966
8967 vector_to_target = vector_add(vector_to_target, vector_multiply_scalar(leading, lead));
8968 vector_to_target = vector_normal_or_fallback(vector_to_target, kBasisZVector);
8969
8970 // do the tracking!
8971 aim_cos = dot_product(vector_to_target, my_aim);
8972 ref_cos = dot_product(vector_to_target, my_ref);
8973
8974 if (ref_cos > TURRET_MINIMUM_COS) // target is forward of self
8975 {
8976 axis_to_track_by = cross_product(vector_to_target, my_aim);
8977 } else {
8978 return -2.0; // target is out of fire arc
8979 }
8980
8981 quaternion_rotate_about_axis(&orientation, axis_to_track_by, thrust * delta_t);
8982 [self orientationChanged];
8983
8984 [self setStatus:STATUS_ACTIVE];
8985
8986 return aim_cos;
8987}
8988
8989- (void)setEvasiveJink:(GLfloat)z
8990{
8992 jink = kZeroVector;
8993 } else {
8994 jink.x = (ranrot_rand() % 256) - 128.0;
8995 jink.y = (ranrot_rand() % 256) - 128.0;
8996 jink.z = z;
8997
8998 // make sure we don't accidentally have near-zero jink
8999 if (jink.x < 0.0) {
9000 jink.x -= 128.0;
9001 } else {
9002 jink.x += 128.0;
9003 }
9004 if (jink.y < 0) {
9005 jink.y -= 128.0;
9006 } else {
9007 jink.y += 128.0;
9008 }
9009 }
9010}
9011
9012- (void)evasiveAction:(double)delta_t
9013{
9014 stick_roll = flightRoll; // desired roll and pitch
9016
9017 ShipEntity* target = [self primaryTarget];
9018 if (!target) // leave now!
9019 {
9020 [self noteLostTargetAndGoIdle]; // NOTE: was AI message: rather than reactToMessage:
9021 return;
9022 }
9023
9024 double agreement = dot_product(v_right, target->v_right);
9025 if (agreement > -0.3 && agreement < 0.3) {
9026 stick_roll = 0.0;
9027 } else {
9028 if (stick_roll >= 0.0) {
9030 } else {
9032 }
9033 }
9034 if (stick_pitch >= 0.0) {
9036 } else {
9038 }
9039
9040 [self applySticks:delta_t];
9041}
9042
9043- (double)trackPrimaryTarget:(double)delta_t retreat:(BOOL)retreat
9044{
9045 Entity* target = [self primaryTarget];
9046
9047 if (!target) // leave now!
9048 {
9049 [self noteLostTargetAndGoIdle]; // NOTE: was AI message: rather than reactToMessage:
9050 return 0.0;
9051 }
9052
9053 if (![self canStillTrackPrimaryTarget]) {
9054 [self noteLostTargetAndGoIdle]; // NOTE: was AI message: rather than reactToMessage:
9055 return 0.0;
9056 }
9057
9058 /* 1.81 change: do the above check first: if a missile can't be
9059 * fired outside scanner range it should self-destruct if the
9060 * target gets far enough away (it's going to miss anyway) -
9061 * CIM */
9062 if (scanClass == CLASS_MISSILE)
9063 return [self missileTrackPrimaryTarget:delta_t];
9064
9065 GLfloat d_forward, d_up, d_right;
9066
9068
9069 double range2 = HPmagnitude2(HPvector_subtract([target position], position));
9070
9071 // jink if retreating
9072 if (retreat) // calculate jink position when flying away from target.
9073 {
9074 Vector vx, vy, vz;
9075 if (target->isShip) {
9076 ShipEntity* targetShip = (ShipEntity*)target;
9077 vx = targetShip->v_right;
9078 vy = targetShip->v_up;
9079 vz = targetShip->v_forward;
9080 } else {
9081 Quaternion q = target->orientation;
9085 }
9086
9087 BOOL avoidCollision = NO;
9088 if (range2 < collision_radius * target->collision_radius * 100.0) // Check direction within 10 * collision radius.
9089 {
9090 Vector targetDirection = kBasisZVector;
9091 if (!vector_equal(relPos, kZeroVector))
9092 targetDirection = vector_normal(relPos);
9093 avoidCollision = (dot_product(targetDirection, v_forward) > -0.1); // is flying toward target or only slightly outward.
9094 }
9095
9096 GLfloat dist_adjust_factor = 1.0;
9098 double range = magnitude(relPos);
9099 if (range > 2000.0) {
9100 dist_adjust_factor = range / 2000.0;
9102 dist_adjust_factor *= 3;
9103 }
9104 }
9105 if (jink.x == 0.0 && behaviour != BEHAVIOUR_RUNNING_DEFENSE) { // test for zero jink and correct
9106 [self setEvasiveJink:400.0];
9107 }
9108 }
9109
9110 if (!avoidCollision) // it is safe to jink
9111 {
9112 relPos.x += (jink.x * vx.x + jink.y * vy.x + jink.z * vz.x) * dist_adjust_factor;
9113 relPos.y += (jink.x * vx.y + jink.y * vy.y + jink.z * vz.y) * dist_adjust_factor;
9114 relPos.z += (jink.x * vx.z + jink.y * vy.z + jink.z * vz.z);
9115 }
9116 }
9117
9118 if (!vector_equal(relPos, kZeroVector))
9119 relPos = vector_normal(relPos);
9120 else
9121 relPos.z = 1.0;
9122
9123 double max_cos = [self currentAimTolerance];
9124
9125 stick_roll = 0.0; // desired roll and pitch
9126 stick_pitch = 0.0;
9127
9128 double reverse = (retreat) ? -1.0 : 1.0;
9129
9130 double min_d = 0.004; // ~= 40m at 10km
9131 int max_factor = 8;
9132 double r_max_factor = 0.125;
9133 if (!retreat) {
9135 // much greater precision in combat
9136 if (max_flight_pitch > 1.0) {
9137 max_factor = floor(max_flight_pitch / 0.125);
9138 r_max_factor = 1.0 / max_factor;
9139 }
9140 min_d = 0.0004; // 10 times more precision ~= 4m at 10km
9141 max_factor *= 3;
9142 r_max_factor /= 3.0;
9143 } else if (accuracy >= COMBAT_AI_ISNT_AWFUL) {
9144 // slowly improve precision to target, but only if missing
9145 min_d -= 0.0001 * [self missedShots];
9146 if (min_d < 0.001) {
9147 min_d = 0.001;
9148 max_factor *= 2;
9149 r_max_factor /= 2.0;
9150 }
9151 }
9152 }
9153
9154 d_right = dot_product(relPos, v_right);
9155 d_up = dot_product(relPos, v_up);
9156 d_forward = dot_product(relPos, v_forward); // == cos of angle between v_forward and vector to target
9157
9158 if (d_forward * reverse > max_cos) // on_target!
9159 {
9160 return d_forward;
9161 }
9162
9163 // begin rule-of-thumb manoeuvres
9164 stick_pitch = 0.0;
9165 stick_roll = 0.0;
9166
9167 if ((reverse * d_forward < -0.5) && !pitching_over) // we're going the wrong way!
9168 pitching_over = YES;
9169
9170 if (pitching_over) {
9171 if (reverse * d_up > 0) // pitch up
9173 else
9175 pitching_over = (reverse * d_forward < 0.707);
9176 }
9177
9178 // check if we are flying toward the destination..
9179 if ((d_forward < max_cos) || (retreat)) // not on course so we must adjust controls..
9180 {
9181 if (d_forward < -max_cos) // hack to avoid just flying away from the destination
9182 {
9183 d_up = min_d * 2.0;
9184 }
9185
9186 if (d_up > min_d) {
9187 int factor = sqrt(fabs(d_right) / fabs(min_d));
9188 if (factor > max_factor)
9189 factor = max_factor;
9190 if (d_right > min_d)
9191 stick_roll = -max_flight_roll * r_max_factor * factor; // note#
9192 if (d_right < -min_d)
9193 stick_roll = +max_flight_roll * r_max_factor * factor; // note#
9194 }
9195 if (d_up < -min_d) {
9196 int factor = sqrt(fabs(d_right) / fabs(min_d));
9197 if (factor > max_factor)
9198 factor = max_factor;
9199 if (d_right > min_d)
9200 stick_roll = +max_flight_roll * r_max_factor * factor; // note#
9201 if (d_right < -min_d)
9202 stick_roll = -max_flight_roll * r_max_factor * factor; // note#
9203 }
9204
9205 if (stick_roll == 0.0) {
9206 int factor = sqrt(fabs(d_up) / fabs(min_d));
9207 if (factor > max_factor)
9208 factor = max_factor;
9209 if (d_up > min_d)
9210 stick_pitch = -max_flight_pitch * reverse * r_max_factor * factor;
9211 if (d_up < -min_d)
9212 stick_pitch = +max_flight_pitch * reverse * r_max_factor * factor;
9213 }
9214
9216 // don't overshoot target (helps accuracy at low frame rates)
9217 if (fabs(d_right) < fabs(stick_roll) * delta_t) {
9218 stick_roll = fabs(d_right) / delta_t * (stick_roll < 0 ? -1 : 1);
9219 }
9220 if (fabs(d_up) < fabs(stick_pitch) * delta_t) {
9221 stick_pitch = fabs(d_up) / delta_t * (stick_pitch < 0 ? -0.9 : 0.9);
9222 }
9223 }
9224 }
9225 /* # note
9226 Eric 9-9-2010: Removed the "reverse" variable from the stick_roll calculation. This was mathematical wrong and
9227 made the ship roll in the wrong direction, preventing the ship to fly away in a straight line from the target.
9228 This means all the places were a jink was set, this jink never worked correctly. The main reason a ship still
9229 managed to turn at close range was probably by the fail-safe mechanisme with the "pitching_over" variable.
9230 The jink was programmed to do nothing within 500 meters of the ship and just fly away in direct line from the target
9231 in that range. Because of the bug the ships always rolled to the wrong side needed to fly away in direct line
9232 resulting in making it a difficult target.
9233 After fixing the bug, the ship realy flew away in direct line during the first 500 meters, making it a easy target
9234 for the player. All jink settings are retested and changed to give a turning behaviour that felt like the old
9235 situation, but now more deliberately set.
9236 */
9237
9238 // end rule-of-thumb manoeuvres
9239 stick_yaw = 0.0;
9240
9241 [self applySticks:delta_t];
9242
9243 if (retreat)
9244 d_forward *= d_forward; // make positive AND decrease granularity
9245
9246 if (d_forward < 0.0)
9247 return 0.0;
9248
9249 if ((!flightRoll) && (!flightPitch)) // no correction
9250 return 1.0;
9251
9252 return d_forward;
9253}
9254
9255- (double)trackSideTarget:(double)delta_t leftside:(BOOL)leftside
9256{
9257 Entity* target = [self primaryTarget];
9258
9259 if (!target) // leave now!
9260 {
9261 [self noteLostTargetAndGoIdle]; // NOTE: was AI message: rather than reactToMessage:
9262 return 0.0;
9263 }
9264
9265 if (![self canStillTrackPrimaryTarget]) {
9266 [self noteLostTargetAndGoIdle]; // NOTE: was AI message: rather than reactToMessage:
9267 return 0.0;
9268 }
9269
9270 if (scanClass == CLASS_MISSILE) // never?
9271 return [self missileTrackPrimaryTarget:delta_t];
9272
9273 GLfloat d_forward, d_up, d_right;
9274
9276
9277 if (!vector_equal(relPos, kZeroVector))
9278 relPos = vector_normal(relPos);
9279 else
9280 relPos.z = 1.0;
9281
9282 // worse shots with side lasers than fore/aft, in general
9283
9284 double max_cos = [self currentAimTolerance];
9285
9286 stick_roll = 0.0; // desired roll and pitch
9287 stick_pitch = 0.0;
9288 stick_yaw = 0.0;
9289
9290 double reverse = (leftside) ? -1.0 : 1.0;
9291
9292 double min_d = 0.004;
9294 min_d = 0.002;
9295 }
9296 int max_factor = 8;
9297 double r_max_factor = 0.125;
9298
9299 d_right = dot_product(relPos, v_right);
9300 d_up = dot_product(relPos, v_up);
9301 d_forward = dot_product(relPos, v_forward); // == cos of angle between v_forward and vector to target
9302
9303 if (d_right * reverse > max_cos) // on_target!
9304 {
9305 return d_right * reverse;
9306 }
9307
9308 // begin rule-of-thumb manoeuvres
9309 stick_pitch = 0.0;
9310 stick_roll = 0.0;
9311 stick_yaw = 0.0;
9312
9313 // check if we are flying toward the destination..
9314 if ((d_right * reverse < max_cos)) // not on course so we must adjust controls..
9315 {
9316 if (d_right < -max_cos) // hack to avoid just pointing away from the destination
9317 {
9318 d_forward = min_d * 2.0;
9319 }
9320
9321 if (d_forward > min_d) {
9322 int factor = sqrt(fabs(d_up) / fabs(min_d));
9323 if (factor > max_factor)
9324 factor = max_factor;
9325 if (d_up > min_d)
9326 stick_pitch = +max_flight_pitch * r_max_factor * factor; // note#
9327 if (d_up < -min_d)
9328 stick_pitch = -max_flight_pitch * r_max_factor * factor; // note#
9329 }
9330 if (d_forward < -min_d) {
9331 int factor = sqrt(fabs(d_up) / fabs(min_d));
9332 if (factor > max_factor)
9333 factor = max_factor;
9334 if (d_up > min_d)
9335 stick_pitch = +max_flight_pitch * r_max_factor * factor; // note#
9336 if (d_up < -min_d)
9337 stick_pitch = -max_flight_pitch * r_max_factor * factor; // note#
9338 }
9339
9340 if (fabs(stick_pitch) == 0.0 || fabs(d_forward) > 0.5) {
9341 stick_pitch = 0.0;
9342 int factor = sqrt(fabs(d_forward) / fabs(min_d));
9343 if (factor > max_factor)
9344 factor = max_factor;
9345 if (d_forward > min_d)
9346 stick_yaw = -max_flight_yaw * reverse * r_max_factor * factor;
9347 if (d_forward < -min_d) {
9348 if (factor < max_factor / 2.0) // compensate for forward thrust
9349 factor *= 2.0;
9350 stick_yaw = +max_flight_yaw * reverse * r_max_factor * factor;
9351 }
9352 }
9353 }
9354
9355 // end rule-of-thumb manoeuvres
9356
9357 [self applySticks:delta_t];
9358
9359 if ((!flightPitch) && (!flightYaw)) // no correction
9360 return 1.0;
9361
9362 return d_right * reverse;
9363}
9364
9365- (double)missileTrackPrimaryTarget:(double)delta_t
9366{
9367 Vector relPos;
9368 GLfloat d_forward, d_up, d_right;
9369 ShipEntity* target = [self primaryTarget];
9370 BOOL inPursuit = YES;
9371
9372 if (!target || ![target isShip]) // leave now!
9373 return 0.0;
9374
9375 double damping = 0.5 * delta_t;
9376
9377 stick_roll = 0.0; // desired roll and pitch
9378 stick_pitch = 0.0;
9379 stick_yaw = 0.0;
9380
9381 relPos = [self vectorTo:target];
9382
9383 // Adjust missile course by taking into account target's velocity and missile
9384 // accuracy. Modification on original code contributed by Cmdr James.
9385
9386 float missileSpeed = (float)[self speed];
9387
9388 // Avoid getting ourselves in a divide by zero situation by setting a missileSpeed
9389 // low threshold. Arbitrarily chosen 0.01, since it seems to work quite well.
9390 // Missile accuracy is already clamped within the 0.0 to 10.0 range at initialization,
9391 // but doing these calculations every frame when accuracy equals 0.0 just wastes cycles.
9392 if (missileSpeed > 0.01f && accuracy > 0.0f) {
9393 inPursuit = (dot_product([target forwardVector], v_forward) > 0.0f);
9394 if (inPursuit) {
9395 Vector leading = [target velocity];
9396 float lead = magnitude(relPos) / missileSpeed;
9397
9398 // Adjust where we are going to take into account target's velocity.
9399 // Use accuracy value to determine how well missile will track target.
9400 relPos.x += (lead * leading.x * (accuracy / 10.0f));
9401 relPos.y += (lead * leading.y * (accuracy / 10.0f));
9402 relPos.z += (lead * leading.z * (accuracy / 10.0f));
9403 }
9404 }
9405
9406 if (!vector_equal(relPos, kZeroVector))
9407 relPos = vector_normal(relPos);
9408 else
9409 relPos.z = 1.0;
9410
9411 d_right = dot_product(relPos, v_right); // = cosine of angle between angle to target and v_right
9412 d_up = dot_product(relPos, v_up); // = cosine of angle between angle to target and v_up
9413 d_forward = dot_product(relPos, v_forward); // = cosine of angle between angle to target and v_forward
9414
9415 // begin rule-of-thumb manoeuvres
9416
9417 stick_roll = 0.0;
9418
9419 if (pitching_over)
9420 pitching_over = (stick_pitch != 0.0);
9421
9422 if ((d_forward < -pitch_tolerance) && (!pitching_over)) {
9423 pitching_over = YES;
9424 if (d_up >= 0)
9426 if (d_up < 0)
9428 }
9429
9430 if (pitching_over) {
9431 pitching_over = (d_forward < 0.5);
9432 } else {
9433 stick_pitch = -max_flight_pitch * d_up;
9434 stick_roll = -max_flight_roll * d_right;
9435 }
9436
9437 // end rule-of-thumb manoeuvres
9438
9439 // apply damping
9440 if (flightRoll < 0)
9441 flightRoll += (flightRoll < -damping) ? damping : -flightRoll;
9442 if (flightRoll > 0)
9443 flightRoll -= (flightRoll > damping) ? damping : flightRoll;
9444 if (flightPitch < 0)
9445 flightPitch += (flightPitch < -damping) ? damping : -flightPitch;
9446 if (flightPitch > 0)
9447 flightPitch -= (flightPitch > damping) ? damping : flightPitch;
9448
9449 [self applySticks:delta_t];
9450
9451 //
9452 // return target confidence 0.0 .. 1.0
9453 //
9454 if (d_forward < 0.0)
9455 return 0.0;
9456 return d_forward;
9457}
9458
9459- (double)trackDestination:(double)delta_t retreat:(BOOL)retreat
9460{
9461 Vector relPos;
9462 GLfloat d_forward, d_up, d_right;
9463
9464 BOOL we_are_docking = (nil != dockingInstructions);
9465
9466 stick_roll = 0.0; // desired roll and pitch
9467 stick_pitch = 0.0;
9468 stick_yaw = 0.0;
9469
9470 double reverse = 1.0;
9471 double reversePlayer = 1.0;
9472
9473 double min_d = 0.004;
9474 double max_cos = MAX_COS; // should match default value of max_cos in behaviour_fly_to_destination!
9475 double precision = we_are_docking ? 0.25 : 0.9025; // lower values force a direction closer to the target. (resp. 50% and 95% within range)
9476
9477 if (retreat)
9478 reverse = -reverse;
9479
9480 if (isPlayer) {
9481 reverse = -reverse;
9482 reversePlayer = -1;
9483 }
9484
9486 double range2 = magnitude2(relPos);
9487 double desired_range2 = desired_range * desired_range;
9488
9489 /* 2009-7-18 Eric: We need to aim well inide the desired_range sphere round the target and not at the surface of the sphere.
9490 Because of the framerate most ships normally overshoot the target and they end up flying clearly on a path
9491 through the sphere. Those ships give no problems, but ships with a very low turnrate will aim close to the surface and will than
9492 have large trouble with reaching their destination. When those ships enter the slowdown range, they have almost no speed vector
9493 in the direction of the target. I now used 95% of desired_range to aim at, but a smaller value might even be better.
9494 */
9495 if (range2 > desired_range2) {
9496 max_cos = sqrt(1 - precision * desired_range2 / range2); // Head for a point within 95% of desired_range.
9497 if (max_cos >= 0.99999) {
9498 max_cos = 0.99999;
9499 }
9500 }
9501
9502 if (!vector_equal(relPos, kZeroVector))
9503 relPos = vector_normal(relPos);
9504 else
9505 relPos.z = 1.0;
9506
9507 d_right = dot_product(relPos, v_right);
9508 d_up = dot_product(relPos, v_up);
9509 d_forward = dot_product(relPos, v_forward); // == cos of angle between v_forward and vector to target
9510
9511 // begin rule-of-thumb manoeuvres
9512 stick_pitch = 0.0;
9513 stick_roll = 0.0;
9514
9515 // pitching_over is currently only set in behaviour_formation_form_up, for escorts and in avoidCollision.
9516 // This allows for immediate pitch corrections instead of first waiting untill roll has completed.
9517 if (pitching_over) {
9518 if (reverse * d_up > 0) // pitch up
9520 else
9522 pitching_over = (reverse * d_forward < 0.707);
9523 }
9524
9525 // check if we are flying toward (or away from) the destination..
9526 if ((d_forward < max_cos) || (retreat)) // not on course so we must adjust controls..
9527 {
9528
9529 if (d_forward <= -max_cos || (retreat && d_forward >= max_cos)) // hack to avoid just flying away from the destination
9530 {
9531 d_up = min_d * 2.0;
9532 }
9533
9534 if (d_up > min_d) {
9535 int factor = sqrt(fabs(d_right) / fabs(min_d));
9536 if (factor > 8)
9537 factor = 8;
9538 if (d_right > min_d)
9539 stick_roll = -max_flight_roll * reversePlayer * 0.125 * factor; // only reverse sign for the player;
9540 if (d_right < -min_d)
9541 stick_roll = +max_flight_roll * reversePlayer * 0.125 * factor;
9542 if (fabs(d_right) < fabs(stick_roll) * delta_t)
9543 stick_roll = fabs(d_right) / delta_t * (stick_roll < 0 ? -1 : 1); // don't overshoot heading
9544 }
9545
9546 if (d_up < -min_d) {
9547 int factor = sqrt(fabs(d_right) / fabs(min_d));
9548 if (factor > 8)
9549 factor = 8;
9550 if (d_right > min_d)
9551 stick_roll = +max_flight_roll * reversePlayer * 0.125 * factor; // only reverse sign for the player;
9552 if (d_right < -min_d)
9553 stick_roll = -max_flight_roll * reversePlayer * 0.125 * factor;
9554 if (fabs(d_right) < fabs(stick_roll) * delta_t)
9555 stick_roll = fabs(d_right) / delta_t * (stick_roll < 0 ? -1 : 1); // don't overshoot heading
9556 }
9557
9558 if (stick_roll == 0.0) {
9559 int factor = sqrt(fabs(d_up) / fabs(min_d));
9560 if (factor > 8)
9561 factor = 8;
9562 if (d_up > min_d)
9563 stick_pitch = -max_flight_pitch * reverse * 0.125 * factor; // pitch_pitch * reverse;
9564 if (d_up < -min_d)
9565 stick_pitch = +max_flight_pitch * reverse * 0.125 * factor;
9566 if (fabs(d_up) < fabs(stick_pitch) * delta_t)
9567 stick_pitch = fabs(d_up) / delta_t * (stick_pitch < 0 ? -1 : 1); // don't overshoot heading
9568 }
9569
9570 if (stick_pitch == 0.0) {
9571 // not sufficiently on course yet, but min_d is too high
9572 // turn anyway slightly to adjust
9573 stick_pitch = 0.01;
9574 }
9575 }
9576
9577 if (we_are_docking && docking_match_rotation && (d_forward > max_cos)) {
9578 /* we are docking and need to consider the rotation/orientation of the docking port */
9579 StationEntity* station_for_docking = (StationEntity*)[self targetStation];
9580
9581 if ((station_for_docking) && (station_for_docking->isStation)) {
9583 }
9584 }
9585
9586 // end rule-of-thumb manoeuvres
9587
9588 [self applySticks:delta_t];
9589
9590 if (retreat)
9591 d_forward *= d_forward; // make positive AND decrease granularity
9592
9593 if (d_forward < 0.0)
9594 return 0.0;
9595
9596 if ((!flightRoll) && (!flightPitch)) // no correction
9597 return 1.0;
9598
9599 return d_forward;
9600}
9601
9602- (GLfloat)rollToMatchUp:(Vector)up_vec rotating:(GLfloat)match_roll
9603{
9604 GLfloat cosTheta = dot_product(up_vec, v_up); // == cos of angle between up vectors
9605 GLfloat sinTheta = dot_product(up_vec, v_right);
9606
9607 if (!isPlayer) {
9608 match_roll = -match_roll; // make necessary corrections for a different viewpoint
9609 sinTheta = -sinTheta;
9610 }
9611
9612 if (cosTheta < 0.0f) {
9613 cosTheta = -cosTheta;
9614 sinTheta = -sinTheta;
9615 }
9616
9617 if (sinTheta > 0.0f) {
9618 // increase roll rate
9619 return cosTheta * cosTheta * match_roll + sinTheta * sinTheta * max_flight_roll;
9620 } else {
9621 // decrease roll rate
9622 return cosTheta * cosTheta * match_roll - sinTheta * sinTheta * max_flight_roll;
9623 }
9624}
9625
9627{
9629}
9630
9632{
9633 if (_collisionExceptions == nil) {
9634 return [NSArray array];
9635 }
9637}
9638
9639- (void)addCollisionException:(ShipEntity*)ship
9640{
9641 if (_collisionExceptions == nil) {
9642 // Allocate lazily for the benefit of the ships that never need this.
9643 _collisionExceptions = [[OOWeakSet alloc] init];
9644 }
9646}
9647
9648- (void)removeCollisionException:(ShipEntity*)ship
9649{
9650 if (_collisionExceptions != nil) {
9652 }
9653}
9654
9655- (BOOL)collisionExceptedFor:(ShipEntity*)ship
9656{
9657 if (_collisionExceptions == nil) {
9658 return NO;
9659 }
9661}
9662
9664{
9665 return [_defenseTargets count];
9666}
9667
9669{
9670 return [_defenseTargets allObjects];
9671}
9672
9674{
9676}
9677
9678- (BOOL)addDefenseTarget:(Entity*)target
9679{
9680 if ([self defenseTargetCount] >= MAX_TARGETS) {
9681 return NO;
9682 }
9683 // primary target can be a wormhole, defense targets shouldn't be
9684 if (target == nil || [self isDefenseTarget:target] || ![target isShip]) {
9685 return NO;
9686 }
9687 if (_defenseTargets == nil) {
9688 // Allocate lazily for the benefit of the ships that never get in fights.
9689 _defenseTargets = [[OOWeakSet alloc] init];
9690 }
9691
9692 [_defenseTargets addObject:target];
9693 return YES;
9694}
9695
9697{
9698 if (_defenseTargets == nil) {
9699 return;
9700 }
9701 // get enumerator from array as we'll be modifying original during enumeration
9702 NSEnumerator* defTargets = [[self allDefenseTargets] objectEnumerator];
9703 Entity* target = nil;
9704 while ((target = [[defTargets nextObject] weakRefUnderlyingObject])) {
9705 if ([target status] == STATUS_DEAD) {
9706 [self removeDefenseTarget:target];
9707 }
9708 }
9709}
9710
9711- (BOOL)isDefenseTarget:(Entity*)target
9712{
9713 return [_defenseTargets containsObject:target];
9714}
9715
9716// exposed to AI (as alias of clearDefenseTargets)
9721
9722- (void)removeDefenseTarget:(Entity*)target
9723{
9725}
9726
9728{
9729 return [self rangeToSecondaryTarget:[self primaryTarget]];
9730}
9731
9732- (double)rangeToSecondaryTarget:(Entity*)target
9733{
9734 double dist;
9735 Vector delta;
9736 if (target == nil) // leave now!
9737 return 0.0;
9739 dist = magnitude(delta);
9740 dist -= target->collision_radius;
9741 dist -= collision_radius;
9742 return dist;
9743}
9744
9746{
9747 Vector delta;
9748 Entity* target = [self primaryTarget];
9749 if (target == nil || ![target isShip]) // leave now!
9750 {
9751 return 0.0;
9752 }
9753 ShipEntity* ship_target = (ShipEntity*)target;
9754
9756
9757 return dot_product(vector_normal(delta), ship_target->v_forward);
9758}
9759
9760- (BOOL)hasProximityAlertIgnoringTarget:(BOOL)ignore_target
9761{
9762 if (([self proximityAlert] != nil) && (!ignore_target || ([self proximityAlert] != [self primaryTarget]))) {
9763 return YES;
9764 }
9765 return NO;
9766}
9767
9768// lower is better. Defines angular size of circle in which ship
9769// thinks is on target
9771{
9772 GLfloat basic_aim = aim_tolerance;
9773 GLfloat best_cos = 0.99999; // ~45m in 10km (track won't go better than 40)
9775 // better general targeting
9776 best_cos = 0.999999; // ~14m in 10km (track won't go better than 10)
9777 // if missing, aim better!
9778 basic_aim /= 1.0 + ((GLfloat)[self missedShots] / 4.0);
9779 }
9781 // deadly shots
9782 best_cos = 0.9999999; // ~4m in 10km (track won't go better than 4)
9783 // and start with extremely good aim circle
9784 basic_aim /= 5.0;
9785 }
9786 if (currentWeaponFacing == WEAPON_FACING_AFT && accuracy < COMBAT_AI_ISNT_AWFUL) { // bad shots with aft lasers
9787 basic_aim *= 1.3;
9788 } else if (currentWeaponFacing == WEAPON_FACING_PORT || currentWeaponFacing == WEAPON_FACING_STARBOARD) { // everyone a bit worse with side lasers
9789 if (accuracy < COMBAT_AI_ISNT_AWFUL) { // especially these
9790 basic_aim *= 1.3 + randf();
9791 } else {
9792 basic_aim *= 1.3;
9793 }
9794 }
9795 // only apply glare if ship is not shadowed
9796 if (isSunlit) {
9797 OOSunEntity* sun = [UNIVERSE sun];
9798 if (sun) {
9799 GLfloat sunGlareAngularSize = atan([sun radius] / HPdistance([self position], [sun position])) * SUN_GLARE_MULT_FACTOR + (SUN_GLARE_ADD_FACTOR);
9800 GLfloat glareLevel = [self lookingAtSunWithThresholdAngleCos:cos(sunGlareAngularSize)] * (1.0f - [self sunGlareFilter]);
9801 if (glareLevel > 0.1f) {
9802 // looking towards sun can seriously mess up aim (glareLevel 0..1)
9803 basic_aim *= (1.0 + glareLevel * 3.0);
9804 // OOLog(@"aim.debug",@"Sun glare affecting aim: %f for %@",glareLevel,self);
9805 if (glareLevel > 0.5f) {
9806 // strong glare makes precise targeting impossible
9807 best_cos = 0.99999;
9808 }
9809 }
9810 }
9811 }
9812
9813 GLfloat max_cos = sqrt(1 - (basic_aim * basic_aim / 100000000.0));
9814
9815 if (max_cos < best_cos) {
9816 return max_cos;
9817 }
9818 return best_cos;
9819}
9820
9821// much simpler than player version
9822- (GLfloat)lookingAtSunWithThresholdAngleCos:(GLfloat)thresholdAngleCos
9823{
9824 OOSunEntity* sun = [UNIVERSE sun];
9825 GLfloat measuredCos = 999.0f, measuredCosAbs;
9826 GLfloat sunBrightness = 0.0f;
9827 Vector relativePosition, unitRelativePosition;
9828
9829 if (EXPECT_NOT(!sun))
9830 return 0.0f;
9831
9833 unitRelativePosition = vector_normal_or_zbasis(relativePosition);
9834 switch (currentWeaponFacing) {
9836 measuredCos = -dot_product(unitRelativePosition, v_forward);
9837 break;
9838 case WEAPON_FACING_AFT:
9839 measuredCos = +dot_product(unitRelativePosition, v_forward);
9840 break;
9841 case WEAPON_FACING_PORT:
9842 measuredCos = +dot_product(unitRelativePosition, v_right);
9843 break;
9845 measuredCos = -dot_product(unitRelativePosition, v_right);
9846 break;
9847 default:
9848 break;
9849 }
9850 measuredCosAbs = fabs(measuredCos);
9851 if (thresholdAngleCos <= measuredCosAbs && measuredCosAbs <= 1.0f) // angle from viewpoint to sun <= desired threshold
9852 {
9853 sunBrightness = (measuredCos - thresholdAngleCos) / (1.0f - thresholdAngleCos);
9854 if (sunBrightness < 0.0f)
9855 sunBrightness = 0.0f;
9856 }
9857 return sunBrightness * sunBrightness * sunBrightness;
9858}
9859
9860- (BOOL)onTarget:(OOWeaponFacing)direction withWeapon:(OOWeaponType)weapon_type
9861{
9862 // initialize dq to a value that would normally return NO; dq is handled inside the defaultless switch(direction) statement
9863 // and should alaways be recalculated anyway. Initialization here needed to silence compiler warning - Nikos 20120526
9864 GLfloat dq = -1.0f;
9865 GLfloat d2, radius, astq;
9866 Vector rel_pos, urp;
9867 if ([weapon_type isTurretLaser]) {
9868 return YES;
9869 }
9870
9871 Entity* target = [self primaryTarget];
9872 if (target == nil)
9873 return NO;
9874 if ([target status] == STATUS_DEAD)
9875 return NO;
9876
9877 if (isSunlit && (target->isSunlit == NO) && (randf() < 0.75)) {
9878 return NO; // 3/4 of the time you can't see from a lit place into a darker place
9879 }
9880 radius = target->collision_radius;
9882 d2 = magnitude2(rel_pos);
9883 urp = vector_normal_or_zbasis(rel_pos);
9884
9885 switch (direction) {
9887 dq = +dot_product(urp, v_forward); // cosine of angle between v_forward and unit relative position
9888 break;
9889
9890 case WEAPON_FACING_AFT:
9891 dq = -dot_product(urp, v_forward); // cosine of angle between v_forward and unit relative position
9892 break;
9893
9894 case WEAPON_FACING_PORT:
9895 dq = -dot_product(urp, v_right); // cosine of angle between v_right and unit relative position
9896 break;
9897
9899 dq = +dot_product(urp, v_right); // cosine of angle between v_right and unit relative position
9900 break;
9901
9902 case WEAPON_FACING_NONE:
9903 break;
9904 }
9905
9906 if (dq < 0.0)
9907 return NO;
9908
9909 GLfloat aim = [self currentAimTolerance];
9910 if (dq > aim * aim)
9911 return YES;
9912
9913 // cosine of 1/3 of half angle subtended by target (mostly they'll
9914 // fire sooner anyway due to currentAimTolerance, but this should
9915 // almost always be a solid hit)
9916 astq = sqrt(1.0 - radius * radius / (d2 * 9));
9917
9918 return (fabs(dq) >= astq);
9919}
9920
9921- (BOOL)fireWeapon:(OOWeaponType)weapon_type direction:(OOWeaponFacing)direction range:(double)range
9922{
9923 weapon_temp = 0.0;
9924 switch (direction) {
9927 break;
9928
9929 case WEAPON_FACING_AFT:
9931 break;
9932
9933 case WEAPON_FACING_PORT:
9935 break;
9936
9939 break;
9940
9941 case WEAPON_FACING_NONE:
9942 break;
9943 }
9945 return NO;
9946
9947 NSUInteger multiplier = 1;
9948 if (_multiplyWeapons) {
9949 // multiple fitted
9950 multiplier = [[self laserPortOffset:direction] count];
9951 }
9952
9953 if (energy <= weapon_energy_use * multiplier)
9954 return NO;
9955 if ([self shotTime] < weapon_recharge_rate)
9956 return NO;
9957 if (![weapon_type isTurretLaser]) { // thargoid laser may just pick secondary target in this case
9958 if (range > randf() * weaponRange * (accuracy + 7.5))
9959 return NO;
9960 if (range > weaponRange)
9961 return NO;
9962 }
9963 if (![self onTarget:direction withWeapon:weapon_type])
9964 return NO;
9965
9966 BOOL fired = NO;
9967 if (!isWeaponNone(weapon_type)) {
9968 if ([weapon_type isTurretLaser]) {
9969 [self fireDirectLaserShot:range];
9970 fired = YES;
9971 } else {
9973 fired = YES;
9974 }
9975 }
9976
9977 if (fired) {
9978 energy -= weapon_energy_use * multiplier;
9979 switch (direction) {
9982 break;
9983
9984 case WEAPON_FACING_AFT:
9986 break;
9987
9988 case WEAPON_FACING_PORT:
9990 break;
9991
9994 break;
9995
9996 case WEAPON_FACING_NONE:
9997 break;
9998 }
9999 }
10000
10001 if (direction == WEAPON_FACING_FORWARD) {
10002 // can we fire lasers from our subentities?
10003 ShipEntity* se = nil;
10004 foreach (se, [self shipSubEntityEnumerator]) {
10005 if ([se fireSubentityLaserShot:range]) {
10006 fired = YES;
10007 }
10008 }
10009 }
10010
10011 if (fired && cloaking_device_active && cloakPassive) {
10013 }
10014
10015 return fired;
10016}
10017
10018- (BOOL)fireMainWeapon:(double)range
10019{
10020 // set the values from forward_weapon_type.
10021 // OXPs can override the default front laser energy damage.
10023 [self setWeaponDataFromType:forward_weapon_type];
10024
10025 // weapon damage override no longer effective
10026 // weapon_damage = weapon_damage_override;
10027
10028 BOOL result = [self fireWeapon:forward_weapon_type direction:WEAPON_FACING_FORWARD range:range];
10030 // need to check subentities to avoid AI oddities
10031 // will already have fired them by now, though
10032 NSEnumerator* subEnum = [self shipSubEntityEnumerator];
10033 ShipEntity* se = nil;
10034 OOWeaponType weapon_type = nil;
10035 BOOL hasTurrets = NO;
10036 while (isWeaponNone(weapon_type) && (se = [subEnum nextObject])) {
10037 weapon_type = se->forward_weapon_type;
10039 if (se->behaviour == BEHAVIOUR_TRACK_AS_TURRET) {
10040 hasTurrets = YES;
10041 }
10042 }
10043 if (isWeaponNone(weapon_type) && hasTurrets) { /* no forward weapon but has turrets, so set up range calculations accordingly
10044 note: this was hard-coded to 10000.0, although turrets have a notably
10045 shorter range. We are using a multiplier of 1.667 in order to not change
10046 something that already works, but probably it would be best to use
10047 TURRET_SHOT_RANGE * COMBAT_WEAPON_RANGE_FACTOR here
10048 */
10050 } else {
10051 [self setWeaponDataFromType:weapon_type];
10052 }
10053 }
10054 return result;
10055}
10056
10057- (BOOL)fireAftWeapon:(double)range
10058{
10059 // set the values from aft_weapon_type.
10061 [self setWeaponDataFromType:aft_weapon_type];
10062
10063 return [self fireWeapon:aft_weapon_type direction:WEAPON_FACING_AFT range:range];
10064}
10065
10066- (BOOL)firePortWeapon:(double)range
10067{
10068 // set the values from port_weapon_type.
10070 [self setWeaponDataFromType:port_weapon_type];
10071
10072 return [self fireWeapon:port_weapon_type direction:WEAPON_FACING_PORT range:range];
10073}
10074
10075- (BOOL)fireStarboardWeapon:(double)range
10076{
10077 // set the values from starboard_weapon_type.
10079 [self setWeaponDataFromType:starboard_weapon_type];
10080
10081 return [self fireWeapon:starboard_weapon_type direction:WEAPON_FACING_STARBOARD range:range];
10082}
10083
10085{
10086 return shot_time;
10087}
10088
10090{
10091 shot_time = 0.0;
10092}
10093
10094- (BOOL)fireTurretCannon:(double)range
10095{
10096 if ([self shotTime] < weapon_recharge_rate)
10097 return NO;
10098 if (range > weaponRange * 1.01) // 1% more than max range - open up just slightly early
10099 return NO;
10100 ShipEntity* root = [self rootShipEntity];
10101 if ([root isPlayer] && ![PLAYER weaponsOnline])
10102 return NO;
10103
10104 if ([root isCloaked] && [root cloakPassive]) {
10105 // can't fire turrets while cloaked
10106 return NO;
10107 }
10108
10109 Vector vel;
10110 HPVector origin = [self position];
10111
10112 Entity* last = nil;
10113 Entity* father = [self parentEntity];
10114 OOMatrix r_mat;
10115
10117 // adjust velocity and position vectors to absolute coordinates
10118 while ((father) && (father != last) && (father != NO_TARGET)) {
10119 r_mat = [father drawRotationMatrix];
10121 vel = OOVectorMultiplyMatrix(vel, r_mat);
10122 last = father;
10123 if (![last isSubEntity])
10124 break;
10125 father = [father owner];
10126 }
10127
10128 origin = HPvector_add(origin, vectorToHPVector(vector_multiply_scalar(vel, collision_radius + 0.5))); // Start just outside collision sphere
10129 vel = vector_multiply_scalar(vel, TURRET_SHOT_SPEED); // Shot velocity
10130
10131 OOPlasmaShotEntity* shot = [[OOPlasmaShotEntity alloc] initWithPosition:origin
10132 velocity:vel
10133 energy:weapon_damage
10134 duration:weaponRange / TURRET_SHOT_SPEED
10135 color:laser_color];
10136
10137 [shot autorelease];
10138 [UNIVERSE addEntity:shot];
10139 [shot setOwner:[self rootShipEntity]]; // has to be done AFTER adding shot to the UNIVERSE
10140
10141 [self resetShotTime];
10142 return YES;
10143}
10144
10145- (void)setLaserColor:(OOColor*)color
10146{
10147 if (color) {
10148 [laser_color release];
10149 laser_color = [color retain];
10150 }
10151}
10152
10153- (void)setExhaustEmissiveColor:(OOColor*)color
10154{
10155 if (color) {
10156 [exhaust_emissive_color release];
10157 exhaust_emissive_color = [color retain];
10158 }
10159}
10160
10162{
10163 return [[laser_color retain] autorelease];
10164}
10165
10167{
10168 return [[exhaust_emissive_color retain] autorelease];
10169}
10170
10171- (BOOL)fireSubentityLaserShot:(double)range
10172{
10173 [self setShipHitByLaser:nil];
10174
10176 return NO;
10177 [self setWeaponDataFromType:forward_weapon_type];
10178
10179 ShipEntity* parent = [self owner];
10180 NSAssert([parent isShipWithSubEntityShip:self], @"-fireSubentityLaserShot: called on ship which is not a subentity.");
10181
10182 // subentity lasers still draw power from the main entity
10183 if ([parent energy] <= weapon_energy_use)
10184 return NO;
10185 if ([self shotTime] < weapon_recharge_rate)
10186 return NO;
10188 return NO;
10189 if (range > weaponRange)
10190 return NO;
10191
10193 [parent setEnergy:([parent energy] - weapon_energy_use)];
10194
10195 GLfloat hitAtRange = weaponRange;
10197 ShipEntity* victim = [UNIVERSE firstShipHitByLaserFromShip:self inDirection:direction offset:kZeroVector gettingRangeFound:&hitAtRange];
10198 [self setShipHitByLaser:victim];
10199
10200 OOLaserShotEntity* shot = [OOLaserShotEntity laserFromShip:self direction:direction offset:kZeroVector];
10201 [shot setColor:laser_color];
10202 [shot setScanClass:CLASS_NO_DRAW];
10203
10204 if (victim != nil) {
10205 [self adjustMissedShots:-1];
10206
10207 if ([self isPlayer]) {
10208 [PLAYER addRoleForAggression:victim];
10209 }
10210
10212 if (subent != nil && [victim isFrangible]) {
10213 // do 1% bleed-through damage...
10214 [victim takeEnergyDamage:0.01 * weapon_damage from:self becauseOf:parent weaponIdentifier:[[self weaponTypeForFacing:WEAPON_FACING_FORWARD strict:YES] identifier]];
10215 victim = subent;
10216 }
10217
10218 if (hitAtRange < weaponRange) {
10219 [victim takeEnergyDamage:weapon_damage from:self becauseOf:parent weaponIdentifier:[[self weaponTypeForFacing:WEAPON_FACING_FORWARD strict:YES] identifier]]; // a very palpable hit
10220
10221 [shot setRange:hitAtRange];
10223 HPVector flash_pos = HPvector_add([shot position], vectorToHPVector(vector_multiply_scalar(vd, hitAtRange)));
10224 [UNIVERSE addLaserHitEffectsAt:flash_pos against:victim damage:weapon_damage color:laser_color];
10225 }
10226 } else {
10227 [self adjustMissedShots:+1];
10228
10229 // see ATTACKER_MISSED section of main entity laser routine
10230 if (![parent isCloaked]) {
10231 victim = [parent primaryTarget];
10232
10233 Vector shotDirection = vector_forward_from_quaternion([shot orientation]);
10234 Vector victimDirection = vector_normal(HPVectorToVector(HPvector_subtract([victim position], [parent position])));
10235 if (dot_product(shotDirection, victimDirection) > 0.995) // Within 84.26 degrees
10236 {
10237 if ([self isPlayer]) {
10238 [PLAYER addRoleForAggression:victim];
10239 }
10240 [victim setPrimaryAggressor:parent];
10241 [victim setFoundTarget:parent];
10242 [victim reactToAIMessage:@"ATTACKER_MISSED" context:@"attacker narrowly misses"];
10243 [victim doScriptEvent:OOJSID("shipBeingAttackedUnsuccessfully") withArgument:parent];
10244 }
10245 }
10246 }
10247
10248 [UNIVERSE addEntity:shot];
10249 [self resetShotTime];
10250
10251 return YES;
10252}
10253
10254- (BOOL)fireDirectLaserShot:(double)range
10255{
10256 Entity* my_target = [self primaryTarget];
10257 if (my_target == nil)
10258 return [self fireDirectLaserDefensiveShot];
10259 if (range > randf() * weaponRange * (accuracy + 5.5))
10260 return [self fireDirectLaserDefensiveShot];
10261 if (range > weaponRange)
10262 return [self fireDirectLaserDefensiveShot];
10263 return [self fireDirectLaserShotAt:my_target];
10264}
10265
10267{
10268 NSEnumerator* targetEnum = [self defenseTargetEnumerator];
10269 Entity* target = nil;
10270 while ((target = [[targetEnum nextObject] weakRefUnderlyingObject])) {
10271 // can't fire defensively at cloaked ships
10272 if ([target scanClass] == CLASS_NO_DRAW || [(ShipEntity*)target isCloaked] || [target energy] <= 0.0) {
10273 [self removeDefenseTarget:target];
10274 } else {
10275 double range = [self rangeToSecondaryTarget:target];
10276 if (range < weaponRange) {
10277 return [self fireDirectLaserShotAt:target];
10278 } else if (range > scannerRange) {
10279 [self removeDefenseTarget:target];
10280 }
10281 }
10282 }
10283 return NO;
10284}
10285
10286- (BOOL)fireDirectLaserShotAt:(Entity*)my_target
10287{
10288 GLfloat hit_at_range;
10289 double range_limit2 = weaponRange * weaponRange;
10290 Vector r_pos;
10291
10292 r_pos = vector_normal_or_zbasis([self vectorTo:my_target]);
10293
10295
10296 GLfloat acc_factor = (10.0 - accuracy) * 0.001;
10297
10298 q_laser.x += acc_factor * (randf() - 0.5); // randomise aim a little (+/- 0.005 at accuracy 0, never miss at accuracy 10)
10299 q_laser.y += acc_factor * (randf() - 0.5);
10300 q_laser.z += acc_factor * (randf() - 0.5);
10301 quaternion_normalize(&q_laser);
10302
10303 Quaternion q_save = orientation; // save rotation
10304 orientation = q_laser; // face in direction of laser
10305 // weapon offset for thargoid lasers is always zero
10306 ShipEntity* victim = [UNIVERSE firstShipHitByLaserFromShip:self inDirection:WEAPON_FACING_FORWARD offset:kZeroVector gettingRangeFound:&hit_at_range];
10307 [self setShipHitByLaser:victim];
10308 orientation = q_save; // restore rotation
10309
10311
10312 // do special effects laser line
10313 OOLaserShotEntity* shot = [OOLaserShotEntity laserFromShip:self direction:WEAPON_FACING_FORWARD offset:kZeroVector];
10314 [shot setColor:laser_color];
10315 [shot setScanClass:CLASS_NO_DRAW];
10316 [shot setPosition:position];
10317 [shot setOrientation:q_laser];
10318 [shot setVelocity:vel];
10319
10320 if (victim != nil) {
10322 if (subent != nil && [victim isFrangible]) {
10323 // do 1% bleed-through damage...
10324 [victim takeEnergyDamage:0.01 * weapon_damage from:self becauseOf:self weaponIdentifier:[[self weaponTypeForFacing:WEAPON_FACING_FORWARD strict:YES] identifier]];
10325 victim = subent;
10326 }
10327
10328 if (hit_at_range * hit_at_range < range_limit2) {
10329 [victim takeEnergyDamage:weapon_damage from:self becauseOf:self weaponIdentifier:[[self weaponTypeForFacing:WEAPON_FACING_FORWARD strict:YES] identifier]]; // a very palpable hit
10330
10331 [shot setRange:hit_at_range];
10333 HPVector flash_pos = HPvector_add([shot position], vectorToHPVector(vector_multiply_scalar(vd, hit_at_range)));
10334 [UNIVERSE addLaserHitEffectsAt:flash_pos against:victim damage:weapon_damage color:laser_color];
10335 }
10336 }
10337
10338 [UNIVERSE addEntity:shot];
10339
10340 [self resetShotTime];
10341
10342 return YES;
10343}
10344
10345- (NSArray*)laserPortOffset:(OOWeaponFacing)direction
10346{
10347 NSArray* laserPortOffset = nil;
10348 switch (direction) {
10350 case WEAPON_FACING_NONE:
10351 laserPortOffset = forwardWeaponOffset;
10352 break;
10353
10354 case WEAPON_FACING_AFT:
10355 laserPortOffset = aftWeaponOffset;
10356 break;
10357
10358 case WEAPON_FACING_PORT:
10359 laserPortOffset = portWeaponOffset;
10360 break;
10361
10363 laserPortOffset = starboardWeaponOffset;
10364 break;
10365 }
10366 return laserPortOffset;
10367}
10368
10369- (BOOL)fireLaserShotInDirection:(OOWeaponFacing)direction weaponIdentifier:(NSString*)weaponIdentifier
10370{
10371 double range_limit2 = weaponRange * weaponRange;
10372 GLfloat hit_at_range;
10373 NSUInteger i, barrels;
10375 NSArray* laserPortOffsets = [self laserPortOffset:direction];
10376 OOLaserShotEntity* shot = nil;
10377
10378 barrels = [laserPortOffsets count];
10379 NSMutableArray* shotEntities = [NSMutableArray arrayWithCapacity:barrels];
10380
10381 GLfloat effective_damage = weapon_damage;
10382 if (barrels > 1 && !_multiplyWeapons) {
10383 // then divide the shot power between the shots
10384 effective_damage /= (GLfloat)barrels;
10385 }
10386
10387 for (i = 0; i < barrels; i++) {
10388 Vector laserPortOffset = [laserPortOffsets oo_vectorAtIndex:i];
10389
10390 last_shot_time = [UNIVERSE getTime];
10391
10392 ShipEntity* victim = [UNIVERSE firstShipHitByLaserFromShip:self inDirection:direction offset:laserPortOffset gettingRangeFound:&hit_at_range];
10393 [self setShipHitByLaser:victim];
10394
10395 shot = [OOLaserShotEntity laserFromShip:self direction:direction offset:laserPortOffset];
10396 if ([self isPlayer]) {
10397 [shotEntities addObject:shot];
10398 }
10399
10400 [shot setColor:laser_color];
10401 [shot setScanClass:CLASS_NO_DRAW];
10402 [shot setVelocity:vel];
10403
10404 if (victim != nil) {
10405 [self adjustMissedShots:-1];
10406 if ([self isPlayer]) {
10407 [PLAYER addRoleForAggression:victim];
10408 }
10409
10410 /* CRASH in [victim->sub_entities containsObject:subent] here (1.69, OS X/x86).
10411 Analysis: Crash is in _freedHandler called from CFEqual, indicating either a dead
10412 object in victim->sub_entities or dead victim->subentity_taking_damage. I suspect
10413 the latter. Probable solution: dying subentities must cause parent to clean up
10414 properly. This was probably obscured by the entity recycling scheme in the past.
10415 Fix: made subentity_taking_damage a weak reference accessed via a method.
10416 -- Ahruman 20070706, 20080304
10417 */
10419 if (subent != nil && [victim isFrangible]) {
10420 // do 1% bleed-through damage...
10421 [victim takeEnergyDamage:0.01 * effective_damage from:self becauseOf:self weaponIdentifier:weaponIdentifier];
10422 victim = subent;
10423 }
10424
10425 if (hit_at_range * hit_at_range < range_limit2) {
10426 [victim takeEnergyDamage:effective_damage from:self becauseOf:self weaponIdentifier:weaponIdentifier]; // a very palpable hit
10427
10428 [shot setRange:hit_at_range];
10430 HPVector flash_pos = HPvector_add([shot position], vectorToHPVector(vector_multiply_scalar(vd, hit_at_range)));
10431 [UNIVERSE addLaserHitEffectsAt:flash_pos against:victim damage:effective_damage color:laser_color];
10432 }
10433 } else {
10434 [self adjustMissedShots:+1];
10435
10436 // shot missed
10437 if (![self isCloaked]) {
10438 victim = [self primaryTarget];
10439 if ([victim isShip]) // it might not be - fixes crash bug
10440 {
10441
10442 /* player currently gets a bit of an advantage here if
10443 * they ambush without having their target actually
10444 * targeted. Though in those circumstances they
10445 * shouldn't be missing their first shot anyway. */
10446 if (dot_product(vector_forward_from_quaternion([shot orientation]), vector_normal([self vectorTo:victim])) > 0.995) {
10447 /* plausibly aimed at target. Allows reaction
10448 * before attacker actually hits. But we need to
10449 * be able to distinguish in AI from ATTACKED so
10450 * that ships in combat aren't bothered by
10451 * amateurs. So should only respond to
10452 * ATTACKER_MISSED if not already fighting */
10453 if ([self isPlayer]) {
10454 [PLAYER addRoleForAggression:victim];
10455 }
10456 [victim setPrimaryAggressor:self];
10457 [victim setFoundTarget:self];
10458 [victim reactToAIMessage:@"ATTACKER_MISSED" context:@"attacker narrowly misses"];
10459 [victim doScriptEvent:OOJSID("shipBeingAttackedUnsuccessfully") withArgument:self];
10460 }
10461 }
10462 }
10463 }
10464
10465 [UNIVERSE addEntity:shot];
10466 }
10467
10468 if ([self isPlayer]) {
10469 [(PlayerEntity*)self setLastShot:shotEntities];
10470 }
10471
10472 [self resetShotTime];
10473
10474 return YES;
10475}
10476
10477- (void)adjustMissedShots:(int)delta
10478{
10479 if ([self isSubEntity]) {
10480 [[self owner] adjustMissedShots:delta];
10481 } else {
10482 _missed_shots += delta;
10483 if (_missed_shots < 0) {
10484 _missed_shots = 0;
10485 }
10486 }
10487}
10488
10490{
10491 if ([self isSubEntity]) {
10492 return [[self owner] missedShots];
10493 } else {
10494 return _missed_shots;
10495 }
10496}
10497
10499{
10500 Vector offset = {
10501 randf() * (boundingBox.max.x - boundingBox.min.x) + boundingBox.min.x,
10502 randf() * (boundingBox.max.y - boundingBox.min.y) + boundingBox.min.y,
10503 randf() * boundingBox.max.z + boundingBox.min.z // rear section only
10504 };
10506
10507 float w = boundingBox.max.x - boundingBox.min.x;
10508 float h = boundingBox.max.y - boundingBox.min.y;
10509 float m = (w < h) ? 0.25 * w : 0.25 * h;
10510
10511 float sz = m * (1 + randf() + randf()); // half minimum dimension on average
10512
10514
10515 OOColor* color = [OOColor colorWithHue:0.08 + 0.17 * randf() saturation:1.0 brightness:1.0 alpha:1.0];
10516
10517 OOSparkEntity* spark = [[OOSparkEntity alloc] initWithPosition:origin
10518 velocity:vel
10519 duration:2.0 + 3.0 * randf()
10520 size:sz
10521 color:color];
10522
10523 [spark setOwner:self];
10524 [UNIVERSE addEntity:spark];
10525 [spark release];
10526
10528}
10529
10530- (void)considerFiringMissile:(double)delta_t
10531{
10532 int missile_chance = 0;
10533 int rhs = 3.2 / delta_t;
10534 if (rhs)
10535 missile_chance = 1 + (ranrot_rand() % rhs);
10536
10537 double hurt_factor = 16 * pow(energy / maxEnergy, 4.0);
10538 if (missiles > missile_chance * hurt_factor) {
10539 [self fireMissile];
10540 }
10541}
10542
10544{
10545 Vector start;
10546 // default launching position
10547 start.x = 0.0f; // in the middle
10548 start.y = boundingBox.min.y - 4.0f; // 4m below bounding box
10549 start.z = boundingBox.max.z + 1.0f; // 1m ahead of bounding box
10550
10551 // custom launching position
10552 start = [shipinfoDictionary oo_vectorForKey:@"missile_launch_position" defaultValue:start];
10553 if (EXPECT_NOT(_scaleFactor != 1.0)) {
10554 start = vector_multiply_scalar(start, _scaleFactor);
10555 }
10556
10557 if (start.x == 0.0f && start.y == 0.0f && start.z <= 0.0f) // The kZeroVector as start is illegal also.
10558 {
10559 OOLog(@"ship.missileLaunch.invalidPosition", @"***** ERROR: The missile_launch_position defines a position %@ behind the %@. In future versions such missiles may explode on launch because they have to travel through the ship.", VectorDescription(start), self);
10560 start.x = 0.0f;
10561 start.y = boundingBox.min.y - 4.0f;
10562 start.z = boundingBox.max.z + 1.0f;
10563 }
10564 return start;
10565}
10566
10568{
10569 return [self fireMissileWithIdentifier:nil andTarget:[self primaryTarget]];
10570}
10571
10572- (ShipEntity*)fireMissileWithIdentifier:(NSString*)identifier andTarget:(Entity*)target
10573{
10574 // both players and NPCs!
10575 //
10576 ShipEntity* missile = nil;
10577 ShipEntity* target_ship = nil;
10578
10579 Vector vel;
10580 Vector start, v_eject;
10581
10582 if ([UNIVERSE getTime] < missile_launch_time)
10583 return nil;
10584
10585 start = [self missileLaunchPosition];
10586
10587 double throw_speed = 250.0f;
10588
10589 if ((missiles <= 0) || (target == nil) || ([target scanClass] == CLASS_NO_DRAW)) // no missile lock!
10590 return nil;
10591
10592 if ([target isShip]) {
10593 target_ship = (ShipEntity*)target;
10594 if ([target_ship isCloaked]) {
10595 return nil;
10596 }
10597 // missile fire requires being in scanner range
10599 return nil;
10600 }
10601 if (![self hasMilitaryScannerFilter] && [target_ship isJammingScanning]) {
10602 return nil;
10603 }
10604 }
10605
10606 unsigned i;
10607 if (identifier == nil) {
10608 // use a random missile from the list
10609 i = floor(randf() * (double)missiles);
10610 identifier = [missile_list[i] identifier];
10611 missile = [UNIVERSE newShipWithRole:identifier];
10612 if (EXPECT_NOT(missile == nil)) // invalid missile role.
10613 {
10614 // remove that invalid missile role from the missiles list.
10615 while (++i < missiles)
10616 missile_list[i - 1] = missile_list[i];
10617 missiles--;
10618 }
10619 } else
10620 missile = [UNIVERSE newShipWithRole:identifier];
10621
10622 if (EXPECT_NOT(missile == nil))
10623 return nil;
10624
10625 // By definition, the player will always have the specified missile.
10626 // What if the NPC didn't actually have the specified missile to begin with?
10627 if (!isPlayer && ![self removeExternalStore:[OOEquipmentType equipmentTypeWithIdentifier:identifier]]) {
10628 [missile release];
10629 return nil;
10630 }
10631
10632 double mcr = missile->collision_radius;
10633 v_eject = vector_normal(start);
10634 vel = kZeroVector; // starting velocity
10635
10636 // check if start is within bounding box...
10637 while ((start.x > boundingBox.min.x - mcr) && (start.x < boundingBox.max.x + mcr) && (start.y > boundingBox.min.y - mcr) && (start.y < boundingBox.max.y + mcr) && (start.z > boundingBox.min.z - mcr) && (start.z < boundingBox.max.z + mcr)) {
10638 start = vector_add(start, vector_multiply_scalar(v_eject, mcr));
10639 }
10640
10641 vel = vector_add(vel, vector_multiply_scalar(v_forward, flightSpeed + throw_speed));
10642
10643 Quaternion q1 = [self normalOrientation];
10645
10646 if (isPlayer)
10647 [missile setScanClass:CLASS_MISSILE];
10648
10649 // special cases
10650
10651 // We don't want real missiles in a group. Missiles could become escorts when the group is also used as escortGroup.
10652 if ([missile scanClass] == CLASS_THARGOID) {
10653 if ([self group] == nil)
10654 [self setGroup:[OOShipGroup groupWithName:@"thargoid group"]];
10655
10656 ShipEntity* thisGroupLeader = [_group leader];
10657
10658 if ([thisGroupLeader escortGroup] != _group) // avoid adding tharons to escort groups
10659 {
10660 [missile setGroup:[self group]];
10661 }
10662 }
10663
10664 // is this a submunition?
10665 if (![self isMissileFlagSet])
10666 [missile setOwner:self];
10667 else
10668 [missile setOwner:[self owner]];
10669
10670 // end special cases
10671
10672 [missile setPosition:origin];
10673 [missile addTarget:target];
10676 [missile setVelocity:vel];
10677 [missile setSpeed:150.0f];
10680 missile_launch_time = [UNIVERSE getTime] + missile_load_time; // set minimum launchtime for the next missile.
10681
10682 [UNIVERSE addEntity:missile]; // STATUS_IN_FLIGHT, AI state GLOBAL
10683 [missile release]; // release
10684
10685 // missile lives on after UNIVERSE addEntity
10686 if ([missile isMissile] && [target isShip]) {
10687 [self doScriptEvent:OOJSID("shipFiredMissile") withArgument:missile andArgument:target_ship];
10689 [target_ship doScriptEvent:OOJSID("shipAttackedWithMissile") withArgument:missile andArgument:self];
10690 [target_ship reactToAIMessage:@"INCOMING_MISSILE" context:@"someone's shooting at me!"];
10692 // parity between player &NPCs, only deactivate cloak for missiles
10694 }
10695 } else {
10696 [self doScriptEvent:OOJSID("shipReleasedEquipment") withArgument:missile];
10697 }
10698
10699 return missile;
10700}
10701
10703{
10704 return isMissile; // were we created using fireMissile? (for tracking submunitions and preventing collisions at launch)
10705}
10706
10707- (void)setIsMissileFlag:(BOOL)newValue
10708{
10709 isMissile = !!newValue; // set the isMissile flag, used for tracking submunitions and preventing collisions at launch.
10710}
10711
10713{
10714 return missile_load_time;
10715}
10716
10717- (void)setMissileLoadTime:(OOTimeDelta)newMissileLoadTime
10718{
10719 missile_load_time = fmax(0.0, newMissileLoadTime);
10720}
10721
10722// reactions to ECM that are not dependent on current AI state here
10724{
10725 if (accuracy >= COMBAT_AI_ISNT_AWFUL && missiles > 0 && [[missile_list[0] identifier] isEqualTo:@"EQ_MISSILE"]) {
10726 // if we're being ECMd, and our missiles appear to be standard, and we
10727 // have some combat sense, wait a bit before firing the next one!
10728 missile_launch_time = [UNIVERSE getTime] + fmax(2.0, missile_load_time); // set minimum launchtime for the next missile.
10729 }
10730}
10731
10732// Exposed to AI
10733- (BOOL)fireECM
10734{
10735 if (![self hasECM])
10736 return NO;
10737
10738 OOECMBlastEntity* ecmDevice = [[OOECMBlastEntity alloc] initFromShip:self];
10739 [UNIVERSE addEntity:ecmDevice];
10740 [ecmDevice release];
10741 return YES;
10742}
10743
10745{
10747 return cloaking_device_active; // no changes.
10748
10752 [self doScriptEvent:OOJSID("shipCloakActivated")];
10754}
10755
10757{
10760 [self doScriptEvent:OOJSID("shipCloakDeactivated")];
10761 }
10762}
10763
10765{
10766 if (![self hasCascadeMine])
10767 return NO;
10768 [self setSpeed:maxFlightSpeed + 300];
10769 ShipEntity* bomb = [UNIVERSE newShipWithRole:@"energy-bomb"];
10770 if (bomb == nil)
10771 return NO;
10772
10773 [self removeEquipmentItem:@"EQ_QC_MINE"];
10774
10775 double start = collision_radius + bomb->collision_radius;
10776 Quaternion random_direction;
10777 Vector vel;
10778 HPVector rpos;
10779 double random_roll = randf() - 0.5; // -0.5 to +0.5
10780 double random_pitch = randf() - 0.5; // -0.5 to +0.5
10781 quaternion_set_random(&random_direction);
10782
10784
10785 double eject_speed = -800.0;
10786 vel = vector_multiply_scalar(v_forward, [self flightSpeed] + eject_speed);
10787 eject_speed *= 0.5 * (randf() - 0.5); // -0.25x .. +0.25x
10788 vel = vector_add(vel, vector_multiply_scalar(v_up, eject_speed));
10789 eject_speed *= 0.5 * (randf() - 0.5); // -0.0625x .. +0.0625x
10790 vel = vector_add(vel, vector_multiply_scalar(v_right, eject_speed));
10791
10792 [bomb setPosition:rpos];
10793 [bomb setOrientation:random_direction];
10794 [bomb setRoll:random_roll];
10795 [bomb setPitch:random_pitch];
10796 [bomb setVelocity:vel];
10797 [bomb setScanClass:CLASS_MINE];
10798 [bomb setEnergy:5.0]; // 5 second countdown
10799 [bomb setBehaviour:BEHAVIOUR_ENERGY_BOMB_COUNTDOWN];
10800 [bomb setOwner:self];
10801 [UNIVERSE addEntity:bomb]; // STATUS_IN_FLIGHT, AI state GLOBAL
10802 [bomb release];
10803
10806 }
10807
10808 if (self != PLAYER) // get the heck out of here
10809 {
10810 [self addTarget:bomb];
10811 [self setBehaviour:BEHAVIOUR_FLEE_TARGET];
10812 frustration = 0.0;
10813 }
10814 return YES;
10815}
10816
10818{
10819 ShipEntity* result = nil;
10820 ShipEntity* mainPod = nil;
10821 unsigned n_pods, i;
10822 NSMutableArray* passengers = nil;
10823
10824 /*
10825 CHANGE: both player & NPCs can now launch escape pods in interstellar
10826 space. -- Kaks 20101113
10827 */
10828
10829 // check number of pods aboard -- require at least one.
10830 n_pods = [shipinfoDictionary oo_unsignedIntForKey:@"has_escape_pod"];
10831 if (n_pods > 65)
10832 n_pods = 65; // maximum of 64 passengers.
10833 if (n_pods > 1)
10834 passengers = [NSMutableArray arrayWithCapacity:n_pods - 1];
10835
10836 if (crew) // transfer crew
10837 {
10838 // make sure crew inherit any legalStatus
10839 for (i = 0; i < [crew count]; i++) {
10840 OOCharacter* ch = (OOCharacter*)[crew objectAtIndex:i];
10842 }
10843 mainPod = [self launchPodWithCrew:crew];
10844 if (mainPod) {
10845 result = mainPod;
10846 [self setCrew:nil];
10847 [self setHulk:YES]; // we are without crew now.
10848 }
10849 }
10850
10851 // launch other pods (passengers)
10852 for (i = 1; i < n_pods; i++) {
10853 ShipEntity* passenger = nil;
10854 passenger = [self launchPodWithCrew:[NSArray arrayWithObject:[OOCharacter randomCharacterWithRole:@"passenger" andOriginalSystem:gen_rnd_number()]]];
10855 [passengers addObject:passenger];
10856 }
10857
10858 if (mainPod)
10859 [self doScriptEvent:OOJSID("shipLaunchedEscapePod") withArgument:mainPod andArgument:passengers];
10860
10861 return result;
10862}
10863
10864// This is a documented AI method; do not change semantics. (Note: AIs don't have access to the return value.)
10866{
10867 ShipEntity* jetto = [self dumpCargoItem:nil];
10868 if (jetto != nil) {
10869 return [jetto commodityType];
10870 } else {
10871 return nil;
10872 }
10873}
10874
10875- (ShipEntity*)dumpCargoItem:(OOCommodityType)preferred
10876{
10877 ShipEntity* jetto = nil;
10878 NSUInteger i = 0;
10879
10880 if (([cargo count] > 0) && ([UNIVERSE getTime] - cargo_dump_time > 0.5)) // space them 0.5s or 10m apart
10881 {
10882 if (preferred == nil) {
10883 jetto = [[[cargo objectAtIndex:0] retain] autorelease];
10884 } else {
10885 BOOL found = NO;
10886 for (i = 0; i < [cargo count]; i++) {
10887 if ([[[cargo objectAtIndex:i] commodityType] isEqualToString:preferred]) {
10888 jetto = [[[cargo objectAtIndex:i] retain] autorelease];
10889 found = YES;
10890 break;
10891 }
10892 }
10893 if (found == NO) {
10894 // dump anything
10895 jetto = [[[cargo objectAtIndex:0] retain] autorelease];
10896 i = 0;
10897 }
10898 }
10899 if (jetto != nil) {
10900 [self dumpItem:jetto]; // CLASS_CARGO, STATUS_IN_FLIGHT, AI state GLOBAL
10901 [cargo removeObjectAtIndex:i];
10902 [self broadcastAIMessage:@"CARGO_DUMPED"]; // goes only to 16 nearby ships in range, but that should be enough.
10903 unsigned i;
10904 // only send script event to powered entities
10906 for (i = 0; i < n_scanned_ships; i++) {
10907 ShipEntity* other = scanned_ships[i];
10908 [other doScriptEvent:OOJSID("cargoDumpedNearby") withArgument:jetto andArgument:self];
10909 }
10910 }
10911 }
10912
10913 return jetto;
10914}
10915
10916- (OOCargoType)dumpItem:(ShipEntity*)cargoObj
10917{
10918 if (!cargoObj)
10919 return 0;
10920
10921 ShipEntity* jetto = [UNIVERSE reifyCargoPod:cargoObj];
10922
10923 int result = [jetto cargoType];
10924 AI* jettoAI = nil;
10925 Vector start;
10926
10927 // players get to see their old ship sailing forth, while NPCs run away more efficiently!
10928 // cargo is ejected at higher speed from any ship
10929 double eject_speed = EXPECT_NOT([jetto crew] && [jetto isPlayer]) ? 20.0 : 100.0;
10930 double eject_reaction = -eject_speed * [jetto mass] / [self mass];
10931 double jcr = jetto->collision_radius;
10932
10933 Quaternion jetto_orientation = kIdentityQuaternion;
10934 Vector vel, v_eject, v_eject_normal;
10936 double jetto_roll = 0;
10937 double jetto_pitch = 0;
10938
10939 // default launching position
10940 start.x = 0.0; // in the middle
10941 start.y = 0.0; //
10942 start.z = boundingBox.min.z - jcr; // 1m behind of bounding box
10943
10944 // custom launching position
10945 start = [shipinfoDictionary oo_vectorForKey:@"aft_eject_position" defaultValue:start];
10946
10947 v_eject = vector_normal(start);
10948
10949 // check if start is within bounding box...
10950 while ((start.x > boundingBox.min.x - jcr) && (start.x < boundingBox.max.x + jcr) && (start.y > boundingBox.min.y - jcr) && (start.y < boundingBox.max.y + jcr) && (start.z > boundingBox.min.z - jcr) && (start.z < boundingBox.max.z + jcr)) {
10951 start = vector_add(start, vector_multiply_scalar(v_eject, jcr));
10952 }
10953
10954 v_eject = quaternion_rotate_vector([self normalOrientation], start);
10955 rpos = HPvector_add(rpos, vectorToHPVector(v_eject));
10956 v_eject = vector_normal(v_eject);
10957 v_eject_normal = v_eject;
10958
10959 v_eject.x += (randf() - randf()) / eject_speed;
10960 v_eject.y += (randf() - randf()) / eject_speed;
10961 v_eject.z += (randf() - randf()) / eject_speed;
10962
10964 velocity = vector_add(velocity, vector_multiply_scalar(v_eject, eject_reaction));
10965
10966 [jetto setPosition:rpos];
10967 if ([jetto crew]) // jetto has a crew, so assume it is an escape pod.
10968 {
10969 // orient the pod away from the ship to avoid colliding with it.
10970 jetto_orientation = quaternion_rotation_between(v_eject_normal, kBasisZVector);
10971 } else {
10972 // It is true cargo, let it tumble.
10973 jetto_roll = ((ranrot_rand() % 1024) - 512.0) / 1024.0; // -0.5 to +0.5
10974 jetto_pitch = ((ranrot_rand() % 1024) - 512.0) / 1024.0; // -0.5 to +0.5
10975 quaternion_set_random(&jetto_orientation);
10976 }
10977
10978 [jetto setOrientation:jetto_orientation];
10979 [jetto setRoll:jetto_roll];
10980 [jetto setPitch:jetto_pitch];
10981 [jetto setVelocity:vel];
10982 [jetto setScanClass:CLASS_CARGO];
10984 [UNIVERSE addEntity:jetto]; // STATUS_IN_FLIGHT, AI state GLOBAL
10985
10986 jettoAI = [jetto getAI];
10987 if ([jettoAI hasSuspendedStateMachines]) // check if this was previous scooped cargo.
10988 {
10989 [jetto setThrust:[jetto maxThrust]]; // restore old thrust.
10990 [jetto setOwner:jetto];
10991 [jettoAI exitStateMachineWithMessage:nil]; // exit nullAI.
10992 }
10993 [jetto doScriptEvent:OOJSID("shipWasDumped") withArgument:self];
10994 [self doScriptEvent:OOJSID("shipDumpedCargo") withArgument:jetto];
10995
10996 cargo_dump_time = [UNIVERSE getTime];
10997 return result;
10998}
10999
11001{
11002 // deal with collisions
11003 //
11004 Entity* ent;
11005 ShipEntity* other_ship;
11006
11007 while ([collidingEntities count] > 0) {
11008 // EMMSTRAN: investigate if doing this backwards would be more efficient. (Not entirely obvious, NSArray is kinda funky.) -- Ahruman 2011-02-12
11009 ent = [[[collidingEntities objectAtIndex:0] retain] autorelease];
11010 [collidingEntities removeObjectAtIndex:0];
11011 if (ent) {
11012 if ([ent isShip]) {
11013 other_ship = (ShipEntity*)ent;
11014 [self collideWithShip:other_ship];
11015 } else if ([ent isStellarObject]) {
11016 [self getDestroyedBy:ent damageType:[ent isSun] ? kOODamageTypeHitASun : kOODamageTypeHitAPlanet];
11017 if (self == PLAYER)
11018 [self retain];
11019 } else if ([ent isWormhole]) {
11020 if ([self isPlayer])
11021 [self enterWormhole:(WormholeEntity*)ent];
11022 else
11023 [self enterWormhole:(WormholeEntity*)ent replacing:NO];
11024 }
11025 }
11026 }
11027}
11028
11029- (BOOL)collideWithShip:(ShipEntity*)other
11030{
11031 HPVector hploc;
11032 Vector loc;
11033 double dam1, dam2;
11034
11035 if (!other)
11036 return NO;
11037
11038 ShipEntity* otherParent = [other parentEntity];
11039 BOOL otherIsStation = other == [UNIVERSE station];
11040 // calculate line of centers using centres
11042 loc = HPVectorToVector(hploc);
11043
11044 if ([self canScoop:other]) {
11045 [self scoopIn:other];
11046 return NO;
11047 }
11048 if ([other canScoop:self]) {
11049 [other scoopIn:self];
11050 return NO;
11051 }
11052 if (universalID == NO_TARGET)
11053 return NO;
11054 if (other->universalID == NO_TARGET)
11055 return NO;
11056
11057 // find velocity along line of centers
11058 //
11059 // momentum = mass x velocity
11060 // ke = mass x velocity x velocity
11061 //
11062 GLfloat m1 = mass; // mass of self
11063 GLfloat m2 = [other mass]; // mass of other
11064
11065 // starting velocities:
11066 Vector v, vel1b = [self velocity];
11067
11068 if (otherParent != nil) {
11069 // Subentity
11070 /* TODO: if the subentity is rotating (subentityRotationalVelocity is
11071 not 1 0 0 0) we should calculate the tangential velocity from the
11072 other's position relative to our absolute position and add that in.
11073 */
11074 v = [otherParent velocity];
11075 } else {
11076 v = [other velocity];
11077 }
11078
11079 v = vector_subtract(vel1b, v);
11080
11081 GLfloat v2b = dot_product(v, loc); // velocity of other along loc before collision
11082
11083 GLfloat v1a = sqrt(v2b * v2b * m2 / m1); // velocity of self along loc after elastic collision
11084 if (v2b < 0.0f)
11085 v1a = -v1a; // in same direction as v2b
11086
11087 // are they moving apart at over 1m/s already?
11088 if (v2b < 0.0f) {
11089 if (v2b < -1.0f)
11090 return NO;
11091 else {
11092 position = HPvector_subtract(position, hploc); // adjust self position
11093 v = kZeroVector; // go for the 1m/s solution
11094 }
11095 }
11096
11097 // convert change in velocity into damage energy (KE)
11098 dam1 = m2 * v2b * v2b / 50000000;
11099 dam2 = m1 * v2b * v2b / 50000000;
11100
11101 // calculate adjustments to velocity after collision
11102 Vector vel1a = vector_multiply_scalar(loc, -v1a);
11103 Vector vel2a = vector_multiply_scalar(loc, v2b);
11104
11105 if (magnitude2(v) <= 0.1) // virtually no relative velocity - we must provide at least 1m/s to avoid conjoined objects
11106 {
11107 vel1a = vector_multiply_scalar(loc, -1);
11108 vel2a = loc;
11109 }
11110
11111 // apply change in velocity
11112 if (otherParent != nil) {
11113 [otherParent adjustVelocity:vel2a]; // move the otherParent not the subentity
11114 } else {
11115 [other adjustVelocity:vel2a];
11116 }
11117
11118 [self adjustVelocity:vel1a];
11119
11120 BOOL selfDestroyed = (dam1 > energy);
11121 BOOL otherDestroyed = (dam2 > [other energy]) && !otherIsStation;
11122
11123 if (dam1 > 0.05) {
11124 [self takeScrapeDamage:dam1 from:other];
11125 if (selfDestroyed) // inelastic! - take xplosion velocity damage instead
11126 {
11127 vel2a = vector_multiply_scalar(vel2a, -1);
11128 [other adjustVelocity:vel2a];
11129 }
11130 }
11131
11132 if (dam2 > 0.05) {
11133 if (otherParent != nil && ![otherParent isFrangible]) {
11134 [otherParent takeScrapeDamage:dam2 from:self];
11135 } else {
11136 [other takeScrapeDamage:dam2 from:self];
11137 }
11138
11139 if (otherDestroyed) // inelastic! - take explosion velocity damage instead
11140 {
11141 vel1a = vector_multiply_scalar(vel1a, -1);
11142 [self adjustVelocity:vel1a];
11143 }
11144 }
11145
11146 if (!selfDestroyed && !otherDestroyed) {
11147 float t = 10.0 * [UNIVERSE getTimeDelta]; // 10 ticks
11148
11150 [self setPosition:pos1a];
11151
11152 if (!otherIsStation) {
11153 HPVector pos2a = HPvector_add([other position], vectorToHPVector(vector_multiply_scalar(loc, t * v2b)));
11154 [other setPosition:pos2a];
11155 }
11156 }
11157
11158 // remove self from other's collision list
11159 [[other collisionArray] removeObject:self];
11160
11161 [self doScriptEvent:OOJSID("shipCollided") withArgument:other andReactToAIMessage:@"COLLISION"];
11162 [other doScriptEvent:OOJSID("shipCollided") withArgument:self andReactToAIMessage:@"COLLISION"];
11163
11164 return YES;
11165}
11166
11171
11173{
11174 return vector_add([super velocity], [self thrustVector]);
11175}
11176
11177- (void)setTotalVelocity:(Vector)vel
11178{
11179 [self setVelocity:vector_subtract(vel, [self thrustVector])];
11180}
11181
11182- (void)adjustVelocity:(Vector)xVel
11183{
11184 velocity = vector_add(velocity, xVel);
11185}
11186
11187- (void)addImpactMoment:(Vector)moment fraction:(GLfloat)howmuch
11188{
11190}
11191
11192- (BOOL)canScoop:(ShipEntity*)other
11193{
11194 if (other == nil)
11195 return NO;
11196 if (![self hasCargoScoop])
11197 return NO;
11198 if ([cargo count] >= [self maxAvailableCargoSpace])
11199 return NO;
11200 if (scanClass == CLASS_CARGO)
11201 return NO; // we have no power so we can't scoop
11202 if ([other scanClass] != CLASS_CARGO)
11203 return NO;
11204 if ([other cargoType] == CARGO_NOT_CARGO)
11205 return NO;
11206
11207 if ([other isStation])
11208 return NO;
11209
11211
11212 if (dot_product(v_forward, HPVectorToVector(loc)) < 0.0f)
11213 return NO; // Must be in front of us
11214 if ([self isPlayer] && dot_product(v_up, HPVectorToVector(loc)) > 0.0f)
11215 return NO; // player has to scoop on underside, give more flexibility to NPCs
11216
11217 return YES;
11218}
11219
11220- (void)getTractoredBy:(ShipEntity*)other
11221{
11222 if ([self status] == STATUS_BEING_SCOOPED)
11223 return; // both cargo and ship call this. Act only once.
11224 desired_speed = 0.0;
11225 [self setAITo:@"nullAI.plist"]; // prevent AI from changing status or behaviour.
11226 behaviour = BEHAVIOUR_TRACTORED;
11227 [self setStatus:STATUS_BEING_SCOOPED];
11228 [self addTarget:other];
11229 [self setOwner:other];
11230 // should we make this an all rather than first 16? - CIM
11231 // made it ignore other cargopods and similar at least. - CIM 28/7/2013
11233 unsigned i;
11234 ShipEntity* scooper;
11235 for (i = 0; i < n_scanned_ships; i++) {
11236 scooper = (ShipEntity*)scanned_ships[i];
11237 // 'Dibs!' - Stops other ships from trying to scoop/shoot this cargo.
11238 if (other != scooper && (id)self == [scooper primaryTarget]) {
11240 }
11241 }
11242}
11243
11244- (void)scoopIn:(ShipEntity*)other
11245{
11246 [other getTractoredBy:self];
11247}
11248
11250{
11251}
11252
11253- (void)scoopUp:(ShipEntity*)other
11254{
11255 [self scoopUpProcess:other processEvents:YES processMessages:YES];
11256}
11257
11258- (void)scoopUpProcess:(ShipEntity*)other processEvents:(BOOL)procEvents processMessages:(BOOL)procMessages
11259{
11260 if (other == nil)
11261 return;
11262
11263 OOCommodityType co_type = nil;
11264 OOCargoQuantity co_amount;
11265
11266 // don't even think of trying to scoop if the cargo hold is already full
11267 if (max_cargo && [cargo count] >= [self maxAvailableCargoSpace]) {
11268 [other setStatus:STATUS_IN_FLIGHT];
11269 return;
11270 }
11271
11272 switch ([other cargoType]) {
11273 case CARGO_RANDOM:
11274 co_type = [other commodityType];
11275 co_amount = [other commodityAmount];
11276 break;
11277
11278 case CARGO_SCRIPTED_ITEM: {
11279 // scripting
11280 PlayerEntity* player = PLAYER;
11281 [player setScriptTarget:self];
11282 if (procEvents) {
11283 [other doScriptEvent:OOJSID("shipWasScooped") withArgument:self];
11284 }
11285
11286 if ([other commodityType] != nil) {
11287 co_type = [other commodityType];
11288 co_amount = [other commodityAmount];
11289 // don't show scoop message now, will happen later.
11290 } else {
11291 if (isPlayer && [other showScoopMessage] && procMessages) {
11292 [UNIVERSE clearPreviousMessage];
11293 NSString* shipName = [other displayName];
11294 [UNIVERSE addMessage:OOExpandKey(@"scripted-item-scooped", shipName) forCount:4];
11295 }
11296 [other setCommodityForPod:nil andAmount:0];
11297 co_amount = 0;
11298 co_type = nil;
11299 }
11300 } break;
11301
11302 default:
11303 co_amount = 0;
11304 co_type = nil;
11305 break;
11306 }
11307
11308 /* Bug: docking failed due to NSRangeException while looking for element
11309 NSNotFound of cargo mainfest in -[PlayerEntity unloadCargoPods].
11310 Analysis: bad cargo pods being generated due to
11311 -[Universe commodityForName:] looking in wrong place for names.
11312 Fix 1: fix -[Universe commodityForName:].
11313 Fix 2: catch NSNotFound here and substitute random cargo type.
11314 -- Ahruman 20070714
11315 */
11316 if (co_type == nil && co_amount > 0) {
11317 co_type = [UNIVERSE getRandomCommodity];
11318 co_amount = [UNIVERSE getRandomAmountOfCommodity:co_type];
11319 }
11320
11321 if (co_amount > 0) {
11322 [other setCommodity:co_type andAmount:co_amount]; // belt and braces setting this!
11324
11325 if (isPlayer) {
11326 if ([other crew]) {
11327 if ([other showScoopMessage] && procMessages) {
11328 [UNIVERSE clearPreviousMessage];
11329 unsigned i;
11330 for (i = 0; i < [[other crew] count]; i++) {
11331 OOCharacter* rescuee = [[other crew] objectAtIndex:i];
11332 NSString* characterName = [rescuee name];
11333 if ([rescuee legalStatus]) {
11334 [UNIVERSE addMessage:OOExpandKey(@"scoop-captured-character", characterName) forCount:4.5];
11335 } else if ([rescuee insuranceCredits]) {
11336 [UNIVERSE addMessage:OOExpandKey(@"scoop-rescued-character", characterName) forCount:4.5];
11337 } else {
11338 [UNIVERSE addMessage:DESC(@"scoop-got-slave") forCount:4.5];
11339 }
11340 }
11341 }
11342 if (procEvents) {
11343 [(PlayerEntity*)self playEscapePodScooped];
11344 }
11345 } else {
11346 if ([other showScoopMessage] && procMessages) {
11347 [UNIVERSE clearPreviousMessage];
11348 [UNIVERSE addMessage:[UNIVERSE describeCommodity:co_type amount:co_amount] forCount:4.5];
11349 }
11350 }
11351 }
11352 [cargo insertObject:other atIndex:0]; // places most recently scooped object at eject position
11353 [other setStatus:STATUS_IN_HOLD];
11354 [other performTumble];
11355 [shipAI message:@"CARGO_SCOOPED"];
11356 if (max_cargo && [cargo count] >= [self maxAvailableCargoSpace])
11357 [shipAI message:@"HOLD_FULL"];
11358 }
11359 if (procEvents) {
11360 [self doScriptEvent:OOJSID("shipScoopedOther") withArgument:other]; // always fire, even without commodity.
11361 }
11362
11363 // if shipScoopedOther does something strange to the object, we must
11364 // then remove it from the hold, or it will be over-retained
11365 if ([other status] != STATUS_IN_HOLD) {
11366 if ([cargo containsObject:other]) {
11367 [cargo removeObject:other];
11368 }
11369 }
11370
11371 [[other collisionArray] removeObject:self]; // so it can't be scooped twice!
11372 // make sure other ships trying to scoop it lose it
11373 // probably already happened, but some may have acquired it
11374 // after the scooping started, and they might get stuck in a scooping
11375 // attempt as a result
11377 unsigned i;
11378 ShipEntity* scooper;
11379 for (i = 0; i < n_scanned_ships; i++) {
11380 scooper = (ShipEntity*)scanned_ships[i];
11381 if (self != scooper && (id)other == [scooper primaryTargetWithoutValidityCheck]) {
11383 }
11384 }
11385
11386 [self suppressTargetLost];
11387 [UNIVERSE removeEntity:other];
11388}
11389
11390- (BOOL)cascadeIfAppropriateWithDamageAmount:(double)amount cascadeOwner:(Entity*)owner
11391{
11392 BOOL cascade = NO;
11393 switch ([self scanClass]) {
11394 case CLASS_WORMHOLE:
11395 case CLASS_ROCK:
11396 case CLASS_CARGO:
11397 case CLASS_VISUAL_EFFECT:
11398 case CLASS_BUOY:
11399 // does not normally cascade
11400 if ((fuel > MIN_FUEL) || isStation) {
11401 // we have fuel onboard so we can still go pop, or we are a station which can
11402 } else
11403 break;
11404
11405 case CLASS_STATION:
11406 case CLASS_MINE:
11407 case CLASS_PLAYER:
11408 case CLASS_POLICE:
11409 case CLASS_MILITARY:
11410 case CLASS_THARGOID:
11411 case CLASS_MISSILE:
11412 case CLASS_NOT_SET:
11413 case CLASS_NO_DRAW:
11414 case CLASS_NEUTRAL:
11415 case CLASS_TARGET:
11416 // ...start a chain reaction, if we're dying and have a non-trivial amount of energy.
11417 if (energy < amount && energy > 10 && [self countsAsKill]) {
11418 cascade = YES; // confirm we're cascading, then try to add our cascade to UNIVERSE.
11419 [UNIVERSE addEntity:[OOQuiriumCascadeEntity quiriumCascadeFromShip:self]];
11420 }
11421 break;
11422 // no default thanks, we want the compiler to tell us if we missed a case.
11423 }
11424 return cascade;
11425}
11426
11427- (void)takeEnergyDamage:(double)amount from:(Entity*)ent becauseOf:(Entity*)other weaponIdentifier:(NSString*)weaponIdentifier
11428{
11429 if ([self status] == STATUS_DEAD)
11430 return;
11431 if (amount <= 0.0)
11432 return;
11433
11434 BOOL energyMine = [ent isCascadeWeapon];
11435 BOOL cascade = NO;
11436 if (energyMine) {
11438 }
11439
11440 energy -= amount;
11441 /* Heat increase from energy impacts will never directly cause
11442 * overheating - too easy for missile hits to cause an uncredited
11443 * death by overheating - CIM */
11448 }
11449 }
11450
11451 being_mined = NO;
11452 ShipEntity* hunter = nil;
11453
11454 hunter = [other rootShipEntity];
11455 if (hunter == nil && [other isShip])
11456 hunter = (ShipEntity*)other;
11457
11458 // must check for this before potentially deleting 'other' for cloaking
11459 if ((other) && ([other isShip])) {
11461 }
11462
11463 if (hunter != nil && [self owner] != hunter) // our owner could be the same entity as the one responsible for our taking damage in the case of submunitions
11464 {
11465 if ([hunter isCloaked]) {
11466 [self doScriptEvent:OOJSID("shipBeingAttackedByCloaked") andReactToAIMessage:@"ATTACKED_BY_CLOAKED"];
11467
11468 // lose it!
11469 other = nil;
11470 hunter = nil;
11471 }
11472 } else {
11473 hunter = nil;
11474 }
11475
11476 // if the other entity is a ship note it as an aggressor
11477 if (hunter != nil) {
11478 BOOL iAmTheLaw = [self isPolice];
11479 BOOL uAreTheLaw = [hunter isPolice];
11480
11481 DESTROY(_lastEscortTarget); // we're being attacked, escorts can scramble!
11482
11483 [self setPrimaryAggressor:hunter];
11484 [self setFoundTarget:hunter];
11485
11486 // firing on an innocent ship is an offence
11487 [self broadcastHitByLaserFrom:hunter];
11488
11489 // tell ourselves we've been attacked
11490 if (energy > 0) {
11491 [self respondToAttackFrom:ent becauseOf:hunter];
11492 }
11493
11494 OOShipGroup* group = [self group];
11495 // JSAIs manage group notifications themselves
11496 if (![self hasNewAI]) {
11497 // additionally, tell our group we've been attacked
11498 if (group != nil && group != [hunter group] && !(iAmTheLaw || uAreTheLaw)) {
11499 if ([self isTrader] || [self isEscort]) {
11500 ShipEntity* groupLeader = [group leader];
11501 if (groupLeader != self) {
11502 [groupLeader setFoundTarget:hunter];
11505 // unsetting group leader for carriers can break stuff
11506 }
11507 }
11508 if ([self isPirate]) {
11509 NSEnumerator* groupEnum = nil;
11510 ShipEntity* otherPirate = nil;
11511
11512 for (groupEnum = [group mutationSafeEnumerator]; (otherPirate = [groupEnum nextObject]);) {
11513 if (otherPirate != self && randf() < 0.5) // 50% chance they'll help
11514 {
11515 [otherPirate setFoundTarget:hunter];
11518 }
11519 }
11520 } else if (iAmTheLaw) {
11521 NSEnumerator* groupEnum = nil;
11522 ShipEntity* otherPolice = nil;
11523
11524 for (groupEnum = [group mutationSafeEnumerator]; (otherPolice = [groupEnum nextObject]);) {
11525 if (otherPolice != self) {
11526 [otherPolice setFoundTarget:hunter];
11529 }
11530 }
11531 }
11532 }
11533 }
11534
11535 // if I'm a copper and you're not, then mark the other as an offender!
11536 if (iAmTheLaw && !uAreTheLaw) {
11537 // JSAI's can choose not to do this for friendly fire purposes
11538 if (![self hasNewAI]) {
11539 [hunter markAsOffender:64 withReason:kOOLegalStatusReasonAttackedPolice];
11540 }
11541 }
11542
11543 if ((group != nil && [hunter group] == group) || (iAmTheLaw && uAreTheLaw)) {
11544 // avoid shooting each other
11545 if ([hunter behaviour] == BEHAVIOUR_ATTACK_FLY_TO_TARGET) // avoid me please!
11546 {
11547 [hunter setBehaviour:BEHAVIOUR_ATTACK_FLY_FROM_TARGET];
11549 }
11550 }
11551 }
11552
11553 OOShipDamageType damageType = kOODamageTypeEnergy;
11555 damageType = kOODamageTypeRemoved;
11556 else if (energyMine)
11557 damageType = kOODamageTypeCascadeWeapon;
11558
11559 if (!suppressExplosion) {
11560 [self noteTakingDamage:amount from:other type:damageType];
11561 if (cascade)
11562 energy = 0.0; // explicit set energy to zero in case an oxp raised the energy in previous line.
11563 }
11564
11565 // die if I'm out of energy
11566 if (energy <= 0.0) {
11567 // backup check just in case scripts have reduced energy
11568 if (self != [UNIVERSE station]) {
11569 if (hunter != nil)
11571 [self getDestroyedBy:other damageType:damageType];
11572 }
11573 } else {
11574 // warn if I'm low on energy
11575 if (energy < maxEnergy * 0.25) {
11576 [self doScriptEvent:OOJSID("shipEnergyIsLow") andReactToAIMessage:@"ENERGY_LOW"];
11577 }
11578 if ((energy < maxEnergy * 0.125 || (energy < 64 && energy < amount * 2)) && [self hasEscapePod] && (ranrot_rand() & 3) == 0) // 25% chance he gets to an escape pod
11579 {
11580 [self abandonShip];
11581 }
11582 }
11583}
11584
11586{
11587 BOOL OK = NO;
11588 if ([self isPlayer] && [(PlayerEntity*)self isDocked]) {
11589 OOLog(@"ShipEntity.abandonShip.failed", @"%@", @"Player cannot abandon ship while docked.");
11590 return OK;
11591 }
11592
11593 if (![self hasEscapePod]) {
11594 OOLog(@"ShipEntity.abandonShip.failed", @"Ship abandonment was requested for %@, but this ship does not carry escape pod(s).", self);
11595 return OK;
11596 }
11597
11598 if (EXPECT([self launchEscapeCapsule] != NO_TARGET)) // -launchEscapeCapsule takes care of everything for the player
11599 {
11600 if (![self isPlayer]) {
11601 OK = YES;
11602 // if multiple items providing escape pod, remove all of them (NPC process)
11603 while ([self hasEquipmentItemProviding:@"EQ_ESCAPE_POD"]) {
11604 [self removeEquipmentItem:[self equipmentItemProviding:@"EQ_ESCAPE_POD"]];
11605 }
11606 [self setAITo:@"nullAI.plist"];
11607 behaviour = BEHAVIOUR_IDLE;
11608 frustration = 0.0;
11609 [self setScanClass:CLASS_CARGO]; // we're unmanned now!
11610 thrust = thrust * 0.5;
11611 if (thrust > 5)
11612 thrust = 5; // 5 is the thrust of an escape-capsule
11613 desired_speed = 0.0;
11614 if ([self group])
11615 [self setGroup:nil]; // remove self from group.
11616 if (![self isSubEntity] && [self owner])
11617 [self setOwner:nil]; // unset owner, but not if we are a subent
11618 if ([self hasEscorts]) {
11620 NSEnumerator* escortEnum = nil;
11621 ShipEntity* escort = nil;
11622 // Note: works on escortArray rather than escortEnumerator because escorts may be mutated.
11623 for (escortEnum = [[self escortArray] objectEnumerator]; (escort = [escortEnum nextObject]);) {
11624 // act individually now!
11625 if ([escort group] == escortGroup)
11626 [escort setGroup:nil];
11627 if ([escort owner] == self)
11628 [escort setOwner:escort];
11629 }
11630
11631 // We now have no escorts.
11632 [_escortGroup release];
11633 _escortGroup = nil;
11634 }
11635 }
11636 } else if (EXPECT([self isSubEntity])) {
11637 // may still have launched passenger pods even if no crew
11638 // if multiple items providing escape pod, remove all of them (NPC process)
11639 while ([self hasEquipmentItemProviding:@"EQ_ESCAPE_POD"]) {
11640 [self removeEquipmentItem:[self equipmentItemProviding:@"EQ_ESCAPE_POD"]];
11641 }
11642
11643 } else {
11644 // this shouldn't happen any more!
11645 OOLog(@"ShipEntity.abandonShip.notPossible", @"Ship %@ cannot be abandoned at this time.", self);
11646 }
11647 return OK;
11648}
11649
11650- (void)takeScrapeDamage:(double)amount from:(Entity*)ent
11651{
11652 if ([self status] == STATUS_DEAD)
11653 return;
11654
11655 if ([self status] == STATUS_LAUNCHING || [ent status] == STATUS_LAUNCHING) {
11656 // no collisions during launches please
11657 return;
11658 }
11659
11660 energy -= amount;
11661 [self noteTakingDamage:amount from:ent type:kOODamageTypeScrape];
11662
11663 // oops we hit too hard!!!
11664 if (energy <= 0.0) {
11665 float frag_chance = [ent mass] * 10 / [self mass];
11666 /* impacts from heavier entities produce fragments
11667 * impacts from lighter entities might do but not always
11668 * asteroid-asteroid impacts likely to fragment
11669 * ship-asteroid impacts might, or might just vaporise it
11670 * projectile weapons just get the default chance
11671 */
11672 if (randf() < frag_chance) {
11673 being_mined = YES; // same as using a mining laser
11674 }
11675 if ([ent isShip]) {
11677 }
11678 [self getDestroyedBy:ent damageType:kOODamageTypeScrape];
11679 } else {
11680 // warn if I'm low on energy
11681 if (energy < maxEnergy * 0.25) {
11682 [self doScriptEvent:OOJSID("shipEnergyIsLow") andReactToAIMessage:@"ENERGY_LOW"];
11683 }
11684 }
11685}
11686
11687- (void)takeHeatDamage:(double)amount
11688{
11689 if ([self status] == STATUS_DEAD)
11690 return;
11691
11692 if ([self isSubEntity]) {
11693 ShipEntity* owner = [self owner];
11694 if (![owner isFrangible]) {
11695 return;
11696 }
11697 }
11698
11699 energy -= amount;
11700 throw_sparks = YES;
11701
11702 [self noteTakingDamage:amount from:nil type:kOODamageTypeHeat];
11703
11704 // oops we're burning up!
11705 if (energy <= 0.0) {
11706 [self getDestroyedBy:nil damageType:kOODamageTypeHeat];
11707 } else {
11708 // warn if I'm low on energy
11709 if (energy < maxEnergy * 0.25) {
11710 [self doScriptEvent:OOJSID("shipEnergyIsLow") andReactToAIMessage:@"ENERGY_LOW"];
11711 }
11712 }
11713}
11714
11715- (void)enterDock:(StationEntity*)station
11716{
11717 // throw these away now we're docked...
11718 if (dockingInstructions != nil) {
11719 [dockingInstructions autorelease];
11721 }
11722
11723 [self doScriptEvent:OOJSID("shipWillDockWithStation") withArgument:station];
11724 [self doScriptEvent:OOJSID("shipDockedWithStation") withArgument:station];
11725 [shipAI message:@"DOCKED"];
11726 [station noteDockedShip:self];
11727 [UNIVERSE removeEntity:self];
11728}
11729
11730- (void)leaveDock:(StationEntity*)station
11731{
11732 // This code is never used. Currently npc ships are only launched from the stations launch queue.
11733 if (station == nil)
11734 return;
11735
11736 [station launchShip:self];
11737}
11738
11739- (void)enterWormhole:(WormholeEntity*)w_hole
11740{
11741 [self enterWormhole:w_hole replacing:YES];
11742}
11743
11744- (void)enterWormhole:(WormholeEntity*)w_hole replacing:(BOOL)replacing
11745{
11746 if (w_hole == nil)
11747 return;
11748 if ([self status] == STATUS_ENTERING_WITCHSPACE) {
11749 return; // has already entered a different wormhole
11750 }
11751 // Replacement ships now handled by system repopulator
11752
11753 // MKW 2011.02.27 - Moved here from ShipEntityAI so escorts reliably follow
11754 // mother in all wormhole cases, not just when the ship
11755 // creates the wormhole.
11756 [self addTarget:w_hole];
11757 [self setFoundTarget:w_hole];
11758 [shipAI reactToMessage:@"WITCHSPACE OKAY" context:@"performHyperSpaceExit"]; // must be a reaction, the ship is about to disappear
11759
11760 // CIM 2012.07.22 above only covers those cases where ship expected to leave
11761 if ([[self escortArray] count] > 1) {
11762 // so wormhole escorts anyway if it leaves unexpectedly.
11763 [self wormholeEscorts];
11764 }
11765
11766 if ([self scriptedMisjump]) {
11767 [self setScriptedMisjump:NO];
11769 [self setScriptedMisjumpRange:0.5];
11770 }
11771 [w_hole suckInShip:self]; // removes ship from universe
11772}
11773
11775{
11776 [UNIVERSE addWitchspaceJumpEffectForShip:self];
11777 [shipAI message:@"ENTERED_WITCHSPACE"];
11778
11779 if (![[UNIVERSE sun] willGoNova]) {
11780 // if the sun's not going nova, add a new ship like this one leaving.
11781 [UNIVERSE witchspaceShipWithPrimaryRole:[self primaryRole]];
11782 }
11783
11784 [UNIVERSE removeEntity:self];
11785}
11786
11788{
11789 Quaternion q1;
11792 double d1 = 0.0;
11793
11794 GLfloat min_d1 = [UNIVERSE safeWitchspaceExitDistance];
11795
11796 while (fabs(d1) < min_d1) {
11797 // not scannerRange - has no effect on witchspace exit
11798 d1 = SCANNER_MAX_RANGE * (randf() - randf());
11799 }
11800
11801 HPVector exitposition = [UNIVERSE getWitchspaceExitPosition];
11802 exitposition.x += v1.x * d1; // randomise exit position
11803 exitposition.y += v1.y * d1;
11804 exitposition.z += v1.z * d1;
11805 [self setPosition:exitposition];
11807}
11808
11810{
11811 // all ships exiting witchspace will share the same orientation.
11812 orientation = [UNIVERSE getWitchspaceExitRotation];
11813 flightRoll = 0.0;
11814 stick_roll = 0.0;
11815 flightPitch = 0.0;
11816 stick_pitch = 0.0;
11817 flightYaw = 0.0;
11818 stick_yaw = 0.0;
11819 flightSpeed = 50.0; // constant speed same for all ships
11820 // was a quarter of max speed, so the Anaconda speeds up and most
11821 // others slow down - CIM
11822 // will be overridden if left witchspace via a genuine wormhole
11824 if (![UNIVERSE addEntity:self]) // AI and status get initialised here
11825 {
11826 return NO;
11827 }
11828 [self setStatus:STATUS_EXITING_WITCHSPACE];
11829 [shipAI message:@"EXITED_WITCHSPACE"];
11830
11831 [UNIVERSE addWitchspaceJumpEffectForShip:self];
11832 [self setStatus:STATUS_IN_FLIGHT];
11833 return YES;
11834}
11835
11836- (void)markAsOffender:(int)offence_value
11837{
11838 [self markAsOffender:offence_value withReason:kOOLegalStatusReasonUnknown];
11839}
11840
11841- (void)markAsOffender:(int)offence_value withReason:(OOLegalStatusReason)reason
11842{
11843 if (![self isPolice] && ![self isCloaked] && self != [UNIVERSE station]) {
11844 if ([self isSubEntity]) {
11845 [[self parentEntity] markAsOffender:offence_value withReason:reason];
11846 } else {
11847 if ((scanClass == CLASS_THARGOID || scanClass == CLASS_STATION) && reason != kOOLegalStatusReasonSetup && reason != kOOLegalStatusReasonByScript) {
11848 return; // no non-scripted bounties for thargoids and stations
11849 }
11850
11851 JSContext* context = OOJSAcquireContext();
11852
11853 OOJSVal amountVal = OOJSValueFromDouble(context, (bounty | offence_value) - bounty);
11854
11855 bounty |= offence_value; // can't set the new bounty until the size of the change is known
11856
11857 OOJSVal reasonVal = OOJSValueFromLegalStatusReason(context, reason);
11858
11859 ShipScriptEvent(context, self, "shipBountyChanged", amountVal, reasonVal);
11860
11861 OOJSRelinquishContext(context);
11862 }
11863 }
11864}
11865
11866// Exposed to AI
11868{
11869 OOFlasherEntity* se = nil;
11870 ShipEntity* sub = nil;
11871
11872 _lightsActive = YES;
11873
11874 foreach (se, [self flasherEnumerator]) {
11875 [se setActive:YES];
11876 }
11877 foreach (sub, [self shipSubEntityEnumerator]) {
11879 }
11880}
11881
11882// Exposed to AI
11884{
11885 OOFlasherEntity* se = nil;
11886 ShipEntity* sub = nil;
11887
11888 _lightsActive = NO;
11889
11890 foreach (se, [self flasherEnumerator]) {
11891 [se setActive:NO];
11892 }
11893 foreach (sub, [self shipSubEntityEnumerator]) {
11895 }
11896}
11897
11899{
11900 return _lightsActive;
11901}
11902
11903- (void)setDestination:(HPVector)dest
11904{
11905 _destination = dest;
11906 frustration = 0.0; // new destination => no frustration!
11907}
11908
11909- (void)setEscortDestination:(HPVector)dest
11910{
11911 _destination = dest; // don't reset frustration for escorts.
11912}
11913
11914- (BOOL)canAcceptEscort:(ShipEntity*)potentialEscort
11915{
11916 if (dockingInstructions) // we are busy with docking.
11917 {
11918 return NO;
11919 }
11920 if (scanClass != [potentialEscort scanClass]) // this makes sure that wingman can only select police, thargons only thargoids.
11921 {
11922 return NO;
11923 }
11924 if ([self bounty] == 0 && [potentialEscort bounty] != 0) // clean mothers can only accept clean escorts
11925 {
11926 return NO;
11927 }
11928 if (![self isEscort]) // self is NOT wingman or escort or thargon
11929 {
11930 return [potentialEscort isEscort]; // is wingman or escort or thargon
11931 }
11932 return NO;
11933}
11934
11935- (BOOL)acceptAsEscort:(ShipEntity*)other_ship
11936{
11937 // can't pair with self
11938 if (self == other_ship)
11939 return NO;
11940
11941 // no longer in flight, probably entered wormhole without telling escorts.
11942 if ([self status] != STATUS_IN_FLIGHT)
11943 return NO;
11944
11945 // increased stack depth at which it can accept escorts to avoid rejections at this stage.
11946 // doesn't seem to have any adverse effect for now. - Kaks.
11947 if ([shipAI stackDepth] > 3) {
11948 OOLog(@"ship.escort.reject", @"%@ rejecting escort %@ because AI stack depth is %zu.", self, other_ship, [shipAI stackDepth]);
11949 return NO;
11950 }
11951
11952 if ([self canAcceptEscort:other_ship]) {
11954
11955 if ([escortGroup containsShip:other_ship])
11956 return YES;
11957
11958 // check total number acceptable
11959 // the system's patrols don't have escorts set inside their dictionary, but accept max escorts.
11960 if (_maxEscortCount == 0 && ([self hasPrimaryRole:@"police"] || [self hasPrimaryRole:@"hunter"] || [self hasRole:@"thargoid-mothership"])) {
11962 }
11963
11964 NSUInteger maxEscorts = _maxEscortCount; // never bigger than MAX_ESCORTS.
11965 NSUInteger escortCount = [escortGroup count] - 1; // always 0 or higher.
11966
11967 if (escortCount < maxEscorts) {
11968 [other_ship setGroup:escortGroup];
11969 if ([self group] == nil) {
11970 [self setGroup:escortGroup];
11971 } else if ([self group] != escortGroup)
11972 [[self group] addShip:other_ship];
11973
11974 if (([other_ship maxFlightSpeed] < cruiseSpeed) && ([other_ship maxFlightSpeed] > cruiseSpeed * 0.3)) {
11975 cruiseSpeed = [other_ship maxFlightSpeed] * 0.99;
11976 }
11977
11978 OOLog(@"ship.escort.accept", @"%@ accepting escort %@.", self, other_ship);
11979
11980 [self doScriptEvent:OOJSID("shipAcceptedEscort") withArgument:other_ship];
11981 [other_ship doScriptEvent:OOJSID("escortAccepted") withArgument:self];
11982 [shipAI message:@"ACCEPTED_ESCORT"];
11983 return YES;
11984 } else {
11985 OOLog(@"ship.escort.reject", @"%@ already got max escorts(%zu). Escort rejected: %@.", self, escortCount, other_ship);
11986 }
11987 } else {
11988 OOLog(@"ship.escort.reject", @"%@ failed canAcceptEscort for escort %@.", self, other_ship);
11989 }
11990
11991 return NO;
11992}
11993
11994// Exposed to AI
11996{
11998}
11999
12000/*
12001 NOTE: it's tempting to call refreshEscortPositions from coordinatesForEscortPosition:
12002 as needed, but that would cause unnecessary extra work if the formation
12003 callback itself calls updateEscortFormation.
12004*/
12006{
12007 if (!_escortPositionsValid) {
12008 JSContext* context = OOJSAcquireContext();
12009 OOJSVal result;
12010 OOJSVal args[] = { OOJSValueFromDouble(context, 0), OOJSValueFromDouble(context, _maxEscortCount) };
12011 BOOL OK;
12012
12013 // Reset validity first so updateEscortFormation can be called from the update callback.
12014 _escortPositionsValid = YES;
12015
12016 uint8_t i;
12017 for (i = 0; i < _maxEscortCount; i++) {
12018 args[0] = OOJSValueFromDouble(context, i); // Numbers need not be freed.
12019 result = OOJSUndefinedValue();
12020 OK = [script callMethod:OOJSID("coordinatesForEscortPosition")
12021 inContext:context
12022 withArguments:args
12023 count:sizeof args / sizeof *args
12024 result:&result];
12025
12026 if (OK)
12027 OK = JSValueToVector(context, result, &_escortPositions[i]);
12028 OOJSFreeValue(context, result);
12029
12030 if (!OK)
12031 _escortPositions[i] = kZeroVector;
12032 }
12033
12034 OOJSRelinquishContext(context);
12035 }
12036}
12037
12038- (HPVector)coordinatesForEscortPosition:(unsigned)idx
12039{
12040 /*
12041 This function causes problems with Thargoids: their missiles (aka Thargons) are automatically
12042 added to the escorts group, and when a mother ship dies all thargons will attach themselves
12043 as escorts to the surviving battleships. This can lead to huge escort groups.
12044 TODO: better handling of Thargoid groups:
12045 - put thargons (& all other thargon missiles) in their own non-escort group perhaps?
12046 */
12047
12048 // The _escortPositions array is always MAX_ESCORTS long.
12049 // Kludge: return the same last escort position if we have escorts above MAX_ESCORTS...
12050 idx = MIN(idx, (unsigned)(MAX_ESCORTS - 1));
12051
12052 return HPvector_add(self->position, vectorToHPVector(quaternion_rotate_vector([self normalOrientation], _escortPositions[idx])));
12053}
12054
12055// Exposed to AI
12057{
12058 ShipEntity* escort = nil;
12059 ShipEntity* target = nil;
12060 NSMutableSet* idleEscorts = nil;
12061 unsigned deployCount;
12062
12063 if ([self primaryTarget] == nil || _escortGroup == nil)
12064 return;
12065
12067 NSUInteger escortCount = [escortGroup count] - 1; // escorts minus leader.
12068 if (escortCount == 0)
12069 return;
12070
12071 if ([self group] == nil)
12072 [self setGroup:escortGroup];
12073
12074 if ([self primaryTarget] == [self lastEscortTarget]) {
12075 // already deployed escorts onto this target!
12076 return;
12077 }
12078
12079 [self setLastEscortTarget:[self primaryTarget]];
12080
12081 // Find idle escorts
12082 idleEscorts = [NSMutableSet set];
12083 foreach (escort, [self escortEnumerator]) {
12084 if (![[[escort getAI] name] isEqualToString:@"interceptAI.plist"] && ![escort hasNewAI]) {
12085 [idleEscorts addObject:escort];
12086 } else if ([escort hasNewAI]) {
12087 // JS-based escorts get a help request
12088 [escort doScriptEvent:OOJSID("helpRequestReceived") withArgument:self andArgument:[self primaryTarget]];
12089 }
12090 }
12091
12092 escortCount = [idleEscorts count];
12093 if (escortCount == 0)
12094 return;
12095
12096 deployCount = ranrot_rand() % escortCount + 1;
12097
12098 // Deploy deployCount idle escorts.
12099 target = [self primaryTarget];
12100 foreach (escort, idleEscorts) {
12101 [escort addTarget:target];
12102 [escort setAITo:@"interceptAI.plist"];
12103 [escort doScriptEvent:OOJSID("escortAttack") withArgument:target];
12104
12105 if (--deployCount == 0)
12106 break;
12107 }
12108
12109 [self updateEscortFormation];
12110}
12111
12112// Exposed to AI
12114{
12115 if (![self hasEscorts])
12116 return;
12117
12119 ShipEntity* escort = nil;
12120 ShipEntity* target = [self primaryTarget];
12121 unsigned i = 0;
12122 // Note: works on escortArray rather than escortEnumerator because escorts may be mutated.
12123 foreach (escort, [self escortArray]) {
12124 float delay = i++ * 3.0 + 1.5; // send them off at three second intervals
12125 AI* ai = [escort getAI];
12126
12127 // act individually now!
12128 if ([escort group] == escortGroup)
12129 [escort setGroup:nil];
12130 if ([escort owner] == self)
12131 [escort setOwner:escort];
12132 if (target && [target isStation])
12133 [escort setTargetStation:target];
12134 // JSAI: handles own delay
12135 if (![escort hasNewAI]) {
12136 [escort setAITo:@"dockingAI.plist"];
12137 [ai setState:@"ABORT" afterDelay:delay + 0.25];
12138 }
12139 [escort doScriptEvent:OOJSID("escortDock") withArgument:[NSNumber numberWithFloat:delay]];
12140 }
12141
12142 // We now have no escorts.
12143 [_escortGroup release];
12144 _escortGroup = nil;
12145}
12146
12147- (void)setTargetToNearestStationIncludingHostiles:(BOOL)includeHostiles
12148{
12149 // check if the groupID (parent ship) points to a station...
12150 Entity* mother = [[self group] leader];
12151 if ([mother isStation]) {
12152 [self addTarget:mother];
12153 [self setTargetStation:mother];
12154 return; // head for mother!
12155 }
12156
12157 /*- selects the nearest station it can find -*/
12158 if (!UNIVERSE)
12159 return;
12160 int ent_count = UNIVERSE->n_entities;
12161 Entity** uni_entities = UNIVERSE->sortedEntities; // grab the public sorted list
12162 Entity* my_entities[ent_count];
12163 int i;
12164 int station_count = 0;
12165 for (i = 0; i < ent_count; i++)
12166 if (uni_entities[i]->isStation)
12167 my_entities[station_count++] = [uni_entities[i] retain]; // retained
12168 //
12169 StationEntity *thing = nil, *station = nil;
12170 double range2, nearest2 = SCANNER_MAX_RANGE2 * 1000000.0; // 1000x typical scanner range (25600 km), squared.
12171 for (i = 0; i < station_count; i++) {
12172 thing = (StationEntity*)my_entities[i];
12173 range2 = HPdistance2(position, thing->position);
12174 if (range2 < nearest2 && (includeHostiles || ![thing isHostileTo:self])) {
12175 station = thing;
12176 nearest2 = range2;
12177 }
12178 }
12179 for (i = 0; i < station_count; i++)
12180 [my_entities[i] release]; // released
12181 //
12182 if (station) {
12183 [self addTarget:station];
12184 [self setTargetStation:station];
12185 } else {
12186 [shipAI message:@"NO_STATION_FOUND"];
12187 }
12188}
12189
12190// Exposed to AI
12195
12196// Exposed to AI
12201
12202// Exposed to AI
12204{
12205 StationEntity* system_station = [UNIVERSE station];
12206
12207 if (!system_station) {
12208 [shipAI message:@"NOTHING_FOUND"];
12209 [shipAI message:@"NO_STATION_FOUND"];
12211 [self setTargetStation:nil];
12212 return;
12213 }
12214
12215 if (!system_station->isStation) {
12216 [shipAI message:@"NOTHING_FOUND"];
12217 [shipAI message:@"NO_STATION_FOUND"];
12219 [self setTargetStation:nil];
12220 return;
12221 }
12222
12223 [self addTarget:system_station];
12224 [self setTargetStation:system_station];
12225 return;
12226}
12227
12228- (void)landOnPlanet:(OOPlanetEntity*)planet
12229{
12230 if (planet && [self isShuttle]) {
12231 [planet welcomeShuttle:self];
12232 }
12233 [self doScriptEvent:OOJSID("shipLandedOnPlanet") withArgument:planet andReactToAIMessage:@"LANDED_ON_PLANET"];
12234
12235#ifndef NDEBUG
12236 if ([self reportAIMessages]) {
12237 OOLog(@"planet.collide.shuttleLanded", @"DEBUG: %@ landed on planet %@", self, planet);
12238 }
12239#endif
12240
12241 [UNIVERSE removeEntity:self];
12242}
12243
12244// Exposed to AI
12246{
12247 [[UNIVERSE findEntitiesMatchingPredicate:IsStationPredicate
12248 parameter:nil
12249 inRange:-1
12250 ofEntity:nil]
12251 makeObjectsPerformSelector:@selector(abortDockingForShip:)
12252 withObject:self];
12253}
12254
12255- (NSDictionary*)dockingInstructions
12256{
12257 return dockingInstructions;
12258}
12259
12261{
12262 [[UNIVERSE findShipsMatchingPredicate:HasRolePredicate
12263 parameter:@"tharglet"
12264 inRange:SCANNER_MAX_RANGE
12265 ofEntity:self]
12266 makeObjectsPerformSelector:@selector(sendAIMessage:)
12267 withObject:@"THARGOID_DESTROYED"];
12268}
12269
12270static BOOL AuthorityPredicate(Entity* entity, void* parameter)
12271{
12272 ShipEntity* victim = parameter;
12273
12274 // Select main station, if victim is in aegis
12275 if (entity == [UNIVERSE station] && [victim withinStationAegis]) {
12276 return YES;
12277 }
12278
12279 // Select police units in typical scanner range
12280 if ([entity scanClass] == CLASS_POLICE && HPdistance2([victim position], [entity position]) < SCANNER_MAX_RANGE2) {
12281 return YES;
12282 }
12283
12284 // Reject others
12285 return NO;
12286}
12287
12288- (void)broadcastHitByLaserFrom:(ShipEntity*)aggressor_ship
12289{
12290 /*-- If you're clean, locates all police and stations in range and tells them OFFENCE_COMMITTED --*/
12291 if (!UNIVERSE)
12292 return;
12293 if ([self bounty])
12294 return;
12295 if (!aggressor_ship)
12296 return;
12297
12298 if ((scanClass == CLASS_NEUTRAL) || (scanClass == CLASS_STATION) || (scanClass == CLASS_BUOY) || (scanClass == CLASS_POLICE) || (scanClass == CLASS_MILITARY) || (scanClass == CLASS_PLAYER)) // only for active ships...
12299 {
12300 NSArray* authorities = nil;
12301 ShipEntity* auth = nil;
12302
12303 authorities = [UNIVERSE findShipsMatchingPredicate:AuthorityPredicate
12304 parameter:self
12305 inRange:-1
12306 ofEntity:nil];
12307 foreach (auth, authorities) {
12308 [auth setFoundTarget:aggressor_ship];
12309 [auth doScriptEvent:OOJSID("offenceCommittedNearby") withArgument:aggressor_ship andArgument:self];
12310 [auth reactToAIMessage:@"OFFENCE_COMMITTED" context:@"combat update"];
12311 }
12312 }
12313}
12314
12315- (void)sendMessage:(NSString*)message_text toShip:(ShipEntity*)other_ship withUnpilotedOverride:(BOOL)unpilotedOverride
12316{
12317 if (!other_ship || !message_text)
12318 return;
12319 if (!crew && !unpilotedOverride)
12320 return;
12321
12322 double d2 = HPdistance2(position, [other_ship position]);
12323 if (d2 > scannerRange * scannerRange)
12324 return; // out of comms range
12325
12326 NSString* expandedMessage = OOExpand(message_text); // consistent with broadcast message.
12327
12328 if (other_ship->isPlayer) {
12329 [self setCommsMessageColor];
12330 [(PlayerEntity*)other_ship receiveCommsMessage:expandedMessage from:self];
12331 messageTime = 6.0;
12332 [UNIVERSE resetCommsLogColor];
12333 } else
12334 [other_ship receiveCommsMessage:expandedMessage from:self];
12335}
12336
12337- (void)sendExpandedMessage:(NSString*)message_text toShip:(ShipEntity*)other_ship
12338{
12339 if (!other_ship || !crew)
12340 return; // nobody to receive or send the signal
12341 if ((lastRadioMessage) && (messageTime > 0.0) && [message_text isEqual:lastRadioMessage])
12342 return; // don't send the same message too often
12343 [lastRadioMessage autorelease];
12344 lastRadioMessage = [message_text retain];
12345
12346 double d2 = HPdistance2(position, [other_ship position]);
12347 if (d2 > scannerRange * scannerRange) {
12348 // out of comms range
12349 return;
12350 }
12351
12352 Random_Seed very_random_seed;
12353 very_random_seed.a = rand() & 255;
12354 very_random_seed.b = rand() & 255;
12355 very_random_seed.c = rand() & 255;
12356 very_random_seed.d = rand() & 255;
12357 very_random_seed.e = rand() & 255;
12358 very_random_seed.f = rand() & 255;
12359 seed_RNG_only_for_planet_description(very_random_seed);
12360
12361 NSDictionary* specials = [NSDictionary dictionaryWithObjectsAndKeys:
12362 [self displayName], @"[self:name]",
12363 [other_ship identFromShip:self], @"[target:name]",
12364 nil];
12365 NSString* expandedMessage = OOExpandDescriptionString(OOStringExpanderDefaultRandomSeed(), message_text, specials, nil, nil, kOOExpandNoOptions);
12366
12367 [self sendMessage:expandedMessage toShip:other_ship withUnpilotedOverride:NO];
12368}
12369
12370- (void)broadcastAIMessage:(NSString*)ai_message
12371{
12372 NSString* expandedMessage = OOExpand(ai_message);
12373
12374 [self checkScanner];
12375 unsigned i;
12376 for (i = 0; i < n_scanned_ships; i++) {
12377 ShipEntity* ship = scanned_ships[i];
12378 [[ship getAI] message:expandedMessage];
12379 }
12380}
12381
12382- (void)broadcastMessage:(NSString*)message_text withUnpilotedOverride:(BOOL)unpilotedOverride
12383{
12384 NSString* expandedMessage = OOExpand(message_text); // consistent with broadcast message.
12385
12386 if (!crew && !unpilotedOverride)
12387 return; // nobody to send the signal and no override for unpiloted craft is set
12388
12389 [self checkScanner];
12390 unsigned i;
12391 for (i = 0; i < n_scanned_ships; i++) {
12392 ShipEntity* ship = scanned_ships[i];
12393 if (![ship isPlayer])
12394 [ship receiveCommsMessage:expandedMessage from:self];
12395 }
12396
12397 PlayerEntity* player = PLAYER; // make sure that the player always receives a message when in range
12398 // SCANNER_MAX_RANGE2 because it's the player's scanner range
12399 // which is important
12401 [self setCommsMessageColor];
12402 [player receiveCommsMessage:expandedMessage from:self];
12403 messageTime = 6.0;
12404 [UNIVERSE resetCommsLogColor];
12405 }
12406}
12407
12409{
12410 float hue = 0.0625f * (universalID & 15);
12411 [[UNIVERSE commLogGUI] setTextColor:[OOColor colorWithHue:hue saturation:0.375f brightness:1.0f alpha:1.0f]];
12412 if (scanClass == CLASS_THARGOID)
12413 [[UNIVERSE commLogGUI] setTextColor:[OOColor greenColor]];
12414 if (scanClass == CLASS_POLICE)
12415 [[UNIVERSE commLogGUI] setTextColor:[OOColor cyanColor]];
12416}
12417
12418- (void)receiveCommsMessage:(NSString*)message_text from:(ShipEntity*)other
12419{
12420 // Too complex for AI scripts to handle, JS event only.
12421 [self doScriptEvent:OOJSID("commsMessageReceived") withArgument:message_text andArgument:other];
12422}
12423
12424- (void)commsMessage:(NSString*)valueString withUnpilotedOverride:(BOOL)unpilotedOverride
12425{
12426 Random_Seed very_random_seed;
12427 very_random_seed.a = rand() & 255;
12428 very_random_seed.b = rand() & 255;
12429 very_random_seed.c = rand() & 255;
12430 very_random_seed.d = rand() & 255;
12431 very_random_seed.e = rand() & 255;
12432 very_random_seed.f = rand() & 255;
12433 seed_RNG_only_for_planet_description(very_random_seed);
12434
12435 [self broadcastMessage:valueString withUnpilotedOverride:unpilotedOverride];
12436}
12437
12439{
12440 return being_fined;
12441}
12442
12444{
12445 if (being_fined)
12446 return NO; // can't mark twice
12447 being_fined = ([self legalStatus] > 0);
12448 return being_fined;
12449}
12450
12452{
12453 return ((behaviour == BEHAVIOUR_ATTACK_MINING_TARGET) && ([forward_weapon_type isMiningLaser]));
12454}
12455
12456- (void)interpretAIMessage:(NSString*)ms
12457{
12458 if ([ms hasPrefix:AIMS_AGGRESSOR_SWITCHED_TARGET]) {
12459 // if I'm under attack send a thank-you message to the rescuer
12460 //
12461 NSArray* tokens = ScanTokensFromString(ms);
12462 int switcher_id = [(NSString*)[tokens objectAtIndex:1] intValue]; // Attacker that switched targets.
12463 Entity* switcher = [UNIVERSE entityForUniversalID:switcher_id];
12464 int rescuer_id = [(NSString*)[tokens objectAtIndex:2] intValue]; // New primary target of attacker.
12465 Entity* rescuer = [UNIVERSE entityForUniversalID:rescuer_id];
12466 if ((switcher == [self primaryAggressor]) && (switcher == [self primaryTarget]) && (switcher) && (rescuer) && (rescuer->isShip) && ([self thankedShip] != rescuer) && (scanClass != CLASS_THARGOID)) {
12467 ShipEntity* rescueShip = (ShipEntity*)rescuer;
12468 // ShipEntity* switchingShip = (ShipEntity*)switcher;
12469 if (scanClass == CLASS_POLICE) {
12470 [self sendExpandedMessage:@"[police-thanks-for-assist]" toShip:rescueShip];
12471 [rescueShip setBounty:[rescueShip bounty] * 0.80 withReason:kOOLegalStatusReasonAssistingPolice]; // lower bounty by 20%
12472 } else {
12473 [self sendExpandedMessage:@"[thanks-for-assist]" toShip:rescueShip];
12474 }
12475 [self setThankedShip:rescuer];
12476 }
12477 }
12478}
12479
12480- (BoundingBox)findBoundingBoxRelativeTo:(Entity*)other i:(Vector)i j:(Vector)j k:(Vector)k
12481{
12482 HPVector opv = other ? other->position : position;
12483 return [self findBoundingBoxRelativeToPosition:opv i:i j:j k:k];
12484}
12485
12486// Exposed to AI and legacy scripts.
12487- (void)spawn:(NSString*)roles_number
12488{
12489 NSArray* tokens = ScanTokensFromString(roles_number);
12490 NSString* roleString = nil;
12491 NSString* numberString = nil;
12492 NSUInteger number;
12493
12494 if ([tokens count] != 2) {
12495 OOLog(kOOLogSyntaxAddShips, @"***** Could not spawn: \"%@\" (must be two tokens, role and number)", roles_number);
12496 return;
12497 }
12498
12499 roleString = [tokens oo_stringAtIndex:0];
12500 numberString = [tokens oo_stringAtIndex:1];
12501
12502 number = [numberString intValue];
12503
12504 [self spawnShipsWithRole:roleString count:number];
12505}
12506
12508{
12509 // checks if there are any large masses close by
12510 // since we want to place the space station at least 10km away
12511 // the formula we'll use is K x m / d2 < 1.0
12512 // (m = mass, d2 = distance squared)
12513 // coriolis station is mass 455,223,200
12514 // 10km is 10,000m,
12515 // 10km squared is 100,000,000
12516 // therefore K is 0.22 (approx)
12517
12518 int result = NO_TARGET;
12519
12520 GLfloat k = 0.1;
12521
12522 int ent_count = UNIVERSE->n_entities;
12523 Entity** uni_entities = UNIVERSE->sortedEntities; // grab the public sorted list
12524 ShipEntity* my_entities[ent_count];
12525 int i;
12526
12527 int ship_count = 0;
12528 for (i = 0; i < ent_count; i++)
12529 if ((uni_entities[i]->isShip) && (uni_entities[i] != self))
12530 my_entities[ship_count++] = (ShipEntity*)[uni_entities[i] retain]; // retained
12531 //
12532 for (i = 0; (i < ship_count) && (result == NO_TARGET); i++) {
12533 ShipEntity* ship = my_entities[i];
12535 GLfloat d2 = HPmagnitude2(delta);
12536 if (![ship isPlayer] || ![PLAYER isDocked]) { // player doesn't block if docked
12537 if ((k * [ship mass] > d2) && (d2 < SCANNER_MAX_RANGE2)) // if you go off (typical) scanner from a blocker - it ceases to block
12538 result = [ship universalID];
12539 }
12540 }
12541 for (i = 0; i < ship_count; i++)
12542 [my_entities[i] release]; // released
12543
12544 return result;
12545}
12546
12548{
12549 return trackCloseContacts;
12550}
12551
12552- (void)setTrackCloseContacts:(BOOL)value
12553{
12554 if (value == (BOOL)trackCloseContacts)
12555 return;
12556
12557 trackCloseContacts = value;
12558 [closeContactsInfo release];
12559
12560 if (trackCloseContacts) {
12561 closeContactsInfo = [[NSMutableDictionary alloc] init];
12562 } else {
12564 }
12565}
12566
12567#if OO_SALVAGE_SUPPORT
12568// Never used.
12569- (void)claimAsSalvage
12570{
12571 // Create a bouy and beacon where the hulk is.
12572 // Get the main GalCop station to launch a pilot boat to deliver a pilot to the hulk.
12573 OOLog(@"claimAsSalvage.called", @"claimAsSalvage called on %@ %@", [self name], [self roleSet]);
12574
12575 // Not an abandoned hulk, so don't allow the salvage
12576 if (![self isHulk]) {
12577 OOLog(@"claimAsSalvage.failed.notHulk", @"claimAsSalvage failed because not a hulk");
12578 return;
12579 }
12580
12581 // Set target to main station, and return now if it can't be found
12582 [self setTargetToSystemStation];
12583 if ([self primaryTarget] == nil) {
12584 OOLog(@"claimAsSalvage.failed.noStation", @"claimAsSalvage failed because did not find a station");
12585 return;
12586 }
12587
12588 // Get the station to launch a pilot boat to bring a pilot out to the hulk (use a viper for now)
12589 StationEntity* station = (StationEntity*)[self primaryTarget];
12590 OOLog(@"claimAsSalvage.requestingPilot", @"claimAsSalvage asking station to launch a pilot boat");
12591 [station launchShipWithRole:@"pilot"];
12592 [self setReportAIMessages:YES];
12593 OOLog(@"claimAsSalvage.success", @"claimAsSalvage setting own state machine to capturedShipAI.plist");
12594 [self setAITo:@"capturedShipAI.plist"];
12595}
12596
12597- (void)sendCoordinatesToPilot
12598{
12599 Entity* scan;
12600 ShipEntity *scanShip, *pilot;
12601
12602 n_scanned_ships = 0;
12603 scan = z_previous;
12604 OOLog(@"ship.pilotage", @"searching for pilot boat");
12605 while (scan && (scan->isShip == NO)) {
12606 scan = scan->z_previous; // skip non-ships
12607 }
12608
12609 pilot = nil;
12610 while (scan) {
12611 if (scan->isShip) {
12612 scanShip = (ShipEntity*)scan;
12613
12614 if ([self hasRole:@"pilot"] == YES) {
12615 if ([scanShip primaryTarget] == nil) {
12616 OOLog(@"ship.pilotage", @"found pilot boat with no target, will use this one");
12617 pilot = scanShip;
12618 [pilot setPrimaryRole:@"pilot"];
12619 break;
12620 }
12621 }
12622 }
12623 scan = scan->z_previous;
12624 while (scan && (scan->isShip == NO)) {
12625 scan = scan->z_previous;
12626 }
12627 }
12628
12629 if (pilot != nil) {
12630 OOLog(@"ship.pilotage", @"becoming pilot target and setting AI");
12631 [pilot setReportAIMessages:YES];
12632 [pilot addTarget:self];
12633 [pilot setAITo:@"pilotAI.plist"];
12634 [self reactToAIMessage:@"FOUND_PILOT" context:@"flight update"];
12635 }
12636}
12637
12638- (void)pilotArrived
12639{
12640 [self setHulk:NO];
12641 [self reactToAIMessage:@"PILOT_ARRIVED" context:@"flight update"];
12642}
12643#endif
12644
12645#ifdef OO_DEBUG_MONITOR_ENABLED
12646- (void)dumpSelfState
12647{
12648 NSMutableArray* flags = nil;
12649 NSString* flagsString = nil;
12650
12651 [super dumpSelfState];
12652
12653 OOLog(@"dumpState.shipEntity", @"Type: %@", [self shipDataKey]);
12654 OOLog(@"dumpState.shipEntity", @"Name: %@", name);
12655 OOLog(@"dumpState.shipEntity", @"Display Name: %@", [self displayName]);
12656 OOLog(@"dumpState.shipEntity", @"Roles: %@", [self roleSet]);
12657 OOLog(@"dumpState.shipEntity", @"Primary role: %@", primaryRole);
12658 OOLog(@"dumpState.shipEntity", @"Script: %@", script);
12659 OOLog(@"dumpState.shipEntity", @"Subentity count: %zu", [self subEntityCount]);
12660 OOLog(@"dumpState.shipEntity", @"Behaviour: %@", OOStringFromBehaviour(behaviour));
12661 id target = [self primaryTarget];
12662 if (target == nil)
12663 target = @"<none>";
12664 OOLog(@"dumpState.shipEntity", @"Target: %@", target);
12665 OOLog(@"dumpState.shipEntity", @"Destination: %@", HPVectorDescription(_destination));
12666 OOLog(@"dumpState.shipEntity", @"Other destination: %@", HPVectorDescription(coordinates));
12667 OOLog(@"dumpState.shipEntity", @"Waypoint count: %u", number_of_navpoints);
12668 OOLog(@"dumpState.shipEntity", @"Desired speed: %g", desired_speed);
12669 OOLog(@"dumpState.shipEntity", @"Thrust: %g", thrust);
12670 if ([self escortCount] != 0)
12671 OOLog(@"dumpState.shipEntity", @"Escort count: %u", [self escortCount]);
12672 OOLog(@"dumpState.shipEntity", @"Fuel: %i", fuel);
12673 OOLog(@"dumpState.shipEntity", @"Fuel accumulator: %g", fuel_accumulator);
12674 OOLog(@"dumpState.shipEntity", @"Missile count: %u", missiles);
12675
12676 if (shipAI != nil && OOLogWillDisplayMessagesInClass(@"dumpState.shipEntity.ai")) {
12677 OOLog(@"dumpState.shipEntity.ai", @"%@", @"AI:");
12679 OOLogIndent();
12680 @try {
12681 [shipAI dumpState];
12682 }
12683 @catch (id exception) {
12684 }
12686 }
12687 OOLog(@"dumpState.shipEntity", @"Accuracy: %g", accuracy);
12688 OOLog(@"dumpState.shipEntity", @"Jink position: %@", VectorDescription(jink));
12689 OOLog(@"dumpState.shipEntity", @"Frustration: %g", frustration);
12690 OOLog(@"dumpState.shipEntity", @"Success factor: %g", success_factor);
12691 OOLog(@"dumpState.shipEntity", @"Shots fired: %u", shot_counter);
12692 OOLog(@"dumpState.shipEntity", @"Time since shot: %g", [self shotTime]);
12693 OOLog(@"dumpState.shipEntity", @"Spawn time: %g (%g seconds ago)", [self spawnTime], [self timeElapsedSinceSpawn]);
12694 if ([self isBeacon]) {
12695 OOLog(@"dumpState.shipEntity", @"Beacon code: %@", [self beaconCode]);
12696 }
12697 OOLog(@"dumpState.shipEntity", @"Hull temperature: %g", ship_temperature);
12698 OOLog(@"dumpState.shipEntity", @"Heat insulation: %g", [self heatInsulation]);
12699
12700 flags = [NSMutableArray array];
12701#define ADD_FLAG_IF_SET(x) \
12702 if (x) { \
12703 [flags addObject:@ #x]; \
12704 }
12705 ADD_FLAG_IF_SET(military_jammer_active);
12706 ADD_FLAG_IF_SET(docking_match_rotation);
12707 ADD_FLAG_IF_SET(pitching_over);
12708 ADD_FLAG_IF_SET(reportAIMessages);
12709 ADD_FLAG_IF_SET(being_mined);
12710 ADD_FLAG_IF_SET(being_fined);
12711 ADD_FLAG_IF_SET(isHulk);
12712 ADD_FLAG_IF_SET(trackCloseContacts);
12713 ADD_FLAG_IF_SET(isNearPlanetSurface);
12714 ADD_FLAG_IF_SET(isFrangible);
12715 ADD_FLAG_IF_SET(cloaking_device_active);
12716 ADD_FLAG_IF_SET(canFragment);
12717 ADD_FLAG_IF_SET([self proximityAlert] != nil);
12718 flagsString = [flags count] ? [flags componentsJoinedByString:@", "] : (NSString*)@"none";
12719 OOLog(@"dumpState.shipEntity", @"Flags: %@", flagsString);
12720}
12721#endif
12722
12724{
12725 return script;
12726}
12727
12728- (NSDictionary*)scriptInfo
12729{
12730 return (scriptInfo != nil) ? scriptInfo : (NSDictionary*)[NSDictionary dictionary];
12731}
12732
12733- (void)overrideScriptInfo:(NSDictionary*)override
12734{
12735 if (scriptInfo == nil)
12736 scriptInfo = [override retain];
12737 else if (override != nil) {
12738 NSMutableDictionary* newInfo = [NSMutableDictionary dictionaryWithDictionary:scriptInfo];
12739 [newInfo addEntriesFromDictionary:override];
12740 [scriptInfo release];
12741 scriptInfo = [newInfo copy];
12742 }
12743}
12744
12746{
12747 return [self rootShipEntity];
12748}
12749
12750- (void)setDemoShip:(OOScalar)rate
12751{
12753 demoRate = rate;
12754 isDemoShip = YES;
12755 [self setPitch:0.0f];
12756 [self setRoll:0.0f];
12757}
12758
12760{
12761 return isDemoShip;
12762}
12763
12764- (void)setDemoStartTime:(OOTimeAbsolute)time
12765{
12766 demoStartTime = time;
12767}
12768
12770{
12771 return demoStartTime;
12772}
12773
12774// *** Script event dispatch.
12775- (void)doScriptEvent:(OOJSPropID)message
12776{
12777 JSContext* context = OOJSAcquireContext();
12778 [self doScriptEvent:message inContext:context withArguments:NULL count:0];
12779 OOJSRelinquishContext(context);
12780}
12781
12782- (void)doScriptEvent:(OOJSPropID)message withArgument:(id)argument
12783{
12784 JSContext* context = OOJSAcquireContext();
12785
12786 OOJSVal value = OOJSValueFromNativeObject(context, argument);
12787 [self doScriptEvent:message inContext:context withArguments:&value count:1];
12788 OOJSFreeValue(context, value);
12789
12790 OOJSRelinquishContext(context);
12791}
12792
12793- (void)doScriptEvent:(OOJSPropID)message
12794 withArgument:(id)argument1
12795 andArgument:(id)argument2
12796{
12797 JSContext* context = OOJSAcquireContext();
12798
12799 OOJSVal argv[2] = { OOJSValueFromNativeObject(context, argument1), OOJSValueFromNativeObject(context, argument2) };
12800 [self doScriptEvent:message inContext:context withArguments:argv count:2];
12801 OOJSFreeValue(context, argv[0]);
12802 OOJSFreeValue(context, argv[1]);
12803
12804 OOJSRelinquishContext(context);
12805}
12806
12807- (void)doScriptEvent:(OOJSPropID)message withArguments:(NSArray*)arguments
12808{
12809 JSContext* context = OOJSAcquireContext();
12810 int i, argc;
12811 OOJSVal* argv = NULL;
12812
12813 // Convert arguments to JS values and make them temporarily un-garbage-collectable.
12814 argc = (int)[arguments count];
12815 if (argc != 0) {
12816 argv = malloc(sizeof *argv * argc);
12817 if (argv != NULL) {
12818 for (i = 0; i != argc; ++i) {
12819 argv[i] = [[arguments objectAtIndex:i] oo_jsValueInContext:context];
12820#if !OOJS_QUICKJS
12821 OOJSAddGCValueRoot(context, &argv[i], "event parameter");
12822#endif
12823 }
12824 } else
12825 argc = 0;
12826 }
12827
12828 [self doScriptEvent:message inContext:context withArguments:argv count:argc];
12829
12830 // Re-garbage-collectibalize (or, with QuickJS, release) the arguments and free the array.
12831 if (argv != NULL) {
12832 for (i = 0; i != argc; ++i) {
12833#if OOJS_QUICKJS
12834 OOJSFreeValue(context, argv[i]);
12835#else
12836 JS_RemoveValueRoot(context, &argv[i]);
12837#endif
12838 }
12839 free(argv);
12840 }
12841
12842 OOJSRelinquishContext(context);
12843}
12844
12845- (void)doScriptEvent:(OOJSPropID)message withArguments:(OOJSVal*)argv count:(int)argc
12846{
12847 JSContext* context = OOJSAcquireContext();
12848 [self doScriptEvent:message inContext:context withArguments:argv count:argc];
12849 OOJSRelinquishContext(context);
12850}
12851
12852- (void)doScriptEvent:(OOJSPropID)message inContext:(JSContext*)context withArguments:(OOJSVal*)argv count:(int)argc
12853{
12854 // This method is a bottleneck so that PlayerEntity can override at one point.
12855 [script callMethod:message inContext:context withArguments:argv count:argc result:NULL];
12856 [aiScript callMethod:message inContext:context withArguments:argv count:argc result:NULL];
12857}
12858
12859- (void)reactToAIMessage:(NSString*)message context:(NSString*)debugContext
12860{
12861 [shipAI reactToMessage:message context:debugContext];
12862}
12863
12864- (void)sendAIMessage:(NSString*)message
12865{
12866 [shipAI message:message];
12867}
12868
12869- (void)doScriptEvent:(OOJSPropID)scriptEvent andReactToAIMessage:(NSString*)aiMessage
12870{
12871 [self doScriptEvent:scriptEvent];
12872 [self reactToAIMessage:aiMessage context:nil];
12873}
12874
12875- (void)doScriptEvent:(OOJSPropID)scriptEvent withArgument:(id)argument andReactToAIMessage:(NSString*)aiMessage
12876{
12877 [self doScriptEvent:scriptEvent withArgument:argument];
12878 [self reactToAIMessage:aiMessage context:nil];
12879}
12880
12881// exposed for shaders; fake alert level
12882// since NPCs don't have torus drive, they're never at condition green
12884{
12885 if ([self status] == STATUS_DOCKED) {
12887 }
12888 if ([self hasHostileTarget] || energy < maxEnergy / 4) {
12889 return ALERT_CONDITION_RED;
12890 }
12892}
12893
12895{
12896 if ([self status] == STATUS_DOCKED) {
12898 }
12899 if ([self hasHostileTarget]) {
12900 return ALERT_CONDITION_RED;
12901 } else {
12902 NSEnumerator* sEnum = [_defenseTargets objectEnumerator];
12903 ShipEntity* ship = nil;
12904 double scanrange2 = scannerRange * scannerRange;
12905 // FIXME: OOWeakSet doesn't implement NSFastEnumeration protocol.
12906 foreach (ship, sEnum) {
12907 if ([ship hasHostileTarget] || ([ship isPlayer] && [PLAYER weaponsOnline])) {
12908 if (HPdistance2([ship position], position) < scanrange2) {
12909 return ALERT_CONDITION_RED;
12910 }
12911 }
12912 }
12913 // also need to check primary target separately
12914 if ([self hasHostileTarget]) {
12915 Entity* ptarget = [self primaryTargetWithoutValidityCheck];
12916 if (ptarget != nil && [ptarget isShip]) {
12917 ship = (ShipEntity*)ptarget;
12918 if ([ship hasHostileTarget] || ([ship isPlayer] && [PLAYER weaponsOnline])) {
12919 if (HPdistance2([ship position], position) < scanrange2 * 1.5625) {
12920 return ALERT_CONDITION_RED;
12921 }
12922 }
12923 }
12924 }
12925 if (_group) {
12926 sEnum = [_group objectEnumerator];
12927 while ((ship = [sEnum nextObject])) {
12928 if ([ship hasHostileTarget] || ([ship isPlayer] && [PLAYER weaponsOnline])) {
12929 if (HPdistance2([ship position], position) < scanrange2) {
12930 return ALERT_CONDITION_RED;
12931 }
12932 }
12933 }
12934 }
12935 if (_escortGroup && _group != _escortGroup) {
12937 while ((ship = [sEnum nextObject])) {
12938 if ([ship hasHostileTarget] || ([ship isPlayer] && [PLAYER weaponsOnline])) {
12939 if (HPdistance2([ship position], position) < scanrange2) {
12940 return ALERT_CONDITION_RED;
12941 }
12942 }
12943 }
12944 }
12945 }
12947}
12948
12949// Exposed to AI and scripts.
12951{
12952}
12953
12954#ifdef OO_DEBUG_MONITOR_ENABLED
12955- (NSString*)descriptionForObjDump
12956{
12957 NSString* desc = [super descriptionForObjDump];
12958 desc = [NSString stringWithFormat:@"%@ mass %g", desc, [self mass]];
12959 if (![self isPlayer]) {
12960 desc = [NSString stringWithFormat:@"%@ AI: %@", desc, [[self getAI] shortDescriptionComponents]];
12961 }
12962 return desc;
12963}
12964#endif
12965
12966@end
12967
12968@implementation Entity (SubEntityRelationship)
12969
12970- (BOOL)isShipWithSubEntityShip:(Entity*)other
12971{
12972 return NO;
12973}
12974
12975- (void)drawSubEntityImmediate:(bool)immediate translucent:(bool)translucent
12976{
12977 // Do nothing.
12978}
12979
12980@end
12981
12982@implementation ShipEntity (SubEntityRelationship)
12983
12984- (BOOL)isShipWithSubEntityShip:(Entity*)other
12985{
12986 assert([self isShip]);
12987
12988 if (![other isShip])
12989 return NO;
12990 if (![other isSubEntity])
12991 return NO;
12992 if ([other owner] != self)
12993 return NO;
12994
12995#ifndef NDEBUG
12996 // Sanity check; this should always be true.
12997 if (![self hasSubEntity:(ShipEntity*)other]) {
12998 OOLogERR(@"ship.subentity.sanityCheck.failed", @"%@ thinks it's a subentity of %@, but the supposed parent does not agree. %@", [other shortDescription], [self shortDescription], @"This is an internal error, please report it.");
12999 [other setOwner:nil];
13000 return NO;
13001 }
13002#endif
13003
13004 return YES;
13005}
13006
13007@end
13008
13009NSDictionary* OODefaultShipShaderMacros(void)
13010{
13011 static NSDictionary* macros = nil;
13012
13013 if (macros == nil) {
13014 macros = [[[ResourceManager materialDefaults] oo_dictionaryForKey:@"ship-prefix-macros" defaultValue:[NSDictionary dictionary]] retain];
13015 }
13016
13017 return macros;
13018}
13019
13020// is this the right place for this function now? - CIM
13021BOOL OOUniformBindingPermitted(NSString* propertyName, id bindingTarget)
13022{
13023 static NSSet* entityWhitelist = nil;
13024 static NSSet* shipWhitelist = nil;
13025 static NSSet* playerShipWhitelist = nil;
13026 static NSSet* visualEffectWhitelist = nil;
13027
13028 if (entityWhitelist == nil) {
13029 NSDictionary* wlDict = [ResourceManager whitelistDictionary];
13030 entityWhitelist = [[NSSet alloc] initWithArray:[wlDict oo_arrayForKey:@"shader_entity_binding_methods"]];
13031 shipWhitelist = [[NSSet alloc] initWithArray:[wlDict oo_arrayForKey:@"shader_ship_binding_methods"]];
13032 playerShipWhitelist = [[NSSet alloc] initWithArray:[wlDict oo_arrayForKey:@"shader_player_ship_binding_methods"]];
13033 visualEffectWhitelist = [[NSSet alloc] initWithArray:[wlDict oo_arrayForKey:@"shader_visual_effect_binding_methods"]];
13034 }
13035
13036 if ([bindingTarget isKindOfClass:[Entity class]]) {
13037 if ([entityWhitelist containsObject:propertyName])
13038 return YES;
13039 if ([bindingTarget isShip]) {
13040 if ([shipWhitelist containsObject:propertyName])
13041 return YES;
13042 }
13043 if ([bindingTarget isPlayerLikeShip]) {
13044 if ([playerShipWhitelist containsObject:propertyName])
13045 return YES;
13046 }
13047 if ([bindingTarget isVisualEffect]) {
13048 if ([visualEffectWhitelist containsObject:propertyName])
13049 return YES;
13050 }
13051 }
13052
13053 return NO;
13054}
13055
13057{
13058 return [weapon_type weaponRange];
13059}
13060
13062{
13063 return weapon == nil || [[weapon identifier] isEqualToString:@"EQ_WEAPON_NONE"];
13064}
#define NO_DRAW_DISTANCE_FACTOR
Definition Entity.h:49
OOEntityStatus
Definition Entity.h:60
OOScanClass OOScanClassFromString(NSString *string) PURE_FUNC
OOScanClass
Definition Entity.h:69
#define SCANNER_MAX_RANGE
Definition Entity.h:53
#define SCANNER_MAX_RANGE2
Definition Entity.h:54
#define ADD_FLAG_IF_SET(x)
OOINLINE void bounding_box_add_vector(BoundingBox *box, Vector vec) ALWAYS_INLINE_FUNC NONNULL_FUNC
Vector OORandomPositionInBoundingBox(BoundingBox bb)
Definition OOVector.m:107
OOINLINE jsval OOJSValueFromLegalStatusReason(JSContext *context, OOLegalStatusReason value)
OOINLINE jsval OOJSValueFromShipDamageType(JSContext *context, OOShipDamageType value)
OOCargoType StringToCargoType(NSString *string) PURE_FUNC
NSString * OOStringFromLegalStatusReason(OOLegalStatusReason reason)
#define gDebugFlags
@ DEBUG_BOUNDING_BOXES
#define OODebugDrawBoundingBox(box)
void OOStandardsDeprecated(NSString *message)
BOOL OOEnforceStandards(void)
OOINLINE float OOLerp(float v0, float v1, float fraction) INLINE_CONST_FUNC
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 OOHPScalar HPdot_product(HPVector first, HPVector second) INLINE_CONST_FUNC
Definition OOHPVector.h:317
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 OOHPScalar HPmagnitude(HPVector vec) INLINE_CONST_FUNC
Definition OOHPVector.h:260
OOINLINE Vector HPVectorToVector(HPVector v) INLINE_CONST_FUNC
Definition OOHPVector.h:175
OOINLINE HPVector make_HPvector(OOHPScalar vx, OOHPScalar vy, OOHPScalar vz) INLINE_CONST_FUNC
Definition OOHPVector.h:149
OOINLINE OOHPScalar HPdistance2(HPVector v1, HPVector v2) INLINE_CONST_FUNC
Definition OOHPVector.h:293
OOINLINE HPVector HPvector_normal(HPVector vec) INLINE_CONST_FUNC
Definition OOHPVector.h:288
OOINLINE HPVector HPvector_normal_or_zbasis(HPVector vec) INLINE_CONST_FUNC
Definition OOHPVector.h:283
OOINLINE HPVector HPvector_add(HPVector a, HPVector b) INLINE_CONST_FUNC
Definition OOHPVector.h:213
HPVector OOHPVectorRandomSpatial(OOHPScalar maxLength)
Definition OOHPVector.m:75
#define HPvector_between(a, b)
Definition OOHPVector.h:83
OOINLINE OOHPScalar HPmagnitude2(HPVector vec) INLINE_CONST_FUNC
Definition OOHPVector.h:255
OOINLINE OOHPScalar HPdistance(HPVector v1, HPVector v2) INLINE_CONST_FUNC
Definition OOHPVector.h:298
OOINLINE HPVector OOHPVectorInterpolate(HPVector a, HPVector b, OOHPScalar where) INLINE_CONST_FUNC
Definition OOHPVector.h:222
#define OOJS_PROFILE_EXIT
#define OOJS_PROFILE_ENTER
jsid OOJSPropID
Definition OOJSPropID.h:31
BOOL JSValueToVector(JSContext *context, jsval value, Vector *outVector) NONNULL_FUNC
Definition OOJSVector.m:341
OOINLINE jsval OOJSValueFromDouble(JSContext *context, double value)
jsval OOJSVal
#define OOJSFreeValue(context, value)
#define OOJSUndefinedValue()
OOINLINE jsval OOJSValueFromNativeObject(JSContext *context, id object)
id OOJSNativeObjectFromJSObject(JSContext *context, JSObject *object)
OOINLINE BOOL OOJSValueToBOOL(JSContext *context, jsval value)
OOINLINE JSContext * OOJSAcquireContext(void)
OOINLINE void OOJSRelinquishContext(JSContext *context)
#define OOJSAddGCValueRoot(context, root, name)
void OOLogPushIndent(void)
Definition OOLogging.m:301
#define OOLogWARN(class, format,...)
Definition OOLogging.h:126
#define OOLogERR(class, format,...)
Definition OOLogging.h:125
void OOLogPopIndent(void)
Definition OOLogging.m:323
BOOL OOLogWillDisplayMessagesInClass(NSString *inMessageClass)
Definition OOLogging.m:136
#define OOLog(class, format,...)
Definition OOLogging.h:84
void OOLogIndent(void)
Definition OOLogging.m:345
#define MIN(A, B)
Definition OOMaths.h:91
GLfloat OOScalar
Definition OOMaths.h:49
#define M_PI
Definition OOMaths.h:54
const OOMatrix kIdentityMatrix
Definition OOMatrix.m:28
HPVector OOHPVectorMultiplyMatrix(HPVector v, OOMatrix m) CONST_FUNC
Definition OOMatrix.m:137
Vector OOVectorMultiplyMatrix(Vector v, OOMatrix m) CONST_FUNC
Definition OOMatrix.m:121
void OOGLPushModelView(void)
void OOGLTranslateModelView(Vector vector)
void OOGLMultModelView(OOMatrix matrix)
OOMatrix OOGLPopModelView(void)
#define OOVerifyOpenGLState()
Definition OOOpenGL.h:133
return self
unsigned count
return nil
Quaternion quaternion_rotation_between(Vector v0, Vector v1) CONST_FUNC
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
Quaternion quaternion_multiply(Quaternion q1, Quaternion q2) CONST_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
void quaternion_set_random(Quaternion *quat) NONNULL_FUNC
Vector vector_right_from_quaternion(Quaternion quat) CONST_FUNC
@ STELLAR_TYPE_MOON
@ STELLAR_TYPE_MINIATURE
@ STELLAR_TYPE_NORMAL_PLANET
@ kOOExpandNoOptions
Random_Seed OOStringExpanderDefaultRandomSeed(void)
NSString * OOExpandDescriptionString(Random_Seed seed, NSString *string, NSDictionary *overrides, NSDictionary *legacyLocals, NSString *systemName, OOExpandOptions options)
#define OOExpand(string,...)
NSMutableArray * ScanTokensFromString(NSString *values)
BOOL ScanVectorFromString(NSString *xyzString, Vector *outVector)
OOINLINE Vector resolveVectorInIJK(Vector v0, Triangle ijk)
Definition OOTriangle.h:58
@ UNIVERSE_MAX_ENTITIES
Definition OOTypes.h:168
@ NO_TARGET
Definition OOTypes.h:169
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_CLOSE_TO_ANY_PLANET
Definition OOTypes.h:55
@ AEGIS_NONE
Definition OOTypes.h:54
@ DETAIL_LEVEL_EXTRAS
Definition OOTypes.h:212
OOLegalStatusReason
Definition OOTypes.h:139
uint64_t OOCreditsQuantity
Definition OOTypes.h:160
uint16_t OOUniversalID
Definition OOTypes.h:165
#define VALID_WEAPON_FACINGS
Definition OOTypes.h:206
int16_t OOSystemID
Definition OOTypes.h:183
OOCargoType
Definition OOTypes.h:60
@ CARGO_RANDOM
Definition OOTypes.h:66
@ CARGO_NOT_CARGO
Definition OOTypes.h:61
@ CARGO_THARGOID
Definition OOTypes.h:65
@ CARGO_SLAVES
Definition OOTypes.h:62
@ CARGO_ALLOY
Definition OOTypes.h:63
@ CARGO_SCRIPTED_ITEM
Definition OOTypes.h:67
@ CARGO_MINERALS
Definition OOTypes.h:64
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
OOCargoFlag
Definition OOTypes.h:99
@ CARGO_FLAG_FULL_CONTRABAND
Definition OOTypes.h:104
@ CARGO_FLAG_FULL_SCARCE
Definition OOTypes.h:102
@ CARGO_FLAG_FULL_PLENTIFUL
Definition OOTypes.h:101
@ CARGO_FLAG_PIRATE
Definition OOTypes.h:105
@ CARGO_FLAG_CANISTERS
Definition OOTypes.h:107
@ CARGO_FLAG_FULL_UNIFORM
Definition OOTypes.h:106
@ CARGO_FLAG_FULL_MEDICAL
Definition OOTypes.h:103
@ CARGO_FLAG_FULL_PASSENGERS
Definition OOTypes.h:108
@ CARGO_FLAG_NONE
Definition OOTypes.h:100
uint8_t OOGovernmentID
Definition OOTypes.h:179
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
OOINLINE Vector vector_add(Vector a, Vector b) INLINE_CONST_FUNC
Definition OOVector.h:195
#define vector_between(a, b)
Definition OOVector.h:74
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
OOINLINE Vector vector_normal_or_fallback(Vector vec, Vector fallback) INLINE_CONST_FUNC
Definition OOVector.h:247
const Vector kZeroVector
Definition OOVector.m:27
OOINLINE bool vector_equal(Vector a, Vector b) INLINE_CONST_FUNC
Definition OOVector.h:232
const Vector kBasisYVector
Definition OOVector.h:46
OOINLINE Vector cross_product(Vector first, Vector second) INLINE_CONST_FUNC
Definition OOVector.h:294
OOINLINE void scale_vector(Vector *outVector, OOScalar factor) ALWAYS_INLINE_FUNC NONNULL_FUNC
Definition OOVector.h:166
OOINLINE OOScalar magnitude2(Vector vec) INLINE_CONST_FUNC
Definition OOVector.h:237
const Vector kBasisZVector
Definition OOVector.h:47
const Vector kBasisXVector
Definition OOVector.h:45
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
OOINLINE Vector vector_normal(Vector vec) INLINE_CONST_FUNC
Definition OOVector.h:270
static GLfloat scripted_color[4]
static BOOL isHitByOctree(Octree_details axialDetails, Octree_details otherDetails, Vector delta, Triangle other_ijk)
static NSString *const kOOLogSyntaxAddShips
#define HYPERSPEED_FACTOR
@ SCOOP_STATUS_FULL_HOLD
@ SCOOP_STATUS_NOT_INSTALLED
@ SCOOP_STATUS_ACTIVE
@ SCOOP_STATUS_OKAY
#define MIN_HYPERSPEED_FACTOR
#define PLAYER
#define PLAYER_MAX_FUEL
#define MIN_FUEL
Definition ShipEntity.h:104
#define INITIAL_SHOT_TIME
Definition ShipEntity.h:102
#define COMBAT_BROADSIDE_IN_RANGE_FACTOR
Definition ShipEntity.h:57
OOEquipmentType * OOWeaponType
Definition ShipEntity.h:164
BOOL isWeaponNone(OOWeaponType weapon)
#define COMBAT_AI_TRACKS_CLOSER
Definition ShipEntity.h:132
#define SHIP_COOLING_FACTOR
Definition ShipEntity.h:63
#define CLOAKING_DEVICE_MIN_ENERGY
Definition ShipEntity.h:50
#define COMBAT_AI_WEAPON_TEMP_READY
Definition ShipEntity.h:119
OOAlertCondition
Definition ShipEntity.h:166
@ ALERT_CONDITION_RED
Definition ShipEntity.h:172
@ ALERT_CONDITION_YELLOW
Definition ShipEntity.h:171
@ ALERT_CONDITION_DOCKED
Definition ShipEntity.h:169
#define MAX_SCAN_NUMBER
Definition ShipEntity.h:99
OOWeaponType OOWeaponTypeFromEquipmentIdentifierStrict(NSString *string) PURE_FUNC
#define COMBAT_BROADSIDE_RANGE_FACTOR
Definition ShipEntity.h:59
#define COMBAT_AI_WEAPON_TEMP_USABLE
Definition ShipEntity.h:120
#define TURRET_SHOT_RANGE
Definition ShipEntity.h:84
#define COMBAT_AI_ISNT_AWFUL
Definition ShipEntity.h:124
#define TURRET_MINIMUM_COS
Definition ShipEntity.h:44
NSDictionary * OODefaultShipShaderMacros(void)
#define SHIP_MIN_CABIN_TEMP
Definition ShipEntity.h:70
#define CLOAKING_DEVICE_START_ENERGY
Definition ShipEntity.h:51
#define MAX_COS
Definition ShipEntity.h:142
#define NPC_MAX_WEAPON_TEMP
Definition ShipEntity.h:116
#define COMBAT_AI_FLEES_BETTER_2
Definition ShipEntity.h:135
#define MILITARY_JAMMER_ENERGY_RATE
Definition ShipEntity.h:53
#define MAX_JUMP_RANGE
Definition ShipEntity.h:109
#define TRACTOR_FORCE
Definition ShipEntity.h:94
#define MAX_ESCORTS
Definition ShipEntity.h:76
#define CLOAKING_DEVICE_ENERGY_RATE
Definition ShipEntity.h:49
#define AIMS_AGGRESSOR_SWITCHED_TARGET
Definition ShipEntity.h:96
#define COMBAT_AI_DOGFIGHTER
Definition ShipEntity.h:130
#define WEAPON_COOLING_FACTOR
Definition ShipEntity.h:115
#define ENTITY_PERSONALITY_MAX
Definition ShipEntity.h:112
GLfloat getWeaponRangeFromType(OOWeaponType weapon_type)
#define SHIP_MAX_CABIN_TEMP
Definition ShipEntity.h:69
#define MILITARY_JAMMER_MIN_ENERGY
Definition ShipEntity.h:54
#define COMBAT_AI_FLEES_BETTER
Definition ShipEntity.h:128
#define TURRET_SHOT_SPEED
Definition ShipEntity.h:82
OOBehaviour
Definition ShipEntity.h:147
#define COMBAT_IN_RANGE_FACTOR
Definition ShipEntity.h:56
#define COMBAT_OUT_RANGE_FACTOR
Definition ShipEntity.h:58
#define SUN_TEMPERATURE
Definition ShipEntity.h:74
#define COMBAT_WEAPON_RANGE_FACTOR
Definition ShipEntity.h:60
#define MAX_TARGETS
Definition ShipEntity.h:38
#define COMBAT_AI_CONFIDENCE_FACTOR
Definition ShipEntity.h:123
#define COMBAT_AI_IS_SMART
Definition ShipEntity.h:126
NSString * OOStringFromBehaviour(OOBehaviour behaviour) CONST_FUNC
#define MAX_COS2
Definition ShipEntity.h:143
OOWeaponType OOWeaponTypeFromEquipmentIdentifierSloppy(NSString *string) PURE_FUNC
#define BASELINE_SHIELD_LEVEL
Definition ShipEntity.h:101
OOShipDamageType
Definition ShipEntity.h:175
#define SHIPENTITY_MAX_MISSILES
Definition ShipEntity.h:79
#define MAX_LANDING_SPEED2
Definition ShipEntity.h:140
#define SHIP_THRUST_FACTOR
Definition ShipEntity.h:46
OOWeaponType OOWeaponTypeFromString(NSString *string) PURE_FUNC
#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
static ShipEntity * doOctreesCollide(ShipEntity *prime, ShipEntity *other)
static GLfloat mascem_color1[4]
#define kMassCharge
static GLfloat neutral_color[4]
static GLfloat cargo_color[4]
static GLfloat hostile_color[4]
static GLfloat missile_color[4]
static GLfloat police_color1[4]
#define kBaseCharge
BOOL OOUniformBindingPermitted(NSString *propertyName, id bindingTarget)
static GLfloat mascem_color2[4]
static GLfloat calcFuelChargeRate(GLfloat myMass)
Definition ShipEntity.m:104
static GLfloat jammed_color[4]
static GLfloat friendly_color[4]
static GLfloat police_color2[4]
#define UNIVERSE
Definition Universe.h:827
#define DESC(key)
Definition Universe.h:832
#define PROXIMITY_AVOID_DISTANCE_FACTOR
Definition Universe.h:101
Entity< OOStellarBody > * lastAegisLock()
Definition AI.h:35
void setOwner:(ShipEntity *ship)
Definition AI.m:175
void exitStateMachineWithMessage:(NSString *message)
Definition AI.m:268
NSString * name()
Definition AI.m:329
void message:(NSString *ms)
Definition AI.m:536
void setState:afterDelay:(NSString *stateName,[afterDelay] NSTimeInterval delay)
Definition AI.m:324
void clearAllData()
Definition AI.m:609
void setState:(NSString *stateName)
Definition AI.m:303
void reactToMessage:context:(NSString *message,[context] NSString *debugContext)
Definition AI.m:363
void setDimensionsAndCorridor:ddc:launching:(BOOL docking,[ddc] BOOL ddc,[launching] BOOL launching)
void setVirtual()
Definition DockEntity.m:189
unsigned throw_sparks
Definition Entity.h:97
BOOL validForAddToUniverse()
Definition Entity.m:195
void wasAddedToUniverse()
Definition Entity.m:489
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
Entity * z_next
Definition Entity.h:118
NSMutableArray * collisionArray()
Definition Entity.m:845
NSMutableArray * collidingEntities
Definition Entity.h:144
void setVelocity:(Vector vel)
Definition Entity.m:703
Entity * z_previous
Definition Entity.h:118
Quaternion orientation
Definition Entity.m:682
unsigned isSubEntity
Definition Entity.m:140
BOOL isSun()
Definition Entity.m:155
void moveForward:(double amount)
Definition Entity.m:796
void setOrientation:(Quaternion quat)
Definition Entity.m:676
void update:(OOTimeDelta delta_t)
Definition Entity.m:850
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
void setOwner:(Entity *ent)
Definition Entity.m:542
BOOL isInSpace()
Definition Entity.m:1033
void orientationChanged()
Definition Entity.m:697
void setScanClass:(OOScanClass sClass)
Definition Entity.m:738
OOEntityStatus status()
Definition Entity.m:733
unsigned isWormhole
Definition Entity.m:175
void drawSubEntityImmediate:translucent:(bool immediate, [translucent] bool translucent)
void setDistanceTravelled:(GLfloat value)
Definition Entity.m:723
GLfloat cam_zero_distance
Definition Entity.h:105
GLfloat distanceTravelled
Definition Entity.m:718
NSString * descriptionComponents()
Definition Entity.m:115
ShipEntity * rootShipEntity()
Definition Entity.m:566
BoundingBox boundingBox
Definition Entity.m:666
unsigned isStation
Definition Entity.m:135
unsigned isPlayer
Definition Entity.m:145
HPVector position
Definition Entity.m:576
void setEnergy:(GLfloat amount)
Definition Entity.m:748
GLfloat no_draw_distance
Definition Entity.h:106
Quaternion normalOrientation()
Definition Entity.m:687
BOOL isStellarObject()
Definition Entity.m:165
Vector velocity
Definition Entity.m:708
ShipEntity * parentEntity()
Definition Entity.m:553
BOOL isPlanet()
Definition Entity.m:150
void takeEnergyDamage:from:becauseOf:weaponIdentifier:(double amount,[from] Entity *ent,[becauseOf] Entity *other,[weaponIdentifier] NSString *weaponIdentifier)
Definition Entity.m:899
Entity * collider
Definition Entity.h:124
Vector vectorTo:(Entity *entity)
Definition Entity.m:603
double speed()
Definition Entity.m:713
OOMatrix rotMatrix
Definition Entity.h:134
id init()
Definition Entity.m:64
Vector relativePosition()
Definition Entity.m:598
void setStatus:(OOEntityStatus stat)
Definition Entity.m:728
id owner()
Definition Entity.m:548
unsigned isSunlit
Definition Entity.m:160
GLfloat mass
Definition Entity.m:671
void setPosition:(HPVector posn)
Definition Entity.m:608
OOMatrix drawRotationMatrix()
Definition Entity.m:808
id fragmentBurstFromEntity:(Entity *entity)
NSString * name()
OOCharacter * characterWithDictionary:(NSDictionary *c_dict)
void setLegalStatus:(int value)
NSDictionary * infoForScripting()
OOCharacter * randomCharacterWithRole:andOriginalSystem:(NSString *c_role,[andOriginalSystem] OOSystemID s)
Definition OOCharacter.m:94
OOColor * cyanColor()
Definition OOColor.m:274
OOColor * colorWithRGBAComponents:(OORGBAComponents components)
Definition OOColor.m:119
OOColor * brightColorWithDescription:(id description)
Definition OOColor.m:202
OOColor * colorWithDescription:(id description)
Definition OOColor.m:135
OOColor * redColor()
Definition OOColor.m:259
OOColor * greenColor()
Definition OOColor.m:264
void getRed:green:blue:alpha:(float *red,[green] float *green,[blue] float *blue,[alpha] float *alpha)
Definition OOColor.m:344
OOColor * colorWithHue:saturation:brightness:alpha:(float hue,[saturation] float saturation,[brightness] float brightness,[alpha] float alpha)
Definition OOColor.m:100
void setBindingTarget:(id< OOWeakReferenceSupport > target)
Definition OODrawable.m:66
void setDrawable:(OODrawable *drawable)
void drawImmediate:translucent:(bool immediate, [translucent] bool translucent)
NSString * conditionScript()
GLfloat weaponShotTemperature()
void addEquipmentWithInfo:(NSArray *itemInfo)
void setMissileRegistryRole:forShip:(NSString *roles,[forShip] NSString *shipKey)
OOColor * weaponColor()
OOCargoQuantity requiredCargoSpace()
NSString * getMissileRegistryRoleForShip:(NSString *shipKey)
OOEquipmentType * equipmentTypeWithIdentifier:(NSString *identifier)
NSArray * allEquipmentTypes()
NSString * identifier()
GLfloat weaponRechargeRate()
id exhaustForShip:withDefinition:andScale:(ShipEntity *ship,[withDefinition] NSArray *definition,[andScale] float scale)
instancetype explosionCloudFromEntity:withSettings:(Entity *entity,[withSettings] NSDictionary *settings)
instancetype explosionCloudFromEntity:withSize:andSettings:(Entity *entity,[withSize] float size,[andSettings] NSDictionary *settings)
instancetype explosionFlashFromEntity:(Entity *entity)
instancetype flasherWithDictionary:(NSDictionary *dictionary)
void rescaleBy:(GLfloat factor)
BOOL callMethod:inContext:withArguments:count:result:(jsid methodID,[inContext] JSContext *context,[withArguments] jsval *argv,[count] intN argc,[result] jsval *outResult)
Definition OOJSScript.m:328
instancetype laserFromShip:direction:offset:(ShipEntity *ship,[direction] OOWeaponFacing direction,[offset] Vector offset)
void setColor:(OOColor *color)
BoundingBox findBoundingBoxRelativeToPosition:ri:rj:rk:selfPosition:si:sj:sk:(Vector opv,[ri] Vector ri,[rj] Vector rj,[rk] Vector rk,[selfPosition] Vector position,[si] Vector si,[sj] Vector sj,[sk] Vector sk)
Definition OOMesh.m:664
void rebindMaterials()
Definition OOMesh.m:530
Octree * octree
Definition OOMesh.m:631
BoundingBox findSubentityBoundingBoxWithPosition:rotMatrix:(Vector position,[rotMatrix] OOMatrix rotMatrix)
Definition OOMesh.m:709
instancetype meshWithName:cacheKey:materialDictionary:shadersDictionary:smooth:shaderMacros:shaderBindingTarget:scaleFactor:cacheWriteable:(NSString *name,[cacheKey] NSString *cacheKey,[materialDictionary] NSDictionary *materialDict,[shadersDictionary] NSDictionary *shadersDict,[smooth] BOOL smooth,[shaderMacros] NSDictionary *macros,[shaderBindingTarget] id< OOWeakReferenceSupport > object,[scaleFactor] float factor,[cacheWriteable] BOOL cacheWriteable)
Definition OOMesh.m:242
instancetype quiriumCascadeFromShip:(ShipEntity *ship)
instancetype ringFromEntity:(Entity *sourceEntity)
id roleSetWithAddedRoleIfNotSet:probability:(NSString *role,[probability] float probability)
Definition OORoleSet.m:197
instancetype roleSetWithString:(NSString *roleString)
Definition OORoleSet.m:42
BOOL hasRole:(NSString *role)
Definition OORoleSet.m:135
NSString * anyRole()
Definition OORoleSet.m:173
id roleSetWithAddedRole:probability:(NSString *role,[probability] float probability)
Definition OORoleSet.m:210
instancetype roleSetWithRole:probability:(NSString *role,[probability] float probability)
Definition OORoleSet.m:47
id roleSetWithRemovedRole:(NSString *role)
Definition OORoleSet.m:223
id jsScriptFromFileNamed:properties:(NSString *fileName,[properties] NSDictionary *properties)
Definition OOScript.m:177
BOOL addShip:(ShipEntity *ship)
void setLeader:(ShipEntity *leader)
NSUInteger count()
NSEnumerator * mutationSafeEnumerator()
instancetype groupWithName:(NSString *name)
Definition OOShipGroup.m:94
NSEnumerator * objectEnumerator()
ShipEntity * leader()
BOOL removeShip:(ShipEntity *ship)
NSDictionary * shipyardInfoForKey:(NSString *key)
OOShipRegistry * sharedRegistry()
id fragmentBurstFromEntity:(Entity *entity)
OOWeakReference * weakSelf
void addObject:(id< OOWeakReferenceSupport > object)
Definition OOWeakSet.m:149
NSArray * allObjects()
Definition OOWeakSet.m:192
NSEnumerator * objectEnumerator()
Definition OOWeakSet.m:144
BOOL containsObject:(id< OOWeakReferenceSupport > object)
Definition OOWeakSet.m:135
void removeObject:(id< OOWeakReferenceSupport > object)
Definition OOWeakSet.m:160
void removeAllObjects()
Definition OOWeakSet.m:209
NSUInteger count()
Definition OOWeakSet.m:129
GLfloat volume()
Definition Octree.m:669
Vector randomPoint()
Definition Octree.m:716
GLfloat isHitByLine:v1:(Vector v0,[v1] Vector v1)
Definition Octree.m:457
void setScriptTarget:(ShipEntity *ship)
void receiveCommsMessage:from:(NSString *message_text, [from] ShipEntity *other)
void adjustTradeInFactorBy:(int value)
NSDictionary * materialDefaults()
NSDictionary * whitelistDictionary()
NSDictionary * dictionaryFromFilesNamed:inFolder:andMerge:(NSString *fileName,[inFolder] NSString *folderName,[andMerge] BOOL mergeFiles)
void landOnPlanet()
void behaviour_fly_to_destination:(double delta_t)
BOOL firePortWeapon:(double range)
void setWeaponEnergy:(float value)
OOWeaponFacingSet weapon_facings
Definition ShipEntity.h:293
BOOL isExplicitlyUnpiloted()
BOOL suppressFlightNotifications()
OOTimeAbsolute last_shot_time
Definition ShipEntity.h:348
void suppressTargetLost()
void behaviour_stop_still:(double delta_t)
void behaviour_evasive_action:(double delta_t)
GLfloat laserHeatLevelAft()
BOOL hasAllEquipment:includeWeapons:whileLoading:(id equipmentKeys,[includeWeapons] BOOL includeWeapons,[whileLoading] BOOL loading)
OOCargoQuantity commodity_amount
Definition ShipEntity.h:353
Vector positionOffsetForShipInRotationToAlignment(ShipEntity *ship, Quaternion q, NSString *align)
void setCommsMessageColor()
BOOL hasScoop()
unsigned suppressExplosion
Definition ShipEntity.h:260
Entity * rememberedShip()
void removeRole:(NSString *role)
NSUInteger passengerCount()
GLfloat weapon_damage
Definition ShipEntity.h:298
void setSuppressExplosion:(BOOL suppress)
OOWeakReference * _targetStation
Definition ShipEntity.h:427
void setBounty:withReasonAsString:(OOCreditsQuantity amount,[withReasonAsString] NSString *reason)
Vector forwardVector()
void enterWitchspace()
void getDestroyedBy:damageType:(Entity *whom,[damageType] OOShipDamageType type)
void setCargo:(NSArray *some_cargo)
unsigned trackCloseContacts
double launch_delay
Definition ShipEntity.h:334
double next_spark_time
Definition ShipEntity.h:373
double missileTrackPrimaryTarget:(double delta_t)
void doScriptEvent:(OOJSPropID message)
NSUInteger turretCount()
BOOL canStillTrackPrimaryTarget()
void setMesh:(OOMesh *mesh)
OOColor * laser_color
Definition ShipEntity.h:218
void setScannerDisplayColor1:(OOColor *color1)
Vector tractor_position
Definition ShipEntity.h:395
BOOL validForAddToUniverse()
unsigned noRocks
Definition ShipEntity.h:270
OOCargoFlag cargo_flag
Definition ShipEntity.h:288
NSComparisonResult ComparePlanetsBySurfaceDistance(id i1, id i2, void *context)
BOOL addEquipmentItem:inContext:(NSString *equipmentKey,[inContext] NSString *context)
void setShipHitByLaser:(ShipEntity *ship)
OOCommodityType commodity_type
Definition ShipEntity.h:352
double trackPrimaryTarget:retreat:(double delta_t,[retreat] BOOL retreat)
BOOL hasMilitaryJammer()
void landOnPlanet:(OOPlanetEntity *planet)
HPVector absoluteTractorPosition()
void setTargetStation:(Entity *targetEntity)
NSMutableArray * cargo
void setLastAegisLock:(Entity< OOStellarBody > *lastAegisLock)
BOOL setUpOneStandardSubentity:asTurret:(NSDictionary *subentDict,[asTurret] BOOL asTurret)
Definition ShipEntity.m:860
void noteLostTarget()
void resumePostProximityAlert()
unsigned isMissile
BOOL isPirate()
OOEquipmentType * selectMissile()
unsigned _lightsActive
Definition ShipEntity.h:271
void decrease_flight_speed:(double delta)
NSArray * spawnShipsWithRole:count:(NSString *role,[count] NSUInteger count)
GLfloat currentAimTolerance()
void behaviour_tractored:(double delta_t)
BOOL isJammingScanning()
void transitionToAegisNone()
OOTimeAbsolute aiScriptWakeTime
Definition ShipEntity.h:213
BOOL hasAutoAI()
void setBounty:withReason:(OOCreditsQuantity amount,[withReason] OOLegalStatusReason reason)
BOOL markForFines()
void refreshEscortPositions()
float maxThrust()
float randomEjectaTemperatureWithMaxFactor:(float factor)
void evasiveAction:(double delta_t)
void addTarget:(Entity *targetEntity)
void setPrimaryAggressor:(Entity *targetEntity)
Vector v_forward
Definition ShipEntity.h:189
float shieldBoostFactor()
unsigned haveStartedJSAI
Definition ShipEntity.h:269
void setUpEscorts()
void noteKilledBy:damageType:(Entity *whom,[damageType] OOShipDamageType type)
int _missed_shots
Definition ShipEntity.h:365
NSArray * allDefenseTargets()
float weaponRechargeRate()
Vector upVector()
void broadcastHitByLaserFrom:(ShipEntity *aggressor_ship)
id primaryTargetWithoutValidityCheck()
void setDesiredSpeed:(double amount)
GLfloat pitch_tolerance
Definition ShipEntity.h:363
NSUInteger defenseTargetCount()
ShipEntity ** scannedShips()
NSString * beaconLabel()
GLfloat stick_pitch
Definition ShipEntity.h:198
void collectBountyFor:(ShipEntity *other)
void behaviour_close_to_broadside_range:(double delta_t)
NSDictionary * shipInfoDictionary()
void removeEquipmentItem:(NSString *equipmentKey)
BOOL markedForFines()
void setTargetToSystemStation()
float hyperspaceSpinTime()
void setUpCargoType:(NSString *cargoString)
Definition ShipEntity.m:937
NSUInteger passengerCapacity()
void setLaserColor:(OOColor *color)
void behaviour_fly_thru_navpoints:(double delta_t)
NSDictionary * scriptInfo
OOColor * scanner_display_color_hostile2
Definition ShipEntity.h:224
BOOL hasAutoWeapons()
OOScript * shipScript()
void setFuel:(OOFuelQuantity amount)
void rescaleBy:writeToCache:(GLfloat factor, [writeToCache] BOOL writeToCache)
void setThankedShip:(Entity *targetEntity)
GLfloat rollToMatchUp:rotating:(Vector up_vec,[rotating] GLfloat match_roll)
void removeTarget:(Entity *targetEntity)
GLfloat scriptedMisjumpRange()
OOTimeAbsolute cargo_dump_time
Definition ShipEntity.h:347
void takeEnergyDamage:from:becauseOf:weaponIdentifier:(double amount, [from] Entity *ent, [becauseOf] Entity *other, [weaponIdentifier] NSString *weaponIdentifier)
void calculateTrackingCurve()
BOOL hasEscorts()
BOOL _escortPositionsValid
Definition ShipEntity.h:458
NSArray * contractListForScripting()
void considerFiringMissile:(double delta_t)
GLfloat frustration
OOWeakReference * _thankedShip
Definition ShipEntity.h:430
OOSystemID destination_system
Definition ShipEntity.h:369
OOWeakReference * _rememberedShip
Definition ShipEntity.h:431
unsigned reportAIMessages
OOWeaponFacing currentWeaponFacing
void manageCollisions()
unsigned isNearPlanetSurface
Definition ShipEntity.h:252
GLfloat rangeToDestination()
unsigned hasScoopMessage
Definition ShipEntity.h:264
void setStatus:(OOEntityStatus stat)
OOTimeAbsolute trackingCurveTimes[4]
Definition ShipEntity.h:439
NSDictionary * dockingInstructions
id initWithKey:definition:(NSString *key,[definition] NSDictionary *dict)
Definition ShipEntity.m:190
OOTimeAbsolute shipAIScriptWakeTime()
void behaviour_attack_broadside_target:leftside:(double delta_t,[leftside] BOOL leftside)
void behaviour_fly_from_destination:(double delta_t)
GLfloat weapon_damage_override
Definition ShipEntity.h:299
NSUInteger equipmentCount()
GLfloat maxFlightRoll()
GLfloat weaponRange
void broadcastEnergyBlastImminent()
ShipEntity * doOctreesCollide(ShipEntity *prime, ShipEntity *other)
int numberOfScannedShips()
void forceAegisCheck()
HPVector coordinatesForEscortPosition:(unsigned idx)
void behaviour_attack_broadside_right:(double delta_t)
BOOL isWeapon()
void behaviour_formation_form_up:(double delta_t)
void behaviour_scripted_ai:(double delta_t)
GLfloat weapon_energy_use
Definition ShipEntity.h:303
uint8_t _maxEscortCount
Definition ShipEntity.h:454
BOOL witchspaceLeavingEffects()
GLfloat afterburner_speed_factor
Definition ShipEntity.h:281
BOOL addEquipmentItem:withValidation:inContext:(NSString *equipmentKey,[withValidation] BOOL validateAddition,[inContext] NSString *context)
void applySticks:(double delta_t)
void behaviour_land_on_planet:(double delta_t)
GLfloat lookingAtSunWithThresholdAngleCos:(GLfloat thresholdAngleCos)
void noteFrustration:(NSString *context)
GLfloat aft_weapon_temp
Definition ShipEntity.h:304
ShipEntity * scanned_ships[MAX_SCAN_NUMBER+1]
Definition ShipEntity.h:401
void setEvasiveJink:(GLfloat z)
unsigned isFrangible
void setRoll:(double amount)
void setThrust:(double amount)
OOAlertCondition alertCondition()
GLfloat _scriptedMisjumpRange
Definition ShipEntity.h:273
GLfloat max_flight_pitch
Definition ShipEntity.h:230
Vector jink
Definition ShipEntity.h:327
NSDictionary * shipinfoDictionary
Definition ShipEntity.h:206
void performTumble()
BOOL collideWithShip:(ShipEntity *other)
ShipEntity * subEntityTakingDamage()
unsigned _showDamage
Definition ShipEntity.h:259
void broadcastThargoidDestroyed()
BOOL hasFuelScoop()
unsigned isWreckage
Definition ShipEntity.h:258
BOOL hasFuelInjection()
OOShipGroup * escortGroup()
BOOL hasOneEquipmentItem:includeWeapons:whileLoading:(NSString *itemKey,[includeWeapons] BOOL includeMissiles,[whileLoading] BOOL loading)
void setSpeed:(double amount)
void takeScrapeDamage:from:(double amount,[from] Entity *ent)
void behaviour_intercept_target:(double delta_t)
BOOL hasMilitaryShieldEnhancer()
OOTimeAbsolute getDemoStartTime()
void setSingleCrewWithRole:(NSString *crewRole)
void switchLightsOn()
void setScannerDisplayColorHostile1:(OOColor *color1)
NSEnumerator * escortEnumerator()
OOEquipmentType * verifiedMissileTypeFromRole:(NSString *role)
unsigned suppressAegisMessages
Definition ShipEntity.h:261
NSString * shipDataKey()
NSMutableArray * _equipment
Definition ShipEntity.h:447
void setTargetToNearestStationIncludingHostiles:(BOOL includeHostiles)
int checkShipsInVicinityForWitchJumpExit()
NSUInteger subIdx()
Definition ShipEntity.m:729
NSUInteger missileCount()
OORoleSet * roleSet
void setGroup:(OOShipGroup *group)
void scoopIn:(ShipEntity *other)
NSString * primaryRole
void applyAttitudeChanges:(double delta_t)
GLfloat laserHeatLevelStarboard()
BOOL fireLaserShotInDirection:weaponIdentifier:(OOWeaponFacing direction,[weaponIdentifier] NSString *weaponIdentifier)
void setSubEntityTakingDamage:(ShipEntity *sub)
GLfloat port_weapon_temp
Definition ShipEntity.h:304
BOOL fireDirectLaserShotAt:(Entity *my_target)
OOEquipmentType * generateMissileEquipmentTypeFrom:(NSString *role)
NSString * beaconCode()
NSString * _missileRole
Definition ShipEntity.h:310
void setEscortDestination:(HPVector dest)
OOColor * scanner_display_color2
Definition ShipEntity.h:222
OOShipGroup * group()
OOCargoQuantity availableCargoSpace()
unsigned cloakAutomatic
Definition ShipEntity.h:256
unsigned missiles
Definition ShipEntity.h:308
void behaviour_attack_fly_to_target:(double delta_t)
float reactionTime
OOWeakReference * _subEntityTakingDamage
Definition ShipEntity.h:443
void addImpactMoment:fraction:(Vector moment,[fraction] GLfloat howmuch)
OOWeakReference * _primaryAggressor
Definition ShipEntity.h:426
void behaviour_attack_broadside_left:(double delta_t)
static float SurfaceDistanceSqared(Entity *reference, Entity< OOStellarBody > *stellar)
OOCargoFlag cargoFlag()
void receiveCommsMessage:from:(NSString *message_text,[from] ShipEntity *other)
void setDisplayName:(NSString *inName)
BOOL abandonShip()
unsigned number_of_navpoints
Definition ShipEntity.h:408
double rangeToSecondaryTarget:(Entity *target)
OOColor * scannerDisplayColor2()
void setAccuracy:(GLfloat new_accuracy)
unsigned being_fined
Definition ShipEntity.h:248
double desiredRange()
NSString * name
uint8_t maxEscortCount()
unsigned max_missiles
Definition ShipEntity.h:309
float maxForwardShieldLevel()
HPVector _destination
Definition ShipEntity.h:192
void wasAddedToUniverse()
BOOL isTrader()
GLfloat stick_yaw
Definition ShipEntity.h:199
NSArray * portWeaponOffset
Quaternion subentityRotationalVelocity
Definition ShipEntity.h:208
float hyperspaceMotorSpinTime
Definition ShipEntity.h:236
BOOL isTurret()
OOCargoType dumpItem:(ShipEntity *jetto)
NSString * repeatString:times:(NSString *str, [times] NSUInteger times)
Definition ShipEntity.m:739
BOOL fireDirectLaserDefensiveShot()
GLint entityPersonalityInt()
OOShipGroup * stationGroup()
NSString * shipClassName
GLfloat flightPitch
void setUpMixedEscorts()
BOOL isPolice()
Entity * primaryAggressor()
OOTimeDelta missile_load_time
Definition ShipEntity.h:311
void setPrimaryRole:(NSString *role)
OOShipGroup * _group
Definition ShipEntity.h:452
void releaseCargoPodsDebris()
OOWeaponType weaponTypeIDForFacing:strict:(OOWeaponFacing facing,[strict] BOOL strict)
GLfloat flightSpeed
void validateDefenseTargets()
void subEntityDied:(ShipEntity *sub)
BOOL fireStarboardWeapon:(double range)
OOCargoType cargoType()
double trackSideTarget:leftside:(double delta_t,[leftside] BOOL leftside)
NSArray * equipmentListForScripting()
OOWeakSet * _collisionExceptions
Definition ShipEntity.h:463
void deployEscorts()
void behaviour_close_with_target:(double delta_t)
OOWeaponType aft_weapon_type
Definition ShipEntity.h:295
void deactivateCloakingDevice()
void throwSparks()
BOOL countsAsKill()
void setUpOneEscort:inGroup:withRole:atPosition:andCount:(ShipEntity *escorter, [inGroup] OOShipGroup *escortGroup, [withRole] NSString *escortRole, [atPosition] HPVector ex_pos, [andCount] uint8_t currentEscortCount)
void increase_flight_speed:(double delta)
BoundingBox totalBoundingBox
Vector v_up
Definition ShipEntity.h:189
Entity * entityForShaderProperties()
OOCreditsQuantity removeMissiles()
OOWeakReference * _lastAegisLock
Definition ShipEntity.h:450
void wasRemovedFromUniverse()
void setShipScript:(NSString *script_name)
NSString * scanDescription()
void behaviour_idle:(double delta_t)
BOOL isPirateVictim()
BOOL hasEquipmentItem:(id equipmentKeys)
OOWeakReference * _lastEscortTarget
Definition ShipEntity.h:429
NSEnumerator * defenseTargetEnumerator()
NSMutableDictionary * previousCondition
Definition ShipEntity.h:342
NSString * descriptionComponents()
BOOL removeExternalStore:(OOEquipmentType *eqType)
BOOL hasNewAI()
void updateTrackingCurve()
GLfloat _scaleFactor
Definition ShipEntity.h:377
OOWeakReference * _primaryTarget
Definition ShipEntity.h:425
void broadcastMessage:withUnpilotedOverride:(NSString *message_text,[withUnpilotedOverride] BOOL unpilotedOverride)
NSArray * starboardWeaponOffset
void setTargetToNearestFriendlyStation()
Entity * thankedShip()
GLfloat desired_range
Definition ShipEntity.h:194
BOOL activateCloakingDevice()
NSEnumerator * equipmentEnumerator()
void drawImmediate:translucent:(bool immediate, [translucent] bool translucent)
HPVector coordinates
GLfloat temperature()
void setHeatInsulation:(GLfloat value)
void abortDocking()
OOTimeDelta shotTime()
void resetExhaustPlumes()
void setScannerDisplayColor2:(OOColor *color2)
void behaviour_attack_break_off_target:(double delta_t)
OOFuelQuantity fuel
OOFuelQuantity fuelCapacity()
float shieldRechargeRate()
OOEquipmentType * missile_list[SHIPENTITY_MAX_MISSILES]
Definition ShipEntity.h:422
BOOL hasHeatShield()
NSArray * escortArray()
OOCreditsQuantity bounty
ShipEntity * dumpCargoItem:(OOCommodityType preferred)
id< OOHUDBeaconIcon > _beaconDrawable
Definition ShipEntity.h:474
NSArray * parcelListForScripting()
HPVector calculateTargetPosition()
OOAegisStatus aegis_status
Definition ShipEntity.h:367
OOScanClass scanClass()
void checkScannerIgnoringUnpowered()
BOOL hasMilitaryScannerFilter()
void setLastEscortTarget:(Entity *targetEntity)
void behaviour_fly_to_target_six:(double delta_t)
NSArray * cargoListForScripting()
BoundingBox findBoundingBoxRelativeToPosition:i:j:k:(HPVector opv,[i] Vector i,[j] Vector j,[k] Vector k)
void respondToAttackFrom:becauseOf:(Entity *from,[becauseOf] Entity *other)
NSEnumerator * flasherEnumerator()
Entity * proximityAlert()
NSMutableDictionary * closeContactsInfo
Definition ShipEntity.h:390
void scoopUpProcess:processEvents:processMessages:(ShipEntity *other,[processEvents] BOOL proc_events,[processMessages] BOOL proc_messages)
BOOL hasEquipmentItemProviding:(NSString *equipmentType)
NSString * scan_description
Definition ShipEntity.h:320
StationEntity * targetStation()
GLfloat sunGlareFilter
BOOL hasEscapePod()
void leaveWitchspace()
GLfloat distance2_scanned_ships[MAX_SCAN_NUMBER+1]
Definition ShipEntity.h:402
uint16_t entity_personality
Definition ShipEntity.h:418
NSString * serializeShipSubEntities()
Definition ShipEntity.m:753
void setPitch:(double amount)
void behaviour_running_defense:(double delta_t)
void behaviour_tumble:(double delta_t)
NSString * identFromShip:(ShipEntity *otherShip)
BOOL fireTurretCannon:(double range)
OOWeakReference * _proximityAlert
Definition ShipEntity.h:432
OOAlertCondition realAlertCondition()
OOTimeAbsolute missile_launch_time
Definition ShipEntity.h:312
void drawDebugStuff()
GLfloat accuracy
GLfloat forward_weapon_temp
Definition ShipEntity.h:304
BOOL cascadeIfAppropriateWithDamageAmount:cascadeOwner:(double amount,[cascadeOwner] Entity *owner)
uint32_t randomSeedForShaders()
void doScriptEvent:withArgument:andArgument:(OOJSPropID message,[withArgument] id argument1,[andArgument] id argument2)
static BOOL AuthorityPredicate(Entity *entity, void *parameter)
void removeAllEquipment()
void broadcastAIMessage:(NSString *ai_message)
double desiredSpeed()
ShipEntity * fireMissile()
NSString * shipUniqueName
unsigned being_mined
Definition ShipEntity.h:246
void removeDefenseTarget:(Entity *target)
OOCargoQuantity likely_cargo
Definition ShipEntity.h:283
OOTimeDelta missileLoadTime()
NSString * scanDescriptionForScripting()
void setBeaconCode:(NSString *bcode)
NSUInteger missileCapacity()
OOColor * exhaust_emissive_color
Definition ShipEntity.h:220
void dealEnergyDamageWithinDesiredRange()
Vector reference
void enterWormhole:(WormholeEntity *w_hole)
double approachAspectToPrimaryTarget()
OOSystemID home_system
Definition ShipEntity.h:368
double ballTrackLeadingTarget:atTarget:(double delta_t,[atTarget] Entity *target)
BOOL isValidTarget:(Entity *target)
static BOOL IsBehaviourHostile(OOBehaviour behaviour)
BOOL equipmentValidToAdd:whileLoading:inContext:(NSString *equipmentKey,[whileLoading] BOOL loading,[inContext] NSString *context)
GLfloat thrust
OOPlanetEntity * findNearestPlanet()
OOCommodityType dumpCargo()
GLfloat starboard_weapon_temp
Definition ShipEntity.h:304
void setAITo:(NSString *aiString)
void sendMessage:toShip:withUnpilotedOverride:(NSString *message_text,[toShip] ShipEntity *other_ship,[withUnpilotedOverride] BOOL unpilotedOverride)
BOOL hasCascadeMine()
void applyThrust:(double delta_t)
OOTimeDelta shot_time
Definition ShipEntity.h:186
OOColor * scannerDisplayColorHostile2()
HPVector navpoints[32]
Definition ShipEntity.h:406
float energyRechargeRate()
void setWeaponDataFromType:(OOWeaponType weapon_type)
NSArray * missilesList()
OOCargoType cargo_type
Definition ShipEntity.h:287
GLfloat stick_roll
Definition ShipEntity.h:197
BOOL isUnpiloted()
BOOL isTemplateCargoPod()
Definition ShipEntity.m:932
ShipEntity * launchEscapeCapsule()
void behaviour_attack_mining_target:(double delta_t)
NSEnumerator * shipSubEntityEnumerator()
void switchLightsOff()
unsigned pitching_over
Definition ShipEntity.h:242
BOOL hasDockingComputer()
void dockEscorts()
GLfloat speedFactor()
void noteTargetDestroyed:(ShipEntity *target)
void addRole:(NSString *role)
Vector missileLaunchPosition()
NSEnumerator * exhaustEnumerator()
NSUInteger _subIdx
Definition ShipEntity.h:331
BOOL isMissileFlagSet()
void behaviour_attack_broadside:(double delta_t)
NSArray * aftWeaponOffset
NSArray * laserPortOffset:(OOWeaponFacing direction)
void setWeaponRange:(GLfloat value)
ShipEntity * launchPodWithCrew:(NSArray *podCrew)
void behaviour_attack_sniper:(double delta_t)
BOOL isShuttle()
void doScriptEvent:inContext:withArguments:count:(OOJSPropID message,[inContext] JSContext *context,[withArguments] jsval *argv,[count] int argc)
void adjustVelocity:(Vector xVel)
NSArray * forwardWeaponOffset
Entity< OOStellarBody > * findNearestStellarBody()
float maxAftShieldLevel()
OOColor * scanner_display_color1
Definition ShipEntity.h:221
int legalStatus()
void setWeaponRechargeRate:(float value)
NSString * equipmentItemProviding:(NSString *equipmentType)
float afterburnerRate()
NSArray * passengerListForScripting()
void setEscortGroup:(OOShipGroup *group)
NSArray * collisionExceptions()
OOWeaponFacingSet weaponFacings()
NSString * shortDescriptionComponents()
void behaviour_face_destination:(double delta_t)
HPVector destination()
NSEnumerator * subEntityEnumerator()
void sendExpandedMessage:toShip:(NSString *message_text,[toShip] ShipEntity *other_ship)
GLfloat weapon_temp
Definition ShipEntity.h:303
BOOL isBeacon()
BOOL hasShieldBooster()
float randomEjectaTemperature()
OOBehaviour behaviour
unsigned cloakPassive
float _heatInsulation
Definition ShipEntity.h:448
OOWeaponType starboard_weapon_type
Definition ShipEntity.h:297
OOJSScript * script
void addSubentityToCollisionRadius:(Entity< OOSubEntity > *subent)
void doScriptEvent:andReactToAIMessage:(OOJSPropID scriptEvent,[andReactToAIMessage] NSString *aiMessage)
void setScriptedMisjumpRange:(GLfloat newValue)
void wormholeEscorts()
Vector velocity()
NSUInteger parcelCount()
void behaviour_track_target:(double delta_t)
unsigned scripted_misjump
Definition ShipEntity.h:267
void behaviour_attack_target:(double delta_t)
OOColor * scannerDisplayColorHostile1()
float ship_temperature
Definition ShipEntity.h:398
void setEntityPersonalityInt:(uint16_t value)
void setReportAIMessages:(BOOL yn)
void removeAllDefenseTargets()
BOOL hasGalacticHyperdrive()
BOOL fireDirectLaserShot:(double range)
BOOL launchCascadeMine()
GLfloat heatInsulation()
OOColor * exhaustEmissiveColor()
void setTrackCloseContacts:(BOOL value)
GLfloat aim_tolerance
Definition ShipEntity.h:364
uint8_t escortCount()
void behaviour_avoid_collision:(double delta_t)
OOTimeAbsolute demoStartTime
Definition ShipEntity.h:481
void updateEscortFormation()
BOOL hasHostileTarget()
unsigned military_jammer_active
Definition ShipEntity.h:238
BOOL hasCargoScoop()
void clearSubEntities()
void setSubIdx:(NSUInteger value)
Definition ShipEntity.m:724
OOCargoQuantity commodityAmount()
GLfloat weapon_shot_temperature
Definition ShipEntity.h:303
void noteLostTargetAndGoIdle()
GLfloat max_flight_yaw
Definition ShipEntity.h:231
BOOL isMinable()
GLfloat energy_recharge_rate
Definition ShipEntity.h:291
NSUInteger extraCargo()
void overrideScriptInfo:(NSDictionary *override)
OOCargoQuantity maxAvailableCargoSpace()
OOColor * default_laser_color
Definition ShipEntity.h:219
double launch_time
Definition ShipEntity.h:333
void orientationChanged()
float weapon_recharge_rate
Definition ShipEntity.h:345
void update:(OOTimeDelta delta_t)
uint8_t pendingEscortCount()
GLfloat laserHeatLevel()
void setTemperature:(GLfloat value)
void dealMomentumWithinDesiredRange:(double amount)
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
OOSystemID destinationSystem()
void adjustMissedShots:(int delta)
void setScriptedMisjump:(BOOL newValue)
ShipEntity * shipHitByLaser()
Quaternion subEntityRotationalVelocity()
OOShipGroup * _escortGroup
Definition ShipEntity.h:453
GLfloat max_flight_roll
Definition ShipEntity.h:229
void checkScanner()
HPVector trackingCurveCoeffs[3]
Definition ShipEntity.h:440
GLfloat laserHeatLevelPort()
BOOL fireAftWeapon:(double range)
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
GLfloat desired_speed
Definition ShipEntity.h:195
void processBehaviour:(OOTimeDelta delta_t)
double messageTime
NSString * _beaconCode
Definition ShipEntity.h:470
void setCloaked:(BOOL cloak)
BOOL hasAutoCloak()
double trackDestination:retreat:(double delta_t,[retreat] BOOL retreat)
float volume()
void setIsBoulder:(BOOL flag)
OOEquipmentType * weaponTypeForFacing:strict:(OOWeaponFacing facing,[strict] BOOL strict)
NSArray * crewForScripting()
void setCrew:(NSArray *crewArray)
void setCommodityForPod:andAmount:(OOCommodityType co_type,[andAmount] OOCargoQuantity co_amount)
OOWeaponType port_weapon_type
Definition ShipEntity.h:296
void markAsOffender:withReason:(int offence_value,[withReason] OOLegalStatusReason reason)
BOOL canCollide()
BOOL lightsActive()
BOOL fireMainWeapon:(double range)
Entity< OOBeaconEntity > * nextBeacon()
double maxHyperspaceDistance()
BOOL isVisible()
void subEntityReallyDied:(ShipEntity *sub)
OOCargoQuantity max_cargo
Definition ShipEntity.h:284
OOColor * laserColor()
void dealloc()
Definition ShipEntity.m:986
void setBehaviour:(OOBehaviour cond)
NSUInteger maxShipSubEntities()
Definition ShipEntity.m:734
Vector thrustVector()
Octree * octree
NSUInteger subEntityCount()
BOOL isBoulder()
void setIsMissileFlag:(BOOL newValue)
void scoopUp:(ShipEntity *other)
void switchAITo:(NSString *aiString)
BOOL setUpOneSubentity:(NSDictionary *subentDict)
Definition ShipEntity.m:835
GLfloat maxFlightYaw()
NSString * shipDataKeyAutoRole()
BOOL hasHyperspaceMotor()
uint8_t _pendingEscortCount
Definition ShipEntity.h:455
unsigned canFragment
Definition ShipEntity.h:257
OOAegisStatus checkForAegis()
GLfloat laserHeatLevelForward()
unsigned isHulk
OOJSScript * aiScript
Definition ShipEntity.h:212
void setHulk:(BOOL isNowHulk)
id< OOHUDBeaconIcon > beaconDrawable()
void setTargetToNearestStation()
OOMesh * mesh()
Quaternion demoStartOrientation
Definition ShipEntity.h:482
void setBeaconLabel:(NSString *blabel)
double rangeToPrimaryTarget()
GLfloat fuelChargeRate()
Triangle absoluteIJKForSubentity()
BOOL scriptedMisjump()
void behaviour_flee_target:(double delta_t)
OOCargoQuantity cargoQuantityOnBoard()
unsigned next_navpoint_index
Definition ShipEntity.h:407
void reactToAIMessage:context:(NSString *message,[context] NSString *debugContext)
void setFoundTarget:(Entity *targetEntity)
BOOL withinStationAegis()
void setScannerDisplayColorHostile2:(OOColor *color2)
OOWeakReference * _nextBeacon
Definition ShipEntity.h:473
BOOL setUpOneFlasher:(NSDictionary *subentDict)
Definition ShipEntity.m:851
NSString * _beaconLabel
Definition ShipEntity.h:471
GLfloat entityPersonality()
OOPlanetEntity * findNearestPlanetExcludingMoons()
OOWeakSet * _defenseTargets
Definition ShipEntity.h:460
void becomeExplosion()
GLfloat fuel_accumulator
Definition ShipEntity.h:278
void applyRoll:climb:andYaw:(GLfloat roll1, [climb] GLfloat climb1, [andYaw] GLfloat yaw1)
unsigned n_scanned_ships
Definition ShipEntity.h:403
OOColor * scanner_display_color_hostile1
Definition ShipEntity.h:223
void setCommodity:andAmount:(OOCommodityType co_type,[andAmount] OOCargoQuantity co_amount)
unsigned docking_match_rotation
Definition ShipEntity.h:240
void behaviour_fly_range_from_destination:(double delta_t)
void behaviour_attack_fly_from_target:(double delta_t)
OOWeaponType forward_weapon_type
Definition ShipEntity.h:294
NSArray * crew
unsigned cloaking_device_active
Definition ShipEntity.h:254
GLfloat flightRoll
BOOL hasEquipmentItem:includeWeapons:whileLoading:(id equipmentKeys,[includeWeapons] BOOL includeWeapons,[whileLoading] BOOL loading)
OOCargoQuantity extra_cargo
Definition ShipEntity.h:285
void startTrackingCurve()
OOScalar demoRate
Definition ShipEntity.h:480
NSMutableArray * subEntities
void addRole:withProbability:(NSString *role,[withProbability] float probability)
OOCargoQuantity equipment_weight
Definition ShipEntity.h:286
void enterWormhole:replacing:(WormholeEntity *w_hole,[replacing] BOOL replacing)
BOOL showScoopMessage()
Vector rightVector()
unsigned _explicitlyUnpiloted
Definition ShipEntity.h:263
HPVector trackingCurvePositions[4]
Definition ShipEntity.h:438
GLfloat scannerRange
GLfloat weaponRecoveryTime()
OOWeakReference * _prevBeacon
Definition ShipEntity.h:472
GLfloat maxFlightSpeed
BOOL isCloaked()
OOCommodityType commodityType()
void setOwner:(Entity *who_owns_entity)
NSArray * explosionType
Definition ShipEntity.h:324
GLfloat _profileRadius
Definition ShipEntity.h:465
BoundingBox findSubentityBoundingBox()
BOOL isThargoid()
void behaviour_track_as_turret:(double delta_t)
BOOL hasExpandedCargoBay()
NSString * displayName
NSUInteger countEquipmentItem:(NSString *eqkey)
void doScriptEvent:withArgument:andReactToAIMessage:(OOJSPropID scriptEvent,[withArgument] id argument,[andReactToAIMessage] NSString *aiMessage)
GLfloat success_factor
Definition ShipEntity.h:338
OOWeakReference * _foundTarget
Definition ShipEntity.h:428
Entity< OOBeaconEntity > * prevBeacon()
void becomeEnergyBlast()
Entity< OOStellarBody > * lastAegisLock()
BOOL hasCloakingDevice()
void behaviour_attack_slow_dogfight:(double delta_t)
NSString * lastRadioMessage
Definition ShipEntity.h:392
Entity * lastEscortTarget()
void removeScript()
GLfloat maxFlightPitch()
Entity * foundTarget()
OOColor * scannerDisplayColor1()
NSUInteger _maxShipSubIdx
Definition ShipEntity.h:332
GLfloat hullHeatLevel()
NSString * _shipKey
Definition ShipEntity.h:445
void addSubEntity:(Entity< OOSubEntity > *sub)
double _nextAegisCheck
Definition ShipEntity.h:476
OOScript * shipAIScript()
GLfloat flightYaw
GLfloat frustumRadius()
Definition ShipEntity.m:822
unsigned haveExecutedSpawnAction
Definition ShipEntity.h:268
void avoidCollision()
void setReference:(Vector v)
BOOL isEscort()
static float SurfaceDistanceSqaredV(HPVector reference, Entity< OOStellarBody > *stellar)
void disengageAutopilot()
BOOL fireWeapon:direction:range:(OOWeaponType weapon_type, [direction] OOWeaponFacing direction, [range] double range)
Vector v_right
Definition ShipEntity.h:189
GLfloat cruiseSpeed
BOOL showDamage()
OOSystemID homeSystem()
void launchShip:(ShipEntity *ship)
Vector portUpVectorForShip:(ShipEntity *ship)
void launchShipWithRole:(NSString *role)
void noteDockedShip:(ShipEntity *ship)
BOOL suckInShip:(ShipEntity *ship)
void setMisjumpWithRange:(GLfloat range)
voidpf uLong int origin
Definition ioapi.h:132
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 seed_RNG_only_for_planet_description(Random_Seed s_seed)
float bellf(int n)
unsigned Ranrot(void)
#define ranrot_rand()
OOHPScalar x
Definition OOHPVector.h:36
OOHPScalar y
Definition OOHPVector.h:37
OOHPScalar z
Definition OOHPVector.h:38
OOScalar w
OOScalar x
OOScalar y
OOScalar z
Vector v[3]
Definition OOTriangle.h:29
OOScalar x
Definition OOVector.h:32
OOScalar y
Definition OOVector.h:33
OOScalar z
Definition OOVector.h:34