BaseGUI.cpp 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include "client/gui/BaseGUI.h"
  2. static const Color4 INPUT_BACKGROUND(0x00, 0x00, 0x00, 0xA0);
  3. static const Color4 INPUT_BACKGROUND_2(0x00, 0x00, 0x00, 0x80);
  4. const Vector2 BaseGUI::FIXED_SIZE(400.0f, 300.0f);
  5. BaseGUI::BaseGUI(const Size& size, TextInput*& textInput,
  6. const Controller& controller)
  7. : size(size), textInput(textInput), controller(controller) {
  8. }
  9. void BaseGUI::tick() {
  10. if(controller.leftClick.wasReleased()) {
  11. Vector2 mousePos = controller.getMouse() / scale;
  12. for(Input& input : inputs) {
  13. if(isIn(input.pos, input.size, mousePos)) {
  14. textInput = &input.text;
  15. textInput->setActive(true);
  16. break;
  17. }
  18. }
  19. }
  20. }
  21. void BaseGUI::updateScale(ShaderMatrix& sm) {
  22. scale = static_cast<int>(
  23. std::min(size.width / FIXED_SIZE[0], size.height / FIXED_SIZE[1]));
  24. scale = scale < 1.0f ? 1.0f : scale;
  25. scaledSize = Vector2(size.width / scale, size.height / scale);
  26. sm.scale(scale).update();
  27. }
  28. void BaseGUI::render(float, ShaderMatrix&, Renderer& r) {
  29. Vector2 mousePos = controller.getMouse() / scale;
  30. for(Input& input : inputs) {
  31. input.text.setLimit(r.charsInSpace(input.size[0] - 20.0f));
  32. if(isIn(input.pos, input.size, mousePos)) {
  33. r.drawRectangle(input.pos, input.size, INPUT_BACKGROUND_2);
  34. } else {
  35. r.drawRectangle(input.pos, input.size, INPUT_BACKGROUND);
  36. }
  37. StringBuffer<256> text(input.text);
  38. Vector2 size = r.getStringSize(text);
  39. Vector2 pos = input.pos + (input.size - size) * 0.5f;
  40. drawString(r, pos, text);
  41. if(textInput == &input.text) {
  42. Vector2 cursor = r.getStringSize(text, input.text.getCursor());
  43. drawString(r, Vector2(pos[0] + cursor[0], pos[1] + 2.0f), "&292_");
  44. drawString(r, Vector2(pos[0] + cursor[0], pos[1] + 3.0f), "&292_");
  45. }
  46. }
  47. }
  48. Vector2 BaseGUI::round(const Vector2& v) const {
  49. return Vector2(static_cast<int>(v[0] * scale) / scale,
  50. static_cast<int>(v[1] * scale) / scale);
  51. }
  52. void BaseGUI::drawString(Renderer& r, const Vector2& pos, const char* s) {
  53. r.drawString(round(pos), s);
  54. }
  55. BaseGUI::Input& BaseGUI::addInput() {
  56. inputs.add();
  57. return inputs[inputs.getLength() - 1];
  58. }
  59. void BaseGUI::drawCenteredString(Renderer& r, const Vector2& pos,
  60. const Vector2& size, const char* text) {
  61. Vector2 textSize = r.getStringSize(text);
  62. drawString(r, pos + (size - textSize) * 0.5f, text);
  63. }
  64. bool BaseGUI::isIn(const Vector2& pos, const Vector2& size,
  65. const Vector2& point) const {
  66. Vector2 end = pos + size;
  67. return pos[0] <= point[0] && point[0] <= end[0] && pos[1] <= point[1] &&
  68. point[1] <= end[1];
  69. }