-
Notifications
You must be signed in to change notification settings - Fork 2
/
GranularLine.cpp
91 lines (73 loc) · 2.3 KB
/
GranularLine.cpp
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
84
85
86
87
88
89
90
91
//
// GranularLine.cpp
// DSPLibrary
//
// Created by Mayank on 9/11/12.
// Copyright (c) 2012 Mayank Sanganeria. All rights reserved.
//
#include "GranularLine.h"
void GranularLine::resetGrain(int i)
{
float lowerBound = fmaxf((avgDelay - 2 * spread * maxSpread * 0.5), 0);// + 0.01 * srate / length);
float upperBound = fminf((avgDelay + 2 * spread * maxSpread * 0.5), 1);
int delay;
if (upperBound == lowerBound)
delay = avgDelay * length;
else
delay = (lowerBound + fmodf((float)rand()/RAND_MAX, upperBound-lowerBound)) * length;
grains[i].readHead = (writeHead - delay + length)%length;
grains[i].grainLength = (int)((50 + rand()%100) * srate * 0.001);
grains[i].elapsed = 0;
if (i <= numGrains)
grains[i].isActive = 1;
else
grains[i].isActive = 0;
grains[i].currentNumGrainsAmplitude = 1/sqrtf(numGrains) * grains[i].isActive;
}
void GranularLine::setLength(const float withLength, float withFs) {
length = withLength * withFs;
circularBuffer = new float[length];
clearBuffer(); // clear the buffer before we start writing into it
grains = new Grain[numGrains];
for (int i=0;i<numGrains;i++)
{
resetGrain(i);
}
writeHead = 0;
setRate(1.0);
populateWindow(); // create window buffer
}
void GranularLine::clearBuffer() {
for (int i = 0; i < length; i++) { // clear buffer
circularBuffer[(i + length) % length] = 0;
}
}
void GranularLine::advanceWriteHead() {
writeHead = (writeHead + rate)%length;
}
void GranularLine::write(float withSample) {
circularBuffer[writeHead] = withSample;
}
float GranularLine::readGrain(int i) {
float window = getWindow((float)grains[i].elapsed/grains[i].grainLength);
float sample = window * circularBuffer[(grains[i].readHead+grains[i].elapsed++)%length];
if (grains[i].elapsed>=grains[i].grainLength)
{
resetGrain(i);
}
return sample*grains[i].currentNumGrainsAmplitude;
}
float GranularLine::getWindow(float x)
{
int index = x*length;
return cosValues[index];
}
void GranularLine::populateWindow()
{
cosValues = new float[length];
for (int i=0;i<length;i++)
cosValues[i] = 0.5-0.5*cosf(2*M_PI*i/length);
}
void GranularLine::setRate(float withRate) {
rate = withRate;
}