summaryrefslogtreecommitdiffhomepage
path: root/dragon/framerate.rb
blob: 255044313d513b6de3fff9e6916e333568f41ca0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# Copyright 2019 DragonRuby LLC
# MIT License
# framerate.rb has been released under MIT (*only this file*).

module GTK
  class Runtime
    module Framerate
      def framerate_init
        @tick_time = Time.new.to_i
      end

      def delta_framerate
        (current_framerate || 0) - (@previous_framerate || 0)
      end

      def reset_framerate_calculation
        @tick_speed_sum = 0
        @tick_speed_count = 0
        @previous_framerate = 0
      end

      def check_framerate
        if @framerate_diagnostics_requested
          log "================================"
          log framerate_get_diagnostics
          @framerate_diagnostics_requested = false
        end

        if !@paused
          if @tick_time
            @tick_speed_count += 1
            @tick_speed_sum += Time.now.to_i - @tick_time
            if @tick_speed_count > 60 * 2
              if framerate_below_threshold?
                @last_framerate = current_framerate
                if [email protected]?
                  if !@framerate_important_notification_happened
                    log_important framerate_warning_message
                  else
                    log framerate_warning_message
                  end
                  @framerate_important_notification_happened = true
                end
              end

              @previous_framerate = current_framerate.floor
            end
          end

          @tick_time = Time.new.to_i
        else
          reset_framerate_calculation
        end
      rescue
        reset_framerate_calculation
      end

      def framerate_diagnostics
        # request framerate diagnostics to be printed at the end of tick
        @framerate_diagnostics_requested = true
      end

      def framerate_below_threshold?
        @last_framerate ||= 60
        current_framerate < @last_framerate &&
          current_framerate < 50 &&
          @previous_framerate > current_framerate &&
          Kernel.tick_count > 600
      end

      def current_framerate
        return 60 if !@tick_speed_sum || !@tick_speed_sum
        r = 100.fdiv(@tick_speed_sum.fdiv(@tick_speed_count) * 100)
        if (r.nan? || r.infinite? || r > 58)
          r = 60
        end
        r || 60
      rescue
        60
      end
    end # module Framerate
  end # end class Runtime
end # end module GTK