Files

79 lines
2.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import time
from datetime import datetime, timedelta
class SimClock:
"""
Симулятор времени с управлением по ускорению.
- acceleration: -10..10, задаётся энкодером; пока != 0, velocity растёт
- velocity: множитель скорости (1.0 = реальное время, 60 = 1 мин/сек,
3600 = 1 час/сек, отрицательные значения = назад)
- При release (acceleration = 0) velocity плавно возвращается к 1.0
"""
ACCEL_RATE = 600.0 # прирост velocity за 1 с при acceleration=1
DECAY_RATE = 0.5 # скорость затухания velocity к 1.0 (τ ≈ 2 с)
MAX_VELOCITY = 7200.0 # 2 часа в секунду
MIN_VELOCITY = -7200.0
def __init__(self):
self._acceleration = 0.0
self._velocity = 1.0
self._sim_time = datetime.now()
self._last_update = time.time()
# --- внешнее управление ---
def set_acceleration(self, accel):
self._acceleration = max(-10.0, min(10.0, float(accel)))
def stop(self):
"""Однократное нажатие: немедленно нормальная скорость от текущей точки."""
self._acceleration = 0.0
self._velocity = 1.0
def reset_to_system_time(self):
"""Удержание: сброс на системное время + нормальная скорость."""
self._sim_time = datetime.now()
self._acceleration = 0.0
self._velocity = 1.0
# --- свойства для внешнего кода ---
@property
def acceleration(self):
return self._acceleration
@property
def speed(self):
"""Обратная совместимость — возвращает текущий множитель."""
return self._velocity
@property
def is_rewinding(self):
return self._acceleration != 0 or abs(self._velocity - 1.0) > 0.01
# --- обновление ---
def update(self):
now = time.time()
dt = now - self._last_update
self._last_update = now
if self._acceleration != 0.0:
self._velocity += self._acceleration * self.ACCEL_RATE * dt
else:
# плавное возвращение к нормальной скорости
self._velocity += (1.0 - self._velocity) * self.DECAY_RATE * dt
if self._velocity > self.MAX_VELOCITY:
self._velocity = self.MAX_VELOCITY
elif self._velocity < self.MIN_VELOCITY:
self._velocity = self.MIN_VELOCITY
self._sim_time += timedelta(seconds=dt * self._velocity)
@property
def current_time(self):
return self._sim_time
def time_string(self, fmt='%Y-%m-%d %H:%M:%S'):
return self._sim_time.strftime(fmt)