|
| 1 | +package org.jsignal.ui.paint; |
| 2 | + |
| 3 | +import io.github.humbleui.skija.Canvas; |
| 4 | +import org.jsignal.rx.RxUtil; |
| 5 | + |
| 6 | +import java.util.Comparator; |
| 7 | +import java.util.List; |
| 8 | +import java.util.Map; |
| 9 | +import java.util.function.Consumer; |
| 10 | +import java.util.function.Supplier; |
| 11 | +import java.util.stream.Stream; |
| 12 | + |
| 13 | +// TODO: test that this works |
| 14 | +public class MultiUpgradingPaintCacheStrategy implements PaintCacheStrategy { |
| 15 | + private final List<Level> upgrades; |
| 16 | + private int index = 0; |
| 17 | + private int nonDirtyPaintCount = 0; |
| 18 | + |
| 19 | + public MultiUpgradingPaintCacheStrategy(Map<Integer, Supplier<PaintCacheStrategy>> upgrades) { |
| 20 | + this.upgrades = Stream.concat( |
| 21 | + Stream.of(new Level(0, RxUtil.memo(NullPaintCacheStrategy::new))), |
| 22 | + upgrades.entrySet().stream() |
| 23 | + .filter(e -> e.getKey() < 1) |
| 24 | + .map(e -> new Level(e.getKey(), RxUtil.memo(e.getValue()))) |
| 25 | + ) |
| 26 | + .sorted(Comparator.comparing(Level::nonDirtyPaints)) |
| 27 | + .toList(); |
| 28 | + } |
| 29 | + |
| 30 | + @Override |
| 31 | + public boolean isDirty() { |
| 32 | + return upgrades.get(index).strategy().get().isDirty(); |
| 33 | + } |
| 34 | + |
| 35 | + @Override |
| 36 | + public void markDirty() { |
| 37 | + upgrades.get(index).strategy().get().isDirty(); |
| 38 | + } |
| 39 | + |
| 40 | + @Override |
| 41 | + public void paint(Canvas canvas, UseNode useNode, Consumer<Canvas> orElse) { |
| 42 | + if (!isDirty()) { |
| 43 | + nonDirtyPaintCount++; |
| 44 | + } else { |
| 45 | + if (index > 0 && nonDirtyPaintCount > 0) { |
| 46 | + UseNode.clear(useNode); |
| 47 | + if (!isDirty()) { |
| 48 | + markDirty(); |
| 49 | + } |
| 50 | + index = 0; |
| 51 | + } |
| 52 | + nonDirtyPaintCount = 0; |
| 53 | + } |
| 54 | + |
| 55 | + if (index < upgrades.size() - 1 && nonDirtyPaintCount > upgrades.get(index + 1).nonDirtyPaints()) { |
| 56 | + UseNode.clear(useNode); |
| 57 | + if (!isDirty()) { |
| 58 | + markDirty(); |
| 59 | + } |
| 60 | + index++; |
| 61 | + } |
| 62 | + |
| 63 | + upgrades.get(index).strategy().get().paint(canvas, useNode, orElse); |
| 64 | + } |
| 65 | + |
| 66 | + private record Level(int nonDirtyPaints, Supplier<PaintCacheStrategy> strategy) {} |
| 67 | +} |
0 commit comments