1-- Copyright © 2008-2021 Pioneer Developers. See AUTHORS.txt for details
2-- Licensed under the terms of the GPL v3. See licenses/GPL-3.txt
3
4local Engine = require 'Engine'
5local Game = require 'Game'
6local Space = require 'Space'
7local Event = require 'Event'
8local Serializer = require 'Serializer'
9local ShipDef = require 'ShipDef'
10local Ship = require 'Ship'
11local utils = require 'utils'
12
13local loaded
14
15local spawnShips = function ()
16	local population = Game.system.population
17
18	if population == 0 then
19		return
20	end
21
22	local stations = Space.GetBodies(function (body) return body:isa("SpaceStation") and not body.isGroundStation end)
23	if #stations == 0 then
24		return
25	end
26
27	local shipdefs = utils.build_array(utils.filter(function (k,def) return def.tag == 'STATIC_SHIP' end, pairs(ShipDef)))
28	if #shipdefs == 0 then return end
29
30	-- one ship per three billion, min 1, max 2*num of stations
31	local num_bulk_ships = math.min(#stations*2, math.floor((math.ceil(population)+2)/3))
32
33	for i=1, num_bulk_ships do
34		local station = stations[Engine.rand:Integer(1,#stations)]
35		local ship = Space.SpawnShipParked(shipdefs[Engine.rand:Integer(1,#shipdefs)].id, station)
36		ship:SetLabel(Ship.MakeRandomLabel())
37	end
38end
39
40local onEnterSystem = function (player)
41	if not player:IsPlayer() then return end
42
43	spawnShips()
44end
45
46local onGameStart = function ()
47	if loaded == nil then
48		spawnShips()
49	end
50	loaded = nil
51end
52
53local serialize = function ()
54	return true
55end
56
57local unserialize = function (data)
58	loaded = true
59end
60
61Event.Register("onEnterSystem", onEnterSystem)
62Event.Register("onGameStart", onGameStart)
63
64Serializer:Register("BulkShips", serialize, unserialize)
65