forked from zxbc/BAR_widgets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gui_attackrange_gl4.lua
1507 lines (1293 loc) · 49 KB
/
gui_attackrange_gl4.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
include("keysym.h.lua")
local versionNumber = "1.1"
function widget:GetInfo()
return {
name = "Attack Range GL4",
desc =
"[v" .. string.format("%s", versionNumber ) .. "] Displays attack ranges of selected units. Custom keybind actions: attackrange_cursor_toggle, attackrange_nextweaponconfig, attackrange_prevweaponconfig",
author = "Errrrrrr, Beherith",
date = "July 20, 2023",
license = "GPLv2",
layer = -99,
enabled = true,
handler = true,
}
end
---------------------------------------------------------------------------------------------------------------------------
-- Bindable action:
-- -- Toggle cursor unit range on and off: attackrange_cursor_toggle
-- -- Unit weapon range dislay cycle forward: attackrange_nextweaponconfig
-- -- Unit weapon range dislay cycle backward: attackrange_prevweaponconfig
-- The widget's individual unit type's display setup is saved in LuaUI/config/AttackRangeConfig2.lua
---------------------------------------------------------------------------------------------------------------------------
local shift_only = false -- only show ranges when shift is held down
local cursor_unit_range = true -- displays the range of the unit at the mouse cursor (if there is one)
---------------------------------------------------------------------------------------------------------------------------
------------------ CONFIGURABLES --------------
local buttonConfig = {
ally = { ground = true, AA = true, nano = true },
enemy = { ground = true, AA = true, nano = true }
}
local colorConfig = {
drawStencil = true, -- wether to draw the outer, merged rings (quite expensive!)
cannon_separate_stencil = false, -- set to true to have cannon and ground be on different stencil mask
drawInnerRings = true, -- wether to draw inner, per attack rings (very cheap)
externalalpha = 0.80, -- alpha of outer rings
internalalpha = 0.20, -- alpha of inner rings
fill_alpha = 0.10, -- this is the solid color in the middle of the stencil
outer_fade_height_difference = 2500, -- this is the height difference at which the outer ring starts to fade out compared to inner rings
--distanceScaleStart = 1500, -- Linewidth is 100% up to this camera height
--distanceScaleEnd = 5000, -- Linewidth becomes 50% above this camera height
ground = {
color = { 1.0, 0.22, 0.05, 0.60 },
fadeparams = { 1500, 2200, 1.0, 0.0 }, -- FadeStart, FadeEnd, StartAlpha, EndAlpha
groupselectionfadescale = 0.75,
externallinethickness = 3.0,
internallinethickness = 2.0,
},
nano = {
color = { 0.24, 1.0, 0.2, 0.40 },
fadeparams = { 2000, 4000, 1.0, 0.0 }, -- FadeStart, FadeEnd, StartAlpha, EndAlpha
groupselectionfadescale = 0.05,
externallinethickness = 3.0,
internallinethickness = 2.0,
},
AA = {
color = { 0.8, 0.44, 2.0, 0.40 },
fadeparams = { 1500, 2200, 1.0, 0.0 }, -- FadeStart, FadeEnd, StartAlpha, EndAlpha
groupselectionfadescale = 0.75,
externallinethickness = 2.5,
internallinethickness = 2.0,
},
cannon = {
color = { 1.0, 0.22, 0.05, 0.60 },
fadeparams = { 1500, 2200, 1.0, 0.0 }, -- FadeStart, FadeEnd, StartAlpha, EndAlpha
groupselectionfadescale = 0.75,
externallinethickness = 3.0,
internallinethickness = 2.0,
},
}
----------------------------------
local show_selected_weapon_ranges = true
local buttonconfigmap = { 'ground', 'nano', 'AA', 'cannon' }
local DEBUG = false --generates debug message
local weaponTypeMap = { 'ground', 'nano', 'AA', 'cannon' }
local unitDefRings = {} --each entry should be a unitdefIDkey to very specific table:
-- a list of tables, ideally ranged from 0 where
local mobileAntiUnitDefs = {
[UnitDefNames.armscab.id] = true,
[UnitDefNames.armcarry.id] = true,
[UnitDefNames.cormabm.id] = true,
[UnitDefNames.corcarry.id] = true,
}
local vtoldamagetag = Game.armorTypes['vtol']
local defaultdamagetag = Game.armorTypes['default']
-- globals
local selUnitCount = 0
local selBuilderCount = 0 -- we need builder count separately
local shifted = false
local isBuilding = false
local builders = {} -- { unitID = unitDef, ...}
local unitToggles = {}
local unitTogglesChunked = {}
local chunk, err = loadfile("LuaUI/config/AttackRangeConfig2.lua")
if chunk then
local tmp = {}
setfenv(chunk, tmp)
unitTogglesChunked = chunk()
end
--helpers
local function tableToString(t)
local result = ""
if type(t) ~= "table" then
result = tostring(t)
elseif t == nil then
result = "nil"
else
for k, v in pairs(t) do
result = result .. "[" .. tostring(k) .. "] = "
if type(v) == "table" then
result = result .. "{"
for k2, v2 in pairs(v) do
result = result .. "[" .. tostring(k2) .. "] = "
if type(v2) == "table" then
result = result .. "{"
for k3, v3 in pairs(v2) do
result = result .. "[" .. tostring(k3) .. "] = " .. tostring(v3) .. ", "
end
result = result .. "}, "
else
result = result .. tostring(v2) .. ", "
end
end
result = result .. "}, "
else
result = result .. tostring(v) .. ", "
end
result = result .. " "
end
end
return "{" .. result:sub(1, -3) .. "}"
end
local function dumpToFile(obj, prefix, filename)
local file = assert(io.open(filename, "w"))
if type(obj) == "table" then
for k, v in pairs(obj) do
local key = prefix and (prefix .. "." .. tostring(k)) or tostring(k)
if type(v) == "function" then
local info = debug.getinfo(v, "S")
file:write(key .. " (function) defined in " .. info.source .. " at line " .. info.linedefined .. "\n")
elseif type(v) == "table" then
file:write(key .. " (table):\n")
dumpToFile(v, key, filename)
else
file:write(key .. " = " .. tostring(v) .. "\n")
end
end
end
if type(obj) == "string" then
file:write(obj)
end
file:close()
end
local function convertToBitmap(statusTable)
if type(statusTable) ~= "table" then
return 0
end
local bitmap = 0
for i, status in ipairs(statusTable) do
if status then
bitmap = bitmap + 2 ^ (i - 1)
end
end
return bitmap
end
local function convertToStatusTable(bitmap, numWeapons)
local statusTable = {}
for i = 1, numWeapons do
local status = bitmap % 2 == 1
table.insert(statusTable, status)
bitmap = (bitmap - (bitmap % 2)) / 2
end
return statusTable
end
local function getNextWeaponCombination(currentCombination, direction)
local numWeapons = #currentCombination
local bitmap = convertToBitmap(currentCombination)
bitmap = (bitmap + direction) % (2 ^ numWeapons)
return convertToStatusTable(bitmap, numWeapons)
end
-- this returns if unitDef is a builder and not a factory
local function isBuilder(unitDef)
if not unitDef then return false end
if unitDef.isFactory and #unitDef.buildOptions > 0 then
return false
end
return unitDef.isBuilder and (unitDef.canAssist or unitDef.canReclaim)
end
local function initializeUnitDefRing(unitDefID)
local weapons = UnitDefs[unitDefID].weapons
unitDefRings[unitDefID]['rings'] = {}
local weaponCount = #weapons or 0
for weaponNum = 1, #weapons do
local weaponDefID = weapons[weaponNum].weaponDef
local weaponDef = WeaponDefs[weaponDefID]
local range = weaponDef.range
local dps = 0
local weaponType = unitDefRings[unitDefID]['weapons'][weaponNum]
--Spring.Echo(weaponType)
if weaponType ~= nil and weaponType > 0 then
local damage = 0
if weaponType == 3 then --AA
damage = weaponDef.damages[vtoldamagetag]
else
damage = weaponDef.damages[defaultdamagetag]
end
dps = damage * (weaponDef.salvoSize or 1) / (weaponDef.reload or 1)
local color = colorConfig[weaponTypeMap[weaponType]].color
local fadeparams = colorConfig[weaponTypeMap[weaponType]].fadeparams
local isCylinder = weaponDef.cylinderTargeting and 1 or 0
local isDgun = (weaponDef.type == "DGun") and 1 or 0
if isDgun == 1 then
--Spring.Echo("dgun found, range in weaponDef is: "..weaponDef.range)
end
local customParams = weaponDef.customParams
local wName = weaponDef.name
if (weaponDef.type == "AircraftBomb") or (wName:find("bogus")) then
--Spring.Echo("bogus weapon found: "..tostring(wName))
range = 0
end
--Spring.Echo("weaponNum: ".. weaponNum ..", name: " .. tableToString(weaponDef.name))
local groupselectionfadescale = colorConfig[weaponTypeMap[weaponType]].groupselectionfadescale
local ringParams = { range, color[1], color[2], color[3], color[4],
fadeparams[1], fadeparams[2], fadeparams[3], fadeparams[4],
weaponDef.projectilespeed or 1,
isCylinder,
weaponDef.heightBoostFactor or 0,
weaponDef.heightMod or 0,
groupselectionfadescale,
weaponType,
isDgun
}
unitDefRings[unitDefID]['rings'][weaponNum] = ringParams
--Spring.Echo("Added ringParams: "..tableToString(ringParams))
end
end
-- for builders, we need to add a special nano ring def
local unitDef = UnitDefs[unitDefID]
if isBuilder(unitDef) then
local range = unitDef.buildDistance
local color = colorConfig['nano'].color
local fadeparams = colorConfig['nano'].fadeparams
local groupselectionfadescale = colorConfig['nano'].groupselectionfadescale
local ringParams = { range, color[1], color[2], color[3], color[4],
fadeparams[1], fadeparams[2], fadeparams[3], fadeparams[4],
1,
false,
0,
0,
groupselectionfadescale,
2,
0
}
unitDefRings[unitDefID]['rings'][weaponCount + 1] = ringParams -- weaponCount + 1 is nano
--Spring.Echo("added builder! "..tableToString(unitDefRings[unitDef.id]))
end
end
local function initUnitList()
unitDefRings = {}
for unitDefID, _ in pairs(unitDefRings) do
initializeUnitDefRing(unitDefID)
end
-- Initialize Colors too
--[[ local scavlist = {}
for k,_ in pairs(unitDefRings) do
scavlist[k] = true
end
-- add scavs
for k,_ in pairs(scavlist) do
--Spring.Echo(k, UnitDefs[k].name)
if UnitDefNames[UnitDefs[k].name .. '_scav'] then
unitDefRings[UnitDefNames[UnitDefs[k].name .. '_scav'].id] = unitDefRings[k]
end
end
local scavlist = {}
for k,_ in pairs(mobileAntiUnitDefs) do
scavlist[k] = true
end
for k,v in pairs(scavlist) do
mobileAntiUnitDefs[UnitDefNames[UnitDefs[k].name .. '_scav'].id] = mobileAntiUnitDefs[k]
end
-- Initialize featureDefIDtoUnitDefID
local wreckheaps = {"_dead","_heap"}
for unitDefID,_ in pairs(unitDefRings) do
local unitDefName = UnitDefs[unitDefID].name
for i, suffix in pairs(wreckheaps) do
if FeatureDefNames[unitDefName..suffix] then
featureDefIDtoUnitDefID[FeatureDefNames[unitDefName..suffix].id] = unitDefID
--Spring.Echo(FeatureDefNames[unitDefName..suffix].id, unitDefID)
end
end
end ]]
end
--Button display configuration
--position only relevant if no saved config data found
local myAllyTeam = Spring.GetMyAllyTeamID()
--------------------------------------------------------------------------------
local glDepthTest = gl.DepthTest
local glLineWidth = gl.LineWidth
local glTexture = gl.Texture
local glClear = gl.Clear
local glColorMask = gl.ColorMask
local glStencilTest = gl.StencilTest
local glStencilMask = gl.StencilMask
local glStencilFunc = gl.StencilFunc
local glStencilOp = gl.StencilOp
local GL_STENCIL_BUFFER_BIT = GL.STENCIL_BUFFER_BIT
local GL_TRIANGLE_FAN = GL.TRIANGLE_FAN
local GL_LEQUAL = GL.LEQUAL
local GL_LINE_LOOP = GL.LINE_LOOP
local GL_NOTEQUAL = GL.NOTEQUAL
local GL_KEEP = 0x1E00 --GL.KEEP
local GL_REPLACE = GL.REPLACE --GL.KEEP
local spGetPositionLosState = Spring.GetPositionLosState
local spGetUnitDefID = Spring.GetUnitDefID
local spGetUnitPosition = Spring.GetUnitPosition
local spGetUnitAllyTeam = Spring.GetUnitAllyTeam
local spFindUnitCmdDesc = Spring.FindUnitCmdDesc
local spGetMouseState = Spring.GetMouseState
local spTraceScreenRay = Spring.TraceScreenRay
local GetModKeyState = Spring.GetModKeyState
local GetInvertQueueKey = Spring.GetInvertQueueKey
local GetActiveCommand = Spring.GetActiveCommand
local GetSelectedUnits = Spring.GetSelectedUnits
local chobbyInterface
function widget:TextCommand(command)
local mycommand = false --buttonConfig["enemy"][tag]
if string.find(command, "defrange", nil, true) then
mycommand = true
local ally = 'ally'
local rangetype = 'ground'
local enabled = false
if string.find(command, "enemy", nil, true) then
ally = 'enemy'
end
if string.find(command, "nano", nil, true) then
rangetype = 'nano'
elseif string.find(command, "AA", nil, true) then
rangetype = 'AA'
end
if string.find(command, "+", nil, true) then
enabled = true
end
buttonConfig[ally][rangetype] = enabled
Spring.Echo("Range visibility of " .. ally .. " " .. rangetype .. " attacks set to", enabled)
return true
end
return false
end
------ GL4 THINGS -----
-- AA and cannons:
local largeCircleVBO = nil
local largeCircleSegments = 512
-- others:
local smallCircleVBO = nil
local smallCircleSegments = 128
local weaponTypeToString = { "ground", "nano", "AA", "cannon", }
local allyenemypairs = { "ally", "enemy" }
local attackRangeClasses = { 'enemyground', 'enemyAA', 'enemynano', 'allyground', 'allyAA', 'enemycannon', 'allycannon',
'allynano' }
local attackRangeVAOs = {}
local circleInstanceVBOLayout = {
{ id = 1, name = 'posscale', size = 4 }, -- a vec4 for pos + scale
{ id = 2, name = 'color1', size = 4 }, -- vec4 the color of this new
{ id = 3, name = 'visibility', size = 4 }, --- vec4 heightdrawstart, heightdrawend, fadefactorin, fadefactorout
{ id = 4, name = 'projectileParams', size = 4 }, --- heightboost gradient
{ id = 5, name = 'additionalParams', size = 4 }, --- groupselectionfadescale, +3 additional reserved
{ id = 6, name = 'instData', size = 4, type = GL.UNSIGNED_INT },
}
local luaShaderDir = "LuaUI/Widgets/Include/"
local LuaShader = VFS.Include(luaShaderDir .. "LuaShader.lua")
VFS.Include(luaShaderDir .. "instancevbotable.lua")
local attackRangeShader = nil
local function goodbye(reason)
Spring.Echo("AttackRange GL4 widget exiting with reason: " .. reason)
widgetHandler:RemoveWidget()
end
local function makeCircleVBO(circleSegments)
circleSegments = circleSegments - 1 -- for po2 buffers
local circleVBO = gl.GetVBO(GL.ARRAY_BUFFER, true)
if circleVBO == nil then goodbye("Failed to create circleVBO") end
local VBOLayout = {
{ id = 0, name = "position", size = 4 },
}
local VBOData = {}
for i = 0, circleSegments do -- this is +1
VBOData[#VBOData + 1] = math.sin(math.pi * 2 * i / circleSegments) -- X
VBOData[#VBOData + 1] = math.cos(math.pi * 2 * i / circleSegments) -- Y
VBOData[#VBOData + 1] = i / circleSegments -- circumference [0-1]
VBOData[#VBOData + 1] = 0
end
circleVBO:Define(
circleSegments + 1,
VBOLayout
)
circleVBO:Upload(VBOData)
return circleVBO
end
local vsSrc = [[
#version 420
#extension GL_ARB_uniform_buffer_object : require
#extension GL_ARB_shader_storage_buffer_object : require
#extension GL_ARB_shading_language_420pack: require
#line 10000
//__DEFINES__
layout (location = 0) in vec4 circlepointposition;
layout (location = 1) in vec4 posscale;
layout (location = 2) in vec4 color1;
layout (location = 3) in vec4 visibility; // FadeStart, FadeEnd, StartAlpha, EndAlpha
layout (location = 4) in vec4 projectileParams; // projectileSpeed, iscylinder!!!! , heightBoostFactor , heightMod
layout (location = 5) in vec4 additionalParams; // groupselectionfadescale, weaponType, +2 reserved
layout (location = 6) in uvec4 instData;
uniform float lineAlphaUniform = 1.0;
uniform float cannonmode = 0.0;
uniform float fadeDistOffset = 0.0;
uniform sampler2D heightmapTex;
uniform sampler2D losTex; // hmm maybe?
out DataVS {
flat vec4 blendedcolor;
vec4 circleprogress;
float groupselectionfadescale;
float weaponType;
};
//__ENGINEUNIFORMBUFFERDEFS__
struct SUniformsBuffer {
uint composite; // u8 drawFlag; u8 unused1; u16 id;
uint unused2;
uint unused3;
uint unused4;
float maxHealth;
float health;
float unused5;
float unused6;
vec4 drawPos;
vec4 speed;
vec4[4] userDefined; //can't use float[16] because float in arrays occupies 4 * float space
};
layout(std140, binding=1) readonly buffer UniformsBuffer {
SUniformsBuffer uni[];
};
#define UNITID (uni[instData.y].composite >> 16)
#line 11000
float heightAtWorldPos(vec2 w){
vec2 uvhm = heighmapUVatWorldPos(w);
return textureLod(heightmapTex, uvhm, 0.0).x;
}
float GetRangeFactor(float projectileSpeed) { // returns >0 if weapon can shoot here, <0 if it cannot, 0 if just right
// on first run, with yDiff = 0, what do we get?
float speed2d = projectileSpeed * 0.707106;
float gravity = 120.0 * (0.001111111);
return ((speed2d * speed2d) * 2.0 ) / (gravity);
}
float GetRange2DCannon(float yDiff,float projectileSpeed,float rangeFactor,float heightBoostFactor) { // returns >0 if weapon can shoot here, <0 if it cannot, 0 if just right
// on first run, with yDiff = 0, what do we get?
//float factor = 0.707106;
float smoothHeight = 100.0;
float speed2d = projectileSpeed*0.707106;
float speed2dSq = speed2d * speed2d;
float gravity = -1.0* (120.0 /900);
if (heightBoostFactor < 0){
heightBoostFactor = (2.0 - rangeFactor) / sqrt(rangeFactor);
}
if (yDiff < -100.0){
yDiff = yDiff * heightBoostFactor;
}else {
if (yDiff < 0.0) {
yDiff = yDiff * (1.0 + (heightBoostFactor - 1.0 ) * (-1.0 * yDiff) * 0.01);
}
}
float root1 = speed2dSq + 2 * gravity *yDiff;
if (root1 < 0.0 ){
return 0.0;
}else{
return rangeFactor * ( speed2dSq + speed2d * sqrt( root1 ) ) / (-1.0 * gravity);
}
}
//float heightMod default: 0.2 (0.8 for #Cannon, 1.0 for #BeamLaser and #LightningCannon)
//Changes the spherical weapon range into an ellipsoid. Values above 1.0 mean the weapon cannot target as high as it can far, values below 1.0 mean it can target higher than it can far. For example 0.5 would allow the weapon to target twice as high as far.
//float heightBoostFactor default: -1.0
//Controls the boost given to range by high terrain. Values > 1.0 result in increased range, 0.0 means the cannon has fixed range regardless of height difference to target. Any value < 0.0 (i.e. the default value) result in an automatically calculated value based on range and theoretical maximum range.
#define RANGE posscale.w
#define PROJECTILESPEED projectileParams.x
#define ISCYLINDER projectileParams.y
#define HEIGHTBOOSTFACTOR projectileParams.z
#define HEIGHTMOD projectileParams.w
#define YGROUND posscale.y
#define OUTOFBOUNDSALPHA alphaControl.y
#define FADEALPHA alphaControl.z
#define MOUSEALPHA alphaControl.w
#define ISDGUN additionalParams.z
void main() {
// Get the center pos of the unit
vec3 modelWorldPos = uni[instData.y].drawPos.xyz;
circleprogress.xy = circlepointposition.xy;
circleprogress.w = circlepointposition.z;
blendedcolor = color1;
groupselectionfadescale = additionalParams.x;
weaponType = additionalParams.y;
// translate to world pos:
vec4 circleWorldPos = vec4(1.0);
float range2 = RANGE;
if (ISDGUN > 0.5) {
circleWorldPos.xz = circlepointposition.xy * RANGE * 1.05 + modelWorldPos.xz;
} else {
circleWorldPos.xz = circlepointposition.xy * RANGE + modelWorldPos.xz;
}
vec4 alphaControl = vec4(1.0);
// get heightmap
circleWorldPos.y = heightAtWorldPos(circleWorldPos.xz);
if (cannonmode > 0.5){
// BAR only has 3 distinct ballistic projectiles, heightBoostFactor is only a handful from -1 to 2.8 and 6 and 8
// gravity we can assume to be linear
float heightDiff = (circleWorldPos.y - YGROUND) * 0.5;
float rangeFactor = RANGE / GetRangeFactor(PROJECTILESPEED); //correct
if (rangeFactor > 1.0 ) rangeFactor = 1.0;
if (rangeFactor <= 0.0 ) rangeFactor = 1.0;
float radius = RANGE;// - heightDiff;
float adjRadius = GetRange2DCannon(heightDiff * HEIGHTMOD, PROJECTILESPEED, rangeFactor, HEIGHTBOOSTFACTOR);
float adjustment = radius * 0.5;
float yDiff = 0;
float adds = 0;
//for (int i = 0; i < mod(timeInfo.x/8,16); i ++){ //i am a debugging god
for (int i = 0; i < 16; i ++){
if (adjRadius > radius){
radius = radius + adjustment;
adds = adds + 1;
}else{
radius = radius - adjustment;
adds = adds - 1;
}
adjustment = adjustment * 0.5;
circleWorldPos.xz = circlepointposition.xy * radius + modelWorldPos.xz;
float newY = heightAtWorldPos(circleWorldPos.xz );
yDiff = abs(circleWorldPos.y - newY);
circleWorldPos.y = max(0, newY);
heightDiff = circleWorldPos.y - modelWorldPos.y;
adjRadius = GetRange2DCannon(heightDiff * HEIGHTMOD, PROJECTILESPEED, rangeFactor, HEIGHTBOOSTFACTOR);
}
}else{
if (ISCYLINDER < 0.5){ // isCylinder
//simple implementation, 4 samples per point
//for (int i = 0; i<mod(timeInfo.x/4,30); i++){
for (int i = 0; i<8; i++){
// draw vector from centerpoint to new height point and normalize it to range length
vec3 tonew = circleWorldPos.xyz - modelWorldPos.xyz;
tonew.y *= HEIGHTMOD;
tonew = normalize(tonew) * RANGE;
circleWorldPos.xz = modelWorldPos.xz + tonew.xz;
circleWorldPos.y = heightAtWorldPos(circleWorldPos.xz);
}
}
}
circleWorldPos.y += 6; // lift it from the ground
// -- MAP OUT OF BOUNDS
vec2 mymin = min(circleWorldPos.xz,mapSize.xy - circleWorldPos.xz);
float inboundsness = min(mymin.x, mymin.y);
OUTOFBOUNDSALPHA = 1.0 - clamp(inboundsness*(-0.02),0.0,1.0);
//--- DISTANCE FADE ---
vec4 camPos = cameraViewInv[3];
float distToCam = length(modelWorldPos.xyz - camPos.xyz); //dist from cam
// FadeStart, FadeEnd, StartAlpha, EndAlpha
float fadeDist = visibility.y - visibility.x;
if (ISDGUN > 0.5) {
FADEALPHA = clamp((visibility.y + fadeDistOffset + 1000 - distToCam)/(fadeDist),visibility.w,visibility.z);
} else {
FADEALPHA = clamp((visibility.y + fadeDistOffset - distToCam)/(fadeDist),visibility.w,visibility.z);
}
//FADEALPHA = clamp((visibility.y + fadeDistOffset - distToCam)/(fadeDist),visibility.w,visibility.z);
//--- Optimize by anything faded out getting transformed back to origin with 0 range?
//seems pretty ok!
if (FADEALPHA < 0.001) {
circleWorldPos.xyz = modelWorldPos.xyz;
}
if (cannonmode > 0.5){
// cannons should fade distance based on their range
//float cvmin = max(visibility.x+fadeDistOffset, 2* RANGE);
//float cvmax = max(visibility.y+fadeDistOffset, 4* RANGE);
//FADEALPHA = clamp((cvmin - distToCam)/(cvmax - cvmin + 1.0),visibility.z,visibility.w);
}
blendedcolor = color1;
// -- DARKEN OUT OF LOS
//vec4 losTexSample = texture(losTex, vec2(circleWorldPos.x / mapSize.z, circleWorldPos.z / mapSize.w)); // lostex is PO2
//float inlos = dot(losTexSample.rgb,vec3(0.33));
//inlos = clamp(inlos*5 -1.4 , 0.5,1.0); // fuck if i know why, but change this if LOSCOLORS are changed!
//blendedcolor.rgb *= inlos;
// --- YES FOG
float fogDist = length((cameraView * vec4(circleWorldPos.xyz,1.0)).xyz);
float fogFactor = clamp((fogParams.y - fogDist) * fogParams.w, 0, 1);
blendedcolor.rgb = mix(fogColor.rgb, vec3(blendedcolor), fogFactor);
// -- IN-SHADER MOUSE-POS BASED HIGHLIGHTING
float disttomousefromunit = 1.0 - smoothstep(48, 64, length(modelWorldPos.xz - mouseWorldPos.xz));
// this will be positive if in mouse, negative else
float highlightme = clamp( (disttomousefromunit ) + 0.0, 0.0, 1.0);
MOUSEALPHA = 0.1* highlightme;
// ------------ dump the stuff for FS --------------------
//worldPos = circleWorldPos;
//worldPos.a = RANGE;
alphaControl.x = circlepointposition.z; // save circle progress here
gl_Position = cameraViewProj * vec4(circleWorldPos.xyz, 1.0);
//lets blend the alpha here, and save work in FS:
float outalpha = OUTOFBOUNDSALPHA * (MOUSEALPHA + FADEALPHA * lineAlphaUniform);
blendedcolor.a *= outalpha ;
if (ISDGUN > 0.5) {
blendedcolor.a = clamp(blendedcolor.a * 3, 0.1, 1.0);
}
//blendedcolor.rgb = vec3(fract(distToCam/100));
}
]]
local fsSrc = [[
#version 330
#extension GL_ARB_uniform_buffer_object : require
#extension GL_ARB_shading_language_420pack: require
//_DEFINES__
#line 20000
uniform float selUnitCount = 1.0;
uniform float selBuilderCount = 1.0;
uniform float drawAlpha = 1.0;
uniform float drawMode = 0.0;
//_ENGINEUNIFORMBUFFERDEFS__
in DataVS {
flat vec4 blendedcolor;
vec4 circleprogress;
float groupselectionfadescale;
float weaponType;
};
out vec4 fragColor;
void main() {
// -- we need to mod alpha based on groupselectionfadescale and weaponType
// -- innerRingDim = group_selection_fade_scale * 0.1 * numUnitsSelected
float numUnitsSelected = selUnitCount;
// -- nano is 2
if(weaponType == 2.0) {
numUnitsSelected = selBuilderCount;
}
numUnitsSelected = clamp(numUnitsSelected, 1, 25);
float innerRingDim = groupselectionfadescale * 0.1 * numUnitsSelected;
float finalAlpha = drawAlpha;
if(drawMode == 2.0) {
finalAlpha = drawAlpha / pow(innerRingDim, 2);
}
finalAlpha = clamp(finalAlpha, 0.0, 1.0);
fragColor = vec4(blendedcolor.x, blendedcolor.y, blendedcolor.z, blendedcolor.w * finalAlpha);
}
]]
local cacheTable = {}
for i = 1, 24 do cacheTable[i] = 0 end
-- code for selected units start here
local selectedUnits = {}
local selUnits = {}
local updateSelection = false
local selections = {} -- contains params for added vaos
local mouseUnit
local mouseovers = {} -- mirroring selections, but for mouseovers
local unitsOnOff = {} -- unit weapon toggle states, tracked from CommandNotify (also building on off status)
local myTeam = Spring.GetMyTeamID()
local function GetUnitDef(unitID)
local unitDefID = spGetUnitDefID(unitID)
if unitDefID then
local unitDef = UnitDefs[unitDefID]
return unitDef
end
return nil
end
-- mirrors functionality of UnitDetected
local function AddSelectedUnit(unitID, mouseover)
--if not show_selected_weapon_ranges then return end
local collections = selections
if mouseover then
collections = mouseovers
end
local unitDef = GetUnitDef(unitID)
if not unitDef then return end
if collections[unitID] ~= nil then return end
--- if unittype is toggled off we don't proceed at all
local unitName = unitDef.name
local alliedUnit = (spGetUnitAllyTeam(unitID) == myAllyTeam)
local allystring = alliedUnit and "ally" or "enemy"
--local alliedUnit = (spGetUnitAllyTeam(unitID) == myAllyTeam)
--local x, y, z, mpx, mpy, mpz, apx, apy, apz = spGetUnitPosition(unitID, true, true)
local weapons = unitDef.weapons
if (not weapons or #weapons == 0) and not isBuilder(unitDef) then return end -- no weapons and not builder, nothing to add
-- we want to add to unitDefRings here if it doesn't exist
if not unitDefRings[unitDef.id] then
-- read weapons and add them to weapons table, then add to entry
local entry = { weapons = {} }
for weaponNum = 1, #weapons do
local weaponDefID = weapons[weaponNum].weaponDef
local weaponDef = WeaponDefs[weaponDefID]
local range = weaponDef.range
local weapon = weapons[weaponNum]
-- debug shit
--[[ local weaponTable = {}
for name,param in pairs(weapon.onlyTargets) do--:pairs() do
weaponTable[name]=param
end ]]
--Spring.Echo("----------weaponDef: "..tableToString(weaponTable))
if true then --range > 0 then -- trying something different
--if weaponDef.description:find("g2a") and not weaponDef.description:find("g2g") then
if weapon.onlyTargets and weapon.onlyTargets.vtol then
--Spring.Echo("AA? " .. weaponDef.name..": "..tostring(weaponDef.description))
entry.weapons[weaponNum] = 3 -- weaponTypeMap[3] is "AA"
--Spring.Echo("added AA weapon: ".. weaponDef.name)
elseif weaponDef.type == "Cannon" then
entry.weapons[weaponNum] = 4 -- weaponTypeMap[4] is "cannon"
else
entry.weapons[weaponNum] = 1 -- weaponTypeMap[1] is "ground"
end
end
end
-- builder can have no weapon but still need to be added
if isBuilder(unitDef) then
local wt = entry.weapons
wt[#wt + 1] = 2 -- 2 is nano
end
unitDefRings[unitDef.id] = entry -- we insert the entry so we can reuse existing code
--Spring.Echo("unitDefRings entry added: "..tableToString(entry))
-- we need to initialize the other params
initializeUnitDefRing(unitDef.id)
end
local x, y, z, mpx, mpy, mpz, apx, apy, apz = spGetUnitPosition(unitID, true, true)
--for weaponNum = 1, #weapons do
local addedRings = 0
local weapons = unitDefRings[unitDef.id]['weapons']
for j, weaponType in pairs(weapons) do
local drawIt = true
-- we need to check if the unit has on/off weapon states, and only add the one active
local weaponOnOff, onOffName
local unitIsOnOff = unitDef.onOffable --spFindUnitCmdDesc(unitID, 85) ~= nil -- if this unit can toggle weapons
local customParams = unitDef.customParams
if customParams then
onOffName = customParams.onoffname
--Spring.Echo("onOffName: ".. tostring(onOffName))
end
-- on off can be set on a building, we need to check that
if unitIsOnOff and not onOffName then -- if it's a building with actual on/off, we display range if it's on
weaponOnOff = unitsOnOff[unitID] or 1
drawIt = (weaponOnOff == 1)
elseif unitIsOnOff and onOffName then -- this is a unit or building with 2 weapons
weaponOnOff = unitsOnOff[unitID] or 0
drawIt = ((weaponOnOff + 1) == j) or
#weapons == 1 -- remember weaponOnOff is 0 or 1, weapon number starts from 1
end
-- we add checks here for the display toggle status from config
if unitToggles[unitName] then -- only if there's a config, else default is to draw it
local wToggleStatuses = unitToggles[unitName][allystring]
if type(wToggleStatuses) == 'table' then
drawIt = wToggleStatuses[j] and drawIt
else
-- fixing the unitToggles table since something was corrupted
local entry = {}
for i=1, #weapons do
entry[i] = true
end
unitToggles[unitName][allystring] = entry
end
end
local ringParams = unitDefRings[unitDef.id]['rings'][j]
if drawIt and ringParams[1] > 0 then
--local weaponType = unitDefRings[unitDefID]['weapons'][weaponNum]
cacheTable[1] = mpx
cacheTable[2] = mpy
cacheTable[3] = mpz
local vaokey = allystring .. weaponTypeToString[weaponType]
for i = 1, 16 do
cacheTable[i + 3] = ringParams[i]
end
if false then
local s = ' '
for i = 1, 20 do
s = s .. "; " .. tostring(cacheTable[i])
end
if true then
Spring.Echo("Adding rings for", unitID, x, z)
Spring.Echo("added", vaokey, s)
end
end
local instanceID = 10000000 * (mouseover and 1 or 0) + 1000000 * weaponType + unitID +
100000 *
j -- weapon index needs to be included here for uniqueness
--Spring.Echo("instanceID created: "..tostring(instanceID))
pushElementInstance(attackRangeVAOs[vaokey], cacheTable, instanceID, true, false, unitID)
addedRings = addedRings + 1
if collections[unitID] == nil then
--lazy creation
collections[unitID] = {
posx = mpx,
posy = mpy,
posz = mpz,
vaokeys = {},
allied = alliedUnit,
unitDefID = unitDef.id
}
end
collections[unitID].vaokeys[instanceID] = vaokey
end
end
--Spring.Echo("Rings added: " ..tostring(addedRings))
-- we cheat here and update builder count
if isBuilder(unitDef) and addedRings > 0 then
selBuilderCount = selBuilderCount + 1
end
end
local function RemoveSelectedUnit(unitID, mouseover)
--if not show_selected_weapon_ranges then return end
local collections = selections
if mouseover then collections = mouseovers end
local removedRings = 0
if collections[unitID] then
local collection = collections[unitID]
if not collection then return end
for instanceKey, vaoKey in pairs(collection.vaokeys) do
--Spring.Echo(vaoKey,instanceKey)
popElementInstance(attackRangeVAOs[vaoKey], instanceKey)
removedRings = removedRings + 1
end
--Spring.Echo("Rings removed: "..tostring(removedRings))
-- before we get rid of the definition we cheat again
local unitDef = UnitDefs[collections[unitID].unitDefID]
if isBuilder(unitDef) then
selBuilderCount = selBuilderCount - 1
end
collections[unitID] = nil
--Spring.Echo("removed rings from unitID: "..tostring(unitID))
end
end
function widget:SelectionChanged(sel)
updateSelection = true
--Spring.Echo("selection changed!")
end
local function InitializeBuilders()
builders = {}
for _, unitID in ipairs(Spring.GetTeamUnits(Spring.GetMyTeamID())) do
if isBuilder(UnitDefs[spGetUnitDefID(unitID)]) then
builders[unitID] = UnitDefs[spGetUnitDefID(unitID)]
end
end
end
local function makeShaders()
local engineUniformBufferDefs = LuaShader.GetEngineUniformBufferDefs()
vsSrc = vsSrc:gsub("//__ENGINEUNIFORMBUFFERDEFS__", engineUniformBufferDefs)
fsSrc = fsSrc:gsub("//__ENGINEUNIFORMBUFFERDEFS__", engineUniformBufferDefs)
attackRangeShader = LuaShader(
{
vertex = vsSrc:gsub("//__DEFINES__", "#define MYGRAVITY " .. tostring(Game.gravity + 0.1)),
fragment = fsSrc,
--geometry = gsSrc, no geom shader for now
uniformInt = {