You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.4KB

  1. // Copyright 2011 Olivier Gillet.
  2. //
  3. // Author: Olivier Gillet (ol.gillet@gmail.com)
  4. //
  5. // This program is free software: you can redistribute it and/or modify
  6. // it under the terms of the GNU General Public License as published by
  7. // the Free Software Foundation, either version 3 of the License, or
  8. // (at your option) any later version.
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. //
  16. // -----------------------------------------------------------------------------
  17. //
  18. // Global clock. This works as a 31-bit phase increment counter. To implement
  19. // swing, the value at which the counter wraps is (1 << 31) times a swing
  20. // factor.
  21. #ifndef GRIDS_CLOCK_H_
  22. #define GRIDS_CLOCK_H_
  23. #include "avrlib/base.h"
  24. #include "grids/pattern_generator.h"
  25. namespace grids {
  26. class Clock {
  27. public:
  28. Clock() { }
  29. ~Clock() { }
  30. static inline void Init() {
  31. Update(120, CLOCK_RESOLUTION_24_PPQN);
  32. locked_ = false;
  33. }
  34. static void Update(uint16_t bpm, ClockResolution resolution);
  35. static inline void Reset() {
  36. phase_ = 0;
  37. }
  38. static inline void Tick() { phase_ += phase_increment_; }
  39. static inline void Wrap(int8_t amount) {
  40. LongWord* w = (LongWord*)(&phase_);
  41. if (amount == 0) {
  42. w->bytes[3] &= 0x7f;
  43. falling_edge_ = 0x40;
  44. } else {
  45. if (w->bytes[3] >= 128 + amount) {
  46. w->bytes[3] = 0;
  47. }
  48. falling_edge_ = (128 + amount) >> 1;
  49. }
  50. }
  51. static inline bool raising_edge() { return phase_ < phase_increment_; }
  52. static inline bool past_falling_edge() {
  53. LongWord w;
  54. w.value = phase_;
  55. return w.bytes[3] >= falling_edge_;
  56. }
  57. static inline void Lock() { locked_ = true; }
  58. static inline void Unlock() { locked_ = false; }
  59. static inline bool locked() { return locked_; }
  60. static inline uint16_t bpm() { return bpm_; }
  61. private:
  62. static bool locked_;
  63. static uint16_t bpm_;
  64. static uint32_t phase_;
  65. static uint32_t phase_increment_;
  66. static uint8_t falling_edge_;
  67. DISALLOW_COPY_AND_ASSIGN(Clock);
  68. };
  69. extern Clock clock;
  70. } // namespace grids
  71. #endif // GRIDS_CLOCK_H_