forked from mrSkortch/MissionScriptingTools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmist.lua
More file actions
5057 lines (4276 loc) · 160 KB
/
mist.lua
File metadata and controls
5057 lines (4276 loc) · 160 KB
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
--MiST Mission Scripting Tools
mist = {}
-- don't change these
mist.majorVersion = 3
mist.minorVersion = 4
mist.build = 27
--------------------------------------------------------------------------------------------------------------
-- the main area
do
local coroutines = {}
local function update_alive_units() -- coroutine function
local lalive_units = mist.DBs.aliveUnits -- local references for faster execution
local lunits = mist.DBs.unitsByNum
local ldeepcopy = mist.utils.deepCopy
local lUnit = Unit
local lremovedAliveUnits = mist.DBs.removedAliveUnits
local updatedUnits = {}
if #lunits > 0 then
local units_per_run = math.ceil(#lunits/20)
if units_per_run < 5 then
units_per_run = 5
end
for i = 1, #lunits do
if lunits[i].category ~= 'static' then -- can't get statics with Unit.getByName :(
local unit = lUnit.getByName(lunits[i].unitName)
if unit then
--print('unit named ' .. lunits[i].unitName .. ' alive!')
local pos = unit:getPosition()
local newtbl = ldeepcopy(lunits[i])
if pos then
newtbl['pos'] = pos.p
end
newtbl['unit'] = unit
--newtbl['rt_id'] = unit.id_
lalive_units[unit.id_] = newtbl
updatedUnits[unit.id_] = true
end
end
if i%units_per_run == 0 then
--print('yielding at: ' .. tostring(i))
coroutine.yield()
--print('resuming at: ' .. tostring(i))
end
end
-- All units updated, remove any "alive" units that were not updated- they are dead!
for unit_id, unit in pairs(lalive_units) do
if not updatedUnits[unit_id] then
lremovedAliveUnits[unit_id] = unit
lalive_units[unit_id] = nil
end
end
end
end
local update_alive_units_counter = 0
-- THE MAIN FUNCTION -- Accessed 100 times/sec.
mist.main = function()
timer.scheduleFunction(mist.main, {}, timer.getTime() + 0.01) --reschedule first in case of Lua error
----------------------------------------------------------------------------------------------------------
--area to add new stuff in
-----------------------------------------------------------------------------------------------------------
--updating alive units
update_alive_units_counter = update_alive_units_counter + 1
if update_alive_units_counter == 5 then
update_alive_units_counter = 0
if not coroutines.update_alive_units then
coroutines['update_alive_units'] = coroutine.create(update_alive_units)
end
coroutine.resume(coroutines.update_alive_units)
if coroutine.status(coroutines.update_alive_units) == 'dead' then
coroutines.update_alive_units = nil
end
end
mist.do_scheduled_functions()
end -- end of mist.main
end
------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------
--Modified Slmod task scheduler, superior to timer.scheduleFunction
do
local Tasks = {}
local task_id = 0
--[[ mist.scheduleFunction:
int id = mist.schedule_task(f function, vars table, t number, rep number, st number)
id - integer id of this function task
f - function to run
vars - table of vars for that function
t - time to run function
rep - time between repetitions of this function (OPTIONAL)
st - time when repetitions of this function will stop automatically (OPTIONAL)
]]
mist.scheduleFunction = function(f, vars, t, rep, st)
--verify correct types
assert(type(f) == 'function', 'variable 1, expected function, got ' .. type(f))
assert(type(vars) == 'table' or vars == nil, 'variable 2, expected table or nil, got ' .. type(f))
assert(type(t) == 'number', 'variable 3, expected number, got ' .. type(t))
assert(type(rep) == 'number' or rep == nil, 'variable 4, expected number or nil, got ' .. type(rep))
assert(type(st) == 'number' or st == nil, 'variable 5, expected number or nil, got ' .. type(st))
if not vars then
vars = {}
end
task_id = task_id + 1
table.insert(Tasks, {f = f, vars = vars, t = t, rep = rep, st = st, id = task_id})
return task_id
end
-- removes a scheduled function based on the function's id. returns true if successful, false if not successful.
mist.removeFunction = function(id)
local i = 1
while i <= #Tasks do
if Tasks[i].id == id then
table.remove(Tasks, i)
else
i = i + 1
end
end
end
--------------------------------------------------------------------------------------------------------------------
-- not intended for users to use this function.
mist.do_scheduled_functions = function()
local i = 1
while i <= #Tasks do
if not Tasks[i].rep then -- not a repeated process
if Tasks[i].t <= timer.getTime() then
local Task = Tasks[i] -- local reference
table.remove(Tasks, i)
local err, errmsg = pcall(Task.f, unpack(Task.vars, 1, table.maxn(Task.vars)))
if not err then
env.info('mist.scheduleFunction, error in scheduled function: ' .. errmsg)
end
--Task.f(unpack(Task.vars, 1, table.maxn(Task.vars))) -- do the task, do not increment i
else
i = i + 1
end
else
if Tasks[i].st and Tasks[i].st <= timer.getTime() then --if a stoptime was specified, and the stop time exceeded
table.remove(Tasks, i) -- stop time exceeded, do not execute, do not increment i
elseif Tasks[i].t <= timer.getTime() then
local Task = Tasks[i] -- local reference
Task.t = timer.getTime() + Task.rep --schedule next run
local err, errmsg = pcall(Task.f, unpack(Task.vars, 1, table.maxn(Task.vars)))
if not err then
env.info('mist.scheduleFunction, error in scheduled function: ' .. errmsg)
end
--Tasks[i].f(unpack(Tasks[i].vars, 1, table.maxn(Tasks[i].vars))) -- do the task
i = i + 1
else
i = i + 1
end
end
end
end
end
do
local idNum = 0
--Simplified event handler
mist.addEventHandler = function(f) --id is optional!
local handler = {}
idNum = idNum + 1
handler.id = idNum
handler.f = f
handler.onEvent = function(self, event)
self.f(event)
end
world.addEventHandler(handler)
end
mist.removeEventHandler = function(id)
for key, handler in pairs(world.eventHandlers) do
if handler.id and handler.id == id then
world.eventHandlers[key] = nil
return true
end
end
return false
end
end
----------------------------------------------------------------------------------------------
-- Utils- conversion, Lua utils, etc.
mist.utils = {}
mist.utils.toDegree = function(angle)
return angle*180/math.pi
end
mist.utils.toRadian = function(angle)
return angle*math.pi/180
end
mist.utils.metersToNM = function(meters)
return meters/1852
end
mist.utils.metersToFeet = function(meters)
return meters/0.3048
end
mist.utils.NMToMeters = function(NM)
return NM*1852
end
mist.utils.feetToMeters = function(feet)
return feet*0.3048
end
mist.utils.mpsToKnots = function(mps)
return mps*3600/1852
end
mist.utils.mpsToKmph = function(mps)
return mps*3.6
end
mist.utils.knotsToMps = function(knots)
return knots*1852/3600
end
mist.utils.kmphToMps = function(kmph)
return kmph/3.6
end
function mist.utils.makeVec2(Vec3)
if Vec3.z then
return {x = Vec3.x, y = Vec3.z}
else
return {x = Vec3.x, y = Vec3.y} -- it was actually already vec2.
end
end
function mist.utils.makeVec3(Vec2, y)
if not Vec2.z then
if not y then
y = 0
end
return {x = Vec2.x, y = y, z = Vec2.y}
else
return {x = Vec2.x, y = Vec2.y, z = Vec2.z} -- it was already Vec3, actually.
end
end
function mist.utils.makeVec3GL(Vec2, offset)
local adj = offset or 0
if not Vec2.z then
return {x = Vec2.x, y = (land.getHeight(Vec2) + adj), z = Vec2.y}
else
return {x = Vec2.x, y = (land.getHeight({x = Vec2.x, y = Vec2.z}) + adj), z = Vec2.z}
end
end
mist.utils.zoneToVec3 = function(zone)
local new = {}
if type(zone) == 'table' and zone.point then
new.x = zone.point.x
new.y = zone.point.y
new.z = zone.point.z
return new
elseif type(zone) == 'string' then
zone = trigger.misc.getZone(zone)
if zone then
new.x = zone.point.x
new.y = zone.point.y
new.z = zone.point.z
return new
end
end
end
-- gets heading-error corrected direction from point along vector vec.
function mist.utils.getDir(vec, point)
local dir = math.atan2(vec.z, vec.x)
dir = dir + mist.getNorthCorrection(point)
if dir < 0 then
dir = dir + 2*math.pi -- put dir in range of 0 to 2*pi
end
return dir
end
-- gets distance in meters between two points (2 dimensional)
function mist.utils.get2DDist(point1, point2)
point1 = mist.utils.makeVec3(point1)
point2 = mist.utils.makeVec3(point2)
return mist.vec.mag({x = point1.x - point2.x, y = 0, z = point1.z - point2.z})
end
-- gets distance in meters between two points (3 dimensional)
function mist.utils.get3DDist(point1, point2)
return mist.vec.mag({x = point1.x - point2.x, y = point1.y - point2.y, z = point1.z - point2.z})
end
--from http://lua-users.org/wiki/CopyTable
mist.utils.deepCopy = function(object)
local lookup_table = {}
local function _copy(object)
if type(object) ~= "table" then
return object
elseif lookup_table[object] then
return lookup_table[object]
end
local new_table = {}
lookup_table[object] = new_table
for index, value in pairs(object) do
new_table[_copy(index)] = _copy(value)
end
return setmetatable(new_table, getmetatable(object))
end
return _copy(object)
end
-- From http://lua-users.org/wiki/SimpleRound
-- use negative idp for rounding ahead of decimal place, positive for rounding after decimal place
mist.utils.round = function(num, idp)
local mult = 10^(idp or 0)
return math.floor(num * mult + 0.5) / mult
end
-- porting in Slmod's dostring
mist.utils.dostring = function(s)
local f, err = loadstring(s)
if f then
return true, f()
else
return false, err
end
end
--[[ mist.utils.typeCheck(fname, type_tbl, var_tbl)
Type-checking function:
Checks a var_tbl to a type_tbl. Returns true if the var_tbl passes the type check, returns false plus an error message if the var_tbl fails.
type_tbl examples:
type_tbl = { {'table', 'number'}, 'string', 'number', 'number', {'string', 'nil'}, {'number', 'nil'} }
Compare to a var_tbl with up to six entries; var_tbl index 1 must be a table or a number; index 2, a string; index 3, a number;
index 4, a number; index 5, either a string or nil; and index 6, either a number or nil.
Another example:
type_tbl = { {'text', 'msg', 'text_out'} = 'string', display_time = 'number', display_mode = {'string', 'nil'} coa = {'string', 'nil'}}
var_tbl must have a string at one of the following table keys: "text", "msg", or "text_out". var_tbl must have a number at table key "display_time",
the table key "display_mode" must be either a string or nil, and the table key "coa" must be either a string or nil.
]]
function mist.utils.typeCheck(fname, type_tbl, var_tbl)
--env.info('type check')
for type_key, type_val in pairs(type_tbl) do
--print('type_key:')
--print(type_key)
--print('type_val:')
--print(type_val)
--type_key can be a table of accepted keys- so try to find one that is not nil
local type_key_str = ''
local act_key = type_key -- actual key within var_tbl - necessary to use for multiple possible key variables. Initialize to type_key
if type(type_key) == 'table' then
for i = 1, #type_key do
if i ~= 1 then
type_key_str = type_key_str .. '/'
end
type_key_str = type_key_str .. tostring(type_key[i])
if var_tbl[type_key[i]] ~= nil then
act_key = type_key[i] -- found a non-nil entry, make act_key now this val.
end
end
else
type_key_str = tostring(type_key)
end
local err_msg = 'Error in function ' .. fname .. ', parameter "' .. type_key_str .. '", expected: '
local passed_check = false
if type(type_tbl[type_key]) == 'table' then
--print('err_msg, before and after:')
--print(err_msg)
for j = 1, #type_tbl[type_key] do
if j == 1 then
err_msg = err_msg .. type_tbl[type_key][j]
else
err_msg = err_msg .. ' or ' .. type_tbl[type_key][j]
end
if type(var_tbl[act_key]) == type_tbl[type_key][j] then
passed_check = true
end
end
--print(err_msg)
else
--print('err_msg, before and after:')
--print(err_msg)
err_msg = err_msg .. type_tbl[type_key]
--print(err_msg)
if type(var_tbl[act_key]) == type_tbl[type_key] then
passed_check = true
end
end
if not passed_check then
err_msg = err_msg .. ', got ' .. type(var_tbl[act_key])
return false, err_msg
end
end
return true
end
--porting in Slmod's "safestring" basic serialize
mist.utils.basicSerialize = function(s)
if s == nil then
return "\"\""
else
if ((type(s) == 'number') or (type(s) == 'boolean') or (type(s) == 'function') or (type(s) == 'table') or (type(s) == 'userdata') ) then
return tostring(s)
elseif type(s) == 'string' then
s = string.format('%q', s)
return s
end
end
end
--porting in Slmod's serialize_slmod
mist.utils.serialize = function(name, value, level)
-----Based on ED's serialize_simple2
local basicSerialize = function (o)
if type(o) == "number" then
return tostring(o)
elseif type(o) == "boolean" then
return tostring(o)
else -- assume it is a string
return mist.utils.basicSerialize(o)
end
end
local serialize_to_t = function (name, value, level)
----Based on ED's serialize_simple2
local var_str_tbl = {}
if level == nil then level = "" end
if level ~= "" then level = level.." " end
table.insert(var_str_tbl, level .. name .. " = ")
if type(value) == "number" or type(value) == "string" or type(value) == "boolean" then
table.insert(var_str_tbl, basicSerialize(value) .. ",\n")
elseif type(value) == "table" then
table.insert(var_str_tbl, "\n"..level.."{\n")
for k,v in pairs(value) do -- serialize its fields
local key
if type(k) == "number" then
key = string.format("[%s]", k)
else
key = string.format("[%q]", k)
end
table.insert(var_str_tbl, mist.utils.serialize(key, v, level.." "))
end
if level == "" then
table.insert(var_str_tbl, level.."} -- end of "..name.."\n")
else
table.insert(var_str_tbl, level.."}, -- end of "..name.."\n")
end
else
env.info("Cannot serialize a "..type(value))
end
return var_str_tbl
end
local t_str = serialize_to_t(name, value, level)
return table.concat(t_str)
end
-- porting in slmod's serialize_wcycles
mist.utils.serializeWithCycles = function(name, value, saved)
--mostly straight out of Programming in Lua
local basicSerialize = function (o)
if type(o) == "number" then
return tostring(o)
elseif type(o) == "boolean" then
return tostring(o)
else -- assume it is a string
return mist.utils.basicSerialize(o)
end
end
local t_str = {}
saved = saved or {} -- initial value
if ((type(value) == 'string') or (type(value) == 'number') or (type(value) == 'table') or (type(value) == 'boolean')) then
table.insert(t_str, name .. " = ")
if type(value) == "number" or type(value) == "string" or type(value) == "boolean" then
table.insert(t_str, basicSerialize(value) .. "\n")
else
if saved[value] then -- value already saved?
table.insert(t_str, saved[value] .. "\n")
else
saved[value] = name -- save name for next time
table.insert(t_str, "{}\n")
for k,v in pairs(value) do -- save its fields
local fieldname = string.format("%s[%s]", name, basicSerialize(k))
table.insert(t_str, mist.utils.serializeWithCycles(fieldname, v, saved))
end
end
end
return table.concat(t_str)
else
return ""
end
end
-- porting in Slmod's serialize_slmod2
mist.utils.oneLineSerialize = function(tbl) -- serialization of a table all on a single line, no comments, made to replace old get_table_string function
if type(tbl) == 'table' then --function only works for tables!
local tbl_str = {}
tbl_str[#tbl_str + 1] = '{ '
for ind,val in pairs(tbl) do -- serialize its fields
if type(ind) == "number" then
tbl_str[#tbl_str + 1] = '['
tbl_str[#tbl_str + 1] = tostring(ind)
tbl_str[#tbl_str + 1] = '] = '
else --must be a string
tbl_str[#tbl_str + 1] = '['
tbl_str[#tbl_str + 1] = mist.utils.basicSerialize(ind)
tbl_str[#tbl_str + 1] = '] = '
end
if ((type(val) == 'number') or (type(val) == 'boolean')) then
tbl_str[#tbl_str + 1] = tostring(val)
tbl_str[#tbl_str + 1] = ', '
elseif type(val) == 'string' then
tbl_str[#tbl_str + 1] = mist.utils.basicSerialize(val)
tbl_str[#tbl_str + 1] = ', '
elseif type(val) == 'nil' then -- won't ever happen, right?
tbl_str[#tbl_str + 1] = 'nil, '
elseif type(val) == 'table' then
tbl_str[#tbl_str + 1] = mist.utils.oneLineSerialize(val)
tbl_str[#tbl_str + 1] = ', ' --I think this is right, I just added it
else
env.info('unable to serialize value type ' .. mist.utils.basicSerialize(type(val)) .. ' at index ' .. tostring(ind))
end
end
tbl_str[#tbl_str + 1] = '}'
return table.concat(tbl_str)
end
end
--Function to create string for viewing the contents of a table -NOT for serialization
mist.utils.tableShow = function(tbl, loc, indent, tableshow_tbls) --based on serialize_slmod, this is a _G serialization
tableshow_tbls = tableshow_tbls or {} --create table of tables
loc = loc or ""
indent = indent or ""
if type(tbl) == 'table' then --function only works for tables!
tableshow_tbls[tbl] = loc
local tbl_str = {}
tbl_str[#tbl_str + 1] = indent .. '{\n'
for ind,val in pairs(tbl) do -- serialize its fields
if type(ind) == "number" then
tbl_str[#tbl_str + 1] = indent
tbl_str[#tbl_str + 1] = loc .. '['
tbl_str[#tbl_str + 1] = tostring(ind)
tbl_str[#tbl_str + 1] = '] = '
else
tbl_str[#tbl_str + 1] = indent
tbl_str[#tbl_str + 1] = loc .. '['
tbl_str[#tbl_str + 1] = mist.utils.basicSerialize(ind)
tbl_str[#tbl_str + 1] = '] = '
end
if ((type(val) == 'number') or (type(val) == 'boolean')) then
tbl_str[#tbl_str + 1] = tostring(val)
tbl_str[#tbl_str + 1] = ',\n'
elseif type(val) == 'string' then
tbl_str[#tbl_str + 1] = mist.utils.basicSerialize(val)
tbl_str[#tbl_str + 1] = ',\n'
elseif type(val) == 'nil' then -- won't ever happen, right?
tbl_str[#tbl_str + 1] = 'nil,\n'
elseif type(val) == 'table' then
if tableshow_tbls[val] then
tbl_str[#tbl_str + 1] = tostring(val) .. ' already defined: ' .. tableshow_tbls[val] .. ',\n'
else
tableshow_tbls[val] = loc .. '[' .. mist.utils.basicSerialize(ind) .. ']'
tbl_str[#tbl_str + 1] = tostring(val) .. ' '
tbl_str[#tbl_str + 1] = mist.utils.tableShow(val, loc .. '[' .. mist.utils.basicSerialize(ind).. ']', indent .. ' ', tableshow_tbls)
tbl_str[#tbl_str + 1] = ',\n'
end
elseif type(val) == 'function' then
if debug and debug.getinfo then
fcnname = tostring(val)
local info = debug.getinfo(val, "S")
if info.what == "C" then
tbl_str[#tbl_str + 1] = string.format('%q', fcnname .. ', C function') .. ',\n'
else
if (string.sub(info.source, 1, 2) == [[./]]) then
tbl_str[#tbl_str + 1] = string.format('%q', fcnname .. ', defined in (' .. info.linedefined .. '-' .. info.lastlinedefined .. ')' .. info.source) ..',\n'
else
tbl_str[#tbl_str + 1] = string.format('%q', fcnname .. ', defined in (' .. info.linedefined .. '-' .. info.lastlinedefined .. ')') ..',\n'
end
end
else
tbl_str[#tbl_str + 1] = 'a function,\n'
end
else
tbl_str[#tbl_str + 1] = 'unable to serialize value type ' .. mist.utils.basicSerialize(type(val)) .. ' at index ' .. tostring(ind)
end
end
tbl_str[#tbl_str + 1] = indent .. '}'
return table.concat(tbl_str)
end
end
mist.debug = {}
mist.debug.dump_G = function(fname)
if lfs and io then
local fdir = lfs.writedir() .. [[Logs\]] .. fname
local f = io.open(fdir, 'w')
f:write(mist.utils.tableShow(_G))
f:close()
local errmsg = 'mist.debug.dump_G wrote data to ' .. fdir
env.info(errmsg)
trigger.action.outText(errmsg, 10)
else
local errmsg = 'Error: insufficient libraries to run mist.debug.dump_G, you must disable the sanitization of the io and lfs libraries in ./Scripts/MissionScripting.lua'
env.info(errmsg)
trigger.action.outText(errmsg, 10)
end
end
mist.debug.writeData = function(fcn, fcnVars, fname)
if lfs and io then
local fdir = lfs.writedir() .. [[Logs\]] .. fname
local f = io.open(fdir, 'w')
f:write(fcn(unpack(fcnVars, 1, table.maxn(fcnVars))))
f:close()
local errmsg = 'mist.debug.writeData wrote data to ' .. fdir
env.info(errmsg)
trigger.action.outText(errmsg, 10)
else
local errmsg = 'Error: insufficient libraries to run mist.debug.writeData, you must disable the sanitization of the io and lfs libraries in ./Scripts/MissionScripting.lua'
env.info(errmsg)
trigger.action.outText(errmsg, 10)
end
end
mist.debug.dumpDBs = function()
for DBname, DB in pairs(mist.DBs) do
if type(DB) == 'table' and type(DBname) == 'string' then
mist.debug.writeData(mist.utils.serialize, {DBname, DB}, 'mist_DBs_' .. DBname .. '.lua')
end
end
end
-----------------------------------------------------------------------------------------------------------------
--3D Vector manipulation
mist.vec = {}
mist.vec.add = function(vec1, vec2)
return {x = vec1.x + vec2.x, y = vec1.y + vec2.y, z = vec1.z + vec2.z}
end
mist.vec.sub = function(vec1, vec2)
return {x = vec1.x - vec2.x, y = vec1.y - vec2.y, z = vec1.z - vec2.z}
end
mist.vec.scalarMult = function(vec, mult)
return {x = vec.x*mult, y = vec.y*mult, z = vec.z*mult}
end
mist.vec.scalar_mult = mist.vec.scalarMult
mist.vec.dp = function(vec1, vec2)
return vec1.x*vec2.x + vec1.y*vec2.y + vec1.z*vec2.z
end
mist.vec.cp = function(vec1, vec2)
return { x = vec1.y*vec2.z - vec1.z*vec2.y, y = vec1.z*vec2.x - vec1.x*vec2.z, z = vec1.x*vec2.y - vec1.y*vec2.x}
end
mist.vec.mag = function(vec)
return (vec.x^2 + vec.y^2 + vec.z^2)^0.5
end
mist.vec.getUnitVec = function(vec)
local mag = mist.vec.mag(vec)
return { x = vec.x/mag, y = vec.y/mag, z = vec.z/mag }
end
mist.vec.rotateVec2 = function(vec2, theta)
return { x = vec2.x*math.cos(theta) - vec2.y*math.sin(theta), y = vec2.x*math.sin(theta) + vec2.y*math.cos(theta)}
end
---------------------------------------------------------------------------------------------------------------------------
-- acc- the accuracy of each easting/northing. 0, 1, 2, 3, 4, or 5.
mist.tostringMGRS = function(MGRS, acc)
if acc == 0 then
return MGRS.UTMZone .. ' ' .. MGRS.MGRSDigraph
else
return MGRS.UTMZone .. ' ' .. MGRS.MGRSDigraph .. ' ' .. string.format('%0' .. acc .. 'd', mist.utils.round(MGRS.Easting/(10^(5-acc)), 0))
.. ' ' .. string.format('%0' .. acc .. 'd', mist.utils.round(MGRS.Northing/(10^(5-acc)), 0))
end
end
--[[acc:
in DM: decimal point of minutes.
In DMS: decimal point of seconds.
position after the decimal of the least significant digit:
So:
42.32 - acc of 2.
]]
mist.tostringLL = function(lat, lon, acc, DMS)
local latHemi, lonHemi
if lat > 0 then
latHemi = 'N'
else
latHemi = 'S'
end
if lon > 0 then
lonHemi = 'E'
else
lonHemi = 'W'
end
lat = math.abs(lat)
lon = math.abs(lon)
local latDeg = math.floor(lat)
local latMin = (lat - latDeg)*60
local lonDeg = math.floor(lon)
local lonMin = (lon - lonDeg)*60
if DMS then -- degrees, minutes, and seconds.
local oldLatMin = latMin
latMin = math.floor(latMin)
local latSec = mist.utils.round((oldLatMin - latMin)*60, acc)
local oldLonMin = lonMin
lonMin = math.floor(lonMin)
local lonSec = mist.utils.round((oldLonMin - lonMin)*60, acc)
if latSec == 60 then
latSec = 0
latMin = latMin + 1
end
if lonSec == 60 then
lonSec = 0
lonMin = lonMin + 1
end
local secFrmtStr -- create the formatting string for the seconds place
if acc <= 0 then -- no decimal place.
secFrmtStr = '%02d'
else
local width = 3 + acc -- 01.310 - that's a width of 6, for example.
secFrmtStr = '%0' .. width .. '.' .. acc .. 'f'
end
return string.format('%02d', latDeg) .. ' ' .. string.format('%02d', latMin) .. '\' ' .. string.format(secFrmtStr, latSec) .. '"' .. latHemi .. ' '
.. string.format('%02d', lonDeg) .. ' ' .. string.format('%02d', lonMin) .. '\' ' .. string.format(secFrmtStr, lonSec) .. '"' .. lonHemi
else -- degrees, decimal minutes.
latMin = mist.utils.round(latMin, acc)
lonMin = mist.utils.round(lonMin, acc)
if latMin == 60 then
latMin = 0
latDeg = latDeg + 1
end
if lonMin == 60 then
lonMin = 0
lonDeg = lonDeg + 1
end
local minFrmtStr -- create the formatting string for the minutes place
if acc <= 0 then -- no decimal place.
minFrmtStr = '%02d'
else
local width = 3 + acc -- 01.310 - that's a width of 6, for example.
minFrmtStr = '%0' .. width .. '.' .. acc .. 'f'
end
return string.format('%02d', latDeg) .. ' ' .. string.format(minFrmtStr, latMin) .. '\'' .. latHemi .. ' '
.. string.format('%02d', lonDeg) .. ' ' .. string.format(minFrmtStr, lonMin) .. '\'' .. lonHemi
end
end
--[[ required: az - radian
required: dist - meters
optional: alt - meters (set to false or nil if you don't want to use it).
optional: metric - set true to get dist and alt in km and m.
precision will always be nearest degree and NM or km.]]
mist.tostringBR = function(az, dist, alt, metric)
az = mist.utils.round(mist.utils.toDegree(az), 0)
if metric then
dist = mist.utils.round(dist/1000, 0)
else
dist = mist.utils.round(mist.utils.metersToNM(dist), 0)
end
local s = string.format('%03d', az) .. ' for ' .. dist
if alt then
if metric then
s = s .. ' at ' .. mist.utils.round(alt, 0)
else
s = s .. ' at ' .. mist.utils.round(mist.utils.metersToFeet(alt), 0)
end
end
return s
end
mist.getNorthCorrection = function(point) --gets the correction needed for true north
if not point.z then --Vec2; convert to Vec3
point.z = point.y
point.y = 0
end
local lat, lon = coord.LOtoLL(point)
local north_posit = coord.LLtoLO(lat + 1, lon)
return math.atan2(north_posit.z - point.z, north_posit.x - point.x)
end
function mist.getGroupPoints(groupname) -- if groupname exists in env.mission, then returns table of the group's points in numerical order, such as: { [1] = {x = 299435.224, y = -1146632.6773}, [2] = { x = 663324.6563, y = 322424.1112}}
for coa_name, coa_data in pairs(env.mission.coalition) do
if (coa_name == 'red' or coa_name == 'blue') and type(coa_data) == 'table' then
if coa_data.country then --there is a country table
for cntry_id, cntry_data in pairs(coa_data.country) do
for obj_type_name, obj_type_data in pairs(cntry_data) do
if obj_type_name == "helicopter" or obj_type_name == "ship" or obj_type_name == "plane" or obj_type_name == "vehicle" then -- only these types have points
if ((type(obj_type_data) == 'table') and obj_type_data.group and (type(obj_type_data.group) == 'table') and (#obj_type_data.group > 0)) then --there's a group!
for group_num, group_data in pairs(obj_type_data.group) do
if group_data and group_data.name and group_data.name == groupname then -- this is the group we are looking for
if group_data.route and group_data.route.points and #group_data.route.points > 0 then
local points = {}
for point_num, point in pairs(group_data.route.points) do
if not point.point then
points[point_num] = { x = point.x, y = point.y }
else
points[point_num] = point.point --it's possible that the ME could move to the point = Vec2 notation.
end
end
return points
end
return
end --if group_data and group_data.name and group_data.name == 'groupname'
end --for group_num, group_data in pairs(obj_type_data.group) do
end --if ((type(obj_type_data) == 'table') and obj_type_data.group and (type(obj_type_data.group) == 'table') and (#obj_type_data.group > 0)) then
end --if obj_type_name == "helicopter" or obj_type_name == "ship" or obj_type_name == "plane" or obj_type_name == "vehicle" or obj_type_name == "static" then
end --for obj_type_name, obj_type_data in pairs(cntry_data) do
end --for cntry_id, cntry_data in pairs(coa_data.country) do
end --if coa_data.country then --there is a country table
end --if coa_name == 'red' or coa_name == 'blue' and type(coa_data) == 'table' then
end --for coa_name, coa_data in pairs(mission.coalition) do
end
--[[ table attitude = getAttitude(string unitname) -- will work on any unit, even if not an aircraft.
attitude = {
Heading = number, -- in radians, range of 0 to 2*pi, relative to true north
Pitch = number, -- in radians, range of -pi/2 to pi/2
Roll = number, -- in radians, range of 0 to 2*pi, right roll is positive direction
--Yaw, AoA, ClimbAngle - relative to earth reference- DOES NOT TAKE INTO ACCOUNT WIND.
Yaw = number, -- in radians, range of -pi to pi, right yaw is positive direction
AoA = number, -- in radians, range of -pi to pi, rotation of aircraft to the right in comparison to flight direction being positive
ClimbAngle = number, -- in radians, range of -pi/2 to pi/2
--Maybe later?
AxialVel = table, velocity of the aircraft transformed into directions of aircraft axes
Speed = number -- absolute velocity in meters/sec
}
]]
function mist.getAttitude(unit)
local unitpos = unit:getPosition()
if unitpos then
local Heading = math.atan2(unitpos.x.z, unitpos.x.x)
Heading = Heading + mist.getNorthCorrection(unitpos.p)
if Heading < 0 then
Heading = Heading + 2*math.pi -- put heading in range of 0 to 2*pi
end
---- heading complete.----
local Pitch = math.asin(unitpos.x.y)
---- pitch complete.----
-- now get roll:
--maybe not the best way to do it, but it works.
--first, make a vector that is perpendicular to y and unitpos.x with cross product
local cp = mist.vec.cp(unitpos.x, {x = 0, y = 1, z = 0})
--now, get dot product of of this cross product with unitpos.z
local dp = mist.vec.dp(cp, unitpos.z)
--now get the magnitude of the roll (magnitude of the angle between two vectors is acos(vec1.vec2/|vec1||vec2|)
local Roll = math.acos(dp/(mist.vec.mag(cp)*mist.vec.mag(unitpos.z)))
--now, have to get sign of roll.
-- by convention, making right roll positive
-- to get sign of roll, use the y component of unitpos.z. For right roll, y component is negative.
if unitpos.z.y > 0 then -- left roll, flip the sign of the roll
Roll = -Roll
end
---- roll complete. ----
--now, work on yaw, AoA, climb, and abs velocity
local Yaw
local AoA
local ClimbAngle
-- get unit velocity
local unitvel = unit:getVelocity()
if mist.vec.mag(unitvel) ~= 0 then --must have non-zero velocity!
local AxialVel = {} --unit velocity transformed into aircraft axes directions
--transform velocity components in direction of aircraft axes.
AxialVel.x = mist.vec.dp(unitpos.x, unitvel)
AxialVel.y = mist.vec.dp(unitpos.y, unitvel)
AxialVel.z = mist.vec.dp(unitpos.z, unitvel)
--Yaw is the angle between unitpos.x and the x and z velocities
--define right yaw as positive
Yaw = math.acos(mist.vec.dp({x = 1, y = 0, z = 0}, {x = AxialVel.x, y = 0, z = AxialVel.z})/mist.vec.mag({x = AxialVel.x, y = 0, z = AxialVel.z}))
--now set correct direction:
if AxialVel.z > 0 then
Yaw = -Yaw
end
-- AoA is angle between unitpos.x and the x and y velocities
AoA = math.acos(mist.vec.dp({x = 1, y = 0, z = 0}, {x = AxialVel.x, y = AxialVel.y, z = 0})/mist.vec.mag({x = AxialVel.x, y = AxialVel.y, z = 0}))
--now set correct direction:
if AxialVel.y > 0 then
AoA = -AoA
end
ClimbAngle = math.asin(unitvel.y/mist.vec.mag(unitvel))
end
return { Heading = Heading, Pitch = Pitch, Roll = Roll, Yaw = Yaw, AoA = AoA, ClimbAngle = ClimbAngle}
else
env.info('unit:getPosition() is nil!')
end
end
function mist.getHeading(unit, rawHeading)