From 762f72c160fc918f3f633933592c63f7dddfc671 Mon Sep 17 00:00:00 2001 From: Niklas Kapelle Date: Sun, 21 Jan 2024 16:32:55 +0100 Subject: [PATCH] added LayerdRootElement --- src/lib/ui/CanvasStack.hx | 56 ++++++++++++++++++++++++ src/lib/ui/elements/LayerdRootElement.hx | 29 ++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 src/lib/ui/CanvasStack.hx create mode 100644 src/lib/ui/elements/LayerdRootElement.hx diff --git a/src/lib/ui/CanvasStack.hx b/src/lib/ui/CanvasStack.hx new file mode 100644 index 0000000..ac610ad --- /dev/null +++ b/src/lib/ui/CanvasStack.hx @@ -0,0 +1,56 @@ +package lib.ui; + +import kernel.ui.Pixel; +import lib.ui.Canvas; + +/** + Layer multiple canvases and compress them into one from a top down view. +**/ +class CanvasStack { + private var layers:Array<{c:Canvas, offset:Pos}> = []; + private var width:Int = 0; + private var hight:Int = 0; + + public function new() {} + + public function addLayer(c:Canvas, offset:Pos) { + this.layers.push({c: c, offset: offset}); + + var layerWidth = c.maxWidth() + offset.x; + var layerHight = c.height() + offset.y; + + if (layerWidth > this.width) { + this.width = layerWidth; + } + + if (layerHight > this.hight) { + this.hight = layerHight; + } + } + + public function compress():Canvas { + var rtn = new Canvas(); + + for (y in 0...this.hight) { + for (x in 0...this.width) { + var pos = new Pos({x: x, y: y}); + rtn.set(pos, this.pixelAt(pos)); + } + } + + return rtn; + } + + public function pixelAt(pos:Pos):Null { + for (i in 0...this.layers.length) { + var newi = (this.layers.length - 1) - i; + var offset = this.layers[newi].offset; + var px = this.layers[newi].c.get(pos - offset); + if (px != null) { + return px; + } + } + + return null; + } +} diff --git a/src/lib/ui/elements/LayerdRootElement.hx b/src/lib/ui/elements/LayerdRootElement.hx new file mode 100644 index 0000000..c9659cb --- /dev/null +++ b/src/lib/ui/elements/LayerdRootElement.hx @@ -0,0 +1,29 @@ +package lib.ui.elements; + +class LayerdRootElement implements UIElement { + private var children:Array<{element:UIElement, offset:Pos}>; + private final eventManager:UIEventManager = new UIEventManager(); + + public function new(?children:Array<{element:UIElement, offset:Pos}>) { + this.children = children == null ? [] : children; + } + + public function setChildren(children:Array<{element:UIElement, offset:Pos}>) { + this.children = children; + } + + public function getEventHandlers():UIEvents { + return eventManager.getEventHandlers(); + } + + public function render(bounds:Pos):Canvas { + // TODO: add event handle + var stack = new CanvasStack(); + + for (child in this.children) { + stack.addLayer(child.element.render(bounds), child.offset); + } + + return stack.compress(); + } +}