InGameMenuEvents.cs 11.1 KB
Newer Older
cann-alberto's avatar
cann-alberto committed
1
2
3
4
5
6
using kcp2k;
using Mirror;
using ReadyPlayerMe.Samples.QuickStart;
using System;
using System.Collections;
using System.Diagnostics;
cann-alberto's avatar
cann-alberto committed
7
using System.Runtime.InteropServices.WindowsRuntime;
cann-alberto's avatar
cann-alberto committed
8
9
using UnityEngine;
using UnityEngine.UIElements;
cann-alberto's avatar
cann-alberto committed
10
using static UnityEngine.UIElements.UxmlAttributeDescription;
cann-alberto's avatar
cann-alberto committed
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

public class InGameMenuEvents : MonoBehaviour
{
    private UIDocument _document;
    private VisualElement _inGameMenuVisualElem;
    private Button _buttonMMSend;
    private Button _buttonCreateRoom;
    private Button _buttonMenu;
    private Label _messageLabel;

    private PlayerTracker _playerTracker;    
    public NetworkManager networkManager;
    public KcpTransport transport;
    public CameraOrbit cameraOrbit;

    private Process _serverProcess;
    private ThirdPersonControllerNetworked _thirdPersonControllerNetworked;        

    void Awake()
    {        
        _document = GetComponent<UIDocument>();
        var root = _document.rootVisualElement;
        
        _buttonMenu = _document.rootVisualElement.Q("MenuButton") as Button;
        _buttonMenu.RegisterCallback<ClickEvent>(OnMenuButtonClicked);

        _inGameMenuVisualElem = root.Q("InGameMenuPanel") as VisualElement;
        _inGameMenuVisualElem.style.visibility = UnityEngine.UIElements.Visibility.Hidden;

        _buttonMMSend = _document.rootVisualElement.Q("MMSendButton") as Button;
        _buttonMMSend.RegisterCallback<ClickEvent>(OnMMSendButtonClicked);

        _buttonCreateRoom = root.Q("CreateRoomButton") as Button;
        _buttonCreateRoom.RegisterCallback<ClickEvent>(OnCreateRoomButtonClicked);

        _messageLabel = _document.rootVisualElement.Q("ChatTextLabel") as Label;
        GameManager.Instance.ServerSocket.OnMessageReceived += UpdateMessageLabel;

    }

    private void OnMenuButtonClicked(ClickEvent evt)
    {
        if (_inGameMenuVisualElem != null)
        {
            _thirdPersonControllerNetworked = NetworkClient.localPlayer.GetComponent<ThirdPersonControllerNetworked>();

            if (_inGameMenuVisualElem.style.visibility.Equals(UnityEngine.UIElements.Visibility.Visible))
            {                
                _inGameMenuVisualElem.style.visibility = UnityEngine.UIElements.Visibility.Hidden;
                cameraOrbit.enabled = true;                
                _thirdPersonControllerNetworked.inputEnabled = true;
            }
            else
            {
                _inGameMenuVisualElem.style.visibility = UnityEngine.UIElements.Visibility.Visible;
                cameraOrbit.enabled = false;
                _thirdPersonControllerNetworked.inputEnabled = false;
            }
        }
    }
    
    void UpdateMessageLabel(MessageInfo message)
    {
        if (_messageLabel != null)
        {
            //Split the string by newlines
            string[] lines = _messageLabel.text.Split("\n", StringSplitOptions.RemoveEmptyEntries);
            
            //Remove the first line
            if (lines.Length > 10)
            {
cann-alberto's avatar
cann-alberto committed
82
                lines = new ArraySegment<string>(lines, 1, lines.Length - 1).ToArray();                
cann-alberto's avatar
cann-alberto committed
83
84
85
86
87
88
            }

            // Add a new line
            string[] updatedLines = new string[lines.Length + 1];
            Array.Copy(lines, updatedLines, lines.Length);
            updatedLines[updatedLines.Length - 1] = 
cann-alberto's avatar
cann-alberto committed
89
                "[" + message.time + "] "+ message.source + " : " + message.body + "\n";
cann-alberto's avatar
cann-alberto committed
90
91
92
93
94
95
96
97

            // Join the lines back with newlines and print the result
            _messageLabel.text = string.Join("\n", updatedLines);            
        }
    }



cann-alberto's avatar
cann-alberto committed
98
99

    #region MM-SEND
cann-alberto's avatar
cann-alberto committed
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
    private void OnMMSendButtonClicked(ClickEvent evt)
    {
        VisualElement sendMsgVisualElement = _document.rootVisualElement.Q("SendMsgVisualElement") as VisualElement;
        Button sendMsgButton = _document.rootVisualElement.Q("SendMessageButton") as Button;

        if (sendMsgVisualElement.style.display.Equals(UnityEngine.UIElements.DisplayStyle.Flex))
        {
            sendMsgVisualElement.style.display = UnityEngine.UIElements.DisplayStyle.None;
            sendMsgButton.UnregisterCallback<ClickEvent>(SendMsg);
        }

        else
        {
            sendMsgVisualElement.style.display= UnityEngine.UIElements.DisplayStyle.Flex;
            sendMsgButton.RegisterCallback<ClickEvent>(SendMsg);
        }
        
    }

    private void SendMsg(ClickEvent evt)
    {
cann-alberto's avatar
cann-alberto committed
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
        

        TextField toTextField = _document.rootVisualElement.Q<TextField>("toTextField");
        TextField msgTextField = _document.rootVisualElement.Q<TextField>("msgTextField");

        if (toTextField == null || msgTextField == null)
        {
            UnityEngine.Debug.LogError("Input fields not found.");
            return;
        }


        // Retrieve comInfo by humanID
        UnityEngine.Debug.Log("S-Process: User1;\nAction: MM-Send;\nS-Compl: Message;\nD-Process: ACSrvc"); //User1 checks User2s whereabout
        StartCoroutine(RetrieveComInfo(toTextField.value, (comInfo) =>
        {
            if (string.IsNullOrEmpty(comInfo))
            {
                UnityEngine.Debug.LogError("Failed to retrieve communication info.");
                return;
            }

            // Send the message
            UnityEngine.Debug.Log("S-Process: User1;\nAction: MM-Send;\nS-Compl: Message;\nD-Process: To User2");// User1 sends a message to User2
            UnityEngine.Debug.Log("after" + comInfo);
            string actionDataJson = CreateMessageJson(comInfo, msgTextField.value);
            StartCoroutine(GameManager.Instance.WebAPIManager.Upload("Communication/messages", actionDataJson, HandleResponse));

            SendTextMessage(comInfo, actionDataJson);
            UnityEngine.Debug.Log("Message sent to " + comInfo);
cann-alberto's avatar
cann-alberto committed
151

cann-alberto's avatar
cann-alberto committed
152
153
            MessageInfo myMessage = new MessageInfo(DateTime.Now, GameManager.Instance.userID, comInfo, msgTextField.value);
            UpdateMessageLabel(myMessage);
cann-alberto's avatar
cann-alberto committed
154

cann-alberto's avatar
cann-alberto committed
155
156
157
158
159
160
161
            msgTextField.value = "";
        }));
    }

    private IEnumerator RetrieveComInfo(string humanID, Action<string> onCompleted)
    {
        User targetUser = null;
cann-alberto's avatar
cann-alberto committed
162

cann-alberto's avatar
cann-alberto committed
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
        yield return GameManager.Instance.WebAPIManager.GetRequest("Activity/user/humanid/" + humanID, (responseText) =>
        {
            if (!string.IsNullOrEmpty(responseText))
            {
                targetUser = JsonUtility.FromJson<User>(responseText);
            }
            else
            {
                UnityEngine.Debug.LogError("Error while retrieving the account.");
            }
        });
        
        if (targetUser == null)
        {
            UnityEngine.Debug.LogError("Account is null.");
            onCompleted?.Invoke(null);
            yield break;
        }
        UnityEngine.Debug.Log(targetUser.comIp);
        UnityEngine.Debug.Log(targetUser.comPort);
cann-alberto's avatar
cann-alberto committed
183

cann-alberto's avatar
cann-alberto committed
184
185
186
        string comInfo = targetUser.comIp + ":" + targetUser.comPort;
        UnityEngine.Debug.Log("before" + comInfo);
        onCompleted?.Invoke(comInfo);
cann-alberto's avatar
cann-alberto committed
187
188
189
190
    }

    private void HandleResponse(string response)
    {
cann-alberto's avatar
cann-alberto committed
191
        UnityEngine.Debug.Log("Received response: " + response); // Log the response received from the server        
cann-alberto's avatar
cann-alberto committed
192
193
194
195
    }

    private string CreateMessageJson(string toTextField, string msgTextField)
    {        
cann-alberto's avatar
cann-alberto committed
196
197
        string jsonData = "{" +            
            "\"body\": \"" + msgTextField + "\"," +
cann-alberto's avatar
cann-alberto committed
198
199
            "\"source\": \"" + GameManager.Instance.userID + "\"," +
            "\"destination\": \"" + toTextField + "\"," +
cann-alberto's avatar
cann-alberto committed
200
            "\"time\": \"" + DateTime.Now + "\"" +
cann-alberto's avatar
cann-alberto committed
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
            "}";
        return jsonData;
    }

    private void SendTextMessage(string toTextField, string msgTextField)
    {
        string[] parts = toTextField.Split(':');

        if (parts.Length == 2 && int.TryParse(parts[1], out int port))
        {
            string ipAddress = parts[0];
            // Start the connection process asynchronously and wait for it to finish
            StartCoroutine(ConnectAndSendMessage(ipAddress, port, msgTextField));            
        }
        else
        {
            UnityEngine.Debug.Log("Invalid input format.");
        }        
    }

    // Coroutine that waits for the connection to complete and then sends the message
    private IEnumerator ConnectAndSendMessage(string ipAddress, int port, string msgTextField)
    {
        // Start the connection process
        GameManager.Instance.ClientSocket.ConnectToServer(ipAddress, port);

        // Wait until the connection is successfully established
        while (GameManager.Instance.ClientSocket.client == null || !GameManager.Instance.ClientSocket.client.Connected)
        {
            yield return null; // Wait for one frame
        }

        // Once connected, send the message
        GameManager.Instance.ClientSocket.SendSocketMessage(msgTextField);
    }
cann-alberto's avatar
cann-alberto committed
236
    #endregion
cann-alberto's avatar
cann-alberto committed
237

cann-alberto's avatar
cann-alberto committed
238
    #region ROOM
cann-alberto's avatar
cann-alberto committed
239
    private void OnCreateRoomButtonClicked(ClickEvent evt)
cann-alberto's avatar
cann-alberto committed
240
    {      
cann-alberto's avatar
cann-alberto committed
241
242
243
244
245
246
247
248
        _playerTracker = GameManager.Instance.localPlayerPrefab.GetComponent<PlayerTracker>();

        if (_playerTracker == null)
        {
            UnityEngine.Debug.LogError("PlayerTracker not found in the local player.");
        }
        if (_playerTracker != null)
        {
cann-alberto's avatar
cann-alberto committed
249
250
251
252
253
254
255
256
257
258
259
260
261
            StartCoroutine(BuyAndCreateRoom(_playerTracker));                     
        }              
    }


    private IEnumerator BuyAndCreateRoom(PlayerTracker playerTracker)
    {
        // User buys the Parcel        
        bool isTransactSucces = false;
        string newTransact = CreateTransaction();
        UnityEngine.Debug.Log($"S-Process: User;\nAction: Transact; \nS-Compl: With Transaction;\nD-Process: User"); //User1 buys Parcel

        yield return GameManager.Instance.WebAPIManager.Upload("Transact/transaction", newTransact, (responseText) =>
cann-alberto's avatar
cann-alberto committed
262
        {
cann-alberto's avatar
cann-alberto committed
263
264
265
266
267
268
269
270
271
272
273
            if (responseText != null)
            {
                UnityEngine.Debug.Log("Transaction created successfully");                
                isTransactSucces = true;
            }
            else
            {
                UnityEngine.Debug.LogError("Error while creating the trasaction");
            }
        });
        if (!isTransactSucces) yield break;
cann-alberto's avatar
cann-alberto committed
274

cann-alberto's avatar
cann-alberto committed
275
276
277
        // Request to istantiate the room pref on the server
        _playerTracker.OnRoomInstantiated += HandleRoomInstantiated;
        _playerTracker.InstantiateRoomPrefab();
cann-alberto's avatar
cann-alberto committed
278
279
    }

cann-alberto's avatar
cann-alberto committed
280
281
    private void HandleRoomInstantiated()
    {                
cann-alberto's avatar
cann-alberto committed
282
283
284
285
286
        _playerTracker.OnRoomInstantiated -= HandleRoomInstantiated; // Unsubscribe to avoid memory leaks        
        // Activate the camera orbit script
        cameraOrbit.enabled = true;
    }

cann-alberto's avatar
cann-alberto committed
287
288
289
290
291
292
293
294
295
296
297
298
299
300
    private string CreateTransaction()
    {        
        string jsonData = "{" +
            " \"header\": \"MMM-ACC-V2.2\",  " +
            " \"mInstanceID\": \"MInstance00\",  " +
            " \"transactionData\": {" +
            "   \"assetID\": \" Asset00\", " +
            "   \"transactionTime\": \"" + DateTime.Now + "\"" +
            "},  " +
            "\"descrMetadata\": \"" + DateTime.Now + "\"}";        
        return jsonData;
    }
    #endregion

cann-alberto's avatar
cann-alberto committed
301
302
303
304
305
306
307
308
309
310
311
    void OnApplicationQuit()
    {
        if (_serverProcess != null && !_serverProcess.HasExited)
        {
            _serverProcess.Kill();
            _serverProcess.Dispose();
            UnityEngine.Debug.Log("Server process terminated.");
        }
    }
    
}