From edddfd5879952ef8c06f51c82917fa0c5b7a1c00 Mon Sep 17 00:00:00 2001 From: Adam Wonak Date: Tue, 1 Jul 2025 12:23:50 -0700 Subject: [PATCH] Optimize euclidean pattern by changing from an array of ints to a bitmask. --- examples/Gravity/euclidean.h | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/examples/Gravity/euclidean.h b/examples/Gravity/euclidean.h index 57e5cb6..f18e0ac 100644 --- a/examples/Gravity/euclidean.h +++ b/examples/Gravity/euclidean.h @@ -1,7 +1,7 @@ #ifndef EUCLIDEAN_H #define EUCLIDEAN_H -#define MAX_PATTERN_LEN 16 +#define MAX_PATTERN_LEN 32 struct PatternState { uint8_t steps; @@ -26,9 +26,12 @@ class Pattern { updatePattern(); } - PatternState GetState() { return {steps_, hits_}; } + PatternState GetState() const { return {steps_, hits_}; } - Step GetCurrentStep(byte i) { return pattern_[i]; } + Step GetCurrentStep(byte i) { + if (i >= MAX_PATTERN_LEN) return REST; + return (pattern_bitmap_ & (1UL << i)) ? HIT : REST; + } void SetSteps(int steps) { steps_ = constrain(steps, 1, MAX_PATTERN_LEN); @@ -47,8 +50,6 @@ class Pattern { uint8_t GetHits() { return hits_; } uint8_t GetStepIndex() { return step_index_; } - // Get the current step value and advance the euclidean rhythm step index - // to the next step in the pattern. Step NextStep() { if (steps_ == 0) return REST; @@ -61,19 +62,23 @@ class Pattern { uint8_t steps_ = 0; uint8_t hits_ = 0; volatile uint8_t step_index_ = 0; - Step pattern_[MAX_PATTERN_LEN]; + uint32_t pattern_bitmap_ = 0; - // Update the euclidean rhythm pattern when attributes change. + // Update the euclidean rhythm pattern using bitmap void updatePattern() { + pattern_bitmap_ = 0; // Clear the bitmap + + if (steps_ == 0) return; + byte bucket = 0; - pattern_[0] = HIT; + // Set the first bit (index 0) if it's a HIT + pattern_bitmap_ |= (1UL << 0); + for (int i = 1; i < steps_; i++) { bucket += hits_; if (bucket >= steps_) { bucket -= steps_; - pattern_[i] = HIT; - } else { - pattern_[i] = REST; + pattern_bitmap_ |= (1UL << i); } } }