Files
rmlui-app-template/src/elements/health_bar_element.cpp

51 lines
1.9 KiB
C++

#include "health_bar_element.hpp"
#include <RmlUi/Core/Factory.h>
#include <RmlUi/Core/ID.h>
#include <RmlUi/Core/Math.h>
#include <RmlUi/Core/Property.h>
#include <RmlUi/Core/Types.h>
#include <RmlUi/Core/Unit.h>
HealthBarElement::HealthBarElement(const Rml::String& tag) : Rml::Element(tag) {
Rml::XMLAttributes attributes;
Rml::ElementPtr track = Rml::Factory::InstanceElement(this, "div", "div", attributes);
track->SetClass("healthbar-track", true);
Rml::ElementPtr fillElement = Rml::Factory::InstanceElement(this, "div", "div", attributes);
fillElement->SetClass("healthbar-fill", true);
fill = fillElement.get();
track->AppendChild(std::move(fillElement));
AppendChild(std::move(track));
UpdateFill();
}
void HealthBarElement::OnAttributeChange(const Rml::ElementAttributes &changed_attributes) {
Rml::Element::OnAttributeChange(changed_attributes);
if (changed_attributes.find("current") != changed_attributes.end() ||
changed_attributes.find("max") != changed_attributes.end()) {
UpdateFill();
}
}
void HealthBarElement::UpdateFill() {
int current = GetAttribute<int>("current", 0);
int max = GetAttribute<int>("max", 100);
if (max <= 0) max = 1;
float pct = Rml::Math::Clamp(static_cast<float>(current) / static_cast<float>(max), 0.0f, 1.0f) * 100.0f;
if (fill) {
fill->SetProperty(Rml::PropertyId::Width, Rml::Property(pct, Rml::Unit::PERCENT));
if (current >= 90) {
fill->SetProperty(Rml::PropertyId::BackgroundColor, Rml::Property("#33cc33", Rml::Unit::COLOUR));
} else if (current >= 50) {
fill->SetProperty(Rml::PropertyId::BackgroundColor, Rml::Property("#cccc33", Rml::Unit::COLOUR));
} else if (current >= 0) {
fill->SetProperty(Rml::PropertyId::BackgroundColor, Rml::Property("#cc3333", Rml::Unit::COLOUR));
}
}
}