humus-old/common/world-time.js

76 lines
1.6 KiB
JavaScript
Raw Normal View History

2019-05-13 21:07:57 -05:00
import {compose} from '@avocado/core';
import {Synchronized} from '@avocado/state';
2019-04-04 07:31:21 -05:00
import {Ticker} from '@avocado/timing';
2019-05-13 21:07:57 -05:00
import {WorldTimePacket} from './world-time.packet';
const MAGIC_TO_FIT_HOUR_INTO_USHORT = 2730;
2019-05-13 21:07:57 -05:00
const decorate = compose(
Synchronized,
);
export class WorldTime extends decorate(class {}) {
2019-04-04 07:31:21 -05:00
constructor() {
2019-05-13 21:07:57 -05:00
super();
2019-04-08 08:01:39 -05:00
this._hour = 0;
2019-05-13 21:07:57 -05:00
this._isUpdateReady = true;
this._lastHour = 0;
2019-04-23 15:26:56 -05:00
this.ticker = new Ticker(0.25);
2019-04-04 07:31:21 -05:00
this.ticker.on('tick', () => {
2019-05-13 21:07:57 -05:00
this._isUpdateReady = true;
2019-04-04 07:31:21 -05:00
});
}
2019-05-13 21:07:57 -05:00
acceptPacket(packet) {
if (packet instanceof WorldTimePacket) {
this._hour = packet.data / MAGIC_TO_FIT_HOUR_INTO_USHORT;
}
}
2019-04-12 11:01:55 -05:00
static format(time) {
const rawHour = (time + 12) % 12;
const hour = Math.floor(0 === Math.floor(rawHour) ? 12 : rawHour);
const minutes = String(Math.floor((rawHour - Math.floor(rawHour)) * 60)).padStart(2, '0');
if (time >= 12) {
return `${hour}:${minutes} pm`;
}
else {
return `${hour}:${minutes} am`;
}
}
2019-04-08 08:01:39 -05:00
get hour() {
return this._hour;
}
set hour(hour) {
this._hour = hour;
2019-04-04 07:31:21 -05:00
}
2019-05-13 21:07:57 -05:00
packetsForUpdate(force) {
const updates = [];
if (force || this._isUpdateReady) {
updates.push(new WorldTimePacket(
(this._hour * MAGIC_TO_FIT_HOUR_INTO_USHORT) >> 0
));
}
if (!force) {
this._isUpdateReady = false;
2019-04-05 22:14:17 -05:00
}
2019-05-13 21:07:57 -05:00
return updates;
2019-04-05 15:16:50 -05:00
}
2019-04-04 07:31:21 -05:00
secondsPerHour() {
return 60;
}
tick(elapsed) {
2019-04-08 08:01:39 -05:00
this._hour += (elapsed / this.secondsPerHour());
this._hour = this._hour % 24;
2019-04-04 07:31:21 -05:00
this.ticker.tick(elapsed);
}
}