Hello3DUI.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #include <Urho3D/Core/CoreEvents.h>
  4. #include <Urho3D/Engine/Engine.h>
  5. #include <Urho3D/Graphics/Graphics.h>
  6. #include <Urho3D/Graphics/Model.h>
  7. #include <Urho3D/Graphics/Octree.h>
  8. #include <Urho3D/Graphics/StaticModel.h>
  9. #include <Urho3D/Graphics/Technique.h>
  10. #include <Urho3D/Graphics/Zone.h>
  11. #include <Urho3D/GraphicsAPI/Texture2D.h>
  12. #include <Urho3D/Input/Input.h>
  13. #include <Urho3D/Resource/ResourceCache.h>
  14. #include <Urho3D/UI/Button.h>
  15. #include <Urho3D/UI/CheckBox.h>
  16. #include <Urho3D/UI/LineEdit.h>
  17. #include <Urho3D/UI/ListView.h>
  18. #include <Urho3D/UI/Text.h>
  19. #include <Urho3D/UI/ToolTip.h>
  20. #include <Urho3D/UI/UI.h>
  21. #include <Urho3D/UI/UIComponent.h>
  22. #include <Urho3D/UI/UIEvents.h>
  23. #include <Urho3D/UI/Window.h>
  24. #include "Hello3DUI.h"
  25. #include <Urho3D/DebugNew.h>
  26. URHO3D_DEFINE_APPLICATION_MAIN(Hello3DUI)
  27. Hello3DUI::Hello3DUI(Context* context) :
  28. Sample(context),
  29. uiRoot_(GetSubsystem<UI>()->GetRoot()),
  30. dragBeginPosition_(IntVector2::ZERO),
  31. animateCube_(true),
  32. renderOnCube_(false),
  33. drawDebug_(false)
  34. {
  35. }
  36. void Hello3DUI::Start()
  37. {
  38. // Execute base class startup
  39. Sample::Start();
  40. // Enable OS cursor
  41. GetSubsystem<Input>()->SetMouseVisible(true);
  42. // Load XML file containing default UI style sheet
  43. auto* cache = GetSubsystem<ResourceCache>();
  44. auto* style = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");
  45. // Set the loaded style as default style
  46. uiRoot_->SetDefaultStyle(style);
  47. // Initialize Scene
  48. InitScene();
  49. // Initialize Window
  50. InitWindow();
  51. // Create and add some controls to the Window
  52. InitControls();
  53. // Create a draggable Fish
  54. CreateDraggableFish();
  55. // Create 3D UI rendered on a cube.
  56. Init3DUI();
  57. // Set the mouse mode to use in the sample
  58. Sample::InitMouseMode(MM_FREE);
  59. }
  60. void Hello3DUI::InitControls()
  61. {
  62. // Create a CheckBox
  63. auto* checkBox = new CheckBox(context_);
  64. checkBox->SetName("CheckBox");
  65. // Create a Button
  66. auto* button = new Button(context_);
  67. button->SetName("Button");
  68. button->SetMinHeight(24);
  69. // Create a LineEdit
  70. auto* lineEdit = new LineEdit(context_);
  71. lineEdit->SetName("LineEdit");
  72. lineEdit->SetMinHeight(24);
  73. // Add controls to Window
  74. window_->AddChild(checkBox);
  75. window_->AddChild(button);
  76. window_->AddChild(lineEdit);
  77. // Apply previously set default style
  78. checkBox->SetStyleAuto();
  79. button->SetStyleAuto();
  80. lineEdit->SetStyleAuto();
  81. instructions_ = new Text(context_);
  82. instructions_->SetStyleAuto();
  83. instructions_->SetText("[TAB] - toggle between rendering on screen or cube.\n"
  84. "[Space] - toggle cube rotation.");
  85. uiRoot_->AddChild(instructions_);
  86. }
  87. void Hello3DUI::InitWindow()
  88. {
  89. // Create the Window and add it to the UI's root node
  90. window_ = new Window(context_);
  91. uiRoot_->AddChild(window_);
  92. // Set Window size and layout settings
  93. window_->SetMinWidth(384);
  94. window_->SetLayout(LM_VERTICAL, 6, IntRect(6, 6, 6, 6));
  95. window_->SetAlignment(HA_CENTER, VA_CENTER);
  96. window_->SetName("Window");
  97. // Create Window 'titlebar' container
  98. auto* titleBar = new UIElement(context_);
  99. titleBar->SetMinSize(0, 24);
  100. titleBar->SetVerticalAlignment(VA_TOP);
  101. titleBar->SetLayoutMode(LM_HORIZONTAL);
  102. // Create the Window title Text
  103. auto* windowTitle = new Text(context_);
  104. windowTitle->SetName("WindowTitle");
  105. windowTitle->SetText("Hello GUI!");
  106. // Create the Window's close button
  107. auto* buttonClose = new Button(context_);
  108. buttonClose->SetName("CloseButton");
  109. // Add the controls to the title bar
  110. titleBar->AddChild(windowTitle);
  111. titleBar->AddChild(buttonClose);
  112. // Add the title bar to the Window
  113. window_->AddChild(titleBar);
  114. // Create a list.
  115. auto* list = window_->CreateChild<ListView>();
  116. list->SetSelectOnClickEnd(true);
  117. list->SetHighlightMode(HM_ALWAYS);
  118. list->SetMinHeight(200);
  119. for (int i = 0; i < 32; i++)
  120. {
  121. auto* text = new Text(context_);
  122. text->SetStyleAuto();
  123. text->SetText(ToString("List item %d", i));
  124. text->SetName(ToString("Item %d", i));
  125. list->AddItem(text);
  126. }
  127. // Apply styles
  128. window_->SetStyleAuto();
  129. list->SetStyleAuto();
  130. windowTitle->SetStyleAuto();
  131. buttonClose->SetStyle("CloseButton");
  132. // Subscribe to buttonClose release (following a 'press') events
  133. SubscribeToEvent(buttonClose, E_RELEASED, URHO3D_HANDLER(Hello3DUI, HandleClosePressed));
  134. // Subscribe also to all UI mouse clicks just to see where we have clicked
  135. SubscribeToEvent(E_UIMOUSECLICK, URHO3D_HANDLER(Hello3DUI, HandleControlClicked));
  136. }
  137. void Hello3DUI::InitScene()
  138. {
  139. auto* cache = GetSubsystem<ResourceCache>();
  140. scene_ = new Scene(context_);
  141. scene_->CreateComponent<Octree>();
  142. auto* zone = scene_->CreateComponent<Zone>();
  143. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  144. zone->SetFogColor(Color::GRAY);
  145. zone->SetFogStart(100.0f);
  146. zone->SetFogEnd(300.0f);
  147. // Create a child scene node (at world origin) and a StaticModel component into it.
  148. Node* boxNode = scene_->CreateChild("Box");
  149. boxNode->SetScale(Vector3(5.0f, 5.0f, 5.0f));
  150. boxNode->SetRotation(Quaternion(90, Vector3::LEFT));
  151. // Create a box model and hide it initially.
  152. auto* boxModel = boxNode->CreateComponent<StaticModel>();
  153. boxModel->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  154. boxNode->SetEnabled(false);
  155. // Create a camera.
  156. cameraNode_ = scene_->CreateChild("Camera");
  157. cameraNode_->CreateComponent<Camera>();
  158. // Set an initial position for the camera scene node.
  159. cameraNode_->SetPosition(Vector3(0.0f, 0.0f, -10.0f));
  160. // Set up a viewport so 3D scene can be visible.
  161. auto* renderer = GetSubsystem<Renderer>();
  162. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  163. renderer->SetViewport(0, viewport);
  164. // Subscribe to update event and animate cube and handle input.
  165. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(Hello3DUI, HandleUpdate));
  166. }
  167. void Hello3DUI::CreateDraggableFish()
  168. {
  169. auto* cache = GetSubsystem<ResourceCache>();
  170. auto* graphics = GetSubsystem<Graphics>();
  171. // Create a draggable Fish button
  172. auto* draggableFish = new Button(context_);
  173. draggableFish->SetTexture(cache->GetResource<Texture2D>("Textures/UrhoDecal.dds")); // Set texture
  174. draggableFish->SetBlendMode(BLEND_ADD);
  175. draggableFish->SetSize(128, 128);
  176. draggableFish->SetPosition((graphics->GetWidth() - draggableFish->GetWidth()) / 2, 200);
  177. draggableFish->SetName("Fish");
  178. uiRoot_->AddChild(draggableFish);
  179. // Add a tooltip to Fish button
  180. auto* toolTip = new ToolTip(context_);
  181. draggableFish->AddChild(toolTip);
  182. toolTip->SetPosition(IntVector2(draggableFish->GetWidth() + 5, draggableFish->GetWidth() / 2)); // slightly offset from close button
  183. auto* textHolder = new BorderImage(context_);
  184. toolTip->AddChild(textHolder);
  185. textHolder->SetStyle("ToolTipBorderImage");
  186. auto* toolTipText = new Text(context_);
  187. textHolder->AddChild(toolTipText);
  188. toolTipText->SetStyle("ToolTipText");
  189. toolTipText->SetText("Please drag me!");
  190. // Subscribe draggableFish to Drag Events (in order to make it draggable)
  191. // See "Event list" in documentation's Main Page for reference on available Events and their eventData
  192. SubscribeToEvent(draggableFish, E_DRAGBEGIN, URHO3D_HANDLER(Hello3DUI, HandleDragBegin));
  193. SubscribeToEvent(draggableFish, E_DRAGMOVE, URHO3D_HANDLER(Hello3DUI, HandleDragMove));
  194. SubscribeToEvent(draggableFish, E_DRAGEND, URHO3D_HANDLER(Hello3DUI, HandleDragEnd));
  195. }
  196. void Hello3DUI::HandleDragBegin(StringHash eventType, VariantMap& eventData)
  197. {
  198. // Get UIElement relative position where input (touch or click) occurred (top-left = IntVector2(0,0))
  199. dragBeginPosition_ = IntVector2(eventData["ElementX"].GetI32(), eventData["ElementY"].GetI32());
  200. }
  201. void Hello3DUI::HandleDragMove(StringHash eventType, VariantMap& eventData)
  202. {
  203. IntVector2 dragCurrentPosition = IntVector2(eventData["X"].GetI32(), eventData["Y"].GetI32());
  204. UIElement* draggedElement = static_cast<UIElement*>(eventData["Element"].GetPtr());
  205. draggedElement->SetPosition(dragCurrentPosition - dragBeginPosition_);
  206. }
  207. void Hello3DUI::HandleDragEnd(StringHash eventType, VariantMap& eventData) // For reference (not used here)
  208. {
  209. }
  210. void Hello3DUI::HandleClosePressed(StringHash eventType, VariantMap& eventData)
  211. {
  212. if (GetPlatform() != "Web")
  213. engine_->Exit();
  214. }
  215. void Hello3DUI::HandleControlClicked(StringHash eventType, VariantMap& eventData)
  216. {
  217. // Get the Text control acting as the Window's title
  218. auto* windowTitle = window_->GetChildStaticCast<Text>("WindowTitle", true);
  219. // Get control that was clicked
  220. auto* clicked = static_cast<UIElement*>(eventData[UIMouseClick::P_ELEMENT].GetPtr());
  221. String name = "...?";
  222. if (clicked)
  223. {
  224. // Get the name of the control that was clicked
  225. name = clicked->GetName();
  226. }
  227. // Update the Window's title text
  228. windowTitle->SetText("Hello " + name + "!");
  229. }
  230. void Hello3DUI::Init3DUI()
  231. {
  232. auto* cache = GetSubsystem<ResourceCache>();
  233. // Node that will get UI rendered on it.
  234. Node* boxNode = scene_->GetChild("Box");
  235. // Create a component that sets up UI rendering. It sets material to StaticModel of the node.
  236. auto* component = boxNode->CreateComponent<UIComponent>();
  237. // Optionally modify material. Technique is changed so object is visible without any lights.
  238. component->GetMaterial()->SetTechnique(0, cache->GetResource<Technique>("Techniques/DiffUnlit.xml"));
  239. // Save root element of texture UI for later use.
  240. textureRoot_ = component->GetRoot();
  241. // Set size of root element. This is size of texture as well.
  242. textureRoot_->SetSize(512, 512);
  243. }
  244. void Hello3DUI::HandleUpdate(StringHash, VariantMap& eventData)
  245. {
  246. using namespace Update;
  247. float timeStep = eventData[P_TIMESTEP].GetFloat();
  248. auto* input = GetSubsystem<Input>();
  249. Node* node = scene_->GetChild("Box");
  250. if (current_.NotNull() && drawDebug_)
  251. GetSubsystem<UI>()->DebugDraw(current_);
  252. if (input->GetMouseButtonPress(MOUSEB_LEFT))
  253. current_ = GetSubsystem<UI>()->GetElementAt(input->GetMousePosition());
  254. if (input->GetKeyPress(KEY_TAB))
  255. {
  256. renderOnCube_ = !renderOnCube_;
  257. // Toggle between rendering on screen or to texture.
  258. if (renderOnCube_)
  259. {
  260. node->SetEnabled(true);
  261. textureRoot_->AddChild(window_);
  262. }
  263. else
  264. {
  265. node->SetEnabled(false);
  266. uiRoot_->AddChild(window_);
  267. }
  268. }
  269. if (input->GetKeyPress(KEY_SPACE))
  270. animateCube_ = !animateCube_;
  271. if (input->GetKeyPress(KEY_F2))
  272. drawDebug_ = !drawDebug_;
  273. if (animateCube_)
  274. {
  275. node->Yaw(6.0f * timeStep * 1.5f);
  276. node->Roll(-6.0f * timeStep * 1.5f);
  277. node->Pitch(-6.0f * timeStep * 1.5f);
  278. }
  279. }