Advertisement
Guest User

Untitled

a guest
Jun 17th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.75 KB | None | 0 0
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEngine.SceneManagement;
  4. using UnityEngine.Networking;
  5. using UnityEngine.Networking.Types;
  6. using UnityEngine.Networking.Match;
  7. using System.Collections;
  8. using WebSocketSharp;
  9. using Newtonsoft.Json;
  10. using System.Collections.Generic;
  11. using System;
  12.  
  13. namespace Prototype.NetworkLobby
  14. {
  15. public class LobbyManager : NetworkLobbyManager
  16. {
  17. static short MsgKicked = MsgType.Highest + 1;
  18.  
  19. static public LobbyManager s_Singleton;
  20. public GameObject engine;
  21.  
  22. static public WebSocket ws;
  23.  
  24. [Header("Unity UI Lobby")]
  25. [Tooltip("Time in second between all players ready & match start")]
  26. public float prematchCountdown = 5.0f;
  27.  
  28. [Space]
  29. [Header("UI Reference")]
  30. public LobbyTopPanel topPanel;
  31. public string UserName = "Client";
  32. public string LobbyName = "1";
  33.  
  34. public RectTransform mainMenuPanel;
  35. public RectTransform lobbyPanel;
  36.  
  37. public LobbyInfoPanel infoPanel;
  38. public LobbyCountdownPanel countdownPanel;
  39. public GameObject addPlayerButton;
  40.  
  41. protected RectTransform currentPanel;
  42.  
  43. public Button backButton;
  44.  
  45. public Text statusInfo;
  46. public Text hostInfo;
  47.  
  48. public GameObject numpad;
  49.  
  50. //Client numPlayers from NetworkManager is always 0, so we count (throught connect/destroy in LobbyPlayer) the number
  51. //of players, so that even client know how many player there is.
  52. [HideInInspector]
  53. public int _playerNumber = 0;
  54.  
  55. //used to disconnect a client properly when exiting the matchmaker
  56. [HideInInspector]
  57. public bool _isMatchmaking = false;
  58.  
  59. protected bool _disconnectServer = false;
  60.  
  61. protected ulong _currentMatchID;
  62.  
  63. protected LobbyHook _lobbyHooks;
  64.  
  65. private bool startDemo = false;
  66.  
  67. public static Dictionary<string, RectTransform> screens;
  68. public static Dictionary<string, Action<Payload>> serverCommands;
  69. public static Dictionary<string, Action<Payload>> playerCommands;
  70. public static Dictionary<string, Action<Payload>> adminCommands;
  71. public static Dictionary<string, Dictionary<string, Action<Payload>>> commandsSet;
  72.  
  73. public float min;
  74. public float max;
  75. public bool diapasonSet = false;
  76.  
  77. private void Update()
  78. {
  79. if (startDemo)
  80. {
  81. playerCommands["beginDemo"](new Payload());
  82. startDemo = false;
  83. }
  84.  
  85. if (diapasonSet)
  86. {
  87. playerCommands["setMinMax"](new Payload());
  88. diapasonSet = false;
  89. }
  90. }
  91.  
  92. void Start()
  93. {
  94. s_Singleton = this;
  95. _lobbyHooks = GetComponent<Prototype.NetworkLobby.LobbyHook>();
  96. currentPanel = mainMenuPanel;
  97.  
  98. backButton.gameObject.SetActive(false);
  99. GetComponent<Canvas>().enabled = true;
  100.  
  101. adminCommands = new Dictionary<string, Action<Payload>> {
  102. { "playerConnected", (payload) => {
  103. User user = payload.user;
  104. GameObject obj = Instantiate(lobbyPlayerPrefab.gameObject) as GameObject;
  105.  
  106. LobbyPlayer newPlayer = obj.GetComponent<LobbyPlayer>();
  107.  
  108. newPlayer.playerName = user.userName;
  109. newPlayer.nameInput.text = user.userName;
  110.  
  111. LobbyPlayerList._instance.AddPlayer(newPlayer);
  112. }
  113. }
  114. };
  115.  
  116. playerCommands = new Dictionary<string, Action<Payload>> {
  117. { "refreshData", (payload) => {
  118. Debug.Log("Calling refresh data");
  119. User user = new User();
  120. user.userName = UserName;
  121. user.userType = "Player";
  122.  
  123. Payload newPayload = new Payload();
  124. newPayload.user = user;
  125. newPayload.lobby = LobbyName;
  126. newPayload.stateData = payload.stateData;
  127.  
  128. Command command = new Command();
  129. command.setType = "playerCommands";
  130. command.command = "refreshData";
  131.  
  132. Message message = new Message();
  133. message.payload = newPayload;
  134. message.command = command;
  135. message.user = user;
  136.  
  137. string json = JsonConvert.SerializeObject(message);
  138. ws.Send(json);
  139. }
  140. },
  141. { "startDemo", (payload) => {
  142. startDemo = true;
  143. }
  144. },
  145. { "beginDemo", (payload) => {
  146. Debug.Log("GO DEMO");
  147. engine = GameObject.Find("ENGINE");
  148. engine.GetComponent<engineClient>().StartDemo();
  149. }
  150. },
  151. { "setMinMax", (payload) => {
  152. Debug.Log("Setting diapason");
  153. numpad.GetComponent<speedtest>().speedMin = min;
  154. numpad.GetComponent<speedtest>().speedMax = max;
  155. }
  156. },
  157. { "onSpeedTest", (payload) => {
  158. Debug.Log("Setting diapason");
  159. min = payload.speedTest - 2;
  160. max = payload.speedTest + 2;
  161. diapasonSet = true;
  162. }
  163. }
  164. };
  165.  
  166. serverCommands = new Dictionary<string, Action<Payload>> {
  167. { "joinLobby", (payload) => {
  168.  
  169. User user = new User();
  170. user.userName = UserName;
  171. user.userType = "Player";
  172.  
  173. Payload newPayload = new Payload();
  174. newPayload.user = user;
  175. newPayload.lobby = LobbyName;
  176.  
  177. Command command = new Command();
  178. command.setType = "serverCommands";
  179. command.command = "joinLobby";
  180.  
  181. Message message = new Message();
  182. message.payload = newPayload;
  183. message.command = command;
  184.  
  185. string json = JsonConvert.SerializeObject(message);
  186. ws.Send(json);
  187. }
  188. }
  189. };
  190.  
  191. screens = new Dictionary<string, RectTransform> {
  192. { "mainMenu", s_Singleton.mainMenuPanel},
  193. { "lobby", s_Singleton.lobbyPanel }
  194. };
  195.  
  196. commandsSet = new Dictionary<string, Dictionary<string, Action<Payload>>> {
  197. { "playerCommands", playerCommands },
  198. { "adminCommands", adminCommands },
  199. { "serverCommands", serverCommands }
  200. };
  201.  
  202.  
  203. ws = new WebSocket("ws://localhost:8999");
  204.  
  205.  
  206. User admin = new User();
  207. admin.userType = "Player";
  208. admin.userName = UserName;
  209.  
  210. Payload initPayload = new Payload();
  211. initPayload.user = admin;
  212.  
  213. Command newCommand = new Command();
  214. newCommand.setType = "serverCommands";
  215. newCommand.command = "reg";
  216.  
  217. Message newMessage = new Message();
  218. newMessage.command = newCommand;
  219. newMessage.payload = initPayload;
  220.  
  221. string jsonAdmin = JsonConvert.SerializeObject(newMessage);
  222. ws.OnMessage += (sender, e) => {
  223. Message message = JsonConvert.DeserializeObject<Message>(e.Data);
  224. Debug.Log(message);
  225. Command command = message.command;
  226.  
  227. Dictionary<string, Action<Payload>> currentCommandSet = commandsSet[command.setType];
  228.  
  229. currentCommandSet[command.command](message.payload);
  230. };
  231.  
  232. ws.Connect();
  233. ws.Send(jsonAdmin);
  234.  
  235. DontDestroyOnLoad(gameObject);
  236.  
  237. SetServerInfo("Offline", "None");
  238. }
  239.  
  240. public LobbyPlayer GetPlayer(Payload payload)
  241. {
  242. User user = payload.user;
  243. GameObject obj = Instantiate(lobbyPlayerPrefab.gameObject) as GameObject;
  244.  
  245. LobbyPlayer newPlayer = obj.GetComponent<LobbyPlayer>();
  246.  
  247. newPlayer.playerName = user.userName;
  248. newPlayer.nameInput.text = user.userName;
  249.  
  250. return newPlayer;
  251. }
  252.  
  253. public override void OnLobbyClientSceneChanged(NetworkConnection conn)
  254. {
  255. if (SceneManager.GetSceneAt(0).name == lobbyScene)
  256. {
  257. if (topPanel.isInGame)
  258. {
  259. ChangeTo(lobbyPanel);
  260. if (_isMatchmaking)
  261. {
  262. if (conn.playerControllers[0].unetView.isServer)
  263. {
  264. backDelegate = StopHostClbk;
  265. }
  266. else
  267. {
  268. backDelegate = StopClientClbk;
  269. }
  270. }
  271. else
  272. {
  273. if (conn.playerControllers[0].unetView.isClient)
  274. {
  275. backDelegate = StopHostClbk;
  276. }
  277. else
  278. {
  279. backDelegate = StopClientClbk;
  280. }
  281. }
  282. }
  283. else
  284. {
  285. ChangeTo(mainMenuPanel);
  286. }
  287.  
  288. topPanel.ToggleVisibility(true);
  289. topPanel.isInGame = false;
  290. }
  291. else
  292. {
  293. ChangeTo(null);
  294.  
  295. Destroy(GameObject.Find("MainMenuUI(Clone)"));
  296.  
  297. //backDelegate = StopGameClbk;
  298. topPanel.isInGame = true;
  299. topPanel.ToggleVisibility(false);
  300. }
  301. }
  302.  
  303. public void ConnectToLobby()
  304. {
  305. serverCommands["joinLobby"](new Payload());
  306.  
  307. User admin = new User();
  308. admin.userType = "Player";
  309. admin.userName = UserName;
  310.  
  311. Payload initPayload = new Payload();
  312. initPayload.user = admin;
  313.  
  314. LobbyPlayerList._instance.AddPlayer(GetPlayer(initPayload));
  315. }
  316.  
  317. public void ChangeTo(RectTransform newPanel)
  318. {
  319. if (currentPanel != null)
  320. {
  321. currentPanel.gameObject.SetActive(false);
  322. }
  323.  
  324. if (newPanel != null)
  325. {
  326. newPanel.gameObject.SetActive(true);
  327. }
  328.  
  329. currentPanel = newPanel;
  330.  
  331. if (currentPanel != mainMenuPanel)
  332. {
  333. backButton.gameObject.SetActive(true);
  334. }
  335. else
  336. {
  337. backButton.gameObject.SetActive(false);
  338. SetServerInfo("Offline", "None");
  339. _isMatchmaking = false;
  340. }
  341. }
  342.  
  343. public void DisplayIsConnecting()
  344. {
  345. var _this = this;
  346. infoPanel.Display("Connecting...", "Cancel", () => { _this.backDelegate(); });
  347. }
  348.  
  349. public void SetServerInfo(string status, string host)
  350. {
  351. statusInfo.text = status;
  352. hostInfo.text = host;
  353. }
  354.  
  355.  
  356. public delegate void BackButtonDelegate();
  357. public BackButtonDelegate backDelegate;
  358. public void GoBackButton()
  359. {
  360. backDelegate();
  361. topPanel.isInGame = false;
  362. }
  363.  
  364. // ----------------- Server management
  365.  
  366. public void AddLocalPlayer()
  367. {
  368. TryToAddPlayer();
  369. }
  370.  
  371. public void RemovePlayer(LobbyPlayer player)
  372. {
  373. player.RemovePlayer();
  374. }
  375.  
  376. public void SimpleBackClbk()
  377. {
  378. ChangeTo(mainMenuPanel);
  379. }
  380.  
  381. public void StopHostClbk()
  382. {
  383. if (_isMatchmaking)
  384. {
  385. matchMaker.DestroyMatch((NetworkID)_currentMatchID, 0, OnDestroyMatch);
  386. _disconnectServer = true;
  387. }
  388. else
  389. {
  390. StopHost();
  391. }
  392.  
  393.  
  394. ChangeTo(mainMenuPanel);
  395. }
  396.  
  397. public void StopClientClbk()
  398. {
  399. StopClient();
  400.  
  401. if (_isMatchmaking)
  402. {
  403. StopMatchMaker();
  404. }
  405.  
  406. ChangeTo(mainMenuPanel);
  407. }
  408.  
  409. public void StopServerClbk()
  410. {
  411. StopServer();
  412. ChangeTo(mainMenuPanel);
  413. }
  414.  
  415. class KickMsg : MessageBase { }
  416. public void KickPlayer(NetworkConnection conn)
  417. {
  418. conn.Send(MsgKicked, new KickMsg());
  419. }
  420.  
  421.  
  422.  
  423.  
  424. public void KickedMessageHandler(NetworkMessage netMsg)
  425. {
  426. infoPanel.Display("Kicked by Server", "Close", null);
  427. netMsg.conn.Disconnect();
  428. }
  429.  
  430. //===================
  431.  
  432. public override void OnStartHost()
  433. {
  434. base.OnStartHost();
  435.  
  436. ChangeTo(lobbyPanel);
  437. backDelegate = StopHostClbk;
  438. SetServerInfo("Hosting", networkAddress);
  439. }
  440.  
  441. public override void OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo)
  442. {
  443. base.OnMatchCreate(success, extendedInfo, matchInfo);
  444. _currentMatchID = (System.UInt64)matchInfo.networkId;
  445. }
  446.  
  447. public override void OnDestroyMatch(bool success, string extendedInfo)
  448. {
  449. base.OnDestroyMatch(success, extendedInfo);
  450. if (_disconnectServer)
  451. {
  452. StopMatchMaker();
  453. StopHost();
  454. }
  455. }
  456.  
  457. //allow to handle the (+) button to add/remove player
  458. public void OnPlayersNumberModified(int count)
  459. {
  460. _playerNumber += count;
  461.  
  462. int localPlayerCount = 0;
  463. foreach (PlayerController p in ClientScene.localPlayers)
  464. localPlayerCount += (p == null || p.playerControllerId == -1) ? 0 : 1;
  465.  
  466. addPlayerButton.SetActive(localPlayerCount < maxPlayersPerConnection && _playerNumber < maxPlayers);
  467. }
  468.  
  469. // ----------------- Server callbacks ------------------
  470.  
  471. //we want to disable the button JOIN if we don't have enough player
  472. //But OnLobbyClientConnect isn't called on hosting player. So we override the lobbyPlayer creation
  473. public override GameObject OnLobbyServerCreateLobbyPlayer(NetworkConnection conn, short playerControllerId)
  474. {
  475. GameObject obj = Instantiate(lobbyPlayerPrefab.gameObject) as GameObject;
  476.  
  477. LobbyPlayer newPlayer = obj.GetComponent<LobbyPlayer>();
  478. newPlayer.ToggleJoinButton(numPlayers + 1 >= minPlayers);
  479.  
  480.  
  481. for (int i = 0; i < lobbySlots.Length; ++i)
  482. {
  483. LobbyPlayer p = lobbySlots[i] as LobbyPlayer;
  484.  
  485. if (p != null)
  486. {
  487. p.RpcUpdateRemoveButton();
  488. p.ToggleJoinButton(numPlayers + 1 >= minPlayers);
  489. }
  490. }
  491.  
  492. return obj;
  493. }
  494.  
  495. public override void OnLobbyServerPlayerRemoved(NetworkConnection conn, short playerControllerId)
  496. {
  497. for (int i = 0; i < lobbySlots.Length; ++i)
  498. {
  499. LobbyPlayer p = lobbySlots[i] as LobbyPlayer;
  500.  
  501. if (p != null)
  502. {
  503. p.RpcUpdateRemoveButton();
  504. p.ToggleJoinButton(numPlayers + 1 >= minPlayers);
  505. }
  506. }
  507. }
  508.  
  509. public override void OnLobbyServerDisconnect(NetworkConnection conn)
  510. {
  511. for (int i = 0; i < lobbySlots.Length; ++i)
  512. {
  513. LobbyPlayer p = lobbySlots[i] as LobbyPlayer;
  514.  
  515. if (p != null)
  516. {
  517. p.RpcUpdateRemoveButton();
  518. p.ToggleJoinButton(numPlayers >= minPlayers);
  519. }
  520. }
  521.  
  522. }
  523.  
  524. public override bool OnLobbyServerSceneLoadedForPlayer(GameObject lobbyPlayer, GameObject gamePlayer)
  525. {
  526. //This hook allows you to apply state data from the lobby-player to the game-player
  527. //just subclass "LobbyHook" and add it to the lobby object.
  528.  
  529. if (_lobbyHooks)
  530. _lobbyHooks.OnLobbyServerSceneLoadedForPlayer(this, lobbyPlayer, gamePlayer);
  531.  
  532. return true;
  533. }
  534.  
  535. // --- Countdown management
  536.  
  537. public override void OnLobbyServerPlayersReady()
  538. {
  539. bool allready = true;
  540. for (int i = 0; i < lobbySlots.Length; ++i)
  541. {
  542. if (lobbySlots[i] != null)
  543. allready &= lobbySlots[i].readyToBegin;
  544. }
  545.  
  546. if (allready)
  547. StartCoroutine(ServerCountdownCoroutine());
  548. }
  549.  
  550. public IEnumerator ServerCountdownCoroutine()
  551. {
  552. float remainingTime = prematchCountdown;
  553. int floorTime = Mathf.FloorToInt(remainingTime);
  554.  
  555. while (remainingTime > 0)
  556. {
  557. yield return null;
  558.  
  559. remainingTime -= Time.deltaTime;
  560. int newFloorTime = Mathf.FloorToInt(remainingTime);
  561.  
  562. if (newFloorTime != floorTime)
  563. {//to avoid flooding the network of message, we only send a notice to client when the number of plain seconds change.
  564. floorTime = newFloorTime;
  565.  
  566. for (int i = 0; i < lobbySlots.Length; ++i)
  567. {
  568. if (lobbySlots[i] != null)
  569. {//there is maxPlayer slots, so some could be == null, need to test it before accessing!
  570. (lobbySlots[i] as LobbyPlayer).RpcUpdateCountdown(floorTime);
  571. }
  572. }
  573. }
  574. }
  575.  
  576. for (int i = 0; i < lobbySlots.Length; ++i)
  577. {
  578. if (lobbySlots[i] != null)
  579. {
  580. (lobbySlots[i] as LobbyPlayer).RpcUpdateCountdown(0);
  581. }
  582. }
  583.  
  584. ServerChangeScene(playScene);
  585. }
  586.  
  587. // ----------------- Client callbacks ------------------
  588.  
  589. public override void OnClientConnect(NetworkConnection conn)
  590. {
  591. base.OnClientConnect(conn);
  592.  
  593. infoPanel.gameObject.SetActive(false);
  594.  
  595. conn.RegisterHandler(MsgKicked, KickedMessageHandler);
  596.  
  597. if (!NetworkServer.active)
  598. {//only to do on pure client (not self hosting client)
  599. ChangeTo(lobbyPanel);
  600. backDelegate = StopClientClbk;
  601. SetServerInfo("Client", networkAddress);
  602. }
  603. }
  604.  
  605.  
  606. public override void OnClientDisconnect(NetworkConnection conn)
  607. {
  608. base.OnClientDisconnect(conn);
  609. ChangeTo(mainMenuPanel);
  610. }
  611.  
  612. public override void OnClientError(NetworkConnection conn, int errorCode)
  613. {
  614. ChangeTo(mainMenuPanel);
  615. //infoPanel.Display("Cient error : " + (errorCode == 6 ? "timeout" : errorCode.ToString()), "Close", null);
  616. }
  617. }
  618. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement