// // Copyright (c) 2008-2017 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "../Precompiled.h" #include "../Core/Context.h" #include "../Core/CoreEvents.h" #include "../Core/Profiler.h" #include "../Container/Sort.h" #include "../Graphics/Graphics.h" #include "../Graphics/GraphicsEvents.h" #include "../Graphics/Shader.h" #include "../Graphics/ShaderVariation.h" #include "../Graphics/Texture2D.h" #include "../Graphics/VertexBuffer.h" #include "../Input/Input.h" #include "../Input/InputEvents.h" #include "../IO/Log.h" #include "../Math/Matrix3x4.h" #include "../Resource/ResourceCache.h" #include "../UI/CheckBox.h" #include "../UI/Cursor.h" #include "../UI/DropDownList.h" #include "../UI/FileSelector.h" #include "../UI/Font.h" #include "../UI/LineEdit.h" #include "../UI/ListView.h" #include "../UI/MessageBox.h" #include "../UI/ProgressBar.h" #include "../UI/ScrollBar.h" #include "../UI/Slider.h" #include "../UI/Sprite.h" #include "../UI/Text.h" #include "../UI/Text3D.h" #include "../UI/ToolTip.h" #include "../UI/UI.h" #include "../UI/UIEvents.h" #include "../UI/Window.h" #include "../UI/View3D.h" #include #include #include "../DebugNew.h" #define TOUCHID_MASK(id) (1 << id) namespace Urho3D { StringHash VAR_ORIGIN("Origin"); const StringHash VAR_ORIGINAL_PARENT("OriginalParent"); const StringHash VAR_ORIGINAL_CHILD_INDEX("OriginalChildIndex"); const StringHash VAR_PARENT_CHANGED("ParentChanged"); const float DEFAULT_DOUBLECLICK_INTERVAL = 0.5f; const float DEFAULT_DRAGBEGIN_INTERVAL = 0.5f; const float DEFAULT_TOOLTIP_DELAY = 0.5f; const int DEFAULT_DRAGBEGIN_DISTANCE = 5; const int DEFAULT_FONT_TEXTURE_MAX_SIZE = 2048; const char* UI_CATEGORY = "UI"; UI::UI(Context* context) : Object(context), rootElement_(new UIElement(context)), rootModalElement_(new UIElement(context)), doubleClickInterval_(DEFAULT_DOUBLECLICK_INTERVAL), dragBeginInterval_(DEFAULT_DRAGBEGIN_INTERVAL), defaultToolTipDelay_(DEFAULT_TOOLTIP_DELAY), dragBeginDistance_(DEFAULT_DRAGBEGIN_DISTANCE), mouseButtons_(0), lastMouseButtons_(0), qualifiers_(0), maxFontTextureSize_(DEFAULT_FONT_TEXTURE_MAX_SIZE), initialized_(false), usingTouchInput_(false), #ifdef _WIN32 nonFocusedMouseWheel_(false), // Default MS Windows behaviour #else nonFocusedMouseWheel_(true), // Default Mac OS X and Linux behaviour #endif useSystemClipboard_(false), #if defined(__ANDROID__) || defined(IOS) || defined(TVOS) useScreenKeyboard_(true), #else useScreenKeyboard_(false), #endif useMutableGlyphs_(false), forceAutoHint_(false), fontHintLevel_(FONT_HINT_LEVEL_NORMAL), fontSubpixelThreshold_(12), fontOversampling_(2), uiRendered_(false), nonModalBatchSize_(0), dragElementsCount_(0), dragConfirmedCount_(0), uiScale_(1.0f), customSize_(IntVector2::ZERO) { rootElement_->SetTraversalMode(TM_DEPTH_FIRST); rootModalElement_->SetTraversalMode(TM_DEPTH_FIRST); // Register UI library object factories RegisterUILibrary(context_); SubscribeToEvent(E_SCREENMODE, URHO3D_HANDLER(UI, HandleScreenMode)); SubscribeToEvent(E_MOUSEBUTTONDOWN, URHO3D_HANDLER(UI, HandleMouseButtonDown)); SubscribeToEvent(E_MOUSEBUTTONUP, URHO3D_HANDLER(UI, HandleMouseButtonUp)); SubscribeToEvent(E_MOUSEMOVE, URHO3D_HANDLER(UI, HandleMouseMove)); SubscribeToEvent(E_MOUSEWHEEL, URHO3D_HANDLER(UI, HandleMouseWheel)); SubscribeToEvent(E_TOUCHBEGIN, URHO3D_HANDLER(UI, HandleTouchBegin)); SubscribeToEvent(E_TOUCHEND, URHO3D_HANDLER(UI, HandleTouchEnd)); SubscribeToEvent(E_TOUCHMOVE, URHO3D_HANDLER(UI, HandleTouchMove)); SubscribeToEvent(E_KEYDOWN, URHO3D_HANDLER(UI, HandleKeyDown)); SubscribeToEvent(E_TEXTINPUT, URHO3D_HANDLER(UI, HandleTextInput)); SubscribeToEvent(E_DROPFILE, URHO3D_HANDLER(UI, HandleDropFile)); // Try to initialize right now, but skip if screen mode is not yet set Initialize(); } UI::~UI() { } void UI::SetCursor(Cursor* cursor) { // Remove old cursor (if any) and set new if (cursor_) { rootElement_->RemoveChild(cursor_); cursor_.Reset(); } if (cursor) { rootElement_->AddChild(cursor); cursor_ = cursor; IntVector2 pos = cursor_->GetPosition(); const IntVector2& rootSize = rootElement_->GetSize(); const IntVector2& rootPos = rootElement_->GetPosition(); pos.x_ = Clamp(pos.x_, rootPos.x_, rootPos.x_ + rootSize.x_ - 1); pos.y_ = Clamp(pos.y_, rootPos.y_, rootPos.y_ + rootSize.y_ - 1); cursor_->SetPosition(pos); } } void UI::SetFocusElement(UIElement* element, bool byKey) { using namespace FocusChanged; UIElement* originalElement = element; if (element) { // Return if already has focus if (focusElement_ == element) return; // Only allow child elements of the modal element to receive focus if (HasModalElement()) { UIElement* topLevel = element->GetParent(); while (topLevel && topLevel->GetParent() != rootElement_) topLevel = topLevel->GetParent(); if (topLevel) // If parented to non-modal root then ignore return; } // Search for an element in the hierarchy that can alter focus. If none found, exit element = GetFocusableElement(element); if (!element) return; } // Remove focus from the old element if (focusElement_) { UIElement* oldFocusElement = focusElement_; focusElement_.Reset(); VariantMap& focusEventData = GetEventDataMap(); focusEventData[Defocused::P_ELEMENT] = oldFocusElement; oldFocusElement->SendEvent(E_DEFOCUSED, focusEventData); } // Then set focus to the new if (element && element->GetFocusMode() >= FM_FOCUSABLE) { focusElement_ = element; VariantMap& focusEventData = GetEventDataMap(); focusEventData[Focused::P_ELEMENT] = element; focusEventData[Focused::P_BYKEY] = byKey; element->SendEvent(E_FOCUSED, focusEventData); } VariantMap& eventData = GetEventDataMap(); eventData[P_CLICKEDELEMENT] = originalElement; eventData[P_ELEMENT] = element; SendEvent(E_FOCUSCHANGED, eventData); } bool UI::SetModalElement(UIElement* modalElement, bool enable) { if (!modalElement) return false; // Currently only allow modal window if (modalElement->GetType() != Window::GetTypeStatic()) return false; assert(rootModalElement_); UIElement* currParent = modalElement->GetParent(); if (enable) { // Make sure it is not already the child of the root modal element if (currParent == rootModalElement_) return false; // Adopt modal root as parent modalElement->SetVar(VAR_ORIGINAL_PARENT, currParent); modalElement->SetVar(VAR_ORIGINAL_CHILD_INDEX, currParent ? currParent->FindChild(modalElement) : M_MAX_UNSIGNED); modalElement->SetParent(rootModalElement_); // If it is a popup element, bring along its top-level parent UIElement* originElement = static_cast(modalElement->GetVar(VAR_ORIGIN).GetPtr()); if (originElement) { UIElement* element = originElement; while (element && element->GetParent() != rootElement_) element = element->GetParent(); if (element) { originElement->SetVar(VAR_PARENT_CHANGED, element); UIElement* oriParent = element->GetParent(); element->SetVar(VAR_ORIGINAL_PARENT, oriParent); element->SetVar(VAR_ORIGINAL_CHILD_INDEX, oriParent ? oriParent->FindChild(element) : M_MAX_UNSIGNED); element->SetParent(rootModalElement_); } } return true; } else { // Only the modal element can disable itself if (currParent != rootModalElement_) return false; // Revert back to original parent modalElement->SetParent(static_cast(modalElement->GetVar(VAR_ORIGINAL_PARENT).GetPtr()), modalElement->GetVar(VAR_ORIGINAL_CHILD_INDEX).GetUInt()); VariantMap& vars = const_cast(modalElement->GetVars()); vars.Erase(VAR_ORIGINAL_PARENT); vars.Erase(VAR_ORIGINAL_CHILD_INDEX); // If it is a popup element, revert back its top-level parent UIElement* originElement = static_cast(modalElement->GetVar(VAR_ORIGIN).GetPtr()); if (originElement) { UIElement* element = static_cast(originElement->GetVar(VAR_PARENT_CHANGED).GetPtr()); if (element) { const_cast(originElement->GetVars()).Erase(VAR_PARENT_CHANGED); element->SetParent(static_cast(element->GetVar(VAR_ORIGINAL_PARENT).GetPtr()), element->GetVar(VAR_ORIGINAL_CHILD_INDEX).GetUInt()); vars = const_cast(element->GetVars()); vars.Erase(VAR_ORIGINAL_PARENT); vars.Erase(VAR_ORIGINAL_CHILD_INDEX); } } return true; } } void UI::Clear() { rootElement_->RemoveAllChildren(); rootModalElement_->RemoveAllChildren(); if (cursor_) rootElement_->AddChild(cursor_); } void UI::Update(float timeStep) { assert(rootElement_ && rootModalElement_); URHO3D_PROFILE(UpdateUI); // Expire hovers for (HashMap, bool>::Iterator i = hoveredElements_.Begin(); i != hoveredElements_.End(); ++i) i->second_ = false; Input* input = GetSubsystem(); bool mouseGrabbed = input->IsMouseGrabbed(); IntVector2 cursorPos; bool cursorVisible; GetCursorPositionAndVisible(cursorPos, cursorVisible); // Drag begin based on time if (dragElementsCount_ > 0 && !mouseGrabbed) { for (HashMap, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();) { WeakPtr dragElement = i->first_; UI::DragData* dragData = i->second_; if (!dragElement) { i = DragElementErase(i); continue; } if (!dragData->dragBeginPending) { ++i; continue; } if (dragData->dragBeginTimer.GetMSec(false) >= (unsigned)(dragBeginInterval_ * 1000)) { dragData->dragBeginPending = false; IntVector2 beginSendPos = dragData->dragBeginSumPos / dragData->numDragButtons; dragConfirmedCount_++; if (!usingTouchInput_) dragElement->OnDragBegin(dragElement->ScreenToElement(beginSendPos), beginSendPos, dragData->dragButtons, qualifiers_, cursor_); else dragElement->OnDragBegin(dragElement->ScreenToElement(beginSendPos), beginSendPos, dragData->dragButtons, 0, 0); SendDragOrHoverEvent(E_DRAGBEGIN, dragElement, beginSendPos, IntVector2::ZERO, dragData); } ++i; } } // Mouse hover if (!mouseGrabbed && !input->GetTouchEmulation()) { if (!usingTouchInput_ && cursorVisible) ProcessHover(cursorPos, mouseButtons_, qualifiers_, cursor_); } // Touch hover unsigned numTouches = input->GetNumTouches(); for (unsigned i = 0; i < numTouches; ++i) { TouchState* touch = input->GetTouch(i); IntVector2 touchPos = touch->position_; touchPos.x_ = (int)(touchPos.x_ / uiScale_); touchPos.y_ = (int)(touchPos.y_ / uiScale_); ProcessHover(touchPos, TOUCHID_MASK(touch->touchID_), 0, 0); } // End hovers that expired without refreshing for (HashMap, bool>::Iterator i = hoveredElements_.Begin(); i != hoveredElements_.End();) { if (i->first_.Expired() || !i->second_) { UIElement* element = i->first_; if (element) { using namespace HoverEnd; VariantMap& eventData = GetEventDataMap(); eventData[P_ELEMENT] = element; element->SendEvent(E_HOVEREND, eventData); } i = hoveredElements_.Erase(i); } else ++i; } Update(timeStep, rootElement_); Update(timeStep, rootModalElement_); } void UI::RenderUpdate() { assert(rootElement_ && rootModalElement_ && graphics_); URHO3D_PROFILE(GetUIBatches); uiRendered_ = false; // If the OS cursor is visible, do not render the UI's own cursor bool osCursorVisible = GetSubsystem()->IsMouseVisible(); // Get rendering batches from the non-modal UI elements batches_.Clear(); vertexData_.Clear(); const IntVector2& rootSize = rootElement_->GetSize(); const IntVector2& rootPos = rootElement_->GetPosition(); // Note: the scissors operate on unscaled coordinates. Scissor scaling is only performed during render IntRect currentScissor = IntRect(rootPos.x_, rootPos.y_, rootPos.x_ + rootSize.x_, rootPos.y_ + rootSize.y_); if (rootElement_->IsVisible()) GetBatches(rootElement_, currentScissor); // Save the batch size of the non-modal batches for later use nonModalBatchSize_ = batches_.Size(); // Get rendering batches from the modal UI elements GetBatches(rootModalElement_, currentScissor); // Get batches from the cursor (and its possible children) last to draw it on top of everything if (cursor_ && cursor_->IsVisible() && !osCursorVisible) { currentScissor = IntRect(0, 0, rootSize.x_, rootSize.y_); cursor_->GetBatches(batches_, vertexData_, currentScissor); GetBatches(cursor_, currentScissor); } } void UI::Render(bool resetRenderTargets) { // Perform the default render only if not rendered yet if (resetRenderTargets && uiRendered_) return; URHO3D_PROFILE(RenderUI); // If the OS cursor is visible, apply its shape now if changed bool osCursorVisible = GetSubsystem()->IsMouseVisible(); if (cursor_ && osCursorVisible) cursor_->ApplyOSCursorShape(); SetVertexData(vertexBuffer_, vertexData_); SetVertexData(debugVertexBuffer_, debugVertexData_); // Render non-modal batches Render(resetRenderTargets, vertexBuffer_, batches_, 0, nonModalBatchSize_); // Render debug draw Render(resetRenderTargets, debugVertexBuffer_, debugDrawBatches_, 0, debugDrawBatches_.Size()); // Render modal batches Render(resetRenderTargets, vertexBuffer_, batches_, nonModalBatchSize_, batches_.Size()); // Clear the debug draw batches and data debugDrawBatches_.Clear(); debugVertexData_.Clear(); uiRendered_ = true; } void UI::DebugDraw(UIElement* element) { if (element) { const IntVector2& rootSize = rootElement_->GetSize(); const IntVector2& rootPos = rootElement_->GetPosition(); element->GetDebugDrawBatches(debugDrawBatches_, debugVertexData_, IntRect(rootPos.x_, rootPos.y_, rootPos.x_ + rootSize.x_, rootPos.y_ + rootSize.y_)); } } SharedPtr UI::LoadLayout(Deserializer& source, XMLFile* styleFile) { SharedPtr xml(new XMLFile(context_)); if (!xml->Load(source)) return SharedPtr(); else return LoadLayout(xml, styleFile); } SharedPtr UI::LoadLayout(XMLFile* file, XMLFile* styleFile) { URHO3D_PROFILE(LoadUILayout); SharedPtr root; if (!file) { URHO3D_LOGERROR("Null UI layout XML file"); return root; } URHO3D_LOGDEBUG("Loading UI layout " + file->GetName()); XMLElement rootElem = file->GetRoot("element"); if (!rootElem) { URHO3D_LOGERROR("No root UI element in " + file->GetName()); return root; } String typeName = rootElem.GetAttribute("type"); if (typeName.Empty()) typeName = "UIElement"; root = DynamicCast(context_->CreateObject(typeName)); if (!root) { URHO3D_LOGERROR("Could not create unknown UI element " + typeName); return root; } // Use default style file of the root element if it has one if (!styleFile) styleFile = rootElement_->GetDefaultStyle(false); // Set it as default for later use by children elements if (styleFile) root->SetDefaultStyle(styleFile); root->LoadXML(rootElem, styleFile); return root; } bool UI::SaveLayout(Serializer& dest, UIElement* element) { URHO3D_PROFILE(SaveUILayout); return element && element->SaveXML(dest); } void UI::SetClipboardText(const String& text) { clipBoard_ = text; if (useSystemClipboard_) SDL_SetClipboardText(text.CString()); } void UI::SetDoubleClickInterval(float interval) { doubleClickInterval_ = Max(interval, 0.0f); } void UI::SetDragBeginInterval(float interval) { dragBeginInterval_ = Max(interval, 0.0f); } void UI::SetDragBeginDistance(int pixels) { dragBeginDistance_ = Max(pixels, 0); } void UI::SetDefaultToolTipDelay(float delay) { defaultToolTipDelay_ = Max(delay, 0.0f); } void UI::SetMaxFontTextureSize(int size) { if (IsPowerOfTwo((unsigned)size) && size >= FONT_TEXTURE_MIN_SIZE) { if (size != maxFontTextureSize_) { maxFontTextureSize_ = size; ReleaseFontFaces(); } } } void UI::SetNonFocusedMouseWheel(bool nonFocusedMouseWheel) { nonFocusedMouseWheel_ = nonFocusedMouseWheel; } void UI::SetUseSystemClipboard(bool enable) { useSystemClipboard_ = enable; } void UI::SetUseScreenKeyboard(bool enable) { useScreenKeyboard_ = enable; } void UI::SetUseMutableGlyphs(bool enable) { if (enable != useMutableGlyphs_) { useMutableGlyphs_ = enable; ReleaseFontFaces(); } } void UI::SetForceAutoHint(bool enable) { if (enable != forceAutoHint_) { forceAutoHint_ = enable; ReleaseFontFaces(); } } void UI::SetFontHintLevel(FontHintLevel level) { if (level != fontHintLevel_) { fontHintLevel_ = level; ReleaseFontFaces(); } } void UI::SetFontSubpixelThreshold(float threshold) { assert(threshold >= 0); if (threshold != fontSubpixelThreshold_) { fontSubpixelThreshold_ = threshold; ReleaseFontFaces(); } } void UI::SetFontOversampling(int oversampling) { assert(oversampling >= 1); oversampling = Clamp(oversampling, 1, 8); if (oversampling != fontOversampling_) { fontOversampling_ = oversampling; ReleaseFontFaces(); } } void UI::SetScale(float scale) { uiScale_ = Max(scale, M_EPSILON); ResizeRootElement(); } void UI::SetWidth(float width) { IntVector2 size = GetEffectiveRootElementSize(false); SetScale((float)size.x_ / width); } void UI::SetHeight(float height) { IntVector2 size = GetEffectiveRootElementSize(false); SetScale((float)size.y_ / height); } void UI::SetCustomSize(const IntVector2& size) { customSize_ = IntVector2(Max(0, size.x_), Max(0, size.y_)); ResizeRootElement(); } void UI::SetCustomSize(int width, int height) { customSize_ = IntVector2(Max(0, width), Max(0, height)); ResizeRootElement(); } IntVector2 UI::GetCursorPosition() const { return cursor_ ? cursor_->GetPosition() : GetSubsystem()->GetMousePosition(); } UIElement* UI::GetElementAt(const IntVector2& position, bool enabledOnly) { IntVector2 positionCopy(position); const IntVector2& rootSize = rootElement_->GetSize(); const IntVector2& rootPos = rootElement_->GetPosition(); // If position is out of bounds of root element return null. if (position.x_ < rootPos.x_ || position.x_ > rootPos.x_ + rootSize.x_) return 0; if (position.y_ < rootPos.y_ || position.y_ > rootPos.y_ + rootSize.y_) return 0; // If UI is smaller than the screen, wrap if necessary if (rootSize.x_ > 0 && rootSize.y_ > 0) { if (positionCopy.x_ >= rootPos.x_ + rootSize.x_) positionCopy.x_ = rootPos.x_ + ((positionCopy.x_ - rootPos.x_) % rootSize.x_); if (positionCopy.y_ >= rootPos.y_ + rootSize.y_) positionCopy.y_ = rootPos.y_ + ((positionCopy.y_ - rootPos.y_) % rootSize.y_); } UIElement* result = 0; GetElementAt(result, HasModalElement() ? rootModalElement_ : rootElement_, positionCopy, enabledOnly); return result; } UIElement* UI::GetElementAt(int x, int y, bool enabledOnly) { return GetElementAt(IntVector2(x, y), enabledOnly); } UIElement* UI::GetFrontElement() const { const Vector >& rootChildren = rootElement_->GetChildren(); int maxPriority = M_MIN_INT; UIElement* front = 0; for (unsigned i = 0; i < rootChildren.Size(); ++i) { // Do not take into account input-disabled elements, hidden elements or those that are always in the front if (!rootChildren[i]->IsEnabled() || !rootChildren[i]->IsVisible() || !rootChildren[i]->GetBringToBack()) continue; int priority = rootChildren[i]->GetPriority(); if (priority > maxPriority) { maxPriority = priority; front = rootChildren[i]; } } return front; } const Vector UI::GetDragElements() { // Do not return the element until drag begin event has actually been posted if (!dragElementsConfirmed_.Empty()) return dragElementsConfirmed_; for (HashMap, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();) { WeakPtr dragElement = i->first_; UI::DragData* dragData = i->second_; if (!dragElement) { i = DragElementErase(i); continue; } if (!dragData->dragBeginPending) dragElementsConfirmed_.Push(dragElement); ++i; } return dragElementsConfirmed_; } UIElement* UI::GetDragElement(unsigned index) { GetDragElements(); if (index >= dragElementsConfirmed_.Size()) return (UIElement*)0; return dragElementsConfirmed_[index]; } const String& UI::GetClipboardText() const { if (useSystemClipboard_) { char* text = SDL_GetClipboardText(); clipBoard_ = String(text); if (text) SDL_free(text); } return clipBoard_; } bool UI::HasModalElement() const { return rootModalElement_->GetNumChildren() > 0; } void UI::Initialize() { Graphics* graphics = GetSubsystem(); if (!graphics || !graphics->IsInitialized()) return; URHO3D_PROFILE(InitUI); graphics_ = graphics; UIBatch::posAdjust = Vector3(Graphics::GetPixelUVOffset(), 0.0f); // Set initial root element size ResizeRootElement(); vertexBuffer_ = new VertexBuffer(context_); debugVertexBuffer_ = new VertexBuffer(context_); initialized_ = true; SubscribeToEvent(E_BEGINFRAME, URHO3D_HANDLER(UI, HandleBeginFrame)); SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(UI, HandlePostUpdate)); SubscribeToEvent(E_RENDERUPDATE, URHO3D_HANDLER(UI, HandleRenderUpdate)); URHO3D_LOGINFO("Initialized user interface"); } void UI::Update(float timeStep, UIElement* element) { // Keep a weak pointer to the element in case it destroys itself on update WeakPtr elementWeak(element); element->Update(timeStep); if (elementWeak.Expired()) return; const Vector >& children = element->GetChildren(); // Update of an element may modify its child vector. Use just index-based iteration to be safe for (unsigned i = 0; i < children.Size(); ++i) Update(timeStep, children[i]); } void UI::SetVertexData(VertexBuffer* dest, const PODVector& vertexData) { if (vertexData.Empty()) return; // Update quad geometry into the vertex buffer // Resize the vertex buffer first if too small or much too large unsigned numVertices = vertexData.Size() / UI_VERTEX_SIZE; if (dest->GetVertexCount() < numVertices || dest->GetVertexCount() > numVertices * 2) dest->SetSize(numVertices, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1, true); dest->SetData(&vertexData[0]); } void UI::Render(bool resetRenderTargets, VertexBuffer* buffer, const PODVector& batches, unsigned batchStart, unsigned batchEnd) { // Engine does not render when window is closed or device is lost assert(graphics_ && graphics_->IsInitialized() && !graphics_->IsDeviceLost()); if (batches.Empty()) return; if (resetRenderTargets) graphics_->ResetRenderTargets(); IntVector2 viewSize = graphics_->GetViewport().Size(); Vector2 invScreenSize(1.0f / (float)viewSize.x_, 1.0f / (float)viewSize.y_); Vector2 scale(2.0f * invScreenSize.x_, -2.0f * invScreenSize.y_); Vector2 offset(-1.0f, 1.0f); Matrix4 projection(Matrix4::IDENTITY); projection.m00_ = scale.x_ * uiScale_; projection.m03_ = offset.x_; projection.m11_ = scale.y_ * uiScale_; projection.m13_ = offset.y_; projection.m22_ = 1.0f; projection.m23_ = 0.0f; projection.m33_ = 1.0f; graphics_->ClearParameterSources(); graphics_->SetColorWrite(true); graphics_->SetCullMode(CULL_CCW); graphics_->SetDepthTest(CMP_ALWAYS); graphics_->SetDepthWrite(false); graphics_->SetFillMode(FILL_SOLID); graphics_->SetStencilTest(false); graphics_->SetVertexBuffer(buffer); ShaderVariation* noTextureVS = graphics_->GetShader(VS, "Basic", "VERTEXCOLOR"); ShaderVariation* diffTextureVS = graphics_->GetShader(VS, "Basic", "DIFFMAP VERTEXCOLOR"); ShaderVariation* noTexturePS = graphics_->GetShader(PS, "Basic", "VERTEXCOLOR"); ShaderVariation* diffTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP VERTEXCOLOR"); ShaderVariation* diffMaskTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP ALPHAMASK VERTEXCOLOR"); ShaderVariation* alphaTexturePS = graphics_->GetShader(PS, "Basic", "ALPHAMAP VERTEXCOLOR"); unsigned alphaFormat = Graphics::GetAlphaFormat(); for (unsigned i = batchStart; i < batchEnd; ++i) { const UIBatch& batch = batches[i]; if (batch.vertexStart_ == batch.vertexEnd_) continue; ShaderVariation* ps; ShaderVariation* vs; if (!batch.texture_) { ps = noTexturePS; vs = noTextureVS; } else { // If texture contains only an alpha channel, use alpha shader (for fonts) vs = diffTextureVS; if (batch.texture_->GetFormat() == alphaFormat) ps = alphaTexturePS; else if (batch.blendMode_ != BLEND_ALPHA && batch.blendMode_ != BLEND_ADDALPHA && batch.blendMode_ != BLEND_PREMULALPHA) ps = diffMaskTexturePS; else ps = diffTexturePS; } graphics_->SetShaders(vs, ps); if (graphics_->NeedParameterUpdate(SP_OBJECT, this)) graphics_->SetShaderParameter(VSP_MODEL, Matrix3x4::IDENTITY); if (graphics_->NeedParameterUpdate(SP_CAMERA, this)) graphics_->SetShaderParameter(VSP_VIEWPROJ, projection); if (graphics_->NeedParameterUpdate(SP_MATERIAL, this)) graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, Color(1.0f, 1.0f, 1.0f, 1.0f)); float elapsedTime = GetSubsystem