
    ^jU                    &   d Z ddlmZ ddlZddlmZmZ ddlm	Z
 ddlmZ ddlmZ ddlmZ dd	lmZ  G d
 d          Z G d d          Z G d d          Z e            ad,dZd-dZd.d/dZd0dZd1dZd2d#Zd3d%Zd4d'Z d5d(Z!d6d*Z"d7d+Z#dS )8a  Precise framerate calculation function scheduling.

The :py:mod:`~pyglet.clock` module allows you to schedule functions
to run periodically, or for one-shot future execution. pyglet's default
event loop (:py:func:`~pyglet.app.run`) keeps an internal instance of
a :py:class:`~pyglet.clock.Clock`, which is ticked automatically.

.. note:: Some internal modules will schedule items on the clock. If you
          are using a custom event loop, always remember to `tick` the clock!

Scheduling
==========

You can schedule a function to be called every time the clock is ticked::

    def callback(dt):
        print(f"{dt} seconds since last callback")

    clock.schedule(callback)

The `schedule_interval` method causes a function to be called every "n"
seconds::

    clock.schedule_interval(callback, 0.5)   # called twice a second

The `schedule_once` method causes a function to be called once "n" seconds
in the future::

    clock.schedule_once(callback, 5)        # called in 5 seconds

All the `schedule` methods will pass on any additional args or keyword args
you specify to the callback function::

    def move(dt, velocity, sprite):
        sprite.position += dt * velocity

    clock.schedule(move, velocity=5.0, sprite=alien)

You can cancel a function scheduled with any of these methods using
`unschedule`::

    clock.unschedule(move)

Using multiple clocks
=====================

The clock functions are all relayed to an instance of
:py:class:`~pyglet.clock.Clock` which is initialised with the module.  You can
get this instance to use directly::

    clk = pyglet.clock.get_default()

You can also replace the default clock with your own:

    myclk = pyglet.clock.Clock()
    pyglet.clock.set_default(myclk)

Each clock maintains its own set of scheduled functions and frequency
measurement.  Each clock must be "ticked" separately.

Multiple and derived clocks potentially allow you to separate "game-time" and
"wall-time", or to synchronise your clock to an audio or video stream instead
of the system clock.
    )annotationsN)AnyCallable)heappop)heappush)heappushpop)
attrgetter)dequec                      e Zd Zg dZdd	Zd
S )_ScheduledItemfuncargskwargsr   r   r   r   r   returnNonec                0    || _         || _        || _        d S Nr   )selfr   r   r   s       G/home/agentuser/manim-venv/lib/python3.11/site-packages/pyglet/clock.py__init__z_ScheduledItem.__init__Q   s    		    Nr   r   r   r   r   r   r   r   )__name__
__module____qualname__	__slots__r    r   r   r   r   N   s3        ***I     r   r   c                  &    e Zd Zg dZddZddZdS )_ScheduledIntervalItemr   intervallast_tsnext_tsr   r   r   r   r"   floatr#   r$   r   r   r   r   r   c                Z    || _         || _        || _        || _        || _        || _        d S r   r!   )r   r   r"   r#   r$   r   r   s          r   r   z_ScheduledIntervalItem.__init__Z   s0    	 	r   otherboolc                "    | j         |j         k     S r   )r$   )r   r'   s     r   __lt__z_ScheduledIntervalItem.__lt__b   s    |em++r   N)r   r   r"   r%   r#   r%   r$   r%   r   r   r   r   r   r   )r'   r    r   r(   )r   r   r   r   r   r*   r   r   r   r    r    W   sG        LLLI   , , , , , ,r   r    c                      e Zd ZU ded<   ded<   dZded<   ej        fd)dZed*d            Z	d+dZ
d,dZd-d.dZd/dZd+dZd+dZd0dZd1d Zd2d"Zd3d#Zd4d%Zd3d&Zd5d'Zd(S )6Clocklist_schedule_items_schedule_interval_itemsFr(   _force_sleeptime_functionr   r   r   c                    || _         d| _        |                                  | _        t                      | _        d| _        d| _        g | _        g | _        d| _	        dS )a3  Initialise a Clock, with optional custom time function.

        You can provide a custom time function to return the elapsed
        time of the application, in seconds. Defaults to ``time.perf_counter``,
        but can be replaced to allow for easy time dilation effects or game
        pausing.
        N        <   )
timer#   r$   _dequetimescumulative_timewindow_sizer.   r/   _current_interval_item)r   r1   s     r   r   zClock.__init__q   s\     "	yy{{ $XX
"!(*%&*###r   microsecondsr%   c                4    t          j        | dz             d S )Ngư>)_timesleep)r;   s    r   r>   zClock.sleep   s    L4'(((((r   c                @   |                                  }| j        d}nh|| j        z
  }| j                            |           t	          | j                  | j        k    r'| xj        | j                                        z  c_        | xj        |z  c_        || _        |S )a	  Get the elapsed time since the last call to `update_time`.

        This updates the clock's internal measure of time and returns
        the difference (in seconds) since the last time it was called.
        The first call of this method always returns 0.
        Nr3   )r5   r#   r7   
appendleftlenr9   r8   pop)r   tsdelta_ts      r   update_timezClock.update_time   s     YY[[<GG4<'GJ!!'***4:!111$$
(8(88$$'r   dtc                   | j         p|                                 }d}| j        r4d}t          | j                  D ]} |j        |g|j        R i |j         | j        }	 |d         j        |k    r|S n# t          $ r |cY S w xY wdx| _
        }| j        }|r|t          |          }nt          ||          }|| _
        |j        |k    rn |j        ||j         z
  g|j        R i |j         |j        ro|j         |j        z   |_        ||_         |j        |k    rH||j        z
  dk     r||j        z   |_        n4 |||j                  |_        |j        |j        z
  |_         n	dx| _
        }||t          ||           dS )a  Call scheduled functions that elapsed on the last `update_time`.

        This method is called automatically when the clock is ticked
        (see :py:meth:`~pyglet.clock.tick`), so you need not call it
        yourself in most cases.

        Args:
            dt:
                The elapsed time since the last update to pass to each
                scheduled function. This is *not* used to calculate which
                functions have elapsed.

        Returns: ``True`` if any functions were called, else ``False``.
        FTr   Ng?)r#   r5   r.   r-   r   r   r   r/   r$   
IndexErrorr:   _get_soft_next_ts_heappop_heappushpopr"   	_heappush)r   rF   nowresultiteminterval_itemsget_soft_next_tss          r   call_scheduled_functionszClock.call_scheduled_functions   s    l)diikk  	9FT122 9 9	"8ty888DK8888 6	a (3.. / 	 	 	MMM	 .21#d1 /	:
 |//#ND99
 +/D' |c!! DIcDL(D49DDDDDD} :
  $|dm;" <3&& T\)D00 (+T]': (8'7T]'K'K'+|dm'C 6:9+d_  /	:b nd+++ts   !A5 5BBpollc                    |s| j         r|                     d           |                                 }|                     |           |S )a$  Signify that one frame has passed.

        This will call any scheduled functions that have elapsed,
        and returns the number of seconds since the last time this
        method has been called. The first time this method is called,
        0 is returned.

        Args:
            poll:
                If True, the function will call any scheduled functions
                but will not sleep or busy-wait for any reason.  Recommended
                for advanced applications managing their own sleep timers
                only.
        r   )r0   r>   rE   rR   )r   rS   rD   s      r   tickz
Clock.tick   sO      	) 	JJqMMM""$$%%g...r   
sleep_idlefloat | Nonec                    | j         s|sdS | j        r5t          | j        d         j        |                                 z
  d          S dS )a;  Get the time until the next item is scheduled, if any.

        Applications can choose to continue receiving updates at the
        maximum framerate during idle time (when no functions are scheduled),
        or they can sleep through their idle time and allow the CPU to
        switch to other processes or run in low-power mode.

        If ``sleep_idle`` is ``True`` the latter behaviour is selected, and
        ``None`` will be returned if there are no scheduled items.

        Otherwise, if ``sleep_idle`` is ``False``, or if any scheduled items
        exist, a value of 0 is returned.

        Args:
            sleep_idle:
                If True, the application intends to sleep through its idle
                time; otherwise it will continue ticking at the maximum
                frame rate allowed.
        r3   r   N)r.   r/   maxr$   r5   )r   rV   s     r   get_sleep_timezClock.get_sleep_time  sT    (  	z 	3( 	Tt4Q7?$))++MsSSStr   c                L    | j         sdS t          | j                  | j         z  S )a(  Get the average clock update frequency of recent history.

        The result is the average of a sliding window of the last "n" updates,
        where "n" is some number designed to cover approximately 1 second.
        This is the clock frequency, **not** the Window redraw rate (fps).
        r   )r8   rA   r7   )r   s    r   get_frequencyzClock.get_frequency-  s*     # 	14:!555r   c                `    | j         p| j        }|                                 }||z
  dk    r|S |S )zGet the nearest timestamp.

        Schedule from now, unless now is sufficiently close to last_ts, in
        which case use last_ts.  This clusters together scheduled items that
        probably want to be scheduled together.
        g?)r#   r$   r5   )r   r#   rC   s      r   _get_nearest_tszClock._get_nearest_ts8  s8     ,.$,YY[[<#Ir   r#   r"   c                    d fd} j                             t          d                     ||z   } |||d	z            s|S |}d
}	 |}t          |d
z
            D ]}||z  } |||d	z            s|c S |dz  }|dz  }|dk    r|S B)NrC   r%   er   r(   c                z    j         D ]1}t          |j        | z
            |k    r dS |j        | |z   k    r dS 2dS )z7Check if `ts` has already got an item scheduled nearby.TF)r/   absr$   )rC   r`   rO   r   s      r   takenz&Clock._get_soft_next_ts.<locals>.takenG  s\     5 ! !t|b())Q..44\BF** 55 + 5r   r$   )key      T      )rC   r%   r`   r%   r   r(   )r/   sort_attrgetterrange)r   r#   r"   rc   r$   rF   divs_s   `       r   rI   zClock._get_soft_next_tsE  s    
	 
	 
	 
	 
	 
	" 	%**{9/E/E*FFF" H$uWhl++ 	N	G4!8__ # #2uWb1f-- #"NNN#!GBAID byy	r   r   r   r   r   c                \    t          |||          }| j                            |           dS )a  Schedule a function to be called every tick.

        The scheduled function should have a prototype that includes ``dt``
        as the first argument, which gives the elapsed time in seconds since
        the last clock tick. Any additional args or kwargs given to this
        method are passed on to the callback::

            def callback(dt, *args, **kwargs):
                pass


        .. note:: Functions scheduled using this method will be called
                  every tick by the default pyglet event loop, which can
                  lead to high CPU usage. It is usually better to use
                  :py:meth:`~pyglet.clock.schedule_interval` unless
                  this is desired.
        N)r   r.   append)r   r   r   r   rO   s        r   schedulezClock.schedule|  s2    $ dD&11##D)))))r   delayc                    |                                  }||z   }t          |d||||          }t          | j        |           dS )zSchedule a function to be called once after ``delay`` seconds.

        The callback function prototype is the same as for
        :py:meth:`~pyglet.clock.Clock.schedule`.
        r   Nr^   r    rL   r/   )r   r   rq   r   r   r#   r$   rO   s           r   schedule_oncezClock.schedule_once  sN     &&((E/%dAwvNN$/66666r   c                    |                                  }||z   }t          ||||||          }t          | j        |           dS )a  Schedule a function to be called every ``interval`` seconds.

        To schedule a function to be called at 60Hz (60fps), you would use ``1/60``
        for the interval, and so on. If pyglet is unable to call the function on
        time, the schedule will be skipped (not accumulated). This can occur if the
        main thread is overloaded, or other hard blocking calls taking place.

        The callback function prototype is the same as for
        :py:meth:`~pyglet.clock.Clock.schedule`.

        .. note:: Specifying an interval of ``0`` will prevent the function from
                  being called again. If you want to schedule a function to be called
                  as often as possible, see :py:meth:`~pyglet.clock.Clock.schedule`.
        Nrs   )r   r   r"   r   r   r#   r$   rO   s           r   schedule_intervalzClock.schedule_interval  sO     &&((H$%dHgwfUU$/66666r   durationc                f     d	 fd}  j         ||g|R i |                      |||           dS )
a  Temporarily schedule a function to be called every ``interval`` seconds.

        This method will schedule a function to be called every ``interval``
        seconds (see  :py:meth:`~pyglet.clock.Clock.schedule_interval`), but
        will automatically unschedule it after ``duration`` seconds.

        The callback function prototype is the same as for
        :py:meth:`~pyglet.clock.Clock.schedule`.

        :Args:
            func:
                The function to call when the timer lapses.
            interval:
                The number of seconds to wait between each call.
            duration:
                The number of seconds for which the function is scheduled.
        _dtr%   _funcr   r   r   c                2                         |           d S r   )
unschedule)ry   rz   r   s     r   _unschedulez9Clock.schedule_interval_for_duration.<locals>._unschedule  s    OOE"""""r   N)ry   r%   rz   r   r   r   )rv   rt   )r   r   r"   rw   r   r   r}   s   `      r   schedule_interval_for_durationz$Clock.schedule_interval_for_duration  sf    (	# 	# 	# 	# 	# 	# 	tX???????;$77777r   c                    |                      |                                 |          }||z
  }t          ||||||          }t          | j        |           dS )a8  Schedule a function to be called approximately every ``interval`` seconds.

        This method is similar to :py:meth:`~pyglet.clock.Clock.schedule_interval`,
        except that the clock will move the interval out of phase with other
        scheduled functions in order to distribute CPU load more evenly.

        This is useful for functions that need to be called regularly,
        but not relative to the initial start time.  :py:mod:`pyglet.media`
        does this for scheduling audio buffer updates, which need to occur
        regularly -- if all audio updates are scheduled at the same time
        (for example, mixing several tracks of a music score, or playing
        multiple videos back simultaneously), the resulting load on the
        CPU is excessive for those intervals but idle outside.  Using
        the soft interval scheduling, the load is more evenly distributed.

        Soft interval scheduling can also be used as an easy way to schedule
        graphics animations out of phase; for example, multiple flags
        waving in the wind.
        N)rI   r^   r    rL   r/   )r   r   r"   r   r   r$   r#   rO   s           r   schedule_interval_softzClock.schedule_interval_soft  s_    ( (()=)=)?)?JJH$%dHgwfUU$/66666r   c                    fd| j         D             }| j        r*| j        j        k    r|                    | j                   |D ]}d|_        d |_        fd| j        D             | _        dS )zRemove a function from the schedule.

        If the function appears in the schedule more than once, all occurrences
        are removed.  If the function was not scheduled, no error is raised.
        c                *    h | ]}|j         k    |S r   r   ).0rO   r   s     r   	<setcomp>z#Clock.unschedule.<locals>.<setcomp>  s&    [[[VZIZIZtIZIZIZr   r   c                    | S r   r   )xr   r   s      r   <lambda>z"Clock.unschedule.<locals>.<lambda>  s    1 r   c                *    g | ]}|j         k    |S r   r   )r   ir   s     r   
<listcomp>z$Clock.unschedule.<locals>.<listcomp>  s     RRRa16T>>>>>r   N)r/   r:   r   addr"   r.   )r   r   valid_itemsrO   s    `  r   r|   zClock.unschedule  s     \[[[(E[[[& 	94+F+Kt+S+SOOD7888 	5 	5DDM44DIIRRRR4+?RRRr   N)r1   r   r   r   )r;   r%   r   r   r   r%   )rF   r%   r   r(   FrS   r(   r   r%   rV   r(   r   rW   )r#   r%   r"   r%   r   r%   r   )
r   r   rq   r%   r   r   r   r   r   r   
r   r   r"   r%   r   r   r   r   r   r   )r   r   r"   r%   rw   r%   r   r   r   r   r   r   r   r   r   r   )r   r   r   __annotations__r0   r=   perf_counterr   staticmethodr>   rE   rR   rU   rZ   r\   r^   rI   rp   rt   rv   r~   r   r|   r   r   r   r,   r,   f   s          #""" L161C + + + + +* ) ) ) \)   ([ [ [ [z    ,   8	6 	6 	6 	6   5 5 5 5n* * * **	7 	7 	7 	77 7 7 7(8 8 8 847 7 7 72S S S S S Sr   r,   defaultr   r   c                
    | a dS )zSet the default clock to use for all module-level functions.

    By default, an instance of :py:class:`~pyglet.clock.Clock` is used.
    N_default)r   s    r   set_defaultr     s     HHHr   c                     t           S )zGet the pyglet default Clock.

    Return the :py:class:`~pyglet.clock.Clock` instance that is used by all
    module-level clock functions.
    r   r   r   r   get_defaultr     s	     Or   FrS   r(   r%   c                6    t                               |           S )z*:see: :py:meth:`~pyglet.clock.Clock.tick`.)r   rU   )rS   s    r   rU   rU     s    ==r   rV   rW   c                6    t                               |           S )z4:see: :py:meth:`~pyglet.clock.Clock.get_sleep_time`.)r   rZ   )rV   s    r   rZ   rZ     s    "":...r   c                 4    t                                           S )z3:see: :py:meth:`~pyglet.clock.Clock.get_frequency`.)r   r\   r   r   r   r\   r\     s    !!###r   r   r   r   r   r   c                0    t          j        | g|R i | dS )z.:see: :py:meth:`~pyglet.clock.Clock.schedule`.N)r   rp   r   s      r   rp   rp     s)    d,T,,,V,,,,,r   r"   c                2    t          j        | |g|R i | dS )z7:see: :py:meth:`~pyglet.clock.Clock.schedule_interval`.N)r   rv   r   r"   r   r   s       r   rv   rv   "  s+    tX?????????r   rw   c                4    t          j        | ||g|R i | dS )zD:see: :py:meth:`~pyglet.clock.Clock.schedule_interval_for_duration`.N)r   r~   )r   r"   rw   r   r   s        r   r~   r~   '  s-    +D(HVtVVVvVVVVVr   c                2    t          j        | |g|R i | dS )z<:see: :py:meth:`~pyglet.clock.Clock.schedule_interval_soft`.N)r   r   r   s       r   r   r   ,  s+    #D(DTDDDVDDDDDr   rq   c                2    t          j        | |g|R i | dS )z3:see: :py:meth:`~pyglet.clock.Clock.schedule_once`.N)r   rt   )r   rq   r   r   s       r   rt   rt   1  s+    4888888888r   c                :    t                               |            dS )z0:see: :py:meth:`~pyglet.clock.Clock.unschedule`.N)r   r|   r   s    r   r|   r|   6  s    r   )r   r,   r   r   )r   r,   r   r   r   r   r   r   )r   r   r"   r%   rw   r%   r   r   )r   r   r"   r%   r   r   )r   r   rq   r%   r   r   r   )$__doc__
__future__r   r5   r=   typingr   r   heapqr   rJ   r   rL   r   rK   operatorr	   rj   collectionsr
   r6   r   r    r,   r   r   r   rU   rZ   r\   rp   rv   r~   r   rt   r|   r   r   r   <module>r      s/  ? ?@ # " " " " "                     % % % % % % ' ' ' ' ' ' - - - - - - . . . . . . ' ' ' ' ' '       , , , , , , , ,OS OS OS OS OS OS OS OSf 577          
/ / / /
$ $ $ $
- - - -
@ @ @ @
W W W W
E E E E
9 9 9 9
     r   