forked from jacksondunstan/UnityNativeScripting
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerateBindings.cs
More file actions
8710 lines (8259 loc) · 216 KB
/
Copy pathGenerateBindings.cs
File metadata and controls
8710 lines (8259 loc) · 216 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 System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using UnityEditor;
using UnityEngine;
namespace NativeScript
{
/// <summary>
/// Code generator that reads a JSON file and outputs C# and C++ code
/// bindings so C++ can call managed functions and MonoBehaviour "messages"
/// like Update() can call their C++ counterparts.
/// </summary>
/// <author>
/// Jackson Dunstan, 2017, http://JacksonDunstan.com
/// </author>
/// <license>
/// MIT
/// </license>
public static class GenerateBindings
{
// Disable unused field types. JsonUtility actually uses them, but it
// does so with reflection.
#pragma warning disable CS0649
[Serializable]
class JsonConstructor
{
public string[] ParamTypes;
public string[] Exceptions;
}
[Serializable]
class JsonGenericParams
{
public string[] Types;
public int MaxSimultaneous;
}
[Serializable]
class JsonMethod
{
public string Name;
public string[] ParamTypes;
public JsonGenericParams[] GenericParams;
public bool IsReadOnly;
public string[] Exceptions;
}
[Serializable]
class JsonPropertyGet
{
public bool IsReadOnly = true;
public string[] ParamTypes;
public string[] Exceptions;
}
[Serializable]
class JsonPropertySet
{
public bool IsReadOnly;
public string[] ParamTypes;
public string[] Exceptions;
}
[Serializable]
class JsonProperty
{
public string Name;
public JsonPropertyGet Get;
public JsonPropertySet Set;
}
[Serializable]
class JsonType
{
public string Name;
public JsonConstructor[] Constructors;
public JsonMethod[] Methods;
public JsonProperty[] Properties;
public string[] Fields;
public JsonGenericParams[] GenericParams;
public int MaxSimultaneous;
}
[Serializable]
class JsonMonoBehaviour
{
public string Name;
public string[] Messages;
}
[Serializable]
class JsonArray
{
public string Type;
public int[] Ranks;
}
[Serializable]
class JsonDelegate
{
public string Type;
public JsonGenericParams[] GenericParams;
public int MaxSimultaneous;
}
[Serializable]
class JsonDocument
{
public string[] Assemblies;
public JsonType[] Types;
public JsonMonoBehaviour[] MonoBehaviours;
public JsonArray[] Arrays;
public JsonDelegate[] Delegates;
}
const int InitialStringBuilderCapacity = 1024 * 100;
class StringBuilders
{
public StringBuilder CsharpInitParams =
new StringBuilder(InitialStringBuilderCapacity);
public StringBuilder CsharpDelegateTypes =
new StringBuilder(InitialStringBuilderCapacity);
public StringBuilder CsharpStructStoreInitCalls =
new StringBuilder(InitialStringBuilderCapacity);
public StringBuilder CsharpInitCall =
new StringBuilder(InitialStringBuilderCapacity);
public StringBuilder CsharpFunctions =
new StringBuilder(InitialStringBuilderCapacity);
public StringBuilder CsharpMonoBehaviours =
new StringBuilder(InitialStringBuilderCapacity);
public StringBuilder CsharpDelegates =
new StringBuilder(InitialStringBuilderCapacity);
public StringBuilder CsharpImports =
new StringBuilder(InitialStringBuilderCapacity);
public StringBuilder CsharpGetDelegateCalls =
new StringBuilder(InitialStringBuilderCapacity);
public StringBuilder CppFunctionPointers =
new StringBuilder(InitialStringBuilderCapacity);
public StringBuilder CppTypeDeclarations =
new StringBuilder(InitialStringBuilderCapacity);
public StringBuilder CppTypeDefinitions =
new StringBuilder(InitialStringBuilderCapacity);
public StringBuilder CppMethodDefinitions =
new StringBuilder(InitialStringBuilderCapacity);
public StringBuilder CppInitParams =
new StringBuilder(InitialStringBuilderCapacity);
public StringBuilder CppInitBody =
new StringBuilder(InitialStringBuilderCapacity);
public StringBuilder CppMonoBehaviourMessages =
new StringBuilder(InitialStringBuilderCapacity);
public StringBuilder CppGlobalStateAndFunctions =
new StringBuilder(InitialStringBuilderCapacity);
public StringBuilder TempStrBuilder =
new StringBuilder(InitialStringBuilderCapacity);
}
class ParameterInfo
{
public string Name;
public Type ParameterType;
public Type DereferencedParameterType;
public bool IsOut;
public bool IsRef;
public TypeKind Kind;
public bool IsVirtual;
}
enum TypeKind
{
// No type (e.g. a global function)
None,
// An instance of any class
Class,
// A struct that must be managed. This includes types like
// RaycastHit which have class fields (Transform) and types with no
// C++ equivalent like decimal.
ManagedStruct,
// A struct that can be copied between C#/C++. These are types like
// Vector3 with only non-class fields and a C++ equivalent can be
// generated.
FullStruct,
// Any enum
Enum,
// Any primitive (e.g. int) except pointers
Primitive,
// A pointer to any type, either X*, IntPtr, or UIntPtr
Pointer,
// The decimal type
Decimal
}
// Compares by field declaration order
// This uses MetadataToken, which isn't guaranteed to match field
// declaration order. It just happens to on Mono and .NET.
class FieldOrderComparer : IComparer
{
int IComparer.Compare(object x, object y)
{
FieldInfo xField = (FieldInfo)x;
FieldInfo yField = (FieldInfo)y;
return xField.MetadataToken < yField.MetadataToken
? -1
: xField.MetadataToken > yField.MetadataToken
? 1
: 0;
}
}
class MessageInfo
{
public string Name;
public Type[] ParameterTypes;
public bool Selected;
public MessageInfo(
string name,
params Type[] parameterTypes)
{
Name = name;
ParameterTypes = parameterTypes;
}
}
static readonly MessageInfo[] messageInfos = new[] {
new MessageInfo("Awake"),
new MessageInfo("FixedUpdate"),
new MessageInfo("LateUpdate"),
new MessageInfo("OnAnimatorIK", typeof(int)),
new MessageInfo("OnAnimatorMove"),
new MessageInfo("OnApplicationFocus", typeof(bool)),
new MessageInfo("OnApplicationPause", typeof(bool)),
new MessageInfo("OnApplicationQuit"),
new MessageInfo("OnAudioFilterRead", typeof(float[]), typeof(int)),
new MessageInfo("OnBecameInvisible"),
new MessageInfo("OnBecameVisible"),
new MessageInfo("OnCollisionEnter", typeof(Collision)),
new MessageInfo("OnCollisionEnter2D", typeof(Collision2D)),
new MessageInfo("OnCollisionExit", typeof(Collision)),
new MessageInfo("OnCollisionExit2D", typeof(Collision2D)),
new MessageInfo("OnCollisionStay", typeof(Collision)),
new MessageInfo("OnCollisionStay2D", typeof(Collision2D)),
new MessageInfo("OnConnectedToServer"),
new MessageInfo("OnControllerColliderHit", typeof(ControllerColliderHit)),
new MessageInfo("OnDestroy"),
new MessageInfo("OnDisable"),
new MessageInfo("OnDisconnectedFromServer", typeof(NetworkDisconnection)),
new MessageInfo("OnDrawGizmos"),
new MessageInfo("OnDrawGizmosSelected"),
new MessageInfo("OnEnable"),
new MessageInfo("OnFailedToConnect", typeof(NetworkConnectionError)),
new MessageInfo("OnFailedToConnectToMasterServer", typeof(NetworkConnectionError)),
new MessageInfo("OnGUI"),
new MessageInfo("OnJointBreak", typeof(float)),
new MessageInfo("OnJointBreak2D", typeof(Joint2D)),
new MessageInfo("OnMasterServerEvent", typeof(MasterServerEvent)),
new MessageInfo("OnMouseDown"),
new MessageInfo("OnMouseDrag"),
new MessageInfo("OnMouseEnter"),
new MessageInfo("OnMouseExit"),
new MessageInfo("OnMouseOver"),
new MessageInfo("OnMouseUp"),
new MessageInfo("OnMouseUpAsButton"),
new MessageInfo("OnNetworkInstantiate", typeof(NetworkMessageInfo)),
new MessageInfo("OnParticleCollision", typeof(GameObject)),
new MessageInfo("OnParticleTrigger"),
new MessageInfo("OnPlayerConnected", typeof(NetworkPlayer)),
new MessageInfo("OnPlayerDisconnected", typeof(NetworkPlayer)),
new MessageInfo("OnPostRender"),
new MessageInfo("OnPreCull"),
new MessageInfo("OnPreRender"),
new MessageInfo("OnRenderImage", typeof(RenderTexture), typeof(RenderTexture)),
new MessageInfo("OnRenderObject"),
new MessageInfo("OnSerializeNetworkView", typeof(BitStream), typeof(NetworkMessageInfo)),
new MessageInfo("OnServerInitialized"),
new MessageInfo("OnTransformChildrenChanged"),
new MessageInfo("OnTransformParentChanged"),
new MessageInfo("OnTriggerEnter", typeof(Collider)),
new MessageInfo("OnTriggerEnter2D", typeof(Collider2D)),
new MessageInfo("OnTriggerExit", typeof(Collider)),
new MessageInfo("OnTriggerExit2D", typeof(Collider2D)),
new MessageInfo("OnTriggerStay", typeof(Collider)),
new MessageInfo("OnTriggerStay2D", typeof(Collider2D)),
new MessageInfo("OnValidate"),
new MessageInfo("OnWillRenderObject"),
new MessageInfo("Reset"),
new MessageInfo("Start"),
new MessageInfo("Update"),
};
const string PostCompileWorkPref = "NativeScriptGenerateBindingsPostCompileWork";
const string DryRunPref = "NativeScriptGenerateBindingsDryRun";
static readonly string DotNetDllsDirPath = new FileInfo(
new Uri(typeof(string).Assembly.CodeBase).LocalPath
).DirectoryName;
static readonly string UnityDllsDirPath = new FileInfo(
new Uri(typeof(GameObject).Assembly.CodeBase).LocalPath
).DirectoryName;
static readonly string AssetsDirPath = Application.dataPath;
static readonly string ProjectDirPath =
new DirectoryInfo(AssetsDirPath)
.Parent
.FullName;
static readonly string CppDirPath =
Path.Combine(
Path.Combine(
ProjectDirPath,
"CppSource"),
"NativeScript");
static readonly string CsharpPath = Path.Combine(
AssetsDirPath,
Path.Combine(
"NativeScript",
"Bindings.cs"));
static readonly string CppHeaderPath = Path.Combine(
CppDirPath,
"Bindings.h");
static readonly string CppSourcePath = Path.Combine(
CppDirPath,
"Bindings.cpp");
static readonly FieldOrderComparer DefaultFieldOrderComparer
= new FieldOrderComparer();
// Restore unused field types
#pragma warning restore CS0649
[MenuItem("NativeScript/Generate Bindings #%g")]
public static void Generate()
{
Generate(false);
}
[MenuItem("NativeScript/Generate Bindings (dry run) #%&g")]
public static void GenerateDryRun()
{
Generate(true);
}
static void Generate(bool dryRun)
{
EditorPrefs.DeleteKey(PostCompileWorkPref);
EditorPrefs.SetBool(DryRunPref, dryRun);
if (dryRun)
{
DoPostCompileWork(true);
}
else
{
JsonDocument doc = LoadJson();
Assembly[] assemblies = GetAssemblies(doc.Assemblies);
// Determine whether we need to generate stubs
// We can skip this step if we've already generated all the
// required MonoBehaviour classes and their messages
bool needStubs = false;
foreach (JsonMonoBehaviour monoBehaviour in doc.MonoBehaviours)
{
// Check if the MonoBehaviour type is already generated
Type type = TryGetType(
monoBehaviour.Name,
assemblies);
if (type == null)
{
needStubs = true;
break;
}
// Check if all the messages are already generated
foreach (string message in monoBehaviour.Messages)
{
MethodInfo methodInfo = type.GetMethod(message);
if (methodInfo == null)
{
needStubs = true;
goto determinedNeedStubs;
}
}
}
determinedNeedStubs:;
if (needStubs)
{
// We'll need to be able to get these via reflection later
StringBuilder csharpMonoBehaviours = new StringBuilder(
InitialStringBuilderCapacity);
string timestamp = DateTime.Now.ToLongTimeString();
AppendStubMonoBehaviours(
doc.MonoBehaviours,
timestamp,
csharpMonoBehaviours);
// Inject
string csharpContents = File.ReadAllText(CsharpPath);
csharpContents = InjectIntoString(
csharpContents,
"/*BEGIN MONOBEHAVIOURS*/\n",
"\n/*END MONOBEHAVIOURS*/",
csharpMonoBehaviours.ToString());
File.WriteAllText(CsharpPath, csharpContents);
// Compile and continue after scripts are refreshed
Debug.Log("Waiting for compile...");
AssetDatabase.Refresh();
EditorPrefs.SetBool(PostCompileWorkPref, true);
}
else
{
DoPostCompileWork(true);
}
}
}
static void AppendStubMonoBehaviours(
JsonMonoBehaviour[] monoBehaviours,
string timestamp,
StringBuilder output)
{
if (monoBehaviours != null)
{
foreach (JsonMonoBehaviour jsonMonoBehaviour in monoBehaviours)
{
// Split namespace from name
string fullName = jsonMonoBehaviour.Name;
string monoBehaviourName;
string monoBehaviourNamespace;
int index = fullName.LastIndexOf('.');
if (index >= 0)
{
monoBehaviourNamespace = fullName.Substring(
0,
index);
monoBehaviourName = fullName.Substring(
index + 1);
}
else
{
monoBehaviourName = fullName;
monoBehaviourNamespace = string.Empty;
}
int indent = AppendNamespaceBeginning(
monoBehaviourNamespace,
output);
AppendIndent(indent, output);
output.Append("public class ");
output.Append(monoBehaviourName);
output.Append(" : UnityEngine.MonoBehaviour\n");
AppendIndent(indent, output);
output.Append("{\n");
AppendIndent(indent + 1, output);
output.Append("// Stub version. GenerateBindings is still in progress. ");
output.Append(timestamp);
output.Append('\n');
AppendIndent(indent, output);
output.Append("}\n");
AppendNamespaceEnding(indent, output);
}
}
}
[UnityEditor.Callbacks.DidReloadScripts]
static void OnScriptsReloaded()
{
// Scripts get reloaded for many reasons, not just our work
// Check if this reload is due to us refreshing the asset DB
bool doWork = EditorPrefs.GetBool(PostCompileWorkPref, false);
EditorPrefs.DeleteKey(PostCompileWorkPref);
if (doWork)
{
DoPostCompileWork(false);
}
}
static void DoPostCompileWork(bool canRefreshAssetDb)
{
bool dryRun = EditorPrefs.GetBool(DryRunPref);
EditorPrefs.DeleteKey(DryRunPref);
JsonDocument doc = LoadJson();
Assembly[] assemblies = GetAssemblies(doc.Assemblies);
StringBuilders builders = new StringBuilders();
// Generate types
foreach (JsonType jsonType in doc.Types)
{
AppendType(
jsonType,
assemblies,
builders);
}
// Generate MonoBehaviours
if (doc.MonoBehaviours != null)
{
foreach (JsonMonoBehaviour monoBehaviour in doc.MonoBehaviours)
{
AppendMonoBehaviour(
monoBehaviour,
assemblies,
builders);
}
}
// Generate arrays
if (doc.Arrays != null)
{
foreach (JsonArray array in doc.Arrays)
{
AppendArray(
array,
assemblies,
builders);
}
}
if (doc.Delegates != null)
{
foreach (JsonDelegate del in doc.Delegates)
{
AppendDelegate(
del,
assemblies,
builders);
}
}
// Generate exception setters
AppendExceptions(
doc,
assemblies,
builders);
RemoveTrailingChars(builders);
if (dryRun)
{
LogStringBuilders(builders);
}
else
{
InjectBuilders(builders);
if (canRefreshAssetDb)
{
AssetDatabase.Refresh();
Debug.Log("Done generating bindings.");
}
else
{
Debug.LogWarning(
"Can't auto-refresh due to a bug in Unity. " +
"Please manually refresh assets with " +
"Assets -> Refresh to finish generating bindings");
}
}
}
static JsonDocument LoadJson()
{
string jsonPath = Path.Combine(
Application.dataPath,
NativeScriptConstants.ExposedTypesJsonPath);
string json = File.ReadAllText(jsonPath);
return JsonUtility.FromJson<JsonDocument>(json);
}
static Assembly[] GetAssemblies(string[] assemblyNames)
{
const int numDefaultAssemblies =
#if UNITY_2017_2_OR_NEWER
43;
#else
7;
#endif
int numAssemblies;
Assembly[] assemblies;
if (assemblyNames == null)
{
numAssemblies = numDefaultAssemblies;
assemblies = new Assembly[numAssemblies];
}
else
{
numAssemblies = numDefaultAssemblies + assemblyNames.Length;
assemblies = new Assembly[numAssemblies];
for (int i = 0; i < assemblyNames.Length; ++i)
{
string path = assemblyNames[i]
.Replace("UNITY_PROJECT", ProjectDirPath)
.Replace("UNITY_ASSETS", AssetsDirPath)
.Replace("DOTNET_DLLS", DotNetDllsDirPath)
.Replace("UNITY_DLLS", UnityDllsDirPath);
Assembly assembly = Assembly.LoadFrom(path);
assemblies[numDefaultAssemblies + i] = assembly;
}
}
assemblies[0] = typeof(string).Assembly; // .NET: mscorlib
assemblies[1] = typeof(Uri).Assembly; // .NET: System
assemblies[2] = typeof(Action).Assembly; // .NET: System.Core
assemblies[3] = typeof(Vector3).Assembly; // UnityEngine (core module for 2017.2+)
assemblies[4] = typeof(Bindings).Assembly; // Runtime scripts
assemblies[5] = typeof(GenerateBindings).Assembly; // Editor scripts
assemblies[6] = typeof(EditorPrefs).Assembly; // UnityEditor
#if UNITY_2017_2_OR_NEWER
assemblies[7] = typeof(UnityEngine.Accessibility.VisionUtility).Assembly; // Unity accessibility module
assemblies[8] = typeof(UnityEngine.AI.NavMesh).Assembly; // Unity AI module
assemblies[9] = typeof(UnityEngine.Animations.AnimationClipPlayable).Assembly; // Unity animation module
assemblies[10] = typeof(UnityEngine.XR.ARRenderMode).Assembly; // Unity AR module
assemblies[11] = typeof(UnityEngine.AudioSettings).Assembly; // Unity audio module
assemblies[12] = typeof(UnityEngine.Cloth).Assembly; // Unity cloth module
assemblies[13] = typeof(UnityEngine.ClusterInput).Assembly; // Unity cluster input module
assemblies[14] = typeof(UnityEngine.ClusterNetwork).Assembly; // Unity custer renderer module
assemblies[15] = typeof(UnityEngine.CrashReportHandler.CrashReportHandler).Assembly; // Unity crash reporting module
assemblies[16] = typeof(UnityEngine.Playables.PlayableDirector).Assembly; // Unity director module
assemblies[17] = typeof(UnityEngine.SocialPlatforms.IAchievement).Assembly; // Unity game center module
assemblies[18] = typeof(UnityEngine.ImageConversion).Assembly; // Unity image conversion module
assemblies[19] = typeof(UnityEngine.GUI).Assembly; // Unity IMGUI module
assemblies[20] = typeof(UnityEngine.JsonUtility).Assembly; // Unity JSON serialize module
assemblies[21] = typeof(UnityEngine.ParticleSystem).Assembly; // Unity particle system module
assemblies[22] = typeof(UnityEngine.Analytics.PerformanceReporting).Assembly; // Unity performance reporting module
assemblies[23] = typeof(UnityEngine.Physics2D).Assembly; // Unity physics 2D module
assemblies[24] = typeof(UnityEngine.Physics).Assembly; // Unity physics module
assemblies[25] = typeof(UnityEngine.ScreenCapture).Assembly; // Unity screen capture module
assemblies[26] = typeof(UnityEngine.Terrain).Assembly; // Unity terrain module
assemblies[27] = typeof(UnityEngine.TerrainCollider).Assembly; // Unity terrain physics module
assemblies[28] = typeof(UnityEngine.Font).Assembly; // Unity text rendering module
assemblies[29] = typeof(UnityEngine.Tilemaps.Tile).Assembly; // Unity tilemap module
assemblies[30] = typeof(UnityEngine.Experimental.UIElements.Button).Assembly; // Unity UI elements module
assemblies[31] = typeof(UnityEngine.Canvas).Assembly; // Unity UI module
assemblies[32] = typeof(UnityEngine.Networking.NetworkTransport).Assembly; // Unity cloth module
assemblies[33] = typeof(UnityEngine.Analytics.Analytics).Assembly; // Unity analytics module
assemblies[34] = typeof(UnityEngine.RemoteSettings).Assembly; // Unity Unity connect module
assemblies[35] = typeof(UnityEngine.Networking.DownloadHandlerAudioClip).Assembly; // Unity web request audio module
assemblies[36] = typeof(UnityEngine.WWWForm).Assembly; // Unity web request module
assemblies[37] = typeof(UnityEngine.Networking.DownloadHandlerTexture).Assembly; // Unity web request texture module
assemblies[38] = typeof(UnityEngine.WWW).Assembly; // Unity web request WWW module
assemblies[39] = typeof(UnityEngine.WheelCollider).Assembly; // Unity vehicles module
assemblies[40] = typeof(UnityEngine.Video.VideoClip).Assembly; // Unity video module
assemblies[41] = typeof(UnityEngine.XR.InputTracking).Assembly; // Unity VR module
assemblies[42] = typeof(UnityEngine.WindZone).Assembly; // Unity wind module
#endif
return assemblies;
}
static Type[] GetTypes(
string[] typeNames,
Assembly[] assemblies)
{
if (typeNames == null)
{
return new Type[0];
}
Type[] types = new Type[typeNames.Length];
for (int i = 0; i < typeNames.Length; ++i)
{
types[i] = GetType(typeNames[i], assemblies);
}
return types;
}
static Type GetType(
string typeName,
Assembly[] assemblies)
{
Type type = TryGetType(
typeName,
assemblies);
if (type != null)
{
return type;
}
// Not finding a type is a fatal error
StringBuilder errorBuilder = new StringBuilder(1024);
errorBuilder.Append("Couldn't find type \"");
errorBuilder.Append(typeName);
errorBuilder.Append('"');
throw new Exception(errorBuilder.ToString());
}
static Type TryGetType(
string typeName,
Assembly[] assemblies)
{
// Search all assemblies for the type
foreach (Assembly assembly in assemblies)
{
Type type = assembly.GetType(typeName);
if (type != null)
{
return type;
}
}
return null;
}
static TypeKind GetTypeKind(Type type)
{
if (type == typeof(void))
{
return TypeKind.None;
}
if (type.IsPointer)
{
return TypeKind.Pointer;
}
if (type.IsEnum)
{
return TypeKind.Enum;
}
if (type.IsPrimitive)
{
return TypeKind.Primitive;
}
if (!type.IsValueType)
{
return TypeKind.Class;
}
// Decimal (currently) can't be represented on the C++ side, so
// don't count it as a full struct
if (type != typeof(decimal) && IsFullValueType(type))
{
return TypeKind.FullStruct;
}
return TypeKind.ManagedStruct;
}
static ParameterInfo[] GetConstructorParameters(
Type type,
string[] paramTypeNames)
{
foreach (ConstructorInfo ctor in type.GetConstructors())
{
System.Reflection.ParameterInfo[] reflectionParams
= ctor.GetParameters();
if (CheckParametersMatch(
paramTypeNames,
reflectionParams))
{
return ConvertParameters(reflectionParams);
}
}
// Throw an exception so the user knows what to fix in the JSON
StringBuilder errorBuilder = new StringBuilder(1024);
errorBuilder.Append("Constructor \"");
AppendCsharpTypeName(type, errorBuilder);
errorBuilder.Append('(');
for (int i = 0; i < paramTypeNames.Length; ++i)
{
errorBuilder.Append(paramTypeNames[i]);
if (i != paramTypeNames.Length - 1)
{
errorBuilder.Append(", ");
}
}
errorBuilder.Append(")\" not found");
throw new Exception(errorBuilder.ToString());
}
static MethodInfo GetMethod(
Type type,
MethodInfo[] methods,
string methodName,
string[] paramTypeNames)
{
foreach (MethodInfo method in methods)
{
// Name must match
if (method.Name != methodName)
{
continue;
}
// All parameters must match
if (CheckParametersMatch(
paramTypeNames,
method.GetParameters()))
{
return method;
}
}
// Throw an exception so the user knows what to fix in the JSON
StringBuilder errorBuilder = new StringBuilder(1024);
errorBuilder.Append("Method \"");
AppendCsharpTypeName(type, errorBuilder);
errorBuilder.Append('.');
errorBuilder.Append(methodName);
errorBuilder.Append('(');
for (int i = 0; i < paramTypeNames.Length; ++i)
{
errorBuilder.Append(paramTypeNames[i]);
if (i != paramTypeNames.Length - 1)
{
errorBuilder.Append(", ");
}
}
errorBuilder.Append(")\" not found");
throw new Exception(errorBuilder.ToString());
}
static bool CheckParametersMatch(
string[] paramTypeNames,
System.Reflection.ParameterInfo[] reflectionParams)
{
// Length must match
if (reflectionParams.Length != paramTypeNames.Length)
{
return false;
}
// All params must match
for (int i = 0; i < reflectionParams.Length; ++i)
{
Type type = DereferenceParameterType(
reflectionParams[i]);
string typeName = paramTypeNames[i];
if (!CheckTypeNameMatches(typeName, type))
{
return false;
}
}
return true;
}
static bool CheckTypeNameMatches(
string typeName,
Type type)
{
// No namespace. Only name must match.
if (string.IsNullOrEmpty(type.Namespace))
{
if (type.Name != typeName)
{
return false;
}
}
// Must be: Namespace.Name
else
{
// Length must be the same as (namespace + '.' + name)
if (
typeName.Length !=
type.Namespace.Length
+ 1
+ type.Name.Length)
{
return false;
}
// Must start with namespace
if (!typeName.StartsWith(type.Namespace))
{
return false;
}
// Namespace must be followed by '.'
if (typeName[type.Namespace.Length] != '.')
{
return false;
}
// Must end with name
if (!typeName.EndsWith(type.Name))
{
return false;
}
}
return true;
}
static void AppendParameterTypeNames(
ParameterInfo[] parameters,
StringBuilder output)
{
for (int i = 0, len = parameters.Length; i < len; ++i)
{
Type type = parameters[i].DereferencedParameterType;
AppendNamespace(type.Namespace, string.Empty, output);
AppendTypeNameWithoutSuffixes(
type.Name,
output);
if (i != len - 1)
{
output.Append('_');
}
}
}
static void AppendTypeNames(
Type[] typeParams,
StringBuilder output)
{
if (typeParams != null)
{
for (int i = 0, len = typeParams.Length; i < len; ++i)
{
Type curType = typeParams[i];
AppendNamespace(
curType.Namespace,
string.Empty,
output);
AppendTypeNameWithoutSuffixes(
curType.Name,
output);
if (i != len - 1)
{
output.Append('_');
}
}
}
}
static void AppendNamespace(
string namespaceName,
string separator,
StringBuilder output)
{
int startIndex = 0;
if (!string.IsNullOrEmpty(namespaceName))
{
do
{
int separatorIndex = namespaceName.IndexOf(
'.',
startIndex);
if (separatorIndex < 0)
{
separatorIndex = namespaceName.IndexOf(
'+',
startIndex);
if (separatorIndex < 0)
{
break;
}
break;
}
output.Append(
namespaceName,
startIndex,
separatorIndex - startIndex);
output.Append(separator);
startIndex = separatorIndex + 1;
}
while (true);
output.Append(
namespaceName,
startIndex,
namespaceName.Length - startIndex);
}
}
static ParameterInfo[] ConvertParameters(
System.Reflection.ParameterInfo[] reflectionParameters)
{
int num = reflectionParameters.Length;
ParameterInfo[] parameters = new ParameterInfo[num];
for (int i = 0; i < num; ++i)
{
var reflectionInfo = reflectionParameters[i];
ParameterInfo info = new ParameterInfo();
info.Name = reflectionInfo.Name;
info.ParameterType = reflectionInfo.ParameterType;
info.IsOut = reflectionInfo.IsOut;
info.IsRef = !info.IsOut && info.ParameterType.IsByRef;
info.DereferencedParameterType = DereferenceParameterType(
reflectionInfo);
info.Kind = GetTypeKind(
info.DereferencedParameterType);
parameters[i] = info;
}
return parameters;
}
static Type DereferenceParameterType(