forked from Courseplay/courseplay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.lua
1245 lines (1070 loc) · 38.2 KB
/
helpers.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
local abs, ceil, floor, huge, max, min, pi, sqrt = math.abs, math.ceil, math.floor, math.huge, math.max, math.min, math.pi, math.sqrt;
function courseplay:isEven(n)
return tonumber(n) % 2 == 0;
end;
function courseplay:isOdd(n)
return tonumber(n) % 2 == 1;
end;
--Table concatenation: http://stackoverflow.com/a/1413919
-- return a new array containing the concatenation of all of its parameters. Scaler parameters are included in place, and array parameters have their values shallow-copied to the final array. Note that userdata and function values are treated as scalar.
function tableConcat(...)
local t = {};
for n = 1, select('#', ...) do
local arg = select(n, ...);
if type(arg) == 'table' then
for _,v in ipairs(arg) do
t[#t+1] = v;
end;
else
t[#t+1] = arg;
end;
end;
return t;
end;
function courseplay:isFolding(workTool) --returns isFolding, isFolded, isUnfolded
if not courseplay:isFoldable(workTool) then
return false, false, true;
end;
local isFolding, isFolded, isUnfolded = false, true, true;
courseplay:debug(string.format('%s: isFolding(): realUnfoldDirection=%s, turnOnFoldDirection=%s, startAnimTime=%s, foldMoveDirection=%s', nameNum(workTool), tostring(workTool.cp.realUnfoldDirection), tostring(workTool.turnOnFoldDirection), tostring(workTool.startAnimTime), tostring(workTool.foldMoveDirection)), 17);
for k,foldingPart in pairs(workTool.foldingParts) do
--local charSet = foldingPart.animCharSet;
--local animTime = charSet ~= 0 and getAnimTrackTime(charSet, 0) or workTool:getRealAnimationTime(foldingPart.animationName);
--isFolded/isUnfolded
--print(string.format('\tfoldingPart %d: animTime=%s, foldAnimTime=%s, isFoldedAnimTime=%s, isUnfoldedAnimTime=%s', k, tostring(animTime), tostring(workTool.foldAnimTime), tostring(foldingPart.isFoldedAnimTime), tostring(foldingPart.isUnfoldedAnimTime)));
if workTool.foldAnimTime ~= foldingPart.isFoldedAnimTimeNormal then
isFolded = false;
courseplay:debug(string.format('\tfoldingPart %d: foldAnimTime=%s, isFoldedAnimTimeNormal=%s, isUnfoldedAnimTimeNormal=%s -> isFolded = false', k, tostring(workTool.foldAnimTime), tostring(foldingPart.isFoldedAnimTimeNormal), tostring(foldingPart.isUnfoldedAnimTimeNormal)), 17);
end;
if workTool.foldAnimTime ~= foldingPart.isUnfoldedAnimTimeNormal then
isUnfolded = false;
courseplay:debug(string.format('\tfoldingPart %d: foldAnimTime=%s, isFoldedAnimTimeNormal=%s, isUnfoldedAnimTimeNormal=%s -> isUnfolded = false', k, tostring(workTool.foldAnimTime), tostring(foldingPart.isFoldedAnimTimeNormal), tostring(foldingPart.isUnfoldedAnimTimeNormal)), 17);
end;
--isFolding
if workTool.oldFoldAnimTime == nil then workTool.oldFoldAnimTime = 0; end;
if workTool.foldAnimTime ~= workTool.oldFoldAnimTime then
--if workTool.foldMoveDirection > 0 and animTime < foldingPart.animDuration then
if workTool.foldMoveDirection > 0 and workTool.foldAnimTime < 1 then
isFolding = true;
--elseif workTool.foldMoveDirection < 0 and animTime > 0 then
elseif workTool.foldMoveDirection < 0 and workTool.foldAnimTime > 0 then
isFolding = true;
end;
workTool.oldFoldAnimTime = workTool.foldAnimTime;
end;
end;
courseplay:debug(string.format('\treturn isFolding=%s, isFolded=%s, isUnfolded=%s', tostring(isFolding), tostring(isFolded), tostring(isUnfolded)), 17);
return isFolding, isFolded, isUnfolded;
end;
function courseplay:isAnimationPartPlaying(workTool, index)
if type(index) == "number" then
local animPart = workTool.animationParts[index];
if animPart == nil then
print(nameNum(workTool) .. ": animationParts[" .. tostring(index) .. "] doesn't exist! isAnimationPartPlaying() returns nil");
return nil;
end;
return animPart.clipStartTime == false and animPart.clipEndTime == false;
elseif type(index) == "table" then
for i,singleIndex in pairs(index) do
local animPart = workTool.animationParts[singleIndex];
if animPart == nil then
print(nameNum(workTool) .. ": animationParts[" .. tostring(singleIndex) .. "] doesn't exist! isAnimationPartPlaying() returns nil");
return nil;
end;
if animPart.clipStartTime == false and animPart.clipEndTime == false then
return true;
end;
end;
return false;
else
print(nameNum(workTool) .. ": type of index doesn't work with animationParts! isAnimationPartPlaying() returns nil");
return nil;
end;
end;
function courseplay:round(num, decimals)
if num == nil or type(num) ~= "number" then
return nil;
end;
if decimals and decimals > 0 then
local mult = 10^decimals;
return math.floor(num * mult + 0.5) / mult;
end;
return math.floor(num + 0.5);
end;
function courseplay:nilOrBool(variable, bool)
return variable == nil or (variable ~= nil and variable == bool);
end;
function nameNum(vehicle, hideNum)
if vehicle == nil then
return 'nil';
end;
if vehicle.cp ~= nil and vehicle.cp.coursePlayerNum ~= nil then
if hideNum then
return tostring(vehicle.name);
end;
return tostring(vehicle.name) .. ' (#' .. tostring(vehicle.cp.coursePlayerNum) .. ')';
elseif vehicle.isHired then
return tostring(vehicle.name) .. ' (helper)';
end;
return tostring(vehicle.name);
end;
function courseplay:isBetween(n, num1, num2, include)
if type(n) ~= "number" or type(num1) ~= "number" or type(num2) ~= "number" then
return;
end;
if include then
return (num1 > num2 and n <= num1 and n >= num2) or (num1 < num2 and n >= num1 and n <= num2);
else
return (num1 > num2 and n < num1 and n > num2) or (num1 < num2 and n > num1 and n < num2);
end;
end;
function courseplay:setVarValueFromString(self, str, value)
print(string.format("courseplay:setVarValueFromString(self, %s, %s)",str,tostring(value)))
local what = Utils.splitString(".", str);
local whatDepth = #what;
if whatDepth < 1 or whatDepth > 5 then
return;
end;
local baseVar;
if what[1] == "self" then
baseVar = self;
elseif what[1] == "courseplay" then
baseVar = courseplay;
end;
if baseVar ~= nil then
local result;
if whatDepth == 1 then --self
baseVar = value;
result = value;
elseif whatDepth == 2 then --self.cp or self.var
baseVar[what[2]] = value;
result = value;
elseif whatDepth == 3 then --self.cp.var
if baseVar == self and what[2] == 'cp' then
self:setCpVar(what[3], value,true,courseplay.isClient)
result = value;
else
baseVar[what[2]][what[3]] = value;
result = value;
end
elseif whatDepth == 4 then --self.cp.table.var
baseVar[what[2]][what[3]][what[4]] = value;
result = value;
elseif whatDepth == 5 then --self.cp.table1.table2.var
baseVar[what[2]][what[3]][what[4]][what[5]] = value;
result = value;
end;
courseplay:debug(" " .. table.concat(what, ".") .." = " .. tostring(result),5);
end;
what = nil;
end;
function courseplay:getVarValueFromString(self, str)
local what = Utils.splitString(".", str);
local whatDepth = #what;
local whatObj;
if what[1] == "self" then
whatObj = self;
elseif what[1] == "courseplay" then
whatObj = courseplay;
end;
if whatObj ~= nil then
for i=2,whatDepth do
local key = what[i];
whatObj = whatObj[key];
if i ~= whatDepth and type(whatObj) ~= "table" then
print(('%s: error in string %q @ %s: traversal failed'):format(nameNum(self), str, key));
whatObj = nil;
break;
end;
end;
end;
--print(table.concat(what, ".") .."=" .. tostring(whatObj))
return whatObj;
end;
function courseplay:boolToInt(bool)
if bool == nil or type(bool) ~= "boolean" then
return nil;
elseif bool == true then
return 1;
elseif bool == false then
return 0;
end;
end;
function courseplay:intToBool(int)
if int == nil or type(int) ~= "number" then
return nil;
end;
return int == 1;
end;
function courseplay:trueOrNil(bool)
if bool ~= nil and bool == true then
return true;
end;
return nil;
end;
function courseplay:loopedTable(tab, idx, maxIdx)
maxIdx = maxIdx or #tab;
while idx > maxIdx do
--idx = maxIdx - idx;
idx = idx - maxIdx;
end;
while idx < 1 do
idx = idx + maxIdx;
end;
return tab[idx];
end;
function courseplay:waypointsHaveAttr(vehicle, curRecordNumber, back, forward, attr, value, all)
for i=curRecordNumber+back, curRecordNumber+forward do
local wp = courseplay:loopedTable(vehicle.Waypoints, i);
if wp[attr] ~= nil and wp[attr] == value then
if not all then -- one waypoint has met condition, not all needed -> return true
return true;
end;
elseif all then -- condition not met, but all waypoints should meet condition -> return false
return false;
end;
end;
if all then -- all waypoints have met condition (no return false in loop) -> return true
return true;
else -- none of the waypoints have met condition (no return true in loop) -> return false
return false;
end;
end;
function courseplay:varLoop(var, changeBy, maxVar, minVar)
minVar = minVar or 1;
var = var + changeBy;
if var > maxVar then
var = minVar;
elseif var < minVar then
var = maxVar;
end;
return var;
end;
function courseplay:fillTypesMatch(fillTrigger, workTool)
if fillTrigger ~= nil then
if rawget(fillTrigger, 'fillType') then -- make sure the fillTrigger doesn't return a meta fillType from a parent class
return workTool:allowFillType(fillTrigger.fillType, false);
elseif fillTrigger.currentFillType then
return workTool:allowFillType(fillTrigger.currentFillType, false);
elseif fillTrigger.getFillType then
return workTool:allowFillType(fillTrigger:getFillType(), false);
end;
end;
return false;
end;
-- by horoman
courseplay.utils.table = {}
function courseplay.utils.table.compare(t1,t2,field)
local result = false
local C1 = t1[field]
local C2 = t2[field]
if type(C1) == 'string' or type(C2) == 'string' then
local c1 = string.lower(C1)
local c2 = string.lower(C2)
if c1 == c2 then
result = C1 < C2
else
result = c1 < c2
end
else
result = C1 < C2
end
return result
end
function courseplay.utils.table.compare_name(t1,t2)
-- return courseplay.utils.table.compare(t1,t2,'name')
return courseplay.utils.table.compare(t1, t2, 'nameClean');
end
function courseplay.utils.table.search_in_field(tab, field, term)
local result = {}
for k,v in pairs(tab) do
if v[field] == term then
table.insert(result, v)
end
end
return result
end
function courseplay.utils.table.copy(tab, recursive)
-- note that if 'recursive' is not 'true', only tab is copied. if tab contains tables itself again, these tables are not copied but referenced again (the reference is copied).
local result = {};
for k,v in pairs(tab) do
if recursive and type(v) == 'table' then
result[k] = courseplay.utils.table.copy(v, recursive);
else
result[k] = v;
end;
end;
return result;
end;
function courseplay.utils.table.append(t1,t2)
for k,v in pairs(t2) do
table.insert(t1,v)
end
return t1
end
function courseplay.utils.table.merge(t1, t2, overwrite)
if overwrite == nil then
overwrite = false
end
for k, v in pairs(t2) do
if overwrite or t1[k] == nil then
t1[k] = v
end
end
return t1
end
function courseplay.utils.table.move(t1, t2, t1_index, t2_index)
t1_index = t1_index or (#t1);
t2_index = t2_index or (#t2 + 1);
if t1[t1_index] == nil then
return false;
end;
t2[t2_index] = t1[t1_index];
t1[t1_index] = nil;
return t2[t2_index] ~= nil;
end;
function table.map(t, func)
local newArray = {};
for i,v in pairs(t) do
newArray[i] = func(v);
end;
return newArray;
end;
function table.reverse(t)
local reversedTable = {};
local itemCount = #t;
for k,v in ipairs(t) do
reversedTable[itemCount + 1 - k] = v;
end;
return reversedTable;
end;
function table.getLast(t)
if #t == 0 then
if next(t) ~= nil then
return table.maxn(t);
end;
return nil;
end;
return t[#t];
end;
function table.rotate(tbl, inc) --@gist: https://gist.github.com/JakobTischler/b4bb7a4d1c8cf8d2d85f
if inc == nil or inc == 0 then
return tbl;
end;
local t = tbl;
local rot = math.abs(inc);
if inc < 0 then
for i=1,rot do
local p = t[1];
table.remove(t, 1);
table.insert(t, p);
end;
else
for i=1,rot do
local n = #t;
local p = t[n];
table.remove(t, n);
table.insert(t, 1, p);
end;
end;
return t;
end;
function courseplay.utils.table.getMax(tab, field)
local max;
if tab ~= nil and field ~= nil then
max = false
for k, v in pairs(tab) do -- TODO (Jakob): use next(tab) instead of for loop
if v[field] ~= nil then
max = v[field]
break
end
end
for k, v in pairs(tab) do
if v[field] ~= nil then
if v[field] > max then
max = v[field]
end
end
end
end
return max
end;
courseplay.prmGetXMLFn = {
Bool = getXMLBool,
Float = getXMLFloat,
Int = getXMLInt,
String = getXMLString
};
courseplay.prmSetXMLFn = {
Bool = setXMLBool,
Float = setXMLFloat,
Int = setXMLInt,
String = setXMLString
};
function courseplay.utils.findXMLNodeByAttr(File, node, attr, value, valueType)
-- returns the node number in case of success
-- else it returns the negative value of the next unused node (if there are 6 nodes with the name defined by the node parameter and none matches the search, the function returns -7)
valueType = valueType or 'Int'
local i = -1
local done = false
local dummy
if courseplay.prmGetXMLFn[valueType] ~= nil then
-- this solution does not look very nice but has no unnecessary statements in the loops which should make them as fast as possible
repeat
i = i + 1;
dummy = '';
dummy = courseplay.prmGetXMLFn[valueType](File, string.format(node .. '(%d)' .. "#" .. attr, i));
if dummy == value then
done = true;
elseif dummy == nil then -- the attribute seems not to exist. Does the node?
if not hasXMLProperty(File, string.format(node .. '(%d)', i)) then -- if the node does not exist, we are at the end and done
done = true;
end;
end;
until done;
else
-- ERROR
end;
if dummy ~= nil then
return i;
else
return -1 * i;
end;
end;
function courseplay.utils.findFreeXMLNode(File, node)
-- returns the node number in case of success
local i = -1
local done = false
local exists
repeat
i = i+1
exists = hasXMLProperty(File, string.format(node .. '(%d)', i))
if not exists then
done = true
end
until done
return i
end
function courseplay.utils.setXML(File, node, attribute, value, valueType, match_attr, match_attr_value, match_attr_type)
-- this function is not meant do be called in loops as it is rather slow:
-- it is searched for the node everytime the function is called.
-- Use setMultipleXML instead.
attribute = attribute or '';
valueType = valueType or 'Int';
match_attr = match_attr or '';
match_attr_value = match_attr_value or '';
match_attr_type = match_attr_type or 'Int';
if attribute ~= '' then
attribute = '#' .. attribute;
end;
if match_attr ~= '' and match_attr_value ~= '' then
local i = courseplay.utils.findXMLNodeByAttr(File, node, match_attr, match_attr_value, match_attr_type);
if i < 0 then i = -i end;
courseplay.prmSetXMLFn[valueType](File, ('%s(%d)%s'):format(node, i, attribute), value);
else
courseplay.prmSetXMLFn[valueType](File, node .. attribute, value);
end;
end;
function courseplay.utils.setMultipleXML(File, node, values, types)
-- function to save multiple attributes (and to the node itself) of one node
--
-- File: File got by loadXML(...)
-- node (string)
-- values has to be a table of the form:
-- {attribute1 = value1, attribute2 = value2, ...}
-- to write into the node directly set attribute = '_node_'
-- types is a table of the form:
-- {attribute1 = type1, attribute2 = type2, ...}; type1 is a string (e.g. 'Int')
-- attributes with no type in the types table will be skipped.
for attribute, value in pairs(values) do
local valueType = types[attribute]
if valueType ~= nil then
if attribute ~= '_node_' then
attribute = '#' .. attribute
else
attribute = ''
end
if value ~= nil and courseplay.prmSetXMLFn[valueType] ~= nil then
courseplay.prmSetXMLFn[valueType](File, node .. attribute, value);
else
-- Error?!
print('could not save attribute: ' .. attribute)
end
end -- end if not skip then
end -- end for k, v in pairs(values) do
end
function courseplay.utils.setMultipleXMLNodes(File, root_node, node_name , values, types, unique_nodes)
-- values has to be a table of the form:
-- {attribute1 = value1, attribute2 = value2, ...}
-- types a table of the form:
-- {attribute1 = type1, attribute2 = type2, ...}
-- to write into the node directly set attribute = '_node_'
if unique_nodes == nil then
unique_nodes = true
end
local skip = false
local j = 0
local node = ''
for k, v in pairs(values) do
if unique_nodes then
node = root_node .. '.' .. node_name .. k
else
node = string.format(root_node .. '.' .. node_name .. '(%d)', j)
j = j+1
end
courseplay.utils.setMultipleXML(File, node, v, types)
end
end
---------------------------
function courseplay.utils.normalizeAngle(angle)
local newAngle = angle;
while newAngle >= 360 do
newAngle = newAngle - 360;
end;
while newAngle < 0 do
newAngle = newAngle + 360;
end;
return newAngle;
end;
function courseplay:setCustomTimer(vehicle, timerName, seconds)
vehicle.cp.timers[timerName] = vehicle.timer + (seconds * 1000);
end;
function courseplay:timerIsThrough(vehicle, timerName, defaultToBool)
local timer = vehicle.cp.timers[timerName];
if timer == nil then
return Utils.getNoNil(defaultToBool, true);
end;
return vehicle.timer > timer;
end;
function courseplay:getCustomTimerExists(vehicle, timerName)
return vehicle.cp.timers[timerName] ~= nil;
end;
function courseplay:resetCustomTimer(vehicle, timerName, setToNil)
if setToNil then
vehicle.cp.timers[timerName] = nil;
else
vehicle.cp.timers[timerName] = 0.0;
end;
end;
function courseplay:getDriveDirection(node, x, y, z)
local lx, ly, lz = worldToLocal(node, x, y, z)
local length = Utils.vector3Length(lx,ly,lz)
if length > 0 then
lx = lx / length
lz = lz / length
ly = ly /length
end
return lx,ly,lz
end
-- TODO (Jakob) (FS15): move all UTF/normalization stuff to courseManagement.lua
--UTF-8: ALLOWED CHARACTERS and NORMALIZATION
--src: ASCII Table - Decimal (Base 10) Values @ http://www.parse-o-matic.com/parse/pskb/ASCII-Chart.htm
--src: http://en.wikipedia.org/wiki/List_of_Unicode_characters
function courseplay:getAllowedCharacters()
local allowedSpan = { from = 32, to = 591 };
local prohibitedUnicodes = { [34] = true, [39] = true, [94] = true, [96] = true, [215] = true, [247] = true };
for unicode=127,190 do
prohibitedUnicodes[unicode] = true;
end;
local result = {};
for unicode=allowedSpan.from,allowedSpan.to do
prohibitedUnicodes[unicode] = prohibitedUnicodes[unicode] or false;
result[unicode] = not prohibitedUnicodes[unicode] and getCanRenderUnicode(unicode);
if courseplay.debugChannels and courseplay.debugChannels[8] and getCanRenderUnicode(unicode) then
print(string.format('allowedCharacters[%d]=%s (%q) (prohibited=%s, getCanRenderUnicode()=true)', unicode, tostring(result[unicode]), unicodeToUtf8(unicode), tostring(prohibitedUnicodes[unicode])));
end;
end;
return result;
end;
function courseplay:getUtf8normalization()
local result = {};
local normalizationSpans = {
a = { {192,195}, 197, {224,227}, 229, {256,261} },
ae = { 196, 198, 228, 230 },
c = { 199, 231, {262,269} },
d = { {270,273} },
e = { {200,203}, {232,235}, {274,283} },
g = { {284,291} },
h = { {292,295} },
i = { {204,207}, {236,239}, {296,307} },
j = { {308,309} },
k = { {310,312} },
l = { {313,322} },
n = { 209, 241, {323,331} },
o = { {210,213}, {242,245}, {332,337} },
oe = { 214, 216, 246, 248, 338, 339 },
r = { {340,345} },
s = { {346,353}, 383 },
ss = { 223 },
t = { {354,359} },
u = { {217,219}, {249,251}, {360,371} },
ue = { 220, 252 },
w = { 372, 373 },
y = { 221, 253, 255, {374,376} },
z = { {377,382} }
};
--[[
local test = { 197, 229, 216, 248, 198, 230 };
for _,unicode in pairs(test) do
print(string.format("%q: getCanRenderUnicode(%d)=%s", unicodeToUtf8(unicode), unicode, tostring(getCanRenderUnicode(unicode))));
end;
]]
for normal,unicodes in pairs(normalizationSpans) do
for _,data in pairs(unicodes) do
if type(data) == "number" then
local utf8 = unicodeToUtf8(data);
result[utf8] = normal;
if false and getCanRenderUnicode(data) then
print(string.format("courseplay.utf8normalization[%q] = %q", utf8, normal));
end;
elseif type(data) == "table" then
for unicode=data[1],data[2] do
local utf8 = unicodeToUtf8(unicode);
result[utf8] = normal;
if false and getCanRenderUnicode(unicode) then
print(string.format("courseplay.utf8normalization[%q] = %q", utf8, normal));
end;
end;
end;
end;
end;
return result;
end;
function courseplay:normalizeUTF8_BAK(str)
local normal = str;
if str:len() ~= utf8Strlen(str) then --special char in str
courseplay:debug(string.format("%q: has special char, normal = %q", str, str:gsub("(..?)", courseplay.utf8normalization)), 8);
normal = str:gsub("(..?)", courseplay.utf8normalization);
end;
courseplay:debug(string.format("normalizeUTF8(%q): %q", str, normal), 8);
return normal:lower();
end;
function courseplay:normalizeUTF8(str)
local len = str:len();
local utfLen = utf8Strlen(str);
courseplay:debug(string.format("str %q: len=%d, utfLen=%d", str, len, utfLen), 8);
if len ~= utfLen then --special char in str
local result = "";
for i=0,utfLen-1 do
local char = utf8Substr(str,i,1);
courseplay:debug(string.format("\tchar=%q, replaceChar=%q", char, tostring(courseplay.utf8normalization[char])), 8);
local clean = courseplay.utf8normalization[char] or char:lower();
result = result .. clean;
end;
courseplay:debug(string.format("normalizeUTF8(%q) --> clean=%q", str, result), 8);
return result;
end;
return str:lower();
end;
function courseplay:checkAndPrintChange(vehicle, variable, VariableNameString)
if vehicle.cp.checkTable == nil then
vehicle.cp.checkTable = {}
end
if variable == nil then
variable = -32756
end
if variable ~= vehicle.cp.checkTable[VariableNameString] then
print(string.format("%s: changed Variable: %s: %s",nameNum(vehicle),VariableNameString,tostring(variable)))
vehicle.cp.checkTable[VariableNameString] = variable
end
end;
function courseplay.utils:hasVarChanged(vehicle, variableName, direct)
if direct == nil then direct = false; end;
if vehicle.cp.varMemory == nil then
vehicle.cp.varMemory = {};
end;
local variable;
if direct then
variable = vehicle[variableName];
else
variable = vehicle.cp[variableName];
end;
local memory = vehicle.cp.varMemory[variableName];
if (memory == nil and variable ~= nil) or (memory ~= nil and (variable == nil or variable ~= vehicle.cp.varMemory[variableName])) then
courseplay:debug(string.format('%s: hasVarChanged(): changed variable %q - old=%q, new=%q', nameNum(vehicle), variableName, tostring(memory), tostring(variable)), 12);
vehicle.cp.varMemory[variableName] = variable;
return true;
end;
return false;
end;
function courseplay.utils:getFnCallSource(level)
level = (level or 1) + 1;
return tostring(debug.getinfo(level, "n").name);
end;
function courseplay.utils:getFnCallPath(numPathSteps)
numPathSteps = numPathSteps or 1;
if numPathSteps > 1 then
local ret = {};
local fn, file, line;
for level=numPathSteps + 2, 2, -1 do
local debugData = debug.getinfo(level, 'nSl');
if level <= numPathSteps + 1 then
fn = debugData.name;
if fn and file and line then
ret[#ret + 1] = ('[%d] %s() (%s:%d)'):format(level - 1, fn, file, line);
end;
end;
file = courseplay.utils:getFileNameFromPath(debugData.source);
line = debugData.currentline;
-- print(('level %d: fn=%q, file=%q, line=%d'):format(level, tostring(fn), tostring(file), line))
end;
return table.concat(ret, ' -> ');
end;
local debugData = debug.getinfo(2, 'nSl');
local file = courseplay.utils:getFileNameFromPath(debugData.source);
return ('%s() (%s:%d)'):format(debugData.name, file, debugData.currentline);
end;
function courseplay.utils:getFileNameFromPath(filePath)
local fileName = filePath;
local idx = filePath:match('^.*()/'); -- check for last forward slash
if idx == nil then
idx = filePath:match('^.*()\\'); -- check for last backward slash
end;
if idx then
fileName = filePath:sub(idx + 1);
end;
return fileName;
end;
function courseplay:loc(key)
return courseplay.locales[key] or key;
end;
function courseplay.utils:crossProductQuery(a, b, c, useC)
-- returns:
-- -1 vector from A to right intersects BC (except at the bottom end point)
-- 0 A is directly on BC
-- 1 all else
if useC == nil then useC = true; end;
local x,z = useC and 'cx' or 'x', useC and 'cz' or 'z';
if a[z] == b[z] and b[z] == c[z] then
if (b[x] <= a[x] and a[x] <= c[x]) or (c[x] <= a[x] and a[x] <= b[x]) then
return 0;
else
return 1;
end;
end;
if b[z] > c[z] then
local cNew = b;
local bNew = c;
b,c = bNew,cNew;
end;
if a[z] == b[z] and a[x] == b[x] then
return 0;
end;
if a[z] <= b[z] or a[z] > c[z] then
return 1;
end;
local delta = (b[x] - a[x]) * (c[z] - a[z]) - (b[z] - a[z]) * (c[x] - a[x]);
-- possible to use Utils.sign(): return Utils.sign(delta) * -1;
if delta > 0 then
return -1;
elseif delta < 0 then
return 1;
else
return 0;
end;
end;
function courseplay:getRelativePointDirection(pp, cp, np, useC)
if pp == nil or cp == nil or np == nil then return nil; end;
if useC == nil then useC = true; end;
local dx1, dz1 = courseplay.generation:getPointDirection(pp, cp, useC);
local dx2, dz2 = courseplay.generation:getPointDirection(cp, np, useC);
local rot1 = Utils.getYRotationFromDirection(dx1, dz1);
local rot2 = Utils.getYRotationFromDirection(dx2, dz2);
local rotDelta = rot1 - rot2; --TODO: rot2 - rot1 ?
return Utils.getDirectionFromYRotation(rotDelta);
end;
function courseplay:getObjectName(object, xmlFile)
-- if object.name ~= nil the return object.name; end;
if object.cp and (object.cp.hasSpecializationPathVehicle or object.cp.hasSpecializationTrafficVehicle) then
return 'TrafficVehicle_' .. tostring(object.rootNode);
end;
if object.configFileName then
local storeItem = StoreItemsUtil.storeItemsByXMLFilename[object.configFileName:lower()];
if storeItem and storeItem.name then
return storeItem.name;
end;
end;
if xmlFile ~= nil and xmlFile ~= 0 then
local nameSearch = { 'vehicle.name.' .. g_languageShort, 'vehicle.name.en', 'vehicle.name', 'vehicle#type' };
local name;
for i,xmlKey in ipairs(nameSearch) do
name = getXMLString(xmlFile, xmlKey);
if name ~= nil then
return name;
end;
end;
end;
return courseplay:loc('UNKNOWN') .. '_' .. tostring(object.rootNode);
end;
function courseplay:getRealWorldRotation(node, direction)
if not direction then direction = 1 end;
local x,_,z = localDirectionToWorld(node, 0, 0, direction);
return Utils.getYRotationFromDirection(x, z);
end;
function courseplay:getWorldDirection(fromX, fromY, fromZ, toX, toY, toZ)
-- NOTE: if only 2D is needed, pass fromY and toY as 0
local wdx, wdy, wdz = toX - fromX, toY - fromY, toZ - fromZ;
local dist = Utils.vector3Length(wdx, wdy, wdz); -- length of vector
if dist and dist > 0.01 then
wdx, wdy, wdz = wdx/dist, wdy/dist, wdz/dist; -- if not too short: normalize
return wdx, wdy, wdz, dist;
end;
return 0, 0, 0, 0;
end;
function courseplay.utils:setOverlayUVsSymmetric(overlay, col, line, numCols, numLines)
if overlay.overlayId and overlay.currentUVs == nil or overlay.currentUVs ~= { col, line, numCols, numLines } then
local bottomY = 1 - line / numLines;
local topY = bottomY + 1 / numLines;
local leftX = (col - 1) / numCols;
local rightX = leftX + 1 / numCols;
setOverlayUVs(overlay.overlayId, leftX,bottomY, leftX,topY, rightX,bottomY, rightX,topY);
overlay.currentUVs = { col, line, numCols, numLines };
end;
end;
function courseplay.utils:setOverlayUVsPx(overlay, UVs, textureSizeX, textureSizeY)
if overlay.overlayId and overlay.currentUVs == nil or overlay.currentUVs ~= UVs then
local leftX, bottomY, rightX, topY = unpack(UVs);
local fromTop = false;
if topY < bottomY then
fromTop = true;
end;
local leftXNormal = leftX / textureSizeX;
local rightXNormal = rightX / textureSizeX;
local bottomYNormal = bottomY / textureSizeY;
local topYNormal = topY / textureSizeY;
if fromTop then
bottomYNormal = 1 - bottomYNormal;
topYNormal = 1 - topYNormal;
end;
setOverlayUVs(overlay.overlayId, leftXNormal,bottomYNormal, leftXNormal,topYNormal, rightXNormal,bottomYNormal, rightXNormal,topYNormal);
overlay.currentUVs = UVs;
end;
end;
function courseplay.utils:roundToLowerInterval(num, idp)
return floor(num / idp) * idp;
end;
function courseplay.utils:roundToUpperInterval(num, idp)
return ceil(num / idp) * idp;
end;
function courseplay.utils:getColorFromPct(pct, colorMap, step)
if colorMap[pct] then
return unpack(colorMap[pct]);
end;
local lower = self:roundToLowerInterval(pct, step);
local upper = self:roundToUpperInterval(pct, step);
local alpha = (pct - lower) / step;
return Utils.vector3ArrayLerp(colorMap[lower], colorMap[upper], alpha);
end;
-- 2D course
function courseplay.utils:getCourseDimensions(poly)
local xMin, yMin = huge, huge;
local xMax, yMax = -huge, -huge;
for _,point in pairs(poly) do
xMin = min(xMin, point.cx);
yMin = min(yMin, point.cz);
xMax = max(xMax, point.cx);
yMax = max(yMax, point.cz);
end;
local span = max(xMax-xMin,yMax-yMin);
return { xMin = xMin, xMax = xMax, yMin = yMin, yMax = yMax, span = span };