/
SearchRescue.lua
2040 lines (1780 loc) · 73.6 KB
/
SearchRescue.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- Copyright © 2008-2016 Pioneer Developers. See AUTHORS.txt for details
-- Licensed under the terms of the GPL v3. See licenses/GPL-3.txt
-- Notes:
-- - All station/planet location references in ad/mission are stored as paths for consistency because
-- some can't be accessed as bodies until the player enters the respective system and getting a path from
-- systembody needs to go through body. Variable "location" is a SystemsBody.
-- TODO:
-- - add degToDegMinSec function to src/LuaFormat.cpp
-- - re-create target ships if player left the system and returns again (works - except for look of ship)
-- - handle situation where player buys a new ship or sells/buys passenger cabins and loaded passengers
-- need to follow into the new ship/cabin
-- Explanations
-- ============
-- Variable flavour.pickup_crew, etc. is the goal, while variable mission.pickup_crew is the meter for
-- actually accomplished parts of the task.
-- Variable mission.pickup_crew_check provides the level of completion:
-- - "NOT" = not started
-- - "PARTIAL" = partially completed, but can't do more for now
-- - "ABORT" = aborted, but can work on it again
-- - "COMPLETE" = finished task
local Engine = import("Engine")
local Lang = import("Lang")
local Game = import("Game")
local Space = import("Space")
local Comms = import("Comms")
local Event = import("Event")
local Mission = import("Mission")
local Format = import("Format")
local Serializer = import("Serializer")
local Character = import("Character")
local Equipment = import("Equipment")
local ShipDef = import("ShipDef")
local Ship = import("Ship")
local utils = import("utils")
local Timer = import("Timer")
local InfoFace = import("ui/InfoFace")
local l = Lang.GetResource("module-searchrescue")
-- Get the UI class
local ui = Engine.ui
-- basic variables for mission creation
local max_mission_dist = 30 -- max distance for long distance mission target location [ly]
local max_close_dist = 5000 -- max distance for "CLOSE_PLANET" target location [km]
local max_close_space_dist = 10000 -- max distance for "CLOSE_SPACE" target location [km]
local far_space_orbit_dist = 100000 -- orbital distance around planet for "FAR_SPACE" target location [km]
local min_interaction_dist = 50 -- min distance for successful interaction with target [meters]
local target_interaction_time = 10 -- target interaction time to load/unload one unit of cargo/person [sec]
local max_pass = 2 -- max number of passengers on target ship (high max: 10)
local max_crew = 4 -- max number of crew on target ship (high max: 8)
local reward_close = 200 -- basic reward for "CLOSE" mission (+/- random half of that)
local reward_medium = 1000 -- basic reward for "MEDIUM" mission (+/- random half of that)
local reward_far = 2000 -- basic reward for "FAR" mission (+/- random half of that)
local ad_freq_max = 3.0 -- maximum frequency for ad creation
local ad_freq_min = 0.3 -- minimum frequency for ad creation
-- global containers and variables
local aircontrol_chars = {} -- saving specific aircontrol character per spacestation
local ads = {} -- currently active ads in the system
local missions = {} -- accepted missions that are currently active
local leaving_system = false -- needed for last minute cleanup before leaving system (searchForTarget)
local discarded_ships = {} -- ships that are not needed any longer
-- Flavour Variables
-- =================
-- Use with caution! There are checks in place but impossible combinations can still break this script.
-- An appropriate ship type will be chosen depending on the mission. Make sure a ship exists that can do
-- what is requested (i.e. has the necessary crew number).
-- id = 1 : ID to help pull the right ad texts in
-- loctype assumptions : a) "CLOSE" means there are stations within the system (i.e. target ships don't
-- necessarily need hyperdrives
-- b) "PLANET" means any target ship has to have an atmo_shield
-- loctype = "CLOSE_PLANET" : target on the same planet the player is on (not applicable to non-ground stations)
-- loctype = "MEDIUM_PLANET": target on a planet within the same system as the player is in
-- loctype = "CLOSE_SPACE" : target close to space station player is docked at - but drifting in space
-- loctype = "FAR_SPACE" : target in a different system - drifting in space
-- pickup_crew = 0 : how many crew members of the target ship to pick up
-- pickup_pass = 0 : how many passengers of the target ship to pick up
-- pickup_comm = {} : type and amount of commodity to pick up from target ship
-- deliver_crew = 0 : how many crew members to deliver to target ship
-- deliver_pass = 0 : how many passengers to deliver to target ship
-- deliver_comm = {} : type and amount of commodity to deliver to target ship
-- urgency = 1 : factor for how urgent transport ist (most urgent time multiplied by factor)
-- reward_immediate = false : should the mission reward be provided immediately or upon return to station
local flavours = {
-- rescue all crew + passengers from ship stranded close to starport
-- SPECIAL: number of crew/pass to pickup is picked randomly during ad creation
{
id = 1,
loctype = "MEDIUM_PLANET",
pickup_crew = 0,
pickup_pass = 0,
pickup_comm = {},
deliver_crew = 0,
deliver_pass = 0,
deliver_comm = {},
urgency = 1,
reward_immediate = false,
},
-- deliver fuel to ship stranded close to starport
{
id = 2,
loctype = "CLOSE_PLANET",
pickup_crew = 0,
pickup_pass = 0,
pickup_comm = {},
deliver_crew = 0,
deliver_pass = 0,
deliver_comm = {[Equipment.cargo.hydrogen] = 1},
urgency = 5,
reward_immediate = true
},
-- deliver 1 crew to ship stranded close to starport
{
id = 3,
loctype = "CLOSE_PLANET",
pickup_crew = 0,
pickup_pass = 0,
pickup_comm = {},
deliver_crew = 1,
deliver_pass = 0,
deliver_comm = {},
urgency = 5,
reward_immediate = true
},
-- deliver fuel to ship stranded on planet within same system
{
id = 4,
loctype = "MEDIUM_PLANET",
pickup_crew = 0,
pickup_pass = 0,
pickup_comm = {},
deliver_crew = 0,
deliver_pass = 0,
deliver_comm = {[Equipment.cargo.hydrogen] = 1},
urgency = 5,
reward_immediate = true
},
-- deliver fuel to ship stranded in space close to station player is docked at
{
id = 5,
loctype = "CLOSE_SPACE",
pickup_crew = 0,
pickup_pass = 0,
pickup_comm = {},
deliver_crew = 0,
deliver_pass = 0,
deliver_comm = {[Equipment.cargo.hydrogen] = 1},
urgency = 5,
reward_immediate = true
},
-- rescue all crew + passengers from ship stranded in unoccupied system
-- SPECIAL: number of crew/pass to pickup is picked randomly during ad creation
{
id = 6,
loctype = "FAR_SPACE",
pickup_crew = 0,
pickup_pass = 0,
pickup_comm = {},
deliver_crew = 0,
deliver_pass = 0,
deliver_comm = {},
urgency = 5,
reward_immediate = false
},
-- take replacment crew to ship stranded in unoccupied system
-- SPECIAL: number of crew to deliver is picked randomly during ad creation
{
id = 7,
loctype = "FAR_SPACE",
pickup_crew = 0,
pickup_pass = 0,
pickup_comm = {},
deliver_crew = 0,
deliver_pass = 0,
deliver_comm = {},
urgency = 5,
reward_immediate = true
}
}
-- add strings to flavours
for i = 1,#flavours do
local f = flavours[i]
f.adtext = l["FLAVOUR_" .. f.id .. "_ADTEXT"]
f.introtext = l["FLAVOUR_" .. f.id .. "_INTROTEXT"]
f.locationtext = l["FLAVOUR_" .. f.id .. "_LOCATIONTEXT"]
f.typeofhelptext = l["FLAVOUR_" .. f.id .. "_TYPEOFHELPTEXT"]
f.howmuchtimetext = l["FLAVOUR_" .. f.id .. "_HOWMUCHTIMETEXT"]
f.successmsg = l["FLAVOUR_" .. f.id .. "_SUCCESSMSG"]
f.failuremsg = l["FLAVOUR_" .. f.id .. "_FAILUREMSG"]
f.transfermsg = l["FLAVOUR_" .. f.id .. "_TRANSFERMSG"]
end
-- basic lua helper functions
-- ==========================
local arraySize = function (array)
-- Return the size (length) of an array that contains arbitrary entries.
local n = 0
for _,_ in pairs(array) do n = n + 1 end
return n
end
local containerContainsKey = function (container, key)
-- Return true if key is in container and false if not.
return container[key] ~= nil
end
local copyTable = function (orig)
-- Return a copy of a table. Copies only the direct children (no deep copy!).
-- Taken from http://lua-users.org/wiki/CopyTable.
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in pairs(orig) do
copy[orig_key] = orig_value
end
else -- number, string, boolean, etc
copy = orig
end
return copy
end
local compressTableKeys = function (t)
-- Return the table with all keys in numerical order without gaps.
-- Taken from http://www.computercraft.info/forums2/index.php?/topic/18380-how-do-i-remove-gaps-in-an-ordered-list/.
local keySet = {}
for i in pairs(t) do
table.insert(keySet, i)
end
table.sort(keySet)
local retVal = {}
for i = 1, #keySet do
retVal[i] = t[keySet[i]]
end
return retVal
end
-- housekeeping mission functions
-- ==============================
local addMission = function (mission)
-- Add the supplied mission to the player, generate a unique ID and store this mission within the script.
table.insert(missions,Mission.New(mission))
end
local removeMission = function (mission)
-- Remove the supplied mission from the player and from the internal mission storage within the script.
local ref
for i,v in pairs(missions) do
if v == mission then
ref = i
break
end
end
mission:Remove()
missions[ref] = nil
end
-- basic mission functions
-- =======================
local triggerAdCreation = function ()
-- Return if ad should be created based on lawlessness and min/max frequency values.
-- Ad number per system is based on how many stations a system has so a player will
-- be met with a certain number of stations that have one or more ads.
local stations = Space.GetBodies(function (body) return body.superType == 'STARPORT' end)
local freq = Game.system.lawlessness * ad_freq_max
if freq < ad_freq_min then freq = ad_freq_min end
local ad_num_max = freq * #stations
if arraySize(ads) < ad_num_max then
if Engine.rand:Integer(0,1) == 1 then
return true
end
end
return false
end
local getNumberOfFlavours = function (str)
-- Returns the number of flavours of the given string (assuming first flavour has suffix '_1').
-- Taken from CargoRun.lua.
local num = 1
while l[str .. "_" .. num] do
num = num + 1
end
return num - 1
end
local mToAU = function (meters)
-- Transform meters into AU.
return meters/149598000000
end
local splitName = function (name)
-- Splits the supplied name into first and last name and returns a table of both separately.
-- Idea from http://stackoverflow.com/questions/2779700/lua-split-into-words.
local names = {}
for word in name:gmatch("%w+") do table.insert(names, word) end
return names
end
local decToDegMinSec = function (coord_orig)
-- Converts geographic coordinates from decimal to degree/minutes/seconds format
-- and returns a string.
local coord = math.abs(coord_orig)
local degrees = math.floor(coord)
local minutes = math.floor(60*(coord - degrees))
local seconds = math.floor(3600 * ((coord - degrees) - minutes / 60))
if coord_orig < 0 then degrees = degrees * -1 end
local str = string.format("%i° %i' %i\"", degrees, minutes, seconds)
return str
end
local getAircontrolChar = function (station)
-- Get the correct aircontrol character for the supplied station. If it does not exist
-- create one and store it.
if containerContainsKey(aircontrol_chars, station.path) then
return aircontrol_chars[station.path]
else
local char = Character.New()
aircontrol_chars[station.path] = char
return char
end
end
local randomLatLong = function (station)
-- Provide a set of random latitude and longitude coordinates for ship placement that are:
-- (a) random, within max_close_dist from starting base if base is provided, or
-- (b) completely random.
local lat, long, dist
-- calc new lat/lon based on distance and bearing
-- formulas taken from http://www.movable-type.co.uk/scripts/latlong.html
if station then
local old_lat, old_long = station:GetGroundPosition()
local planet_radius = station.path:GetSystemBody().parent.radius / 1000
local bearing = math.rad(Engine.rand:Number(0,360))
dist = Engine.rand:Integer(1,max_close_dist) -- min distance is 1 km
lat = math.asin(math.sin(old_lat) * math.cos(dist/planet_radius) + math.cos(old_lat) *
math.sin(dist/planet_radius) * math.cos(bearing))
long = old_long + math.atan2(math.sin(bearing) * math.sin(dist/planet_radius) * math.cos(old_lat),
math.cos(dist/planet_radius) - math.sin(old_lat) * math.sin(lat))
dist = dist * 1000 -- convert to m for downstream consistency
else
lat = Engine.rand:Number(-90,90)
lat = math.rad(lat)
long = Engine.rand:Number(-180,180)
long = math.rad(long)
end
return lat, long, dist
end
local shipdefFromName = function (shipdef_name)
-- Return the corresponding shipdef for the supplied shipdef name. Necessary because serialization
-- crashes if actual shipdef is stored in ad. There may be a smarter way to do this!
local shipdefs = utils.build_array(utils.filter(function (_,def) return def.tag == 'SHIP'
and def.name == shipdef_name end, pairs(ShipDef)))
return shipdefs[1]
end
local crewPresent = function (ship)
-- Check if any crew is present on the ship.
if ship:CrewNumber() > 0 then
return true
else
return false
end
end
local passengersPresent = function (ship)
-- Check if any passengers are present on the ship.
if ship:CountEquip(Equipment.misc.cabin_occupied) > 0 then
return true
else
return false
end
end
local passengerSpace = function (ship)
-- Check if the ship has space for passengers.
if ship:CountEquip(Equipment.misc.cabin) > 0 then
return true
else
return false
end
end
local cargoPresent = function (ship, item)
-- Check if this cargo item is present on the ship.
if ship:CountEquip(item) > 0 then
return true
else
return false
end
end
local cargoSpace = function (ship)
-- Check if the ship has space for additional cargo.
-- TODO: GetEquipFree("cargo") does not seem to work right - issue submitted.
if ship:GetEquipFree("cargo") > 0 then
return true
else
return false
end
end
local addCrew = function (ship, crew_member)
-- Add a crew member to the supplied ship.
if ship:CrewNumber() == ship.maxCrew then return end
if not crew_member then
crew_member = Character.New()
end
ship:Enroll(crew_member)
end
local removeCrew = function (ship)
-- Remove a crew member from the supplied ship.
if ship:CrewNumber() == 0 then return end
local crew_member
for member in ship:EachCrewMember() do -- only way to get a single crew member?
crew_member = member
break
end
ship:Dismiss(crew_member)
return crew_member
end
local addPassenger = function (ship)
-- Add a passenger to the supplied ship.
if not passengerSpace(ship) then return end
ship:RemoveEquip(Equipment.misc.cabin, 1)
ship:AddEquip(Equipment.misc.cabin_occupied, 1)
end
local removePassenger = function (ship)
-- Remove a passenger from the supplied ship.
if not passengersPresent(ship) then return end
ship:RemoveEquip(Equipment.misc.cabin_occupied, 1)
ship:AddEquip(Equipment.misc.cabin, 1)
end
local addCargo = function (ship, item)
-- Add a ton of the supplied cargo item to the ship.
if not cargoSpace(ship) then return end
ship:AddEquip(item, 1)
end
local removeCargo = function (ship, item)
-- Remove a ton of the supplied cargo item from the ship.
if not cargoPresent(ship, item) then return end
ship:RemoveEquip(item, 1)
end
local passEquipmentRequirements = function (requirements)
-- Check if player ship passes equipment requirements for this mission.
if requirements == {} then return true end
for equipment,amount in pairs(requirements) do
if Game.player:CountEquip(equipment) < amount then return false end
end
return true
end
local isQualifiedFor = function(ad)
-- Return if player is qualified for this mission. Used for example by ads to determine if they are
-- enabled or disabled for selection on the banter board of if certain missions can be accepted.
-- TODO: enable reputation based qualifications
-- collect equipment requirements per mission flavor
local requirements = {}
local empty_cabins = ad.pickup_crew + ad.deliver_crew + ad.pickup_pass + ad.deliver_pass
if empty_cabins > 0 then requirements[Equipment.misc.cabin] = empty_cabins end
if not passEquipmentRequirements(requirements) then return false end
return true
end
-- extended mission functions
-- ==========================
local calcReward = function (flavour)
-- Calculate the appropriate reward for this mission.
-- TODO: Extend for other mission types.
-- TODO: Adjust based on urgency + risk?
local reward
if flavour.loctype == "CLOSE_PLANET" or flavour.loctype == "CLOSE_SPACE" then
reward = reward_close + Engine.rand:Number(reward_close / 2 * -1, reward_close / 2)
elseif flavour.loctype == "MEDIUM_PLANET" then
reward = reward_medium + Engine.rand:Number(reward_medium / 2 * -1, reward_medium / 2)
elseif flavour.loctype == "FAR_SPACE" then
reward = reward_far + Engine.rand:Number(reward_far / 2 * -1, reward_far / 2)
end
return reward
end
local createTargetShipParameters = function (flavour, deliver_crew, pickup_crew, pickup_pass)
-- Create the basic parameters for the target ship. It is important to set these before ad creation
-- so certain info can be included in the ad text. The actual ship is created once the mission has
-- been accepted.
-- pick appropriate hull type
local shipdefs = utils.build_array(utils.filter(function (_,def) return def.tag == 'SHIP'
end, pairs(ShipDef)))
----> hyperdrive mandatory (for clean exiting of ships)
for i,shipdef in pairs(shipdefs) do
if shipdef.equipSlotCapacity.engine == 0 then shipdefs[i] = nil end
end
----> atmo-shield if ship stranded on planet
if flavour.loctype == "CLOSE_PLANET" or flavour.loctype == "MEDIUM_PLANET" then
for i,shipdef in pairs(shipdefs) do
if shipdef.equipSlotCapacity.atmo_shield == 0 then shipdefs[i] = nil end
end
end
----> crew quarters for crew delivery missions
if deliver_crew > 0 then
for i,shipdef in pairs(shipdefs) do
if shipdef.maxCrew <= deliver_crew+1 then shipdefs[i] = nil end
end
end
----> crew quarters for crew pickup missions
if pickup_crew > 0 then
for i,shipdef in pairs(shipdefs) do
if shipdef.maxCrew < pickup_crew then shipdefs[i] = nil end
end
end
----> cargo space for passenger pickup missions
---- (this is just an estimate to make sure enough space remains after loading drive, weapons etc.
if pickup_pass > 0 then
for i,shipdef in pairs(shipdefs) do
if shipdef.capacity * 10 < pickup_pass then shipdefs[i] = nil end
end
end
if arraySize(shipdefs) == 0 then
print("Could not find appropriate ship type for this mission!")
return
end
shipdefs = compressTableKeys(shipdefs)
local shipdef = shipdefs[Engine.rand:Integer(1,#shipdefs)]
-- number of crew
local crew_num
if pickup_crew > 0 then
crew_num = pickup_crew
else
crew_num = Engine.rand:Integer(shipdef.minCrew,shipdef.maxCrew)
crew_num = crew_num - flavour.deliver_crew
if crew_num <= 0 then crew_num = 1 end
end
-- label
local shiplabel = Ship.MakeRandomLabel()
return shipdef, crew_num, shiplabel
end
local createTargetShip = function (mission)
-- Create the target ship to be search for.
local ship
local shipdef = shipdefFromName(mission.shipdef_name)
-- create ship
if mission.flavour.loctype == "CLOSE_PLANET" then
ship = Space.SpawnShipLanded(shipdef.id, Space.GetBody(mission.planet_target.bodyIndex), mission.lat, mission.long)
elseif mission.flavour.loctype == "MEDIUM_PLANET" then
ship = Space.SpawnShipLanded(shipdef.id, Space.GetBody(mission.planet_target.bodyIndex), mission.lat, mission.long)
elseif mission.flavour.loctype == "CLOSE_SPACE" then
ship = Space.SpawnShipNear(shipdef.id, Space.GetBody(mission.station_target.bodyIndex), mission.dist/1000, mission.dist/1000)
elseif mission.flavour.loctype == "FAR_SPACE" then
ship = Space.SpawnShipNear(shipdef.id, Space.GetBody(mission.planet_target.bodyIndex), far_space_orbit_dist, far_space_orbit_dist)
ship:AIEnterHighOrbit(Space.GetBody(mission.planet_target.bodyIndex))
end
-- misc ship settings (label, crew)
ship:SetLabel(mission.shiplabel)
for _ = 1, mission.crew_num do
ship:Enroll(Character.New())
end
-- load a hyperdrive
local default_drive = Equipment.hyperspace['hyperdrive_'..tostring(shipdef.hyperdriveClass)]
if default_drive then
ship:AddEquip(default_drive)
else
ship:AddEquip(Equipment.hyperspace['hyperdrive_1'])
end
-- load a laser
local max_laser_size
if default_drive then
max_laser_size = shipdef.capacity - default_drive.capabilities.mass
else
max_laser_size = shipdef.capacity
end
local laserdefs = utils.build_array(utils.filter(function (_,laser) return laser:IsValidSlot('laser_front')
and laser.capabilities.mass <= max_laser_size
and laser.l10n_key:find("PULSECANNON") end, pairs(Equipment.laser)))
local laserdef = laserdefs[Engine.rand:Integer(1,#laserdefs)]
ship:AddEquip(laserdef)
-- load passengers
if mission.pickup_pass > 0 then
ship:AddEquip(Equipment.misc.cabin_occupied, mission.pickup_pass)
end
-- load atmo_shield
if shipdef.equipSlotCapacity.atmo_shield ~= 0 then
ship:AddEquip(Equipment.misc.atmospheric_shielding)
end
return ship
end
local onChat = function (form, ref, option)
-- Ad has been clicked on in banter board.
local ad = ads[ref]
form:Clear()
if option == -1 then
form:Close()
return
end
form:SetFace(ad.client)
-- TODO: work out a better system for equipment qualification check
-- local qualified = isQualifiedFor(ad)
-- if not qualified then
-- local denytext = string.interp(l.EQUIPMENT, {cabins = ad.pickup_crew + ad.deliver_crew +
-- ad.pickup_pass + ad.deliver_pass})
-- form:SetMessage(denytext)
-- return
-- end
if option == 0 then
local introtext = string.interp(ad.flavour.introtext, {
name = ad.client.name,
entity = ad.entity,
problem = ad.problem,
cash = Format.Money(ad.reward),
ship = ad.shipdef_name,
starport = ad.station_local:GetSystemBody().name,
shiplabel = ad.shiplabel,
planet = ad.planet_target:GetSystemBody().name
})
form:SetMessage(introtext)
elseif option == 1 then
local dist
if ad.flavour.loctype == "CLOSE_PLANET" or ad.flavour.loctype == "CLOSE_SPACE" then
dist = string.format("%.0f", ad.dist/1000)
else
dist = string.format("%.2f", ad.dist/1000)
end
local locationtext = string.interp(ad.flavour.locationtext, {
starport = ad.station_local:GetSystemBody().name,
shiplabel = ad.shiplabel,
system = ad.system_target:GetStarSystem().name,
sectorx = ad.system_target.sectorX,
sectory = ad.system_target.sectorY,
sectorz = ad.system_target.sectorZ,
dist = dist,
lat = decToDegMinSec(math.rad2deg(ad.lat)),
long = decToDegMinSec(math.rad2deg(ad.long)),
planet = ad.planet_target:GetSystemBody().name
})
form:SetMessage(locationtext)
elseif option == 2 then
local typeofhelptext = string.interp(ad.flavour.typeofhelptext, {
starport = ad.station_local:GetSystemBody().name,
crew = ad.crew_num,
pass = ad.pickup_pass,
deliver_crew = ad.deliver_crew
})
form:SetMessage(typeofhelptext)
elseif option == 3 then
local howmuchtimetext = string.interp(ad.flavour.howmuchtimetext, {due = Format.Date(ad.due)})
form:SetMessage(howmuchtimetext)
elseif option == 5 then
-- TODO: work out a better system for equipment qualification check (add cargo space check + reputation)
local qualified = isQualifiedFor(ad)
if not qualified then
local cabins = ad.pickup_crew + ad.deliver_crew + ad.pickup_pass + ad.deliver_pass
local denytext = string.interp(l.EQUIPMENT, {unit = cabins, equipment = l.UNOCCUPIED_PASSENGER_CABINS})
form:SetMessage(denytext)
return
end
form:RemoveAdvertOnClose()
ads[ref] = nil
local mission = {
-- these variables are hardcoded and need to be filled
type = "searchrescue",
client = ad.client,
location = ad.location,
due = ad.due,
reward = ad.reward,
status = "ACTIVE",
-- these variables are script specific
station_local = ad.station_local,
planet_local = ad.planet_local,
system_local = ad.system_local,
station_target = ad.station_target,
planet_target = ad.planet_target,
system_target = ad.system_target,
entity = ad.entity,
problem = ad.problem,
dist = ad.dist,
flavour = ad.flavour,
target = "NIL",
lat = ad.lat,
long = ad.long,
shipdef_name = ad.shipdef_name,
shiplabel = ad.shiplabel,
crew_num = ad.crew_num,
-- "..._orig" => original variables from ad
pickup_crew_orig = ad.pickup_crew,
pickup_pass_orig = ad.pickup_pass,
pickup_comm_orig = copyTable(ad.pickup_comm),
deliver_crew_orig = ad.deliver_crew,
deliver_pass_orig = ad.deliver_pass,
deliver_comm_orig = copyTable(ad.deliver_comm),
-- variables are changed based on completion status
pickup_crew = ad.pickup_crew,
pickup_pass = ad.pickup_pass,
pickup_comm = copyTable(ad.pickup_comm),
deliver_crew = ad.deliver_crew,
deliver_pass = ad.deliver_pass,
deliver_comm = copyTable(ad.deliver_comm),
pickup_crew_check = "NOT",
pickup_pass_check = "NOT",
pickup_comm_check = {},
deliver_crew_check = "NOT",
deliver_pass_check = "NOT",
deliver_comm_check = {},
cargo_pass = {},
cargo_comm = {},
searching = false -- makes sure only one search is active for this mission (function "searchForTarget")
}
-- create target ship if in the same systems, otherwise create when jumping there
if mission.flavour.loctype ~= "FAR_SPACE" then
mission.target = createTargetShip(mission)
end
-- load crew/passenger
if ad.deliver_crew > 0 then
for _ = 1, ad.deliver_crew do
local passenger = Character.New()
addPassenger(Game.player)
table.insert(mission.cargo_pass, passenger)
end
end
if ad.deliver_pass > 0 then
for _ = 1, ad.deliver_pass do
local passenger = Character.New()
addPassenger(Game.player)
table.insert(mission.cargo_pass, passenger)
end
end
form:SetMessage(l.THANK_YOU_ACCEPTANCE_TXT)
addMission(mission)
return
end
form:AddOption(l.WHERE_IS_THE_TARGET, 1)
form:AddOption(l.TYPE_OF_HELP, 2)
form:AddOption(l.HOW_MUCH_TIME, 3)
form:AddOption(l.COULD_YOU_REPEAT_THE_ORIGINAL_REQUEST, 0)
form:AddOption(l.OK_AGREED, 5)
end
local onDelete = function (ref)
ads[ref] = nil
end
local isEnabled = function (ref)
-- Called from within ad to enable or disable it for selecton on the banter board.
-- TODO: possibly integrate reputation based qualification filter
return true
end
--local nearbysystems
local findNearbyStations = function (vacuum, body)
-- Return a list with stations within this system sorted by distance from supplied body (ascending). If vacuum is set to true
-- then only return orbital stations
-- get station bodies within current system depending on vacuum variable
local nearbystations_raw
if vacuum == true then
nearbystations_raw = Space.GetBodies(function (body)
return body.superType == 'STARPORT' and (body.type == 'STARPORT_ORBITAL' or (not body.path:GetSystemBody().parent.hasAtmosphere)) end)
else
nearbystations_raw = Space.GetBodies(function (body) return body.superType == 'STARPORT' end)
end
-- determine distance to body
local nearbystations_dist = {}
for _,station in pairs(nearbystations_raw) do
if station ~= body then
local dist = body:DistanceTo(station)
table.insert(nearbystations_dist, {station, dist})
end
end
-- sort stations by distance to body (ascending)
local nearbystations = {}
table.sort(nearbystations_dist, function (a,b) return a[2] < b[2] end)
for _,data in ipairs(nearbystations_dist) do
table.insert(nearbystations, data[1].path)
end
return nearbystations
end
local findNearbyPlanets = function (station)
-- Return list of all rocky planets in the system (excluding any planets with stations), sorted by
-- distance from the station.
-- get rocky planets (except the one the station is on)
local nearbyplanets_raw = {}
for _,path in pairs(Game.system:GetBodyPaths()) do
local sbody = path:GetSystemBody()
if sbody.superType == "ROCKY_PLANET" then
if sbody ~= station.path:GetSystemBody().parent then
table.insert(nearbyplanets_raw, Space.GetBody(sbody.index))
end
end
end
-- get planets with stations and remove from planet list
local stations = Space.GetBodies(function (body)
return body.type == 'STARPORT_SURFACE' end)
for _,station in pairs(stations) do
for i=#nearbyplanets_raw, 1, -1 do
if nearbyplanets_raw[i] == Space.GetBody(station.path:GetSystemBody().parent.index) then
table.remove(nearbyplanets_raw, i)
break
end
end
end
-- determine distance to player station
local nearbyplanets_dist = {}
for _,planet in pairs(nearbyplanets_raw) do
local dist = station:DistanceTo(planet)
table.insert(nearbyplanets_dist, {planet, dist})
end
-- sort planets by distance to station (ascending)
local nearbyplanets = {}
table.sort(nearbyplanets_dist, function (a,b) return a[2] < b[2] end)
for _,data in ipairs(nearbyplanets_dist) do
table.insert(nearbyplanets, data[1].path)
end
return nearbyplanets
end
local findNearbySystems = function (with_stations)
-- Return list of systems within max_mission_dist distance and sorted by distance from player system (ascending).
-- get systems (either inhabited or not - depending on variable with_stations)
local nearbysystems_raw
if with_stations == true then
nearbysystems_raw = Game.system:GetNearbySystems(max_mission_dist, function (s) return #s:GetStationPaths() > 0 end)
else
nearbysystems_raw = Game.system:GetNearbySystems(max_mission_dist, function (s) return #s:GetStationPaths() == 0 end)
end
-- determine distance to player system
local nearbysystems_dist = {}
for _,system in pairs(nearbysystems_raw) do
local dist = Game.system:DistanceTo(system)
table.insert(nearbysystems_dist, {system, dist})
end
-- sort systems by distance to player system (ascending)
local nearbysystems = {}
table.sort(nearbysystems_dist, function (a,b) return a[2] < b[2] end)
for _,data in ipairs(nearbysystems_dist) do
table.insert(nearbysystems, data[1].path)
end
return nearbysystems
end
local randomPlanet = function (system)
-- Return random planet located in the provided system.
local planets = {}
local paths = system:GetBodyPaths()
for _,path in pairs(paths) do
local sbody = path:GetSystemBody()
local supertype = sbody.superType
if supertype == "ROCKY_PLANET" or supertype == "GAS_GIANT" then
table.insert(planets, path)
end
end
if #planets > 0 then return planets[Engine.rand:Integer(1,#planets)] else return nil end
end
local flyToNearbyStation = function (ship)
-- Fly the supplied ship to the closest station. If no station is in the system then jump to the
-- closest system that does have a station.
-- check if ship has atmo shield and limit to vacuum starports if not
local vacuum = false
if ship:CountEquip(Equipment.misc.atmospheric_shielding) == 0 then
vacuum = true
end
local nearbysystems
local nearbystations = findNearbyStations(vacuum, ship)
if #nearbystations > 0 then
-- add ship to discard pile to jump away later
table.insert(discarded_ships, ship)
-- blast off ship if LANDED
if ship.flightState == "LANDED" then
ship:AIEnterLowOrbit(ship:FindNearestTo("PLANET") or ship:FindNearestTo("STAR"))
Timer:CallAt(Game.time + 5, function () ship:AIDockWith(Space.GetBody(nearbystations[1].bodyIndex)) end)
else
ship:AIDockWith(Space.GetBody(nearbystations[1].bodyIndex))
end
else
local with_stations = true
nearbysystems = findNearbySystems(with_stations)
if #nearbysystems > 0 then
ship:AIEnterLowOrbit(ship:FindNearestTo("PLANET") or ship:FindeNearestTo("STAR"))
Timer:CallAt(Game.time + 5, function () ship:InitiateHyperjumpTo(nearbysystems[1]) end)
else
return
end
end
end
local discardShip = function (ship)
-- Gracefully discard ship that is not needed any longer for the ship by hyperjumping
-- away to nearby (if possible populated) system.
local with_stations = true
local nearbysystems = findNearbySystems(with_stations)
if #nearbysystems > 0 then
Timer:CallAt(Game.time + Engine.rand:Integer(5,10), function ()
ship:AIEnterLowOrbit(ship:FindNearestTo("PLANET") or ship:FindeNearestTo("STAR"))
Timer:CallAt(Game.time + 5, function () ship:InitiateHyperjumpTo(nearbysystems[1], 3, 10) end)
end)
else
with_stations = false
nearbysystems = findNearbySystems(with_stations)
if #nearbysystems > 0 then
Timer:CallAt(Game.time + Engine.rand:Integer(5,10), function ()
ship:AIEnterLowOrbit(ship:FindNearestTo("PLANET") or ship:FindeNearestTo("STAR"))