diff --git a/src/lib/ui/Canvas.hx b/src/lib/ui/Canvas.hx index 81e5e00..8e18479 100644 --- a/src/lib/ui/Canvas.hx +++ b/src/lib/ui/Canvas.hx @@ -2,10 +2,9 @@ package lib.ui; import util.Pos; import util.Rect; -import util.Vec.Vec2; import kernel.ui.Pixel; -abstract Canvas(Array>) to Array> { +abstract Canvas(Array>) to Array>{ inline public function new() { this = [[]]; } @@ -18,7 +17,11 @@ abstract Canvas(Array>) to Array> { this[i.y][i.x] = pixel; } - public inline function get(i:Pos):Pixel { + public inline function get(i:Pos):Null { + if (this[i.y] == null) { + return null; + } + return this[i.y][i.x]; } @@ -50,7 +53,7 @@ abstract Canvas(Array>) to Array> { public function maxWidth() { var max = 0; for (i in 0...this.length) { - if (this[i].length > max) { + if (this[i] != null && this[i].length > max) { max = this[i].length; } } @@ -67,32 +70,68 @@ abstract Canvas(Array>) to Array> { } class CanvasKeyValueIterator { - private final canvas:Array>; - private var index:Pos = {x: 0, y: 0}; + private final canvas:Array> ; + private var index:Null = {x: 0, y: 0}; + private var nextIndex:Null = null; @:allow(lib.ui.Canvas) private function new(canvas:Array>) { this.canvas = canvas; + + if (!isValidPos(this.index)){ + this.index = nextValidPixel(); + } + + this.nextIndex = nextValidPixel(); + } + + private function isValidPos(pos: Pos): Bool { + if (this.canvas[pos.y] == null) { + return false; + } + + if (this.canvas[pos.y][pos.x] == null) { + return false; + } + + return true; } public function hasNext():Bool { - return index.y < canvas.length && index.x <= canvas[index.y].length; + return this.index != null; + } + + private function nextValidPixel(): Null { + if (this.index == null) { + return null; + } + + for (y in (this.index.y)...(this.canvas.length)){ + if (this.canvas[y] == null) { + continue; + } + + for (x in (this.index.x + 1)...(this.canvas[y].length)){ + if (this.canvas[y][x] == null) { + continue; + } + + return {x: x, y: y}; + } + } + return null; } public function next():{key:Pos, value:Pixel} { - var oldIndex:Pos = this.index; - - if (index.x >= canvas[index.y].length) { - // Goto next line - index = {x: 0, y: index.y + 1}; - } else { - // Goto next pixel in line - index = {x: index.x + 1, y: index.y}; - } - - return { - key: oldIndex, - value: this.canvas[oldIndex.y][oldIndex.x] + var rtn = { + key: this.index, + value: this.canvas[this.index.y][this.index.x] }; + + this.index = this.nextIndex; + this.nextIndex = nextValidPixel(); + + + return rtn; } }