mapcomplete/Logic/FeatureSource/TileFreshnessCalculator.ts

65 lines
2 KiB
TypeScript
Raw Normal View History

2022-09-08 21:40:48 +02:00
import { Tiles } from "../../Models/TileRange"
export default class TileFreshnessCalculator {
/**
* All the freshnesses per tile index
* @private
*/
2022-09-08 21:40:48 +02:00
private readonly freshnesses = new Map<number, Date>()
/**
* Marks that some data got loaded for this layer
* @param tileId
* @param freshness
*/
2021-11-07 16:34:51 +01:00
public addTileLoad(tileId: number, freshness: Date) {
const existingFreshness = this.freshnessFor(...Tiles.tile_from_index(tileId))
2021-11-07 16:34:51 +01:00
if (existingFreshness >= freshness) {
2022-09-08 21:40:48 +02:00
return
}
this.freshnesses.set(tileId, freshness)
2021-11-07 16:34:51 +01:00
// Do we have freshness for the neighbouring tiles? If so, we can mark the tile above as loaded too!
let [z, x, y] = Tiles.tile_from_index(tileId)
2021-11-07 16:34:51 +01:00
if (z === 0) {
2022-09-08 21:40:48 +02:00
return
}
x = x - (x % 2) // Make the tiles always even
y = y - (y % 2)
2021-11-07 16:34:51 +01:00
const ul = this.freshnessFor(z, x, y)?.getTime()
2021-11-07 16:34:51 +01:00
if (ul === undefined) {
return
}
const ur = this.freshnessFor(z, x + 1, y)?.getTime()
2021-11-07 16:34:51 +01:00
if (ur === undefined) {
return
}
const ll = this.freshnessFor(z, x, y + 1)?.getTime()
2021-11-07 16:34:51 +01:00
if (ll === undefined) {
return
}
const lr = this.freshnessFor(z, x + 1, y + 1)?.getTime()
2021-11-07 16:34:51 +01:00
if (lr === undefined) {
return
}
const leastFresh = Math.min(ul, ur, ll, lr)
const date = new Date()
date.setTime(leastFresh)
2022-09-08 21:40:48 +02:00
this.addTileLoad(Tiles.tile_index(z - 1, Math.floor(x / 2), Math.floor(y / 2)), date)
}
2021-11-07 16:34:51 +01:00
public freshnessFor(z: number, x: number, y: number): Date {
if (z < 0) {
return undefined
}
const tileId = Tiles.tile_index(z, x, y)
2021-11-07 16:34:51 +01:00
if (this.freshnesses.has(tileId)) {
return this.freshnesses.get(tileId)
}
// recurse up
2021-11-07 16:34:51 +01:00
return this.freshnessFor(z - 1, Math.floor(x / 2), Math.floor(y / 2))
}
2022-09-08 21:40:48 +02:00
}