# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import compat from typing import Generator def delay(secs: float) -> Generator[None, None, None]: end = compat.monotonic() + secs while compat.monotonic() < end: yield None def fps(fps: float) -> Generator[None, None, None]: yield None dt = 1 / fps until = compat.monotonic() + dt while True: remain = until - compat.monotonic() if remain > 0: compat.sleep(remain) until += dt if remain < -dt: # Catch up a bit until += -remain / 3 yield None def wait(stop_ms: int) -> Generator[int, None, None]: """Waits for stop_ms to pass, yielding how many ms have passed so far.""" start = compat.monotonic() while True: elapsed = int((compat.monotonic() - start) * 1000) elapsed = min(stop_ms, elapsed) yield elapsed if elapsed >= stop_ms: break