Chat.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. //
  2. // Copyright (c) 2008-2020 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include <Urho3D/Audio/Audio.h>
  23. #include <Urho3D/Audio/Sound.h>
  24. #include <Urho3D/Engine/Engine.h>
  25. #include <Urho3D/Graphics/Graphics.h>
  26. #include <Urho3D/Graphics/Zone.h>
  27. #include <Urho3D/Input/Input.h>
  28. #include <Urho3D/IO/IOEvents.h>
  29. #include <Urho3D/IO/Log.h>
  30. #include <Urho3D/IO/MemoryBuffer.h>
  31. #include <Urho3D/IO/VectorBuffer.h>
  32. #include <Urho3D/Network/Network.h>
  33. #include <Urho3D/Network/NetworkEvents.h>
  34. #include <Urho3D/Resource/ResourceCache.h>
  35. #include <Urho3D/Scene/Scene.h>
  36. #include <Urho3D/UI/Button.h>
  37. #include <Urho3D/UI/Font.h>
  38. #include <Urho3D/UI/LineEdit.h>
  39. #include <Urho3D/UI/Text.h>
  40. #include <Urho3D/UI/UI.h>
  41. #include <Urho3D/UI/UIEvents.h>
  42. #include "Chat.h"
  43. #include <Urho3D/DebugNew.h>
  44. // Undefine Windows macro, as our Connection class has a function called SendMessage
  45. #ifdef SendMessage
  46. #undef SendMessage
  47. #endif
  48. // Identifier for the chat network messages
  49. const int MSG_CHAT = 154;
  50. // UDP port we will use
  51. const unsigned short CHAT_SERVER_PORT = 2345;
  52. URHO3D_DEFINE_APPLICATION_MAIN(Chat)
  53. Chat::Chat(Context* context) :
  54. Sample(context)
  55. {
  56. }
  57. void Chat::Start()
  58. {
  59. // Execute base class startup
  60. Sample::Start();
  61. // Enable OS cursor
  62. GetSubsystem<Input>()->SetMouseVisible(true);
  63. // Create the user interface
  64. CreateUI();
  65. // Subscribe to UI and network events
  66. SubscribeToEvents();
  67. // Set the mouse mode to use in the sample
  68. Sample::InitMouseMode(MM_FREE);
  69. }
  70. void Chat::CreateUI()
  71. {
  72. SetLogoVisible(false); // We need the full rendering window
  73. auto* graphics = GetSubsystem<Graphics>();
  74. UIElement* root = GetSubsystem<UI>()->GetRoot();
  75. auto* cache = GetSubsystem<ResourceCache>();
  76. auto* uiStyle = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");
  77. // Set style to the UI root so that elements will inherit it
  78. root->SetDefaultStyle(uiStyle);
  79. auto* font = cache->GetResource<Font>("Fonts/Anonymous Pro.ttf");
  80. chatHistoryText_ = root->CreateChild<Text>();
  81. chatHistoryText_->SetFont(font, 12);
  82. buttonContainer_ = root->CreateChild<UIElement>();
  83. buttonContainer_->SetFixedSize(graphics->GetWidth(), 20);
  84. buttonContainer_->SetPosition(0, graphics->GetHeight() - 20);
  85. buttonContainer_->SetLayoutMode(LM_HORIZONTAL);
  86. textEdit_ = buttonContainer_->CreateChild<LineEdit>();
  87. textEdit_->SetStyleAuto();
  88. sendButton_ = CreateButton("Send", 70);
  89. connectButton_ = CreateButton("Connect", 90);
  90. disconnectButton_ = CreateButton("Disconnect", 100);
  91. startServerButton_ = CreateButton("Start Server", 110);
  92. UpdateButtons();
  93. float rowHeight = chatHistoryText_->GetRowHeight();
  94. // Row height would be zero if the font failed to load
  95. if (rowHeight)
  96. {
  97. float numberOfRows = (graphics->GetHeight() - 100) / rowHeight;
  98. chatHistory_.Resize(static_cast<unsigned int>(numberOfRows));
  99. }
  100. // No viewports or scene is defined. However, the default zone's fog color controls the fill color
  101. GetSubsystem<Renderer>()->GetDefaultZone()->SetFogColor(Color(0.0f, 0.0f, 0.1f));
  102. }
  103. void Chat::SubscribeToEvents()
  104. {
  105. // Subscribe to UI element events
  106. SubscribeToEvent(textEdit_, E_TEXTFINISHED, URHO3D_HANDLER(Chat, HandleSend));
  107. SubscribeToEvent(sendButton_, E_RELEASED, URHO3D_HANDLER(Chat, HandleSend));
  108. SubscribeToEvent(connectButton_, E_RELEASED, URHO3D_HANDLER(Chat, HandleConnect));
  109. SubscribeToEvent(disconnectButton_, E_RELEASED, URHO3D_HANDLER(Chat, HandleDisconnect));
  110. SubscribeToEvent(startServerButton_, E_RELEASED, URHO3D_HANDLER(Chat, HandleStartServer));
  111. // Subscribe to log messages so that we can pipe them to the chat window
  112. SubscribeToEvent(E_LOGMESSAGE, URHO3D_HANDLER(Chat, HandleLogMessage));
  113. // Subscribe to network events
  114. SubscribeToEvent(E_NETWORKMESSAGE, URHO3D_HANDLER(Chat, HandleNetworkMessage));
  115. SubscribeToEvent(E_SERVERCONNECTED, URHO3D_HANDLER(Chat, HandleConnectionStatus));
  116. SubscribeToEvent(E_SERVERDISCONNECTED, URHO3D_HANDLER(Chat, HandleConnectionStatus));
  117. SubscribeToEvent(E_CONNECTFAILED, URHO3D_HANDLER(Chat, HandleConnectionStatus));
  118. }
  119. Button* Chat::CreateButton(const String& text, int width)
  120. {
  121. auto* cache = GetSubsystem<ResourceCache>();
  122. auto* font = cache->GetResource<Font>("Fonts/Anonymous Pro.ttf");
  123. auto* button = buttonContainer_->CreateChild<Button>();
  124. button->SetStyleAuto();
  125. button->SetFixedWidth(width);
  126. auto* buttonText = button->CreateChild<Text>();
  127. buttonText->SetFont(font, 12);
  128. buttonText->SetAlignment(HA_CENTER, VA_CENTER);
  129. buttonText->SetText(text);
  130. return button;
  131. }
  132. void Chat::ShowChatText(const String& row)
  133. {
  134. chatHistory_.Erase(0);
  135. chatHistory_.Push(row);
  136. // Concatenate all the rows in history
  137. String allRows;
  138. for (unsigned i = 0; i < chatHistory_.Size(); ++i)
  139. allRows += chatHistory_[i] + "\n";
  140. chatHistoryText_->SetText(allRows);
  141. }
  142. void Chat::UpdateButtons()
  143. {
  144. auto* network = GetSubsystem<Network>();
  145. Connection* serverConnection = network->GetServerConnection();
  146. bool serverRunning = network->IsServerRunning();
  147. // Show and hide buttons so that eg. Connect and Disconnect are never shown at the same time
  148. sendButton_->SetVisible(serverConnection != nullptr);
  149. connectButton_->SetVisible(!serverConnection && !serverRunning);
  150. disconnectButton_->SetVisible(serverConnection || serverRunning);
  151. startServerButton_->SetVisible(!serverConnection && !serverRunning);
  152. }
  153. void Chat::HandleLogMessage(StringHash /*eventType*/, VariantMap& eventData)
  154. {
  155. using namespace LogMessage;
  156. ShowChatText(eventData[P_MESSAGE].GetString());
  157. }
  158. void Chat::HandleSend(StringHash /*eventType*/, VariantMap& eventData)
  159. {
  160. String text = textEdit_->GetText();
  161. if (text.Empty())
  162. return; // Do not send an empty message
  163. auto* network = GetSubsystem<Network>();
  164. Connection* serverConnection = network->GetServerConnection();
  165. if (serverConnection)
  166. {
  167. // A VectorBuffer object is convenient for constructing a message to send
  168. VectorBuffer msg;
  169. msg.WriteString(text);
  170. // Send the chat message as in-order and reliable
  171. serverConnection->SendMessage(MSG_CHAT, true, true, msg);
  172. // Empty the text edit after sending
  173. textEdit_->SetText(String::EMPTY);
  174. }
  175. }
  176. void Chat::HandleConnect(StringHash /*eventType*/, VariantMap& eventData)
  177. {
  178. auto* network = GetSubsystem<Network>();
  179. String address = textEdit_->GetText().Trimmed();
  180. if (address.Empty())
  181. address = "localhost"; // Use localhost to connect if nothing else specified
  182. // Empty the text edit after reading the address to connect to
  183. textEdit_->SetText(String::EMPTY);
  184. // Connect to server, do not specify a client scene as we are not using scene replication, just messages.
  185. // At connect time we could also send identity parameters (such as username) in a VariantMap, but in this
  186. // case we skip it for simplicity
  187. network->Connect(address, CHAT_SERVER_PORT, nullptr);
  188. UpdateButtons();
  189. }
  190. void Chat::HandleDisconnect(StringHash /*eventType*/, VariantMap& eventData)
  191. {
  192. auto* network = GetSubsystem<Network>();
  193. Connection* serverConnection = network->GetServerConnection();
  194. // If we were connected to server, disconnect
  195. if (serverConnection)
  196. serverConnection->Disconnect();
  197. // Or if we were running a server, stop it
  198. else if (network->IsServerRunning())
  199. network->StopServer();
  200. UpdateButtons();
  201. }
  202. void Chat::HandleStartServer(StringHash /*eventType*/, VariantMap& eventData)
  203. {
  204. auto* network = GetSubsystem<Network>();
  205. network->StartServer(CHAT_SERVER_PORT);
  206. UpdateButtons();
  207. }
  208. void Chat::HandleNetworkMessage(StringHash /*eventType*/, VariantMap& eventData)
  209. {
  210. auto* network = GetSubsystem<Network>();
  211. using namespace NetworkMessage;
  212. int msgID = eventData[P_MESSAGEID].GetInt();
  213. if (msgID == MSG_CHAT)
  214. {
  215. const PODVector<unsigned char>& data = eventData[P_DATA].GetBuffer();
  216. // Use a MemoryBuffer to read the message data so that there is no unnecessary copying
  217. MemoryBuffer msg(data);
  218. String text = msg.ReadString();
  219. // If we are the server, prepend the sender's IP address and port and echo to everyone
  220. // If we are a client, just display the message
  221. if (network->IsServerRunning())
  222. {
  223. auto* sender = static_cast<Connection*>(eventData[P_CONNECTION].GetPtr());
  224. text = sender->ToString() + " " + text;
  225. VectorBuffer sendMsg;
  226. sendMsg.WriteString(text);
  227. // Broadcast as in-order and reliable
  228. network->BroadcastMessage(MSG_CHAT, true, true, sendMsg);
  229. }
  230. ShowChatText(text);
  231. }
  232. }
  233. void Chat::HandleConnectionStatus(StringHash /*eventType*/, VariantMap& eventData)
  234. {
  235. UpdateButtons();
  236. }