Chat.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. //
  2. // Copyright (c) 2008-2013 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 "Audio.h"
  23. #include "Button.h"
  24. #include "Engine.h"
  25. #include "Font.h"
  26. #include "Graphics.h"
  27. #include "Input.h"
  28. #include "IOEvents.h"
  29. #include "LineEdit.h"
  30. #include "Log.h"
  31. #include "MemoryBuffer.h"
  32. #include "Network.h"
  33. #include "NetworkEvents.h"
  34. #include "ResourceCache.h"
  35. #include "Scene.h"
  36. #include "Sound.h"
  37. #include "Text.h"
  38. #include "UI.h"
  39. #include "UIEvents.h"
  40. #include "VectorBuffer.h"
  41. #include "Zone.h"
  42. #include "Chat.h"
  43. #include "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. // Expands to this example's entry-point
  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. chatHistory_.Resize((graphics->GetHeight() - 20) / chatHistoryText_->GetRowHeight());
  93. // No viewports or scene is defined. However, the default zone's fog color controls the fill color
  94. GetSubsystem<Renderer>()->GetDefaultZone()->SetFogColor(Color(0.0f, 0.0f, 0.1f));
  95. }
  96. void Chat::SubscribeToEvents()
  97. {
  98. // Subscribe to UI element events
  99. SubscribeToEvent(textEdit_, E_TEXTFINISHED, HANDLER(Chat, HandleSend));
  100. SubscribeToEvent(sendButton_, E_RELEASED, HANDLER(Chat, HandleSend));
  101. SubscribeToEvent(connectButton_, E_RELEASED, HANDLER(Chat, HandleConnect));
  102. SubscribeToEvent(disconnectButton_, E_RELEASED, HANDLER(Chat, HandleDisconnect));
  103. SubscribeToEvent(startServerButton_, E_RELEASED, HANDLER(Chat, HandleStartServer));
  104. // Subscribe to log messages so that we can pipe them to the chat window
  105. SubscribeToEvent(E_LOGMESSAGE, HANDLER(Chat, HandleLogMessage));
  106. // Subscribe to network events
  107. SubscribeToEvent(E_NETWORKMESSAGE, HANDLER(Chat, HandleNetworkMessage));
  108. SubscribeToEvent(E_SERVERCONNECTED, HANDLER(Chat, HandleConnectionStatus));
  109. SubscribeToEvent(E_SERVERDISCONNECTED, HANDLER(Chat, HandleConnectionStatus));
  110. SubscribeToEvent(E_CONNECTFAILED, HANDLER(Chat, HandleConnectionStatus));
  111. }
  112. Button* Chat::CreateButton(const String& text, int width)
  113. {
  114. ResourceCache* cache = GetSubsystem<ResourceCache>();
  115. Font* font = cache->GetResource<Font>("Fonts/Anonymous Pro.ttf");
  116. Button* button = buttonContainer_->CreateChild<Button>();
  117. button->SetStyleAuto();
  118. button->SetFixedWidth(width);
  119. Text* buttonText = button->CreateChild<Text>();
  120. buttonText->SetFont(font, 12);
  121. buttonText->SetAlignment(HA_CENTER, VA_CENTER);
  122. buttonText->SetText(text);
  123. return button;
  124. }
  125. void Chat::ShowChatText(const String& row)
  126. {
  127. chatHistory_.Erase(0);
  128. chatHistory_.Push(row);
  129. // Concatenate all the rows in history
  130. String allRows;
  131. for (unsigned i = 0; i < chatHistory_.Size(); ++i)
  132. allRows += chatHistory_[i] + "\n";
  133. chatHistoryText_->SetText(allRows);
  134. }
  135. void Chat::UpdateButtons()
  136. {
  137. Network* network = GetSubsystem<Network>();
  138. Connection* serverConnection = network->GetServerConnection();
  139. bool serverRunning = network->IsServerRunning();
  140. // Show and hide buttons so that eg. Connect and Disconnect are never shown at the same time
  141. sendButton_->SetVisible(serverConnection != 0);
  142. connectButton_->SetVisible(!serverConnection && !serverRunning);
  143. disconnectButton_->SetVisible(serverConnection || serverRunning);
  144. startServerButton_->SetVisible(!serverConnection && !serverRunning);
  145. }
  146. void Chat::HandleLogMessage(StringHash eventType, VariantMap& eventData)
  147. {
  148. using namespace LogMessage;
  149. ShowChatText(eventData[P_MESSAGE].GetString());
  150. }
  151. void Chat::HandleSend(StringHash eventType, VariantMap& eventData)
  152. {
  153. String text = textEdit_->GetText();
  154. if (text.Empty())
  155. return; // Do not send an empty message
  156. Network* network = GetSubsystem<Network>();
  157. Connection* serverConnection = network->GetServerConnection();
  158. if (serverConnection)
  159. {
  160. // A VectorBuffer object is convenient for constructing a message to send
  161. VectorBuffer msg;
  162. msg.WriteString(text);
  163. // Send the chat message as in-order and reliable
  164. serverConnection->SendMessage(MSG_CHAT, true, true, msg);
  165. // Empty the text edit after sending
  166. textEdit_->SetText(String::EMPTY);
  167. }
  168. }
  169. void Chat::HandleConnect(StringHash eventType, VariantMap& eventData)
  170. {
  171. Network* network = GetSubsystem<Network>();
  172. String address = textEdit_->GetText().Trimmed();
  173. if (address.Empty())
  174. address = "localhost"; // Use localhost to connect if nothing else specified
  175. // Empty the text edit after reading the address to connect to
  176. textEdit_->SetText(String::EMPTY);
  177. // Connect to server, do not specify a client scene as we are not using scene replication, just messages.
  178. // At connect time we could also send identity parameters (such as username) in a VariantMap, but in this
  179. // case we skip it for simplicity
  180. network->Connect(address, CHAT_SERVER_PORT, 0);
  181. UpdateButtons();
  182. }
  183. void Chat::HandleDisconnect(StringHash eventType, VariantMap& eventData)
  184. {
  185. Network* network = GetSubsystem<Network>();
  186. Connection* serverConnection = network->GetServerConnection();
  187. // If we were connected to server, disconnect
  188. if (serverConnection)
  189. serverConnection->Disconnect();
  190. // Or if we were running a server, stop it
  191. else if (network->IsServerRunning())
  192. network->StopServer();
  193. UpdateButtons();
  194. }
  195. void Chat::HandleStartServer(StringHash eventType, VariantMap& eventData)
  196. {
  197. Network* network = GetSubsystem<Network>();
  198. network->StartServer(CHAT_SERVER_PORT);
  199. UpdateButtons();
  200. }
  201. void Chat::HandleNetworkMessage(StringHash eventType, VariantMap& eventData)
  202. {
  203. Network* network = GetSubsystem<Network>();
  204. using namespace NetworkMessage;
  205. int msgID = eventData[P_MESSAGEID].GetInt();
  206. if (msgID == MSG_CHAT)
  207. {
  208. const PODVector<unsigned char>& data = eventData[P_DATA].GetBuffer();
  209. // Use a MemoryBuffer to read the message data so that there is no unnecessary copying
  210. MemoryBuffer msg(data);
  211. String text = msg.ReadString();
  212. // If we are the server, prepend the sender's IP address and port and echo to everyone
  213. // If we are a client, just display the message
  214. if (network->IsServerRunning())
  215. {
  216. Connection* sender = (Connection*)eventData[P_CONNECTION].GetPtr();
  217. text = sender->ToString() + " " + text;
  218. VectorBuffer sendMsg;
  219. sendMsg.WriteString(text);
  220. // Broadcast as in-order and reliable
  221. network->BroadcastMessage(MSG_CHAT, true, true, sendMsg);
  222. }
  223. ShowChatText(text);
  224. }
  225. }
  226. void Chat::HandleConnectionStatus(StringHash eventType, VariantMap& eventData)
  227. {
  228. UpdateButtons();
  229. }