Chat.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. //
  2. // Copyright (c) 2008-2015 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 = 32;
  50. // UDP port we will use
  51. const unsigned short CHAT_SERVER_PORT = 2345;
  52. 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. }
  68. void Chat::CreateUI()
  69. {
  70. SetLogoVisible(false); // We need the full rendering window
  71. Graphics* graphics = GetSubsystem<Graphics>();
  72. UIElement* root = GetSubsystem<UI>()->GetRoot();
  73. ResourceCache* cache = GetSubsystem<ResourceCache>();
  74. XMLFile* uiStyle = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");
  75. // Set style to the UI root so that elements will inherit it
  76. root->SetDefaultStyle(uiStyle);
  77. Font* font = cache->GetResource<Font>("Fonts/Anonymous Pro.ttf");
  78. chatHistoryText_ = root->CreateChild<Text>();
  79. chatHistoryText_->SetFont(font, 12);
  80. buttonContainer_ = root->CreateChild<UIElement>();
  81. buttonContainer_->SetFixedSize(graphics->GetWidth(), 20);
  82. buttonContainer_->SetPosition(0, graphics->GetHeight() - 20);
  83. buttonContainer_->SetLayoutMode(LM_HORIZONTAL);
  84. textEdit_ = buttonContainer_->CreateChild<LineEdit>();
  85. textEdit_->SetStyleAuto();
  86. sendButton_ = CreateButton("Send", 70);
  87. connectButton_ = CreateButton("Connect", 90);
  88. disconnectButton_ = CreateButton("Disconnect", 100);
  89. startServerButton_ = CreateButton("Start Server", 110);
  90. UpdateButtons();
  91. int rowHeight = chatHistoryText_->GetRowHeight();
  92. // Row height would be zero if the font failed to load
  93. if (rowHeight)
  94. chatHistory_.Resize((graphics->GetHeight() - 20) / rowHeight);
  95. // No viewports or scene is defined. However, the default zone's fog color controls the fill color
  96. GetSubsystem<Renderer>()->GetDefaultZone()->SetFogColor(Color(0.0f, 0.0f, 0.1f));
  97. }
  98. void Chat::SubscribeToEvents()
  99. {
  100. // Subscribe to UI element events
  101. SubscribeToEvent(textEdit_, E_TEXTFINISHED, URHO3D_HANDLER(Chat, HandleSend));
  102. SubscribeToEvent(sendButton_, E_RELEASED, URHO3D_HANDLER(Chat, HandleSend));
  103. SubscribeToEvent(connectButton_, E_RELEASED, URHO3D_HANDLER(Chat, HandleConnect));
  104. SubscribeToEvent(disconnectButton_, E_RELEASED, URHO3D_HANDLER(Chat, HandleDisconnect));
  105. SubscribeToEvent(startServerButton_, E_RELEASED, URHO3D_HANDLER(Chat, HandleStartServer));
  106. // Subscribe to log messages so that we can pipe them to the chat window
  107. SubscribeToEvent(E_LOGMESSAGE, URHO3D_HANDLER(Chat, HandleLogMessage));
  108. // Subscribe to network events
  109. SubscribeToEvent(E_NETWORKMESSAGE, URHO3D_HANDLER(Chat, HandleNetworkMessage));
  110. SubscribeToEvent(E_SERVERCONNECTED, URHO3D_HANDLER(Chat, HandleConnectionStatus));
  111. SubscribeToEvent(E_SERVERDISCONNECTED, URHO3D_HANDLER(Chat, HandleConnectionStatus));
  112. SubscribeToEvent(E_CONNECTFAILED, URHO3D_HANDLER(Chat, HandleConnectionStatus));
  113. }
  114. Button* Chat::CreateButton(const String& text, int width)
  115. {
  116. ResourceCache* cache = GetSubsystem<ResourceCache>();
  117. Font* font = cache->GetResource<Font>("Fonts/Anonymous Pro.ttf");
  118. Button* button = buttonContainer_->CreateChild<Button>();
  119. button->SetStyleAuto();
  120. button->SetFixedWidth(width);
  121. Text* buttonText = button->CreateChild<Text>();
  122. buttonText->SetFont(font, 12);
  123. buttonText->SetAlignment(HA_CENTER, VA_CENTER);
  124. buttonText->SetText(text);
  125. return button;
  126. }
  127. void Chat::ShowChatText(const String& row)
  128. {
  129. chatHistory_.Erase(0);
  130. chatHistory_.Push(row);
  131. // Concatenate all the rows in history
  132. String allRows;
  133. for (unsigned i = 0; i < chatHistory_.Size(); ++i)
  134. allRows += chatHistory_[i] + "\n";
  135. chatHistoryText_->SetText(allRows);
  136. }
  137. void Chat::UpdateButtons()
  138. {
  139. Network* network = GetSubsystem<Network>();
  140. Connection* serverConnection = network->GetServerConnection();
  141. bool serverRunning = network->IsServerRunning();
  142. // Show and hide buttons so that eg. Connect and Disconnect are never shown at the same time
  143. sendButton_->SetVisible(serverConnection != 0);
  144. connectButton_->SetVisible(!serverConnection && !serverRunning);
  145. disconnectButton_->SetVisible(serverConnection || serverRunning);
  146. startServerButton_->SetVisible(!serverConnection && !serverRunning);
  147. }
  148. void Chat::HandleLogMessage(StringHash eventType, VariantMap& eventData)
  149. {
  150. using namespace LogMessage;
  151. ShowChatText(eventData[P_MESSAGE].GetString());
  152. }
  153. void Chat::HandleSend(StringHash eventType, VariantMap& eventData)
  154. {
  155. String text = textEdit_->GetText();
  156. if (text.Empty())
  157. return; // Do not send an empty message
  158. Network* network = GetSubsystem<Network>();
  159. Connection* serverConnection = network->GetServerConnection();
  160. if (serverConnection)
  161. {
  162. // A VectorBuffer object is convenient for constructing a message to send
  163. VectorBuffer msg;
  164. msg.WriteString(text);
  165. // Send the chat message as in-order and reliable
  166. serverConnection->SendMessage(MSG_CHAT, true, true, msg);
  167. // Empty the text edit after sending
  168. textEdit_->SetText(String::EMPTY);
  169. }
  170. }
  171. void Chat::HandleConnect(StringHash eventType, VariantMap& eventData)
  172. {
  173. Network* network = GetSubsystem<Network>();
  174. String address = textEdit_->GetText().Trimmed();
  175. if (address.Empty())
  176. address = "localhost"; // Use localhost to connect if nothing else specified
  177. // Empty the text edit after reading the address to connect to
  178. textEdit_->SetText(String::EMPTY);
  179. // Connect to server, do not specify a client scene as we are not using scene replication, just messages.
  180. // At connect time we could also send identity parameters (such as username) in a VariantMap, but in this
  181. // case we skip it for simplicity
  182. network->Connect(address, CHAT_SERVER_PORT, 0);
  183. UpdateButtons();
  184. }
  185. void Chat::HandleDisconnect(StringHash eventType, VariantMap& eventData)
  186. {
  187. Network* network = GetSubsystem<Network>();
  188. Connection* serverConnection = network->GetServerConnection();
  189. // If we were connected to server, disconnect
  190. if (serverConnection)
  191. serverConnection->Disconnect();
  192. // Or if we were running a server, stop it
  193. else if (network->IsServerRunning())
  194. network->StopServer();
  195. UpdateButtons();
  196. }
  197. void Chat::HandleStartServer(StringHash eventType, VariantMap& eventData)
  198. {
  199. Network* network = GetSubsystem<Network>();
  200. network->StartServer(CHAT_SERVER_PORT);
  201. UpdateButtons();
  202. }
  203. void Chat::HandleNetworkMessage(StringHash eventType, VariantMap& eventData)
  204. {
  205. Network* network = GetSubsystem<Network>();
  206. using namespace NetworkMessage;
  207. int msgID = eventData[P_MESSAGEID].GetInt();
  208. if (msgID == MSG_CHAT)
  209. {
  210. const PODVector<unsigned char>& data = eventData[P_DATA].GetBuffer();
  211. // Use a MemoryBuffer to read the message data so that there is no unnecessary copying
  212. MemoryBuffer msg(data);
  213. String text = msg.ReadString();
  214. // If we are the server, prepend the sender's IP address and port and echo to everyone
  215. // If we are a client, just display the message
  216. if (network->IsServerRunning())
  217. {
  218. Connection* sender = static_cast<Connection*>(eventData[P_CONNECTION].GetPtr());
  219. text = sender->ToString() + " " + text;
  220. VectorBuffer sendMsg;
  221. sendMsg.WriteString(text);
  222. // Broadcast as in-order and reliable
  223. network->BroadcastMessage(MSG_CHAT, true, true, sendMsg);
  224. }
  225. ShowChatText(text);
  226. }
  227. }
  228. void Chat::HandleConnectionStatus(StringHash eventType, VariantMap& eventData)
  229. {
  230. UpdateButtons();
  231. }