forked from Facepunch/Rust.Community
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommunityEntity.UI.cs
More file actions
1041 lines (892 loc) · 47.4 KB
/
CommunityEntity.UI.cs
File metadata and controls
1041 lines (892 loc) · 47.4 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
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Facepunch.Extend;
using System.IO;
using Rust.Workshop;
using TMPro;
#if CLIENT
public partial class CommunityEntity
{
private static List<GameObject> AllUi = new List<GameObject>();
private static Dictionary<string, GameObject> UiDict = new Dictionary<string, GameObject>();
private static List<string> ScrollViews = new List<string>();
public static void DestroyServerCreatedUI()
{
foreach ( var go in AllUi )
{
if ( !go ) continue;
GameObject.Destroy( go );
}
AllUi.Clear();
UiDict.Clear();
requestingTextureImages.Clear();
ScrollViews.Clear();
UnloadTextureCache();
// Cleanup any custom vitals we created
if (NoticeArea.Instance != null)
{
NoticeArea.Instance.DeleteAllCustomVitals();
}
}
public void SetVisible( bool b )
{
foreach (var go in OverallPanels)
{
var c = go.GetComponent<Canvas>();
if (c != null)
{
c.gameObject.SetActive(b);
}
}
}
private static void RegisterUi( GameObject go )
{
AllUi.Add( go );
UiDict[ go.name ] = go;
}
[RPC_Client]
public void AddUI( RPCMessage msg )
{
if ( Client.IsPlayingDemo && !ConVar.Demo.showCommunityUI )
return;
var str = msg.read.StringRaw();
if ( string.IsNullOrEmpty( str ) ) return;
var jsonArray = JSON.Array.Parse( str );
if ( jsonArray == null ) return;
foreach ( var value in jsonArray )
{
var json = value.Obj;
if ( json.ContainsKey( "destroyUi" ) )
{
DestroyPanel( json.GetString( "destroyUi", "AddUI CreatedPanel" ) );
}
var parentPanel = FindPanel( json.GetString( "parent", "Overlay" ) );
var gameObjectName = json.GetString( "name", "AddUI CreatedPanel" );
// ensuring that unnamed panels are given a unique name
if ( parentPanel == null )
{
Debug.LogWarning( "AddUI: Unknown Parent for \"" + gameObjectName + "\": " + json.GetString( "parent", "Overlay" ) );
return;
}
var allowUpdate = json.GetBoolean( "update", false );
GameObject go = null;
if ( allowUpdate && json.ContainsKey( "name" ) )
{
go = FindPanel( gameObjectName, false );
}
if ( allowUpdate && go == null )
{
Debug.LogWarning( $"[AddUI] Unable to update object '{gameObjectName}': can't be found" );
return;
}
if ( go == null )
{
go = new GameObject( gameObjectName, typeof( RectTransform ) );
go.transform.SetParent( parentPanel.transform, false );
RegisterUi( go );
var rt = go.GetComponent<RectTransform>();
if ( rt )
FitParent(rt);
}
if (json.ContainsKey("activeSelf"))
go.SetActive(json.GetBoolean("activeSelf", true));
foreach ( var component in json.GetArray( "components" ) )
{
CreateComponents( go, component.Obj, allowUpdate );
}
if ( json.ContainsKey( "fadeOut" ) )
{
go.AddComponent<FadeOut>().duration = json.GetFloat( "fadeOut", 0 );
}
}
}
private GameObject FindPanel( string name, bool allowScrollviews = true )
{
// if its a scrollview we're looking for, return the child if it exists
if(allowScrollviews && ScrollViews.Contains(name)){
var scrollContent = FindPanel(name + "___Content");
if(scrollContent != null)
return scrollContent;
}
GameObject panel;
if ( UiDict.TryGetValue( name, out panel ) )
{
return panel;
}
var tx = transform.FindChildRecursive( name );
if ( tx ) return tx.gameObject;
return null;
}
// Move this local function outside CreateComponents()
private static void HandleEnableState( JSON.Object json, Behaviour component )
{
if ( json.TryGetBoolean( "enabled", out var result ) )
{
component.enabled = result;
}
}
private void CreateComponents( GameObject go, JSON.Object obj, bool allowUpdate )
{
// Unsure if local functions allocate like lambdas do, this is just for modding so not a big deal & can double check once it builds
bool ShouldUpdateField( string fieldName )
{
return !allowUpdate || obj.ContainsKey( fieldName );
}
// Only checks field name (if we want to keep default value)
bool HasField( string fieldName)
{
return obj.ContainsKey(fieldName);
}
T GetOrAddComponent<T>() where T : Component
{
if ( allowUpdate && go.TryGetComponent( out T component ) )
{
return component;
}
return go.AddComponent<T>();
}
//
// This is the 'stupid' but 'safe & predictable way of doing this.
//
switch ( obj.GetString( "type", "UnityEngine.UI.Text" ) )
{
case "UnityEngine.UI.Text":
{
var c = GetOrAddComponent<UnityEngine.UI.Text>();
HandleEnableState( obj, c );
if ( ShouldUpdateField( "text" ) )
c.text = obj.GetString( "text", "Text" );
if ( ShouldUpdateField( "fontSize" ) )
c.fontSize = obj.GetInt( "fontSize", 14 );
if ( ShouldUpdateField( "font" ) )
{
c.font = LoadFont(obj.GetString("font", strDEFAULT: "RobotoCondensed-Bold.ttf"));
}
if ( ShouldUpdateField( "align" ) )
c.alignment = ParseEnum( obj.GetString( "align" ), TextAnchor.UpperLeft );
if ( ShouldUpdateField( "color" ) )
c.color = ColorEx.Parse( obj.GetString( "color", "1.0 1.0 1.0 1.0" ) );
if ( ShouldUpdateField( "verticalOverflow" ) )
c.verticalOverflow = ParseEnum( obj.GetString( "verticalOverflow", "Truncate" ), VerticalWrapMode.Truncate );
GraphicComponentCreated( c, obj );
break;
}
case "UnityEngine.UI.Image":
{
var c = GetOrAddComponent<UnityEngine.UI.Image>();
HandleEnableState( obj, c );
if ( ShouldUpdateField( "sprite" ) )
c.sprite = FileSystem.Load<Sprite>( obj.GetString( "sprite", "Assets/Content/UI/UI.Background.Tile.psd" ) );
if ( ShouldUpdateField( "material" ) )
c.material = FileSystem.Load<Material>( obj.GetString( "material", "Assets/Icons/IconMaterial.mat" ) );
if ( ShouldUpdateField( "color" ) )
c.color = ColorEx.Parse( obj.GetString( "color", "1.0 1.0 1.0 1.0" ) );
if ( ShouldUpdateField( "imagetype" ) )
c.type = ParseEnum( obj.GetString( "imagetype", "Simple" ), UnityEngine.UI.Image.Type.Simple );
if( ShouldUpdateField( "fillCenter" ) )
c.fillCenter = obj.GetBoolean("fillCenter", c.fillCenter);
if ( obj.ContainsKey( "png" ) && uint.TryParse( obj.GetString( "png" ), out var id ) )
{
Vector4? slice = null;
if (obj.ContainsKey("slice"))
{
slice = Vector4Ex.Parse(obj.GetString("slice", "0 0 0 0"));
}
ApplyTextureToImage( c, id, slice );
}
if ( obj.ContainsKey( "itemid" ) )
{
var itemdef = ItemManager.FindItemDefinition( obj.GetInt( "itemid" ) );
if ( itemdef != null )
{
c.material = null;
c.sprite = itemdef.iconSprite;
if ( obj.ContainsKey( "skinid" ) )
{
var requestedSkin = (ulong)obj.GetNumber( "skinid" );
var skin = itemdef.skins.FirstOrDefault( x => x.id == (int)requestedSkin );
if ( skin.id == (int)requestedSkin )
{
c.sprite = skin.invItem.icon;
}
else
{
var workshopSprite = WorkshopIconLoader.Find( requestedSkin, null, () =>
{
if ( c != null )
c.sprite = WorkshopIconLoader.Find( requestedSkin );
} );
if ( workshopSprite != null )
{
c.sprite = workshopSprite;
}
}
}
}
}
GraphicComponentCreated( c, obj );
break;
}
case "UnityEngine.UI.RawImage":
{
var c = GetOrAddComponent<UnityEngine.UI.RawImage>();
HandleEnableState( obj, c );
if ( ShouldUpdateField( "sprite" ) )
c.texture = FileSystem.Load<Texture>( obj.GetString( "sprite", "Assets/Icons/rust.png" ) );
if ( ShouldUpdateField( "color" ) )
c.color = ColorEx.Parse( obj.GetString( "color", "1.0 1.0 1.0 1.0" ) );
if ( obj.ContainsKey( "material" ) )
{
c.material = FileSystem.Load<Material>( obj.GetString( "material" ) );
}
if ( obj.ContainsKey( "url" ) )
{
Rust.Global.Runner.StartCoroutine( LoadTextureFromWWW( c, obj.GetString( "url" ) ) );
}
if ( obj.ContainsKey( "png" ) && uint.TryParse( obj.GetString( "png" ), out var id ) )
{
ApplyTextureToImage( c, id );
}
if ( obj.ContainsKey( "steamid" ) )
{
var steamidString = obj.GetString( "steamid" );
if(ulong.TryParse(steamidString, out var steamId))
c.texture = SingletonComponent<SteamClientWrapper>.Instance.GetAvatarTexture(steamId);
}
GraphicComponentCreated( c, obj );
break;
}
case "UnityEngine.UI.Button":
{
var c = GetOrAddComponent<UnityEngine.UI.Button>();
HandleEnableState( obj, c );
if ( obj.ContainsKey( "command" ) )
{
var cmd = obj.GetString( "command" );
if ( allowUpdate )
c.onClick.RemoveAllListeners();
c.onClick.AddListener( () => { ConsoleNetwork.ClientRunOnServer( cmd ); } );
}
if ( obj.ContainsKey( "close" ) )
{
var pnlName = obj.GetString( "close" );
if ( allowUpdate )
c.onClick.RemoveAllListeners();
c.onClick.AddListener( () => { DestroyPanel( pnlName ); } );
}
// bg image
var img = GetOrAddComponent<UnityEngine.UI.Image>();
if ( ShouldUpdateField( "sprite" ) )
img.sprite = FileSystem.Load<Sprite>( obj.GetString( "sprite", "Assets/Content/UI/UI.Background.Tile.psd" ) );
if ( ShouldUpdateField( "material" ) )
img.material = FileSystem.Load<Material>( obj.GetString( "material", "Assets/Icons/IconMaterial.mat" ) );
if ( ShouldUpdateField( "color" ) )
img.color = ColorEx.Parse( obj.GetString( "color", "1.0 1.0 1.0 1.0" ) );
if ( ShouldUpdateField( "imagetype" ) )
img.type = ParseEnum( obj.GetString( "imagetype", "Simple" ), UnityEngine.UI.Image.Type.Simple );
c.image = img;
// Modify the color of the button when hovered
// Have to grab colorBlock, modify then reassign
var colors = c.colors;
if (HasField("normalColor"))
colors.normalColor = ColorEx.Parse(obj.GetString("normalColor", "1.0 1.0 1.0 1.0"));
if (HasField("highlightedColor"))
colors.highlightedColor = ColorEx.Parse(obj.GetString("highlightedColor", "1.0 1.0 1.0 1.0"));
if (HasField("pressedColor"))
colors.pressedColor = ColorEx.Parse(obj.GetString("pressedColor", "1.0 1.0 1.0 1.0"));
if (HasField("selectedColor"))
colors.selectedColor = ColorEx.Parse(obj.GetString("selectedColor", "1.0 1.0 1.0 1.0"));
if (HasField("disabledColor"))
colors.disabledColor = ColorEx.Parse(obj.GetString("disabledColor", "0.5 0.5 0.5 0.5"));
if (HasField("colorMultiplier"))
colors.colorMultiplier = obj.GetFloat("colorMultiplier", 1.0f);
if (HasField("fadeDuration"))
colors.fadeDuration = obj.GetFloat("fadeDuration", 0.1f);
c.colors = colors;
GraphicComponentCreated( img, obj );
break;
}
case "UnityEngine.UI.Outline":
{
var c = GetOrAddComponent<UnityEngine.UI.Outline>();
HandleEnableState( obj, c );
if ( ShouldUpdateField( "color" ) )
c.effectColor = ColorEx.Parse( obj.GetString( "color", "1.0 1.0 1.0 1.0" ) );
if ( ShouldUpdateField( "distance" ) )
c.effectDistance = Vector2Ex.Parse( obj.GetString( "distance", "1.0 -1.0" ) );
c.useGraphicAlpha = obj.ContainsKey( "useGraphicAlpha" );
break;
}
case "UnityEngine.UI.InputField":
{
var t = GetOrAddComponent<UnityEngine.UI.Text>();
HandleEnableState( obj, t );
if ( ShouldUpdateField( "fontSize" ) )
t.fontSize = obj.GetInt( "fontSize", allowUpdate ? t.fontSize : 14 );
if ( ShouldUpdateField( "font" ) )
{
t.font = LoadFont(obj.GetString("font", strDEFAULT: "RobotoCondensed-Bold.ttf"));
}
if ( ShouldUpdateField( "align" ) )
t.alignment = ParseEnum( obj.GetString( "align" ), TextAnchor.UpperLeft );
if ( ShouldUpdateField( "color" ) )
t.color = ColorEx.Parse( obj.GetString( "color", "1.0 1.0 1.0 1.0" ) );
var c = GetOrAddComponent<UnityEngine.UI.InputField>();
HandleEnableState( obj, c );
c.textComponent = t;
if ( ShouldUpdateField( "characterLimit" ) )
c.characterLimit = obj.GetInt( "characterLimit", allowUpdate ? c.characterLimit : 0 );
if ( obj.ContainsKey( "command" ) )
{
var cmd = obj.GetString( "command" );
if ( allowUpdate )
c.onEndEdit.RemoveAllListeners();
c.onEndEdit.AddListener( ( value ) => { ConsoleNetwork.ClientRunOnServer( cmd + " " + value ); } );
}
if ( ShouldUpdateField( "lineType" ) )
c.lineType = ParseEnum( obj.GetString( "lineType", "SingleLine" ), InputField.LineType.SingleLine );
if ( ShouldUpdateField( "text" ) )
c.text = obj.GetString( "text", "Text" );
if ( ShouldUpdateField( "readOnly" ) )
c.readOnly = obj.GetBoolean( "readOnly", false );
if (ShouldUpdateField("placeholderId"))
{
AssignInputFieldPlaceholder(c, obj.GetString("placeholderId"));
}
if ( obj.TryGetBoolean( "password", out var password ) )
{
c.inputType = password ? InputField.InputType.Password : InputField.InputType.Standard;
}
if ( obj.TryGetBoolean( "needsKeyboard", out var needsKeyboard ) )
{
var comp = GetOrAddComponent<NeedsKeyboardInputField>();
comp.enabled = needsKeyboard;
}
//blocks keyboard input the same as NeedsKeyboard, but is used for UI in the inventory/crafting
if ( obj.TryGetBoolean( "hudMenuInput", out var hudMenuInput ) )
{
var comp = GetOrAddComponent<HudMenuInput>();
comp.enabled = hudMenuInput;
}
if ( obj.ContainsKey( "autofocus" ) )
{
c.Select();
}
GraphicComponentCreated( t, obj );
break;
}
case "NeedsCursor":
{
var c = GetOrAddComponent<NeedsCursor>();
HandleEnableState( obj, c );
break;
}
case "RectTransform":
{
var rt = go.GetComponent<RectTransform>();
if ( rt )
{
if ( ShouldUpdateField( "anchormin" ) )
rt.anchorMin = Vector2Ex.Parse( obj.GetString( "anchormin", "0.0 0.0" ) );
if ( ShouldUpdateField( "anchormax" ) )
rt.anchorMax = Vector2Ex.Parse( obj.GetString( "anchormax", "1.0 1.0" ) );
if ( ShouldUpdateField( "offsetmin" ) )
rt.offsetMin = Vector2Ex.Parse( obj.GetString( "offsetmin", "0.0 0.0" ) );
if ( ShouldUpdateField( "offsetmax" ) )
rt.offsetMax = Vector2Ex.Parse( obj.GetString( "offsetmax", "1.0 1.0" ) );
if ( ShouldUpdateField( "rotation" ) )
rt.rotation = Quaternion.Euler( 0, 0, obj.GetFloat("rotation", 0) );
// some Update only fields to allow reparenting of draggables if needed
if (allowUpdate && obj.ContainsKey( "setParent" ) ){
var newParentName = obj.GetString( "setParent", null );
if(!string.IsNullOrEmpty(newParentName)){
var newParent = FindPanel(newParentName);
if(newParent)
rt.SetParent(newParent.transform);
}
}
if(allowUpdate && obj.ContainsKey( "setTransformIndex" ) ){
var newIndex = obj.GetInt("setTransformIndex", -1);
if(newIndex >= 0)
rt.SetSiblingIndex(newIndex);
}
}
break;
}
case "Countdown":
{
var c = GetOrAddComponent<Countdown>();
HandleEnableState( obj, c );
if ( ShouldUpdateField( "endTime" ) )
c.endTime = obj.GetFloat( "endTime", allowUpdate ? c.endTime : 0f );
if ( ShouldUpdateField( "startTime" ) )
c.startTime = obj.GetFloat( "startTime", allowUpdate ? c.startTime : 0f );
if ( ShouldUpdateField( "step" ) )
c.step = obj.GetFloat( "step", allowUpdate ? c.step : 1f );
if ( ShouldUpdateField( "interval" ) ) {
c.interval = obj.GetFloat( "interval", allowUpdate ? c.interval : c.step );
if(allowUpdate)
c.Reset();
}
if ( ShouldUpdateField( "timerFormat" ) )
c.timerFormat = ParseEnum<Countdown.TimerFormat>(obj.GetString("timerFormat", "None"), allowUpdate ? c.timerFormat : Countdown.TimerFormat.None);
if ( ShouldUpdateField( "numberFormat" ) )
c.numberFormat = obj.GetString( "numberFormat", allowUpdate ? c.numberFormat : "0.####" );
if ( ShouldUpdateField( "destroyIfDone" ) )
c.destroyIfDone = obj.GetBoolean( "destroyIfDone", allowUpdate ? c.destroyIfDone : true);
if ( obj.ContainsKey( "command" ) )
{
c.command = obj.GetString( "command" );
}
break;
}
case "UnityEngine.UI.HorizontalLayoutGroup":
{
var c = GetOrAddComponent<HorizontalLayoutGroup>();
HandleEnableState(obj, c);
if (ShouldUpdateField("spacing"))
c.spacing = obj.GetFloat("spacing", 0f);
if (ShouldUpdateField("childAlignment"))
c.childAlignment = ParseEnum(obj.GetString("childAlignment", "UpperLeft"), TextAnchor.UpperLeft);
if (ShouldUpdateField("childForceExpandWidth"))
c.childForceExpandWidth = obj.GetBoolean("childForceExpandWidth", true);
if (ShouldUpdateField("childForceExpandHeight"))
c.childForceExpandHeight = obj.GetBoolean("childForceExpandHeight", true);
if (ShouldUpdateField("childControlWidth"))
c.childControlWidth = obj.GetBoolean("childControlWidth", false);
if (ShouldUpdateField("childControlHeight"))
c.childControlHeight = obj.GetBoolean("childControlHeight", false);
if (ShouldUpdateField("childScaleWidth"))
c.childScaleWidth = obj.GetBoolean("childScaleWidth", false);
if (ShouldUpdateField("childScaleHeight"))
c.childScaleHeight = obj.GetBoolean("childScaleHeight", false);
ApplyPadding(c, obj, ShouldUpdateField);
break;
}
case "UnityEngine.UI.VerticalLayoutGroup":
{
var c = GetOrAddComponent<VerticalLayoutGroup>();
HandleEnableState(obj, c);
if (ShouldUpdateField("spacing"))
c.spacing = obj.GetFloat("spacing", 0f);
if (ShouldUpdateField("childAlignment"))
c.childAlignment = ParseEnum(obj.GetString("childAlignment", "UpperLeft"), TextAnchor.UpperLeft);
if (ShouldUpdateField("childForceExpandWidth"))
c.childForceExpandWidth = obj.GetBoolean("childForceExpandWidth", true);
if (ShouldUpdateField("childForceExpandHeight"))
c.childForceExpandHeight = obj.GetBoolean("childForceExpandHeight", true);
if (ShouldUpdateField("childControlWidth"))
c.childControlWidth = obj.GetBoolean("childControlWidth", false);
if (ShouldUpdateField("childControlHeight"))
c.childControlHeight = obj.GetBoolean("childControlHeight", false);
if (ShouldUpdateField("childScaleWidth"))
c.childScaleWidth = obj.GetBoolean("childScaleWidth", false);
if (ShouldUpdateField("childScaleHeight"))
c.childScaleHeight = obj.GetBoolean("childScaleHeight", false);
ApplyPadding(c, obj, ShouldUpdateField);
break;
}
case "UnityEngine.UI.GridLayoutGroup":
{
var c = GetOrAddComponent<GridLayoutGroup>();
HandleEnableState(obj, c);
if (ShouldUpdateField("cellSize"))
c.cellSize = Vector2Ex.Parse(obj.GetString("cellSize", "100 100"));
if (ShouldUpdateField("spacing"))
c.spacing = Vector2Ex.Parse(obj.GetString("spacing", "0 0"));
if (ShouldUpdateField("startCorner"))
c.startCorner = ParseEnum(obj.GetString("startCorner", "UpperLeft"), GridLayoutGroup.Corner.UpperLeft);
if (ShouldUpdateField("startAxis"))
c.startAxis = ParseEnum(obj.GetString("startAxis", "Horizontal"), GridLayoutGroup.Axis.Horizontal);
if (ShouldUpdateField("childAlignment"))
c.childAlignment = ParseEnum(obj.GetString("childAlignment", "UpperLeft"), TextAnchor.UpperLeft);
if (ShouldUpdateField("constraint"))
c.constraint = ParseEnum(obj.GetString("constraint", "Flexible"), GridLayoutGroup.Constraint.Flexible);
if (ShouldUpdateField("constraintCount"))
c.constraintCount = obj.GetInt("constraintCount", c.constraintCount);
ApplyPadding(c, obj, ShouldUpdateField);
break;
}
case "UnityEngine.UI.ContentSizeFitter":
{
var c = GetOrAddComponent<ContentSizeFitter>();
HandleEnableState(obj, c);
if (ShouldUpdateField("horizontalFit"))
c.horizontalFit = ParseEnum(obj.GetString("horizontalFit", "Unconstrained"), ContentSizeFitter.FitMode.Unconstrained);
if (ShouldUpdateField("verticalFit"))
c.verticalFit = ParseEnum(obj.GetString("verticalFit", "Unconstrained"), ContentSizeFitter.FitMode.Unconstrained);
break;
}
case "UnityEngine.UI.LayoutElement":
{
var c = GetOrAddComponent<LayoutElement>();
HandleEnableState(obj, c);
if (ShouldUpdateField("preferredWidth"))
c.preferredWidth = obj.GetFloat("preferredWidth", -1f);
if (ShouldUpdateField("preferredHeight"))
c.preferredHeight = obj.GetFloat("preferredHeight", -1f);
if (ShouldUpdateField("minWidth"))
c.minWidth = obj.GetFloat("minWidth", 0f);
if (ShouldUpdateField("minHeight"))
c.minHeight = obj.GetFloat("minHeight", 0f);
if (ShouldUpdateField("flexibleWidth"))
c.flexibleWidth = obj.GetFloat("flexibleWidth", 0f);
if (ShouldUpdateField("flexibleHeight"))
c.flexibleHeight = obj.GetFloat("flexibleHeight", 0f);
if (ShouldUpdateField("ignoreLayout"))
c.ignoreLayout = obj.GetBoolean("ignoreLayout", false);
break;
}
case "Draggable":
{
var drag = go.GetComponent<Draggable>();
if(!drag){
drag = go.AddComponent<Draggable>();
go.AddComponent<CanvasGroup>();
}
if( ShouldUpdateField("limitToParent"))
drag.limitToParent = obj.GetBoolean("limitToParent", false);
if( ShouldUpdateField("maxDistance"))
drag.maxDistance = obj.GetFloat("maxDistance", -1f);
if( ShouldUpdateField("allowSwapping"))
drag.allowSwapping = obj.GetBoolean("allowSwapping", false);
if( ShouldUpdateField("dropAnywhere"))
drag.dropAnywhere = obj.GetBoolean("dropAnywhere", true);
if( ShouldUpdateField("dragAlpha"))
drag.dragAlpha = obj.GetFloat("dragAlpha", 1f);
if( ShouldUpdateField("parentLimitIndex"))
drag.parentLimitIndex = obj.GetInt("parentLimitIndex", 1);
if( ShouldUpdateField("filter"))
drag.filter = obj.GetString("filter", null);
if( ShouldUpdateField("parentPadding"))
drag.parentPadding = Vector2Ex.Parse(obj.GetString("parentPadding", "0 0"));
if( ShouldUpdateField("anchorOffset"))
drag.anchorOffset = Vector2Ex.Parse(obj.GetString("anchorOffset", "0 0"));
if( ShouldUpdateField("keepOnTop"))
drag.keepOnTop = obj.GetBoolean("keepOnTop", false);
var preferredDefault = DraggablePositionSendType.NormalizedScreen;
// find a better default depending on specified settings
if(drag.maxDistance > 0f){
preferredDefault = DraggablePositionSendType.RelativeAnchor;
} else if(drag.limitToParent){
preferredDefault = DraggablePositionSendType.NormalizedParent;
}
if( ShouldUpdateField("positionRPC"))
drag.positionRPC = ParseEnum<DraggablePositionSendType>(obj.GetString("positionRPC", null), preferredDefault);
// some Update only fields to trigger certain functions
if(allowUpdate & obj.ContainsKey("moveToAnchor"))
drag.MoveToAnchor();
if(allowUpdate & obj.ContainsKey("rebuildAnchor"))
drag.RebuildAnchor();
drag.Init();
HandleEnableState(obj, drag);
break;
}
case "Slot":
{
var slot = GetOrAddComponent<DraggableSlot>();
if(ShouldUpdateField("filter"))
slot.filter = obj.GetString("filter", null);
slot.Init();
HandleEnableState(obj, slot);
break;
}
case "NeedsKeyboard":
{
var c = GetOrAddComponent<NeedsKeyboard>();
HandleEnableState( obj, c );
break;
}
case "UnityEngine.UI.ScrollView":
{
var scrollRect = GetOrAddComponent<ScrollRect>();
HandleEnableState(obj, scrollRect);
if(!ScrollViews.Contains(go.name)) ScrollViews.Add(go.name);
// Adding a Canvas allows unity to isolate any changes inside the scrollrect, improving performance as the outer canvas wont need an update on scroll
var canvas = go.GetComponent<Canvas>();
if(!canvas){
canvas = go.AddComponent<Canvas>();
go.AddComponent<GraphicRaycaster>();
}
// already present if its being updated
if(!allowUpdate){
// add viewport as child component, dont register it as a ui panel though. this allows scrollbars to resize the viewport if autoHide is set to true
var viewportGO = new GameObject(go.name + "___Viewport");
var viewportRT = viewportGO.AddComponent<RectTransform>();
FitParent(viewportRT);
// this is required if the scrollbar shrinks the viewport, it ensures the viewport is pushed to the top left corner
// the default pivot would center it, meaning the scrollbar would partially cover it instead of being beside it
viewportRT.pivot = new Vector2(0f, 1f);
viewportRT.SetParent(go.transform, false);
var mask = viewportGO.AddComponent<RectMask2D>();
scrollRect.viewport = viewportRT;
// if(obj.ContainsKey("maskSoftness"))
// mask.softness = Vector2Int.RoundToInt(Vector2Ex.Parse( obj.GetString( "maskSoftness", "0.0 0.0" )));
// create & register content panel
var childGO = new GameObject(go.name + "___Content");
childGO.transform.SetParent(viewportGO.transform, false);
RegisterUi(childGO);
scrollRect.content = childGO.AddComponent<RectTransform>();
}
// initialize from the json object
if(ShouldUpdateField("contentTransform")){
var contentObj = obj.GetObject("contentTransform");
scrollRect.content.anchorMin = Vector2Ex.Parse( contentObj.GetString( "anchormin", "0.0 0.0" ) );
scrollRect.content.anchorMax = Vector2Ex.Parse( contentObj.GetString( "anchormax", "1.0 1.0" ) );
scrollRect.content.offsetMin = Vector2Ex.Parse( contentObj.GetString( "offsetmin", "0.0 0.0" ) );
// we dont have to apply the shoddy offsetmax default here because no existing implementations rely on it
scrollRect.content.offsetMax = Vector2Ex.Parse( contentObj.GetString( "offsetmax", "0.0 0.0" ) );
scrollRect.content.pivot = Vector2Ex.Parse( contentObj.GetString( "pivot", "0.5 0.5" ) );
}
if(ShouldUpdateField("horizontal"))
scrollRect.horizontal = obj.GetBoolean("horizontal", false);
if(ShouldUpdateField("vertical"))
scrollRect.vertical = obj.GetBoolean("vertical", false);
if(ShouldUpdateField("movementType"))
scrollRect.movementType = ParseEnum<ScrollRect.MovementType>(obj.GetString("movementType", "Clamped"), ScrollRect.MovementType.Clamped);
if(ShouldUpdateField("elasticity"))
scrollRect.elasticity = obj.GetFloat("elasticity", 0.1f);
if(ShouldUpdateField("inertia"))
scrollRect.inertia = obj.GetBoolean("inertia", false);
if(ShouldUpdateField("decelerationRate"))
scrollRect.decelerationRate = obj.GetFloat("decelerationRate", 0.135f);
if(ShouldUpdateField("scrollSensitivity"))
scrollRect.scrollSensitivity = obj.GetFloat("scrollSensitivity", 1f);
// add scrollbars if objects are present
GameObject barGO;
JSON.Object scrollObj;
bool invert;
bool hideUnlessNeeded;
Scrollbar scrollbar;
// dont need ShouldUpdateField here either
if(scrollRect.horizontal && obj.ContainsKey("horizontalScrollbar")){
barGO = new GameObject("Horizontal Scrollbar");
scrollObj = obj.GetObject("horizontalScrollbar");
invert = scrollObj.GetBoolean("invert", false);
hideUnlessNeeded = scrollObj.GetBoolean("autoHide", false);
scrollbar = barGO.AddComponent<Scrollbar>();
HandleEnableState(scrollObj, scrollbar);
barGO.transform.SetParent(go.transform, false);
scrollbar.direction = (invert ? Scrollbar.Direction.LeftToRight : Scrollbar.Direction.RightToLeft);
scrollRect.horizontalScrollbar = scrollbar;
if(hideUnlessNeeded)
scrollRect.horizontalScrollbarVisibility = ScrollRect.ScrollbarVisibility.AutoHideAndExpandViewport;
BuildScrollbar(scrollbar, scrollObj, false);
}
// dont need ShouldUpdateField here either
if(scrollRect.vertical && obj.ContainsKey("verticalScrollbar")){
barGO = new GameObject("Vertical Scrollbar");
scrollObj = obj.GetObject("verticalScrollbar");
invert = scrollObj.GetBoolean("invert", false);
hideUnlessNeeded = scrollObj.GetBoolean("autoHide", false);
scrollbar = barGO.AddComponent<Scrollbar>();
HandleEnableState(scrollObj, scrollbar);
barGO.transform.SetParent(go.transform, false);
scrollbar.direction = (invert ? Scrollbar.Direction.TopToBottom : Scrollbar.Direction.BottomToTop);
scrollRect.verticalScrollbar = scrollbar;
if(hideUnlessNeeded)
scrollRect.verticalScrollbarVisibility = ScrollRect.ScrollbarVisibility.AutoHideAndExpandViewport;
BuildScrollbar(scrollbar, scrollObj, true);
}
// Add ability to set scroll progress
if (ShouldUpdateField("horizontalNormalizedPosition"))
scrollRect.horizontalNormalizedPosition = obj.GetFloat("horizontalNormalizedPosition", 0f);
if (ShouldUpdateField("verticalNormalizedPosition"))
scrollRect.verticalNormalizedPosition = obj.GetFloat("verticalNormalizedPosition", 0f);
break;
}
}
}
private void AssignInputFieldPlaceholder(InputField input, string panelId)
{
// If clearing placeholder
if (string.IsNullOrEmpty(panelId))
{
input.placeholder = null;
return;
}
// Search for panel
var panel = FindPanel(panelId);
if (panel == null)
{
Debug.LogWarning($"[AddUI] Unable to find placeholder panel '{panelId}' for InputField '{input.name}'");
input.placeholder = null;
return;
}
// Get graphic component
var graphic = panel.GetComponent<Graphic>();
if (graphic == null)
{
Debug.LogWarning($"[AddUI] Unable to find Graphic component on placeholder panel '{panelId}' for InputField '{input.name}'");
input.placeholder = null;
return;
}
// Assign if it's all good
input.placeholder = graphic;
}
private void BuildScrollbar(Scrollbar scrollbar, JSON.Object obj, bool vertical){
// build the scrollbar handle
var handle = new GameObject("Scrollbar Handle");
var handleRT = handle.AddComponent<RectTransform>();
FitParent(handleRT);
handle.transform.SetParent(scrollbar.transform, false);//.SetParent(track.transform, false);
var handleImage = handle.AddComponent<Image>();
handleImage.sprite = FileSystem.Load<Sprite>( obj.GetString( "handleSprite", "assets/content/ui/ui.rounded.tga" ) );
handleImage.type = Image.Type.Sliced;
// target for color changes
scrollbar.image = handleImage;
scrollbar.handleRect = handleRT;
// style the scollbar
float size = obj.GetFloat("size", 20f);
var block = scrollbar.colors;
block.normalColor = ColorEx.Parse( obj.GetString( "handleColor", "0.15 0.15 0.15 1" ) ); // main color
block.highlightedColor = ColorEx.Parse( obj.GetString( "highlightColor", "0.17 0.17 0.17 1" ) ); // hover
block.pressedColor = ColorEx.Parse( obj.GetString( "pressedColor", "0.2 0.2 0.2 1" ) ); // press
block.selectedColor = block.pressedColor; // never really used, but can still show up sometimes
scrollbar.colors = block;
// style the background track
var image = scrollbar.gameObject.AddComponent<Image>();
image.sprite = FileSystem.Load<Sprite>( obj.GetString( "trackSprite", "assets/content/ui/ui.background.tile.psd" ) );
image.type = Image.Type.Sliced;
image.color = ColorEx.Parse( obj.GetString( "trackColor", "0.09 0.09 0.09 1" ) ); // background
// position the scrollbar
var rt = scrollbar.GetComponent<RectTransform>();
if(rt == null)
return;
if(vertical){
// positions it along the right side
rt.anchorMin = new Vector2(1f, 0f);
rt.anchorMax = new Vector2(1f, 1f);
rt.pivot = new Vector2(0f, 0.5f);
rt.offsetMin = new Vector2(-size, 0f);
rt.offsetMax = Vector2.zero;
} else {
// positions it along the bottom
rt.anchorMin = new Vector2(0f, 0f);
rt.anchorMax = new Vector2(1f, 0f);
rt.pivot = new Vector2(0.5f, 0f);
rt.offsetMin = new Vector2(0f, -size);
rt.offsetMax = Vector2.zero;
}
}
// sets the transform to a sensible default
private void FitParent(RectTransform transform){
transform.anchorMin = Vector2.zero;
transform.anchorMax = Vector2.one;
transform.offsetMin = Vector2.zero;
transform.offsetMax = Vector2.one; // to preserve the shoddy offsetmax default that alot of existing UIs rely on
}
private void ApplyPadding(LayoutGroup g, JSON.Object obj, Func<string, bool> ShouldUpdateField)
{
if (g == null || obj == null) return;
// 1) Shorthand "padding" field: "l t r b" (or a single "x" to apply to all sides)
if (ShouldUpdateField("padding") && obj.ContainsKey("padding"))
{
var raw = obj.GetString("padding", "0 0 0 0");
var parts = raw.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
int l = g.padding.left, t = g.padding.top, r = g.padding.right, b = g.padding.bottom;
if (parts.Length == 1)
{
if (int.TryParse(parts[0], out var v))
l = t = r = b = v;
}
else if (parts.Length >= 4)
{
int.TryParse(parts[0], out l);
int.TryParse(parts[1], out t);
int.TryParse(parts[2], out r);
int.TryParse(parts[3], out b);
}
g.padding.left = l;
g.padding.top = t;
g.padding.right = r;
g.padding.bottom = b;
}
}
private static T ParseEnum<T>(string value, T defaultValue)
where T : struct, System.Enum
{
if ( string.IsNullOrWhiteSpace( value ) ) return defaultValue;
return System.Enum.TryParse<T>( value, true, out var parsedValue ) ? parsedValue : defaultValue;
}
private void GraphicComponentCreated( UnityEngine.UI.Graphic c, JSON.Object obj )
{
if ( obj.ContainsKey( "fadeIn" ) )
{
c.canvasRenderer.SetAlpha( 0f );
c.CrossFadeAlpha( 1f, obj.GetFloat( "fadeIn", 0 ), true );
}
if (obj.ContainsKey("placeholderParentId"))
{
var panel = FindPanel(obj.GetString("placeholderParentId"));
if (panel != null && panel.TryGetComponent<InputField>( out var input))
{
input.placeholder = c;
}
}
}
private IEnumerator LoadTextureFromWWW( UnityEngine.UI.RawImage c, string p )
{
var www = new WWW( p.Trim() );
while ( !www.isDone )
{
yield return null;
}
if ( !string.IsNullOrEmpty( www.error ) )
{
Debug.Log( "Error downloading image: " + p + " (" + www.error + ")" );
www.Dispose();
yield break;
}
Texture2D texture = new Texture2D( 2, 2, TextureFormat.RGBA32, false );
www.LoadImageIntoTexture( texture );
if ( c == null )
{
Debug.Log( "Error downloading image: " + p + " (not an image)" );
www.Dispose();
yield break;
}
c.texture = texture;
www.Dispose();
}
private Font LoadFont(string fontName)
{
var font = FileSystem.Load<Font>( "Assets/Content/UI/Fonts/" + fontName );
if (font == null)
{