Chat.cpp 10.0 KB

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