Lua - Random Whale Generation Script

Post new mods and scenarios here.

Moderator: MOD_Command

Post Reply
Rory Noonan
Posts: 2418
Joined: Thu Dec 18, 2014 1:53 am
Location: Brooklyn, NY

Lua - Random Whale Generation Script

Post by Rory Noonan »

I've been doing a little work on Lua scripting. I've been able to do the odd bit here and there, but it has been clunky and time consuming.

Below is the code for a script to generate a random number of whales in an area chosen by the user. All you need is a scenario with a side named 'Nature' and a mission (I use sea-control) called 'Whale Patrol'.

Previously I'd done this by copying and pasting the same entry over and over, manually changing the relevant values. It worked, but it was laborious.

After about an hour of working through the 'Quick guide to Lua' included with Lua for Windows I was able to refine this into a much more elegant, powerful script that makes it just as easy to add 1,000 whales as it is to add 1.

Obviously this is a simple script, but I wanted to post it to show others how powerful Lua is and how simple it is to learn. I had zero knowledge of Lua before 1.06 and no experience programming at all.

Below is the script, fully commented and ready to paste into the game. Instructions are included.

<<START>>

--Whale generation script v1.0 by Apache85

--[[Generates a random number of whales and attaches them to a mission
Instructions:
1. Open scenario, create sides
2. Copy any paste this script into a text editor
3. Edit any values to match your needs; i.e. latitudes/longitudes
4. In script console (or event editor if using a lua event) copy and paste the script and click 'run script'
5. Without any modification, this will produce between 5-15 whales on side 'Nature' around the North of the Falklands, and assign them to a mission called 'Whale Patrol'.

YOU NEED TO CREATE THE SIDE AND MISSION FOR THIS TO WORK CORRECTLY]]


math.randomseed(os.time()) --Resets the random seed to ensure actual randomness, not the same results over and over

--Decimal latitude / longitude values for NE and SW corner. Be careful to LEAVE OUT decimals and ensure that the xx0000000000001 / xx9999999999999 format is used
NW_CornerLat = -460000000000001
SE_CornerLat = -509999999999999
NW_CornerLon = -630000000000001
SE_CornerLon = -539999999999999

TargetSide = "Nature" --Change string value to match biological side name
TargetMission = "Whale Patrol" --Change string value to match desired mission

a=0 --counter initialised at zero
TargetNumber=math.random(5,15) --change parameters to increase min and max number of whales

repeat
count=a+1 --counter step up increment (+1 here)
a=count --resets counter to new value
SeqName=("Whale " .. count) --Sequentially numbered name for created whale
ScenEdit_AddUnit({
type = "Submarine",
side = TargetSide,
name = SeqName,
dbid = "92", --dbid for 'whale' in db3000
latitude = (math.random(SE_CornerLat,NW_CornerLat) / 1e13), --produces a random number between the SE corner latitude and the NW corner latitude
longitude = (math.random(NW_CornerLon,SE_CornerLon) / 1e13), --produces a random number between the SE corner longitude and the NW corner longitude
})
ScenEdit_AssignUnitToMission(
SeqName,
'Whale Patrol'
)
until count == TargetNumber --Finishes loop when 'count' reaches 'TargetNumber'


<<END>>

I tried using the 'code' tags but it just ran off the screen... Is there a better way to post code on the forum?

Anyway, hopefully this is useful to someone or inspires them to learn a little Lua!
Image
skjold89
Posts: 165
Joined: Tue Sep 29, 2015 12:00 pm

RE: Lua - Random Whale Generation Script

Post by skjold89 »

Thanks for the effort man!
User avatar
mikkey
Posts: 3173
Joined: Sun Feb 10, 2008 1:04 pm
Location: Slovakia

RE: Lua - Random Whale Generation Script

Post by mikkey »

Excellent work, thanks for sharing!
Rory Noonan
Posts: 2418
Joined: Thu Dec 18, 2014 1:53 am
Location: Brooklyn, NY

RE: Lua - Random Whale Generation Script

Post by Rory Noonan »

You're welcome. Every time I look at it I see something I can improve haha.
Image
User avatar
AlGrant
Posts: 912
Joined: Tue Aug 18, 2015 4:38 am

RE: Lua - Random Whale Generation Script

Post by AlGrant »


This looks great - I gave it a quick try but think I must be doing something wrong as every time I run it int he script console it returns: ERROR: [string "chunk"]:1: unexpected symbol near '<'

I have no idea about Lua (or any other) scripting so probably something I'm doing wrong.



GOD'S EYE DISABLED.
Rory Noonan
Posts: 2418
Joined: Thu Dec 18, 2014 1:53 am
Location: Brooklyn, NY

RE: Lua - Random Whale Generation Script

Post by Rory Noonan »

Oh... I think I know what that is. As mentioned above there was a bit of a problem using the 'code' function on the forum, so I added <<Start>> and <<end>> tags to help identify where the code begins and ends.

Thinking about it, it is possible that copying and pasting from the forum could introduce problems with the comments as well. To avoid any further problems, I've attached the script in .txt format (inside the .zip file, obviously).
Attachments
WhaleGenv1.1.txt
(2.03 KiB) Downloaded 65 times
Image
i224747
Posts: 89
Joined: Fri Nov 06, 2015 1:19 am

RE: Lua - Random Whale Generation Script

Post by i224747 »

Created 260 whales in an area of 385864 km^2.

- Created contacts should be named as "Contact###" and not as "Whale###"
- Created whales should have been different speeds, altitudes and headings.
Not sure if this possible with LUA.





Rory Noonan
Posts: 2418
Joined: Thu Dec 18, 2014 1:53 am
Location: Brooklyn, NY

RE: Lua - Random Whale Generation Script

Post by Rory Noonan »

There are instructions on how to change the naming of whatever you wish to generate in the comments in the script. Generally since they won't be on the player side, the name is pretty much irrelevant because it will come up as 'GOBLIN xx' until identified. If you attack it with end-game calcs turned on you can see the name, but that's not really my problem or concern (you can also change the name if you wish, as I already mentioned).

As for different speeds, altitudes and headings, this will happen naturally with the assignment to a sea control mission.

As I mentioned earlier, it's a script to demonstrate the power of Lua and the ease of learning it.
Image
User avatar
AlGrant
Posts: 912
Joined: Tue Aug 18, 2015 4:38 am

RE: Lua - Random Whale Generation Script

Post by AlGrant »


apache85,

Thanks for that, I've got it working now and going to take a closer look at Lua.
ORIGINAL: apache85

There are instructions on how to change the naming of whatever you wish to generate in the comments in the script. Generally since they won't be on the player side, the name is pretty much irrelevant because it will come up as 'GOBLIN xx' until identified. If you attack it with end-game calcs turned on you can see the name, but that's not really my problem or concern (you can also change the name if you wish, as I already mentioned).

As for different speeds, altitudes and headings, this will happen naturally with the assignment to a sea control mission.

As I mentioned earlier, it's a script to demonstrate the power of Lua and the ease of learning it.

The script is quite easy to adjust (even for me! [:D]).
I tweaked some of the values and used it to create a random number of fishing vessels off the Irish coast.
The ships were added to a 'Fishing Grounds' Sea Control mission. The units were named 'MFV' 1,2,3 etc and all seems to be working just fine. The fishing boats all set off on various courses once the scenario starts.

As for the speeds ..... all the units have the same speed (5kts), this changes depending on the Station throttle speeds set in the Mission Editor. If set to Cruise then they all had 10kts.


GOD'S EYE DISABLED.
i224747
Posts: 89
Joined: Fri Nov 06, 2015 1:19 am

RE: Lua - Random Whale Generation Script

Post by i224747 »

ORIGINAL: AlGrant

As for the speeds ..... all the units have the same speed (5kts), this changes depending on the Station throttle speeds set in the Mission Editor. If set to Cruise then they all had 10kts.

Quite realistic...

Dont tell me you cannot give AI controlled units a specific speed (for example 3 knots) in this game? Really? OMG.
Rory Noonan
Posts: 2418
Joined: Thu Dec 18, 2014 1:53 am
Location: Brooklyn, NY

RE: Lua - Random Whale Generation Script

Post by Rory Noonan »

ORIGINAL: AlGrant


apache85,

Thanks for that, I've got it working now and going to take a closer look at Lua.
ORIGINAL: apache85

There are instructions on how to change the naming of whatever you wish to generate in the comments in the script. Generally since they won't be on the player side, the name is pretty much irrelevant because it will come up as 'GOBLIN xx' until identified. If you attack it with end-game calcs turned on you can see the name, but that's not really my problem or concern (you can also change the name if you wish, as I already mentioned).

As for different speeds, altitudes and headings, this will happen naturally with the assignment to a sea control mission.

As I mentioned earlier, it's a script to demonstrate the power of Lua and the ease of learning it.

The script is quite easy to adjust (even for me! [:D]).
I tweaked some of the values and used it to create a random number of fishing vessels off the Irish coast.
The ships were added to a 'Fishing Grounds' Sea Control mission. The units were named 'MFV' 1,2,3 etc and all seems to be working just fine. The fishing boats all set off on various courses once the scenario starts.

As for the speeds ..... all the units have the same speed (5kts), this changes depending on the Station throttle speeds set in the Mission Editor. If set to Cruise then they all had 10kts.



Glad you're finding it useful!

If varied speeds are important you could have multiple instances of the script with differing unit types and mission settings. The trade-off is it's more work. Certainly achievable though, and quite trivial to do.

In my original use of the script the idea is to generate whales off the Falklands for a scenario where there is a confirmed diesel sub threat. The whales on a sea control mission with speed setting to 'flank' move at 4kts, the same as the threat sub so it works perfectly.

The script also works quite well with false contacts, and as their DbIDs are sequential you can even randomise between small, medium and large with one iteration of the script.
Image
Whicker
Posts: 664
Joined: Tue Jun 19, 2018 9:54 pm

RE: Lua - Random Whale Generation Script

Post by Whicker »

I'm trying to add a random depth to the random fish/whale/bio script and no matter what I do I can't get a depth of anything other than -131.

local new_bio = ScenEdit_AddUnit({side='Biologics', type='Submarine',name='Biologic #'..i, dbid=DBID,latitude=v_lat,longitude=v_lon, altitude='-200'})

no matter what I put in for the altitude it is always -131. Works the same with actual subs as bios.

I've tried alt instead of altitude, '-200 m', '-200 ft' etc and no matter what it is always -131.

Any idea why? can you show me a script to create a sub/fish where you can set the depth?
User avatar
michaelm75au
Posts: 12455
Joined: Sat May 05, 2001 8:00 am
Location: Melbourne, Australia

RE: Lua - Random Whale Generation Script

Post by michaelm75au »

Use depth=100. That should put is at -100M
Michael
User avatar
michaelm75au
Posts: 12455
Joined: Sat May 05, 2001 8:00 am
Location: Melbourne, Australia

RE: Lua - Random Whale Generation Script

Post by michaelm75au »

Actually it looks like you may have uncovered a defect; if you use FT or M in the depth, it doesn't treat it as below SL.
Michael
Whicker
Posts: 664
Joined: Tue Jun 19, 2018 9:54 pm

RE: Lua - Random Whale Generation Script

Post by Whicker »

great - that works for me. I looked for depth as an attribute but didn't see it.
Whicker
Posts: 664
Joined: Tue Jun 19, 2018 9:54 pm

RE: Lua - Random Whale Generation Script

Post by Whicker »

updated code for random bios.

- random speed between 0 and 4
- random depth (max 270m or so)

I still don't like the way lat and lng are set, kind of a pain. Also it needs a large area - more than one lat/lng integer(?). That can be fixed by changing the random chunk added to it, would be nice if the area could be set with ref points and then add a better way to randomize it. Good enough for now though. I also set the area in the script to larger than what the mission zone is, makes them converge on it for the ones that spawn outside of it.

If you watch the fish depth at high compression it varies -seems to always come up to -131 for a bit and go back down to what it is set to by the script - that actually seems good, I wonder if that is on purpose? they don't seem to do this if I create one manually but I just did it once to see.
math.randomseed(os.time())
bio_num = math.random(35,55) --change to your specified minimum and maximum number of bios

for i = 1,bio_num do
redo_count = 0
::redo::
local lat_var = math.random(1,(10^13)) --don't change
local lon_var = math.random(1,(10^13)) --don't change
v_lat = math.random(14,26) + (lat_var/(10^13)) --change the first set (south is negative) to your specified minimum and maximum latitude values; it's important that the first number is smaller than the second.
v_lon = math.random(-78,-60) + (lon_var/(10^13)) --change first set (west is negative!) to your specified minimum and maximum longitude values; it's important that the first number is smaller than the second.
elevation = World_GetElevation({latitude=v_lat, longitude=v_lon})
if elevation > -40 then --(meters?) Checks to see if the water is deep enough, adjust as you please

redo_count = redo_count + 1
print("picked bad co-ordinates")
if redo_count >50 then
print ('units were not able to find a suitable spot for placement. Re-check latitude and longitude settings')
break --this cuts the loop if there are no suitable positions found after 50 tries, prevents infinite loop/game freeze

else
goto redo --retries the placement if the water is too shallow
end
end

DBIDTABLE = { 92,355,354 } --list of dbids for bios, could be subs
local actual_depth = elevation --need 2 variables for depth - actual depth at that location and the depth the unit is set to, though this is only for the print to log
if elevation < -300 then elevation = -299 end -- max depth for bios is 300, if actual depth is more than 300m set to 299 so random depth is achievable
local bio_depth = -1*elevation*math.random(100, 900)/1000 --have to reverse the sign, depth is a positive number, multiply by random percent between 10 and 90%
DBID = DBIDTABLE[math.random( 1, #DBIDTABLE)] --choose random dbid for unit
local new_bio = ScenEdit_AddUnit({side='Biologics', type='Submarine',name='Biologic #'..i, dbid=DBID,latitude=v_lat,longitude=v_lon, depth='bio_depth', manualSpeed=math.random(0, 4)})

ScenEdit_AssignUnitToMission( new_bio.name, 'Whales') --add to mission which helps with the course
print (new_bio.name..' with dbid '..DBID..' was created in water with a depth of '..actual_depth..'m, at a depth of ' ..bio_depth )
end
Rory Noonan
Posts: 2418
Joined: Thu Dec 18, 2014 1:53 am
Location: Brooklyn, NY

RE: Lua - Random Whale Generation Script

Post by Rory Noonan »

I haven't looked at this in nearly 2 years, so yes there is a lot of room for improvement. Have at it.
Image
Post Reply

Return to “Mods and Scenarios”