// Copyright (c) 2022 Dominic Masters // // This software is released under the MIT License. // https://opensource.org/licenses/MIT #include "UICanvas.hpp" #include "game/DawnGame.hpp" #include "UIComponent.hpp" using namespace Dawn; std::shared_ptr UICanvas::create(Scene *scene) { auto item = scene->createSceneItem(); return item->addComponent(); } UICanvas::UICanvas(std::weak_ptr item) : SceneItemComponent(item), camera(nullptr) { } void UICanvas::rebufferShaderParameters() { struct UICanvasShaderBufferData data; switch(this->drawType) { case UI_DRAW_TYPE_WORLD_ABSOLUTE: data.projection = camera->getProjection(); data.view = camera->item.lock()->getWorldTransform(); break; case UI_DRAW_TYPE_WORLD_CAMERA_RELATIVE: data.projection = glm::ortho( 0.0f, camera->getRenderTarget()->getWidth() / this->getScale(), camera->getRenderTarget()->getHeight() / this->getScale(), 0.0f ); data.view = glm::mat4(1.0f); break; default: assertUnreachable("UICanvas::rebufferShaderParameters: Unknown draw type"); } this->shaderBuffer.buffer(&data); } float_t UICanvas::getScale() { return this->camera->getRenderTarget()->getScale(); } float_t UICanvas::getWidth() { return w; } float_t UICanvas::getHeight() { return h; } float_t UICanvas::getContentWidth() { return this->getWidth(); } float_t UICanvas::getContentHeight() { return this->getHeight(); } float_t UICanvas::getChildOffsetX() { return 0.0f; } float_t UICanvas::getChildOffsetY() { return 0.0f; } void UICanvas::onStart() { if(camera == nullptr) camera = getScene()->findComponent(); this->shaderBuffer.init(); this->rebufferShaderParameters(); useEffectWithTeardown([&]{ if(camera == nullptr) return evtRenderResize = [&] {}; this->w = camera->getRenderTarget()->getWidth() / this->getScale(); this->h = camera->getRenderTarget()->getHeight() / this->getScale(); this->rebufferShaderParameters(); return evtRenderResize = useEvent([&](float_t w, float_t h){ this->w = w / this->getScale(); this->h = h / this->getScale(); this->rebufferShaderParameters(); auto comps = this->item.lock()->findChildren(); auto itComps = comps.begin(); while(itComps != comps.end()) { (*itComps)->alignmentNeedsUpdating = true; ++itComps; } }, camera->eventRenderTargetResized); }, camera)(); } void UICanvas::onDispose() { }