summaryrefslogtreecommitdiff
path: root/Runtime/Export/Networking.txt
blob: 87791221ebc7688a594908332d041a64b0aba86f (plain)
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
C++RAW

#include "UnityPrefix.h"
#include "Configuration/UnityConfigure.h"
#include "Runtime/Math/Quaternion.h"
#include "Runtime/Utilities/Utility.h"
#include "Runtime/Network/NetworkManager.h"
#include "Runtime/Network/NetworkUtility.h"
#include "Runtime/Network/BitStreamPacker.h"
#include "Runtime/Network/MasterServerInterface.h"
#include "Runtime/Mono/MonoBehaviour.h"
#include "Runtime/Scripting/Scripting.h"

CSRAW

#if ENABLE_NETWORK

using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using UnityEngineInternal;

namespace UnityEngine
{

// Option for who will receive an [[RPC]], used by NetworkView.RPC.
CONDITIONAL ENABLE_NETWORK
ENUM RPCMode
	// Sends to the server only
	Server = 0,

	// Sends to everyone except the sender
	Others = 1,

	// Sends to everyone except the sender and adds to the buffer
	OthersBuffered = 5,

	// Sends to everyone
	All = 2,

	// Sends to everyone and adds to the buffer
	AllBuffered = 6
END

// The various test results the connection tester may return with.
CONDITIONAL ENABLE_NETWORK
ENUM ConnectionTesterStatus
	// Some unknown error occurred.
	Error = -2,
	// Test result undetermined, still in progress.
	Undetermined = -1,
	OBSOLETE warning No longer returned, use newer connection tester enums instead.
	PrivateIPNoNATPunchthrough = 0,
	OBSOLETE warning No longer returned, use newer connection tester enums instead.
	PrivateIPHasNATPunchThrough = 1,
	// Public IP address detected and game listen port is accessible to the internet.
	PublicIPIsConnectable = 2,
	// Public IP address detected but the port is not connectable from the internet.
	PublicIPPortBlocked = 3,
	// Public IP address detected but server is not initialized and no port is listening.
	PublicIPNoServerStarted = 4,
	// Port-restricted NAT type, can do NAT punchthrough to everyone except symmetric.
	LimitedNATPunchthroughPortRestricted = 5,
	// Symmetric NAT type, cannot do NAT punchthrough to other symmetric types nor port restricted type.
	LimitedNATPunchthroughSymmetric = 6,
	// Full cone type, NAT punchthrough fully supported.
	NATpunchthroughFullCone = 7,
	// Address-restricted cone type, NAT punchthrough fully supported.
	NATpunchthroughAddressRestrictedCone = 8
END

// Possible status messages returned by Network.Connect and in [[MonoBehaviour.OnFailedToConnect|OnFailedToConnect]]
CONDITIONAL ENABLE_NETWORK
ENUM NetworkConnectionError
	// No error occurred.
	NoError = 0,

	// We presented an RSA public key which does not match what the system we connected to is using.
	RSAPublicKeyMismatch = 21,

	// The server is using a password and has refused our connection because we did not set the correct password.
	InvalidPassword = 23,

	// Connection attempt failed, possibly because of internal connectivity problems.
	ConnectionFailed = 15,

	// The server is at full capacity, failed to connect.
	TooManyConnectedPlayers = 18,

	// We are banned from the system we attempted to connect to (likely temporarily).
	ConnectionBanned = 22,

	// We are already connected to this particular server (can happen after fast disconnect/reconnect).
	AlreadyConnectedToServer = 16,

	// Cannot connect to two servers at once. Close the connection before connecting again.
	AlreadyConnectedToAnotherServer = -1,

	// Internal error while attempting to initialize network interface. Socket possibly already in use.
	CreateSocketOrThreadFailure = -2,

	// Incorrect parameters given to Connect function.
	IncorrectParameters = -3,

	// No host target given in Connect.
	EmptyConnectTarget = -4,

	// Client could not connect internally to same network NAT enabled server.
	InternalDirectConnectFailed = -5,

	// The NAT target we are trying to connect to is not connected to the facilitator server.
	NATTargetNotConnected = 69,

	// Connection lost while attempting to connect to NAT target.
	NATTargetConnectionLost = 71,

	// NAT punchthrough attempt has failed. The cause could be a too restrictive NAT implementation on either endpoints.
	NATPunchthroughFailed = 73
END

// The reason a disconnect event occured, like in [[MonoBehaviour.OnDisconnectedFromServer|OnDisconnectedFromServer]].
CONDITIONAL ENABLE_NETWORK
ENUM NetworkDisconnection
	// The connection to the system has been lost, no reliable packets could be delivered.
	LostConnection = 20,

	// The connection to the system has been closed.
	Disconnected = 19
END

// Describes status messages from the master server as returned in [[MonoBehaviour.OnMasterServerEvent|OnMasterServerEvent]].
CONDITIONAL ENABLE_NETWORK
ENUM MasterServerEvent
	// Registration failed because an empty game name was given.
	RegistrationFailedGameName = 0,

	// Registration failed because an empty game type was given.
	RegistrationFailedGameType = 1,

	// Registration failed because no server is running.
	RegistrationFailedNoServer = 2,

	// Registration to master server succeeded, received confirmation.
	RegistrationSucceeded = 3,

	// Received a host list from the master server.
	HostListReceived = 4
END

// Different types of synchronization for the [[NetworkView]] component.
CONDITIONAL ENABLE_NETWORK
ENUM NetworkStateSynchronization

	// No state data will be synchronized
	Off = 0,

	// All packets are sent reliable and ordered.
	ReliableDeltaCompressed = 1,

	// Brute force unreliable state sending
	Unreliable = 2
END

// Describes the status of the network interface peer type as returned by Network.peerType.
CONDITIONAL ENABLE_NETWORK
ENUM NetworkPeerType
	// No client connection running. Server not initialized.
	Disconnected = 0,
	// Running as server.
	Server = 1,
	// Running as client.
	Client = 2,
	// Attempting to connect to a server.
	Connecting = 3
END

// Describes different levels of log information the network layer supports.
CONDITIONAL ENABLE_NETWORK
ENUM NetworkLogLevel
	// Only report errors, otherwise silent.
	Off = 0,
	// Report informational messages like connectivity events.
	Informational = 1,
	// Full debug level logging down to each individual message being reported.
	Full = 3
END


// The NetworkPlayer is a data structure with which you can locate another player over the network.
CONDITIONAL ENABLE_NETWORK
STRUCT NetworkPlayer
	CSRAW internal int index;

	CUSTOM private static string Internal_GetIPAddress(int index) { return scripting_string_new(GetNetworkManager().GetIPAddress(index));  }
	CUSTOM private static int Internal_GetPort(int index) { return GetNetworkManager().GetPort(index); }
	CUSTOM private static string Internal_GetExternalIP() { return scripting_string_new(GetNetworkManager().GetExternalIP()); }
	CUSTOM private static int Internal_GetExternalPort() { return GetNetworkManager().GetExternalPort(); }
	CUSTOM private static string Internal_GetLocalIP() { return scripting_string_new(GetLocalIP()); }
	CUSTOM private static int Internal_GetLocalPort() { return GetNetworkManager().GetPort(); }
	CUSTOM private static int Internal_GetPlayerIndex ()  { return GetNetworkManager().GetPlayerID(); }
	CUSTOM private static string Internal_GetGUID(int index) { return scripting_string_new(GetNetworkManager().GetGUID(index)); }
	CUSTOM private static string Internal_GetLocalGUID ()  { return scripting_string_new(GetNetworkManager().GetGUID()); }

	// *undocumented*
	CSRAW public NetworkPlayer (string ip, int port)
	{
		Debug.LogError("Not yet implemented");
		index = 0;
	}

	// Returns true if two NetworkPlayers are the same player.
	CSRAW public static bool operator == (NetworkPlayer lhs, NetworkPlayer rhs)
	{
		return lhs.index == rhs.index;
	}

	// Returns true if two NetworkPlayers are not the same player.
	CSRAW public static bool operator != (NetworkPlayer lhs, NetworkPlayer rhs)
	{
		return lhs.index != rhs.index;
	}

	// *undocumented* Used to allow NetworkPlayer to be used as keys in hash tables. Also triggers warning for == and != operators if not present
	CSRAW public override int GetHashCode() {
		return index.GetHashCode();
	}

	// *undocumented* Required for being able to use NetworkPlayer as keys in hash tables
	CSRAW public override bool Equals(object other) {
		if(!(other is NetworkPlayer)) return false;

		NetworkPlayer rhs=(NetworkPlayer)other;
		return rhs.index == index;
	}

	// The IP address of this player.
	CSRAW public string ipAddress { get { if (index == Internal_GetPlayerIndex()) return Internal_GetLocalIP(); else return Internal_GetIPAddress(index); } }

	// The port of this player.
	CSRAW public int port { get { if (index == Internal_GetPlayerIndex()) return Internal_GetLocalPort(); else return Internal_GetPort(index); } }

	// The GUID for this player, used when connecting with NAT punchthrough.
	CSRAW public string guid { get { if (index == Internal_GetPlayerIndex()) return Internal_GetLocalGUID(); else return Internal_GetGUID(index); } }

	// Returns the index number for this network player.
	CSRAW override public string ToString() { return index.ToString(); }

	// Returns the external IP address of the network interface.
	CSRAW public string externalIP { get { return Internal_GetExternalIP(); } }

	// Returns the external port of the network interface.
	CSRAW public int externalPort { get { return Internal_GetExternalPort(); } }

	CSRAW static internal NetworkPlayer unassigned { get { NetworkPlayer val; val.index = -1; return val; } }

END

// The NetworkViewID is a unique identifier for a network view instance in a multiplayer game.
CONDITIONAL ENABLE_NETWORK
STRUCT NetworkViewID
	CSRAW int a;
	CSRAW int b;
	CSRAW int c;

	// Represents an invalid network view ID.
	CUSTOM_PROP static NetworkViewID unassigned { return NetworkViewID::GetUnassignedViewID(); }

	CUSTOM static internal bool Internal_IsMine(NetworkViewID value) { return GetNetworkManager().WasViewIdAllocatedByMe(value); }
	CUSTOM static internal void Internal_GetOwner(NetworkViewID value, out NetworkPlayer player) { *player = GetNetworkManager().GetNetworkViewIDOwner(value); }
	CUSTOM static internal string Internal_GetString(NetworkViewID value) { return scripting_string_new(value.ToString()); }
	CUSTOM static internal bool Internal_Compare(NetworkViewID lhs, NetworkViewID rhs) { return rhs == lhs; }

	// Returns true if two NetworkViewIDs are identical
	CSRAW public static bool operator == (NetworkViewID lhs, NetworkViewID rhs)
	{
		return Internal_Compare(lhs, rhs);
	}

	// Returns true if two NetworkViewIDs are not identical
	CSRAW public static bool operator != (NetworkViewID lhs, NetworkViewID rhs)
	{
		return !Internal_Compare(lhs, rhs);
	}

	// *undocumented* Used to allow NetworkViewIDs to be used as keys in hash tables. Also triggers warning for == and != operators if not present
	CSRAW public override int GetHashCode() {
		return a ^ b ^ c;
	}

	// *undocumented* Required for being able to use NetworkViewIDs as keys in hash tables
	CSRAW public override bool Equals(object other) {
		if(!(other is NetworkViewID)) return false;

		NetworkViewID rhs=(NetworkViewID)other;
		return Internal_Compare(this, rhs);
	}

	// True if instantiated by me
	CSRAW public bool isMine { get
	 { return Internal_IsMine(this); } }

	// The [[NetworkPlayer]] who owns the [[NetworkView]]. Could be the server.
	CSRAW public NetworkPlayer owner  { get { NetworkPlayer p; Internal_GetOwner(this, out p); return p;} }

	// Returns a formatted string with details on this NetworkViewID.
	CSRAW override public string ToString()  { return Internal_GetString(this); }

END


// Ping any given IP address (given in dot notation).
CONDITIONAL ENABLE_NETWORK
CLASS Ping

	// We are matching the Ping class here so we can directly access it.
	CSRAW private IntPtr pingWrapper;

	// this is needed only for batched android build due to bug in txt parser
	// screwing up iphone_input.txt to have cpp line emited in wrong place
	C++RAW #undef GET
	C++RAW #define GET ExtractMonoObjectData<Ping*> (self)

	// Perform a ping to the supplied target IP address.
	CUSTOM Ping(string address)
	{
		GET = new Ping(address);
		GetNetworkManager().PingWrapper(GET);
	}

	//*undocumented*
	THREAD_SAFE
	CUSTOM void DestroyPing()
	{
		if (GET)
		{
			GET->Release();
			GET = 0;
		}
	}

	CSRAW ~Ping()
	{
		DestroyPing();
	}

	// Has the ping function completed?
	CUSTOM_PROP public bool isDone
	{
		if (GET) return (short)GET->GetIsDone();
		else return false;
	}

	// This property contains the ping time result after isDone returns true.
	CUSTOM_PROP public int time
	{
		return GET->GetTime();
	}

	// The IP target of the ping.
	CUSTOM_PROP public string ip
	{
		return scripting_string_new(GET->GetIP());
	}

	C++RAW
 #undef GET

END


// The network view is the binding material of multiplayer games.
CONDITIONAL ENABLE_NETWORK
CLASS NetworkView : Behaviour

	CUSTOM private static void Internal_RPC (NetworkView view, string name, RPCMode mode, object[] args)
	{
		view->RPCCall(name, mode, args);
	}

	CUSTOM private static void Internal_RPC_Target (NetworkView view, string name, NetworkPlayer target, object[] args)
	{
		view->RPCCallSpecificTarget(name, target, args);
	}

	// Call a [[RPC]] function on all connected peers.
	CSRAW public void RPC (string name, RPCMode mode, params object[] args) { Internal_RPC(this, name, mode, args); }

	// Call a RPC function on a specific player
	CSRAW public void RPC (string name, NetworkPlayer target, params object[] args) { Internal_RPC_Target(this, name, target, args); }

	// The component the network view is observing.
	AUTO_PTR_PROP Component observed GetObserved SetObserved

	// The type of [[NetworkStateSynchronization]] set for this network view.
	CUSTOM_PROP NetworkStateSynchronization stateSynchronization  { return self->GetStateSynchronization(); } { self->SetStateSynchronization(value); }

	CUSTOM private void Internal_GetViewID (out NetworkViewID viewID)
	{
		*viewID = self->GetViewID();
	}
	CUSTOM private void  Internal_SetViewID (NetworkViewID viewID) { self->SetViewID(viewID); }

	// The ViewID of this network view.
	CSRAW public NetworkViewID viewID { get { NetworkViewID val; Internal_GetViewID(out val); return val; } set  { Internal_SetViewID(value); } }

	// The network group number of this network view.
	AUTO_PROP int group GetGroup SetGroup

	// Is the network view controlled by this object?
	CSRAW public bool isMine { get { return viewID.isMine; } }

	// The [[NetworkPlayer]] who owns this network view.
	CSRAW public NetworkPlayer owner { get { return viewID.owner; } }

	// Set the scope of the network view in relation to a specific network player.
	CUSTOM bool SetScope(NetworkPlayer player, bool relevancy)
	{
		return self->SetPlayerScope(player, relevancy);
	}

	// Find a network view based on a [[NetworkViewID]].
	CUSTOM static NetworkView Find (NetworkViewID viewID) { return Scripting::ScriptingWrapperFor(GetNetworkManager().ViewIDToNetworkView (viewID)); }

END

// The network class is at the heart of the network implementation and provides the core functions.
CONDITIONAL ENABLE_NETWORK
CLASS Network

	// Initialize the server.
	CUSTOM static NetworkConnectionError InitializeServer (int connections, int listenPort, bool useNat) { return GetNetworkManager().InitializeServer(connections, listenPort, useNat); }

	CUSTOM private static NetworkConnectionError Internal_InitializeServerDeprecated (int connections, int listenPort) { return GetNetworkManager().InitializeServer(connections, listenPort, false); }

	OBSOLETE warning Use the IntializeServer(connections, listenPort, useNat) function instead
	CSRAW public static NetworkConnectionError InitializeServer (int connections, int listenPort) { return Internal_InitializeServerDeprecated(connections, listenPort); }

	// Set the password for the server (for incoming connections).
	CUSTOM_PROP static string incomingPassword { return scripting_string_new(GetNetworkManager().GetIncomingPassword());} { GetNetworkManager().SetIncomingPassword(value);}

	// Set the log level for network messages (default is Off).
	CUSTOM_PROP static NetworkLogLevel logLevel  { return GetNetworkManager().GetDebugLevel(); } { GetNetworkManager().SetDebugLevel(value); }

	// Initializes security layer.
	CUSTOM static void InitializeSecurity() { GetNetworkManager().InitializeSecurity(); }

	CUSTOM private static NetworkConnectionError Internal_ConnectToSingleIP (string IP, int remotePort, int localPort, string password = "")
	{
		return GetNetworkManager().Connect(IP, remotePort, localPort, password);
	}

	CUSTOM private static NetworkConnectionError Internal_ConnectToGuid (string guid, string password)
	{
		RakNetGUID remoteGuid;
		remoteGuid.FromString(guid.AsUTF8().c_str());
		return GetNetworkManager().Connect(remoteGuid, 0, password);
	}

	CUSTOM private static NetworkConnectionError Internal_ConnectToIPs (string[] IP, int remotePort, int localPort, string password = "")
	{
		std::vector<string> ipvector;
		for (int i=0; i < mono_array_length_safe(IP); i++)
		{
			ipvector.push_back(scripting_cpp_string_for(GetMonoArrayElement<MonoString*> (IP, i)));
		}
		return GetNetworkManager().Connect(ipvector, remotePort, localPort, password);
	}

	// Connect to the specified host (ip or domain name) and server port.
	CSRAW public static NetworkConnectionError Connect (string IP, int remotePort, string password = "") { return Internal_ConnectToSingleIP(IP, remotePort, 0, password); }

	// This function is exactly like Network.Connect but can accept an array of IP addresses.
	CSRAW public static NetworkConnectionError Connect (string[] IPs, int remotePort, string password = ""){
		return Internal_ConnectToIPs(IPs, remotePort, 0, password); }

	// Connect to a server GUID. NAT punchthrough can only be performed this way.
	CSRAW public static NetworkConnectionError Connect (string GUID, string password = "") {
		return Internal_ConnectToGuid(GUID, password);
	}

	// Connect to the host represented by a [[HostData]] structure returned by the Master Server.
	CSRAW public static NetworkConnectionError Connect (HostData hostData, string password = "") {
		if(hostData == null)
			throw new NullReferenceException();
		if (hostData.guid.Length > 0 && hostData.useNat)
			return Connect(hostData.guid, password);
		else
			return Connect(hostData.ip, hostData.port, password);
	}

	// Close all open connections and shuts down the network interface.
	CUSTOM static void Disconnect(int timeout = 200) { GetNetworkManager().Disconnect(timeout); }

	// Close the connection to another system.
	CUSTOM static void CloseConnection (NetworkPlayer target, bool sendDisconnectionNotification) { GetNetworkManager().CloseConnection(target, sendDisconnectionNotification); }

	// All connected players.
	CUSTOM_PROP static NetworkPlayer[] connections {
		MonoArray* array = mono_array_new (mono_domain_get (), MONO_COMMON.networkPlayer, GetNetworkManager().GetConnectionCount());
		GetNetworkManager().GetConnections(&GetMonoArrayElement<int> (array,0));
		return array;
	}

	CUSTOM private static int Internal_GetPlayer ()  { return GetNetworkManager().GetPlayerID(); }

	// Get the local [[NetworkPlayer]] instance
	CSRAW public static NetworkPlayer player { get { NetworkPlayer np; np.index = Internal_GetPlayer(); return np; } }

	CUSTOM private static void Internal_AllocateViewID(out NetworkViewID viewID)
	{ *viewID = GetNetworkManager().AllocateViewID(); }

	// Query for the next available network view ID number and allocate it (reserve).
	CSRAW public static NetworkViewID AllocateViewID() { NetworkViewID val; Internal_AllocateViewID (out val); return val; }

	// Network instantiate a prefab.
	CSRAW
	[TypeInferenceRule(TypeInferenceRules.TypeOfFirstArgument)]
	CUSTOM public static Object Instantiate (Object prefab, Vector3 position, Quaternion rotation, int group) { return Scripting::ScriptingWrapperFor(GetNetworkManager().Instantiate (*prefab, position, rotation, group)); }

	// Destroy the object associated with this view ID across the network.
	CUSTOM static void Destroy (NetworkViewID viewID) { GetNetworkManager().DestroyDelayed(viewID); }

	// Destroy the object across the network.
	CSRAW public static void Destroy (GameObject gameObject) {
		if (gameObject != null)
		{
			NetworkView view = gameObject.networkView;
			if (view != null)
				Destroy(view.viewID);
			else
				Debug.LogError("Couldn't destroy game object because no network view is attached to it.", gameObject);
		}
	}

	// Destroy all the objects based on view IDs belonging to this player.
	CUSTOM static void DestroyPlayerObjects(NetworkPlayer playerID) { GetNetworkManager().DestroyPlayerObjects(playerID); }

	CUSTOM private static void Internal_RemoveRPCs(NetworkPlayer playerID, NetworkViewID viewID, uint channelMask) { GetNetworkManager().RemoveRPCs(playerID, viewID, channelMask); }

	// Remove all [[RPC]] functions which belong to this player ID.
	CSRAW public static void RemoveRPCs(NetworkPlayer playerID) { Internal_RemoveRPCs(playerID, NetworkViewID.unassigned, 0xFFFFFFFF); }
	// Remove all [[RPC]] functions which belong to this player ID and were sent based on the given group.
	CSRAW public static void RemoveRPCs(NetworkPlayer playerID, int group) { Internal_RemoveRPCs(playerID, NetworkViewID.unassigned, (uint)(1 << group)); }
	// Remove the [[RPC]] function calls accociated with this view ID number.
	CSRAW public static void RemoveRPCs(NetworkViewID viewID) { Internal_RemoveRPCs(NetworkPlayer.unassigned, viewID, 0xFFFFFFFF); }
	// Remove all [[RPC]] functions which belong to given group number.
	CSRAW public static  void RemoveRPCsInGroup (int group) { Internal_RemoveRPCs(NetworkPlayer.unassigned, NetworkViewID.unassigned, (uint)(1 << group)); }

	// Returns true if your peer type is client.
	CUSTOM_PROP static bool isClient { return GetNetworkManager().IsClient(); }

	// Returns true if your peer type is server.
	CUSTOM_PROP static bool isServer { return GetNetworkManager().IsServer(); }

	// The status of the peer type, i.e. if it is disconnected, connecting, server or client.
	CUSTOM_PROP static NetworkPeerType peerType { return GetNetworkManager().GetPeerType(); }

	// Set the level prefix which will then be prefixed to all network ViewID numbers.
	CUSTOM static void SetLevelPrefix (int prefix) { return GetNetworkManager().SetLevelPrefix(prefix); }


	// The last ping time to the given /player/ in milliseconds.
	CUSTOM static int GetLastPing (NetworkPlayer player) { return GetNetworkManager().GetLastPing(player); }

	// The last average ping time to the given /player/ in milliseconds.
	CUSTOM static int GetAveragePing (NetworkPlayer player) { return GetNetworkManager().GetAveragePing(player); }

	// The default send rate of network updates for all Network Views.
	CUSTOM_PROP static float sendRate { return GetNetworkManager().GetSendRate(); } { GetNetworkManager().SetSendRate(value); }

	// Enable or disable the processing of network messages.
	CUSTOM_PROP static bool isMessageQueueRunning { return GetNetworkManager().GetMessageQueueRunning(); } { GetNetworkManager().SetMessageQueueRunning(value); }

	// Enable or disables the reception of messages in a specific group number from a specific player.
	CUSTOM static void SetReceivingEnabled (NetworkPlayer player, int group, bool enabled)  { GetNetworkManager().SetReceivingGroupEnabled(player, group, enabled); }

	CUSTOM private static void Internal_SetSendingGlobal(int group, bool enabled) { GetNetworkManager().SetSendingGroupEnabled(group, enabled); }

	CUSTOM private static void Internal_SetSendingSpecific (NetworkPlayer player, int group, bool enabled) { GetNetworkManager().SetSendingGroupEnabled(player, group, enabled); }

	// Enables or disables transmission of messages and [[RPC]] calls on a specific network group number.
	CSRAW public static void SetSendingEnabled (int group, bool enabled) { Internal_SetSendingGlobal(group, enabled); }

	// Enable or disable transmission of messages and [[RPC]] calls based on target network player as well as the network group.
	CSRAW public static void SetSendingEnabled (NetworkPlayer player, int group, bool enabled) { Internal_SetSendingSpecific(player, group, enabled); }

	CUSTOM private static void Internal_GetTime(out double t) { *t = GetNetworkManager().GetTime();}

	// Get the current network time (seconds).
	CSRAW public static double time {  get { double t; Internal_GetTime(out t); return t; } }

	// Called on the server whenever a new player has successfully connected.
	CSNONE void OnPlayerConnected (NetworkPlayer player);

	// Called on the server whenever a Network.InitializeServer was invoked and has completed.
	CSNONE void OnServerInitialized ();

	// Called on the client when you have successfully connected to a server
	CSNONE void OnConnectedToServer ();

	// Called on the server whenever a player is disconnected from the server
	CSNONE void OnPlayerDisconnected (NetworkPlayer player);

	// Called on client during disconnection from server, but also on the server when the connection has disconnected.
	CSNONE void OnDisconnectedFromServer (NetworkDisconnection mode);

	// Called on the client when a connection attempt fails for some reason.
	CSNONE void OnFailedToConnect (NetworkConnectionError error);

	// Called on objects which have been network instantiated with Network.Instantiate
	CSNONE void OnNetworkInstantiate (NetworkMessageInfo info);

	// Used to customize synchronization of variables in a script watched by a network view.
	CSNONE void OnSerializeNetworkView (BitStream stream, NetworkMessageInfo info);

	// Get or set the minimum number of ViewID numbers in the ViewID pool given to clients by the server.
	CUSTOM_PROP static int minimumAllocatableViewIDs { return GetNetworkManager().GetMinimumAllocatableViewIDs(); } { GetNetworkManager().SetMinimumAllocatableViewIDs(value); }

	OBSOLETE warning No longer needed. This is now explicitly set in the InitializeServer function call. It is implicitly set when calling Connect depending on if an IP/port combination is used (useNat=false) or a GUID is used(useNat=true).
	CUSTOM_PROP static bool useNat { return GetNetworkManager().GetUseNat(); } { GetNetworkManager().SetUseNat(value); }

	// The IP address of the NAT punchthrough facilitator.
	CUSTOM_PROP static string natFacilitatorIP { return scripting_string_new(GetNetworkManager().GetFacilitatorAddress().ToString());} { GetNetworkManager().GetFacilitatorAddress(false).SetBinaryAddress(value.AsUTF8().c_str());}
	// The port of the NAT punchthrough facilitator.
	CUSTOM_PROP static int natFacilitatorPort { return GetNetworkManager().GetFacilitatorAddress().port;} {
	#ifdef _XBOX	// mircea@XBOX: for some reason, the xbox compiler chokes on the "simple" assign
		SystemAddress& sa = GetNetworkManager().GetFacilitatorAddress(false); sa.port = value;
	#else
		GetNetworkManager().GetFacilitatorAddress(false).port = value;
	#endif
}

	// Test this machines network connection.
	CUSTOM static ConnectionTesterStatus TestConnection(bool forceTest = false) { return GetNetworkManager().TestConnection(false, forceTest); }

	// Test the connecction specifically for NAT punchthrough connectivity.
	CUSTOM static ConnectionTesterStatus TestConnectionNAT(bool forceTest = false) { return GetNetworkManager().TestConnection(true, forceTest); }

	// The IP address of the connection tester used in Network.TestConnection.
	CUSTOM_PROP static string connectionTesterIP { return scripting_string_new(GetNetworkManager().GetConnTesterAddress().ToString(false));} { SystemAddress address = GetNetworkManager().GetConnTesterAddress(); address.SetBinaryAddress(value.AsUTF8().c_str()); GetNetworkManager().SetConnTesterAddress(address);}
	// The port of the connection tester used in Network.TestConnection.
	CUSTOM_PROP static int connectionTesterPort { return GetNetworkManager().GetConnTesterAddress().port;} { SystemAddress address = GetNetworkManager().GetConnTesterAddress(); address.port = value; GetNetworkManager().SetConnTesterAddress(address);}

	// Check if this machine has a public IP address.
	CUSTOM static bool HavePublicAddress() { return CheckForPublicAddress(); }

	// Set the maximum amount of connections/players allowed.
	CUSTOM_PROP static int maxConnections {return GetNetworkManager().GetMaxConnections(); } { GetNetworkManager().SetMaxConnections(value); }

	// The IP address of the proxy server.
	CUSTOM_PROP static string proxyIP { return scripting_string_new(GetNetworkManager().GetProxyIP());} { GetNetworkManager().SetProxyIP(value);}

	// The port of the proxy server.
	CUSTOM_PROP static int proxyPort { return GetNetworkManager().GetProxyPort();} { GetNetworkManager().SetProxyPort(value);}

	// Indicate if proxy support is needed, in which case traffic is relayed through the proxy server.
	CUSTOM_PROP static bool useProxy { return GetNetworkManager().GetUseProxy(); } { GetNetworkManager().SetUseProxy(value); }

	// Set the proxy server password.
	CUSTOM_PROP static string proxyPassword
	{
		return scripting_string_new(GetNetworkManager().GetProxyPassword());
	}
	{
		GetNetworkManager().SetProxyPassword(value);
	}
END

// The BitStream class represents seralized variables, packed into a stream.
CONDITIONAL ENABLE_NETWORK
CLASS BitStream
	CSRAW internal IntPtr m_Ptr;


	C++RAW
 #define GET ExtractMonoObjectData<BitstreamPacker*> (self)

	C++RAW
 #define CHECK_PTR if (ExtractMonoObjectData<BitstreamPacker*> (self) == NULL) Scripting::RaiseNullException("");

	CUSTOM private void Serializeb (ref int value) { CHECK_PTR bool temp = value; GET->Serialize(temp); value = temp; }
	CUSTOM private void Serializec (ref char value) {
		// pre-Unity 2.5 serialized .NET chars as single bytes. Let's keep it backwards compatible for now.
		// on big endian the lower order bits of the 2 byte .NET Char value contains the actual bits we need to send
		#if UNITY_BIG_ENDIAN
		char* hack = reinterpret_cast<char*>(&value)+1;
		#else
		char* hack = reinterpret_cast<char*>(&value);
		#endif
		CHECK_PTR GET->Serialize(*hack);
	}
	CUSTOM private void Serializes (ref short value) { CHECK_PTR GET->Serialize(value); }
	CUSTOM private void Serializei (ref int value) { CHECK_PTR GET->Serialize(reinterpret_cast<SInt32&>(value)); }
	CUSTOM private void Serializef (ref float value, float maximumDelta) { CHECK_PTR GET->Serialize(value, maximumDelta); }
	CUSTOM private void Serializeq (ref Quaternion value, float maximumDelta) { CHECK_PTR GET->Serialize(value, maximumDelta); }
	CUSTOM private void Serializev (ref Vector3 value, float maximumDelta)  { CHECK_PTR GET->Serialize(value, maximumDelta); }
	CUSTOM private void Serializen (ref NetworkViewID viewID) { CHECK_PTR GET->Serialize(viewID); }

	///*listonly*
	CSRAW public void Serialize(ref bool value) { int cross = value ? 1 : 0; Serializeb( ref cross ); value = cross == 0 ? false : true; }
	///*listonly*
	CSRAW public void Serialize(ref char value) { Serializec( ref value ); }
	///*listonly*
	CSRAW public void Serialize(ref short value) { Serializes( ref value); }
	///*listonly*
	CSRAW public void Serialize(ref int value) { Serializei( ref value); }
	///*listonly*
	CSRAW public void Serialize(ref float value, float maxDelta = 0.00001F) { Serializef( ref value, maxDelta); }
	///*listonly*
	CSRAW public void Serialize(ref Quaternion value, float maxDelta = 0.00001F) { Serializeq( ref value, maxDelta); }
	///*listonly*
	CSRAW public void Serialize(ref Vector3 value, float maxDelta = 0.00001F) { Serializev( ref value, maxDelta); }
	///*listonly*
	CSRAW public void Serialize(ref NetworkPlayer value) { int index = value.index; Serializei( ref index ); value.index = index;}
	// Serializes different types of variables.
	CSRAW public void Serialize(ref NetworkViewID viewID) { Serializen(ref viewID); }

	// Is the BitStream currently being read? (RO)
	CUSTOM_PROP bool isReading { CHECK_PTR return GET->IsReading(); }
	// Is the BitStream currently being written? (RO)
	CUSTOM_PROP bool isWriting { CHECK_PTR return GET->IsWriting(); }

	CUSTOM private void Serialize (ref string value)
	{
		CHECK_PTR
		std::string cppValue;
		if (GET->IsWriting())
			cppValue = value;

		GET->Serialize(cppValue);

		if (GET->IsReading())
			value.str = scripting_string_new(cppValue);
	}

	C++RAW
 #undef GET

	C++RAW
 #undef CHECK

END


// Attribute for setting up RPC functions.
CONDITIONAL ENABLE_NETWORK
CSRAW [AttributeUsage(AttributeTargets.Method, AllowMultiple=true)]
CLASS RPC : Attribute
END

// This is the data structure for holding individual host information.
CONDITIONAL ENABLE_NETWORK
CSRAW [StructLayout (LayoutKind.Sequential)]
CLASS HostData
		CSRAW private int    m_Nat;
        CSRAW private string m_GameType;
        CSRAW private string m_GameName;
        CSRAW private int    m_ConnectedPlayers;
        CSRAW private int    m_PlayerLimit;
        CSRAW private string[] m_IP;
        CSRAW private int    m_Port;
        CSRAW private int    m_PasswordProtected;
		CSRAW private string m_Comment;
		CSRAW private string m_GUID;

	// Does this server require NAT punchthrough?

	CSRAW public bool   useNat   { get { return m_Nat != 0; } set { m_Nat = value ? 1 : 0; } }
	// The type of the game (like "MyUniqueGameType")
        CSRAW public string gameType { get { return m_GameType; } set { m_GameType = value; } }

	// The name of the game (like John Doe's Game)
        CSRAW public string gameName { get { return m_GameName; } set { m_GameName = value; } }

	// Currently connected players
	CSRAW public int    connectedPlayers { get { return m_ConnectedPlayers; } set { m_ConnectedPlayers = value; } }

	// Maximum players limit
	CSRAW public int    playerLimit { get { return m_PlayerLimit; } set { m_PlayerLimit = value; } }
	// Server IP address
	CSRAW public string[] ip { get { return m_IP; } set { m_IP = value; } }

	// Server port
	CSRAW public int    port  { get { return m_Port; } set { m_Port = value; } }

	// Does the server require a password?
	CSRAW public bool   passwordProtected { get { return m_PasswordProtected != 0; } set { m_PasswordProtected = value ? 1 : 0; } }

	// A miscellaneous comment (can hold data)
	CSRAW public string comment { get { return m_Comment; } set { m_Comment = value; } }

	// The GUID of the host, needed when connecting with NAT punchthrough.
	CSRAW public string guid { get { return m_GUID; } set { m_GUID = value; } }
END

C++RAW

struct HostDataCpp
{
		int			useNat;
        MonoString* gameType;
        MonoString* gameName;
        int			connectedPlayers;
        int			playerLimit;
        MonoArray*	IP;
        int			port;
        int			passwordProtected;
		MonoString* comment;
		MonoString* guid;
};


// The Master Server is used to make matchmaking between servers and clients easy.
CONDITIONAL ENABLE_NETWORK
CLASS MasterServer

	// Called on clients or servers when there is a problem connecting to the master server.
	CSNONE void OnFailedToConnectToMasterServer (NetworkConnectionError error);

	// Called on clients or servers when reporting events from the MasterServer.
	CSNONE void OnMasterServerEvent (MasterServerEvent msEvent);

	// The IP address of the master server.
	CUSTOM_PROP static string ipAddress { return scripting_string_new(GetMasterServerInterface().GetIPAddress());} { GetMasterServerInterface().SetIPAddress(value);}

	// The connection port of the master server.
	CUSTOM_PROP static int port { return GetMasterServerInterface().GetPort();} { GetMasterServerInterface().SetPort(value);}

	// Request a host list from the master server.
	CUSTOM static void RequestHostList(string gameTypeName) { GetMasterServerInterface().QueryHostList(gameTypeName); }

	// Check for the latest host list received by using MasterServer.RequestHostList.
	CUSTOM static HostData[] PollHostList()
	{
		const std::vector<HostData>& data = GetMasterServerInterface().PollHostList();
		MonoClass* hostType = GetMonoManager ().GetCommonClasses ().hostData;

		//if (data == NULL) return NULL;

		//count = 0;

		MonoArray* array = mono_array_new (mono_domain_get (), hostType, data.size());
		for (int i = 0; i < data.size(); i++)
		{
				MonoObject* element = mono_object_new(mono_domain_get(), hostType);
				GetMonoArrayElement<MonoObject*> (array, i) = element;
				HostDataCpp& dst = ExtractMonoObjectData<HostDataCpp> (element);
				HostData src = data[i];

				dst.useNat = src.useNat;
				dst.gameType = scripting_string_new(src.gameType);
				dst.gameName = scripting_string_new(src.gameName);
				dst.connectedPlayers = src.connectedPlayers;
				dst.playerLimit = src.playerLimit;
				MonoArray* ips = mono_array_new (mono_domain_get (), mono_get_string_class(), src.IP.size());
				for (int i = 0; i < src.IP.size(); i++)
				{
					GetMonoArrayElement<MonoString*> (ips, i) = scripting_string_new(src.IP[i]);
				}
				dst.IP = ips;
				dst.port = src.port;
				dst.passwordProtected = src.passwordProtected;
				dst.comment = scripting_string_new(src.comment);
				dst.guid = scripting_string_new(src.guid);
		}

		return array;
	}

	// Register this server on the master server.
	CUSTOM static void RegisterHost(string gameTypeName, string gameName, string comment = "") { GetMasterServerInterface().RegisterHost(gameTypeName, gameName, comment); }

	// Unregister this server from the master server.
	CUSTOM static void UnregisterHost() { GetMasterServerInterface().UnregisterHost(); }

	// Clear the host list which was received by MasterServer.PollHostList.
	CUSTOM static void ClearHostList() { GetMasterServerInterface().ClearHostList(); }

	// Set the minimum update rate for master server host information update.
	CUSTOM_PROP static int updateRate { return GetMasterServerInterface().GetUpdateRate();} { GetMasterServerInterface().SetUpdateRate(value);}

	// Report this machine as a dedicated server.
	CUSTOM_PROP static bool dedicatedServer { return GetMasterServerInterface().GetDedicatedServer(); } { GetMasterServerInterface().SetDedicatedServer(value); }
END

// This data structure contains information on a message just received from the network.
CONDITIONAL ENABLE_NETWORK
STRUCT NetworkMessageInfo
	CSRAW
	double        m_TimeStamp;
	NetworkPlayer m_Sender;
	NetworkViewID m_ViewID;

	// The time stamp when the Message was sent in seconds.
	CSRAW public double timestamp { get { return m_TimeStamp; }  }

	// The player who sent this network message (owner)
	CSRAW public NetworkPlayer sender { get { return m_Sender; }  }

	// The [[NetworkView]] who sent this message
	CSRAW public NetworkView networkView
	{
		get
		{
			if (m_ViewID == NetworkViewID.unassigned)
			{
				Debug.LogError("No NetworkView is assigned to this NetworkMessageInfo object. Note that this is expected in OnNetworkInstantiate().");
				return NullNetworkView();
			}
			return NetworkView.Find(m_ViewID);
		}
	}

	CUSTOM internal NetworkView NullNetworkView() { return Scripting::ScriptingObjectNULL (ScriptingClassFor (NetworkView)); }

END


CSRAW }
#endif