gioui.org@v0.6.1-0.20240506124620-7a9ce51988ce/gpu/timer.go (about)

     1  // SPDX-License-Identifier: Unlicense OR MIT
     2  
     3  package gpu
     4  
     5  import (
     6  	"time"
     7  
     8  	"gioui.org/gpu/internal/driver"
     9  )
    10  
    11  type timers struct {
    12  	backend driver.Device
    13  	timers  []*timer
    14  }
    15  
    16  type timer struct {
    17  	Elapsed time.Duration
    18  	backend driver.Device
    19  	timer   driver.Timer
    20  	state   timerState
    21  }
    22  
    23  type timerState uint8
    24  
    25  const (
    26  	timerIdle timerState = iota
    27  	timerRunning
    28  	timerWaiting
    29  )
    30  
    31  func newTimers(b driver.Device) *timers {
    32  	return &timers{
    33  		backend: b,
    34  	}
    35  }
    36  
    37  func (t *timers) newTimer() *timer {
    38  	if t == nil {
    39  		return nil
    40  	}
    41  	tt := &timer{
    42  		backend: t.backend,
    43  		timer:   t.backend.NewTimer(),
    44  	}
    45  	t.timers = append(t.timers, tt)
    46  	return tt
    47  }
    48  
    49  func (t *timer) begin() {
    50  	if t == nil || t.state != timerIdle {
    51  		return
    52  	}
    53  	t.timer.Begin()
    54  	t.state = timerRunning
    55  }
    56  
    57  func (t *timer) end() {
    58  	if t == nil || t.state != timerRunning {
    59  		return
    60  	}
    61  	t.timer.End()
    62  	t.state = timerWaiting
    63  }
    64  
    65  func (t *timers) ready() bool {
    66  	if t == nil {
    67  		return false
    68  	}
    69  	for _, tt := range t.timers {
    70  		switch tt.state {
    71  		case timerIdle:
    72  			continue
    73  		case timerRunning:
    74  			return false
    75  		}
    76  		d, ok := tt.timer.Duration()
    77  		if !ok {
    78  			return false
    79  		}
    80  		tt.state = timerIdle
    81  		tt.Elapsed = d
    82  	}
    83  	return t.backend.IsTimeContinuous()
    84  }
    85  
    86  func (t *timers) Release() {
    87  	if t == nil {
    88  		return
    89  	}
    90  	for _, tt := range t.timers {
    91  		tt.timer.Release()
    92  	}
    93  	t.timers = nil
    94  }