id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
29,952
DynNoiseUGens.cpp
supercollider_supercollider/server/plugins/DynNoiseUGens.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* * DynNoiseUGens.cpp * xSC3plugins * * Created by Alberto de Campo, Sekhar Ramacrishnan, Julian Rohrhuber on Sun May 30 2004. * Copyright (c) 2004 HfbK. All rights reserved. * */ #include "SC_PlugIn.h" static InterfaceTable* ft; struct LFDNoise0 : public Unit { float mLevel; float mPhase; }; struct LFDNoise1 : public Unit { float mPhase; float mPrevLevel; float mNextLevel; }; struct LFDNoise3 : public Unit { float mPhase; float mLevelA, mLevelB, mLevelC, mLevelD; }; struct LFDClipNoise : public Unit { float mLevel; float mPhase; }; ////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" { void LFDNoise0_next(LFDNoise0* unit, int inNumSamples); void LFDNoise0_next_k(LFDNoise0* unit, int inNumSamples); void LFDNoise0_Ctor(LFDNoise0* unit); void LFDNoise1_next(LFDNoise1* unit, int inNumSamples); void LFDNoise1_next_k(LFDNoise1* unit, int inNumSamples); void LFDNoise1_Ctor(LFDNoise1* unit); void LFDNoise3_next(LFDNoise3* unit, int inNumSamples); void LFDNoise3_next_k(LFDNoise3* unit, int inNumSamples); void LFDNoise3_Ctor(LFDNoise3* unit); void LFDClipNoise_next(LFDClipNoise* unit, int inNumSamples); void LFDClipNoise_Ctor(LFDClipNoise* unit); } ////////////////////////////////////////////////////////////////////////////////////////////////// void LFDNoise0_next(LFDNoise0* unit, int inNumSamples) { float* out = ZOUT(0); float* freq = ZIN(0); float level = unit->mLevel; float phase = unit->mPhase; float smpdur = SAMPLEDUR; RGET LOOP1( inNumSamples, phase -= ZXP(freq) * smpdur; if (phase < 0) { phase = sc_wrap(phase, 0.f, 1.f); level = frand2(s1, s2, s3); } ZXP(out) = level;) unit->mLevel = level; unit->mPhase = phase; RPUT } void LFDNoise0_next_k(LFDNoise0* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); float level = unit->mLevel; float phase = unit->mPhase; float smpdur = SAMPLEDUR; float dphase = smpdur * freq; RGET LOOP1( inNumSamples, phase -= dphase; if (phase < 0) { phase = sc_wrap(phase, 0.f, 1.f); level = frand2(s1, s2, s3); } ZXP(out) = level;) unit->mLevel = level; unit->mPhase = phase; RPUT } void LFDNoise0_Ctor(LFDNoise0* unit) { if (INRATE(0) == calc_FullRate) { SETCALC(LFDNoise0_next); } else { SETCALC(LFDNoise0_next_k); } unit->mPhase = 0.f; unit->mLevel = 0.f; LFDNoise0_next(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// void LFDNoise1_next(LFDNoise1* unit, int inNumSamples) { float* out = ZOUT(0); float* freq = ZIN(0); float prevLevel = unit->mPrevLevel; float nextLevel = unit->mNextLevel; float phase = unit->mPhase; float smpdur = SAMPLEDUR; RGET LOOP1( inNumSamples, phase -= ZXP(freq) * smpdur; if (phase < 0) { phase = sc_wrap(phase, 0.f, 1.f); prevLevel = nextLevel; nextLevel = frand2(s1, s2, s3); } ZXP(out) = nextLevel + (phase * (prevLevel - nextLevel));) unit->mPrevLevel = prevLevel; unit->mNextLevel = nextLevel; unit->mPhase = phase; RPUT } void LFDNoise1_next_k(LFDNoise1* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); float prevLevel = unit->mPrevLevel; float nextLevel = unit->mNextLevel; float phase = unit->mPhase; float smpdur = SAMPLEDUR; float dphase = freq * smpdur; RGET LOOP1( inNumSamples, phase -= dphase; if (phase < 0) { phase = sc_wrap(phase, 0.f, 1.f); prevLevel = nextLevel; nextLevel = frand2(s1, s2, s3); } ZXP(out) = nextLevel + (phase * (prevLevel - nextLevel));) unit->mPrevLevel = prevLevel; unit->mNextLevel = nextLevel; unit->mPhase = phase; RPUT } void LFDNoise1_Ctor(LFDNoise1* unit) { if (INRATE(0) == calc_FullRate) { SETCALC(LFDNoise1_next); } else { SETCALC(LFDNoise1_next_k); } unit->mPhase = 0.f; unit->mPrevLevel = 0.f; unit->mNextLevel = unit->mParent->mRGen->frand2(); LFDNoise1_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void LFDNoise3_next(LFDNoise3* unit, int inNumSamples) { float* out = ZOUT(0); float* freq = ZIN(0); float a = unit->mLevelA; float b = unit->mLevelB; float c = unit->mLevelC; float d = unit->mLevelD; float phase = unit->mPhase; float smpdur = SAMPLEDUR; RGET LOOP1( inNumSamples, phase -= ZXP(freq) * smpdur; if (phase < 0) { phase = sc_wrap(phase, 0.f, 1.f); a = b; b = c; c = d; d = frand2(s1, s2, s3) * 0.8f; // limits max interpol. overshoot to 1. } ZXP(out) = cubicinterp(1.f - phase, a, b, c, d);) unit->mLevelA = a; unit->mLevelB = b; unit->mLevelC = c; unit->mLevelD = d; unit->mPhase = phase; RPUT } void LFDNoise3_next_k(LFDNoise3* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); float a = unit->mLevelA; float b = unit->mLevelB; float c = unit->mLevelC; float d = unit->mLevelD; float phase = unit->mPhase; float dphase = freq * SAMPLEDUR; RGET LOOP1( inNumSamples, phase -= dphase; if (phase < 0) { phase = sc_wrap(phase, 0.f, 1.f); a = b; b = c; c = d; d = frand2(s1, s2, s3) * 0.8f; // limits max interpol. overshoot to 1. } ZXP(out) = cubicinterp(1.f - phase, a, b, c, d);) unit->mLevelA = a; unit->mLevelB = b; unit->mLevelC = c; unit->mLevelD = d; unit->mPhase = phase; RPUT } void LFDNoise3_Ctor(LFDNoise3* unit) { if (INRATE(0) == calc_FullRate) { SETCALC(LFDNoise3_next); } else { SETCALC(LFDNoise3_next_k); } RGET unit->mPhase = 0.f; unit->mLevelA = frand2(s1, s2, s3) * 0.8f; // limits max interpol. overshoot to 1. unit->mLevelB = frand2(s1, s2, s3) * 0.8f; unit->mLevelC = frand2(s1, s2, s3) * 0.8f; unit->mLevelD = frand2(s1, s2, s3) * 0.8f; RPUT LFDNoise3_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void LFDClipNoise_next(LFDClipNoise* unit, int inNumSamples) { float* out = ZOUT(0); float* freq = ZIN(0); float level = unit->mLevel; float phase = unit->mPhase; float smpdur = SAMPLEDUR; RGET LOOP1( inNumSamples, phase -= ZXP(freq) * smpdur; if (phase < 0) { phase = sc_wrap(phase, 0.f, 1.f); level = fcoin(s1, s2, s3); } ZXP(out) = level;) unit->mLevel = level; unit->mPhase = phase; RPUT } void LFDClipNoise_next_k(LFDClipNoise* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); float level = unit->mLevel; float phase = unit->mPhase; float smpdur = SAMPLEDUR; float dphase = smpdur * freq; RGET LOOP1( inNumSamples, phase -= dphase; if (phase < 0) { phase = sc_wrap(phase, 0.f, 1.f); level = fcoin(s1, s2, s3); } ZXP(out) = level;) unit->mLevel = level; unit->mPhase = phase; RPUT } void LFDClipNoise_Ctor(LFDClipNoise* unit) { if (INRATE(0) == calc_FullRate) { SETCALC(LFDClipNoise_next); } else { SETCALC(LFDClipNoise_next_k); } unit->mPhase = 0.f; unit->mLevel = 0.f; LFDClipNoise_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// PluginLoad(DynNoise) { ft = inTable; DefineSimpleUnit(LFDNoise0); DefineSimpleUnit(LFDNoise1); DefineSimpleUnit(LFDNoise3); DefineSimpleUnit(LFDClipNoise); } ////////////////////////////////////////////////////////////////////////////////////////////////////////
9,162
C++
.cpp
263
28.707224
104
0.566595
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,953
DelayUGens.cpp
supercollider_supercollider/server/plugins/DelayUGens.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef NOVA_SIMD # include "simd_memory.hpp" #endif #include "SC_PlugIn.h" #include <cstdio> #include <boost/align/is_aligned.hpp> using namespace std; // for math functions const int kMAXMEDIANSIZE = 32; static InterfaceTable* ft; struct ScopeOut : public Unit { SndBuf* m_buf; SndBufUpdates* m_bufupdates; float m_fbufnum; uint32 m_framepos, m_framecount; float** mIn; }; struct PlayBuf : public Unit { double m_phase; float m_prevtrig; float m_fbufnum; float m_failedBufNum; SndBuf* m_buf; }; struct Grain { double phase, rate; double b1, y1, y2; // envelope float pan1, pan2; int counter; int bufnum; int chan; int interp; }; const int kMaxGrains = 64; struct TGrains : public Unit { float mPrevTrig; int mNumActive; Grain mGrains[kMaxGrains]; }; #if NOTYET struct SimpleLoopBuf : public Unit { int m_phase; float m_prevtrig; float m_fbufnum; SndBuf* m_buf; }; #endif struct BufRd : public Unit { float m_fbufnum; float m_failedBufNum; SndBuf* m_buf; }; struct BufWr : public Unit { float m_fbufnum; SndBuf* m_buf; }; struct RecordBuf : public Unit { float m_fbufnum; SndBuf* m_buf; int32 m_writepos; float m_recLevel, m_preLevel; float m_prevtrig; float** mIn; }; struct Pitch : public Unit { float m_values[kMAXMEDIANSIZE]; int m_ages[kMAXMEDIANSIZE]; float* m_buffer; float m_freq, m_minfreq, m_maxfreq, m_hasfreq, m_srate, m_ampthresh, m_peakthresh; int m_minperiod, m_maxperiod, m_execPeriod, m_index, m_readp, m_size; int m_downsamp, m_maxlog2bins, m_medianSize; int m_state; bool m_getClarity; }; struct InterpolationUnit { static const int minDelaySamples = 1; }; struct CubicInterpolationUnit { static const int minDelaySamples = 2; }; struct BufDelayUnit : public Unit { float m_fbufnum; SndBuf* m_buf; float m_dsamp; float m_delaytime; long m_iwrphase; uint32 m_numoutput; }; struct BufDelayN : public BufDelayUnit, InterpolationUnit {}; struct BufDelayL : public BufDelayUnit, InterpolationUnit {}; struct BufDelayC : public BufDelayUnit, CubicInterpolationUnit {}; struct BufFeedbackDelay : public BufDelayUnit { float m_feedbk, m_decaytime; }; struct BufCombN : public BufFeedbackDelay, InterpolationUnit {}; struct BufCombL : public BufFeedbackDelay, InterpolationUnit {}; struct BufCombC : public BufFeedbackDelay, CubicInterpolationUnit {}; struct BufAllpassN : public BufFeedbackDelay, InterpolationUnit {}; struct BufAllpassL : public BufFeedbackDelay, InterpolationUnit {}; struct BufAllpassC : public BufFeedbackDelay, CubicInterpolationUnit {}; struct DelayUnit : public Unit { float* m_dlybuf; float m_dsamp, m_fdelaylen; float m_delaytime, m_maxdelaytime; long m_iwrphase, m_idelaylen, m_mask; long m_numoutput; }; struct DelayN : public DelayUnit, InterpolationUnit {}; struct DelayL : public DelayUnit, InterpolationUnit {}; struct DelayC : public DelayUnit, InterpolationUnit {}; struct FeedbackDelay : public DelayUnit { float m_feedbk, m_decaytime; }; struct CombN : public FeedbackDelay, InterpolationUnit {}; struct CombL : public FeedbackDelay, InterpolationUnit {}; struct CombC : public FeedbackDelay, CubicInterpolationUnit {}; struct AllpassN : public FeedbackDelay, InterpolationUnit {}; struct AllpassL : public FeedbackDelay, InterpolationUnit {}; struct AllpassC : public FeedbackDelay, CubicInterpolationUnit {}; struct BufInfoUnit : public Unit { float m_fbufnum; SndBuf* m_buf; }; struct Pluck : public FeedbackDelay, CubicInterpolationUnit { float m_lastsamp, m_prevtrig, m_coef; long m_inputsamps; }; struct LocalBuf : public Unit { SndBuf* m_buf; void* chunk; }; struct MaxLocalBufs : public Unit {}; struct SetBuf : public Unit {}; struct ClearBuf : public Unit {}; struct DelTapWr : public Unit { SndBuf* m_buf; float m_fbufnum; uint32 m_phase; }; struct DelTapRd : public Unit { SndBuf* m_buf; float m_fbufnum, m_delTime; }; ////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" { void SampleRate_Ctor(Unit* unit, int inNumSamples); void ControlRate_Ctor(Unit* unit, int inNumSamples); void SampleDur_Ctor(Unit* unit, int inNumSamples); void ControlDur_Ctor(Unit* unit, int inNumSamples); void SubsampleOffset_Ctor(Unit* unit, int inNumSamples); void RadiansPerSample_Ctor(Unit* unit, int inNumSamples); void NumInputBuses_Ctor(Unit* unit, int inNumSamples); void NumOutputBuses_Ctor(Unit* unit, int inNumSamples); void NumAudioBuses_Ctor(Unit* unit, int inNumSamples); void NumControlBuses_Ctor(Unit* unit, int inNumSamples); void NumBuffers_Ctor(Unit* unit, int inNumSamples); void NodeID_Ctor(Unit* unit, int inNumSamples); void NumRunningSynths_Ctor(Unit* unit, int inNumSamples); void NumRunningSynths_next(Unit* unit, int inNumSamples); void BufSampleRate_next(BufInfoUnit* unit, int inNumSamples); void BufSampleRate_Ctor(BufInfoUnit* unit, int inNumSamples); void BufFrames_next(BufInfoUnit* unit, int inNumSamples); void BufFrames_Ctor(BufInfoUnit* unit, int inNumSamples); void BufDur_next(BufInfoUnit* unit, int inNumSamples); void BufDur_Ctor(BufInfoUnit* unit, int inNumSamples); void BufChannels_next(BufInfoUnit* unit, int inNumSamples); void BufChannels_Ctor(BufInfoUnit* unit, int inNumSamples); void BufSamples_next(BufInfoUnit* unit, int inNumSamples); void BufSamples_Ctor(BufInfoUnit* unit, int inNumSamples); void BufRateScale_next(BufInfoUnit* unit, int inNumSamples); void BufRateScale_Ctor(BufInfoUnit* unit, int inNumSamples); void PlayBuf_next_aa(PlayBuf* unit, int inNumSamples); void PlayBuf_next_ak(PlayBuf* unit, int inNumSamples); void PlayBuf_next_ka(PlayBuf* unit, int inNumSamples); void PlayBuf_next_kk(PlayBuf* unit, int inNumSamples); void PlayBuf_Ctor(PlayBuf* unit); void TGrains_next(TGrains* unit, int inNumSamples); void TGrains_Ctor(TGrains* unit); #if NOTYET void SimpleLoopBuf_next_kk(SimpleLoopBuf* unit, int inNumSamples); void SimpleLoopBuf_Ctor(SimpleLoopBuf* unit); void SimpleLoopBuf_Dtor(SimpleLoopBuf* unit); #endif void BufRd_Ctor(BufRd* unit); void BufRd_next_4(BufRd* unit, int inNumSamples); void BufRd_next_2(BufRd* unit, int inNumSamples); void BufRd_next_1(BufRd* unit, int inNumSamples); void BufWr_Ctor(BufWr* unit); void BufWr_next(BufWr* unit, int inNumSamples); void RecordBuf_Ctor(RecordBuf* unit); void RecordBuf_Dtor(RecordBuf* unit); void RecordBuf_next(RecordBuf* unit, int inNumSamples); void RecordBuf_next_10(RecordBuf* unit, int inNumSamples); void Pitch_Ctor(Pitch* unit); void Pitch_next_a(Pitch* unit, int inNumSamples); void Pitch_next_k(Pitch* unit, int inNumSamples); void LocalBuf_Ctor(LocalBuf* unit); void LocalBuf_Dtor(LocalBuf* unit); void MaxLocalBufs_Ctor(MaxLocalBufs* unit); void SetBuf_Ctor(SetBuf* unit); void ClearBuf_Ctor(ClearBuf* unit); void BufDelayN_Ctor(BufDelayN* unit); void BufDelayN_next(BufDelayN* unit, int inNumSamples); void BufDelayN_next_z(BufDelayN* unit, int inNumSamples); void BufDelayN_next_a(BufDelayN* unit, int inNumSamples); void BufDelayN_next_a_z(BufDelayN* unit, int inNumSamples); void BufDelayL_Ctor(BufDelayL* unit); void BufDelayL_next(BufDelayL* unit, int inNumSamples); void BufDelayL_next_z(BufDelayL* unit, int inNumSamples); void BufDelayL_next_a(BufDelayL* unit, int inNumSamples); void BufDelayL_next_a_z(BufDelayL* unit, int inNumSamples); void BufDelayC_Ctor(BufDelayC* unit); void BufDelayC_next(BufDelayC* unit, int inNumSamples); void BufDelayC_next_z(BufDelayC* unit, int inNumSamples); void BufDelayC_next_a(BufDelayC* unit, int inNumSamples); void BufDelayC_next_a_z(BufDelayC* unit, int inNumSamples); void BufCombN_Ctor(BufCombN* unit); void BufCombN_next(BufCombN* unit, int inNumSamples); void BufCombN_next_z(BufCombN* unit, int inNumSamples); void BufCombN_next_a(BufCombN* unit, int inNumSamples); void BufCombN_next_a_z(BufCombN* unit, int inNumSamples); void BufCombL_Ctor(BufCombL* unit); void BufCombL_next(BufCombL* unit, int inNumSamples); void BufCombL_next_z(BufCombL* unit, int inNumSamples); void BufCombL_next_a(BufCombL* unit, int inNumSamples); void BufCombL_next_a_z(BufCombL* unit, int inNumSamples); void BufCombC_Ctor(BufCombC* unit); void BufCombC_next(BufCombC* unit, int inNumSamples); void BufCombC_next_z(BufCombC* unit, int inNumSamples); void BufCombC_next_a(BufCombC* unit, int inNumSamples); void BufCombC_next_a_z(BufCombC* unit, int inNumSamples); void BufAllpassN_Ctor(BufAllpassN* unit); void BufAllpassN_next(BufAllpassN* unit, int inNumSamples); void BufAllpassN_next_z(BufAllpassN* unit, int inNumSamples); void BufAllpassN_next_a(BufAllpassN* unit, int inNumSamples); void BufAllpassN_next_a_z(BufAllpassN* unit, int inNumSamples); void BufAllpassL_Ctor(BufAllpassL* unit); void BufAllpassL_next(BufAllpassL* unit, int inNumSamples); void BufAllpassL_next_z(BufAllpassL* unit, int inNumSamples); void BufAllpassL_next_a(BufAllpassL* unit, int inNumSamples); void BufAllpassL_next_a_z(BufAllpassL* unit, int inNumSamples); void BufAllpassC_Ctor(BufAllpassC* unit); void BufAllpassC_next(BufAllpassC* unit, int inNumSamples); void BufAllpassC_next_z(BufAllpassC* unit, int inNumSamples); void BufAllpassC_next_a(BufAllpassC* unit, int inNumSamples); void BufAllpassC_next_a_z(BufAllpassC* unit, int inNumSamples); void DelayUnit_Dtor(DelayUnit* unit); void DelayN_Ctor(DelayN* unit); void DelayN_next(DelayN* unit, int inNumSamples); void DelayN_next_z(DelayN* unit, int inNumSamples); void DelayN_next_a(DelayN* unit, int inNumSamples); void DelayN_next_a_z(DelayN* unit, int inNumSamples); void DelayL_Ctor(DelayL* unit); void DelayL_next(DelayL* unit, int inNumSamples); void DelayL_next_z(DelayL* unit, int inNumSamples); void DelayL_next_a(DelayL* unit, int inNumSamples); void DelayL_next_a_z(DelayL* unit, int inNumSamples); void DelayC_Ctor(DelayC* unit); void DelayC_next(DelayC* unit, int inNumSamples); void DelayC_next_z(DelayC* unit, int inNumSamples); void DelayC_next_a(DelayC* unit, int inNumSamples); void DelayC_next_a_z(DelayC* unit, int inNumSamples); void CombN_Ctor(CombN* unit); void CombN_next(CombN* unit, int inNumSamples); void CombN_next_z(CombN* unit, int inNumSamples); void CombN_next_a(CombN* unit, int inNumSamples); void CombN_next_a_z(CombN* unit, int inNumSamples); void CombL_Ctor(CombL* unit); void CombL_next(CombL* unit, int inNumSamples); void CombL_next_z(CombL* unit, int inNumSamples); void CombL_next_a(CombL* unit, int inNumSamples); void CombL_next_a_z(CombL* unit, int inNumSamples); void CombC_Ctor(CombC* unit); void CombC_next(CombC* unit, int inNumSamples); void CombC_next_z(CombC* unit, int inNumSamples); void CombC_next_a(CombC* unit, int inNumSamples); void CombC_next_a_z(CombC* unit, int inNumSamples); void AllpassN_Ctor(AllpassN* unit); void AllpassN_next(AllpassN* unit, int inNumSamples); void AllpassN_next_z(AllpassN* unit, int inNumSamples); void AllpassN_next_a(AllpassN* unit, int inNumSamples); void AllpassN_next_a_z(AllpassN* unit, int inNumSamples); void AllpassL_Ctor(AllpassL* unit); void AllpassL_next(AllpassL* unit, int inNumSamples); void AllpassL_next_z(AllpassL* unit, int inNumSamples); void AllpassL_next_a(AllpassL* unit, int inNumSamples); void AllpassL_next_a_z(AllpassL* unit, int inNumSamples); void AllpassC_Ctor(AllpassC* unit); void AllpassC_next(AllpassC* unit, int inNumSamples); void AllpassC_next_z(AllpassC* unit, int inNumSamples); void AllpassC_next_a(AllpassC* unit, int inNumSamples); void AllpassC_next_a_z(AllpassC* unit, int inNumSamples); void ScopeOut_next(ScopeOut* unit, int inNumSamples); void ScopeOut_Ctor(ScopeOut* unit); void ScopeOut_Dtor(ScopeOut* unit); void Pluck_Ctor(Pluck* unit); void Pluck_next_aa(Pluck* unit, int inNumSamples); void Pluck_next_aa_z(Pluck* unit, int inNumSamples); void Pluck_next_kk(Pluck* unit, int inNumSamples); void Pluck_next_kk_z(Pluck* unit, int inNumSamples); void Pluck_next_ka(Pluck* unit, int inNumSamples); void Pluck_next_ka_z(Pluck* unit, int inNumSamples); void Pluck_next_ak(Pluck* unit, int inNumSamples); void Pluck_next_ak_z(Pluck* unit, int inNumSamples); void DelTapWr_Ctor(DelTapWr* unit); void DelTapWr_next(DelTapWr* unit, int inNumSamples); void DelTapWr_next_simd(DelTapWr* unit, int inNumSamples); void DelTapRd_Ctor(DelTapRd* unit); void DelTapRd_next1_a(DelTapRd* unit, int inNumSamples); void DelTapRd_next2_a(DelTapRd* unit, int inNumSamples); void DelTapRd_next4_a(DelTapRd* unit, int inNumSamples); void DelTapRd_next1_k(DelTapRd* unit, int inNumSamples); void DelTapRd_next1_k_simd(DelTapRd* unit, int inNumSamples); void DelTapRd_next2_k(DelTapRd* unit, int inNumSamples); void DelTapRd_next4_k(DelTapRd* unit, int inNumSamples); } ////////////////////////////////////////////////////////////////////////////////////////////////// void SampleRate_Ctor(Unit* unit, int inNumSamples) { ZOUT0(0) = unit->mWorld->mSampleRate; } void ControlRate_Ctor(Unit* unit, int inNumSamples) { ZOUT0(0) = unit->mWorld->mBufRate.mSampleRate; } void SampleDur_Ctor(Unit* unit, int inNumSamples) { ZOUT0(0) = unit->mWorld->mFullRate.mSampleDur; } void ControlDur_Ctor(Unit* unit, int inNumSamples) { ZOUT0(0) = unit->mWorld->mFullRate.mBufDuration; } void RadiansPerSample_Ctor(Unit* unit, int inNumSamples) { ZOUT0(0) = unit->mWorld->mFullRate.mRadiansPerSample; } void BlockSize_Ctor(Unit* unit, int inNumSamples) { ZOUT0(0) = unit->mWorld->mFullRate.mBufLength; } void SubsampleOffset_Ctor(Unit* unit, int inNumSamples) { ZOUT0(0) = unit->mParent->mSubsampleOffset; } void NumInputBuses_Ctor(Unit* unit, int inNumSamples) { ZOUT0(0) = unit->mWorld->mNumInputs; } void NumOutputBuses_Ctor(Unit* unit, int inNumSamples) { ZOUT0(0) = unit->mWorld->mNumOutputs; } void NumAudioBuses_Ctor(Unit* unit, int inNumSamples) { ZOUT0(0) = unit->mWorld->mNumAudioBusChannels; } void NumControlBuses_Ctor(Unit* unit, int inNumSamples) { ZOUT0(0) = unit->mWorld->mNumControlBusChannels; } void NumBuffers_Ctor(Unit* unit, int inNumSamples) { ZOUT0(0) = unit->mWorld->mNumSndBufs; } void NodeID_Ctor(Unit* unit, int inNumSamples) { ZOUT0(0) = (float)unit->mParent->mNode.mID; } ////////////////////////////////////////////////////////////////////////////////////////////////// void NumRunningSynths_Ctor(Unit* unit, int inNumSamples) { if (INRATE(0) != calc_ScalarRate) { SETCALC(NumRunningSynths_next); } ZOUT0(0) = unit->mWorld->mNumGraphs; } void NumRunningSynths_next(Unit* unit, int inNumSamples) { ZOUT0(0) = unit->mWorld->mNumGraphs; } ////////////////////////////////////////////////////////////////////////////////////////////////// #define CTOR_GET_BUF \ float fbufnum = ZIN0(0); \ fbufnum = sc_max(0.f, fbufnum); \ uint32 bufnum = (int)fbufnum; \ World* world = unit->mWorld; \ SndBuf* buf; \ if (bufnum >= world->mNumSndBufs) { \ int localBufNum = bufnum - world->mNumSndBufs; \ Graph* parent = unit->mParent; \ if (localBufNum <= parent->localBufNum) { \ buf = parent->mLocalSndBufs + localBufNum; \ } else { \ bufnum = 0; \ buf = world->mSndBufs + bufnum; \ } \ } else { \ buf = world->mSndBufs + bufnum; \ } void BufSampleRate_next(BufInfoUnit* unit, int inNumSamples) { SIMPLE_GET_BUF_SHARED ZOUT0(0) = buf->samplerate; } void BufSampleRate_Ctor(BufInfoUnit* unit, int inNumSamples) { SETCALC(BufSampleRate_next); CTOR_GET_BUF unit->m_fbufnum = fbufnum; unit->m_buf = buf; ZOUT0(0) = buf->samplerate; } void BufFrames_next(BufInfoUnit* unit, int inNumSamples) { SIMPLE_GET_BUF_SHARED ZOUT0(0) = buf->frames; } void BufFrames_Ctor(BufInfoUnit* unit, int inNumSamples) { SETCALC(BufFrames_next); CTOR_GET_BUF unit->m_fbufnum = fbufnum; unit->m_buf = buf; ZOUT0(0) = buf->frames; } void BufDur_next(BufInfoUnit* unit, int inNumSamples) { SIMPLE_GET_BUF_SHARED ZOUT0(0) = buf->frames * buf->sampledur; } void BufDur_Ctor(BufInfoUnit* unit, int inNumSamples) { SETCALC(BufDur_next); CTOR_GET_BUF unit->m_fbufnum = fbufnum; unit->m_buf = buf; ZOUT0(0) = buf->frames * buf->sampledur; } void BufChannels_next(BufInfoUnit* unit, int inNumSamples) { SIMPLE_GET_BUF_SHARED ZOUT0(0) = buf->channels; } void BufChannels_Ctor(BufInfoUnit* unit, int inNumSamples) { SETCALC(BufChannels_next); CTOR_GET_BUF unit->m_fbufnum = fbufnum; unit->m_buf = buf; ZOUT0(0) = buf->channels; } void BufSamples_next(BufInfoUnit* unit, int inNumSamples) { SIMPLE_GET_BUF_SHARED ZOUT0(0) = buf->samples; } void BufSamples_Ctor(BufInfoUnit* unit, int inNumSamples) { SETCALC(BufSamples_next); CTOR_GET_BUF unit->m_fbufnum = fbufnum; unit->m_buf = buf; ZOUT0(0) = buf->samples; } void BufRateScale_next(BufInfoUnit* unit, int inNumSamples) { SIMPLE_GET_BUF_SHARED ZOUT0(0) = buf->samplerate * unit->mWorld->mFullRate.mSampleDur; } void BufRateScale_Ctor(BufInfoUnit* unit, int inNumSamples) { SETCALC(BufRateScale_next); CTOR_GET_BUF unit->m_fbufnum = fbufnum; unit->m_buf = buf; ZOUT0(0) = buf->samplerate * unit->mWorld->mFullRate.mSampleDur; } ////////////////////////////////////////////////////////////////////////////////////////////////// inline int32 BUFMASK(int32 x) { return (1 << (31 - CLZ(x))) - 1; } static void LocalBuf_allocBuffer(LocalBuf* unit, SndBuf* buf, int numChannels, int numFrames) { int numSamples = numFrames * numChannels; // Print("bufnum: %i, allocating %i channels and %i frames. memsize: %i\n", (int)unit->m_fbufnum, numChannels, // numFrames, numSamples * sizeof(float)); const int alignment = 128; // in bytes unit->chunk = (float*)RTAlloc(unit->mWorld, numSamples * sizeof(float) + alignment); ClearUnitIfMemFailed(unit->chunk); buf->data = (float*)((intptr_t)((char*)unit->chunk + (alignment - 1)) & -alignment); buf->channels = numChannels; buf->frames = numFrames; buf->samples = numSamples; buf->mask = BUFMASK(numSamples); // for delay lines buf->mask1 = buf->mask - 1; // for oscillators buf->samplerate = unit->mWorld->mSampleRate; buf->sampledur = 1. / buf->samplerate; #if SUPERNOVA buf->isLocal = true; #endif } void LocalBuf_Ctor(LocalBuf* unit) { Graph* parent = unit->mParent; unit->chunk = nullptr; int offset = unit->mWorld->mNumSndBufs; int bufnum = parent->localBufNum; float fbufnum; if (parent->localBufNum >= parent->localMaxBufNum) { fbufnum = -1.f; if (unit->mWorld->mVerbosity > -2) printf("warning: LocalBuf tried to allocate too many local buffers.\n"); } else { fbufnum = (float)(bufnum + offset); unit->m_buf = parent->mLocalSndBufs + bufnum; parent->localBufNum = parent->localBufNum + 1; LocalBuf_allocBuffer(unit, unit->m_buf, (int)IN0(0), (int)IN0(1)); if (!unit->chunk) fbufnum = -1.f; } OUT0(0) = fbufnum; } void LocalBuf_Dtor(LocalBuf* unit) { RTFree(unit->mWorld, unit->chunk); if (unit->mParent->localBufNum <= 1) { // only the last time. for (int i = 0; i != unit->mParent->localMaxBufNum; ++i) unit->mParent->mLocalSndBufs[i].~SndBuf(); RTFree(unit->mWorld, unit->mParent->mLocalSndBufs); unit->mParent->localMaxBufNum = 0; } else unit->mParent->localBufNum = unit->mParent->localBufNum - 1; } ////////////////////////////////////////////////////////////////////////////////////////////////// void MaxLocalBufs_Ctor(MaxLocalBufs* unit) { Graph* parent = unit->mParent; int maxBufNum = (int)(IN0(0) + .5f); if (!parent->localMaxBufNum) { parent->mLocalSndBufs = (SndBuf*)RTAlloc(unit->mWorld, maxBufNum * sizeof(SndBuf)); ClearUnitIfMemFailed(parent->mLocalSndBufs); #ifdef SUPERNOVA for (int i = 0; i != maxBufNum; ++i) new (&parent->mLocalSndBufs[i]) SndBuf(); #endif parent->localMaxBufNum = maxBufNum; } else printf("warning: MaxLocalBufs - maximum number of local buffers is already declared (%i) and must remain " "unchanged.\n", parent->localMaxBufNum); } ////////////////////////////////////////////////////////////////////////////////////////////////// void SetBuf_Ctor(SetBuf* unit) { OUT0(0) = 0.f; CTOR_GET_BUF if (!buf || !buf->data) { if (unit->mWorld->mVerbosity > -2) { Print("SetBuf: no valid buffer\n"); } return; } int offset = (int)IN0(1); int numArgs = (int)IN0(2); int end = sc_min(buf->samples, numArgs + offset); int j = 3; for (int i = offset; i < end; ++j, ++i) { buf->data[i] = IN0(j); } } ////////////////////////////////////////////////////////////////////////////////////////////////// void ClearBuf_Ctor(ClearBuf* unit) { OUT0(0) = 0.f; CTOR_GET_BUF if (!buf || !buf->data) { if (unit->mWorld->mVerbosity > -2) { Print("ClearBuf: no valid buffer\n"); } return; } Clear(buf->samples, buf->data); } //////////////////////////////////////////////////////////////////////////////////////////////////////// inline double sc_loop(Unit* unit, double in, double hi, int loop) { // avoid the divide if possible if (in >= hi) { if (!loop) { unit->mDone = true; return hi; } in -= hi; if (in < hi) return in; } else if (in < 0.) { if (!loop) { unit->mDone = true; return 0.; } in += hi; if (in >= 0.) return in; } else return in; return in - hi * floor(in / hi); } #define CHECK_BUF \ if (!bufData) { \ unit->mDone = true; \ ClearUnitOutputs(unit, inNumSamples); \ return; \ } static inline bool checkBuffer(Unit* unit, const float* bufData, uint32 bufChannels, uint32 expectedChannels, int inNumSamples) { if (!bufData) goto handle_failure; if (expectedChannels > bufChannels) { if (unit->mWorld->mVerbosity > -1 && !unit->mDone) Print("Buffer UGen channel mismatch: expected %i, yet buffer has %i channels\n", expectedChannels, bufChannels); goto handle_failure; } return true; handle_failure: unit->mDone = true; ClearUnitOutputs(unit, inNumSamples); return false; } #define SETUP_IN(offset) \ uint32 numInputs = unit->mNumInputs - (uint32)offset; \ if (numInputs != bufChannels) { \ if (unit->mWorld->mVerbosity > -1 && !unit->mDone) { \ Print("buffer-writing UGen channel mismatch: numInputs %i, yet buffer has %i channels\n", numInputs, \ bufChannels); \ } \ unit->mDone = true; \ ClearUnitOutputs(unit, inNumSamples); \ return; \ } \ if (!unit->mIn) { \ unit->mIn = (float**)RTAlloc(unit->mWorld, numInputs * sizeof(float*)); \ ClearUnitIfMemFailed(unit->mIn); \ } \ float** in = unit->mIn; \ for (uint32 i = 0; i < numInputs; ++i) { \ in[i] = ZIN(i + offset); \ } #define TAKEDOWN_IN \ if (unit->mIn) { \ RTFree(unit->mWorld, unit->mIn); \ } #define LOOP_INNER_BODY_1(SAMPLE_INDEX) OUT(channel)[SAMPLE_INDEX] = table1[index]; #define LOOP_INNER_BODY_2(SAMPLE_INDEX) \ float b = table1[index]; \ float c = table2[index]; \ OUT(channel)[SAMPLE_INDEX] = b + fracphase * (c - b); #define LOOP_INNER_BODY_4(SAMPLE_INDEX) \ float a = table0[index]; \ float b = table1[index]; \ float c = table2[index]; \ float d = table3[index]; \ OUT(channel)[SAMPLE_INDEX] = cubicinterp(fracphase, a, b, c, d); #define LOOP_BODY_4(SAMPLE_INDEX) \ phase = sc_loop((Unit*)unit, phase, loopMax, loop); \ int32 iphase = (int32)phase; \ const float* table1 = bufData + iphase * bufChannels; \ const float* table0 = table1 - bufChannels; \ const float* table2 = table1 + bufChannels; \ const float* table3 = table2 + bufChannels; \ if (iphase == 0) { \ if (loop) { \ table0 += bufSamples; \ } else { \ table0 += bufChannels; \ } \ } else if (iphase >= guardFrame) { \ if (iphase == guardFrame) { \ if (loop) { \ table3 -= bufSamples; \ } else { \ table3 -= bufChannels; \ } \ } else { \ if (loop) { \ table2 -= bufSamples; \ table3 -= bufSamples; \ } else { \ table2 -= bufChannels; \ table3 -= 2 * bufChannels; \ } \ } \ } \ int32 index = 0; \ float fracphase = phase - (double)iphase; \ if (numOutputs == bufChannels) { \ for (uint32 channel = 0; channel < numOutputs; ++channel) { \ LOOP_INNER_BODY_4(SAMPLE_INDEX) \ index++; \ } \ } else if (numOutputs < bufChannels) { \ for (uint32 channel = 0; channel < numOutputs; ++channel) { \ LOOP_INNER_BODY_4(SAMPLE_INDEX) \ index++; \ } \ index += (bufChannels - numOutputs); \ } else { \ for (uint32 channel = 0; channel < bufChannels; ++channel) { \ LOOP_INNER_BODY_4(SAMPLE_INDEX) \ index++; \ } \ for (uint32 channel = bufChannels; channel < numOutputs; ++channel) { \ OUT(channel)[SAMPLE_INDEX] = 0.f; \ index++; \ } \ } #define LOOP_BODY_2(SAMPLE_INDEX) \ phase = sc_loop((Unit*)unit, phase, loopMax, loop); \ int32 iphase = (int32)phase; \ const float* table1 = bufData + iphase * bufChannels; \ const float* table2 = table1 + bufChannels; \ if (iphase > guardFrame) { \ if (loop) { \ table2 -= bufSamples; \ } else { \ table2 -= bufChannels; \ } \ } \ int32 index = 0; \ float fracphase = phase - (double)iphase; \ if (numOutputs == bufChannels) { \ for (uint32 channel = 0; channel < numOutputs; ++channel) { \ LOOP_INNER_BODY_2(SAMPLE_INDEX) \ index++; \ } \ } else if (numOutputs < bufChannels) { \ for (uint32 channel = 0; channel < numOutputs; ++channel) { \ LOOP_INNER_BODY_2(SAMPLE_INDEX) \ index++; \ } \ index += (bufChannels - numOutputs); \ } else { \ for (uint32 channel = 0; channel < bufChannels; ++channel) { \ LOOP_INNER_BODY_2(SAMPLE_INDEX) \ index++; \ } \ for (uint32 channel = bufChannels; channel < numOutputs; ++channel) { \ OUT(channel)[SAMPLE_INDEX] = 0.f; \ index++; \ } \ } #define LOOP_BODY_1(SAMPLE_INDEX) \ phase = sc_loop((Unit*)unit, phase, loopMax, loop); \ int32 iphase = (int32)phase; \ const float* table1 = bufData + iphase * bufChannels; \ int32 index = 0; \ if (numOutputs == bufChannels) { \ for (uint32 channel = 0; channel < numOutputs; ++channel) { \ LOOP_INNER_BODY_1(SAMPLE_INDEX) \ index++; \ } \ } else if (numOutputs < bufChannels) { \ for (uint32 channel = 0; channel < numOutputs; ++channel) { \ LOOP_INNER_BODY_1(SAMPLE_INDEX) \ index++; \ } \ index += (bufChannels - numOutputs); \ } else { \ for (uint32 channel = 0; channel < bufChannels; ++channel) { \ LOOP_INNER_BODY_1(SAMPLE_INDEX) \ index++; \ } \ for (uint32 channel = bufChannels; channel < numOutputs; ++channel) { \ OUT(channel)[SAMPLE_INDEX] = 0.f; \ index++; \ } \ } #define CHECK_BUFFER_DATA \ if (!bufData) { \ if (unit->mWorld->mVerbosity > -1 && !unit->mDone && (unit->m_failedBufNum != fbufnum)) { \ Print("Buffer UGen: no buffer data\n"); \ unit->m_failedBufNum = fbufnum; \ } \ ClearUnitOutputs(unit, inNumSamples); \ return; \ } else { \ if (bufChannels != numOutputs) { \ if (unit->mWorld->mVerbosity > -1 && !unit->mDone && (unit->m_failedBufNum != fbufnum)) { \ Print("Buffer UGen channel mismatch: expected %i, yet buffer has %i channels\n", numOutputs, \ bufChannels); \ unit->m_failedBufNum = fbufnum; \ } \ } \ } void PlayBuf_Ctor(PlayBuf* unit) { if (INRATE(1) == calc_FullRate) { if (INRATE(2) == calc_FullRate) { SETCALC(PlayBuf_next_aa); } else { SETCALC(PlayBuf_next_ak); } } else { if (INRATE(2) == calc_FullRate) { SETCALC(PlayBuf_next_ka); } else { SETCALC(PlayBuf_next_kk); } } unit->m_fbufnum = -1e9f; unit->m_failedBufNum = -1e9f; unit->m_prevtrig = 0.; unit->m_phase = ZIN0(3); ClearUnitOutputs(unit, 1); } void PlayBuf_next_aa(PlayBuf* unit, int inNumSamples) { float* ratein = ZIN(1); float* trigin = ZIN(2); int32 loop = (int32)ZIN0(4); float fbufnum = ZIN0(0); if (fbufnum != unit->m_fbufnum) { uint32 bufnum = (int)fbufnum; World* world = unit->mWorld; if (bufnum >= world->mNumSndBufs) bufnum = 0; unit->m_fbufnum = fbufnum; unit->m_buf = world->mSndBufs + bufnum; } const SndBuf* buf = unit->m_buf; ACQUIRE_SNDBUF_SHARED(buf); const float* bufData __attribute__((__unused__)) = buf->data; uint32 bufChannels __attribute__((__unused__)) = buf->channels; uint32 bufSamples __attribute__((__unused__)) = buf->samples; uint32 bufFrames = buf->frames; int mask __attribute__((__unused__)) = buf->mask; int guardFrame __attribute__((__unused__)) = bufFrames - 2; int numOutputs = unit->mNumOutputs; CHECK_BUFFER_DATA; double loopMax = (double)(loop ? bufFrames : bufFrames - 1); double phase = unit->m_phase; float prevtrig = unit->m_prevtrig; for (int i = 0; i < inNumSamples; ++i) { float trig = ZXP(trigin); if (trig > 0.f && prevtrig <= 0.f) { unit->mDone = false; phase = ZIN0(3); } prevtrig = trig; LOOP_BODY_4(i) phase += ZXP(ratein); } RELEASE_SNDBUF_SHARED(buf); if (unit->mDone) DoneAction((int)ZIN0(5), unit); unit->m_phase = phase; unit->m_prevtrig = prevtrig; } void PlayBuf_next_ak(PlayBuf* unit, int inNumSamples) { float* ratein = ZIN(1); float trig = ZIN0(2); int32 loop = (int32)ZIN0(4); float fbufnum = ZIN0(0); if (fbufnum != unit->m_fbufnum) { uint32 bufnum = (int)fbufnum; World* world = unit->mWorld; if (bufnum >= world->mNumSndBufs) bufnum = 0; unit->m_fbufnum = fbufnum; unit->m_buf = world->mSndBufs + bufnum; } const SndBuf* buf = unit->m_buf; ACQUIRE_SNDBUF_SHARED(buf); const float* bufData __attribute__((__unused__)) = buf->data; uint32 bufChannels __attribute__((__unused__)) = buf->channels; uint32 bufSamples __attribute__((__unused__)) = buf->samples; uint32 bufFrames = buf->frames; int mask __attribute__((__unused__)) = buf->mask; int guardFrame __attribute__((__unused__)) = bufFrames - 2; int numOutputs = unit->mNumOutputs; CHECK_BUFFER_DATA double loopMax = (double)(loop ? bufFrames : bufFrames - 1); double phase = unit->m_phase; if (phase == -1.) phase = bufFrames; if (trig > 0.f && unit->m_prevtrig <= 0.f) { unit->mDone = false; phase = ZIN0(3); } unit->m_prevtrig = trig; for (int i = 0; i < inNumSamples; ++i) { LOOP_BODY_4(i) phase += ZXP(ratein); } RELEASE_SNDBUF_SHARED(buf); if (unit->mDone) DoneAction((int)ZIN0(5), unit); unit->m_phase = phase; } void PlayBuf_next_kk(PlayBuf* unit, int inNumSamples) { float rate = ZIN0(1); float trig = ZIN0(2); int32 loop = (int32)ZIN0(4); GET_BUF_SHARED int numOutputs = unit->mNumOutputs; CHECK_BUFFER_DATA double loopMax = (double)(loop ? bufFrames : bufFrames - 1); double phase = unit->m_phase; if (trig > 0.f && unit->m_prevtrig <= 0.f) { unit->mDone = false; phase = ZIN0(3); } unit->m_prevtrig = trig; for (int i = 0; i < inNumSamples; ++i) { LOOP_BODY_4(i) phase += rate; } if (unit->mDone) DoneAction((int)ZIN0(5), unit); unit->m_phase = phase; } void PlayBuf_next_ka(PlayBuf* unit, int inNumSamples) { float rate = ZIN0(1); float* trigin = ZIN(2); int32 loop = (int32)ZIN0(4); GET_BUF_SHARED int numOutputs = unit->mNumOutputs; CHECK_BUFFER_DATA double loopMax = (double)(loop ? bufFrames : bufFrames - 1); double phase = unit->m_phase; float prevtrig = unit->m_prevtrig; for (int i = 0; i < inNumSamples; ++i) { float trig = ZXP(trigin); if (trig > 0.f && prevtrig <= 0.f) { unit->mDone = false; if (INRATE(3) == calc_FullRate) phase = IN(3)[i]; else phase = ZIN0(3); } prevtrig = trig; LOOP_BODY_4(i) phase += rate; } if (unit->mDone) DoneAction((int)ZIN0(5), unit); unit->m_phase = phase; unit->m_prevtrig = prevtrig; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void BufRd_Ctor(BufRd* unit) { int interp = (int)ZIN0(3); switch (interp) { case 1: SETCALC(BufRd_next_1); break; case 2: SETCALC(BufRd_next_2); break; default: SETCALC(BufRd_next_4); break; } unit->m_fbufnum = -1e9f; unit->m_failedBufNum = -1e9f; BufRd_next_1(unit, 1); } void BufRd_next_4(BufRd* unit, int inNumSamples) { float* phasein = ZIN(1); int32 loop = (int32)ZIN0(2); GET_BUF_SHARED uint32 numOutputs = unit->mNumOutputs; CHECK_BUFFER_DATA double loopMax = (double)(loop ? bufFrames : bufFrames - 1); for (int i = 0; i < inNumSamples; ++i) { double phase = ZXP(phasein); LOOP_BODY_4(i) } } void BufRd_next_2(BufRd* unit, int inNumSamples) { float* phasein = ZIN(1); int32 loop = (int32)ZIN0(2); GET_BUF_SHARED uint32 numOutputs = unit->mNumOutputs; CHECK_BUFFER_DATA double loopMax = (double)(loop ? bufFrames : bufFrames - 1); for (int i = 0; i < inNumSamples; ++i) { double phase = ZXP(phasein); LOOP_BODY_2(i) } } void BufRd_next_1(BufRd* unit, int inNumSamples) { float* phasein = ZIN(1); int32 loop = (int32)ZIN0(2); GET_BUF_SHARED uint32 numOutputs = unit->mNumOutputs; CHECK_BUFFER_DATA double loopMax = (double)(loop ? bufFrames : bufFrames - 1); for (int i = 0; i < inNumSamples; ++i) { double phase = ZXP(phasein); LOOP_BODY_1(i) } } //////////////////////////////////////////////////////////////////////////////////////////////////////// void BufWr_Ctor(BufWr* unit) { SETCALC(BufWr_next); unit->m_fbufnum = -1e9f; ClearUnitOutputs(unit, 1); } void BufWr_next(BufWr* unit, int inNumSamples) { float* phasein = ZIN(1); int32 loop = (int32)ZIN0(2); GET_BUF uint32 numInputChannels = unit->mNumInputs - 3; if (!checkBuffer(unit, bufData, bufChannels, numInputChannels, inNumSamples)) return; double loopMax = (double)(bufFrames - (loop ? 0 : 1)); for (int32 k = 0; k < inNumSamples; ++k) { double phase = sc_loop((Unit*)unit, ZXP(phasein), loopMax, loop); int32 iphase = (int32)phase; float* table0 = bufData + iphase * bufChannels; for (uint32 channel = 0; channel < numInputChannels; ++channel) table0[channel] = IN(channel + 3)[k]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////// // bufnum=0, offset=0.0, recLevel=1.0, preLevel=0.0, run=1.0, loop=1.0, trigger=1.0 void RecordBuf_Ctor(RecordBuf* unit) { uint32 numInputs = unit->mNumInputs - 8; unit->m_fbufnum = -1e9f; unit->mIn = nullptr; unit->m_writepos = (int32)ZIN0(1) * numInputs; unit->m_recLevel = ZIN0(2); unit->m_preLevel = ZIN0(3); unit->m_prevtrig = 0.f; if (INRATE(2) == calc_ScalarRate && INRATE(3) == calc_ScalarRate && unit->m_recLevel == 1.0 && unit->m_preLevel == 0.0) { SETCALC(RecordBuf_next_10); } else { SETCALC(RecordBuf_next); } ClearUnitOutputs(unit, 1); } void RecordBuf_Dtor(RecordBuf* unit) { TAKEDOWN_IN } void RecordBuf_next(RecordBuf* unit, int inNumSamples) { // printf("RecordBuf_next\n"); GET_BUF CHECK_BUF SETUP_IN(8) float recLevel = ZIN0(2); float preLevel = ZIN0(3); float run = ZIN0(4); int32 loop = (int32)ZIN0(5); float trig = ZIN0(6); // printf("loop %d run %g\n", loop, run); int32 writepos = unit->m_writepos; float recLevel_slope = CALCSLOPE(recLevel, unit->m_recLevel); float preLevel_slope = CALCSLOPE(preLevel, unit->m_preLevel); /* reset recLevel and preLevel to use the previous value ... bug fix */ recLevel = unit->m_recLevel; preLevel = unit->m_preLevel; if (loop) { if (trig > 0.f && unit->m_prevtrig <= 0.f) { unit->mDone = false; writepos = (int32)ZIN0(1) * bufChannels; } if (writepos < 0) writepos = bufSamples - bufChannels; else if (writepos >= (int32)bufSamples) writepos = 0; if (run > 0.f) { if (bufChannels == 1) { for (int32 k = 0; k < inNumSamples; ++k) { float* table0 = bufData + writepos; table0[0] = *++(in[0]) * recLevel + table0[0] * preLevel; writepos += 1; if (writepos >= (int32)bufSamples) writepos = 0; recLevel += recLevel_slope; preLevel += preLevel_slope; } } else if (bufChannels == 2 && numInputs == 2) { for (int32 k = 0; k < inNumSamples; ++k) { float* table0 = bufData + writepos; table0[0] = *++(in[0]) * recLevel + table0[0] * preLevel; table0[1] = *++(in[1]) * recLevel + table0[1] * preLevel; writepos += 2; if (writepos >= (int32)bufSamples) writepos = 0; recLevel += recLevel_slope; preLevel += preLevel_slope; } } else { for (int32 k = 0; k < inNumSamples; ++k) { float* table0 = bufData + writepos; for (uint32 i = 0; i < numInputs; ++i) { float* samp = table0 + i; *samp = *++(in[i]) * recLevel + *samp * preLevel; } writepos += bufChannels; if (writepos >= (int32)bufSamples) writepos = 0; recLevel += recLevel_slope; preLevel += preLevel_slope; } } } else if (run < 0.f) { if (bufChannels == 1) { for (int32 k = 0; k < inNumSamples; ++k) { float* table0 = bufData + writepos; table0[0] = *++(in[0]) * recLevel + table0[0] * preLevel; writepos -= 1; if (writepos < 0) writepos = bufSamples - bufChannels; recLevel += recLevel_slope; preLevel += preLevel_slope; } } else if (bufChannels == 2 && numInputs == 2) { for (int32 k = 0; k < inNumSamples; ++k) { float* table0 = bufData + writepos; table0[0] = *++(in[0]) * recLevel + table0[0] * preLevel; table0[1] = *++(in[1]) * recLevel + table0[1] * preLevel; writepos -= 2; if (writepos < 0) writepos = bufSamples - bufChannels; recLevel += recLevel_slope; preLevel += preLevel_slope; } } else { for (int32 k = 0; k < inNumSamples; ++k) { float* table0 = bufData + writepos; for (uint32 i = 0; i < numInputs; ++i) { float* samp = table0 + i; *samp = *++(in[i]) * recLevel + *samp * preLevel; } writepos -= bufChannels; if (writepos < 0) writepos = bufSamples - bufChannels; recLevel += recLevel_slope; preLevel += preLevel_slope; } } } } else { if (trig > 0.f && unit->m_prevtrig <= 0.f) { unit->mDone = false; writepos = (int32)ZIN0(1) * bufChannels; } if (run > 0.f) { int nsmps = bufSamples - writepos; nsmps = sc_clip(nsmps, 0, inNumSamples * bufChannels); if (bufChannels == 1) { for (int32 k = 0; k < nsmps; ++k) { float* table0 = bufData + writepos; table0[0] = *++(in[0]) * recLevel + table0[0] * preLevel; writepos += 1; recLevel += recLevel_slope; preLevel += preLevel_slope; } } else if (bufChannels == 2 && numInputs == 2) { nsmps = nsmps / 2; for (int32 k = 0; k < nsmps; ++k) { float* table0 = bufData + writepos; table0[0] = *++(in[0]) * recLevel + table0[0] * preLevel; table0[1] = *++(in[1]) * recLevel + table0[1] * preLevel; writepos += 2; recLevel += recLevel_slope; preLevel += preLevel_slope; } } else { nsmps = nsmps / bufChannels; for (int32 k = 0; k < nsmps; ++k) { float* table0 = bufData + writepos; for (uint32 i = 0; i < numInputs; ++i) { float* samp = table0 + i; *samp = *++(in[i]) * recLevel + *samp * preLevel; } writepos += bufChannels; recLevel += recLevel_slope; preLevel += preLevel_slope; } } } else if (run < 0.f) { int nsmps = writepos; nsmps = sc_clip(nsmps, 0, inNumSamples * bufChannels); if (bufChannels == 1) { for (int32 k = 0; k < nsmps; ++k) { float* table0 = bufData + writepos; table0[0] = *++(in[0]) * recLevel + table0[0] * preLevel; writepos -= bufChannels; recLevel += recLevel_slope; preLevel += preLevel_slope; } } else if (bufChannels == 2 && numInputs == 2) { nsmps = nsmps / 2; for (int32 k = 0; k < nsmps; ++k) { float* table0 = bufData + writepos; table0[0] = *++(in[0]) * recLevel + table0[0] * preLevel; table0[1] = *++(in[1]) * recLevel + table0[1] * preLevel; writepos -= bufChannels; recLevel += recLevel_slope; preLevel += preLevel_slope; } } else { nsmps = nsmps / bufChannels; for (int32 k = 0; k < nsmps; ++k) { float* table0 = bufData + writepos; for (uint32 i = 0; i < numInputs; ++i) { float* samp = table0 + i; *samp = *++(in[i]) * recLevel + *samp * preLevel; } writepos -= bufChannels; recLevel += recLevel_slope; preLevel += preLevel_slope; } } } if (writepos >= (int32)bufSamples) { unit->mDone = true; DoneAction(IN0(7), unit); } } unit->m_prevtrig = trig; unit->m_writepos = writepos; unit->m_recLevel = recLevel; unit->m_preLevel = preLevel; } void RecordBuf_next_10(RecordBuf* unit, int inNumSamples) { // printf("RecordBuf_next_10\n"); GET_BUF CHECK_BUF SETUP_IN(8) float run = ZIN0(4); int32 loop = (int32)ZIN0(5); float trig = ZIN0(6); // printf("loop %d run %g\n", loop, run); int32 writepos = unit->m_writepos; if (loop) { if (trig > 0.f && unit->m_prevtrig <= 0.f) { unit->mDone = false; writepos = (int32)ZIN0(1) * bufChannels; } if (writepos < 0) writepos = bufSamples - bufChannels; else if (writepos >= (int32)bufSamples) writepos = 0; if (run > 0.f) { if (bufChannels == 1) { for (int32 k = 0; k < inNumSamples; ++k) { float* table0 = bufData + writepos; table0[0] = *++(in[0]); writepos += 1; if (writepos >= (int32)bufSamples) writepos = 0; } } else if (bufChannels == 2) { for (int32 k = 0; k < inNumSamples; ++k) { float* table0 = bufData + writepos; table0[0] = *++(in[0]); table0[1] = *++(in[1]); writepos += 2; if (writepos >= (int32)bufSamples) writepos = 0; } } else { for (int32 k = 0; k < inNumSamples; ++k) { float* table0 = bufData + writepos; for (uint32 i = 0; i < bufChannels; ++i) { float* samp = table0 + i; *samp = *++(in[i]); } writepos += bufChannels; if (writepos >= (int32)bufSamples) writepos = 0; } } } else if (run < 0.f) { if (bufChannels == 1) { for (int32 k = 0; k < inNumSamples; ++k) { float* table0 = bufData + writepos; table0[0] = *++(in[0]); writepos -= 1; if (writepos < 0) writepos = bufSamples - bufChannels; } } else if (bufChannels == 2) { for (int32 k = 0; k < inNumSamples; ++k) { float* table0 = bufData + writepos; table0[0] = *++(in[0]); table0[1] = *++(in[1]); writepos -= 2; if (writepos < 0) writepos = bufSamples - bufChannels; } } else { for (int32 k = 0; k < inNumSamples; ++k) { float* table0 = bufData + writepos; for (uint32 i = 0; i < bufChannels; ++i) { float* samp = table0 + i; *samp = *++(in[i]); } writepos -= bufChannels; if (writepos < 0) writepos = bufSamples - bufChannels; } } } } else { if (trig > 0.f && unit->m_prevtrig <= 0.f) { unit->mDone = false; writepos = (int32)ZIN0(1) * bufChannels; } if (run > 0.f) { int nsmps = bufSamples - writepos; nsmps = sc_clip(nsmps, 0, inNumSamples * bufChannels); if (bufChannels == 1) { for (int32 k = 0; k < nsmps; ++k) { float* table0 = bufData + writepos; table0[0] = *++(in[0]); writepos += 1; } } else if (bufChannels == 2) { nsmps = nsmps / 2; for (int32 k = 0; k < nsmps; ++k) { float* table0 = bufData + writepos; table0[0] = *++(in[0]); table0[1] = *++(in[1]); writepos += 2; } } else { nsmps = nsmps / bufChannels; for (int32 k = 0; k < nsmps; ++k) { float* table0 = bufData + writepos; for (uint32 i = 0; i < bufChannels; ++i) { float* samp = table0 + i; *samp = *++(in[i]); } writepos += bufChannels; } } } else if (run < 0.f) { int nsmps = writepos; nsmps = sc_clip(nsmps, 0, inNumSamples * bufChannels); if (bufChannels == 1) { for (int32 k = 0; k < nsmps; ++k) { float* table0 = bufData + writepos; table0[0] = *++(in[0]); writepos -= 1; } } else if (bufChannels == 2) { nsmps = nsmps / 2; for (int32 k = 0; k < nsmps; ++k) { float* table0 = bufData + writepos; table0[0] = *++(in[0]); table0[1] = *++(in[1]); writepos -= 2; } } else { nsmps = nsmps / bufChannels; for (int32 k = 0; k < nsmps; ++k) { float* table0 = bufData + writepos; for (uint32 i = 0; i < bufChannels; ++i) { float* samp = table0 + i; *samp = *++(in[i]); } writepos -= bufChannels; } } } if (writepos >= (int32)bufSamples) { unit->mDone = true; DoneAction(IN0(7), unit); } } unit->m_prevtrig = trig; unit->m_writepos = writepos; } //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// static float insertMedian(float* values, int* ages, int size, float value) { int pos = -1; // keeps a sorted list of the previous n=size values // the oldest is removed and the newest is inserted. // values between the oldest and the newest are shifted over by one. // values and ages are both arrays that are 'size' int. // the median value is always values[size>>1] int last = size - 1; // find oldest bin and age the other bins. for (int i = 0; i < size; ++i) { if (ages[i] == last) { // is it the oldest bin ? pos = i; } else { ages[i]++; // age the bin } } // move values to fill in place of the oldest and make a space for the newest // search lower if value is too small for the open space while (pos != 0 && value < values[pos - 1]) { values[pos] = values[pos - 1]; ages[pos] = ages[pos - 1]; pos--; } // search higher if value is too big for the open space while (pos != last && value > values[pos + 1]) { values[pos] = values[pos + 1]; ages[pos] = ages[pos + 1]; pos++; } values[pos] = value; ages[pos] = 0; // this is the newest bin, age = 0 return values[size >> 1]; } static void initMedian(float* values, int* ages, int size, float value) { // initialize the arrays with the first value for (int i = 0; i < size; ++i) { values[i] = value; ages[i] = i; } } enum { kPitchIn, kPitchInitFreq, kPitchMinFreq, kPitchMaxFreq, kPitchExecFreq, kPitchMaxBins, kPitchMedian, kPitchAmpThreshold, kPitchPeakThreshold, kPitchDownsamp, kPitchGetClarity }; void Pitch_Ctor(Pitch* unit) { unit->m_freq = ZIN0(kPitchInitFreq); unit->m_minfreq = ZIN0(kPitchMinFreq); unit->m_maxfreq = ZIN0(kPitchMaxFreq); float execfreq = ZIN0(kPitchExecFreq); execfreq = sc_clip(execfreq, unit->m_minfreq, unit->m_maxfreq); int maxbins = (int)ZIN0(kPitchMaxBins); unit->m_maxlog2bins = LOG2CEIL(maxbins); unit->m_medianSize = sc_clip((int)ZIN0(kPitchMedian), 0, kMAXMEDIANSIZE); unit->m_ampthresh = ZIN0(kPitchAmpThreshold); unit->m_peakthresh = ZIN0(kPitchPeakThreshold); int downsamp = (int)ZIN0(kPitchDownsamp); if (INRATE(kPitchIn) == calc_FullRate) { SETCALC(Pitch_next_a); unit->m_downsamp = sc_clip(downsamp, 1, unit->mWorld->mFullRate.mBufLength); unit->m_srate = FULLRATE / (float)unit->m_downsamp; } else { SETCALC(Pitch_next_k); unit->m_downsamp = sc_max(downsamp, 1); unit->m_srate = FULLRATE / (float)(unit->mWorld->mFullRate.mBufLength * unit->m_downsamp); } unit->m_minperiod = (long)(unit->m_srate / unit->m_maxfreq); unit->m_maxperiod = (long)(unit->m_srate / unit->m_minfreq); unit->m_execPeriod = (int)(unit->m_srate / execfreq); unit->m_execPeriod = sc_max(unit->m_execPeriod, unit->mWorld->mFullRate.mBufLength); unit->m_size = sc_max(unit->m_maxperiod << 1, unit->m_execPeriod); unit->m_buffer = (float*)RTAlloc(unit->mWorld, unit->m_size * sizeof(float)); ClearUnitIfMemFailed(unit->m_buffer); unit->m_index = 0; unit->m_readp = 0; unit->m_hasfreq = 0.f; initMedian(unit->m_values, unit->m_ages, unit->m_medianSize, unit->m_freq); unit->m_getClarity = ZIN0(kPitchGetClarity) > 0.f; ZOUT0(0) = 0.f; ZOUT0(1) = 0.f; } void Pitch_Dtor(Pitch* unit) { RTFree(unit->mWorld, unit->m_buffer); } void Pitch_next_a(Pitch* unit, int inNumSamples) { bool foundPeak; float* in = ZIN(kPitchIn); uint32 size = unit->m_size; uint32 index = unit->m_index; int downsamp = unit->m_downsamp; int readp = unit->m_readp; int ksamps = unit->mWorld->mFullRate.mBufLength; float* bufData = unit->m_buffer; float freq = unit->m_freq; float hasfreq = unit->m_hasfreq; // printf("> %d %d readp %d ksamps %d ds %d\n", index, size, readp, ksamps, downsamp); do { float z = in[readp]; bufData[index++] = z; readp += downsamp; if (index >= size) { float ampthresh = unit->m_ampthresh; bool ampok = false; hasfreq = 0.f; // assume failure int minperiod = unit->m_minperiod; int maxperiod = unit->m_maxperiod; // float maxamp = 0.f; // check for amp threshold for (int j = 0; j < maxperiod; ++j) { if (fabs(bufData[j]) >= ampthresh) { ampok = true; break; } // if (fabs(bufData[j]) > maxamp) maxamp = fabs(bufData[j]); } // printf("ampok %d maxperiod %d maxamp %g\n", ampok, maxperiod, maxamp); // if amplitude is too small then don't even look for pitch float ampsum; if (ampok) { int maxlog2bins = unit->m_maxlog2bins; int octave; // calculate the zero lag value and compute the threshold based on that float zerolagval = 0.f; for (int j = 0; j < maxperiod; ++j) { zerolagval += bufData[j] * bufData[j]; } float threshold = zerolagval * unit->m_peakthresh; // skip until drop below threshold int binstep, peakbinstep = 0; int i; for (i = 1; i <= maxperiod; i += binstep) { // compute sum of one lag ampsum = 0.f; for (int j = 0; j < maxperiod; ++j) { ampsum += bufData[i + j] * bufData[j]; } if (ampsum < threshold) break; octave = LOG2CEIL(i); if (octave <= maxlog2bins) { binstep = 1; } else { binstep = 1L << (octave - maxlog2bins); } } int startperiod = i; int period = startperiod; // printf("startperiod %d\n", startperiod); // find the first peak float maxsum = threshold; foundPeak = false; for (i = startperiod; i <= maxperiod; i += binstep) { if (i >= minperiod) { ampsum = 0.f; for (int j = 0; j < maxperiod; ++j) { ampsum += bufData[i + j] * bufData[j]; } if (ampsum > threshold) { if (ampsum > maxsum) { foundPeak = true; maxsum = ampsum; peakbinstep = binstep; period = i; } } else if (foundPeak) break; } octave = LOG2CEIL(i); if (octave <= maxlog2bins) { binstep = 1; } else { binstep = 1L << (octave - maxlog2bins); } } // printf("found %d thr %g maxs %g per %d bs %d\n", foundPeak, threshold, maxsum, period, // peakbinstep); if (foundPeak) { float prevampsum, nextampsum; // find amp sums immediately surrounding max prevampsum = 0.f; if (period > 0) { i = period - 1; for (int j = 0; j < maxperiod; ++j) { prevampsum += bufData[i + j] * bufData[j]; } } nextampsum = 0.f; if (period < maxperiod) { i = period + 1; for (int j = 0; j < maxperiod; ++j) { nextampsum += bufData[i + j] * bufData[j]; } } // printf("prevnext %g %g %g %d\n", prevampsum, maxsum, nextampsum, period); // not on a peak yet. This can happen if binstep > 1 while (prevampsum > maxsum && period > 0) { nextampsum = maxsum; maxsum = prevampsum; period--; i = period - 1; prevampsum = 0.f; for (int j = 0; j < maxperiod; ++j) { prevampsum += bufData[i + j] * bufData[j]; } // printf("slide left %g %g %g %d\n", prevampsum, maxsum, nextampsum, period); } while (nextampsum > maxsum && period < maxperiod) { prevampsum = maxsum; maxsum = nextampsum; period++; i = period + 1; nextampsum = 0.f; for (int j = 0; j < maxperiod; ++j) { nextampsum += bufData[i + j] * bufData[j]; } // printf("slide right %g %g %g %d\n", prevampsum, maxsum, nextampsum, period); } // make a fractional period float beta = 0.5f * (nextampsum - prevampsum); float gamma = 2.f * maxsum - nextampsum - prevampsum; float fperiod = (float)period + (beta / gamma); // calculate frequency float tempfreq = unit->m_srate / fperiod; // printf("freq %g %g / %g %g %g %d\n", tempfreq, unit->m_srate, fperiod, // unit->m_minfreq, unit->m_maxfreq, // tempfreq >= unit->m_minfreq && tempfreq <= unit->m_maxfreq); if (tempfreq >= unit->m_minfreq && tempfreq <= unit->m_maxfreq) { freq = tempfreq; // median filter if (unit->m_medianSize > 1) { freq = insertMedian(unit->m_values, unit->m_ages, unit->m_medianSize, freq); } if (unit->m_getClarity) hasfreq = maxsum / zerolagval; // "clarity" measure is normalised size of first peak else hasfreq = 1.f; startperiod = (ksamps + downsamp - 1) / downsamp; } } } /* else { printf("amp too low \n"); }*/ // shift buffer for next fill int execPeriod = unit->m_execPeriod; int interval = size - execPeriod; // printf("interval %d sz %d ep %d\n", interval, size, execPeriod); for (int i = 0; i < interval; i++) { bufData[i] = bufData[i + execPeriod]; } index = interval; } } while (readp < ksamps); ZOUT0(0) = freq; ZOUT0(1) = hasfreq; unit->m_readp = readp - ksamps; unit->m_index = index; unit->m_freq = freq; unit->m_hasfreq = hasfreq; } // control rate pitch tracking (nescivi 11/2008) void Pitch_next_k(Pitch* unit, int inNumSamples) { bool foundPeak; float in = ZIN0(kPitchIn); // one sample, current input uint32 size = unit->m_size; uint32 index = unit->m_index; int downsamp = unit->m_downsamp; int readp = unit->m_readp; // int ksamps = unit->mWorld->mFullRate.mBufLength; float* bufData = unit->m_buffer; float freq = unit->m_freq; float hasfreq = unit->m_hasfreq; // printf("> %d %d readp %d downsamp %d exec %d\n", index, size, readp, downsamp, unit->m_execPeriod); readp++; if (readp == downsamp) { // do { // float z = in[readp]; float z = in; bufData[index++] = z; readp = 0; // readp += downsamp; if (index >= size) { float ampthresh = unit->m_ampthresh; bool ampok = false; hasfreq = 0.f; // assume failure int minperiod = unit->m_minperiod; int maxperiod = unit->m_maxperiod; // float maxamp = 0.f; // check for amp threshold for (int j = 0; j < maxperiod; ++j) { if (fabs(bufData[j]) >= ampthresh) { ampok = true; break; } // if (fabs(bufData[j]) > maxamp) maxamp = fabs(bufData[j]); } // printf("ampok %d maxperiod %d maxamp %g\n", ampok, maxperiod, maxamp); // if amplitude is too small then don't even look for pitch float ampsum; if (ampok) { int maxlog2bins = unit->m_maxlog2bins; int octave; // calculate the zero lag value and compute the threshold based on that float zerolagval = 0.f; for (int j = 0; j < maxperiod; ++j) { zerolagval += bufData[j] * bufData[j]; } float threshold = zerolagval * unit->m_peakthresh; // skip until drop below threshold int binstep, peakbinstep = 0; int i; for (i = 1; i <= maxperiod; i += binstep) { // compute sum of one lag ampsum = 0.f; for (int j = 0; j < maxperiod; ++j) { ampsum += bufData[i + j] * bufData[j]; } if (ampsum < threshold) break; octave = LOG2CEIL(i); if (octave <= maxlog2bins) { binstep = 1; } else { binstep = 1L << (octave - maxlog2bins); } } int startperiod = i; int period = startperiod; // printf("startperiod %d\n", startperiod); // find the first peak float maxsum = threshold; foundPeak = false; for (i = startperiod; i <= maxperiod; i += binstep) { if (i >= minperiod) { ampsum = 0.f; for (int j = 0; j < maxperiod; ++j) { ampsum += bufData[i + j] * bufData[j]; } if (ampsum > threshold) { if (ampsum > maxsum) { foundPeak = true; maxsum = ampsum; peakbinstep = binstep; period = i; } } else if (foundPeak) break; } octave = LOG2CEIL(i); if (octave <= maxlog2bins) { binstep = 1; } else { binstep = 1L << (octave - maxlog2bins); } } // printf("found %d thr %g maxs %g per %d bs %d\n", foundPeak, threshold, maxsum, period, // peakbinstep); if (foundPeak) { float prevampsum, nextampsum; // find amp sums immediately surrounding max prevampsum = 0.f; if (period > 0) { i = period - 1; for (int j = 0; j < maxperiod; ++j) { prevampsum += bufData[i + j] * bufData[j]; } } nextampsum = 0.f; if (period < maxperiod) { i = period + 1; for (int j = 0; j < maxperiod; ++j) { nextampsum += bufData[i + j] * bufData[j]; } } // printf("prevnext %g %g %g %d\n", prevampsum, maxsum, nextampsum, period); // not on a peak yet. This can happen if binstep > 1 while (prevampsum > maxsum && period > 0) { nextampsum = maxsum; maxsum = prevampsum; period--; i = period - 1; prevampsum = 0.f; for (int j = 0; j < maxperiod; ++j) { prevampsum += bufData[i + j] * bufData[j]; } // printf("slide left %g %g %g %d\n", prevampsum, maxsum, nextampsum, period); } while (nextampsum > maxsum && period < maxperiod) { prevampsum = maxsum; maxsum = nextampsum; period++; i = period + 1; nextampsum = 0.f; for (int j = 0; j < maxperiod; ++j) { nextampsum += bufData[i + j] * bufData[j]; } // printf("slide right %g %g %g %d\n", prevampsum, maxsum, nextampsum, period); } // make a fractional period float beta = 0.5 * (nextampsum - prevampsum); float gamma = 2.0 * maxsum - nextampsum - prevampsum; float fperiod = (float)period + (beta / gamma); // calculate frequency float tempfreq = unit->m_srate / fperiod; // printf("freq %g %g / %g %g %g %d\n", tempfreq, unit->m_srate, fperiod, // unit->m_minfreq, unit->m_maxfreq, // tempfreq >= unit->m_minfreq && tempfreq <= unit->m_maxfreq); if (tempfreq >= unit->m_minfreq && tempfreq <= unit->m_maxfreq) { freq = tempfreq; // median filter if (unit->m_medianSize > 1) { freq = insertMedian(unit->m_values, unit->m_ages, unit->m_medianSize, freq); } if (unit->m_getClarity) hasfreq = maxsum / zerolagval; // "clarity" measure is normalised size of first peak else hasfreq = 1.f; // nescivi: not sure about this one? startperiod = 1; // (ksamps+downsamp-1)/downsamp; } } } /* else { printf("amp too low \n"); }*/ // shift buffer for next fill int execPeriod = unit->m_execPeriod; int interval = size - execPeriod; // printf("interval %d sz %d ep %d\n", interval, size, execPeriod); for (int i = 0; i < interval; i++) { bufData[i] = bufData[i + execPeriod]; } index = interval; } } // while (readp < ksamps); ZOUT0(0) = freq; ZOUT0(1) = hasfreq; // unit->m_readp = readp - ksamps; unit->m_readp = readp; unit->m_index = index; unit->m_freq = freq; unit->m_hasfreq = hasfreq; } //////////////////////////////////////////////////////////////////////////////////////////////////////// #if 0 void DelayUnit_AllocDelayLine(DelayUnit *unit) { long delaybufsize = (long)ceil(unit->m_maxdelaytime * SAMPLERATE + 1.f); delaybufsize = delaybufsize + BUFLENGTH; delaybufsize = NEXTPOWEROFTWO(delaybufsize); // round up to next power of two unit->m_fdelaylen = unit->m_idelaylen = delaybufsize; RTFree(unit->mWorld, unit->m_dlybuf); int size = delaybufsize * sizeof(float); //Print("->RTAlloc %d\n", size); unit->m_dlybuf = (float*)RTAlloc(unit->mWorld, size); //Print("<-RTAlloc %p\n", unit->m_dlybuf); unit->m_mask = delaybufsize - 1; } #endif template <typename Unit> static float BufCalcDelay(const Unit* unit, int bufSamples, float delayTime) { float minDelay = Unit::minDelaySamples; return sc_clip(delayTime * (float)SAMPLERATE, minDelay, (float)(PREVIOUSPOWEROFTWO(bufSamples)) - 1); } template <typename Unit> static void BufDelayUnit_Reset(Unit* unit) { // Print("->DelayUnit_Reset\n"); // unit->m_maxdelaytime = ZIN0(1); unit->m_delaytime = ZIN0(2); // Print("unit->m_delaytime %g\n", unit->m_delaytime); // unit->m_dlybuf = 0; unit->m_fbufnum = -1e9f; // DelayUnit_AllocDelayLine(unit); // Print("->GET_BUF\n"); GET_BUF // Print("<-GET_BUF\n"); unit->m_dsamp = BufCalcDelay(unit, bufSamples, unit->m_delaytime); unit->m_numoutput = 0; unit->m_iwrphase = 0; } //////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename Unit> static void BufFeedbackDelay_Reset(Unit* unit) { BufDelayUnit_Reset(unit); unit->m_decaytime = ZIN0(3); unit->m_feedbk = sc_CalcFeedback(unit->m_delaytime, unit->m_decaytime); } //////////////////////////////////////////////////////////////////////////////////////////////////////// namespace { /* helper classes for delay functionality */ template <bool Checked = false> struct DelayN_helper { static const bool checked = false; static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, long mask) { long irdphase = iwrphase - idsamp; bufData[iwrphase & mask] = ZXP(in); ZXP(out) = bufData[irdphase & mask]; iwrphase++; } /* the frac argument is unneeded. the compiler should make sure, that it won't be computed */ static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, float frac, long mask) { perform(in, out, bufData, iwrphase, idsamp, mask); } }; template <> struct DelayN_helper<true> { static const bool checked = true; static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, long mask) { long irdphase = iwrphase - idsamp; bufData[iwrphase & mask] = ZXP(in); if (irdphase < 0) ZXP(out) = 0.f; else ZXP(out) = bufData[irdphase & mask]; iwrphase++; } static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, float frac, long mask) { perform(in, out, bufData, iwrphase, idsamp, mask); } }; template <bool initializing> static inline void DelayN_delay_loop(float* out, const float* in, long& iwrphase, float dsamp, long mask, float* dlybuf, int inNumSamples, int idelaylen) { long irdphase = iwrphase - (long)dsamp; float* dlybuf1 = dlybuf - ZOFF; float* dlyrd = dlybuf1 + (irdphase & mask); float* dlywr = dlybuf1 + (iwrphase & mask); float* dlyN = dlybuf1 + idelaylen; long remain = inNumSamples; while (remain) { long rdspace = dlyN - dlyrd; long wrspace = dlyN - dlywr; if (initializing) { long nsmps = sc_min(rdspace, wrspace); nsmps = sc_min(remain, nsmps); remain -= nsmps; if (irdphase < 0) { if ((dlywr - dlyrd) > nsmps) { #ifdef NOVA_SIMD if ((nsmps & (nova::vec<float>::size - 1)) == 0) { nova::copyvec_nn_simd(dlywr + ZOFF, in + ZOFF, nsmps); nova::zerovec_na_simd(out + ZOFF, nsmps); } else #endif { ZCopy(nsmps, dlywr, in); ZClear(nsmps, out); } out += nsmps; in += nsmps; dlyrd += nsmps; dlywr += nsmps; } else { LOOP(nsmps, ZXP(dlywr) = ZXP(in); ZXP(out) = 0.f;); dlyrd += nsmps; } } else { LOOP(nsmps, ZXP(dlywr) = ZXP(in); ZXP(out) = ZXP(dlyrd);); } irdphase += nsmps; if (dlyrd == dlyN) dlyrd = dlybuf1; if (dlywr == dlyN) dlywr = dlybuf1; } else { long nsmps = sc_min(rdspace, wrspace); nsmps = sc_min(remain, nsmps); remain -= nsmps; if (std::abs((float)(dlyrd - dlywr)) > nsmps) { #ifdef NOVA_SIMD if ((nsmps & 15) == 0) { nova::copyvec_nn_simd(dlywr + ZOFF, in + ZOFF, nsmps); nova::copyvec_nn_simd(out + ZOFF, dlyrd + ZOFF, nsmps); } else #endif { ZCopy(nsmps, dlywr, in); ZCopy(nsmps, out, dlyrd); } out += nsmps; in += nsmps; dlyrd += nsmps; dlywr += nsmps; } else LOOP(nsmps, ZXP(dlywr) = ZXP(in); ZXP(out) = ZXP(dlyrd);); if (dlyrd == dlyN) dlyrd = dlybuf1; if (dlywr == dlyN) dlywr = dlybuf1; } } iwrphase += inNumSamples; } template <bool Checked = false> struct DelayL_helper { static const bool checked = false; static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, float frac, long mask) { bufData[iwrphase & mask] = ZXP(in); long irdphase = iwrphase - idsamp; long irdphaseb = irdphase - 1; float d1 = bufData[irdphase & mask]; float d2 = bufData[irdphaseb & mask]; ZXP(out) = lininterp(frac, d1, d2); iwrphase++; } }; template <> struct DelayL_helper<true> { static const bool checked = true; static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, float frac, long mask) { bufData[iwrphase & mask] = ZXP(in); long irdphase = iwrphase - idsamp; long irdphaseb = irdphase - 1; if (irdphase < 0) { ZXP(out) = 0.f; } else if (irdphaseb < 0) { float d1 = bufData[irdphase & mask]; ZXP(out) = d1 - frac * d1; } else { float d1 = bufData[irdphase & mask]; float d2 = bufData[irdphaseb & mask]; ZXP(out) = lininterp(frac, d1, d2); } iwrphase++; } }; template <bool Checked = false> struct DelayC_helper { static const bool checked = false; static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, float frac, long mask) { bufData[iwrphase & mask] = ZXP(in); long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; float d0 = bufData[irdphase0 & mask]; float d1 = bufData[irdphase1 & mask]; float d2 = bufData[irdphase2 & mask]; float d3 = bufData[irdphase3 & mask]; ZXP(out) = cubicinterp(frac, d0, d1, d2, d3); iwrphase++; } }; template <> struct DelayC_helper<true> { static const bool checked = true; static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, float frac, long mask) { long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; bufData[iwrphase & mask] = ZXP(in); if (irdphase0 < 0) { ZXP(out) = 0.f; } else { float d0, d1, d2, d3; if (irdphase1 < 0) { d1 = d2 = d3 = 0.f; d0 = bufData[irdphase0 & mask]; } else if (irdphase2 < 0) { d1 = d2 = d3 = 0.f; d0 = bufData[irdphase0 & mask]; d1 = bufData[irdphase1 & mask]; } else if (irdphase3 < 0) { d3 = 0.f; d0 = bufData[irdphase0 & mask]; d1 = bufData[irdphase1 & mask]; d2 = bufData[irdphase2 & mask]; } else { d0 = bufData[irdphase0 & mask]; d1 = bufData[irdphase1 & mask]; d2 = bufData[irdphase2 & mask]; d3 = bufData[irdphase3 & mask]; } ZXP(out) = cubicinterp(frac, d0, d1, d2, d3); } iwrphase++; } }; template <bool Checked = false> struct CombN_helper { static const bool checked = false; static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, long mask, float feedbk) { long irdphase = iwrphase - idsamp; float value = bufData[irdphase & mask]; bufData[iwrphase & mask] = ZXP(in) + feedbk * value; ZXP(out) = value; ++iwrphase; } /* the frac argument is unneeded. the compiler should make sure, that it won't be computed */ static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, float frac, long mask, float feedbk) { perform(in, out, bufData, iwrphase, idsamp, mask, feedbk); } }; template <> struct CombN_helper<true> { static const bool checked = true; static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, long mask, float feedbk) { long irdphase = iwrphase - idsamp; if (irdphase < 0) { bufData[iwrphase & mask] = ZXP(in); ZXP(out) = 0.f; } else { float value = bufData[irdphase & mask]; bufData[iwrphase & mask] = ZXP(in) + feedbk * value; ZXP(out) = value; } iwrphase++; } static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, float frac, long mask, float feedbk) { perform(in, out, bufData, iwrphase, idsamp, mask, feedbk); } }; template <bool Checked = false> struct CombL_helper { static const bool checked = false; static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, float frac, long mask, float feedbk) { long irdphase = iwrphase - idsamp; long irdphaseb = irdphase - 1; float d1 = bufData[irdphase & mask]; float d2 = bufData[irdphaseb & mask]; float value = lininterp(frac, d1, d2); bufData[iwrphase & mask] = ZXP(in) + feedbk * value; ZXP(out) = value; iwrphase++; } }; template <> struct CombL_helper<true> { static const bool checked = true; static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, float frac, long mask, float feedbk) { long irdphase = iwrphase - idsamp; long irdphaseb = irdphase - 1; float zin = ZXP(in); if (irdphase < 0) { bufData[iwrphase & mask] = zin; ZXP(out) = 0.f; } else if (irdphaseb < 0) { float d1 = bufData[irdphase & mask]; float value = d1 - frac * d1; bufData[iwrphase & mask] = zin + feedbk * value; ZXP(out) = value; } else { float d1 = bufData[irdphase & mask]; float d2 = bufData[irdphaseb & mask]; float value = lininterp(frac, d1, d2); bufData[iwrphase & mask] = zin + feedbk * value; ZXP(out) = value; } iwrphase++; } }; template <bool Checked = false> struct CombC_helper { static const bool checked = false; static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, float frac, long mask, float feedbk) { long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; float d0 = bufData[irdphase0 & mask]; float d1 = bufData[irdphase1 & mask]; float d2 = bufData[irdphase2 & mask]; float d3 = bufData[irdphase3 & mask]; float value = cubicinterp(frac, d0, d1, d2, d3); bufData[iwrphase & mask] = ZXP(in) + feedbk * value; ZXP(out) = value; iwrphase++; } }; template <> struct CombC_helper<true> { static const bool checked = true; static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, float frac, long mask, float feedbk) { long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; if (irdphase0 < 0) { bufData[iwrphase & mask] = ZXP(in); ZXP(out) = 0.f; } else { float d0, d1, d2, d3; if (irdphase1 < 0) { d1 = d2 = d3 = 0.f; d0 = bufData[irdphase0 & mask]; } else if (irdphase2 < 0) { d1 = d2 = d3 = 0.f; d0 = bufData[irdphase0 & mask]; d1 = bufData[irdphase1 & mask]; } else if (irdphase3 < 0) { d3 = 0.f; d0 = bufData[irdphase0 & mask]; d1 = bufData[irdphase1 & mask]; d2 = bufData[irdphase2 & mask]; } else { d0 = bufData[irdphase0 & mask]; d1 = bufData[irdphase1 & mask]; d2 = bufData[irdphase2 & mask]; d3 = bufData[irdphase3 & mask]; } float value = cubicinterp(frac, d0, d1, d2, d3); bufData[iwrphase & mask] = ZXP(in) + feedbk * value; ZXP(out) = value; } iwrphase++; } }; template <bool Checked = false> struct AllpassN_helper { static const bool checked = false; static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, long mask, float feedbk) { long irdphase = iwrphase - idsamp; float value = bufData[irdphase & mask]; float dwr = value * feedbk + ZXP(in); bufData[iwrphase & mask] = dwr; ZXP(out) = value - feedbk * dwr; ++iwrphase; } /* the frac argument is unneeded. the compiler should make sure, that it won't be computed */ static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, float frac, long mask, float feedbk) { perform(in, out, bufData, iwrphase, idsamp, mask, feedbk); } }; template <> struct AllpassN_helper<true> { static const bool checked = true; static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, long mask, float feedbk) { long irdphase = iwrphase - idsamp; if (irdphase < 0) { float dwr = ZXP(in); bufData[iwrphase & mask] = dwr; ZXP(out) = -feedbk * dwr; } else { float value = bufData[irdphase & mask]; float dwr = feedbk * value + ZXP(in); bufData[iwrphase & mask] = dwr; ZXP(out) = value - feedbk * dwr; } ++iwrphase; } static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, float frac, long mask, float feedbk) { perform(in, out, bufData, iwrphase, idsamp, mask, feedbk); } }; template <bool Checked = false> struct AllpassL_helper { static const bool checked = false; static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, float frac, long mask, float feedbk) { long irdphase = iwrphase - idsamp; long irdphaseb = irdphase - 1; float d1 = bufData[irdphase & mask]; float d2 = bufData[irdphaseb & mask]; float value = lininterp(frac, d1, d2); float dwr = ZXP(in) + feedbk * value; bufData[iwrphase & mask] = dwr; ZXP(out) = value - feedbk * dwr; iwrphase++; } }; template <> struct AllpassL_helper<true> { static const bool checked = true; static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, float frac, long mask, float feedbk) { long irdphase = iwrphase - idsamp; long irdphaseb = irdphase - 1; float zin = ZXP(in); if (irdphase < 0) { bufData[iwrphase & mask] = zin; ZXP(out) = -feedbk * zin; } else if (irdphaseb < 0) { float d1 = bufData[irdphase & mask]; float value = d1 - frac * d1; float dwr = zin + feedbk * value; bufData[iwrphase & mask] = dwr; ZXP(out) = value - feedbk * dwr; } else { float d1 = bufData[irdphase & mask]; float d2 = bufData[irdphaseb & mask]; float value = lininterp(frac, d1, d2); float dwr = zin + feedbk * value; bufData[iwrphase & mask] = dwr; ZXP(out) = value - feedbk * dwr; } iwrphase++; } }; template <bool Checked = false> struct AllpassC_helper { static const bool checked = false; static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, float frac, long mask, float feedbk) { long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; float d0 = bufData[irdphase0 & mask]; float d1 = bufData[irdphase1 & mask]; float d2 = bufData[irdphase2 & mask]; float d3 = bufData[irdphase3 & mask]; float value = cubicinterp(frac, d0, d1, d2, d3); float dwr = ZXP(in) + feedbk * value; bufData[iwrphase & mask] = dwr; ZXP(out) = value - feedbk * dwr; iwrphase++; } }; template <> struct AllpassC_helper<true> { static const bool checked = true; static inline void perform(const float*& in, float*& out, float* bufData, long& iwrphase, long idsamp, float frac, long mask, float feedbk) { long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; if (irdphase0 < 0) { bufData[iwrphase & mask] = ZXP(in); ZXP(out) = 0.f; } else { float d0, d1, d2, d3; if (irdphase1 < 0) { d1 = d2 = d3 = 0.f; d0 = bufData[irdphase0 & mask]; } else if (irdphase2 < 0) { d1 = d2 = d3 = 0.f; d0 = bufData[irdphase0 & mask]; d1 = bufData[irdphase1 & mask]; } else if (irdphase3 < 0) { d3 = 0.f; d0 = bufData[irdphase0 & mask]; d1 = bufData[irdphase1 & mask]; d2 = bufData[irdphase2 & mask]; } else { d0 = bufData[irdphase0 & mask]; d1 = bufData[irdphase1 & mask]; d2 = bufData[irdphase2 & mask]; d3 = bufData[irdphase3 & mask]; } float value = cubicinterp(frac, d0, d1, d2, d3); float dwr = ZXP(in) + feedbk * value; bufData[iwrphase & mask] = dwr; ZXP(out) = value - feedbk * dwr; } iwrphase++; } }; } //////////////////////////////////////////////////////////////////////////////////////////////////////// /* template function to generate buffer-based delay ugen function, control-rate delay time */ template <typename PerformClass, typename BufDelayX> inline void BufDelayX_perform(BufDelayX* unit, int inNumSamples, UnitCalcFunc resetFunc) { float* out = ZOUT(0); const float* in = ZIN(1); float delaytime = ZIN0(2); GET_BUF CHECK_BUF long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; if (delaytime == unit->m_delaytime) { long idsamp = (long)dsamp; float frac = dsamp - idsamp; LOOP1(inNumSamples, PerformClass::perform(in, out, bufData, iwrphase, idsamp, frac, mask);); } else { float next_dsamp = BufCalcDelay(unit, bufSamples, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); LOOP1(inNumSamples, dsamp += dsamp_slope; long idsamp = (long)dsamp; float frac = dsamp - idsamp; PerformClass::perform(in, out, bufData, iwrphase, idsamp, frac, mask);); unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; } unit->m_iwrphase = iwrphase; if (PerformClass::checked) { unit->m_numoutput += inNumSamples; if (unit->m_numoutput >= bufSamples) unit->mCalcFunc = resetFunc; } } /* template function to generate buffer-based delay ugen function, audio-rate delay time */ template <typename PerformClass, typename BufDelayX> inline void BufDelayX_perform_a(BufDelayX* unit, int inNumSamples, UnitCalcFunc resetFunc) { float* out = ZOUT(0); const float* in = ZIN(1); float* delaytime = ZIN(2); GET_BUF CHECK_BUF long iwrphase = unit->m_iwrphase; LOOP1(inNumSamples, float dsamp = BufCalcDelay(unit, bufSamples, ZXP(delaytime)); long idsamp = (long)dsamp; float frac = dsamp - idsamp; PerformClass::perform(in, out, bufData, iwrphase, idsamp, frac, mask);); unit->m_iwrphase = iwrphase; if (PerformClass::checked) { unit->m_numoutput += inNumSamples; if (unit->m_numoutput >= bufSamples) unit->mCalcFunc = resetFunc; } } //////////////////////////////////////////////////////////////////////////////////////////////////////// void BufDelayN_Ctor(BufDelayN* unit) { if (INRATE(2) == calc_FullRate) SETCALC(BufDelayN_next_a_z); else SETCALC(BufDelayN_next_z); BufDelayUnit_Reset(unit); ZOUT0(0) = 0.f; } void BufDelayN_next(BufDelayN* unit, int inNumSamples) { float* out = ZOUT(0); const float* in = ZIN(1); float delaytime = ZIN0(2); GET_BUF CHECK_BUF long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; if (delaytime == unit->m_delaytime) { DelayN_delay_loop<false>(out, in, iwrphase, dsamp, mask, bufData, inNumSamples, PREVIOUSPOWEROFTWO(bufSamples)); } else { float next_dsamp = BufCalcDelay(unit, bufSamples, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); LOOP1(inNumSamples, dsamp += dsamp_slope; long idsamp = (long)dsamp; DelayN_helper<false>::perform(in, out, bufData, iwrphase, idsamp, mask);); unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; } unit->m_iwrphase = iwrphase; } void BufDelayN_next_z(BufDelayN* unit, int inNumSamples) { float* out = ZOUT(0); const float* in = ZIN(1); float delaytime = ZIN0(2); GET_BUF CHECK_BUF long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; if (delaytime == unit->m_delaytime) { DelayN_delay_loop<true>(out, in, iwrphase, dsamp, mask, bufData, inNumSamples, PREVIOUSPOWEROFTWO(bufSamples)); } else { float next_dsamp = BufCalcDelay(unit, bufSamples, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); LOOP1(inNumSamples, dsamp += dsamp_slope; long idsamp = (long)dsamp; DelayN_helper<true>::perform(in, out, bufData, iwrphase, idsamp, mask);); unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; } unit->m_iwrphase = iwrphase; unit->m_numoutput += inNumSamples; if (unit->m_numoutput >= bufSamples) SETCALC(BufDelayN_next); } template <bool checked> inline void BufDelayN_perform_a(BufDelayN* unit, int inNumSamples) { BufDelayX_perform_a<DelayN_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)BufDelayN_next_a); } void BufDelayN_next_a(BufDelayN* unit, int inNumSamples) { BufDelayN_perform_a<false>(unit, inNumSamples); } void BufDelayN_next_a_z(BufDelayN* unit, int inNumSamples) { BufDelayN_perform_a<true>(unit, inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// void BufDelayL_Ctor(BufDelayL* unit) { BufDelayUnit_Reset(unit); if (INRATE(2) == calc_FullRate) SETCALC(BufDelayL_next_a_z); else SETCALC(BufDelayL_next_z); ZOUT0(0) = 0.f; } template <bool checked> inline void BufDelayL_perform(BufDelayL* unit, int inNumSamples) { BufDelayX_perform<DelayL_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)BufDelayL_next); } void BufDelayL_next(BufDelayL* unit, int inNumSamples) { BufDelayL_perform<false>(unit, inNumSamples); } void BufDelayL_next_z(BufDelayL* unit, int inNumSamples) { BufDelayL_perform<true>(unit, inNumSamples); } template <bool checked> inline void BufDelayL_perform_a(BufDelayL* unit, int inNumSamples) { BufDelayX_perform_a<DelayL_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)BufDelayL_next_a); } void BufDelayL_next_a(BufDelayL* unit, int inNumSamples) { BufDelayL_perform_a<false>(unit, inNumSamples); } void BufDelayL_next_a_z(BufDelayL* unit, int inNumSamples) { BufDelayL_perform_a<true>(unit, inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void BufDelayC_Ctor(BufDelayC* unit) { BufDelayUnit_Reset(unit); if (INRATE(2) == calc_FullRate) SETCALC(BufDelayC_next_a_z); else SETCALC(BufDelayC_next_z); ZOUT0(0) = 0.f; } template <bool checked> inline void BufDelayC_perform(BufDelayC* unit, int inNumSamples) { BufDelayX_perform<DelayC_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)BufDelayC_next); } void BufDelayC_next(BufDelayC* unit, int inNumSamples) { BufDelayC_perform<false>(unit, inNumSamples); } void BufDelayC_next_z(BufDelayC* unit, int inNumSamples) { BufDelayC_perform<true>(unit, inNumSamples); } template <bool checked> inline void BufDelayC_perform_a(BufDelayC* unit, int inNumSamples) { BufDelayX_perform_a<DelayC_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)BufDelayL_next_a); } void BufDelayC_next_a(BufDelayC* unit, int inNumSamples) { BufDelayC_perform_a<false>(unit, inNumSamples); } void BufDelayC_next_a_z(BufDelayC* unit, int inNumSamples) { BufDelayC_perform_a<true>(unit, inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename PerformClass, typename BufCombX> inline void BufFilterX_perform(BufCombX* unit, int inNumSamples, UnitCalcFunc resetFunc) { float* out = ZOUT(0); const float* in = ZIN(1); float delaytime = ZIN0(2); float decaytime = ZIN0(3); GET_BUF CHECK_BUF long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; float feedbk = unit->m_feedbk; if (delaytime == unit->m_delaytime && decaytime == unit->m_decaytime) { long idsamp = (long)dsamp; float frac = dsamp - idsamp; LOOP1(inNumSamples, PerformClass::perform(in, out, bufData, iwrphase, idsamp, frac, mask, feedbk);); } else { float next_dsamp = BufCalcDelay(unit, bufSamples, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); LOOP1(inNumSamples, dsamp += dsamp_slope; feedbk += feedbk_slope; long idsamp = (long)dsamp; float frac = dsamp - idsamp; PerformClass::perform(in, out, bufData, iwrphase, idsamp, frac, mask, feedbk);); unit->m_feedbk = feedbk; unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; unit->m_decaytime = decaytime; } unit->m_iwrphase = iwrphase; if (PerformClass::checked) { unit->m_numoutput += inNumSamples; if (unit->m_numoutput >= bufSamples) unit->mCalcFunc = resetFunc; } } template <typename PerformClass, typename BufCombX> inline void BufFilterX_perform_a(BufCombX* unit, int inNumSamples, UnitCalcFunc resetFunc) { float* out = ZOUT(0); const float* in = ZIN(1); float* delaytime = ZIN(2); float decaytime = ZIN0(3); GET_BUF CHECK_BUF long iwrphase = unit->m_iwrphase; LOOP1(inNumSamples, float del = ZXP(delaytime); float dsamp = BufCalcDelay(unit, bufSamples, del); float feedbk = sc_CalcFeedback(del, decaytime); long idsamp = (long)dsamp; float frac = dsamp - idsamp; PerformClass::perform(in, out, bufData, iwrphase, idsamp, frac, mask, feedbk);); unit->m_iwrphase = iwrphase; if (PerformClass::checked) { unit->m_numoutput += inNumSamples; if (unit->m_numoutput >= bufSamples) unit->mCalcFunc = resetFunc; } } //////////////////////////////////////////////////////////////////////////////////////////////////////// void BufCombN_Ctor(BufCombN* unit) { BufFeedbackDelay_Reset(unit); if (INRATE(2) == calc_FullRate) SETCALC(BufCombN_next_a_z); else SETCALC(BufCombN_next_z); ZOUT0(0) = 0.f; } void BufCombN_next(BufCombN* unit, int inNumSamples) { float* out = ZOUT(0); const float* in = ZIN(1); float delaytime = ZIN0(2); float decaytime = ZIN0(3); GET_BUF CHECK_BUF long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; float feedbk = unit->m_feedbk; // postbuf("BufCombN_next %g %g %g %g %d %d %d\n", delaytime, decaytime, feedbk, dsamp, mask, iwrphase, zorg); if (delaytime == unit->m_delaytime) { long irdphase = iwrphase - (long)dsamp; float* dlybuf1 = bufData - ZOFF; float* dlyrd = dlybuf1 + (irdphase & mask); float* dlywr = dlybuf1 + (iwrphase & mask); float* dlyN = dlybuf1 + PREVIOUSPOWEROFTWO(bufSamples); if (decaytime == unit->m_decaytime) { long remain = inNumSamples; while (remain) { long rdspace = dlyN - dlyrd; long wrspace = dlyN - dlywr; long nsmps = sc_min(rdspace, wrspace); nsmps = sc_min(remain, nsmps); remain -= nsmps; LOOP1(nsmps, float value = ZXP(dlyrd); ZXP(dlywr) = value * feedbk + ZXP(in); ZXP(out) = value;); if (dlyrd == dlyN) dlyrd = dlybuf1; if (dlywr == dlyN) dlywr = dlybuf1; } } else { float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); long remain = inNumSamples; while (remain) { long rdspace = dlyN - dlyrd; long wrspace = dlyN - dlywr; long nsmps = sc_min(rdspace, wrspace); nsmps = sc_min(remain, nsmps); remain -= nsmps; LOOP1(nsmps, float value = ZXP(dlyrd); ZXP(dlywr) = value * feedbk + ZXP(in); ZXP(out) = value; feedbk += feedbk_slope;); if (dlyrd == dlyN) dlyrd = dlybuf1; if (dlywr == dlyN) dlywr = dlybuf1; } unit->m_feedbk = feedbk; unit->m_decaytime = decaytime; } iwrphase += inNumSamples; } else { float next_dsamp = BufCalcDelay(unit, bufSamples, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); LOOP1(inNumSamples, dsamp += dsamp_slope; feedbk += feedbk_slope; CombN_helper<false>::perform(in, out, bufData, iwrphase, (long)dsamp, mask, feedbk);); unit->m_feedbk = feedbk; unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; unit->m_decaytime = decaytime; } unit->m_iwrphase = iwrphase; } void BufCombN_next_z(BufCombN* unit, int inNumSamples) { float* out = ZOUT(0); const float* in = ZIN(1); float delaytime = ZIN0(2); float decaytime = ZIN0(3); GET_BUF CHECK_BUF long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; float feedbk = unit->m_feedbk; // Print("BufCombN_next_z %g %g %g %g %d %d %d\n", delaytime, decaytime, feedbk, dsamp, mask, iwrphase, zorg); if (delaytime == unit->m_delaytime) { long irdphase = iwrphase - (long)dsamp; float* dlybuf1 = bufData - ZOFF; float* dlyN = dlybuf1 + PREVIOUSPOWEROFTWO(bufSamples); if (decaytime == unit->m_decaytime) { long remain = inNumSamples; while (remain) { float* dlywr = dlybuf1 + (iwrphase & mask); float* dlyrd = dlybuf1 + (irdphase & mask); long rdspace = dlyN - dlyrd; long wrspace = dlyN - dlywr; long nsmps = sc_min(rdspace, wrspace); nsmps = sc_min(remain, nsmps); remain -= nsmps; if (irdphase < 0) { LOOP1(nsmps, ZXP(dlywr) = ZXP(in); ZXP(out) = 0.f;); } else { LOOP1(nsmps, float value = ZXP(dlyrd); ZXP(dlywr) = value * feedbk + ZXP(in); ZXP(out) = value;); } iwrphase += nsmps; irdphase += nsmps; } } else { float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); long remain = inNumSamples; while (remain) { float* dlyrd = dlybuf1 + (irdphase & mask); float* dlywr = dlybuf1 + (iwrphase & mask); long rdspace = dlyN - dlyrd; long wrspace = dlyN - dlywr; long nsmps = sc_min(rdspace, wrspace); nsmps = sc_min(remain, nsmps); remain -= nsmps; if (irdphase < 0) { feedbk += nsmps * feedbk_slope; dlyrd += nsmps; LOOP1(nsmps, ZXP(dlywr) = ZXP(in); ZXP(out) = 0.f;); } else { LOOP1(nsmps, float value = ZXP(dlyrd); ZXP(dlywr) = value * feedbk + ZXP(in); ZXP(out) = value; feedbk += feedbk_slope;); } iwrphase += nsmps; irdphase += nsmps; } unit->m_feedbk = feedbk; unit->m_decaytime = decaytime; } } else { float next_dsamp = BufCalcDelay(unit, bufSamples, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); LOOP1(inNumSamples, dsamp += dsamp_slope; feedbk += feedbk_slope; CombN_helper<true>::perform(in, out, bufData, iwrphase, (long)dsamp, mask, feedbk);); unit->m_feedbk = feedbk; unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; unit->m_decaytime = decaytime; } unit->m_iwrphase = iwrphase; unit->m_numoutput += inNumSamples; if (unit->m_numoutput >= bufSamples) SETCALC(BufCombN_next); } template <bool checked> inline void BufCombN_perform_a(BufCombN* unit, int inNumSamples) { BufFilterX_perform_a<CombN_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)BufCombN_next_a); } void BufCombN_next_a(BufCombN* unit, int inNumSamples) { BufCombN_perform_a<false>(unit, inNumSamples); } void BufCombN_next_a_z(BufCombN* unit, int inNumSamples) { BufCombN_perform_a<true>(unit, inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// void BufCombL_Ctor(BufCombL* unit) { BufFeedbackDelay_Reset(unit); if (INRATE(2) == calc_FullRate) SETCALC(BufCombL_next_a_z); else SETCALC(BufCombL_next_z); ZOUT0(0) = 0.f; } template <bool checked> inline void BufCombL_perform(BufCombL* unit, int inNumSamples) { BufFilterX_perform<CombL_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)BufCombL_next); } void BufCombL_next(BufCombL* unit, int inNumSamples) { BufCombL_perform<false>(unit, inNumSamples); } void BufCombL_next_z(BufCombL* unit, int inNumSamples) { BufCombL_perform<true>(unit, inNumSamples); } template <bool checked> inline void BufCombL_perform_a(BufCombL* unit, int inNumSamples) { BufFilterX_perform_a<CombL_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)BufCombL_next_a); } void BufCombL_next_a(BufCombL* unit, int inNumSamples) { BufCombL_perform_a<false>(unit, inNumSamples); } void BufCombL_next_a_z(BufCombL* unit, int inNumSamples) { BufCombL_perform_a<true>(unit, inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void BufCombC_Ctor(BufCombC* unit) { BufFeedbackDelay_Reset(unit); if (INRATE(2) == calc_FullRate) SETCALC(BufCombC_next_a_z); else SETCALC(BufCombC_next_z); ZOUT0(0) = 0.f; } template <bool checked> inline void BufCombC_perform(BufCombC* unit, int inNumSamples) { BufFilterX_perform<CombC_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)BufCombC_next); } void BufCombC_next(BufCombC* unit, int inNumSamples) { BufCombC_perform<false>(unit, inNumSamples); } void BufCombC_next_z(BufCombC* unit, int inNumSamples) { BufCombC_perform<true>(unit, inNumSamples); } template <bool checked> inline void BufCombC_perform_a(BufCombC* unit, int inNumSamples) { BufFilterX_perform_a<CombC_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)BufCombC_next_a); } void BufCombC_next_a(BufCombC* unit, int inNumSamples) { BufCombC_perform_a<false>(unit, inNumSamples); } void BufCombC_next_a_z(BufCombC* unit, int inNumSamples) { BufCombC_perform_a<true>(unit, inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// void BufAllpassN_Ctor(BufAllpassN* unit) { BufFeedbackDelay_Reset(unit); if (INRATE(2) == calc_FullRate) SETCALC(BufAllpassN_next_a_z); else SETCALC(BufAllpassN_next_z); ZOUT0(0) = 0.f; } void BufAllpassN_next(BufAllpassN* unit, int inNumSamples) { float* out = ZOUT(0); const float* in = ZIN(1); float delaytime = ZIN0(2); float decaytime = ZIN0(3); GET_BUF CHECK_BUF long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; float feedbk = unit->m_feedbk; // postbuf("BufAllpassN_next %g %g %g %g %d %d %d\n", delaytime, decaytime, feedbk, dsamp, mask, iwrphase, zorg); if (delaytime == unit->m_delaytime) { long irdphase = iwrphase - (long)dsamp; float* dlybuf1 = bufData - ZOFF; float* dlyrd = dlybuf1 + (irdphase & mask); float* dlywr = dlybuf1 + (iwrphase & mask); float* dlyN = dlybuf1 + PREVIOUSPOWEROFTWO(bufSamples); if (decaytime == unit->m_decaytime) { long remain = inNumSamples; while (remain) { long rdspace = dlyN - dlyrd; long wrspace = dlyN - dlywr; long nsmps = sc_min(rdspace, wrspace); nsmps = sc_min(remain, nsmps); remain -= nsmps; LOOP1(nsmps, float value = ZXP(dlyrd); float dwr = value * feedbk + ZXP(in); ZXP(dlywr) = dwr; ZXP(out) = value - feedbk * dwr;); if (dlyrd == dlyN) dlyrd = dlybuf1; if (dlywr == dlyN) dlywr = dlybuf1; } } else { float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); long remain = inNumSamples; while (remain) { long rdspace = dlyN - dlyrd; long wrspace = dlyN - dlywr; long nsmps = sc_min(rdspace, wrspace); nsmps = sc_min(remain, nsmps); remain -= nsmps; LOOP1(nsmps, float value = ZXP(dlyrd); float dwr = value * feedbk + ZXP(in); ZXP(dlywr) = dwr; ZXP(out) = value - feedbk * dwr; feedbk += feedbk_slope;); if (dlyrd == dlyN) dlyrd = dlybuf1; if (dlywr == dlyN) dlywr = dlybuf1; } unit->m_feedbk = feedbk; unit->m_decaytime = decaytime; } iwrphase += inNumSamples; } else { float next_dsamp = BufCalcDelay(unit, bufSamples, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); LOOP1(inNumSamples, dsamp += dsamp_slope; feedbk += feedbk_slope; AllpassN_helper<false>::perform(in, out, bufData, iwrphase, (long)dsamp, mask, feedbk);); unit->m_feedbk = feedbk; unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; unit->m_decaytime = decaytime; } unit->m_iwrphase = iwrphase; } void BufAllpassN_next_z(BufAllpassN* unit, int inNumSamples) { float* out = ZOUT(0); const float* in = ZIN(1); float delaytime = ZIN0(2); float decaytime = ZIN0(3); GET_BUF CHECK_BUF long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; float feedbk = unit->m_feedbk; // postbuf("BufAllpassN_next_z %g %g %g %g %d %d %d\n", delaytime, decaytime, feedbk, dsamp, mask, iwrphase, zorg); if (delaytime == unit->m_delaytime) { long irdphase = iwrphase - (long)dsamp; float* dlybuf1 = bufData - ZOFF; float* dlyN = dlybuf1 + PREVIOUSPOWEROFTWO(bufSamples); if (decaytime == unit->m_decaytime) { long remain = inNumSamples; while (remain) { float* dlywr = dlybuf1 + (iwrphase & mask); float* dlyrd = dlybuf1 + (irdphase & mask); long rdspace = dlyN - dlyrd; long wrspace = dlyN - dlywr; long nsmps = sc_min(rdspace, wrspace); nsmps = sc_min(remain, nsmps); remain -= nsmps; if (irdphase < 0) { feedbk = -feedbk; LOOP1(nsmps, float dwr = ZXP(in); ZXP(dlywr) = dwr; ZXP(out) = feedbk * dwr;); feedbk = -feedbk; } else { LOOP1(nsmps, float x1 = ZXP(dlyrd); float dwr = x1 * feedbk + ZXP(in); ZXP(dlywr) = dwr; ZXP(out) = x1 - feedbk * dwr;); } iwrphase += nsmps; irdphase += nsmps; } } else { float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); long remain = inNumSamples; while (remain) { float* dlyrd = dlybuf1 + (irdphase & mask); float* dlywr = dlybuf1 + (iwrphase & mask); long rdspace = dlyN - dlyrd; long wrspace = dlyN - dlywr; long nsmps = sc_min(rdspace, wrspace); nsmps = sc_min(remain, nsmps); remain -= nsmps; if (irdphase < 0) { dlyrd += nsmps; LOOP1(nsmps, float dwr = ZXP(in); ZXP(dlywr) = dwr; ZXP(out) = -feedbk * dwr; feedbk += feedbk_slope;); } else { LOOP1(nsmps, float x1 = ZXP(dlyrd); float dwr = x1 * feedbk + ZXP(in); ZXP(dlywr) = dwr; ZXP(out) = x1 - feedbk * dwr; feedbk += feedbk_slope;); } iwrphase += nsmps; irdphase += nsmps; } unit->m_feedbk = feedbk; unit->m_decaytime = decaytime; } } else { float next_dsamp = BufCalcDelay(unit, bufSamples, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); LOOP1(inNumSamples, dsamp += dsamp_slope; feedbk += feedbk_slope; AllpassN_helper<true>::perform(in, out, bufData, iwrphase, (long)dsamp, mask, feedbk);); unit->m_feedbk = feedbk; unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; unit->m_decaytime = decaytime; } unit->m_iwrphase = iwrphase; unit->m_numoutput += inNumSamples; if (unit->m_numoutput >= bufSamples) SETCALC(BufAllpassN_next); } template <bool checked> inline void BufAllpassN_perform_a(BufAllpassN* unit, int inNumSamples) { BufFilterX_perform_a<AllpassN_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)BufAllpassN_next_a); } void BufAllpassN_next_a(BufAllpassN* unit, int inNumSamples) { BufAllpassN_perform_a<false>(unit, inNumSamples); } void BufAllpassN_next_a_z(BufAllpassN* unit, int inNumSamples) { BufAllpassN_perform_a<true>(unit, inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// void BufAllpassL_Ctor(BufAllpassL* unit) { BufFeedbackDelay_Reset(unit); if (INRATE(2) == calc_FullRate) SETCALC(BufAllpassL_next_a_z); else SETCALC(BufAllpassL_next_z); ZOUT0(0) = 0.f; } template <bool checked> inline void BufAllpassL_perform(BufAllpassL* unit, int inNumSamples) { BufFilterX_perform<AllpassL_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)BufAllpassL_next); } void BufAllpassL_next(BufAllpassL* unit, int inNumSamples) { BufAllpassL_perform<false>(unit, inNumSamples); } void BufAllpassL_next_z(BufAllpassL* unit, int inNumSamples) { BufAllpassL_perform<true>(unit, inNumSamples); } template <bool checked> inline void BufAllpassL_perform_a(BufAllpassL* unit, int inNumSamples) { BufFilterX_perform_a<AllpassL_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)BufAllpassL_next_a); } void BufAllpassL_next_a(BufAllpassL* unit, int inNumSamples) { BufAllpassL_perform_a<false>(unit, inNumSamples); } void BufAllpassL_next_a_z(BufAllpassL* unit, int inNumSamples) { BufAllpassL_perform_a<true>(unit, inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// void BufAllpassC_Ctor(BufAllpassC* unit) { BufFeedbackDelay_Reset(unit); if (INRATE(2) == calc_FullRate) SETCALC(BufAllpassC_next_a_z); else SETCALC(BufAllpassC_next_z); ZOUT0(0) = 0.f; } template <bool checked> inline void BufAllpassC_perform(BufAllpassC* unit, int inNumSamples) { BufFilterX_perform<AllpassC_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)BufAllpassC_next); } void BufAllpassC_next(BufAllpassC* unit, int inNumSamples) { BufAllpassC_perform<false>(unit, inNumSamples); } void BufAllpassC_next_z(BufAllpassC* unit, int inNumSamples) { BufAllpassC_perform<true>(unit, inNumSamples); } template <bool checked> inline void BufAllpassC_perform_a(BufAllpassC* unit, int inNumSamples) { BufFilterX_perform_a<AllpassC_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)BufAllpassC_next_a); } void BufAllpassC_next_a(BufAllpassC* unit, int inNumSamples) { BufAllpassC_perform_a<false>(unit, inNumSamples); } void BufAllpassC_next_a_z(BufAllpassC* unit, int inNumSamples) { BufAllpassC_perform_a<true>(unit, inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// static bool DelayUnit_AllocDelayLine(DelayUnit* unit) { long delaybufsize = (long)ceil(unit->m_maxdelaytime * SAMPLERATE + 1.f); delaybufsize = delaybufsize + BUFLENGTH; delaybufsize = NEXTPOWEROFTWO(delaybufsize); // round up to next power of two unit->m_fdelaylen = unit->m_idelaylen = delaybufsize; if (unit->m_dlybuf) RTFree(unit->mWorld, unit->m_dlybuf); unit->m_dlybuf = (float*)RTAlloc(unit->mWorld, delaybufsize * sizeof(float)); #if 0 // for debugging we may want to fill the buffer with nans std::fill_n(unit->m_dlybuf, delaybufsize, std::numeric_limits<float>::signaling_NaN()); #endif unit->m_mask = delaybufsize - 1; return (unit->m_dlybuf != nullptr); } template <typename Unit> static float CalcDelay(Unit* unit, float delaytime) { float minDelay = Unit::minDelaySamples; float next_dsamp = delaytime * (float)SAMPLERATE; return sc_clip(next_dsamp, minDelay, unit->m_fdelaylen); } template <typename Unit> static bool DelayUnit_Reset(Unit* unit) { unit->m_maxdelaytime = ZIN0(1); unit->m_delaytime = ZIN0(2); unit->m_dlybuf = nullptr; if (!DelayUnit_AllocDelayLine(unit)) return false; unit->m_dsamp = CalcDelay(unit, unit->m_delaytime); unit->m_numoutput = 0; unit->m_iwrphase = 0; return true; } void DelayUnit_Dtor(DelayUnit* unit) { RTFree(unit->mWorld, unit->m_dlybuf); } //////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename Unit> static bool FeedbackDelay_Reset(Unit* unit) { unit->m_decaytime = ZIN0(3); bool allocationSucessful = DelayUnit_Reset(unit); if (!allocationSucessful) return false; unit->m_feedbk = sc_CalcFeedback(unit->m_delaytime, unit->m_decaytime); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////// /* template function to generate delay ugen function, control-rate delay time */ template <typename PerformClass, typename DelayX> inline void DelayX_perform(DelayX* unit, int inNumSamples, UnitCalcFunc resetFunc) { float* out = ZOUT(0); const float* in = ZIN(0); float delaytime = ZIN0(2); float* dlybuf = unit->m_dlybuf; long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; long mask = unit->m_mask; if (delaytime == unit->m_delaytime) { long idsamp = (long)dsamp; float frac = dsamp - idsamp; LOOP1(inNumSamples, PerformClass::perform(in, out, dlybuf, iwrphase, idsamp, frac, mask);); } else { float next_dsamp = CalcDelay(unit, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); LOOP1(inNumSamples, dsamp += dsamp_slope; long idsamp = (long)dsamp; float frac = dsamp - idsamp; PerformClass::perform(in, out, dlybuf, iwrphase, idsamp, frac, mask);); unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; } unit->m_iwrphase = iwrphase; if (PerformClass::checked) { unit->m_numoutput += inNumSamples; if (unit->m_numoutput >= unit->m_idelaylen) unit->mCalcFunc = resetFunc; } } /* template function to generate delay ugen function, audio-rate delay time */ template <typename PerformClass, typename DelayX> inline void DelayX_perform_a(DelayX* unit, int inNumSamples, UnitCalcFunc resetFunc) { float* out = ZOUT(0); const float* in = ZIN(0); float* delaytime = ZIN(2); float* dlybuf = unit->m_dlybuf; long iwrphase = unit->m_iwrphase; long mask = unit->m_mask; LOOP1(inNumSamples, float dsamp = CalcDelay(unit, ZXP(delaytime)); long idsamp = (long)dsamp; float frac = dsamp - idsamp; PerformClass::perform(in, out, dlybuf, iwrphase, idsamp, frac, mask);); unit->m_iwrphase = iwrphase; if (PerformClass::checked) { unit->m_numoutput += inNumSamples; if (unit->m_numoutput >= unit->m_idelaylen) unit->mCalcFunc = resetFunc; } } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Delay_next_0(DelayUnit* unit, int inNumSamples) { float* out = OUT(0); const float* in = IN(0); memcpy(out, in, inNumSamples * sizeof(float)); } void Delay_next_0_nop(DelayUnit* unit, int inNumSamples) {} #ifdef NOVA_SIMD void Delay_next_0_nova(DelayUnit* unit, int inNumSamples) { nova::copyvec_simd(OUT(0), IN(0), inNumSamples); } #endif static bool DelayUnit_init_0(DelayUnit* unit) { if (INRATE(2) == calc_ScalarRate && ZIN0(2) == 0) { if (ZIN(0) == ZOUT(0)) SETCALC(Delay_next_0_nop); #ifdef NOVA_SIMD else if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(Delay_next_0_nova); #endif else SETCALC(Delay_next_0); ZOUT0(0) = ZIN0(0); return true; } else return false; } enum { allocFailed, initializationComplete, initializationIncomplete }; template <typename Delay> static int Delay_Ctor(Delay* unit) { bool allocationSucessful = DelayUnit_Reset(unit); if (!allocationSucessful) return allocFailed; // optimize for a constant delay of zero if (DelayUnit_init_0(unit)) return initializationComplete; return initializationIncomplete; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void DelayN_Ctor(DelayN* unit) { int ctor_status = Delay_Ctor(unit); if (ctor_status == allocFailed) { ClearUnitOnMemFailed; } else if (ctor_status == initializationComplete) { return; } if (INRATE(2) == calc_FullRate) SETCALC(DelayN_next_a_z); else SETCALC(DelayN_next_z); ZOUT0(0) = 0.f; } void DelayN_next(DelayN* unit, int inNumSamples) { float* out = ZOUT(0); const float* in = ZIN(0); float delaytime = ZIN0(2); float* dlybuf = unit->m_dlybuf; long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; long mask = unit->m_mask; // Print("DelayN_next %p %g %g %d %d\n", unit, delaytime, dsamp, mask, iwrphase); if (delaytime == unit->m_delaytime) { DelayN_delay_loop<false>(out, in, iwrphase, dsamp, mask, dlybuf, inNumSamples, unit->m_idelaylen); } else { float next_dsamp = CalcDelay(unit, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); LOOP1(inNumSamples, dsamp += dsamp_slope; DelayN_helper<false>::perform(in, out, dlybuf, iwrphase, (long)dsamp, mask);); unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; } unit->m_iwrphase = iwrphase; } void DelayN_next_z(DelayN* unit, int inNumSamples) { float* out = ZOUT(0); const float* in = ZIN(0); float delaytime = ZIN0(2); float* dlybuf = unit->m_dlybuf; long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; long mask = unit->m_mask; if (delaytime == unit->m_delaytime) { DelayN_delay_loop<true>(out, in, iwrphase, dsamp, mask, dlybuf, inNumSamples, unit->m_idelaylen); } else { float next_dsamp = CalcDelay(unit, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); LOOP1(inNumSamples, dsamp += dsamp_slope; DelayN_helper<true>::perform(in, out, dlybuf, iwrphase, (long)dsamp, mask);); unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; } unit->m_iwrphase = iwrphase; unit->m_numoutput += inNumSamples; if (unit->m_numoutput >= unit->m_idelaylen) SETCALC(DelayN_next); } template <bool checked> inline void DelayN_perform_a(DelayN* unit, int inNumSamples) { DelayX_perform_a<DelayN_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)DelayN_next_a); } void DelayN_next_a(DelayN* unit, int inNumSamples) { DelayN_perform_a<false>(unit, inNumSamples); } void DelayN_next_a_z(DelayN* unit, int inNumSamples) { DelayN_perform_a<true>(unit, inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void DelayL_Ctor(DelayL* unit) { int ctor_status = Delay_Ctor(unit); if (ctor_status == allocFailed) { ClearUnitOnMemFailed; } else if (ctor_status == initializationComplete) { return; } if (INRATE(2) == calc_FullRate) SETCALC(DelayL_next_a_z); else SETCALC(DelayL_next_z); ZOUT0(0) = 0.f; } template <bool checked> inline void DelayL_perform(DelayL* unit, int inNumSamples) { DelayX_perform<DelayL_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)DelayL_next); } void DelayL_next(DelayL* unit, int inNumSamples) { DelayL_perform<false>(unit, inNumSamples); } void DelayL_next_z(DelayL* unit, int inNumSamples) { DelayL_perform<true>(unit, inNumSamples); } template <bool checked> inline void DelayL_perform_a(DelayL* unit, int inNumSamples) { DelayX_perform_a<DelayL_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)DelayL_next_a); } void DelayL_next_a(DelayL* unit, int inNumSamples) { DelayL_perform_a<false>(unit, inNumSamples); } void DelayL_next_a_z(DelayL* unit, int inNumSamples) { DelayL_perform_a<true>(unit, inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void DelayC_Ctor(DelayC* unit) { int ctor_status = Delay_Ctor(unit); if (ctor_status == allocFailed) { ClearUnitOnMemFailed; } else if (ctor_status == initializationComplete) { return; } if (INRATE(2) == calc_FullRate) SETCALC(DelayC_next_a_z); else SETCALC(DelayC_next_z); ZOUT0(0) = 0.f; } template <bool checked> inline void DelayC_perform(DelayC* unit, int inNumSamples) { DelayX_perform<DelayC_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)DelayC_next); } void DelayC_next(DelayC* unit, int inNumSamples) { DelayC_perform<false>(unit, inNumSamples); } void DelayC_next_z(DelayC* unit, int inNumSamples) { DelayC_perform<true>(unit, inNumSamples); } template <bool checked> inline void DelayC_perform_a(DelayC* unit, int inNumSamples) { DelayX_perform_a<DelayC_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)DelayC_next_a); } void DelayC_next_a(DelayC* unit, int inNumSamples) { DelayC_perform_a<false>(unit, inNumSamples); } void DelayC_next_a_z(DelayC* unit, int inNumSamples) { DelayC_perform_a<true>(unit, inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename PerformClass, typename BufCombX> inline void FilterX_perform(BufCombX* unit, int inNumSamples, UnitCalcFunc resetFunc) { float* out = ZOUT(0); const float* in = ZIN(0); float delaytime = ZIN0(2); float decaytime = ZIN0(3); float* dlybuf = unit->m_dlybuf; long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; float feedbk = unit->m_feedbk; long mask = unit->m_mask; if (delaytime == unit->m_delaytime && decaytime == unit->m_decaytime) { long idsamp = (long)dsamp; float frac = dsamp - idsamp; LOOP1(inNumSamples, PerformClass::perform(in, out, dlybuf, iwrphase, idsamp, frac, mask, feedbk);); } else { float next_dsamp = CalcDelay(unit, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); LOOP1(inNumSamples, dsamp += dsamp_slope; feedbk += feedbk_slope; long idsamp = (long)dsamp; float frac = dsamp - idsamp; PerformClass::perform(in, out, dlybuf, iwrphase, idsamp, frac, mask, feedbk);); unit->m_feedbk = feedbk; unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; unit->m_decaytime = decaytime; } unit->m_iwrphase = iwrphase; if (PerformClass::checked) { unit->m_numoutput += inNumSamples; if (unit->m_numoutput >= unit->m_idelaylen) unit->mCalcFunc = resetFunc; } } template <typename PerformClass, typename CombX> inline void FilterX_perform_a(CombX* unit, int inNumSamples, UnitCalcFunc resetFunc) { float* out = ZOUT(0); const float* in = ZIN(0); float* delaytime = ZIN(2); float decaytime = ZIN0(3); float* dlybuf = unit->m_dlybuf; long iwrphase = unit->m_iwrphase; long mask = unit->m_mask; LOOP1(inNumSamples, float del = ZXP(delaytime); float dsamp = CalcDelay(unit, del); float feedbk = sc_CalcFeedback(del, decaytime); long idsamp = (long)dsamp; float frac = dsamp - idsamp; PerformClass::perform(in, out, dlybuf, iwrphase, idsamp, frac, mask, feedbk);); unit->m_iwrphase = iwrphase; if (PerformClass::checked) { unit->m_numoutput += inNumSamples; if (unit->m_numoutput >= unit->m_idelaylen) unit->mCalcFunc = resetFunc; } } //////////////////////////////////////////////////////////////////////////////////////////////////////// void CombN_Ctor(CombN* unit) { bool allocationSucessful = FeedbackDelay_Reset(unit); ClearUnitIfMemFailed(allocationSucessful); if (INRATE(2) == calc_FullRate) SETCALC(CombN_next_a_z); else SETCALC(CombN_next_z); ZOUT0(0) = 0.f; } void CombN_next(CombN* unit, int inNumSamples) { float* out = ZOUT(0); const float* in = ZIN(0); float delaytime = ZIN0(2); float decaytime = ZIN0(3); float* dlybuf = unit->m_dlybuf; long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; float feedbk = unit->m_feedbk; long mask = unit->m_mask; // postbuf("CombN_next %g %g %g %g %d %d %d\n", delaytime, decaytime, feedbk, dsamp, mask, iwrphase, zorg); if (delaytime == unit->m_delaytime) { long irdphase = iwrphase - (long)dsamp; float* dlybuf1 = dlybuf - ZOFF; float* dlyrd = dlybuf1 + (irdphase & mask); float* dlywr = dlybuf1 + (iwrphase & mask); float* dlyN = dlybuf1 + unit->m_idelaylen; if (decaytime == unit->m_decaytime) { long remain = inNumSamples; while (remain) { long rdspace = dlyN - dlyrd; long wrspace = dlyN - dlywr; long nsmps = sc_min(rdspace, wrspace); nsmps = sc_min(remain, nsmps); remain -= nsmps; LOOP(nsmps, float value = ZXP(dlyrd); ZXP(dlywr) = value * feedbk + ZXP(in); ZXP(out) = value;); if (dlyrd == dlyN) dlyrd = dlybuf1; if (dlywr == dlyN) dlywr = dlybuf1; } } else { float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); long remain = inNumSamples; while (remain) { long rdspace = dlyN - dlyrd; long wrspace = dlyN - dlywr; long nsmps = sc_min(rdspace, wrspace); nsmps = sc_min(remain, nsmps); remain -= nsmps; LOOP(nsmps, float value = ZXP(dlyrd); ZXP(dlywr) = value * feedbk + ZXP(in); ZXP(out) = value; feedbk += feedbk_slope;); if (dlyrd == dlyN) dlyrd = dlybuf1; if (dlywr == dlyN) dlywr = dlybuf1; } unit->m_feedbk = feedbk; unit->m_decaytime = decaytime; } iwrphase += inNumSamples; } else { float next_dsamp = CalcDelay(unit, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); LOOP1(inNumSamples, dsamp += dsamp_slope; feedbk += feedbk_slope; CombN_helper<false>::perform(in, out, dlybuf, iwrphase, (long)dsamp, mask, feedbk);); unit->m_feedbk = feedbk; unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; unit->m_decaytime = decaytime; } unit->m_iwrphase = iwrphase; } void CombN_next_z(CombN* unit, int inNumSamples) { float* out = ZOUT(0); const float* in = ZIN(0); float delaytime = ZIN0(2); float decaytime = ZIN0(3); float* dlybuf = unit->m_dlybuf; long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; float feedbk = unit->m_feedbk; long mask = unit->m_mask; // postbuf("CombN_next_z %g %g %g %g %d %d %d\n", delaytime, decaytime, feedbk, dsamp, mask, iwrphase, zorg); if (delaytime == unit->m_delaytime) { long irdphase = iwrphase - (long)dsamp; float* dlybuf1 = dlybuf - ZOFF; float* dlyN = dlybuf1 + unit->m_idelaylen; if (decaytime == unit->m_decaytime) { long remain = inNumSamples; while (remain) { float* dlywr = dlybuf1 + (iwrphase & mask); float* dlyrd = dlybuf1 + (irdphase & mask); long rdspace = dlyN - dlyrd; long wrspace = dlyN - dlywr; long nsmps = sc_min(rdspace, wrspace); nsmps = sc_min(remain, nsmps); remain -= nsmps; if (irdphase < 0) { LOOP(nsmps, ZXP(dlywr) = ZXP(in); ZXP(out) = 0.f;); } else { LOOP(nsmps, float value = ZXP(dlyrd); ZXP(dlywr) = value * feedbk + ZXP(in); ZXP(out) = value;); } iwrphase += nsmps; irdphase += nsmps; } } else { float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); long remain = inNumSamples; while (remain) { float* dlyrd = dlybuf1 + (irdphase & mask); float* dlywr = dlybuf1 + (iwrphase & mask); long rdspace = dlyN - dlyrd; long wrspace = dlyN - dlywr; long nsmps = sc_min(rdspace, wrspace); nsmps = sc_min(remain, nsmps); remain -= nsmps; if (irdphase < 0) { feedbk += nsmps * feedbk_slope; dlyrd += nsmps; LOOP(nsmps, ZXP(dlywr) = ZXP(in); ZXP(out) = 0.f;); } else { LOOP(nsmps, float value = ZXP(dlyrd); ZXP(dlywr) = value * feedbk + ZXP(in); ZXP(out) = value; feedbk += feedbk_slope;); } iwrphase += nsmps; irdphase += nsmps; } unit->m_feedbk = feedbk; unit->m_decaytime = decaytime; } } else { float next_dsamp = CalcDelay(unit, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); LOOP1(inNumSamples, dsamp += dsamp_slope; feedbk += feedbk_slope; CombN_helper<true>::perform(in, out, dlybuf, iwrphase, (long)dsamp, mask, feedbk);); unit->m_feedbk = feedbk; unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; unit->m_decaytime = decaytime; } unit->m_iwrphase = iwrphase; unit->m_numoutput += inNumSamples; if (unit->m_numoutput >= unit->m_idelaylen) SETCALC(CombN_next); } template <bool checked> inline void CombN_perform_a(CombN* unit, int inNumSamples) { FilterX_perform_a<CombN_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)CombN_next_a); } void CombN_next_a(CombN* unit, int inNumSamples) { CombN_perform_a<false>(unit, inNumSamples); } void CombN_next_a_z(CombN* unit, int inNumSamples) { CombN_perform_a<true>(unit, inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// void CombL_Ctor(CombL* unit) { bool allocationSucessful = FeedbackDelay_Reset(unit); ClearUnitIfMemFailed(allocationSucessful); if (INRATE(2) == calc_FullRate) SETCALC(CombL_next_a_z); else SETCALC(CombL_next_z); ZOUT0(0) = 0.f; } template <bool checked> inline void CombL_perform(CombL* unit, int inNumSamples) { FilterX_perform<CombL_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)CombL_next); } void CombL_next(CombL* unit, int inNumSamples) { CombL_perform<false>(unit, inNumSamples); } void CombL_next_z(CombL* unit, int inNumSamples) { CombL_perform<true>(unit, inNumSamples); } template <bool checked> inline void CombL_perform_a(CombL* unit, int inNumSamples) { FilterX_perform_a<CombL_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)CombL_next_a); } void CombL_next_a(CombL* unit, int inNumSamples) { CombL_perform_a<false>(unit, inNumSamples); } void CombL_next_a_z(CombL* unit, int inNumSamples) { CombL_perform_a<true>(unit, inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void CombC_Ctor(CombC* unit) { bool allocationSucessful = FeedbackDelay_Reset(unit); ClearUnitIfMemFailed(allocationSucessful); if (INRATE(2) == calc_FullRate) SETCALC(CombC_next_a_z); else SETCALC(CombC_next_z); ZOUT0(0) = 0.f; } template <bool checked> inline void CombC_perform(CombC* unit, int inNumSamples) { FilterX_perform<CombC_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)CombC_next); } void CombC_next(CombC* unit, int inNumSamples) { CombC_perform<false>(unit, inNumSamples); } void CombC_next_z(CombC* unit, int inNumSamples) { CombC_perform<true>(unit, inNumSamples); } template <bool checked> inline void CombC_perform_a(CombC* unit, int inNumSamples) { FilterX_perform_a<CombC_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)CombC_next_a); } void CombC_next_a(CombC* unit, int inNumSamples) { CombC_perform_a<false>(unit, inNumSamples); } void CombC_next_a_z(CombC* unit, int inNumSamples) { CombC_perform_a<true>(unit, inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// void AllpassN_Ctor(AllpassN* unit) { bool allocationSucessful = FeedbackDelay_Reset(unit); ClearUnitIfMemFailed(allocationSucessful); if (INRATE(2) == calc_FullRate) SETCALC(AllpassN_next_a_z); else SETCALC(AllpassN_next_z); ZOUT0(0) = 0.f; } void AllpassN_next(AllpassN* unit, int inNumSamples) { float* out = ZOUT(0); const float* in = ZIN(0); float delaytime = ZIN0(2); float decaytime = ZIN0(3); float* dlybuf = unit->m_dlybuf; long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; float feedbk = unit->m_feedbk; long mask = unit->m_mask; // postbuf("AllpassN_next %g %g %g %g %d %d %d\n", delaytime, decaytime, feedbk, dsamp, mask, iwrphase, zorg); if (delaytime == unit->m_delaytime) { long irdphase = iwrphase - (long)dsamp; float* dlybuf1 = dlybuf - ZOFF; float* dlyrd = dlybuf1 + (irdphase & mask); float* dlywr = dlybuf1 + (iwrphase & mask); float* dlyN = dlybuf1 + unit->m_idelaylen; if (decaytime == unit->m_decaytime) { long remain = inNumSamples; while (remain) { long rdspace = dlyN - dlyrd; long wrspace = dlyN - dlywr; long nsmps = sc_min(rdspace, wrspace); nsmps = sc_min(remain, nsmps); remain -= nsmps; LOOP(nsmps, float value = ZXP(dlyrd); float dwr = value * feedbk + ZXP(in); ZXP(dlywr) = dwr; ZXP(out) = value - feedbk * dwr;); if (dlyrd == dlyN) dlyrd = dlybuf1; if (dlywr == dlyN) dlywr = dlybuf1; } } else { float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); long remain = inNumSamples; while (remain) { long rdspace = dlyN - dlyrd; long wrspace = dlyN - dlywr; long nsmps = sc_min(rdspace, wrspace); nsmps = sc_min(remain, nsmps); remain -= nsmps; LOOP(nsmps, float value = ZXP(dlyrd); float dwr = value * feedbk + ZXP(in); ZXP(dlywr) = dwr; ZXP(out) = value - feedbk * dwr; feedbk += feedbk_slope;); if (dlyrd == dlyN) dlyrd = dlybuf1; if (dlywr == dlyN) dlywr = dlybuf1; } unit->m_feedbk = feedbk; unit->m_decaytime = decaytime; } iwrphase += inNumSamples; } else { float next_dsamp = CalcDelay(unit, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); LOOP1(inNumSamples, dsamp += dsamp_slope; feedbk += feedbk_slope; AllpassN_helper<false>::perform(in, out, dlybuf, iwrphase, (long)dsamp, mask, feedbk);); unit->m_feedbk = feedbk; unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; unit->m_decaytime = decaytime; } unit->m_iwrphase = iwrphase; } void AllpassN_next_z(AllpassN* unit, int inNumSamples) { float* out = ZOUT(0); const float* in = ZIN(0); float delaytime = ZIN0(2); float decaytime = ZIN0(3); float* dlybuf = unit->m_dlybuf; long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; float feedbk = unit->m_feedbk; long mask = unit->m_mask; // postbuf("AllpassN_next_z %g %g %g %g %d %d %d\n", delaytime, decaytime, feedbk, dsamp, mask, iwrphase, zorg); if (delaytime == unit->m_delaytime) { long irdphase = iwrphase - (long)dsamp; float* dlybuf1 = dlybuf - ZOFF; float* dlyN = dlybuf1 + unit->m_idelaylen; if (decaytime == unit->m_decaytime) { long remain = inNumSamples; while (remain) { float* dlywr = dlybuf1 + (iwrphase & mask); float* dlyrd = dlybuf1 + (irdphase & mask); long rdspace = dlyN - dlyrd; long wrspace = dlyN - dlywr; long nsmps = sc_min(rdspace, wrspace); nsmps = sc_min(remain, nsmps); remain -= nsmps; if (irdphase < 0) { feedbk = -feedbk; LOOP(nsmps, float dwr = ZXP(in); ZXP(dlywr) = dwr; ZXP(out) = feedbk * dwr;); feedbk = -feedbk; } else { LOOP(nsmps, float x1 = ZXP(dlyrd); float dwr = x1 * feedbk + ZXP(in); ZXP(dlywr) = dwr; ZXP(out) = x1 - feedbk * dwr;); } iwrphase += nsmps; irdphase += nsmps; } } else { float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); long remain = inNumSamples; while (remain) { float* dlyrd = dlybuf1 + (irdphase & mask); float* dlywr = dlybuf1 + (iwrphase & mask); long rdspace = dlyN - dlyrd; long wrspace = dlyN - dlywr; long nsmps = sc_min(rdspace, wrspace); nsmps = sc_min(remain, nsmps); remain -= nsmps; if (irdphase < 0) { dlyrd += nsmps; LOOP(nsmps, float dwr = ZXP(in); ZXP(dlywr) = dwr; ZXP(out) = -feedbk * dwr; feedbk += feedbk_slope;); } else { LOOP(nsmps, float x1 = ZXP(dlyrd); float dwr = x1 * feedbk + ZXP(in); ZXP(dlywr) = dwr; ZXP(out) = x1 - feedbk * dwr; feedbk += feedbk_slope;); } iwrphase += nsmps; irdphase += nsmps; } unit->m_feedbk = feedbk; unit->m_decaytime = decaytime; } } else { float next_dsamp = CalcDelay(unit, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); LOOP1(inNumSamples, dsamp += dsamp_slope; feedbk += feedbk_slope; AllpassN_helper<true>::perform(in, out, dlybuf, iwrphase, (long)dsamp, mask, feedbk);); unit->m_feedbk = feedbk; unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; unit->m_decaytime = decaytime; } unit->m_iwrphase = iwrphase; unit->m_numoutput += inNumSamples; if (unit->m_numoutput >= unit->m_idelaylen) SETCALC(AllpassN_next); } template <bool checked> inline void AllpassN_perform_a(AllpassN* unit, int inNumSamples) { FilterX_perform_a<AllpassN_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)AllpassN_next_a); } void AllpassN_next_a(AllpassN* unit, int inNumSamples) { AllpassN_perform_a<false>(unit, inNumSamples); } void AllpassN_next_a_z(AllpassN* unit, int inNumSamples) { AllpassN_perform_a<true>(unit, inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// void AllpassL_Ctor(AllpassL* unit) { bool allocationSucessful = FeedbackDelay_Reset(unit); ClearUnitIfMemFailed(allocationSucessful); if (INRATE(2) == calc_FullRate) SETCALC(AllpassL_next_a_z); else SETCALC(AllpassL_next_z); ZOUT0(0) = 0.f; } template <bool checked> inline void AllpassL_perform(AllpassL* unit, int inNumSamples) { FilterX_perform<AllpassL_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)AllpassL_next); } void AllpassL_next(AllpassL* unit, int inNumSamples) { AllpassL_perform<false>(unit, inNumSamples); } void AllpassL_next_z(AllpassL* unit, int inNumSamples) { AllpassL_perform<true>(unit, inNumSamples); } template <bool checked> inline void AllpassL_perform_a(AllpassL* unit, int inNumSamples) { FilterX_perform_a<AllpassL_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)AllpassL_next_a); } void AllpassL_next_a(AllpassL* unit, int inNumSamples) { AllpassL_perform_a<false>(unit, inNumSamples); } void AllpassL_next_a_z(AllpassL* unit, int inNumSamples) { AllpassL_perform_a<true>(unit, inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// void AllpassC_Ctor(AllpassC* unit) { bool allocationSucessful = FeedbackDelay_Reset(unit); ClearUnitIfMemFailed(allocationSucessful); if (INRATE(2) == calc_FullRate) SETCALC(AllpassC_next_a_z); else SETCALC(AllpassC_next_z); ZOUT0(0) = 0.f; } template <bool checked> inline void AllpassC_perform(AllpassC* unit, int inNumSamples) { FilterX_perform<AllpassC_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)AllpassC_next); } void AllpassC_next(AllpassC* unit, int inNumSamples) { AllpassC_perform<false>(unit, inNumSamples); } void AllpassC_next_z(AllpassC* unit, int inNumSamples) { AllpassC_perform<true>(unit, inNumSamples); } template <bool checked> inline void AllpassC_perform_a(AllpassC* unit, int inNumSamples) { FilterX_perform_a<AllpassC_helper<checked>>(unit, inNumSamples, (UnitCalcFunc)AllpassC_next_a); } void AllpassC_next_a(AllpassC* unit, int inNumSamples) { AllpassC_perform_a<false>(unit, inNumSamples); } void AllpassC_next_a_z(AllpassC* unit, int inNumSamples) { AllpassC_perform_a<true>(unit, inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// inline double sc_loop1(int32 in, int32 lo, int32 hi) { // avoid the divide if possible if (in >= hi) { in -= hi; if (in < hi) return in; } else if (in < lo) { in += hi; if (in >= lo) return in; } else return in; int32 range = hi - lo; return lo + range * (in - lo) / range; } #if NOTYET void SimpleLoopBuf_next_kk(SimpleLoopBuf* unit, int inNumSamples) { float trig = ZIN0(1); double loopstart = (double)ZIN0(2); double loopend = (double)ZIN0(3); GET_BUF int numOutputs = unit->mNumOutputs; if (!checkBuffer(unit, bufData, bufChannels, numOutputs, inNumSamples)) return; loopend = sc_max(loopend, bufFrames); int32 phase = unit->m_phase; if (trig > 0.f && unit->m_prevtrig <= 0.f) { unit->mDone = false; phase = (int32)ZIN0(2); } unit->m_prevtrig = trig; for (int i = 0; i < inNumSamples; ++i) { phase = sc_loop1(phase, loopstart, loopend); int32 iphase = (int32)phase; float* table1 = bufData + iphase * bufChannels; int32 index = 0; for (uint32 channel = 0; channel < bufChannels; ++channel) { OUT(channel[i]) = table1[index++]; } phase++; } unit->m_phase = phase; } void SimpleLoopBuf_Ctor(SimpleLoopBuf* unit) { SETCALC(SimpleLoopBuf_next_kk); unit->m_fbufnum = -1e9f; unit->m_prevtrig = 0.; unit->m_phase = ZIN0(2); ClearUnitOutputs(unit, 1); } #endif //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// #define GET_SCOPEBUF \ float fbufnum = ZIN0(0); \ if (fbufnum != unit->m_fbufnum) { \ World* world = unit->mWorld; \ if (!world->mNumSndBufs) { \ ClearUnitOutputs(unit, inNumSamples); \ return; \ } \ uint32 bufnum = (int)fbufnum; \ if (bufnum >= world->mNumSndBufs) \ bufnum = 0; \ unit->m_fbufnum = fbufnum; \ unit->m_buf = world->mSndBufs + bufnum; \ unit->m_bufupdates = world->mSndBufUpdates + bufnum; \ } \ SndBuf* buf = unit->m_buf; \ LOCK_SNDBUF(buf); \ SndBufUpdates* bufupdates = unit->m_bufupdates; \ float* bufData __attribute__((__unused__)) = buf->data; \ uint32 bufChannels __attribute__((__unused__)) = buf->channels; \ uint32 bufFrames __attribute__((__unused__)) = buf->frames; void ScopeOut_next(ScopeOut* unit, int inNumSamples) { GET_SCOPEBUF if (!bufData) { unit->m_framepos = 0; return; } SETUP_IN(1) uint32 framepos = unit->m_framepos; if (framepos >= bufFrames) { unit->m_framepos = 0; } if (bufupdates->reads != bufupdates->writes) { unit->m_framepos += inNumSamples; return; } bufData += framepos * bufChannels; int remain = (bufFrames - framepos), wrap = 0; if (inNumSamples <= remain) { remain = inNumSamples; wrap = 0; } else wrap = inNumSamples - remain; if (bufChannels > 2) { for (int j = 0; j < remain; ++j) { for (uint32 i = 0; i < bufChannels; ++i) { *bufData++ = *++(in[i]); } } bufData = buf->data; for (int j = 0; j < wrap; ++j) { for (uint32 i = 0; i < bufChannels; ++i) { *bufData++ = *++(in[i]); } } } else if (bufChannels == 2) { float* in0 = in[0]; float* in1 = in[1]; for (int j = 0; j < remain; ++j) { *bufData++ = *++in0; *bufData++ = *++in1; } bufData = buf->data; for (int j = 0; j < wrap; ++j) { *bufData++ = *++in0; *bufData++ = *++in1; } } else { float* in0 = in[0]; for (int j = 0; j < remain; ++j) { *bufData++ = *++in0; } bufData = buf->data; for (int j = 0; j < wrap; ++j) { *bufData++ = *++in0; } } unit->m_framepos += inNumSamples; unit->m_framecount += inNumSamples; if (unit->m_framecount >= bufFrames) { bufupdates->writes++; unit->m_framecount = 0; } } void ScopeOut_Ctor(ScopeOut* unit) { unit->m_fbufnum = -1e9; unit->m_framepos = 0; unit->m_framecount = 0; unit->mIn = nullptr; SETCALC(ScopeOut_next); } void ScopeOut_Dtor(ScopeOut* unit) { TAKEDOWN_IN } //////////////////////////////////////////////////////////////////////////////////////////////////////// struct ScopeOut2 : public Unit { ScopeBufferHnd m_buffer; float** m_inBuffers; int m_maxPeriod; uint32 m_phase; }; void ScopeOut2_next(ScopeOut2* unit, int inNumSamples) { if (!unit->m_buffer) return; const int inputOffset = 3; int numChannels = unit->mNumInputs - inputOffset; uint32 period = (uint32)ZIN0(2); uint32 framepos = unit->m_phase; period = std::max((uint32)inNumSamples, std::min(unit->m_buffer.maxFrames, period)); if (framepos >= period) framepos = 0; int remain = period - framepos, wrap = 0; if (inNumSamples <= remain) remain = inNumSamples; else wrap = inNumSamples - remain; for (int i = 0; i != numChannels; ++i) { float* inBuf = unit->m_buffer.channel_data(i); const float* in = IN(inputOffset + i); memcpy(inBuf + framepos, in, remain * sizeof(float)); } if (framepos + inNumSamples >= period) (*ft->fPushScopeBuffer)(unit->mWorld, unit->m_buffer, period); if (wrap) { for (int i = 0; i != numChannels; ++i) { float* inBuf = unit->m_buffer.channel_data(i); const float* in = IN(inputOffset + i); memcpy(inBuf, in + remain, wrap * sizeof(float)); } } framepos += inNumSamples; if (framepos >= period) framepos = wrap; unit->m_phase = framepos; } void ScopeOut2_Ctor(ScopeOut2* unit) { uint32 numChannels = unit->mNumInputs - 3; uint32 scopeNum = (uint32)ZIN0(0); uint32 maxFrames = (uint32)ZIN0(1); bool ok = (*ft->fGetScopeBuffer)(unit->mWorld, scopeNum, numChannels, maxFrames, unit->m_buffer); if (!ok) { if (unit->mWorld->mVerbosity > -1 && !unit->mDone) Print("ScopeOut2: Requested scope buffer unavailable! (index: %d, channels: %d, size: %d)\n", scopeNum, numChannels, maxFrames); } else { unit->m_phase = 0; } SETCALC(ScopeOut2_next); } void ScopeOut2_Dtor(ScopeOut2* unit) { if (unit->m_buffer) (*ft->fReleaseScopeBuffer)(unit->mWorld, unit->m_buffer); } //////////////////////////////////////////////////////////////////////////////////////////////////////// struct PitchShift : public Unit { float* dlybuf; float dsamp1, dsamp1_slope, ramp1, ramp1_slope; float dsamp2, dsamp2_slope, ramp2, ramp2_slope; float dsamp3, dsamp3_slope, ramp3, ramp3_slope; float dsamp4, dsamp4_slope, ramp4, ramp4_slope; float fdelaylen, slope; long iwrphase, idelaylen, mask; long counter, stage, numoutput, framesize; }; void PitchShift_next(PitchShift* unit, int inNumSamples); void PitchShift_next(PitchShift* unit, int inNumSamples) { float *out, *in, *dlybuf; float disppchratio, pchratio, pchratio1, value; float dsamp1, dsamp1_slope, ramp1, ramp1_slope; float dsamp2, dsamp2_slope, ramp2, ramp2_slope; float dsamp3, dsamp3_slope, ramp3, ramp3_slope; float dsamp4, dsamp4_slope, ramp4, ramp4_slope; float fdelaylen, d1, d2, frac, slope, samp_slope, startpos, winsize, pchdisp, timedisp; long remain, nsmps, idelaylen, irdphase, irdphaseb, iwrphase, mask, idsamp; long counter, stage, framesize; RGET out = ZOUT(0); in = ZIN(0); pchratio = ZIN0(2); winsize = ZIN0(1); pchdisp = ZIN0(3); timedisp = ZIN0(4); timedisp = sc_clip(timedisp, 0.f, winsize) * SAMPLERATE; dlybuf = unit->dlybuf; fdelaylen = unit->fdelaylen; idelaylen = unit->idelaylen; iwrphase = unit->iwrphase; counter = unit->counter; stage = unit->stage; mask = unit->mask; framesize = unit->framesize; dsamp1 = unit->dsamp1; dsamp2 = unit->dsamp2; dsamp3 = unit->dsamp3; dsamp4 = unit->dsamp4; dsamp1_slope = unit->dsamp1_slope; dsamp2_slope = unit->dsamp2_slope; dsamp3_slope = unit->dsamp3_slope; dsamp4_slope = unit->dsamp4_slope; ramp1 = unit->ramp1; ramp2 = unit->ramp2; ramp3 = unit->ramp3; ramp4 = unit->ramp4; ramp1_slope = unit->ramp1_slope; ramp2_slope = unit->ramp2_slope; ramp3_slope = unit->ramp3_slope; ramp4_slope = unit->ramp4_slope; slope = unit->slope; remain = inNumSamples; while (remain) { if (counter <= 0) { counter = framesize >> 2; unit->stage = stage = (stage + 1) & 3; disppchratio = pchratio; if (pchdisp != 0.f) { disppchratio += (pchdisp * frand2(s1, s2, s3)); } disppchratio = sc_clip(disppchratio, 0.f, 4.f); pchratio1 = disppchratio - 1.f; samp_slope = -pchratio1; startpos = pchratio1 < 0.f ? 2.f : framesize * pchratio1 + 2.f; startpos += (timedisp * frand(s1, s2, s3)); switch (stage) { case 0: unit->dsamp1_slope = dsamp1_slope = samp_slope; dsamp1 = startpos; ramp1 = 0.0; unit->ramp1_slope = ramp1_slope = slope; unit->ramp3_slope = ramp3_slope = -slope; break; case 1: unit->dsamp2_slope = dsamp2_slope = samp_slope; dsamp2 = startpos; ramp2 = 0.0; unit->ramp2_slope = ramp2_slope = slope; unit->ramp4_slope = ramp4_slope = -slope; break; case 2: unit->dsamp3_slope = dsamp3_slope = samp_slope; dsamp3 = startpos; ramp3 = 0.0; unit->ramp3_slope = ramp3_slope = slope; unit->ramp1_slope = ramp1_slope = -slope; break; case 3: unit->dsamp4_slope = dsamp4_slope = samp_slope; dsamp4 = startpos; ramp4 = 0.0; unit->ramp2_slope = ramp2_slope = -slope; unit->ramp4_slope = ramp4_slope = slope; break; } /*Print("%d %d %g %g %g %g %g %g %g %g %g %g %g %g\n", counter, stage, dsamp1_slope, dsamp2_slope, dsamp3_slope, dsamp4_slope, dsamp1, dsamp2, dsamp3, dsamp4, ramp1, ramp2, ramp3, ramp4);*/ } nsmps = sc_min(remain, counter); remain -= nsmps; counter -= nsmps; LOOP(nsmps, iwrphase = (iwrphase + 1) & mask; dsamp1 += dsamp1_slope; idsamp = (long)dsamp1; frac = dsamp1 - idsamp; irdphase = (iwrphase - idsamp) & mask; irdphaseb = (irdphase - 1) & mask; d1 = dlybuf[irdphase]; d2 = dlybuf[irdphaseb]; value = (d1 + frac * (d2 - d1)) * ramp1; ramp1 += ramp1_slope; dsamp2 += dsamp2_slope; idsamp = (long)dsamp2; frac = dsamp2 - idsamp; irdphase = (iwrphase - idsamp) & mask; irdphaseb = (irdphase - 1) & mask; d1 = dlybuf[irdphase]; d2 = dlybuf[irdphaseb]; value += (d1 + frac * (d2 - d1)) * ramp2; ramp2 += ramp2_slope; dsamp3 += dsamp3_slope; idsamp = (long)dsamp3; frac = dsamp3 - idsamp; irdphase = (iwrphase - idsamp) & mask; irdphaseb = (irdphase - 1) & mask; d1 = dlybuf[irdphase]; d2 = dlybuf[irdphaseb]; value += (d1 + frac * (d2 - d1)) * ramp3; ramp3 += ramp3_slope; dsamp4 += dsamp4_slope; idsamp = (long)dsamp4; frac = dsamp4 - idsamp; irdphase = (iwrphase - idsamp) & mask; irdphaseb = (irdphase - 1) & mask; d1 = dlybuf[irdphase]; d2 = dlybuf[irdphaseb]; value += (d1 + frac * (d2 - d1)) * ramp4; ramp4 += ramp4_slope; dlybuf[iwrphase] = ZXP(in); ZXP(out) = value *= 0.5;); } unit->counter = counter; unit->dsamp1 = dsamp1; unit->dsamp2 = dsamp2; unit->dsamp3 = dsamp3; unit->dsamp4 = dsamp4; unit->ramp1 = ramp1; unit->ramp2 = ramp2; unit->ramp3 = ramp3; unit->ramp4 = ramp4; unit->iwrphase = iwrphase; RPUT } void PitchShift_next_z(PitchShift* unit, int inNumSamples); void PitchShift_next_z(PitchShift* unit, int inNumSamples) { float *out, *in, *dlybuf; float disppchratio, pchratio, pchratio1, value; float dsamp1, dsamp1_slope, ramp1, ramp1_slope; float dsamp2, dsamp2_slope, ramp2, ramp2_slope; float dsamp3, dsamp3_slope, ramp3, ramp3_slope; float dsamp4, dsamp4_slope, ramp4, ramp4_slope; float fdelaylen, d1, d2, frac, slope, samp_slope, startpos, winsize, pchdisp, timedisp; long remain, nsmps, idelaylen, irdphase, irdphaseb, iwrphase; long mask, idsamp; long counter, stage, framesize, numoutput; RGET out = ZOUT(0); in = ZIN(0); pchratio = ZIN0(2); winsize = ZIN0(1); pchdisp = ZIN0(3); timedisp = ZIN0(4); timedisp = sc_clip(timedisp, 0.f, winsize) * SAMPLERATE; dlybuf = unit->dlybuf; fdelaylen = unit->fdelaylen; idelaylen = unit->idelaylen; iwrphase = unit->iwrphase; numoutput = unit->numoutput; counter = unit->counter; stage = unit->stage; mask = unit->mask; framesize = unit->framesize; dsamp1 = unit->dsamp1; dsamp2 = unit->dsamp2; dsamp3 = unit->dsamp3; dsamp4 = unit->dsamp4; dsamp1_slope = unit->dsamp1_slope; dsamp2_slope = unit->dsamp2_slope; dsamp3_slope = unit->dsamp3_slope; dsamp4_slope = unit->dsamp4_slope; ramp1 = unit->ramp1; ramp2 = unit->ramp2; ramp3 = unit->ramp3; ramp4 = unit->ramp4; ramp1_slope = unit->ramp1_slope; ramp2_slope = unit->ramp2_slope; ramp3_slope = unit->ramp3_slope; ramp4_slope = unit->ramp4_slope; slope = unit->slope; remain = inNumSamples; while (remain) { if (counter <= 0) { counter = framesize >> 2; unit->stage = stage = (stage + 1) & 3; disppchratio = pchratio; if (pchdisp != 0.f) { disppchratio += (pchdisp * frand2(s1, s2, s3)); } disppchratio = sc_clip(disppchratio, 0.f, 4.f); pchratio1 = disppchratio - 1.f; samp_slope = -pchratio1; startpos = pchratio1 < 0.f ? 2.f : framesize * pchratio1 + 2.f; startpos += (timedisp * frand(s1, s2, s3)); switch (stage) { case 0: unit->dsamp1_slope = dsamp1_slope = samp_slope; dsamp1 = startpos; ramp1 = 0.0; unit->ramp1_slope = ramp1_slope = slope; unit->ramp3_slope = ramp3_slope = -slope; break; case 1: unit->dsamp2_slope = dsamp2_slope = samp_slope; dsamp2 = startpos; ramp2 = 0.0; unit->ramp2_slope = ramp2_slope = slope; unit->ramp4_slope = ramp4_slope = -slope; break; case 2: unit->dsamp3_slope = dsamp3_slope = samp_slope; dsamp3 = startpos; ramp3 = 0.0; unit->ramp3_slope = ramp3_slope = slope; unit->ramp1_slope = ramp1_slope = -slope; break; case 3: unit->dsamp4_slope = dsamp4_slope = samp_slope; dsamp4 = startpos; ramp4 = 0.0; unit->ramp2_slope = ramp2_slope = -slope; unit->ramp4_slope = ramp4_slope = slope; break; } /*Print("z %d %d %g %g %g %g %g %g %g %g %g %g %g %g\n", counter, stage, dsamp1_slope, dsamp2_slope, dsamp3_slope, dsamp4_slope, dsamp1, dsamp2, dsamp3, dsamp4, ramp1, ramp2, ramp3, ramp4);*/ } nsmps = sc_min(remain, counter); remain -= nsmps; counter -= nsmps; while (nsmps--) { numoutput++; iwrphase = (iwrphase + 1) & mask; dsamp1 += dsamp1_slope; idsamp = (long)dsamp1; frac = dsamp1 - idsamp; irdphase = (iwrphase - idsamp) & mask; irdphaseb = (irdphase - 1) & mask; if (numoutput < idelaylen) { if (irdphase > iwrphase) { value = 0.f; } else if (irdphaseb > iwrphase) { d1 = dlybuf[irdphase]; value = (d1 - frac * d1) * ramp1; } else { d1 = dlybuf[irdphase]; d2 = dlybuf[irdphaseb]; value = (d1 + frac * (d2 - d1)) * ramp1; } } else { d1 = dlybuf[irdphase]; d2 = dlybuf[irdphaseb]; value = (d1 + frac * (d2 - d1)) * ramp1; } ramp1 += ramp1_slope; dsamp2 += dsamp2_slope; idsamp = (long)dsamp2; frac = dsamp2 - idsamp; irdphase = (iwrphase - idsamp) & mask; irdphaseb = (irdphase - 1) & mask; if (numoutput < idelaylen) { if (irdphase > iwrphase) { // value += 0.f; } else if (irdphaseb > iwrphase) { d1 = dlybuf[irdphase]; value += (d1 - frac * d1) * ramp2; } else { d1 = dlybuf[irdphase]; d2 = dlybuf[irdphaseb]; value += (d1 + frac * (d2 - d1)) * ramp2; } } else { d1 = dlybuf[irdphase]; d2 = dlybuf[irdphaseb]; value += (d1 + frac * (d2 - d1)) * ramp2; } ramp2 += ramp2_slope; dsamp3 += dsamp3_slope; idsamp = (long)dsamp3; frac = dsamp3 - idsamp; irdphase = (iwrphase - idsamp) & mask; irdphaseb = (irdphase - 1) & mask; if (numoutput < idelaylen) { if (irdphase > iwrphase) { // value += 0.f; } else if (irdphaseb > iwrphase) { d1 = dlybuf[irdphase]; value += (d1 - frac * d1) * ramp3; } else { d1 = dlybuf[irdphase]; d2 = dlybuf[irdphaseb]; value += (d1 + frac * (d2 - d1)) * ramp3; } } else { d1 = dlybuf[irdphase]; d2 = dlybuf[irdphaseb]; value += (d1 + frac * (d2 - d1)) * ramp3; } ramp3 += ramp3_slope; dsamp4 += dsamp4_slope; idsamp = (long)dsamp4; frac = dsamp4 - idsamp; irdphase = (iwrphase - idsamp) & mask; irdphaseb = (irdphase - 1) & mask; if (numoutput < idelaylen) { if (irdphase > iwrphase) { // value += 0.f; } else if (irdphaseb > iwrphase) { d1 = dlybuf[irdphase]; value += (d1 - frac * d1) * ramp4; } else { d1 = dlybuf[irdphase]; d2 = dlybuf[irdphaseb]; value += (d1 + frac * (d2 - d1)) * ramp4; } } else { d1 = dlybuf[irdphase]; d2 = dlybuf[irdphaseb]; value += (d1 + frac * (d2 - d1)) * ramp4; } ramp4 += ramp4_slope; dlybuf[iwrphase] = ZXP(in); ZXP(out) = value *= 0.5; } } unit->counter = counter; unit->stage = stage; unit->mask = mask; unit->dsamp1 = dsamp1; unit->dsamp2 = dsamp2; unit->dsamp3 = dsamp3; unit->dsamp4 = dsamp4; unit->ramp1 = ramp1; unit->ramp2 = ramp2; unit->ramp3 = ramp3; unit->ramp4 = ramp4; unit->numoutput = numoutput; unit->iwrphase = iwrphase; if (numoutput >= idelaylen) { SETCALC(PitchShift_next); } RPUT } void PitchShift_Ctor(PitchShift* unit); void PitchShift_Ctor(PitchShift* unit) { long delaybufsize; float *out, *in, *dlybuf; float winsize, pchratio; float fdelaylen, slope; long framesize, last; out = ZOUT(0); in = ZIN(0); pchratio = ZIN0(2); winsize = ZIN0(1); // TODO: why does scsynth freeze if the window size is <= 2 samples? // Nobody needs windows that small for pitch shifting anyway, so we will // simply clamp the window size to 3. float minimum_winsize = 3.f * SAMPLEDUR; if (winsize < minimum_winsize) { winsize = minimum_winsize; } delaybufsize = (long)ceil(winsize * SAMPLERATE * 3.f + 3.f); fdelaylen = delaybufsize - 3; delaybufsize = delaybufsize + BUFLENGTH; delaybufsize = NEXTPOWEROFTWO(delaybufsize); // round up to next power of two unit->dlybuf = nullptr; dlybuf = (float*)RTAlloc(unit->mWorld, delaybufsize * sizeof(float)); ClearUnitIfMemFailed(dlybuf); SETCALC(PitchShift_next_z); *dlybuf = ZIN0(0); ZOUT0(0) = 0.f; unit->dlybuf = dlybuf; unit->idelaylen = delaybufsize; unit->fdelaylen = fdelaylen; unit->iwrphase = 0; unit->numoutput = 0; unit->mask = last = (delaybufsize - 1); unit->framesize = framesize = ((long)(winsize * SAMPLERATE) + 2) & ~3; unit->slope = slope = 2.f / framesize; unit->stage = 3; unit->counter = framesize >> 2; unit->ramp1 = 0.5; unit->ramp2 = 1.0; unit->ramp3 = 0.5; unit->ramp4 = 0.0; unit->ramp1_slope = -slope; unit->ramp2_slope = -slope; unit->ramp3_slope = slope; unit->ramp4_slope = slope; dlybuf[last] = 0.f; // put a few zeroes where we start the read heads dlybuf[last - 1] = 0.f; dlybuf[last - 2] = 0.f; unit->numoutput = 0; // start all read heads 2 samples behind the write head unit->dsamp1 = unit->dsamp2 = unit->dsamp3 = unit->dsamp4 = 2.f; // pch ratio is initially zero for the read heads unit->dsamp1_slope = unit->dsamp2_slope = unit->dsamp3_slope = unit->dsamp4_slope = 1.f; } void PitchShift_Dtor(PitchShift* unit) { RTFree(unit->mWorld, unit->dlybuf); } typedef struct graintap1 { float pos, rate, level, slope, curve; long counter; struct graintap1* next; } GrainTap1; #define MAXDGRAINS 32 struct GrainTap : public Unit { float m_fbufnum; SndBuf* m_buf; float fdelaylen; long bufsize, iwrphase; long nextTime; GrainTap1 grains[MAXDGRAINS]; GrainTap1 *firstActive, *firstFree; }; // coefs: pos, rate, level, slope, curve, counter void GrainTap_next(GrainTap* unit, int inNumSamples); void GrainTap_next(GrainTap* unit, int inNumSamples) { float *out, *out0; const float* dlybuf; float sdur, rdur, rdur2; float dsamp, dsamp_slope, fdelaylen, d1, d2, frac; float level, slope, curve; float maxpitch, pitch, maxtimedisp, timedisp, density; long remain, nsmps, irdphase, irdphaseb, iwrphase, iwrphase0; long idsamp, koffset; long counter; uint32 bufsize; GrainTap1 *grain, *prevGrain, *nextGrain; GET_BUF_SHARED RGET out0 = ZOUT(0); // bufnum, grainDur, pchRatio, pchDisp, timeDisp, overlap // 0 1 2 3 4 5 density = ZIN0(5); density = sc_max(0.0001, density); bufsize = unit->bufsize; if (bufsize != bufSamples) { ClearUnitOutputs(unit, inNumSamples); return; } dlybuf = bufData; fdelaylen = unit->fdelaylen; iwrphase0 = unit->iwrphase; // initialize buffer to zero out = out0; LOOP1(inNumSamples, ZXP(out) = 0.f;); // do all current grains prevGrain = nullptr; grain = unit->firstActive; while (grain) { dsamp = grain->pos; dsamp_slope = grain->rate; level = grain->level; slope = grain->slope; curve = grain->curve; counter = grain->counter; nsmps = sc_min(counter, inNumSamples); iwrphase = iwrphase0; out = out0; LOOP(nsmps, dsamp += dsamp_slope; idsamp = (long)dsamp; frac = dsamp - idsamp; iwrphase = (iwrphase + 1) & mask; irdphase = (iwrphase - idsamp) & mask; irdphaseb = (irdphase - 1) & mask; d1 = dlybuf[irdphase]; d2 = dlybuf[irdphaseb]; ZXP(out) += (d1 + frac * (d2 - d1)) * level; level += slope; slope += curve;); grain->pos = dsamp; grain->level = level; grain->slope = slope; grain->counter -= nsmps; nextGrain = grain->next; if (grain->counter <= 0) { // unlink from active list if (prevGrain) prevGrain->next = nextGrain; else unit->firstActive = nextGrain; // link onto free list grain->next = unit->firstFree; unit->firstFree = grain; } else { prevGrain = grain; } grain = nextGrain; } // start new grains remain = inNumSamples; while (unit->nextTime <= remain) { remain -= unit->nextTime; sdur = ZIN0(1) * SAMPLERATE; sdur = sc_max(sdur, 4.f); grain = unit->firstFree; if (grain) { unit->firstFree = grain->next; grain->next = unit->firstActive; unit->firstActive = grain; koffset = inNumSamples - remain; iwrphase = (iwrphase0 + koffset) & mask; grain->counter = (long)sdur; timedisp = ZIN0(4); timedisp = sc_max(timedisp, 0.f); timedisp = frand(s1, s2, s3) * timedisp * SAMPLERATE; pitch = ZIN0(2) + frand2(s1, s2, s3) * ZIN0(3); if (pitch >= 1.f) { maxpitch = 1.f + (fdelaylen / sdur); pitch = sc_min(pitch, maxpitch); dsamp_slope = 1.f - pitch; grain->rate = dsamp_slope; maxtimedisp = fdelaylen + sdur * dsamp_slope; timedisp = sc_min(timedisp, maxtimedisp); dsamp = BUFLENGTH + koffset + 2.f + timedisp - sdur * dsamp_slope; dsamp = sc_min(dsamp, fdelaylen); } else { maxpitch = -(1.f + (fdelaylen / sdur)); pitch = sc_max(pitch, maxpitch); dsamp_slope = 1.f - pitch; grain->rate = dsamp_slope; maxtimedisp = fdelaylen - sdur * dsamp_slope; timedisp = sc_min(timedisp, maxtimedisp); dsamp = BUFLENGTH + koffset + 2.f + timedisp; dsamp = sc_min(dsamp, fdelaylen); } grain->pos = dsamp; // postbuf("ds %g %g %g\n", dsamp_slope, dsamp, fdelaylen); rdur = 1.f / sdur; rdur2 = rdur * rdur; grain->level = level = 0.f; grain->slope = slope = 4.0 * (rdur - rdur2); // ampslope grain->curve = curve = -8.0 * rdur2; // ampcurve nsmps = remain; out = out0 + koffset; LOOP(nsmps, dsamp += dsamp_slope; idsamp = (long)dsamp; frac = dsamp - idsamp; iwrphase = (iwrphase + 1) & mask; irdphase = (iwrphase - idsamp) & mask; irdphaseb = (irdphase - 1) & mask; d1 = dlybuf[irdphase]; d2 = dlybuf[irdphaseb]; ZXP(out) += (d1 + frac * (d2 - d1)) * level; level += slope; slope += curve;); grain->pos = dsamp; grain->level = level; grain->slope = slope; grain->counter -= nsmps; if (grain->counter <= 0) { // unlink from active list unit->firstActive = grain->next; // link onto free list grain->next = unit->firstFree; unit->firstFree = grain; } } unit->nextTime = (long)(sdur / density); if (unit->nextTime < 1) unit->nextTime = 1; /*if (grain == NULL) { postbuf("nextTime %d %g %g %p %p %p\n", unit->nextTime, sdur, density, grain, unit->firstActive, unit->firstFree); }*/ } iwrphase = (iwrphase0 + BUFLENGTH) & mask; unit->nextTime -= remain; if (unit->nextTime < 0) unit->nextTime = 0; unit->iwrphase = iwrphase; RPUT } void GrainTap_Ctor(GrainTap* unit); void GrainTap_Ctor(GrainTap* unit) { float fdelaylen; float maxdelaytime; GET_BUF if (!ISPOWEROFTWO(bufSamples)) { Print("GrainTap buffer size not a power of two.\n"); SETCALC(*ClearUnitOutputs); return; } fdelaylen = bufSamples - 2 * BUFLENGTH - 3; maxdelaytime = fdelaylen * SAMPLEDUR; SETCALC(GrainTap_next); ZOUT0(0) = 0.f; unit->bufsize = bufSamples; unit->fdelaylen = fdelaylen; unit->iwrphase = 0; unit->nextTime = 0; for (int i = 0; i < MAXDGRAINS - 1; ++i) { unit->grains[i].next = unit->grains + (i + 1); } unit->grains[MAXDGRAINS - 1].next = nullptr; unit->firstFree = unit->grains; unit->firstActive = nullptr; } //////////////////////////////////////////////////////////////////////////////////////////////////////// #define GRAIN_BUF \ const SndBuf* buf = NULL; \ if (bufnum >= world->mNumSndBufs) { \ int localBufNum = bufnum - numBufs; \ Graph* parent = unit->mParent; \ if (localBufNum <= parent->localBufNum) { \ buf = parent->mLocalSndBufs + localBufNum; \ } else { \ continue; \ } \ } else { \ buf = bufs + bufnum; \ } \ LOCK_SNDBUF_SHARED(buf); \ const float* bufData __attribute__((__unused__)) = buf->data; \ uint32 bufChannels __attribute__((__unused__)) = buf->channels; \ uint32 bufSamples __attribute__((__unused__)) = buf->samples; \ uint32 bufFrames = buf->frames; \ int guardFrame __attribute__((__unused__)) = bufFrames - 2; inline float IN_AT(Unit* unit, int index, int offset) { if (INRATE(index) == calc_FullRate) return IN(index)[offset]; if (INRATE(index) == calc_DemandRate) return DEMANDINPUT_A(index, offset + 1); return ZIN0(index); } inline double sc_gloop(double in, double hi) { // avoid the divide if possible if (in >= hi) { in -= hi; if (in < hi) return in; } else if (in < 0.) { in += hi; if (in >= 0.) return in; } else return in; return in - hi * floor(in / hi); } #define GRAIN_LOOP_BODY_4 \ float amp = y1 * y1; \ phase = sc_gloop(phase, loopMax); \ int32 iphase = (int32)phase; \ const float* table1 = bufData + iphase; \ const float* table0 = table1 - 1; \ const float* table2 = table1 + 1; \ const float* table3 = table1 + 2; \ if (iphase == 0) { \ table0 += bufSamples; \ } else if (iphase >= guardFrame) { \ if (iphase == guardFrame) { \ table3 -= bufSamples; \ } else { \ table2 -= bufSamples; \ table3 -= bufSamples; \ } \ } \ float fracphase = phase - (double)iphase; \ float a = table0[0]; \ float b = table1[0]; \ float c = table2[0]; \ float d = table3[0]; \ float outval = amp * cubicinterp(fracphase, a, b, c, d); \ ZXP(out1) += outval * pan1; \ if (numOutputs > 1) { \ ZXP(out2) += outval * pan2; \ } \ double y0 = b1 * y1 - y2; \ y2 = y1; \ y1 = y0; #define GRAIN_LOOP_BODY_2 \ float amp = y1 * y1; \ phase = sc_gloop(phase, loopMax); \ int32 iphase = (int32)phase; \ const float* table1 = bufData + iphase; \ const float* table2 = table1 + 1; \ if (iphase > guardFrame) { \ table2 -= bufSamples; \ } \ float fracphase = phase - (double)iphase; \ float b = table1[0]; \ float c = table2[0]; \ float outval = amp * (b + fracphase * (c - b)); \ ZXP(out1) += outval * pan1; \ if (numOutputs > 1) { \ ZXP(out2) += outval * pan2; \ } \ double y0 = b1 * y1 - y2; \ y2 = y1; \ y1 = y0; #define GRAIN_LOOP_BODY_1 \ float amp = y1 * y1; \ phase = sc_gloop(phase, loopMax); \ int32 iphase = (int32)phase; \ float outval = amp * bufData[iphase]; \ ZXP(out1) += outval * pan1; \ ZXP(out2) += outval * pan2; \ double y0 = b1 * y1 - y2; \ y2 = y1; \ y1 = y0; void TGrains_next(TGrains* unit, int inNumSamples) { float* trigin = IN(0); float prevtrig = unit->mPrevTrig; uint32 numOutputs = unit->mNumOutputs; ClearUnitOutputs(unit, inNumSamples); float* out[16]; for (uint32 i = 0; i < numOutputs; ++i) out[i] = ZOUT(i); World* world = unit->mWorld; SndBuf* bufs = world->mSndBufs; uint32 numBufs = world->mNumSndBufs; for (int i = 0; i < unit->mNumActive;) { Grain* grain = unit->mGrains + i; uint32 bufnum = grain->bufnum; GRAIN_BUF if (bufChannels != 1) { ++i; continue; } double loopMax = (double)bufFrames; float pan1 = grain->pan1; float pan2 = grain->pan2; double rate = grain->rate; double phase = grain->phase; double b1 = grain->b1; double y1 = grain->y1; double y2 = grain->y2; uint32 chan1 = grain->chan; uint32 chan2 = chan1 + 1; if (chan2 >= numOutputs) chan2 = 0; float* out1 = out[chan1]; float* out2 = out[chan2]; // printf("B chan %d %d %p %p", chan1, chan2, out1, out2); int nsmps = sc_min(grain->counter, inNumSamples); if (grain->interp >= 4) { for (int j = 0; j < nsmps; ++j) { GRAIN_LOOP_BODY_4; phase += rate; } } else if (grain->interp >= 2) { for (int j = 0; j < nsmps; ++j) { GRAIN_LOOP_BODY_2; phase += rate; } } else { for (int j = 0; j < nsmps; ++j) { GRAIN_LOOP_BODY_1; phase += rate; } } grain->phase = phase; grain->y1 = y1; grain->y2 = y2; grain->counter -= nsmps; if (grain->counter <= 0) { // remove grain *grain = unit->mGrains[--unit->mNumActive]; } else ++i; } int trigSamples = INRATE(0) == calc_FullRate ? inNumSamples : 1; for (int i = 0; i < trigSamples; ++i) { float trig = trigin[i]; if (trig > 0.f && prevtrig <= 0.f) { // start a grain if (unit->mNumActive + 1 >= kMaxGrains) break; uint32 bufnum = (uint32)IN_AT(unit, 1, i); GRAIN_BUF if (bufChannels != 1) continue; float bufSampleRate = buf->samplerate; float bufRateScale = bufSampleRate * SAMPLEDUR; double loopMax = (double)bufFrames; Grain* grain = unit->mGrains + unit->mNumActive++; grain->bufnum = bufnum; double counter = floor(IN_AT(unit, 4, i) * SAMPLERATE); counter = sc_max(4., counter); grain->counter = (int)counter; double rate = grain->rate = IN_AT(unit, 2, i) * bufRateScale; double centerPhase = IN_AT(unit, 3, i) * bufSampleRate; double phase = centerPhase - 0.5 * counter * rate; float pan = IN_AT(unit, 5, i); float amp = IN_AT(unit, 6, i); grain->interp = (int)IN_AT(unit, 7, i); float panangle; float pan1, pan2; if (numOutputs > 1) { if (numOutputs > 2) { pan = sc_wrap(pan * 0.5f, 0.f, 1.f); float cpan = numOutputs * pan + 0.5f; float ipan = floor(cpan); float panfrac = cpan - ipan; panangle = panfrac * pi2_f; grain->chan = (int)ipan; if (grain->chan >= (int)numOutputs) grain->chan -= numOutputs; } else { grain->chan = 0; pan = sc_clip(pan * 0.5f + 0.5f, 0.f, 1.f); panangle = pan * pi2_f; } pan1 = grain->pan1 = amp * cos(panangle); pan2 = grain->pan2 = amp * sin(panangle); } else { grain->chan = 0; pan1 = grain->pan1 = amp; pan2 = grain->pan2 = 0.; } double w = pi / counter; double b1 = grain->b1 = 2. * cos(w); double y1 = sin(w); double y2 = 0.; uint32 chan1 = grain->chan; uint32 chan2 = chan1 + 1; if (chan2 >= numOutputs) chan2 = 0; float* out1 = out[chan1] + i; float* out2 = out[chan2] + i; int nsmps = sc_min(grain->counter, inNumSamples - i); if (grain->interp >= 4) { for (int j = 0; j < nsmps; ++j) { GRAIN_LOOP_BODY_4; phase += rate; } } else if (grain->interp >= 2) { for (int j = 0; j < nsmps; ++j) { GRAIN_LOOP_BODY_2; phase += rate; } } else { for (int j = 0; j < nsmps; ++j) { GRAIN_LOOP_BODY_1; phase += rate; } } grain->phase = phase; grain->y1 = y1; grain->y2 = y2; grain->counter -= nsmps; if (grain->counter <= 0) { // remove grain *grain = unit->mGrains[--unit->mNumActive]; } } prevtrig = trig; } unit->mPrevTrig = prevtrig; } void TGrains_Ctor(TGrains* unit) { SETCALC(TGrains_next); unit->mNumActive = 0; unit->mPrevTrig = 0.; ClearUnitOutputs(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// /* Pluck - Karplus-Strong */ void Pluck_Ctor(Pluck* unit) { unit->m_maxdelaytime = IN0(2); unit->m_delaytime = IN0(3); unit->m_decaytime = IN0(4); unit->m_dlybuf = nullptr; bool allocationSucessful = DelayUnit_AllocDelayLine(unit); ClearUnitIfMemFailed(allocationSucessful); unit->m_dsamp = CalcDelay(unit, unit->m_delaytime); unit->m_numoutput = 0; unit->m_iwrphase = 0; unit->m_feedbk = sc_CalcFeedback(unit->m_delaytime, unit->m_decaytime); if (INRATE(1) == calc_FullRate) { if (INRATE(5) == calc_FullRate) { SETCALC(Pluck_next_aa_z); } else { SETCALC(Pluck_next_ak_z); // ak } } else { if (INRATE(5) == calc_FullRate) { SETCALC(Pluck_next_ka_z); // ka } else { SETCALC(Pluck_next_kk_z); // kk } } OUT0(0) = unit->m_lastsamp = 0.f; unit->m_prevtrig = 0.f; unit->m_inputsamps = 0; unit->m_coef = IN0(5); } void Pluck_next_aa(Pluck* unit, int inNumSamples) { float* out = OUT(0); float* in = IN(0); float* trig = IN(1); float delaytime = IN0(3); float decaytime = IN0(4); float* coef = IN(5); float lastsamp = unit->m_lastsamp; unsigned long inputsamps = unit->m_inputsamps; float* dlybuf = unit->m_dlybuf; long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; float feedbk = unit->m_feedbk; long mask = unit->m_mask; float thisin, curtrig; float prevtrig = unit->m_prevtrig; if (delaytime == unit->m_delaytime && decaytime == unit->m_decaytime) { long idsamp = (long)dsamp; float frac = dsamp - idsamp; for (int i = 0; i < inNumSamples; i++) { curtrig = trig[i]; if ((prevtrig <= 0.f) && (curtrig > 0.f)) { inputsamps = (long)(delaytime * unit->mRate->mSampleRate + .5f); } prevtrig = curtrig; long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; if (inputsamps > 0) { thisin = in[i]; --inputsamps; } else { thisin = 0.f; } float d0 = dlybuf[irdphase0 & mask]; float d1 = dlybuf[irdphase1 & mask]; float d2 = dlybuf[irdphase2 & mask]; float d3 = dlybuf[irdphase3 & mask]; float value = cubicinterp(frac, d0, d1, d2, d3); float thiscoef = coef[i]; float onepole = ((1. - fabs(thiscoef)) * value) + (thiscoef * lastsamp); dlybuf[iwrphase & mask] = thisin + feedbk * onepole; out[i] = lastsamp = onepole; iwrphase++; }; } else { float next_dsamp = CalcDelay(unit, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); for (int i = 0; i < inNumSamples; i++) { curtrig = trig[i]; if ((prevtrig <= 0.f) && (curtrig > 0.f)) { inputsamps = (long)(delaytime * unit->mRate->mSampleRate + .5f); } prevtrig = curtrig; dsamp += dsamp_slope; long idsamp = (long)dsamp; float frac = dsamp - idsamp; long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; if (inputsamps > 0) { thisin = in[i]; --inputsamps; } else { thisin = 0.f; } float d0 = dlybuf[irdphase0 & mask]; float d1 = dlybuf[irdphase1 & mask]; float d2 = dlybuf[irdphase2 & mask]; float d3 = dlybuf[irdphase3 & mask]; float value = cubicinterp(frac, d0, d1, d2, d3); float thiscoef = coef[i]; float onepole = ((1. - fabs(thiscoef)) * value) + (thiscoef * lastsamp); dlybuf[iwrphase & mask] = thisin + feedbk * onepole; out[i] = lastsamp = onepole; feedbk += feedbk_slope; iwrphase++; }; unit->m_feedbk = feedbk; unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; unit->m_decaytime = decaytime; } unit->m_prevtrig = prevtrig; unit->m_inputsamps = inputsamps; unit->m_lastsamp = zapgremlins(lastsamp); unit->m_iwrphase = iwrphase; } void Pluck_next_aa_z(Pluck* unit, int inNumSamples) { float* out = OUT(0); float* in = IN(0); float* trig = IN(1); float delaytime = IN0(3); float decaytime = IN0(4); float* coef = IN(5); float lastsamp = unit->m_lastsamp; float* dlybuf = unit->m_dlybuf; long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; float feedbk = unit->m_feedbk; long mask = unit->m_mask; float d0, d1, d2, d3; float thisin, curtrig; unsigned long inputsamps = unit->m_inputsamps; float prevtrig = unit->m_prevtrig; if (delaytime == unit->m_delaytime && decaytime == unit->m_decaytime) { long idsamp = (long)dsamp; float frac = dsamp - idsamp; for (int i = 0; i < inNumSamples; i++) { curtrig = trig[i]; if ((prevtrig <= 0.f) && (curtrig > 0.f)) { inputsamps = (long)(delaytime * unit->mRate->mSampleRate + .5f); } prevtrig = curtrig; long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; if (inputsamps > 0) { thisin = in[i]; --inputsamps; } else { thisin = 0.f; } if (irdphase0 < 0) { dlybuf[iwrphase & mask] = thisin; out[i] = 0.f; } else { if (irdphase1 < 0) { d1 = d2 = d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; } else if (irdphase2 < 0) { d1 = d2 = d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; } else if (irdphase3 < 0) { d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; d2 = dlybuf[irdphase2 & mask]; } else { d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; d2 = dlybuf[irdphase2 & mask]; d3 = dlybuf[irdphase3 & mask]; } float value = cubicinterp(frac, d0, d1, d2, d3); float thiscoef = coef[i]; float onepole = ((1. - fabs(thiscoef)) * value) + (thiscoef * lastsamp); dlybuf[iwrphase & mask] = thisin + feedbk * onepole; out[i] = lastsamp = onepole; } iwrphase++; }; } else { float next_dsamp = CalcDelay(unit, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); for (int i = 0; i < inNumSamples; i++) { curtrig = trig[i]; if ((prevtrig <= 0.f) && (curtrig > 0.f)) { inputsamps = (long)(delaytime * unit->mRate->mSampleRate + .5f); } prevtrig = curtrig; dsamp += dsamp_slope; long idsamp = (long)dsamp; float frac = dsamp - idsamp; long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; if (inputsamps > 0) { thisin = in[i]; --inputsamps; } else { thisin = 0.f; } if (irdphase0 < 0) { dlybuf[iwrphase & mask] = thisin; out[i] = 0.f; } else { if (irdphase1 < 0) { d1 = d2 = d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; } else if (irdphase2 < 0) { d1 = d2 = d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; } else if (irdphase3 < 0) { d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; d2 = dlybuf[irdphase2 & mask]; } else { d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; d2 = dlybuf[irdphase2 & mask]; d3 = dlybuf[irdphase3 & mask]; } float value = cubicinterp(frac, d0, d1, d2, d3); float thiscoef = coef[i]; float onepole = ((1. - fabs(thiscoef)) * value) + (thiscoef * lastsamp); dlybuf[iwrphase & mask] = thisin + feedbk * onepole; out[i] = lastsamp = onepole; } feedbk += feedbk_slope; iwrphase++; }; unit->m_feedbk = feedbk; unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; unit->m_decaytime = decaytime; } unit->m_inputsamps = inputsamps; unit->m_prevtrig = prevtrig; unit->m_lastsamp = zapgremlins(lastsamp); unit->m_iwrphase = iwrphase; unit->m_numoutput += inNumSamples; if (unit->m_numoutput >= unit->m_idelaylen) { SETCALC(Pluck_next_aa); } } void Pluck_next_kk(Pluck* unit, int inNumSamples) { float* out = OUT(0); float* in = IN(0); float trig = IN0(1); float delaytime = IN0(3); float decaytime = IN0(4); float coef = IN0(5); float lastsamp = unit->m_lastsamp; unsigned long inputsamps = unit->m_inputsamps; float* dlybuf = unit->m_dlybuf; long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; float feedbk = unit->m_feedbk; long mask = unit->m_mask; float thisin; if ((unit->m_prevtrig <= 0.f) && (trig > 0.f)) { inputsamps = (long)(delaytime * unit->mRate->mSampleRate + .5f); } unit->m_prevtrig = trig; if (delaytime == unit->m_delaytime && decaytime == unit->m_decaytime && coef == unit->m_coef) { long idsamp = (long)dsamp; float frac = dsamp - idsamp; for (int i = 0; i < inNumSamples; i++) { long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; if (inputsamps > 0) { thisin = in[i]; --inputsamps; } else { thisin = 0.f; } float d0 = dlybuf[irdphase0 & mask]; float d1 = dlybuf[irdphase1 & mask]; float d2 = dlybuf[irdphase2 & mask]; float d3 = dlybuf[irdphase3 & mask]; float value = cubicinterp(frac, d0, d1, d2, d3); float onepole = ((1. - fabs(coef)) * value) + (coef * lastsamp); dlybuf[iwrphase & mask] = thisin + (feedbk * onepole); out[i] = lastsamp = onepole; // value; iwrphase++; }; } else { float next_dsamp = CalcDelay(unit, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); float curcoef = unit->m_coef; float coef_slope = CALCSLOPE(coef, curcoef); for (int i = 0; i < inNumSamples; i++) { dsamp += dsamp_slope; long idsamp = (long)dsamp; float frac = dsamp - idsamp; long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; if (inputsamps > 0) { thisin = in[i]; --inputsamps; } else { thisin = 0.f; } float d0 = dlybuf[irdphase0 & mask]; float d1 = dlybuf[irdphase1 & mask]; float d2 = dlybuf[irdphase2 & mask]; float d3 = dlybuf[irdphase3 & mask]; float value = cubicinterp(frac, d0, d1, d2, d3); float onepole = ((1. - fabs(curcoef)) * value) + (curcoef * lastsamp); dlybuf[iwrphase & mask] = thisin + (feedbk * onepole); out[i] = lastsamp = onepole; // value; feedbk += feedbk_slope; curcoef += coef_slope; iwrphase++; }; unit->m_feedbk = feedbk; unit->m_coef = coef; unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; unit->m_decaytime = decaytime; } unit->m_inputsamps = inputsamps; unit->m_lastsamp = zapgremlins(lastsamp); unit->m_iwrphase = iwrphase; } void Pluck_next_kk_z(Pluck* unit, int inNumSamples) { float* out = OUT(0); float* in = IN(0); float trig = IN0(1); float delaytime = IN0(3); float decaytime = IN0(4); float coef = IN0(5); float lastsamp = unit->m_lastsamp; float* dlybuf = unit->m_dlybuf; long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; float feedbk = unit->m_feedbk; long mask = unit->m_mask; float d0, d1, d2, d3; float thisin; unsigned long inputsamps = unit->m_inputsamps; if ((unit->m_prevtrig <= 0.f) && (trig > 0.f)) { inputsamps = (long)(delaytime * unit->mRate->mSampleRate + .5f); } unit->m_prevtrig = trig; if (delaytime == unit->m_delaytime && decaytime == unit->m_decaytime && coef == unit->m_coef) { long idsamp = (long)dsamp; float frac = dsamp - idsamp; for (int i = 0; i < inNumSamples; i++) { long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; if (inputsamps > 0) { thisin = in[i]; --inputsamps; } else { thisin = 0.f; } if (irdphase0 < 0) { dlybuf[iwrphase & mask] = thisin; out[i] = 0.f; } else { if (irdphase1 < 0) { d1 = d2 = d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; } else if (irdphase2 < 0) { d1 = d2 = d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; } else if (irdphase3 < 0) { d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; d2 = dlybuf[irdphase2 & mask]; } else { d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; d2 = dlybuf[irdphase2 & mask]; d3 = dlybuf[irdphase3 & mask]; } float value = cubicinterp(frac, d0, d1, d2, d3); float onepole = ((1. - fabs(coef)) * value) + (coef * lastsamp); dlybuf[iwrphase & mask] = thisin + (feedbk * onepole); out[i] = lastsamp = onepole; // value; } iwrphase++; }; } else { float next_dsamp = CalcDelay(unit, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); float curcoef = unit->m_coef; float coef_slope = CALCSLOPE(coef, curcoef); for (int i = 0; i < inNumSamples; i++) { dsamp += dsamp_slope; long idsamp = (long)dsamp; float frac = dsamp - idsamp; long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; if (inputsamps > 0) { thisin = in[i]; --inputsamps; } else { thisin = 0.f; } if (irdphase0 < 0) { dlybuf[iwrphase & mask] = thisin; out[i] = 0.f; } else { if (irdphase1 < 0) { d1 = d2 = d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; } else if (irdphase2 < 0) { d1 = d2 = d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; } else if (irdphase3 < 0) { d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; d2 = dlybuf[irdphase2 & mask]; } else { d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; d2 = dlybuf[irdphase2 & mask]; d3 = dlybuf[irdphase3 & mask]; } float value = cubicinterp(frac, d0, d1, d2, d3); float onepole = ((1. - fabs(curcoef)) * value) + (curcoef * lastsamp); dlybuf[iwrphase & mask] = thisin + (feedbk * onepole); out[i] = lastsamp = onepole; // value; } feedbk += feedbk_slope; curcoef += coef_slope; iwrphase++; }; unit->m_feedbk = feedbk; unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; unit->m_decaytime = decaytime; unit->m_coef = coef; } unit->m_inputsamps = inputsamps; unit->m_lastsamp = zapgremlins(lastsamp); unit->m_iwrphase = iwrphase; unit->m_numoutput += inNumSamples; if (unit->m_numoutput >= unit->m_idelaylen) { SETCALC(Pluck_next_kk); } } void Pluck_next_ak(Pluck* unit, int inNumSamples) { float* out = OUT(0); float* in = IN(0); float* trig = IN(1); float delaytime = IN0(3); float decaytime = IN0(4); float coef = IN0(5); float lastsamp = unit->m_lastsamp; unsigned long inputsamps = unit->m_inputsamps; float* dlybuf = unit->m_dlybuf; long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; float feedbk = unit->m_feedbk; long mask = unit->m_mask; float thisin, curtrig; float prevtrig = unit->m_prevtrig; if (delaytime == unit->m_delaytime && decaytime == unit->m_decaytime) { long idsamp = (long)dsamp; float frac = dsamp - idsamp; for (int i = 0; i < inNumSamples; i++) { curtrig = trig[i]; if ((prevtrig <= 0.f) && (curtrig > 0.f)) { inputsamps = (long)(delaytime * unit->mRate->mSampleRate + .5f); } prevtrig = curtrig; long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; if (inputsamps > 0) { thisin = in[i]; --inputsamps; } else { thisin = 0.f; } float d0 = dlybuf[irdphase0 & mask]; float d1 = dlybuf[irdphase1 & mask]; float d2 = dlybuf[irdphase2 & mask]; float d3 = dlybuf[irdphase3 & mask]; float value = cubicinterp(frac, d0, d1, d2, d3); float onepole = ((1. - fabs(coef)) * value) + (coef * lastsamp); dlybuf[iwrphase & mask] = thisin + feedbk * onepole; out[i] = lastsamp = onepole; iwrphase++; }; } else { float next_dsamp = CalcDelay(unit, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); float curcoef = unit->m_coef; float coef_slope = CALCSLOPE(coef, curcoef); for (int i = 0; i < inNumSamples; i++) { curtrig = trig[i]; if ((prevtrig <= 0.f) && (curtrig > 0.f)) { inputsamps = (long)(delaytime * unit->mRate->mSampleRate + .5f); } prevtrig = curtrig; dsamp += dsamp_slope; long idsamp = (long)dsamp; float frac = dsamp - idsamp; long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; if (inputsamps > 0) { thisin = in[i]; --inputsamps; } else { thisin = 0.f; } float d0 = dlybuf[irdphase0 & mask]; float d1 = dlybuf[irdphase1 & mask]; float d2 = dlybuf[irdphase2 & mask]; float d3 = dlybuf[irdphase3 & mask]; float value = cubicinterp(frac, d0, d1, d2, d3); float onepole = ((1. - fabs(curcoef)) * value) + (curcoef * lastsamp); dlybuf[iwrphase & mask] = thisin + feedbk * onepole; out[i] = lastsamp = onepole; feedbk += feedbk_slope; curcoef += coef_slope; iwrphase++; }; unit->m_feedbk = feedbk; unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; unit->m_decaytime = decaytime; unit->m_coef = coef; } unit->m_prevtrig = prevtrig; unit->m_inputsamps = inputsamps; unit->m_lastsamp = zapgremlins(lastsamp); unit->m_iwrphase = iwrphase; } void Pluck_next_ak_z(Pluck* unit, int inNumSamples) { float* out = OUT(0); float* in = IN(0); float* trig = IN(1); float delaytime = IN0(3); float decaytime = IN0(4); float coef = IN0(5); float lastsamp = unit->m_lastsamp; float* dlybuf = unit->m_dlybuf; long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; float feedbk = unit->m_feedbk; long mask = unit->m_mask; float d0, d1, d2, d3; float thisin, curtrig; unsigned long inputsamps = unit->m_inputsamps; float prevtrig = unit->m_prevtrig; if (delaytime == unit->m_delaytime && decaytime == unit->m_decaytime && coef == unit->m_coef) { long idsamp = (long)dsamp; float frac = dsamp - idsamp; for (int i = 0; i < inNumSamples; i++) { curtrig = trig[i]; if ((prevtrig <= 0.f) && (curtrig > 0.f)) { inputsamps = (long)(delaytime * unit->mRate->mSampleRate + .5f); } prevtrig = curtrig; long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; if (inputsamps > 0) { thisin = in[i]; --inputsamps; } else { thisin = 0.f; } if (irdphase0 < 0) { dlybuf[iwrphase & mask] = thisin; out[i] = 0.f; } else { if (irdphase1 < 0) { d1 = d2 = d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; } else if (irdphase2 < 0) { d1 = d2 = d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; } else if (irdphase3 < 0) { d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; d2 = dlybuf[irdphase2 & mask]; } else { d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; d2 = dlybuf[irdphase2 & mask]; d3 = dlybuf[irdphase3 & mask]; } float value = cubicinterp(frac, d0, d1, d2, d3); float onepole = ((1. - fabs(coef)) * value) + (coef * lastsamp); dlybuf[iwrphase & mask] = thisin + feedbk * onepole; out[i] = lastsamp = onepole; } iwrphase++; }; } else { float next_dsamp = CalcDelay(unit, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); float curcoef = unit->m_coef; float coef_slope = CALCSLOPE(coef, curcoef); for (int i = 0; i < inNumSamples; i++) { curtrig = trig[i]; if ((prevtrig <= 0.f) && (curtrig > 0.f)) { inputsamps = (long)(delaytime * unit->mRate->mSampleRate + .5f); } prevtrig = curtrig; dsamp += dsamp_slope; long idsamp = (long)dsamp; float frac = dsamp - idsamp; long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; if (inputsamps > 0) { thisin = in[i]; --inputsamps; } else { thisin = 0.f; } if (irdphase0 < 0) { dlybuf[iwrphase & mask] = thisin; out[i] = 0.f; } else { if (irdphase1 < 0) { d1 = d2 = d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; } else if (irdphase2 < 0) { d1 = d2 = d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; } else if (irdphase3 < 0) { d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; d2 = dlybuf[irdphase2 & mask]; } else { d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; d2 = dlybuf[irdphase2 & mask]; d3 = dlybuf[irdphase3 & mask]; } float value = cubicinterp(frac, d0, d1, d2, d3); float onepole = ((1. - fabs(curcoef)) * value) + (curcoef * lastsamp); dlybuf[iwrphase & mask] = thisin + feedbk * onepole; out[i] = lastsamp = onepole; } feedbk += feedbk_slope; curcoef += coef_slope; iwrphase++; }; unit->m_feedbk = feedbk; unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; unit->m_decaytime = decaytime; unit->m_coef = coef; } unit->m_inputsamps = inputsamps; unit->m_prevtrig = prevtrig; unit->m_lastsamp = zapgremlins(lastsamp); unit->m_iwrphase = iwrphase; unit->m_numoutput += inNumSamples; if (unit->m_numoutput >= unit->m_idelaylen) { SETCALC(Pluck_next_ak); } } void Pluck_next_ka(Pluck* unit, int inNumSamples) { float* out = OUT(0); float* in = IN(0); float trig = IN0(1); float delaytime = IN0(3); float decaytime = IN0(4); float* coef = IN(5); float lastsamp = unit->m_lastsamp; unsigned long inputsamps = unit->m_inputsamps; float* dlybuf = unit->m_dlybuf; long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; float feedbk = unit->m_feedbk; long mask = unit->m_mask; float thisin; if ((unit->m_prevtrig <= 0.f) && (trig > 0.f)) { inputsamps = (long)(delaytime * unit->mRate->mSampleRate + .5f); } unit->m_prevtrig = trig; if (delaytime == unit->m_delaytime && decaytime == unit->m_decaytime) { long idsamp = (long)dsamp; float frac = dsamp - idsamp; for (int i = 0; i < inNumSamples; i++) { long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; if (inputsamps > 0) { thisin = in[i]; --inputsamps; } else { thisin = 0.f; } float d0 = dlybuf[irdphase0 & mask]; float d1 = dlybuf[irdphase1 & mask]; float d2 = dlybuf[irdphase2 & mask]; float d3 = dlybuf[irdphase3 & mask]; float value = cubicinterp(frac, d0, d1, d2, d3); float thiscoef = coef[i]; float onepole = ((1. - fabs(thiscoef)) * value) + (thiscoef * lastsamp); dlybuf[iwrphase & mask] = thisin + feedbk * onepole; out[i] = lastsamp = onepole; iwrphase++; }; } else { float next_dsamp = CalcDelay(unit, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); for (int i = 0; i < inNumSamples; i++) { dsamp += dsamp_slope; long idsamp = (long)dsamp; float frac = dsamp - idsamp; long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; if (inputsamps > 0) { thisin = in[i]; --inputsamps; } else { thisin = 0.f; } float d0 = dlybuf[irdphase0 & mask]; float d1 = dlybuf[irdphase1 & mask]; float d2 = dlybuf[irdphase2 & mask]; float d3 = dlybuf[irdphase3 & mask]; float value = cubicinterp(frac, d0, d1, d2, d3); float thiscoef = coef[i]; float onepole = ((1. - fabs(thiscoef)) * value) + (thiscoef * lastsamp); dlybuf[iwrphase & mask] = thisin + feedbk * onepole; out[i] = lastsamp = onepole; feedbk += feedbk_slope; iwrphase++; }; unit->m_feedbk = feedbk; unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; unit->m_decaytime = decaytime; } unit->m_inputsamps = inputsamps; unit->m_lastsamp = zapgremlins(lastsamp); unit->m_iwrphase = iwrphase; } void Pluck_next_ka_z(Pluck* unit, int inNumSamples) { float* out = OUT(0); float* in = IN(0); float trig = IN0(1); float delaytime = IN0(3); float decaytime = IN0(4); float* coef = IN(5); float lastsamp = unit->m_lastsamp; float* dlybuf = unit->m_dlybuf; long iwrphase = unit->m_iwrphase; float dsamp = unit->m_dsamp; float feedbk = unit->m_feedbk; long mask = unit->m_mask; float d0, d1, d2, d3; float thisin; unsigned long inputsamps = unit->m_inputsamps; if ((unit->m_prevtrig <= 0.f) && (trig > 0.f)) { inputsamps = (long)(delaytime * unit->mRate->mSampleRate + .5f); } unit->m_prevtrig = trig; if (delaytime == unit->m_delaytime && decaytime == unit->m_decaytime) { long idsamp = (long)dsamp; float frac = dsamp - idsamp; for (int i = 0; i < inNumSamples; i++) { long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; if (inputsamps > 0) { thisin = in[i]; --inputsamps; } else { thisin = 0.f; } if (irdphase0 < 0) { dlybuf[iwrphase & mask] = thisin; out[i] = 0.f; } else { if (irdphase1 < 0) { d1 = d2 = d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; } else if (irdphase2 < 0) { d1 = d2 = d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; } else if (irdphase3 < 0) { d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; d2 = dlybuf[irdphase2 & mask]; } else { d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; d2 = dlybuf[irdphase2 & mask]; d3 = dlybuf[irdphase3 & mask]; } float value = cubicinterp(frac, d0, d1, d2, d3); float thiscoef = coef[i]; float onepole = ((1. - fabs(thiscoef)) * value) + (thiscoef * lastsamp); dlybuf[iwrphase & mask] = thisin + feedbk * onepole; out[i] = lastsamp = onepole; } iwrphase++; }; } else { float next_dsamp = CalcDelay(unit, delaytime); float dsamp_slope = CALCSLOPE(next_dsamp, dsamp); float next_feedbk = sc_CalcFeedback(delaytime, decaytime); float feedbk_slope = CALCSLOPE(next_feedbk, feedbk); for (int i = 0; i < inNumSamples; i++) { dsamp += dsamp_slope; long idsamp = (long)dsamp; float frac = dsamp - idsamp; long irdphase1 = iwrphase - idsamp; long irdphase2 = irdphase1 - 1; long irdphase3 = irdphase1 - 2; long irdphase0 = irdphase1 + 1; if (inputsamps > 0) { thisin = in[i]; --inputsamps; } else { thisin = 0.f; } if (irdphase0 < 0) { dlybuf[iwrphase & mask] = thisin; out[i] = 0.f; } else { if (irdphase1 < 0) { d1 = d2 = d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; } else if (irdphase2 < 0) { d1 = d2 = d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; } else if (irdphase3 < 0) { d3 = 0.f; d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; d2 = dlybuf[irdphase2 & mask]; } else { d0 = dlybuf[irdphase0 & mask]; d1 = dlybuf[irdphase1 & mask]; d2 = dlybuf[irdphase2 & mask]; d3 = dlybuf[irdphase3 & mask]; } float value = cubicinterp(frac, d0, d1, d2, d3); float thiscoef = coef[i]; float onepole = ((1. - fabs(thiscoef)) * value) + (thiscoef * lastsamp); dlybuf[iwrphase & mask] = thisin + feedbk * onepole; out[i] = lastsamp = onepole; } feedbk += feedbk_slope; iwrphase++; }; unit->m_feedbk = feedbk; unit->m_dsamp = dsamp; unit->m_delaytime = delaytime; unit->m_decaytime = decaytime; } unit->m_inputsamps = inputsamps; unit->m_lastsamp = zapgremlins(lastsamp); unit->m_iwrphase = iwrphase; unit->m_numoutput += inNumSamples; if (unit->m_numoutput >= unit->m_idelaylen) { SETCALC(Pluck_next_ka); } } //////////////////////////////////////////////////////////////////////////////////////////////////////// #define DELTAP_BUF \ World* world = unit->mWorld; \ if (bufnum >= world->mNumSndBufs) { \ int localBufNum = bufnum - world->mNumSndBufs; \ Graph* parent = unit->mParent; \ if (localBufNum <= parent->localBufNum) { \ unit->m_buf = parent->mLocalSndBufs + localBufNum; \ } else { \ bufnum = 0; \ unit->m_buf = world->mSndBufs + bufnum; \ } \ } else { \ unit->m_buf = world->mSndBufs + bufnum; \ } \ SndBuf* buf = unit->m_buf; \ float* bufData __attribute__((__unused__)) = buf->data; \ uint32 bufChannels __attribute__((__unused__)) = buf->channels; \ uint32 bufSamples = buf->samples; \ uint32 bufFrames = buf->frames; \ int guardFrame __attribute__((__unused__)) = bufFrames - 2; \ double loopMax __attribute__((__unused__)) = (double)bufSamples; #define CHECK_DELTAP_BUF \ if ((!bufData) || (bufChannels != 1)) { \ unit->mDone = true; \ ClearUnitOutputs(unit, inNumSamples); \ return; \ } static void DelTapWr_first(DelTapWr* unit, int inNumSamples) { float fbufnum = IN0(0); uint32 bufnum = (uint32)fbufnum; float* in = IN(1); float* out = OUT(0); uint32 phase = unit->m_phase; DELTAP_BUF CHECK_DELTAP_BUF // zero out the buffer! #ifdef NOVA_SIMD if (nova::vec<float>::is_aligned(bufData)) { uint32 unroll = bufSamples & (~(nova::vec<float>::size - 1)); nova::zerovec_simd(bufData, unroll); uint32 remain = bufSamples - unroll; Clear(remain, bufData + unroll); } else Clear(bufSamples, bufData); #else Clear(bufSamples, bufData); #endif out[0] = (float)phase; bufData[phase] = in[0]; phase++; if (phase == bufSamples) phase -= bufSamples; unit->m_phase = phase; } void DelTapWr_Ctor(DelTapWr* unit) { if (BUFLENGTH & 15) SETCALC(DelTapWr_next); else SETCALC(DelTapWr_next_simd); unit->m_phase = 0; unit->m_fbufnum = -1e9f; DelTapWr_first(unit, 1); } template <bool simd> static inline void DelTapWr_perform(DelTapWr* unit, int inNumSamples) { float fbufnum = IN0(0); uint32 bufnum = (uint32)fbufnum; const float* in = ZIN(1); float* out = ZOUT(0); uint32* phase_out = (uint32*)out; uint32 phase = unit->m_phase; DELTAP_BUF CHECK_DELTAP_BUF LOCK_SNDBUF(buf); int buf_remain = (int)(bufSamples - phase); if (inNumSamples < buf_remain) { /* fast-path */ #ifdef NOVA_SIMD if (simd) nova::copyvec_an_simd(bufData + phase, IN(1), inNumSamples); else #endif Copy(inNumSamples, bufData + phase, IN(1)); LOOP1(inNumSamples, ZXP(phase_out) = phase++;) } else { LOOP1(inNumSamples, bufData[phase] = ZXP(in); ZXP(phase_out) = phase++; if (phase == bufSamples) phase -= bufSamples;) } unit->m_phase = phase; } void DelTapWr_next(DelTapWr* unit, int inNumSamples) { DelTapWr_perform<false>(unit, inNumSamples); } void DelTapWr_next_simd(DelTapWr* unit, int inNumSamples) { DelTapWr_perform<true>(unit, inNumSamples); } #define SETUP_TAPDELK \ float delTime = unit->m_delTime; \ float newDelTime = IN0(2) * (float)SAMPLERATE; \ float delTimeInc = CALCSLOPE(newDelTime, delTime); \ float* fPhaseIn = IN(1); \ uint32* iPhaseIn = (uint32*)fPhaseIn; \ uint32 phaseIn = *iPhaseIn; \ float fbufnum = IN0(0); \ uint32 bufnum = (uint32)fbufnum; \ float* out __attribute__((__unused__)) = ZOUT(0); #define SETUP_TAPDELA \ float* delTime = ZIN(2); \ float* fPhaseIn = IN(1); \ uint32* iPhaseIn = (uint32*)fPhaseIn; \ uint32 phaseIn = *iPhaseIn; \ float fbufnum = IN0(0); \ uint32 bufnum = (uint32)fbufnum; \ float* out = ZOUT(0); void DelTapRd_Ctor(DelTapRd* unit) { unit->m_fbufnum = -1e9f; unit->m_delTime = IN0(2) * SAMPLERATE; int interp = (int)IN0(3); if (INRATE(2) == calc_FullRate) { if (interp == 2) SETCALC(DelTapRd_next2_a); else if (interp == 4) SETCALC(DelTapRd_next4_a); else SETCALC(DelTapRd_next1_a); } else { if (interp == 2) SETCALC(DelTapRd_next2_k); else if (interp == 4) SETCALC(DelTapRd_next4_k); else if (BUFLENGTH & 15) SETCALC(DelTapRd_next1_k); else { SETCALC(DelTapRd_next1_k_simd); DelTapRd_next1_k(unit, 1); return; } } (unit->mCalcFunc)(unit, 1); } void DelTapRd_next1_a(DelTapRd* unit, int inNumSamples) { SETUP_TAPDELA DELTAP_BUF CHECK_DELTAP_BUF LOCK_SNDBUF_SHARED(buf); LOOP1(inNumSamples, double curDelTimeSamps = ZXP(delTime) * SAMPLERATE; double phase = phaseIn - curDelTimeSamps; if (phase < 0.) phase += loopMax; if (phase >= loopMax) phase -= loopMax; int32 iphase = (int32)phase; ZXP(out) = bufData[iphase]; phaseIn += 1.;) } template <bool simd> inline void DelTapRd_perform1_k(DelTapRd* unit, int inNumSamples) { SETUP_TAPDELK DELTAP_BUF CHECK_DELTAP_BUF float* zout = ZOUT(0); LOCK_SNDBUF_SHARED(buf); if (delTime == newDelTime) { double phase = (double)phaseIn - delTime; int32 iphase = (int32)phase; if ((iphase >= 0) // lower bound && iphase + inNumSamples < (bufSamples - 1)) // upper bound { #ifdef NOVA_SIMD if (simd) nova::copyvec_na_simd(OUT(0), bufData + iphase, inNumSamples); else #endif Copy(inNumSamples, OUT(0), bufData + iphase); } else LOOP1(inNumSamples, if (iphase < 0) iphase += bufSamples; if (iphase >= bufSamples) iphase -= bufSamples; ZXP(zout) = bufData[iphase]; ++iphase;) } else { LOOP1(inNumSamples, double phase = (double)phaseIn - delTime; if (phase < 0.) phase += loopMax; if (phase >= loopMax) phase -= loopMax; int32 iphase = (int32)phase; ZXP(zout) = bufData[iphase]; delTime += delTimeInc; ++phaseIn;) unit->m_delTime = delTime; } } void DelTapRd_next1_k(DelTapRd* unit, int inNumSamples) { DelTapRd_perform1_k<false>(unit, inNumSamples); } void DelTapRd_next1_k_simd(DelTapRd* unit, int inNumSamples) { DelTapRd_perform1_k<true>(unit, inNumSamples); } void DelTapRd_next2_k(DelTapRd* unit, int inNumSamples) { SETUP_TAPDELK DELTAP_BUF CHECK_DELTAP_BUF int32 iloopMax = (int32)bufSamples; LOCK_SNDBUF_SHARED(buf); if (delTime == newDelTime) { double phase = (double)phaseIn - delTime; double dphase; float fracphase = std::modf(phase, &dphase); int32 iphase = (int32)dphase; if ((phase >= 0) // lower bound && phase + inNumSamples < (loopMax - 2)) // upper bound { LOOP1(inNumSamples, int32 iphase1 = iphase + 1; float b = bufData[iphase]; float c = bufData[iphase1]; ZXP(out) = (b + fracphase * (c - b)); iphase += 1;); } else { LOOP1(inNumSamples, if (iphase < 0) iphase += iloopMax; else if (iphase >= bufSamples) phase -= iloopMax; int32 iphase1 = iphase + 1; if (iphase1 >= iloopMax) iphase1 -= iloopMax; float b = bufData[iphase]; float c = bufData[iphase1]; ZXP(out) = (b + fracphase * (c - b)); ++iphase;); } } else { LOOP1(inNumSamples, double phase = (double)phaseIn - delTime; if (phase < 0.) phase += loopMax; if (phase >= loopMax) phase -= loopMax; int32 iphase = (int32)phase; int32 iphase1 = iphase + 1; if (iphase1 >= iloopMax) iphase1 -= iloopMax; float fracphase = phase - (double)iphase; float b = bufData[iphase]; float c = bufData[iphase1]; ZXP(out) = (b + fracphase * (c - b)); delTime += delTimeInc; ++phaseIn;); unit->m_delTime = delTime; } } void DelTapRd_next2_a(DelTapRd* unit, int inNumSamples) { SETUP_TAPDELA DELTAP_BUF CHECK_DELTAP_BUF int32 iloopMax = (int32)bufSamples; LOCK_SNDBUF_SHARED(buf); LOOP1(inNumSamples, double curDelTimeSamps = ZXP(delTime) * SAMPLERATE; double phase = (double)phaseIn - curDelTimeSamps; if (phase < 0.) phase += loopMax; if (phase >= loopMax) phase -= loopMax; int32 iphase = (int32)phase; int32 iphase1 = iphase + 1; if (iphase1 >= iloopMax) iphase1 -= iloopMax; float fracphase = phase - (double)iphase; float b = bufData[iphase]; float c = bufData[iphase1]; ZXP(out) = (b + fracphase * (c - b)); ++phaseIn;); } void DelTapRd_next4_k(DelTapRd* unit, int inNumSamples) { SETUP_TAPDELK DELTAP_BUF CHECK_DELTAP_BUF int32 iloopMax = (int32)loopMax; LOCK_SNDBUF_SHARED(buf); if (delTime == newDelTime) { double phase = (double)phaseIn - delTime; double dphase; float fracphase = std::modf(phase, &dphase); int32 iphase = (int32)dphase; if ((iphase >= 1) // lower bound && iphase + inNumSamples < (iloopMax - 4)) // upper bound { LOOP1(inNumSamples, int32 iphase0 = iphase - 1; int32 iphase1 = iphase + 1; int32 iphase2 = iphase + 2; float a = bufData[iphase0]; float b = bufData[iphase]; float c = bufData[iphase1]; float d = bufData[iphase2]; ZXP(out) = cubicinterp(fracphase, a, b, c, d); ++iphase;); } else { LOOP1(inNumSamples, if (iphase < 0) iphase += iloopMax; else if (iphase >= iloopMax) iphase -= iloopMax; int32 iphase0 = iphase - 1; int32 iphase1 = iphase + 1; int32 iphase2 = iphase + 2; if (iphase0 < 0) iphase0 += iloopMax; if (iphase1 > iloopMax) iphase1 -= iloopMax; if (iphase2 > iloopMax) iphase2 -= iloopMax; float a = bufData[iphase0]; float b = bufData[iphase]; float c = bufData[iphase1]; float d = bufData[iphase2]; ZXP(out) = cubicinterp(fracphase, a, b, c, d); ++iphase;); } } else { LOOP1(inNumSamples, double phase = (double)phaseIn - delTime; double dphase; float fracphase = std::modf(phase, &dphase); int32 iphase = (int32)dphase; if (iphase < 0.) iphase += iloopMax; if (iphase >= iloopMax) iphase -= iloopMax; int32 iphase0 = iphase - 1; int32 iphase1 = iphase + 1; int32 iphase2 = iphase + 2; if (iphase0 < 0) iphase0 += iloopMax; if (iphase1 > iloopMax) iphase1 -= iloopMax; if (iphase2 > iloopMax) iphase2 -= iloopMax; float a = bufData[iphase0]; float b = bufData[iphase]; float c = bufData[iphase1]; float d = bufData[iphase2]; ZXP(out) = cubicinterp(fracphase, a, b, c, d); delTime += delTimeInc; ++phaseIn;); unit->m_delTime = delTime; } } void DelTapRd_next4_a(DelTapRd* unit, int inNumSamples) { SETUP_TAPDELA DELTAP_BUF CHECK_DELTAP_BUF int32 iloopMax = (int32)loopMax; LOCK_SNDBUF_SHARED(buf); LOOP1(inNumSamples, double curDelTimeSamps = ZXP(delTime) * SAMPLERATE; double phase = (double)phaseIn - curDelTimeSamps; if (phase < 0.) phase += loopMax; if (phase >= loopMax) phase -= loopMax; int32 iphase = (int32)phase; int32 iphase0 = iphase - 1; int32 iphase1 = iphase + 1; int32 iphase2 = iphase + 2; if (iphase0 < 0) iphase0 += iloopMax; if (iphase1 > iloopMax) iphase1 -= iloopMax; if (iphase2 > iloopMax) iphase2 -= iloopMax; float fracphase = phase - (double)iphase; float a = bufData[iphase0]; float b = bufData[iphase]; float c = bufData[iphase1]; float d = bufData[iphase2]; ZXP(out) = cubicinterp(fracphase, a, b, c, d); ++phaseIn;); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// PluginLoad(Delay) { ft = inTable; #define DefineInfoUnit(name) (*ft->fDefineUnit)(#name, sizeof(Unit), (UnitCtorFunc)&name##_Ctor, 0, 0); DefineInfoUnit(ControlRate); DefineInfoUnit(SampleRate); DefineInfoUnit(SampleDur); DefineInfoUnit(ControlDur); DefineInfoUnit(SubsampleOffset); DefineInfoUnit(RadiansPerSample); DefineInfoUnit(BlockSize); DefineInfoUnit(NumInputBuses); DefineInfoUnit(NumOutputBuses); DefineInfoUnit(NumAudioBuses); DefineInfoUnit(NumControlBuses); DefineInfoUnit(NumBuffers); DefineInfoUnit(NumRunningSynths); DefineInfoUnit(NodeID); #define DefineBufInfoUnit(name) (*ft->fDefineUnit)(#name, sizeof(BufInfoUnit), (UnitCtorFunc)&name##_Ctor, 0, 0); DefineBufInfoUnit(BufSampleRate); DefineBufInfoUnit(BufRateScale); DefineBufInfoUnit(BufSamples); DefineBufInfoUnit(BufFrames); DefineBufInfoUnit(BufChannels); DefineBufInfoUnit(BufDur); DefineSimpleCantAliasUnit(PlayBuf); #if NOTYET DefineSimpleUnit(SimpleLoopBuf); #endif DefineDtorUnit(RecordBuf); DefineSimpleUnit(BufRd); DefineSimpleUnit(BufWr); DefineDtorUnit(Pitch); DefineSimpleUnit(BufDelayN); DefineSimpleUnit(BufDelayL); DefineSimpleUnit(BufDelayC); DefineSimpleUnit(BufCombN); DefineSimpleUnit(BufCombL); DefineSimpleUnit(BufCombC); DefineSimpleUnit(BufAllpassN); DefineSimpleUnit(BufAllpassL); DefineSimpleUnit(BufAllpassC); #define DefineDelayUnit(name) \ (*ft->fDefineUnit)(#name, sizeof(name), (UnitCtorFunc)&name##_Ctor, (UnitDtorFunc)&DelayUnit_Dtor, 0); DefineDelayUnit(DelayN); DefineDelayUnit(DelayL); DefineDelayUnit(DelayC); DefineDelayUnit(CombN); DefineDelayUnit(CombL); DefineDelayUnit(CombC); DefineDelayUnit(AllpassN); DefineDelayUnit(AllpassL); DefineDelayUnit(AllpassC); DefineDtorUnit(PitchShift); DefineSimpleUnit(GrainTap); DefineSimpleCantAliasUnit(TGrains); DefineDtorUnit(ScopeOut); DefineDtorUnit(ScopeOut2); DefineDelayUnit(Pluck); DefineSimpleUnit(DelTapWr); DefineSimpleUnit(DelTapRd); DefineDtorUnit(LocalBuf); DefineSimpleUnit(MaxLocalBufs); DefineSimpleUnit(SetBuf); DefineSimpleUnit(ClearBuf); } //////////////////////////////////////////////////////////////////////////////////////////////////
270,152
C++
.cpp
5,879
36.269434
120
0.489011
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,954
MulAddUGens.cpp
supercollider_supercollider/server/plugins/MulAddUGens.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "SC_PlugIn.hpp" #include "SIMD_Unit.hpp" static InterfaceTable* ft; namespace { struct MulAdd : SIMD_Unit { ControlRateInput<1> mMul; ControlRateInput<2> mAdd; #define MULADD_CALCFUNC(METHOD_NAME) \ do { \ set_unrolled_calc_function<MulAdd, &MulAdd::METHOD_NAME<unrolled_64>, &MulAdd::METHOD_NAME<unrolled>, \ &MulAdd::METHOD_NAME<scalar>>(); \ return; \ } while (0) MulAdd(void) { mMul.init(this); mAdd.init(this); if (mCalcRate != calc_FullRate) { set_calc_function<MulAdd, &MulAdd::next_scalar>(); return; } assert(inRate(0) == calc_FullRate); switch (inRate(1)) { case calc_FullRate: switch (inRate(2)) { case calc_FullRate: MULADD_CALCFUNC(next_aa); case calc_BufRate: MULADD_CALCFUNC(next_ak); case calc_ScalarRate: if (mAdd == 0.f) MULADD_CALCFUNC(next_a0); else MULADD_CALCFUNC(next_ai); default: assert(false); } case calc_BufRate: switch (inRate(2)) { case calc_FullRate: MULADD_CALCFUNC(next_ka); case calc_BufRate: MULADD_CALCFUNC(next_kk); case calc_ScalarRate: if (mAdd == 0.f) MULADD_CALCFUNC(next_k0); else MULADD_CALCFUNC(next_ki); default: assert(false); } case calc_ScalarRate: switch (inRate(2)) { case calc_FullRate: if (mMul == 1.0) MULADD_CALCFUNC(next_1a); else if (mMul == 0.f) MULADD_CALCFUNC(next_0a); else MULADD_CALCFUNC(next_ia); case calc_BufRate: if (mMul == 1.0) MULADD_CALCFUNC(next_1k); else if (mMul == 0.f) MULADD_CALCFUNC(next_0k); else MULADD_CALCFUNC(next_ik); case calc_ScalarRate: if (mMul == 1.0) { if (mAdd == 0) MULADD_CALCFUNC(next_10); else MULADD_CALCFUNC(next_1i); } else if (mMul == 0.f) { if (mAdd == 0.f) MULADD_CALCFUNC(next_00); else MULADD_CALCFUNC(next_0i); } else { if (mAdd == 0.f) MULADD_CALCFUNC(next_i0); else MULADD_CALCFUNC(next_ii); } default: assert(false); } default: assert(false); } } inline bool mulChanged(void) const { return mMul.changed(this); } inline bool addChanged(void) const { return mAdd.changed(this); } #if __cplusplus <= 199711L nova::detail::scalar_ramp_argument<float> mulSlope(void) #else decltype(nova::slope_argument(0.f, 0.f)) mulSlope(void) #endif { return mMul.slope(this); } #if __cplusplus <= 199711L nova::detail::scalar_ramp_argument<float> addSlope(void) #else decltype(nova::slope_argument(0.f, 0.f)) addSlope(void) #endif { return mAdd.slope(this); } void next_scalar(int inNumSamples) { out0(0) = (in0(0) * in0(1)) + in0(2); } template <int SIMD> void next_aa(int inNumSamples) { muladd<SIMD>(out(0), in(0), in(1), in(2), inNumSamples); } template <int SIMD> void next_ak(int inNumSamples) { if (addChanged()) muladd<SIMD>(out(0), in(0), in(1), addSlope(), inNumSamples); else { if (mAdd == 0.f) times_vec<SIMD>(out(0), in(0), in(1), inNumSamples); else next_ai<SIMD>(inNumSamples); } } template <int SIMD> void next_ai(int inNumSamples) { muladd<SIMD>(out(0), in(0), in(1), mAdd, inNumSamples); } template <int SIMD> void next_ka(int inNumSamples) { if (mulChanged()) muladd<SIMD>(out(0), in(0), mulSlope(), in(2), inNumSamples); else next_ia<SIMD>(inNumSamples); } template <int SIMD> void next_kk(int inNumSamples) { if (addChanged()) { if (mulChanged()) muladd<SIMD>(out(0), in(0), mulSlope(), addSlope(), inNumSamples); else { if (mMul == 0) slope_vec<SIMD>(out(0), addSlope(), inNumSamples); else if (mMul == 1.f) plus_vec<SIMD>(out(0), in(0), addSlope(), inNumSamples); else muladd<SIMD>(out(0), in(0), mMul, addSlope(), inNumSamples); } } else next_ki<SIMD>(inNumSamples); } template <int SIMD> void next_ki(int inNumSamples) { if (mulChanged()) muladd<SIMD>(out(0), in(0), mulSlope(), mAdd, inNumSamples); else next_ii<SIMD>(inNumSamples); } template <int SIMD> void next_ia(int inNumSamples) { if (mMul == 0) next_0a<SIMD>(inNumSamples); else if (mMul == 1.0) next_1a<SIMD>(inNumSamples); else muladd<SIMD>(out(0), in(0), mMul, in(2), inNumSamples); } template <int SIMD> void next_ik(int inNumSamples) { if (addChanged()) { if (mMul == 0.f) slope_vec<SIMD>(out(0), addSlope(), inNumSamples); else if (mMul == 1.f) plus_vec<SIMD>(out(0), in(0), addSlope(), inNumSamples); else muladd<SIMD>(out(0), in(0), mMul, addSlope(), inNumSamples); } else next_ii<SIMD>(inNumSamples); } template <int SIMD> void next_ii(int inNumSamples) { if (mMul == 0) next_0i<SIMD>(inNumSamples); else if (mMul == 1.f) { next_1i<SIMD>(inNumSamples); } else { if (mAdd == 0) times_vec<SIMD>(out(0), in(0), mMul, inNumSamples); else muladd<SIMD>(out(0), in(0), mMul, mAdd, inNumSamples); } } template <int SIMD> void next_1a(int inNumSamples) { plus_vec<SIMD>(out(0), in(0), in(2), inNumSamples); } template <int SIMD> void next_1k(int inNumSamples) { if (addChanged()) plus_vec<SIMD>(out(0), in(0), addSlope(), inNumSamples); else next_1i<SIMD>(inNumSamples); } template <int SIMD> void next_1i(int inNumSamples) { if (mAdd == 0) copy_vec<SIMD>(out(0), in(0), inNumSamples); else plus_vec<SIMD>(out(0), in(0), mAdd, inNumSamples); } template <int SIMD> void next_0a(int inNumSamples) { copy_vec<SIMD>(out(0), in(2), inNumSamples); } template <int SIMD> void next_0k(int inNumSamples) { if (addChanged()) slope_vec<SIMD>(out(0), addSlope(), inNumSamples); else next_0i<SIMD>(inNumSamples); } template <int SIMD> void next_0i(int inNumSamples) { set_vec<SIMD>(out(0), mAdd, inNumSamples); } template <int SIMD> void next_a0(int inNumSamples) { times_vec<SIMD>(out(0), in(0), in(1), inNumSamples); } template <int SIMD> void next_k0(int inNumSamples) { if (mulChanged()) times_vec<SIMD>(out(0), in(0), mulSlope(), inNumSamples); else next_ik<SIMD>(inNumSamples); } template <int SIMD> void next_i0(int inNumSamples) { if (mMul == 0.f) next_00<SIMD>(inNumSamples); else if (mMul == 1.f) next_10<SIMD>(inNumSamples); else times_vec<SIMD>(out(0), in(0), mMul, inNumSamples); } template <int SIMD> void next_10(int inNumSamples) { copy_vec<SIMD>(out(0), in(0), inNumSamples); } template <int SIMD> void next_00(int inNumSamples) { set_vec<SIMD>(out(0), 0.f, inNumSamples); } }; struct Sum3 : SIMD_Unit { ControlRateInput<1> in1; ControlRateInput<2> in2; Sum3(void) { in1.init(this); in2.init(this); if (mCalcRate != calc_FullRate) { set_calc_function<Sum3, &Sum3::next_scalar>(); return; } assert(inRate(0) == calc_FullRate); switch (inRate(1)) { case calc_FullRate: switch (inRate(2)) { case calc_FullRate: set_vector_calc_function<Sum3, &Sum3::next_aaa<true>, &Sum3::next_aaa<false>>(); return; case calc_BufRate: set_vector_calc_function<Sum3, &Sum3::next_aak<true>, &Sum3::next_aak<false>>(); return; case calc_ScalarRate: set_vector_calc_function<Sum3, &Sum3::next_aai<true>, &Sum3::next_aai<false>>(); return; default: assert(false); } case calc_BufRate: switch (inRate(2)) { case calc_BufRate: set_vector_calc_function<Sum3, &Sum3::next_akk<true>, &Sum3::next_akk<false>>(); return; case calc_ScalarRate: set_vector_calc_function<Sum3, &Sum3::next_aki<true>, &Sum3::next_aki<false>>(); return; default: assert(false); } case calc_ScalarRate: assert(inRate(2) == calc_ScalarRate); set_vector_calc_function<Sum3, &Sum3::next_aii<true>, &Sum3::next_aii<false>>(); return; default: assert(false); } } template <bool SIMD, typename Arg1, typename Arg2, typename Arg3> static void sum_vec(float* out, Arg1 const& arg1, Arg2 const& arg2, Arg3 const& arg3, int inNumSamples) { if (SIMD) nova::sum_vec_simd(out, arg1, arg2, arg3, inNumSamples); else nova::sum_vec(out, arg1, arg2, arg3, inNumSamples); } void next_scalar(int inNumSamples) { out0(0) = in0(0) + in0(1) + in0(2); } template <bool SIMD> void next_aaa(int inNumSamples) { sum_vec<SIMD>(out(0), in(0), in(1), in(2), inNumSamples); } template <bool SIMD> void next_aak(int inNumSamples) { if (in2.changed(this)) sum_vec<SIMD>(out(0), in(0), in(1), in2.slope(this), inNumSamples); else next_aai<SIMD>(inNumSamples); } template <bool SIMD> void next_aai(int inNumSamples) { sum_vec<SIMD>(out(0), in(0), in(1), in2, inNumSamples); } template <bool SIMD> void next_aki(int inNumSamples) { if (in1.changed(this)) sum_vec<SIMD>(out(0), in(0), in1.slope(this), in2, inNumSamples); else next_aii<SIMD>(inNumSamples); } template <bool SIMD> void next_akk(int inNumSamples) { if (in2.changed(this)) { if (in1.changed(this)) sum_vec<SIMD>(out(0), in(0), in1.slope(this), in2.slope(this), inNumSamples); else sum_vec<SIMD>(out(0), in(0), in1, in2.slope(this), inNumSamples); } else next_aki<SIMD>(inNumSamples); } template <bool SIMD> void next_aii(int inNumSamples) { sum_vec<SIMD>(out(0), in(0), in0(1), in0(2), inNumSamples); } }; struct Sum4 : SIMD_Unit { ControlRateInput<1> in1; ControlRateInput<2> in2; ControlRateInput<3> in3; Sum4(void) { in1.init(this); in2.init(this); in3.init(this); if (mCalcRate != calc_FullRate) { set_calc_function<Sum4, &Sum4::next_scalar>(); return; } assert(inRate(0) == calc_FullRate); switch (inRate(1)) { case calc_FullRate: switch (inRate(2)) { case calc_FullRate: switch (inRate(3)) { case calc_FullRate: set_vector_calc_function<Sum4, &Sum4::next_aaaa<true>, &Sum4::next_aaaa<false>>(); return; case calc_BufRate: set_vector_calc_function<Sum4, &Sum4::next_aaak<true>, &Sum4::next_aaak<false>>(); return; case calc_ScalarRate: set_vector_calc_function<Sum4, &Sum4::next_aaai<true>, &Sum4::next_aaai<false>>(); return; default: assert(false); } case calc_BufRate: switch (inRate(3)) { case calc_BufRate: set_vector_calc_function<Sum4, &Sum4::next_aakk<true>, &Sum4::next_aakk<false>>(); return; case calc_ScalarRate: set_vector_calc_function<Sum4, &Sum4::next_aaki<true>, &Sum4::next_aaki<false>>(); return; default: assert(false); } case calc_ScalarRate: switch (inRate(3)) { case calc_ScalarRate: set_vector_calc_function<Sum4, &Sum4::next_aaii<true>, &Sum4::next_aaii<false>>(); return; default: assert(false); } } case calc_BufRate: switch (inRate(2)) { case calc_BufRate: switch (inRate(3)) { case calc_BufRate: set_vector_calc_function<Sum4, &Sum4::next_akkk<true>, &Sum4::next_akkk<false>>(); return; case calc_ScalarRate: set_vector_calc_function<Sum4, &Sum4::next_akki<true>, &Sum4::next_akki<false>>(); return; default: assert(false); } case calc_ScalarRate: switch (inRate(3)) { case calc_ScalarRate: set_vector_calc_function<Sum4, &Sum4::next_akii<true>, &Sum4::next_akii<false>>(); return; default: assert(false); } } case calc_ScalarRate: switch (inRate(2)) { case calc_ScalarRate: switch (inRate(3)) { case calc_ScalarRate: set_vector_calc_function<Sum4, &Sum4::next_aiii<true>, &Sum4::next_aiii<false>>(); return; default: assert(false); } default: assert(false); } default: assert(false); } } void next_scalar(int inNumSamples) { out0(0) = in0(0) + in0(1) + in0(2) + in0(3); } template <bool SIMD, typename Arg1, typename Arg2, typename Arg3, typename Arg4> static void sum_vec(float* out, Arg1 const& arg1, Arg2 const& arg2, Arg3 const& arg3, Arg4 const& arg4, int inNumSamples) { if (SIMD) nova::sum_vec_simd(out, arg1, arg2, arg3, arg4, inNumSamples); else nova::sum_vec(out, arg1, arg2, arg3, arg4, inNumSamples); } template <bool SIMD> void next_aaaa(int inNumSamples) { sum_vec<SIMD>(out(0), in(0), in(1), in(2), in(3), inNumSamples); } template <bool SIMD> void next_aaak(int inNumSamples) { if (in3.changed(this)) sum_vec<SIMD>(out(0), in(0), in(1), in(2), in3.slope(this), inNumSamples); else next_aaai<SIMD>(inNumSamples); } template <bool SIMD> void next_aaai(int inNumSamples) { sum_vec<SIMD>(out(0), in(0), in(1), in(2), in3, inNumSamples); } template <bool SIMD> void next_aakk(int inNumSamples) { if (in3.changed(this)) { if (in2.changed(this)) sum_vec<SIMD>(out(0), in(0), in(1), in2.slope(this), in3.slope(this), inNumSamples); else sum_vec<SIMD>(out(0), in(0), in(1), in2, in3.slope(this), inNumSamples); } else next_aaki<SIMD>(inNumSamples); } template <bool SIMD> void next_aaki(int inNumSamples) { if (in2.changed(this)) sum_vec<SIMD>(out(0), in(0), in(1), in2.slope(this), in3, inNumSamples); else next_aaii<SIMD>(inNumSamples); } template <bool SIMD> void next_aaii(int inNumSamples) { sum_vec<SIMD>(out(0), in(0), in(1), in2, in3, inNumSamples); } template <bool SIMD> void next_akkk(int inNumSamples) { if (in3.changed(this)) { if (in2.changed(this)) { if (in1.changed(this)) sum_vec<SIMD>(out(0), in(0), in1.slope(this), in2.slope(this), in3.slope(this), inNumSamples); else sum_vec<SIMD>(out(0), in(0), in1, in2.slope(this), in3.slope(this), inNumSamples); } else { if (in1.changed(this)) sum_vec<SIMD>(out(0), in(0), in1.slope(this), in2, in3.slope(this), inNumSamples); else sum_vec<SIMD>(out(0), in(0), in1, in2, in3.slope(this), inNumSamples); } } else next_akki<SIMD>(inNumSamples); } template <bool SIMD> void next_akki(int inNumSamples) { if (in2.changed(this)) { if (in1.changed(this)) sum_vec<SIMD>(out(0), in(0), in1.slope(this), in2.slope(this), in3, inNumSamples); else sum_vec<SIMD>(out(0), in(0), in1, in2.slope(this), in3, inNumSamples); } else next_akii<SIMD>(inNumSamples); } template <bool SIMD> void next_akii(int inNumSamples) { if (in1.changed(this)) sum_vec<SIMD>(out(0), in(0), in1.slope(this), in2, in3, inNumSamples); else next_aiii<SIMD>(inNumSamples); } template <bool SIMD> void next_aiii(int inNumSamples) { sum_vec<SIMD>(out(0), in(0), in1, in2, in3, inNumSamples); } }; } //////////////////////////////////////////////////////////////////////////////////////////////////////// PluginLoad(MulAdd) { ft = inTable; registerUnit<MulAdd>(ft, "MulAdd"); registerUnit<Sum3>(ft, "Sum3"); registerUnit<Sum4>(ft, "Sum4"); }
19,619
C++
.cpp
482
28.939834
120
0.516292
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,955
IOUGens.cpp
supercollider_supercollider/server/plugins/IOUGens.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "SC_PlugIn.h" #ifdef SC_IPHONE # include "SC_VFP11.h" #endif #ifdef SUPERNOVA # include "nova-tt/spin_lock.hpp" # include "nova-tt/rw_spinlock.hpp" #endif #ifdef NOVA_SIMD # include "simd_memory.hpp" # include "simd_mix.hpp" # include "simd_binary_arithmetic.hpp" # include "function_attributes.h" using nova::slope_argument; #endif #include <boost/align/is_aligned.hpp> static InterfaceTable* ft; ////////////////////////////////////////////////////////////////////////////////////////////////// struct IOUnit : public Unit { int32* m_busTouched; float m_fbusChannel; float* m_bus; }; struct XOut : public IOUnit { float m_xfade; }; struct OffsetOut : public IOUnit { float* m_saved; bool m_empty; }; struct InFeedback : public IOUnit { bool m_busUsedInPrevCycle; }; struct AudioControl : public InFeedback { float* prevVal; // this will have to be a pointer later! float* m_prevBus; }; const int kMaxLags = 16; struct LagControl : public IOUnit { float* m_b1; float* m_y1; }; struct LagIn : public IOUnit { float m_b1; float m_y1[kMaxLags]; }; struct LocalIn : public Unit { float* m_bus; int32* m_busTouched; float* m_realData; }; extern "C" { void Control_Ctor(Unit* inUnit); void Control_next_k(Unit* unit, int inNumSamples); void Control_next_1(Unit* unit, int inNumSamples); void AudioControl_Ctor(AudioControl* inUnit); // void AudioControl_Dtor(AudioControl *inUnit); void AudioControl_next_k(AudioControl* unit, int inNumSamples); void AudioControl_next_1(AudioControl* unit, int inNumSamples); void TrigControl_Ctor(Unit* inUnit); void TrigControl_next_k(Unit* unit, int inNumSamples); void TrigControl_next_1(Unit* unit, int inNumSamples); void LagControl_Ctor(LagControl* inUnit); void LagControl_next_k(LagControl* unit, int inNumSamples); void LagControl_next_1(LagControl* unit, int inNumSamples); void InTrig_Ctor(IOUnit* unit); void InTrig_next_k(IOUnit* unit, int inNumSamples); void In_Ctor(IOUnit* unit); void In_next_a(IOUnit* unit, int inNumSamples); void In_next_k(IOUnit* unit, int inNumSamples); void LagIn_Ctor(LagIn* unit); void LagIn_next_0(LagIn* unit, int inNumSamples); void LagIn_next_k(LagIn* unit, int inNumSamples); void InFeedback_Ctor(InFeedback* unit); void InFeedback_next_a(InFeedback* unit, int inNumSamples); void LocalIn_Ctor(LocalIn* unit); void LocalIn_Dtor(LocalIn* unit); void LocalIn_next_a(LocalIn* unit, int inNumSamples); void LocalIn_next_k(LocalIn* unit, int inNumSamples); void Out_Ctor(IOUnit* unit); void Out_next_a(IOUnit* unit, int inNumSamples); void Out_next_k(IOUnit* unit, int inNumSamples); void XOut_Ctor(XOut* unit); void XOut_next_a(XOut* unit, int inNumSamples); void XOut_next_k(XOut* unit, int inNumSamples); void ReplaceOut_Ctor(IOUnit* unit); void ReplaceOut_next_a(IOUnit* unit, int inNumSamples); void ReplaceOut_next_k(IOUnit* unit, int inNumSamples); void OffsetOut_Ctor(OffsetOut* unit); void OffsetOut_Dtor(OffsetOut* unit); void OffsetOut_next_a(OffsetOut* unit, int inNumSamples); void LocalOut_Ctor(IOUnit* unit); void LocalOut_next_a(IOUnit* unit, int inNumSamples); void LocalOut_next_k(IOUnit* unit, int inNumSamples); } ////////////////////////////////////////////////////////////////////////////////////////////////// void Control_next_k(Unit* unit, int inNumSamples) { uint32 numChannels = unit->mNumOutputs; float** mapin = unit->mParent->mMapControls + unit->mSpecialIndex; for (uint32 i = 0; i < numChannels; ++i, mapin++) { float* out = OUT(i); *out = **mapin; } } void Control_next_1(Unit* unit, int inNumSamples) { float** mapin = unit->mParent->mMapControls + unit->mSpecialIndex; float* out = OUT(0); *out = **mapin; } void Control_Ctor(Unit* unit) { if (unit->mNumOutputs == 1) { SETCALC(Control_next_1); Control_next_1(unit, 1); } else { SETCALC(Control_next_k); Control_next_k(unit, 1); } } ////////////////////////////////////////////////////////////////////////////////////////////////// void AudioControl_next_k(AudioControl* unit, int inNumSamples) { uint32 numChannels = unit->mNumOutputs; float* prevVal = unit->prevVal; float** mapin = unit->mParent->mMapControls + unit->mSpecialIndex; World* world = unit->mWorld; int32 bufCounter = world->mBufCounter; int32* touched = world->mAudioBusTouched; int32* channelOffsets = unit->mParent->mAudioBusOffsets; if (*mapin != unit->m_prevBus) { unit->m_busUsedInPrevCycle = false; unit->m_prevBus = *mapin; } for (uint32 i = 0; i < numChannels; ++i, mapin++) { float* out = OUT(i); int* mapRatep; int mapRate; float nextVal, curVal, valSlope; mapRatep = unit->mParent->mControlRates + unit->mSpecialIndex; mapRate = mapRatep[i]; switch (mapRate) { case 0: { for (int j = 0; j < inNumSamples; j++) { out[j] = *mapin[0]; } } break; case 1: { nextVal = *mapin[0]; curVal = prevVal[i]; valSlope = CALCSLOPE(nextVal, curVal); for (int j = 0; j < inNumSamples; j++) { out[j] = curVal; // should be prevVal curVal += valSlope; } unit->prevVal[i] = curVal; } break; // case 2 - AudioControl is in effect case 2: { /* the graph / unit stores which controls (based on special index) are mapped to which audio buses this is needed to access the touched values for when an audio bus has been written to last. bufCounter is the current value for the control period (basically, the number of control periods that have elapsed since the server started). We check the touched value for the mapped audio bus to see if it has been written to in the current control period or the previous control period (to enable an InFeedback type of mapping)... */ int thisChannelOffset = channelOffsets[unit->mSpecialIndex + i]; bool validOffset = thisChannelOffset >= 0; int diff = bufCounter - touched[thisChannelOffset]; if (validOffset && diff == 0) { Copy(inNumSamples, out, *mapin); unit->m_busUsedInPrevCycle = true; } else if (validOffset && diff == 1) { if (unit->m_busUsedInPrevCycle) { Fill(inNumSamples, out, 0.f); unit->m_busUsedInPrevCycle = false; } else Copy(inNumSamples, out, *mapin); } else { Fill(inNumSamples, out, 0.f); unit->m_busUsedInPrevCycle = false; } } break; } } } void AudioControl_next_1(AudioControl* unit, int inNumSamples) { float** mapin = unit->mParent->mMapControls + unit->mSpecialIndex; float* out = OUT(0); int* mapRatep; int mapRate; float nextVal, curVal, valSlope; float* prevVal; prevVal = unit->prevVal; curVal = prevVal[0]; mapRatep = unit->mParent->mControlRates + unit->mSpecialIndex; mapRate = mapRatep[0]; World* world = unit->mWorld; int32* touched = world->mAudioBusTouched; int32 bufCounter = world->mBufCounter; int32* channelOffsets = unit->mParent->mAudioBusOffsets; if (*mapin != unit->m_prevBus) { unit->m_busUsedInPrevCycle = false; unit->m_prevBus = *mapin; } switch (mapRate) { case 0: { for (int i = 0; i < inNumSamples; i++) { out[i] = *mapin[0]; } } break; case 1: { nextVal = *mapin[0]; valSlope = CALCSLOPE(nextVal, curVal); for (int i = 0; i < inNumSamples; i++) { out[i] = curVal; curVal += valSlope; } unit->prevVal[0] = curVal; } break; /* see case 2 comments above in definition for AudioControl_next_k */ case 2: { int thisChannelOffset = channelOffsets[unit->mSpecialIndex]; bool validOffset = thisChannelOffset >= 0; int diff = bufCounter - touched[thisChannelOffset]; if (validOffset && diff == 0) { Copy(inNumSamples, out, *mapin); unit->m_busUsedInPrevCycle = true; } else if (validOffset && diff == 1) { if (unit->m_busUsedInPrevCycle) { Fill(inNumSamples, out, 0.f); unit->m_busUsedInPrevCycle = false; } else Copy(inNumSamples, out, *mapin); } else { Fill(inNumSamples, out, 0.f); unit->m_busUsedInPrevCycle = false; } } break; } } void AudioControl_Ctor(AudioControl* unit) { unit->prevVal = (float*)RTAlloc(unit->mWorld, unit->mNumOutputs * sizeof(float)); unit->m_prevBus = NULL; ClearUnitIfMemFailed(unit->prevVal); for (int i = 0; i < unit->mNumOutputs; i++) { unit->prevVal[i] = 0.0; } if (unit->mNumOutputs == 1) { SETCALC(AudioControl_next_1); AudioControl_next_1(unit, 1); } else { SETCALC(AudioControl_next_k); AudioControl_next_k(unit, 1); } } void AudioControl_Dtor(AudioControl* unit) { RTFree(unit->mWorld, unit->prevVal); } ////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// void TrigControl_next_k(Unit* unit, int inNumSamples) { uint32 numChannels = unit->mNumOutputs; int specialIndex = unit->mSpecialIndex; Graph* parent = unit->mParent; float** mapin = parent->mMapControls + specialIndex; float* control = parent->mControls + specialIndex; float* buses = unit->mWorld->mControlBus; for (uint32 i = 0; i < numChannels; ++i, mapin++, control++) { float* out = OUT(i); // requires a bit of detective work to see what it has been mapped to. if (*mapin == control) { // read local control. *out = *control; } else { // global control bus. look at time stamp. int busindex = *mapin - buses; *out = buses[busindex]; } // must zero the control even if mapped - otherwise it triggers on unmap *control = 0.f; } } void TrigControl_next_1(Unit* unit, int inNumSamples) { int specialIndex = unit->mSpecialIndex; Graph* parent = unit->mParent; float** mapin = parent->mMapControls + specialIndex; float* control = parent->mControls + specialIndex; float* out = OUT(0); // requires a bit of detective work to see what it has been mapped to. if (*mapin == control) { // read local control. *out = *control; } else { *out = **mapin; } // must zero the control even if mapped - otherwise it triggers on unmap *control = 0.f; } void TrigControl_Ctor(Unit* unit) { // Print("TrigControl_Ctor\n"); if (unit->mNumOutputs == 1) { SETCALC(TrigControl_next_1); } else { SETCALC(TrigControl_next_k); } ClearUnitOutputs(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// void LagControl_next_k(LagControl* unit, int inNumSamples) { uint32 numChannels = unit->mNumOutputs; float** mapin = unit->mParent->mMapControls + unit->mSpecialIndex; for (uint32 i = 0; i < numChannels; ++i, mapin++) { float* out = OUT(i); float z = **mapin; float x = z + unit->m_b1[i] * (unit->m_y1[i] - z); *out = unit->m_y1[i] = zapgremlins(x); } } void LagControl_next_1(LagControl* unit, int inNumSamples) { float** mapin = unit->mParent->mMapControls + unit->mSpecialIndex; float* out = OUT(0); float z = **mapin; float x = z + unit->m_b1[0] * (unit->m_y1[0] - z); *out = unit->m_y1[0] = zapgremlins(x); } void LagControl_Ctor(LagControl* unit) { int numChannels = unit->mNumInputs; float** mapin = unit->mParent->mMapControls + unit->mSpecialIndex; char* chunk = (char*)RTAlloc(unit->mWorld, numChannels * 2 * sizeof(float)); ClearUnitIfMemFailed(chunk); unit->m_y1 = (float*)chunk; unit->m_b1 = unit->m_y1 + numChannels; for (int i = 0; i < numChannels; ++i, mapin++) { unit->m_y1[i] = **mapin; float lag = ZIN0(i); unit->m_b1[i] = lag == 0.f ? 0.f : (float)exp(log001 / (lag * unit->mRate->mSampleRate)); } if (unit->mNumOutputs == 1) { SETCALC(LagControl_next_1); LagControl_next_1(unit, 1); } else { SETCALC(LagControl_next_k); LagControl_next_k(unit, 1); } } void LagControl_Dtor(LagControl* unit) { RTFree(unit->mWorld, unit->m_y1); } ////////////////////////////////////////////////////////////////////////////////////////////////// static inline void IO_a_update_channels(IOUnit* unit, World* world, float fbusChannel, int numChannels, int bufLength) { if (fbusChannel != unit->m_fbusChannel) { unit->m_fbusChannel = fbusChannel; int busChannel = (uint32)fbusChannel; int lastChannel = busChannel + numChannels; if (!(busChannel < 0 || lastChannel > (int)world->mNumAudioBusChannels)) { unit->m_bus = world->mAudioBus + (busChannel * bufLength); unit->m_busTouched = world->mAudioBusTouched + busChannel; } } } template <bool UpdateTouched> static inline void IO_k_update_channels(IOUnit* unit, World* world, float fbusChannel, int numChannels) { if (fbusChannel != unit->m_fbusChannel) { unit->m_fbusChannel = fbusChannel; int busChannel = (int)fbusChannel; int lastChannel = busChannel + numChannels; if (!(busChannel < 0 || lastChannel > (int)world->mNumControlBusChannels)) { unit->m_bus = world->mControlBus + busChannel; if (UpdateTouched) unit->m_busTouched = world->mControlBusTouched + busChannel; } } } template <bool LockShared> struct AudioBusGuard { AudioBusGuard(const Unit* unit, int32 currentChannel, int32 maxChannel): unit(unit), mCurrentChannel(currentChannel), isValid(currentChannel < maxChannel) { if (isValid) lock(); } ~AudioBusGuard() { if (isValid) unlock(); } void lock() { if (LockShared) ACQUIRE_BUS_AUDIO_SHARED(mCurrentChannel); else ACQUIRE_BUS_AUDIO(mCurrentChannel); } void unlock() { if (LockShared) RELEASE_BUS_AUDIO_SHARED(mCurrentChannel); else RELEASE_BUS_AUDIO(mCurrentChannel); } const Unit* unit; const int32 mCurrentChannel; const bool isValid; }; #ifdef NOVA_SIMD FLATTEN void In_next_a_nova(IOUnit* unit, int inNumSamples) { World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumOutputs; float fbusChannel = ZIN0(0); IO_a_update_channels(unit, world, fbusChannel, numChannels, bufLength); float* in = unit->m_bus; int32* touched = unit->m_busTouched; const int32 bufCounter = unit->mWorld->mBufCounter; const int32 maxChannel = world->mNumAudioBusChannels; for (int i = 0; i < numChannels; ++i, in += bufLength) { AudioBusGuard<true> guard(unit, fbusChannel + i, maxChannel); float* out = OUT(i); if (guard.isValid && (touched[i] == bufCounter)) nova::copyvec_simd(out, in, inNumSamples); else nova::zerovec_simd(out, inNumSamples); } } FLATTEN void In_next_a_nova_64(IOUnit* unit, int inNumSamples) { World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumOutputs; float fbusChannel = ZIN0(0); IO_a_update_channels(unit, world, fbusChannel, numChannels, bufLength); float* in = unit->m_bus; int32* touched = unit->m_busTouched; const int32 bufCounter = unit->mWorld->mBufCounter; const int32 maxChannel = world->mNumAudioBusChannels; for (int i = 0; i < numChannels; ++i, in += bufLength) { AudioBusGuard<true> guard(unit, fbusChannel + i, maxChannel); float* out = OUT(i); if (guard.isValid && (touched[i] == bufCounter)) nova::copyvec_simd<64>(out, in); else nova::zerovec_simd<64>(out); } } #endif void In_next_a(IOUnit* unit, int inNumSamples) { World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumOutputs; float fbusChannel = ZIN0(0); IO_a_update_channels(unit, world, fbusChannel, numChannels, bufLength); float* in = unit->m_bus; int32* touched = unit->m_busTouched; const int32 bufCounter = unit->mWorld->mBufCounter; const int32 maxChannel = world->mNumAudioBusChannels; for (int i = 0; i < numChannels; ++i, in += bufLength) { AudioBusGuard<true> guard(unit, fbusChannel + i, maxChannel); float* out = OUT(i); if (guard.isValid && (touched[i] == bufCounter)) Copy(inNumSamples, out, in); else Fill(inNumSamples, out, 0.f); } } #ifdef IPHONE_VEC void vIn_next_a(IOUnit* unit, int inNumSamples) { World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumOutputs; float fbusChannel = ZIN0(0); IO_a_update_channels(unit, world, fbusChannel, numChannels, bufLength); float* in = unit->m_bus; int32* touched = unit->m_busTouched; const int32 bufCounter = unit->mWorld->mBufCounter; const int32 maxChannel = world->mNumAudioBusChannels; for (int i = 0; i < numChannels; ++i, in += bufLength) { AudioBusGuard<true> guard(unit, fbusChannel + i, maxChannel); float* out = OUT(i); if (guard.isValid && (touched[i] == bufCounter)) vcopy(out, in, inNumSamples); else vfill(out, 0.f, inNumSamples); } } #endif static inline float readControlBus(const float* bus, int channelIndex, int maxChannel) { if (channelIndex < maxChannel) return *bus; else return 0; } void In_next_k(IOUnit* unit, int inNumSamples) { World* world = unit->mWorld; uint32 numChannels = unit->mNumOutputs; float fbusChannel = ZIN0(0); IO_k_update_channels<false>(unit, world, fbusChannel, numChannels); const int32 maxChannel = world->mNumControlBusChannels; const int32 firstOutputChannel = (int)fbusChannel; const float* in = unit->m_bus; for (uint32 i = 0; i < numChannels; ++i, in++) OUT0(i) = readControlBus(in, firstOutputChannel + i, maxChannel); } void In_Ctor(IOUnit* unit) { // Print("->In_Ctor\n"); World* world = unit->mWorld; unit->m_fbusChannel = std::numeric_limits<float>::quiet_NaN(); if (unit->mCalcRate == calc_FullRate) { #ifdef NOVA_SIMD if (BUFLENGTH == 64) SETCALC(In_next_a_nova_64); else if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(In_next_a_nova); else #endif SETCALC(In_next_a); unit->m_bus = world->mAudioBus; unit->m_busTouched = world->mAudioBusTouched; In_next_a(unit, 1); } else { SETCALC(In_next_k); unit->m_bus = world->mControlBus; // unit->m_busTouched = world->mControlBusTouched; In_next_k(unit, 1); } // Print("<-In_Ctor\n"); } ////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// void LagIn_next_k(LagIn* unit, int inNumSamples) { World* world = unit->mWorld; int numChannels = unit->mNumOutputs; float fbusChannel = ZIN0(0); IO_k_update_channels<false>(unit, world, fbusChannel, numChannels); const int32 maxChannel = world->mNumControlBusChannels; const int32 firstOutputChannel = (int)fbusChannel; const float* in = unit->m_bus; float b1 = unit->m_b1; float* y1 = unit->m_y1; for (int i = 0; i < numChannels; ++i, in++) { float z = readControlBus(in, firstOutputChannel + i, maxChannel); float x = z + b1 * (y1[i] - z); OUT0(i) = y1[i] = zapgremlins(x); } } void LagIn_next_0(LagIn* unit, int inNumSamples) { World* world = unit->mWorld; int numChannels = unit->mNumOutputs; float fbusChannel = ZIN0(0); IO_k_update_channels<false>(unit, world, fbusChannel, numChannels); const int32 maxChannel = world->mNumControlBusChannels; const int32 firstOutputChannel = (int)fbusChannel; const float* in = unit->m_bus; float* y1 = unit->m_y1; for (int i = 0; i < numChannels; ++i, in++) OUT0(i) = y1[i] = readControlBus(in, firstOutputChannel + i, maxChannel); } void LagIn_Ctor(LagIn* unit) { World* world = unit->mWorld; unit->m_fbusChannel = -1.; float lag = ZIN0(1); unit->m_b1 = lag == 0.f ? 0.f : (float)exp(log001 / (lag * unit->mRate->mSampleRate)); SETCALC(LagIn_next_k); unit->m_bus = world->mControlBus; LagIn_next_0(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// void InFeedback_next_a(InFeedback* unit, int inNumSamples) { World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumOutputs; float fbusChannel = ZIN0(0); if (fbusChannel != unit->m_fbusChannel) unit->m_busUsedInPrevCycle = false; IO_a_update_channels(unit, world, fbusChannel, numChannels, bufLength); float* in = unit->m_bus; int32* touched = unit->m_busTouched; const int32 bufCounter = unit->mWorld->mBufCounter; const int32 maxChannel = world->mNumAudioBusChannels; for (int i = 0; i < numChannels; ++i, in += bufLength) { AudioBusGuard<true> guard(unit, fbusChannel + i, maxChannel); float* out = OUT(i); int diff = bufCounter - touched[i]; if (guard.isValid && diff == 0) { Copy(inNumSamples, out, in); unit->m_busUsedInPrevCycle = true; } else if (guard.isValid && diff == 1) { if (unit->m_busUsedInPrevCycle) { Fill(inNumSamples, out, 0.f); unit->m_busUsedInPrevCycle = false; } else Copy(inNumSamples, out, in); } else { Fill(inNumSamples, out, 0.f); unit->m_busUsedInPrevCycle = false; } } } void InFeedback_Ctor(InFeedback* unit) { // Print("->InFeedback_Ctor\n"); World* world = unit->mWorld; unit->m_fbusChannel = -1.; SETCALC(InFeedback_next_a); unit->m_bus = world->mAudioBus; unit->m_busTouched = world->mAudioBusTouched; InFeedback_next_a(unit, 1); // Print("<-InFeedback_Ctor\n"); } ////////////////////////////////////////////////////////////////////////////////////////////////// void InTrig_next_k(IOUnit* unit, int inNumSamples) { World* world = unit->mWorld; int numChannels = unit->mNumOutputs; float fbusChannel = ZIN0(0); IO_k_update_channels<true>(unit, world, fbusChannel, numChannels); const int32 maxChannel = world->mNumControlBusChannels; const int32 firstOutputChannel = (int)fbusChannel; const float* in = unit->m_bus; int32* touched = unit->m_busTouched; int32 bufCounter = unit->mWorld->mBufCounter; for (int i = 0; i < numChannels; ++i, in++) { float* out = OUT(i); if (touched[i] == bufCounter) *out = readControlBus(in, firstOutputChannel + i, maxChannel); else *out = 0.f; } } void InTrig_Ctor(IOUnit* unit) { World* world = unit->mWorld; unit->m_fbusChannel = -1.; if (unit->mCalcRate == calc_FullRate) { SETCALC(ClearUnitOutputs); ClearUnitOutputs(unit, 1); } else { SETCALC(InTrig_next_k); unit->m_bus = world->mControlBus; unit->m_busTouched = world->mControlBusTouched; InTrig_next_k(unit, 1); } } ////////////////////////////////////////////////////////////////////////////////////////////////// void ReplaceOut_next_a(IOUnit* unit, int inNumSamples) { World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumInputs - 1; float fbusChannel = ZIN0(0); IO_a_update_channels(unit, world, fbusChannel, numChannels, bufLength); float* out = unit->m_bus; int32* touched = unit->m_busTouched; const int32 bufCounter = unit->mWorld->mBufCounter; const int32 maxChannel = world->mNumAudioBusChannels; for (int i = 0; i < numChannels; ++i, out += bufLength) { AudioBusGuard<false> guard(unit, fbusChannel + i, maxChannel); if (guard.isValid) { float* in = IN(i + 1); Copy(inNumSamples, out, in); touched[i] = bufCounter; } } } void ReplaceOut_next_k(IOUnit* unit, int inNumSamples) { World* world = unit->mWorld; int numChannels = unit->mNumInputs - 1; float fbusChannel = ZIN0(0); IO_k_update_channels<true>(unit, world, fbusChannel, numChannels); const int32 maxChannel = world->mNumControlBusChannels; const int32 firstOutputChannel = (int)fbusChannel; float* out = unit->m_bus; int32* touched = unit->m_busTouched; int32 bufCounter = unit->mWorld->mBufCounter; for (int i = 0; i < numChannels; ++i, out++) { if (firstOutputChannel + i < maxChannel) { float* in = IN(i + 1); ACQUIRE_BUS_CONTROL((int32)fbusChannel + i); *out = *in; touched[i] = bufCounter; RELEASE_BUS_CONTROL((int32)fbusChannel + i); } } } #ifdef NOVA_SIMD FLATTEN void ReplaceOut_next_a_nova(IOUnit* unit, int inNumSamples) { World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumInputs - 1; float fbusChannel = ZIN0(0); IO_a_update_channels(unit, world, fbusChannel, numChannels, bufLength); float* out = unit->m_bus; int32* touched = unit->m_busTouched; const int32 bufCounter = unit->mWorld->mBufCounter; const int32 maxChannel = world->mNumAudioBusChannels; for (int i = 0; i < numChannels; ++i, out += bufLength) { AudioBusGuard<false> guard(unit, fbusChannel + i, maxChannel); if (guard.isValid) { float* in = IN(i + 1); nova::copyvec_simd(out, in, inNumSamples); touched[i] = bufCounter; } } } FLATTEN void ReplaceOut_next_a_nova_64(IOUnit* unit, int inNumSamples) { World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumInputs - 1; float fbusChannel = ZIN0(0); IO_a_update_channels(unit, world, fbusChannel, numChannels, bufLength); float* out = unit->m_bus; int32* touched = unit->m_busTouched; const int32 bufCounter = unit->mWorld->mBufCounter; const int32 maxChannel = world->mNumAudioBusChannels; for (int i = 0; i < numChannels; ++i, out += bufLength) { AudioBusGuard<false> guard(unit, fbusChannel + i, maxChannel); if (guard.isValid) { float* in = IN(i + 1); nova::copyvec_simd<64>(out, in); touched[i] = bufCounter; } } } #endif /* NOVA_SIMD */ void ReplaceOut_Ctor(IOUnit* unit) { World* world = unit->mWorld; unit->m_fbusChannel = -1.; if (unit->mCalcRate == calc_FullRate) { #ifdef NOVA_SIMD if (BUFLENGTH == 64) SETCALC(ReplaceOut_next_a_nova_64); else if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(ReplaceOut_next_a_nova); else #endif SETCALC(ReplaceOut_next_a); unit->m_bus = world->mAudioBus; unit->m_busTouched = world->mAudioBusTouched; } else { SETCALC(ReplaceOut_next_k); unit->m_bus = world->mControlBus; unit->m_busTouched = world->mControlBusTouched; } } ////////////////////////////////////////////////////////////////////////////////////////////////// void Out_next_a(IOUnit* unit, int inNumSamples) { // Print("Out_next_a %d\n", unit->mNumInputs); World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumInputs - 1; float fbusChannel = ZIN0(0); IO_a_update_channels(unit, world, fbusChannel, numChannels, bufLength); float* out = unit->m_bus; int32* touched = unit->m_busTouched; const int32 bufCounter = unit->mWorld->mBufCounter; const int32 maxChannel = world->mNumAudioBusChannels; for (int i = 0; i < numChannels; ++i, out += bufLength) { AudioBusGuard<false> guard(unit, fbusChannel + i, maxChannel); if (guard.isValid) { float* in = IN(i + 1); if (touched[i] == bufCounter) Accum(inNumSamples, out, in); else { Copy(inNumSamples, out, in); touched[i] = bufCounter; } } } } #ifdef IPHONE_VEC void vOut_next_a(IOUnit* unit, int inNumSamples) { // Print("Out_next_a %d\n", unit->mNumInputs); World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumInputs - 1; float fbusChannel = ZIN0(0); IO_a_update_channels(unit, world, fbusChannel, numChannels, bufLength); float* out = unit->m_bus; int32* touched = unit->m_busTouched; int32 bufCounter = unit->mWorld->mBufCounter; for (int i = 0; i < numChannels; ++i, out += bufLength) { AudioBusGuard<false> guard(unit, fbusChannel + i, maxChannel); if (guard.isValid) { float* in = IN(i + 1); if (touched[i] == bufCounter) { vadd(out, out, in, inNumSamples); } else { vcopy(out, in, inNumSamples); touched[i] = bufCounter; } } } } #endif #ifdef NOVA_SIMD FLATTEN void Out_next_a_nova(IOUnit* unit, int inNumSamples) { World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumInputs - 1; float fbusChannel = ZIN0(0); IO_a_update_channels(unit, world, fbusChannel, numChannels, bufLength); float* out = unit->m_bus; int32* touched = unit->m_busTouched; const int32 bufCounter = unit->mWorld->mBufCounter; const int32 maxChannel = world->mNumAudioBusChannels; for (int i = 0; i < numChannels; ++i, out += bufLength) { AudioBusGuard<false> guard(unit, fbusChannel + i, maxChannel); if (guard.isValid) { float* in = IN(i + 1); if (touched[i] == bufCounter) nova::addvec_simd(out, in, inNumSamples); else { nova::copyvec_simd(out, in, inNumSamples); touched[i] = bufCounter; } } } } FLATTEN void Out_next_a_nova_64(IOUnit* unit, int inNumSamples) { // Print("Out_next_a %d\n", unit->mNumInputs); World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumInputs - 1; float fbusChannel = ZIN0(0); IO_a_update_channels(unit, world, fbusChannel, numChannels, bufLength); float* out = unit->m_bus; int32* touched = unit->m_busTouched; const int32 bufCounter = unit->mWorld->mBufCounter; const int32 maxChannel = world->mNumAudioBusChannels; for (int i = 0; i < numChannels; ++i, out += bufLength) { AudioBusGuard<false> guard(unit, fbusChannel + i, maxChannel); if (guard.isValid) { float* in = IN(i + 1); if (touched[i] == bufCounter) nova::addvec_simd<64>(out, in); else { nova::copyvec_simd<64>(out, in); touched[i] = bufCounter; } } } } #endif void Out_next_k(IOUnit* unit, int inNumSamples) { World* world = unit->mWorld; int numChannels = unit->mNumInputs - 1; float fbusChannel = ZIN0(0); IO_k_update_channels<true>(unit, world, fbusChannel, numChannels); const int32 maxChannel = world->mNumControlBusChannels; const int32 firstOutputChannel = (int)fbusChannel; float* out = unit->m_bus; int32* touched = unit->m_busTouched; int32 bufCounter = unit->mWorld->mBufCounter; for (int i = 0; i < numChannels; ++i, out++) { if (firstOutputChannel + i < maxChannel) { float* in = IN(i + 1); ACQUIRE_BUS_CONTROL((int32)fbusChannel + i); if (touched[i] == bufCounter) *out += *in; else { *out = *in; touched[i] = bufCounter; } RELEASE_BUS_CONTROL((int32)fbusChannel + i); } } } void Out_Ctor(IOUnit* unit) { // Print("->Out_Ctor\n"); World* world = unit->mWorld; unit->m_fbusChannel = -1.; if (unit->mCalcRate == calc_FullRate) { #if defined(NOVA_SIMD) if (BUFLENGTH == 64) SETCALC(Out_next_a_nova_64); else if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(Out_next_a_nova); else SETCALC(Out_next_a); #else # ifdef IPHONE_VEC SETCALC(vOut_next_a); # else SETCALC(Out_next_a); # endif #endif unit->m_bus = world->mAudioBus; unit->m_busTouched = world->mAudioBusTouched; } else { SETCALC(Out_next_k); unit->m_bus = world->mControlBus; unit->m_busTouched = world->mControlBusTouched; } // Print("<-Out_Ctor\n"); } ////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// void XOut_next_a(XOut* unit, int inNumSamples) { World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumInputs - 2; float fbusChannel = ZIN0(0); IO_a_update_channels(unit, world, fbusChannel, numChannels, bufLength); float next_xfade = ZIN0(1); float xfade0 = unit->m_xfade; float* out = unit->m_bus; int32* touched = unit->m_busTouched; const int32 bufCounter = unit->mWorld->mBufCounter; const int32 maxChannel = world->mNumAudioBusChannels; if (xfade0 != next_xfade) { float slope = CALCSLOPE(next_xfade, xfade0); for (int i = 0; i < numChannels; ++i) { AudioBusGuard<false> guard(unit, fbusChannel + i, maxChannel); if (guard.isValid) { float xfade = xfade0; float* in = IN(i + 2); if (touched[i] == bufCounter) { LOOP1(inNumSamples, float zin = *in; float zout = *out; *out = zout + xfade * (zin - zout); // if (xxi==0) Print("x %d %d %g %g %g %g\n", bufCounter, i, zin, zout, xfade, *out); xfade += slope; ++out; ++in;); } else { LOOP1(inNumSamples, float zin = *in; *out = xfade * zin; xfade += slope; ++out; ++in;); touched[i] = bufCounter; } } } } else if (xfade0 == 1.f) { for (int i = 0; i < numChannels; ++i, out += bufLength) { AudioBusGuard<false> guard(unit, fbusChannel + i, maxChannel); if (guard.isValid) { float* in = IN(i + 2); Copy(inNumSamples, out, in); touched[i] = bufCounter; } } } else if (xfade0 == 0.f) { // do nothing. } else { for (int i = 0; i < numChannels; ++i) { AudioBusGuard<false> guard(unit, fbusChannel + i, maxChannel); if (guard.isValid) { float* in = IN(i + 2); if (touched[i] == bufCounter) { LOOP1(inNumSamples, float zin = *in; float zout = *out; *out = zout + xfade0 * (zin - zout); ++out; ++in;); } else { LOOP1(inNumSamples, float zin = *in; *out = xfade0 * zin; ++out; ++in;); touched[i] = bufCounter; } } } } unit->m_xfade = next_xfade; } #ifdef NOVA_SIMD FLATTEN void XOut_next_a_nova(XOut* unit, int inNumSamples) { World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumInputs - 2; float fbusChannel = ZIN0(0); IO_a_update_channels(unit, world, fbusChannel, numChannels, bufLength); float next_xfade = ZIN0(1); float xfade0 = unit->m_xfade; float* out = unit->m_bus; int32* touched = unit->m_busTouched; const int32 bufCounter = unit->mWorld->mBufCounter; const int32 maxChannel = world->mNumAudioBusChannels; if (xfade0 != next_xfade) { float slope = CALCSLOPE(next_xfade, xfade0); for (int i = 0; i < numChannels; ++i) { AudioBusGuard<false> guard(unit, fbusChannel + i, maxChannel); if (guard.isValid) { float xfade = xfade0; float* in = IN(i + 2); if (touched[i] == bufCounter) nova::mix_vec_simd(out, out, slope_argument(1 - xfade0, -slope), in, slope_argument(xfade0, slope), inNumSamples); else { nova::times_vec_simd(out, in, slope_argument(xfade, slope), inNumSamples); touched[i] = bufCounter; } } } unit->m_xfade = next_xfade; } else if (xfade0 == 1.f) { for (int i = 0; i < numChannels; ++i, out += bufLength) { AudioBusGuard<false> guard(unit, fbusChannel + i, maxChannel); if (guard.isValid) { float* in = IN(i + 2); nova::copyvec_simd(out, in, inNumSamples); touched[i] = bufCounter; } } } else if (xfade0 == 0.f) { // do nothing. } else { for (int i = 0; i < numChannels; ++i) { AudioBusGuard<false> guard(unit, fbusChannel + i, maxChannel); if (guard.isValid) { float* in = IN(i + 2); if (touched[i] == bufCounter) nova::mix_vec_simd(out, out, 1 - xfade0, in, xfade0, inNumSamples); else { nova::times_vec_simd(out, in, xfade0, inNumSamples); touched[i] = bufCounter; } } } } } #endif void XOut_next_k(XOut* unit, int inNumSamples) { World* world = unit->mWorld; int numChannels = unit->mNumInputs - 2; float fbusChannel = ZIN0(0); IO_k_update_channels<true>(unit, world, fbusChannel, numChannels); const int32 maxChannel = world->mNumControlBusChannels; const int32 firstOutputChannel = (int)fbusChannel; float xfade = ZIN0(1); float* out = unit->m_bus; int32* touched = unit->m_busTouched; int32 bufCounter = unit->mWorld->mBufCounter; for (int i = 0; i < numChannels; ++i, out++) { if (firstOutputChannel + i < maxChannel) { float* in = IN(i + 2); ACQUIRE_BUS_CONTROL((int32)fbusChannel + i); if (touched[i] == bufCounter) { float zin = *in; float zout = *out; *out = zout + xfade * (zin - zout); } else { *out = xfade * *in; touched[i] = bufCounter; } RELEASE_BUS_CONTROL((int32)fbusChannel + i); } } } void XOut_Ctor(XOut* unit) { // Print("->Out_Ctor\n"); World* world = unit->mWorld; unit->m_fbusChannel = -1.; unit->m_xfade = ZIN0(1); if (unit->mCalcRate == calc_FullRate) { #ifdef NOVA_SIMD if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(XOut_next_a_nova); #endif SETCALC(XOut_next_a); unit->m_bus = world->mAudioBus; unit->m_busTouched = world->mAudioBusTouched; } else { SETCALC(XOut_next_k); unit->m_bus = world->mControlBus; unit->m_busTouched = world->mControlBusTouched; } // Print("<-Out_Ctor\n"); } ////////////////////////////////////////////////////////////////////////////////////////////////// void OffsetOut_next_a(OffsetOut* unit, int inNumSamples) { World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumInputs - 1; float fbusChannel = ZIN0(0); IO_a_update_channels(unit, world, fbusChannel, numChannels, bufLength); int32 offset = unit->mParent->mSampleOffset; int32 remain = BUFLENGTH - offset; float* out = unit->m_bus; float* saved = unit->m_saved; int32* touched = unit->m_busTouched; const int32 bufCounter = unit->mWorld->mBufCounter; const int32 maxChannel = world->mNumAudioBusChannels; for (int i = 0; i < numChannels; ++i, out += bufLength, saved += offset) { AudioBusGuard<false> guard(unit, fbusChannel + i, maxChannel); float* in = IN(i + 1); // Print("out %d %d %d %d %d\n", // i, touched[i] == bufCounter, unit->m_empty, // offset, remain); if (guard.isValid) { if (touched[i] == bufCounter) { if (unit->m_empty) { // Print("touched offset %d\n", offset); } else { Accum(offset, out, saved); } Accum(remain, out + offset, in); } else { if (unit->m_empty) { Clear(offset, out); // Print("untouched offset %d\n", offset); } else { Copy(offset, out, saved); } Copy(remain, out + offset, in); touched[i] = bufCounter; } } Copy(offset, saved, in + remain); // Print("out %d %d %d %g %g\n", i, in[0], out[0]); } unit->m_empty = false; } void OffsetOut_Ctor(OffsetOut* unit) { // Print("->Out_Ctor\n"); World* world = unit->mWorld; unit->m_fbusChannel = -1.; SETCALC(OffsetOut_next_a); unit->m_bus = world->mAudioBus; unit->m_busTouched = world->mAudioBusTouched; int32 offset = unit->mParent->mSampleOffset; int numChannels = unit->mNumInputs - 1; // NB: if mSampleOffset is 0, RTAlloc() might return a nullptr and // trigger ClearUnitIfMemFailed(), so we have to handle it specially. if (offset > 0) { unit->m_saved = (float*)RTAlloc(unit->mWorld, offset * numChannels * sizeof(float)); ClearUnitIfMemFailed(unit->m_saved); } else { unit->m_saved = nullptr; } unit->m_empty = true; // Print("<-Out_Ctor\n"); } void OffsetOut_Dtor(OffsetOut* unit) { // Write remaining samples (if any) if (unit->m_saved) { World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumInputs - 1; int32 offset = unit->mParent->mSampleOffset; int32 remain = BUFLENGTH - offset; float* out = unit->m_bus; float* saved = unit->m_saved; int32* touched = unit->m_busTouched; int32 bufCounter = unit->mWorld->mBufCounter; for (int i = 0; i < numChannels; ++i, out += bufLength, saved += offset) { // Print("out %d %d %d %d %d\n", // i, touched[i] == bufCounter, unit->m_empty, // offset, remain); if (!unit->m_empty) { if (touched[i] == bufCounter) { Accum(offset, out, saved); } else { Copy(offset, out, saved); Clear(remain, out + offset); touched[i] = bufCounter; } } // Print("out %d %d %d %g %g\n", i, in[0], out[0]); } RTFree(unit->mWorld, unit->m_saved); } } ////////////////////////////////////////////////////////////////////////////////////////////////// void SharedIn_next_k(IOUnit* unit, int inNumSamples) { // Print("->SharedIn_next_k\n"); World* world = unit->mWorld; int numChannels = unit->mNumOutputs; float fbusChannel = ZIN0(0); if (fbusChannel != unit->m_fbusChannel) { unit->m_fbusChannel = fbusChannel; uint32 busChannel = (uint32)fbusChannel; uint32 lastChannel = busChannel + numChannels; if (!(lastChannel > world->mNumSharedControls)) { unit->m_bus = world->mSharedControls + busChannel; } } float* in = unit->m_bus; if (in) { for (int i = 0; i < numChannels; ++i, in++) { float* out = OUT(i); *out = *in; } } else { ClearUnitOutputs(unit, 1); } // Print("<-SharedIn_next_k\n"); } void SharedIn_Ctor(IOUnit* unit) { // Print("->SharedIn_Ctor\n"); World* world = unit->mWorld; unit->m_fbusChannel = -1.; SETCALC(SharedIn_next_k); unit->m_bus = world->mSharedControls; SharedIn_next_k(unit, 1); // Print("<-SharedIn_Ctor\n"); } ////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// void SharedOut_next_k(IOUnit* unit, int inNumSamples) { // Print("->SharedOut_next_k\n"); World* world = unit->mWorld; int numChannels = unit->mNumInputs - 1; float fbusChannel = ZIN0(0); if (fbusChannel != unit->m_fbusChannel) { unit->m_fbusChannel = fbusChannel; uint32 busChannel = (uint32)fbusChannel; uint32 lastChannel = busChannel + numChannels; if (!(lastChannel > world->mNumSharedControls)) { unit->m_bus = world->mSharedControls + busChannel; } } float* out = unit->m_bus; if (out) { for (int i = 1; i < numChannels + 1; ++i, out++) { float* in = IN(i); *out = *in; } } // Print("<-SharedOut_next_k\n"); } void SharedOut_Ctor(IOUnit* unit) { // Print("->SharedOut_Ctor\n"); World* world = unit->mWorld; unit->m_fbusChannel = -1.; SETCALC(SharedOut_next_k); unit->m_bus = world->mSharedControls; SharedOut_next_k(unit, 1); // Print("<-SharedOut_Ctor\n"); } ////////////////////////////////////////////////////////////////////////////////////////////////// void LocalIn_next_a(LocalIn* unit, int inNumSamples) { World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumOutputs; float* in = unit->m_bus; int32* touched = unit->m_busTouched; int32 bufCounter = unit->mWorld->mBufCounter; for (int i = 0; i < numChannels; ++i, in += bufLength) { float* out = OUT(i); int diff = bufCounter - touched[i]; // Print("LocalIn %d %d %g\n", i, diff, in[0]); if (diff == 1 || diff == 0) Copy(inNumSamples, out, in); else Fill(inNumSamples, out, IN0(i)); } } #ifdef NOVA_SIMD FLATTEN void LocalIn_next_a_nova(LocalIn* unit, int inNumSamples) { World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumOutputs; float* in = unit->m_bus; int32* touched = unit->m_busTouched; int32 bufCounter = unit->mWorld->mBufCounter; for (int i = 0; i < numChannels; ++i, in += bufLength) { float* out = OUT(i); int diff = bufCounter - touched[i]; // Print("LocalIn %d %d %g\n", i, diff, in[0]); if (diff == 1 || diff == 0) nova::copyvec_simd(out, in, inNumSamples); else // nova::zerovec_simd(out, inNumSamples); Fill(inNumSamples, out, IN0(i)); } } FLATTEN void LocalIn_next_a_nova_64(LocalIn* unit, int inNumSamples) { World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumOutputs; float* in = unit->m_bus; int32* touched = unit->m_busTouched; int32 bufCounter = unit->mWorld->mBufCounter; for (int i = 0; i < numChannels; ++i, in += bufLength) { float* out = OUT(i); int diff = bufCounter - touched[i]; // Print("LocalIn %d %d %g\n", i, diff, in[0]); if (diff == 1 || diff == 0) nova::copyvec_simd<64>(out, in); else // nova::zerovec_simd<64>(out); Fill(inNumSamples, out, IN0(i)); } } #endif void LocalIn_next_k(LocalIn* unit, int inNumSamples) { uint32 numChannels = unit->mNumOutputs; float* in = unit->m_bus; int32* touched = unit->m_busTouched; int32 bufCounter = unit->mWorld->mBufCounter; for (uint32 i = 0; i < numChannels; ++i, in++) { int diff = bufCounter - touched[i]; float* out = OUT(i); if (diff == 1 || diff == 0) *out = *in; else *out = IN0(i); } } void LocalIn_Ctor(LocalIn* unit) { // Print("->LocalIn_Ctor\n"); int numChannels = unit->mNumOutputs; World* world = unit->mWorld; int busDataSize = numChannels * BUFLENGTH; // align the buffer to 256 bytes so that we can use avx instructions unit->m_realData = (float*)RTAlloc(world, busDataSize * sizeof(float) + numChannels * sizeof(int32) + 32 * sizeof(float)); ClearUnitIfMemFailed(unit->m_realData); size_t alignment = (size_t)unit->m_realData & 31; unit->m_bus = alignment ? (float*)(size_t(unit->m_realData + 32) & ~31) : unit->m_realData; unit->m_busTouched = (int32*)(unit->m_bus + busDataSize); for (int i = 0; i < numChannels; ++i) unit->m_busTouched[i] = -1; if (unit->mCalcRate == calc_FullRate) { if (unit->mParent->mLocalAudioBusUnit) { SETCALC(ClearUnitOutputs); ClearUnitOutputs(unit, 1); return; } unit->mParent->mLocalAudioBusUnit = unit; #ifdef NOVA_SIMD if (BUFLENGTH == 64) SETCALC(LocalIn_next_a_nova_64); else if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(LocalIn_next_a_nova); else #endif SETCALC(LocalIn_next_a); LocalIn_next_a(unit, 1); } else { if (unit->mParent->mLocalControlBusUnit) { SETCALC(ClearUnitOutputs); ClearUnitOutputs(unit, 1); return; } unit->mParent->mLocalControlBusUnit = unit; SETCALC(LocalIn_next_k); LocalIn_next_k(unit, 1); } // Print("<-LocalIn_Ctor\n"); } void LocalIn_Dtor(LocalIn* unit) { World* world = unit->mWorld; RTFree(world, unit->m_realData); } ////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// void LocalOut_next_a(IOUnit* unit, int inNumSamples) { // Print("LocalOut_next_a %d\n", unit->mNumInputs); World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumInputs; LocalIn* localIn = (LocalIn*)unit->mParent->mLocalAudioBusUnit; if (!localIn) return; float* out = localIn->m_bus; if ((out == nullptr) || (numChannels != localIn->mNumOutputs)) return; int32* touched = localIn->m_busTouched; int32 bufCounter = unit->mWorld->mBufCounter; for (int i = 0; i < numChannels; ++i, out += bufLength) { float* in = IN(i); if (touched[i] == bufCounter) Accum(inNumSamples, out, in); else { Copy(inNumSamples, out, in); touched[i] = bufCounter; } // Print("LocalOut %d %g %g\n", i, in[0], out[0]); } } #ifdef NOVA_SIMD FLATTEN void LocalOut_next_a_nova(IOUnit* unit, int inNumSamples) { // Print("LocalOut_next_a %d\n", unit->mNumInputs); World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumInputs; LocalIn* localIn = (LocalIn*)unit->mParent->mLocalAudioBusUnit; if (!localIn) return; float* out = localIn->m_bus; if ((out == nullptr) || (numChannels != localIn->mNumOutputs)) return; int32* touched = localIn->m_busTouched; int32 bufCounter = unit->mWorld->mBufCounter; for (int i = 0; i < numChannels; ++i, out += bufLength) { float* in = IN(i); if (touched[i] == bufCounter) nova::addvec_simd(out, in, inNumSamples); else { nova::copyvec_simd(out, in, inNumSamples); touched[i] = bufCounter; } // Print("LocalOut %d %g %g\n", i, in[0], out[0]); } } FLATTEN void LocalOut_next_a_nova_64(IOUnit* unit, int inNumSamples) { // Print("LocalOut_next_a %d\n", unit->mNumInputs); World* world = unit->mWorld; int bufLength = world->mBufLength; int numChannels = unit->mNumInputs; LocalIn* localIn = (LocalIn*)unit->mParent->mLocalAudioBusUnit; if (!localIn) return; float* out = localIn->m_bus; if ((out == nullptr) || (numChannels != localIn->mNumOutputs)) return; int32* touched = localIn->m_busTouched; int32 bufCounter = unit->mWorld->mBufCounter; for (int i = 0; i < numChannels; ++i, out += bufLength) { float* in = IN(i); if (touched[i] == bufCounter) nova::addvec_simd<64>(out, in); else { nova::copyvec_simd<64>(out, in); touched[i] = bufCounter; } // Print("LocalOut %d %g %g\n", i, in[0], out[0]); } } #endif void LocalOut_next_k(IOUnit* unit, int inNumSamples) { int numChannels = unit->mNumInputs; LocalIn* localIn = (LocalIn*)unit->mParent->mLocalControlBusUnit; if (!localIn) return; float* out = localIn->m_bus; if ((out == nullptr) || (numChannels != localIn->mNumOutputs)) return; int32* touched = localIn->m_busTouched; int32 bufCounter = unit->mWorld->mBufCounter; for (int i = 0; i < numChannels; ++i, out++) { float* in = IN(i); if (touched[i] == bufCounter) *out += *in; else { *out = *in; touched[i] = bufCounter; } } } void LocalOut_Ctor(IOUnit* unit) { // Print("->LocalOut_Ctor\n"); unit->m_fbusChannel = -1.; if (unit->mCalcRate == calc_FullRate) { #ifdef NOVA_SIMD if (BUFLENGTH == 64) SETCALC(LocalOut_next_a_nova_64); else if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(LocalOut_next_a_nova); else #endif SETCALC(LocalOut_next_a); } else { SETCALC(LocalOut_next_k); } // Print("<-LocalOut_Ctor\n"); } ////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// PluginLoad(IO) { ft = inTable; DefineDtorUnit(OffsetOut); DefineDtorUnit(LocalIn); DefineSimpleUnit(XOut); DefineDtorUnit(LagControl); DefineDtorUnit(AudioControl); DefineUnit("Control", sizeof(Unit), (UnitCtorFunc)&Control_Ctor, nullptr, 0); DefineUnit("TrigControl", sizeof(Unit), (UnitCtorFunc)&TrigControl_Ctor, nullptr, 0); DefineUnit("ReplaceOut", sizeof(IOUnit), (UnitCtorFunc)&ReplaceOut_Ctor, nullptr, 0); DefineUnit("Out", sizeof(IOUnit), (UnitCtorFunc)&Out_Ctor, nullptr, 0); DefineUnit("LocalOut", sizeof(IOUnit), (UnitCtorFunc)&LocalOut_Ctor, nullptr, 0); DefineUnit("In", sizeof(IOUnit), (UnitCtorFunc)&In_Ctor, nullptr, 0); DefineUnit("LagIn", sizeof(IOUnit), (UnitCtorFunc)&LagIn_Ctor, nullptr, 0); DefineUnit("InFeedback", sizeof(IOUnit), (UnitCtorFunc)&InFeedback_Ctor, nullptr, 0); DefineUnit("InTrig", sizeof(IOUnit), (UnitCtorFunc)&InTrig_Ctor, nullptr, 0); DefineUnit("SharedOut", sizeof(IOUnit), (UnitCtorFunc)&SharedOut_Ctor, nullptr, 0); DefineUnit("SharedIn", sizeof(IOUnit), (UnitCtorFunc)&SharedIn_Ctor, nullptr, 0); }
57,192
C++
.cpp
1,475
31.513898
120
0.579281
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,956
BinaryOpUGens.cpp
supercollider_supercollider/server/plugins/BinaryOpUGens.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "SC_PlugIn.h" #include <boost/align/is_aligned.hpp> #ifdef _MSC_VER // hypotf is c99, but not c++ # define hypotf _hypotf #endif #ifdef NOVA_SIMD # include "simd_binary_arithmetic.hpp" # include "simd_math.hpp" # include "simd_memory.hpp" # include "function_attributes.h" using nova::slope_argument; # define NOVA_BINARY_WRAPPER(SCNAME, NOVANAME) \ FLATTEN void SCNAME##_aa_nova(BinaryOpUGen* unit, int inNumSamples) { \ nova::NOVANAME##_vec_simd(OUT(0), IN(0), IN(1), inNumSamples); \ } \ \ FLATTEN void SCNAME##_aa_nova_64(BinaryOpUGen* unit, int inNumSamples) { \ nova::NOVANAME##_vec_simd<64>(OUT(0), IN(0), IN(1)); \ } \ \ FLATTEN void SCNAME##_ia_nova(BinaryOpUGen* unit, int inNumSamples) { \ float xa = ZIN0(0); \ \ nova::NOVANAME##_vec_simd(OUT(0), xa, IN(1), inNumSamples); \ unit->mPrevA = xa; \ } \ \ FLATTEN void SCNAME##_ia_nova_64(BinaryOpUGen* unit, int inNumSamples) { \ float xa = ZIN0(0); \ \ nova::NOVANAME##_vec_simd<64>(OUT(0), xa, IN(1)); \ unit->mPrevA = xa; \ } \ \ FLATTEN void SCNAME##_ai_nova(BinaryOpUGen* unit, int inNumSamples) { \ float xb = ZIN0(1); \ \ nova::NOVANAME##_vec_simd(OUT(0), IN(0), xb, inNumSamples); \ unit->mPrevB = xb; \ } \ \ FLATTEN void SCNAME##_ai_nova_64(BinaryOpUGen* unit, int inNumSamples) { \ float xb = ZIN0(1); \ \ nova::NOVANAME##_vec_simd<64>(OUT(0), IN(0), xb); \ unit->mPrevB = xb; \ } # define NOVA_BINARY_WRAPPER_K(SCNAME, NOVANAME) \ FLATTEN void SCNAME##_aa_nova(BinaryOpUGen* unit, int inNumSamples) { \ nova::NOVANAME##_vec_simd(OUT(0), IN(0), IN(1), inNumSamples); \ } \ \ FLATTEN void SCNAME##_aa_nova_64(BinaryOpUGen* unit, int inNumSamples) { \ nova::NOVANAME##_vec_simd<64>(OUT(0), IN(0), IN(1)); \ } \ \ FLATTEN void SCNAME##_ia_nova(BinaryOpUGen* unit, int inNumSamples) { \ float xa = ZIN0(0); \ \ nova::NOVANAME##_vec_simd(OUT(0), xa, IN(1), inNumSamples); \ unit->mPrevA = xa; \ } \ \ FLATTEN void SCNAME##_ia_nova_64(BinaryOpUGen* unit, int inNumSamples) { \ float xa = ZIN0(0); \ \ nova::NOVANAME##_vec_simd<64>(OUT(0), xa, IN(1)); \ unit->mPrevA = xa; \ } \ \ FLATTEN void SCNAME##_ai_nova(BinaryOpUGen* unit, int inNumSamples) { \ float xb = ZIN0(1); \ \ nova::NOVANAME##_vec_simd(OUT(0), IN(0), xb, inNumSamples); \ unit->mPrevB = xb; \ } \ \ FLATTEN void SCNAME##_ai_nova_64(BinaryOpUGen* unit, int inNumSamples) { \ float xb = ZIN0(1); \ \ nova::NOVANAME##_vec_simd<64>(OUT(0), IN(0), xb); \ unit->mPrevB = xb; \ } \ \ FLATTEN void SCNAME##_ak_nova(BinaryOpUGen* unit, int inNumSamples) { \ float xb = unit->mPrevB; \ float next_b = ZIN0(1); \ \ if (xb == next_b) { \ nova::NOVANAME##_vec_simd(OUT(0), IN(0), xb, inNumSamples); \ } else { \ float slope = CALCSLOPE(next_b, xb); \ nova::NOVANAME##_vec_simd(OUT(0), IN(0), slope_argument(xb, slope), inNumSamples); \ unit->mPrevB = next_b; \ } \ } \ \ FLATTEN void SCNAME##_ak_nova_64(BinaryOpUGen* unit, int inNumSamples) { \ float xb = unit->mPrevB; \ float next_b = ZIN0(1); \ \ if (xb == next_b) { \ nova::NOVANAME##_vec_simd<64>(OUT(0), IN(0), xb); \ } else { \ float slope = CALCSLOPE(next_b, xb); \ nova::NOVANAME##_vec_simd(OUT(0), IN(0), slope_argument(xb, slope), inNumSamples); \ unit->mPrevB = next_b; \ } \ } \ \ FLATTEN void SCNAME##_ka_nova(BinaryOpUGen* unit, int inNumSamples) { \ float xa = unit->mPrevA; \ float next_a = ZIN0(0); \ \ if (xa == next_a) { \ nova::NOVANAME##_vec_simd(OUT(0), xa, IN(1), inNumSamples); \ } else { \ float slope = CALCSLOPE(next_a, xa); \ nova::NOVANAME##_vec_simd(OUT(0), slope_argument(xa, slope), IN(1), inNumSamples); \ unit->mPrevA = next_a; \ } \ } \ FLATTEN void SCNAME##_ka_nova_64(BinaryOpUGen* unit, int inNumSamples) { \ float xa = unit->mPrevA; \ float next_a = ZIN0(0); \ \ if (xa == next_a) { \ nova::NOVANAME##_vec_simd<64>(OUT(0), xa, IN(1)); \ } else { \ float slope = CALCSLOPE(next_a, xa); \ nova::NOVANAME##_vec_simd(OUT(0), slope_argument(xa, slope), IN(1), inNumSamples); \ unit->mPrevA = next_a; \ } \ } # define DEFINE_TEMPLATE_FUNCTOR(NAME) \ struct NAME##_functor { \ template <typename FloatType> inline FloatType operator()(FloatType a, FloatType b) const { \ return NAME(a, b); \ } \ \ template <typename FloatType> \ inline nova::vec<FloatType> operator()(nova::vec<FloatType> a, nova::vec<FloatType> b) const { \ return NAME(a, b); \ } \ }; DEFINE_TEMPLATE_FUNCTOR(sc_ring1) DEFINE_TEMPLATE_FUNCTOR(sc_ring2) DEFINE_TEMPLATE_FUNCTOR(sc_ring3) DEFINE_TEMPLATE_FUNCTOR(sc_ring4) DEFINE_TEMPLATE_FUNCTOR(sc_difsqr) DEFINE_TEMPLATE_FUNCTOR(sc_sumsqr) DEFINE_TEMPLATE_FUNCTOR(sc_sqrsum) DEFINE_TEMPLATE_FUNCTOR(sc_sqrdif) namespace nova { NOVA_SIMD_DEFINE_BINARY_WRAPPER(sc_ring1, sc_ring1_functor) NOVA_SIMD_DEFINE_BINARY_WRAPPER(sc_ring2, sc_ring2_functor) NOVA_SIMD_DEFINE_BINARY_WRAPPER(sc_ring3, sc_ring3_functor) NOVA_SIMD_DEFINE_BINARY_WRAPPER(sc_ring4, sc_ring4_functor) NOVA_SIMD_DEFINE_BINARY_WRAPPER(sc_difsqr, sc_difsqr_functor) NOVA_SIMD_DEFINE_BINARY_WRAPPER(sc_sumsqr, sc_sumsqr_functor) NOVA_SIMD_DEFINE_BINARY_WRAPPER(sc_sqrsum, sc_sqrsum_functor) NOVA_SIMD_DEFINE_BINARY_WRAPPER(sc_sqrdif, sc_sqrdif_functor) } #endif using namespace std; // for math functions static InterfaceTable* ft; ////////////////////////////////////////////////////////////////////////////////////////////////// /* special binary math operators */ enum { opAdd, opSub, opMul, opIDiv, opFDiv, opMod, opEQ, opNE, opLT, opGT, opLE, opGE, // opIdentical, // opNotIdentical, opMin, opMax, opBitAnd, opBitOr, opBitXor, opLCM, opGCD, opRound, opRoundUp, opTrunc, opAtan2, opHypot, opHypotx, opPow, opShiftLeft, // opShiftRight, // opUnsignedShift, // opFill, // opRing1, // a * (b + 1) == a * b + a opRing2, // a * b + a + b opRing3, // a*a*b opRing4, // a*a*b - a*b*b opDifSqr, // a*a - b*b opSumSqr, // a*a + b*b opSqrSum, // (a + b)^2 opSqrDif, // (a - b)^2 opAbsDif, // |a - b| opThresh, opAMClip, opScaleNeg, opClip2, opExcess, opFold2, opWrap2, opFirstArg, opRandRange, opExpRandRange, opNumBinarySelectors }; inline float sc_andt(float a, float b) { return int(a) & int(b); } inline float sc_ort(float a, float b) { return int(a) | int(b); } inline float sc_xort(float a, float b) { return int(a) ^ int(b); } inline float sc_rst(float a, float b) { return int(a) >> int(b); } inline float sc_lst(float a, float b) { return int(a) << int(b); } struct BinaryOpUGen : public Unit { float mPrevA, mPrevB; }; typedef void (*BinaryOpFunc)(BinaryOpUGen* unit, int inNumSamples); extern "C" { void BinaryOpUGen_Ctor(BinaryOpUGen* unit); // void zero_d(BinaryOpUGen *unit, int inNumSamples); void zero_1(BinaryOpUGen* unit, int inNumSamples); void zero_aa(BinaryOpUGen* unit, int inNumSamples); void firstarg_d(BinaryOpUGen* unit, int inNumSamples); void firstarg_1(BinaryOpUGen* unit, int inNumSamples); void firstarg_aa(BinaryOpUGen* unit, int inNumSamples); void secondarg_d(BinaryOpUGen* unit, int inNumSamples); void secondarg_1(BinaryOpUGen* unit, int inNumSamples); void secondarg_aa(BinaryOpUGen* unit, int inNumSamples); void add_d(BinaryOpUGen* unit, int inNumSamples); void add_1(BinaryOpUGen* unit, int inNumSamples); void add_aa(BinaryOpUGen* unit, int inNumSamples); void add_ak(BinaryOpUGen* unit, int inNumSamples); void add_ka(BinaryOpUGen* unit, int inNumSamples); void add_ai(BinaryOpUGen* unit, int inNumSamples); void add_ia(BinaryOpUGen* unit, int inNumSamples); void sub_d(BinaryOpUGen* unit, int inNumSamples); void sub_1(BinaryOpUGen* unit, int inNumSamples); void sub_aa(BinaryOpUGen* unit, int inNumSamples); void sub_ak(BinaryOpUGen* unit, int inNumSamples); void sub_ka(BinaryOpUGen* unit, int inNumSamples); void sub_ai(BinaryOpUGen* unit, int inNumSamples); void sub_ia(BinaryOpUGen* unit, int inNumSamples); void mul_d(BinaryOpUGen* unit, int inNumSamples); void mul_1(BinaryOpUGen* unit, int inNumSamples); void mul_aa(BinaryOpUGen* unit, int inNumSamples); void mul_ak(BinaryOpUGen* unit, int inNumSamples); void mul_ka(BinaryOpUGen* unit, int inNumSamples); void mul_ai(BinaryOpUGen* unit, int inNumSamples); void mul_ia(BinaryOpUGen* unit, int inNumSamples); void div_d(BinaryOpUGen* unit, int inNumSamples); void div_1(BinaryOpUGen* unit, int inNumSamples); void div_aa(BinaryOpUGen* unit, int inNumSamples); void div_ak(BinaryOpUGen* unit, int inNumSamples); void div_ka(BinaryOpUGen* unit, int inNumSamples); void div_ai(BinaryOpUGen* unit, int inNumSamples); void div_ia(BinaryOpUGen* unit, int inNumSamples); void mod_d(BinaryOpUGen* unit, int inNumSamples); void mod_1(BinaryOpUGen* unit, int inNumSamples); void mod_aa(BinaryOpUGen* unit, int inNumSamples); void mod_ak(BinaryOpUGen* unit, int inNumSamples); void mod_ka(BinaryOpUGen* unit, int inNumSamples); void mod_ai(BinaryOpUGen* unit, int inNumSamples); void mod_ia(BinaryOpUGen* unit, int inNumSamples); void max_d(BinaryOpUGen* unit, int inNumSamples); void max_1(BinaryOpUGen* unit, int inNumSamples); void max_aa(BinaryOpUGen* unit, int inNumSamples); void max_ak(BinaryOpUGen* unit, int inNumSamples); void max_ka(BinaryOpUGen* unit, int inNumSamples); void max_ai(BinaryOpUGen* unit, int inNumSamples); void max_ia(BinaryOpUGen* unit, int inNumSamples); void min_d(BinaryOpUGen* unit, int inNumSamples); void min_1(BinaryOpUGen* unit, int inNumSamples); void min_aa(BinaryOpUGen* unit, int inNumSamples); void min_ak(BinaryOpUGen* unit, int inNumSamples); void min_ka(BinaryOpUGen* unit, int inNumSamples); void min_ai(BinaryOpUGen* unit, int inNumSamples); void min_ia(BinaryOpUGen* unit, int inNumSamples); void and_d(BinaryOpUGen* unit, int inNumSamples); void and_1(BinaryOpUGen* unit, int inNumSamples); void and_aa(BinaryOpUGen* unit, int inNumSamples); void and_ak(BinaryOpUGen* unit, int inNumSamples); void and_ka(BinaryOpUGen* unit, int inNumSamples); void and_ai(BinaryOpUGen* unit, int inNumSamples); void and_ia(BinaryOpUGen* unit, int inNumSamples); void or_d(BinaryOpUGen* unit, int inNumSamples); void or_1(BinaryOpUGen* unit, int inNumSamples); void or_aa(BinaryOpUGen* unit, int inNumSamples); void or_ak(BinaryOpUGen* unit, int inNumSamples); void or_ka(BinaryOpUGen* unit, int inNumSamples); void or_ai(BinaryOpUGen* unit, int inNumSamples); void or_ia(BinaryOpUGen* unit, int inNumSamples); void xor_d(BinaryOpUGen* unit, int inNumSamples); void xor_1(BinaryOpUGen* unit, int inNumSamples); void xor_aa(BinaryOpUGen* unit, int inNumSamples); void xor_ak(BinaryOpUGen* unit, int inNumSamples); void xor_ka(BinaryOpUGen* unit, int inNumSamples); void xor_ai(BinaryOpUGen* unit, int inNumSamples); void xor_ia(BinaryOpUGen* unit, int inNumSamples); void amclip_d(BinaryOpUGen* unit, int inNumSamples); void amclip_1(BinaryOpUGen* unit, int inNumSamples); void amclip_aa(BinaryOpUGen* unit, int inNumSamples); void amclip_ak(BinaryOpUGen* unit, int inNumSamples); void amclip_ka(BinaryOpUGen* unit, int inNumSamples); void amclip_ai(BinaryOpUGen* unit, int inNumSamples); void amclip_ia(BinaryOpUGen* unit, int inNumSamples); void scaleneg_d(BinaryOpUGen* unit, int inNumSamples); void scaleneg_1(BinaryOpUGen* unit, int inNumSamples); void scaleneg_aa(BinaryOpUGen* unit, int inNumSamples); void scaleneg_ak(BinaryOpUGen* unit, int inNumSamples); void scaleneg_ka(BinaryOpUGen* unit, int inNumSamples); void scaleneg_ai(BinaryOpUGen* unit, int inNumSamples); void scaleneg_ia(BinaryOpUGen* unit, int inNumSamples); void pow_d(BinaryOpUGen* unit, int inNumSamples); void pow_1(BinaryOpUGen* unit, int inNumSamples); void pow_aa(BinaryOpUGen* unit, int inNumSamples); void pow_ak(BinaryOpUGen* unit, int inNumSamples); void pow_ka(BinaryOpUGen* unit, int inNumSamples); void pow_ai(BinaryOpUGen* unit, int inNumSamples); void pow_ia(BinaryOpUGen* unit, int inNumSamples); void ring1_d(BinaryOpUGen* unit, int inNumSamples); void ring1_1(BinaryOpUGen* unit, int inNumSamples); void ring1_aa(BinaryOpUGen* unit, int inNumSamples); void ring1_ak(BinaryOpUGen* unit, int inNumSamples); void ring1_ka(BinaryOpUGen* unit, int inNumSamples); void ring1_ai(BinaryOpUGen* unit, int inNumSamples); void ring1_ia(BinaryOpUGen* unit, int inNumSamples); void ring2_d(BinaryOpUGen* unit, int inNumSamples); void ring2_1(BinaryOpUGen* unit, int inNumSamples); void ring2_aa(BinaryOpUGen* unit, int inNumSamples); void ring2_ak(BinaryOpUGen* unit, int inNumSamples); void ring2_ka(BinaryOpUGen* unit, int inNumSamples); void ring2_ai(BinaryOpUGen* unit, int inNumSamples); void ring2_ia(BinaryOpUGen* unit, int inNumSamples); void ring3_d(BinaryOpUGen* unit, int inNumSamples); void ring3_1(BinaryOpUGen* unit, int inNumSamples); void ring3_aa(BinaryOpUGen* unit, int inNumSamples); void ring3_ak(BinaryOpUGen* unit, int inNumSamples); void ring3_ka(BinaryOpUGen* unit, int inNumSamples); void ring3_ai(BinaryOpUGen* unit, int inNumSamples); void ring3_ia(BinaryOpUGen* unit, int inNumSamples); void ring4_d(BinaryOpUGen* unit, int inNumSamples); void ring4_1(BinaryOpUGen* unit, int inNumSamples); void ring4_aa(BinaryOpUGen* unit, int inNumSamples); void ring4_ak(BinaryOpUGen* unit, int inNumSamples); void ring4_ka(BinaryOpUGen* unit, int inNumSamples); void ring4_ai(BinaryOpUGen* unit, int inNumSamples); void ring4_ia(BinaryOpUGen* unit, int inNumSamples); void thresh_d(BinaryOpUGen* unit, int inNumSamples); void thresh_1(BinaryOpUGen* unit, int inNumSamples); void thresh_aa(BinaryOpUGen* unit, int inNumSamples); void thresh_ak(BinaryOpUGen* unit, int inNumSamples); void thresh_ka(BinaryOpUGen* unit, int inNumSamples); void thresh_ai(BinaryOpUGen* unit, int inNumSamples); void thresh_ia(BinaryOpUGen* unit, int inNumSamples); void clip2_d(BinaryOpUGen* unit, int inNumSamples); void clip2_1(BinaryOpUGen* unit, int inNumSamples); void clip2_aa(BinaryOpUGen* unit, int inNumSamples); void clip2_ak(BinaryOpUGen* unit, int inNumSamples); void clip2_ka(BinaryOpUGen* unit, int inNumSamples); void clip2_ai(BinaryOpUGen* unit, int inNumSamples); void clip2_ia(BinaryOpUGen* unit, int inNumSamples); void fold2_d(BinaryOpUGen* unit, int inNumSamples); void fold2_1(BinaryOpUGen* unit, int inNumSamples); void fold2_aa(BinaryOpUGen* unit, int inNumSamples); void fold2_ak(BinaryOpUGen* unit, int inNumSamples); void fold2_ka(BinaryOpUGen* unit, int inNumSamples); void fold2_ai(BinaryOpUGen* unit, int inNumSamples); void fold2_ia(BinaryOpUGen* unit, int inNumSamples); void wrap2_d(BinaryOpUGen* unit, int inNumSamples); void wrap2_1(BinaryOpUGen* unit, int inNumSamples); void wrap2_aa(BinaryOpUGen* unit, int inNumSamples); void wrap2_ak(BinaryOpUGen* unit, int inNumSamples); void wrap2_ka(BinaryOpUGen* unit, int inNumSamples); void wrap2_ai(BinaryOpUGen* unit, int inNumSamples); void wrap2_ia(BinaryOpUGen* unit, int inNumSamples); void excess_d(BinaryOpUGen* unit, int inNumSamples); void excess_1(BinaryOpUGen* unit, int inNumSamples); void excess_aa(BinaryOpUGen* unit, int inNumSamples); void excess_ak(BinaryOpUGen* unit, int inNumSamples); void excess_ka(BinaryOpUGen* unit, int inNumSamples); void excess_ai(BinaryOpUGen* unit, int inNumSamples); void excess_ia(BinaryOpUGen* unit, int inNumSamples); void rrand_d(BinaryOpUGen* unit, int inNumSamples); void rrand_1(BinaryOpUGen* unit, int inNumSamples); void rrand_aa(BinaryOpUGen* unit, int inNumSamples); void rrand_ak(BinaryOpUGen* unit, int inNumSamples); void rrand_ka(BinaryOpUGen* unit, int inNumSamples); void rrand_ai(BinaryOpUGen* unit, int inNumSamples); void rrand_ia(BinaryOpUGen* unit, int inNumSamples); void exprand_d(BinaryOpUGen* unit, int inNumSamples); void exprand_1(BinaryOpUGen* unit, int inNumSamples); void exprand_aa(BinaryOpUGen* unit, int inNumSamples); void exprand_ak(BinaryOpUGen* unit, int inNumSamples); void exprand_ka(BinaryOpUGen* unit, int inNumSamples); void exprand_ai(BinaryOpUGen* unit, int inNumSamples); void exprand_ia(BinaryOpUGen* unit, int inNumSamples); void lt_d(BinaryOpUGen* unit, int inNumSamples); void lt_1(BinaryOpUGen* unit, int inNumSamples); void lt_aa(BinaryOpUGen* unit, int inNumSamples); void lt_ak(BinaryOpUGen* unit, int inNumSamples); void lt_ka(BinaryOpUGen* unit, int inNumSamples); void lt_ai(BinaryOpUGen* unit, int inNumSamples); void lt_ia(BinaryOpUGen* unit, int inNumSamples); void le_d(BinaryOpUGen* unit, int inNumSamples); void le_1(BinaryOpUGen* unit, int inNumSamples); void le_aa(BinaryOpUGen* unit, int inNumSamples); void le_ak(BinaryOpUGen* unit, int inNumSamples); void le_ka(BinaryOpUGen* unit, int inNumSamples); void le_ai(BinaryOpUGen* unit, int inNumSamples); void le_ia(BinaryOpUGen* unit, int inNumSamples); void lcm_d(BinaryOpUGen* unit, int inNumSamples); void lcm_1(BinaryOpUGen* unit, int inNumSamples); void lcm_aa(BinaryOpUGen* unit, int inNumSamples); void lcm_ak(BinaryOpUGen* unit, int inNumSamples); void lcm_ka(BinaryOpUGen* unit, int inNumSamples); void lcm_ai(BinaryOpUGen* unit, int inNumSamples); void lcm_ia(BinaryOpUGen* unit, int inNumSamples); void gcd_d(BinaryOpUGen* unit, int inNumSamples); void gcd_1(BinaryOpUGen* unit, int inNumSamples); void gcd_aa(BinaryOpUGen* unit, int inNumSamples); void gcd_ak(BinaryOpUGen* unit, int inNumSamples); void gcd_ka(BinaryOpUGen* unit, int inNumSamples); void gcd_ai(BinaryOpUGen* unit, int inNumSamples); void gcd_ia(BinaryOpUGen* unit, int inNumSamples); void gt_d(BinaryOpUGen* unit, int inNumSamples); void gt_1(BinaryOpUGen* unit, int inNumSamples); void gt_aa(BinaryOpUGen* unit, int inNumSamples); void gt_ak(BinaryOpUGen* unit, int inNumSamples); void gt_ka(BinaryOpUGen* unit, int inNumSamples); void gt_ai(BinaryOpUGen* unit, int inNumSamples); void gt_ia(BinaryOpUGen* unit, int inNumSamples); void ge_d(BinaryOpUGen* unit, int inNumSamples); void ge_1(BinaryOpUGen* unit, int inNumSamples); void ge_aa(BinaryOpUGen* unit, int inNumSamples); void ge_ak(BinaryOpUGen* unit, int inNumSamples); void ge_ka(BinaryOpUGen* unit, int inNumSamples); void ge_ai(BinaryOpUGen* unit, int inNumSamples); void ge_ia(BinaryOpUGen* unit, int inNumSamples); void eq_d(BinaryOpUGen* unit, int inNumSamples); void eq_1(BinaryOpUGen* unit, int inNumSamples); void eq_aa(BinaryOpUGen* unit, int inNumSamples); void eq_ak(BinaryOpUGen* unit, int inNumSamples); void eq_ka(BinaryOpUGen* unit, int inNumSamples); void eq_ai(BinaryOpUGen* unit, int inNumSamples); void eq_ia(BinaryOpUGen* unit, int inNumSamples); void neq_d(BinaryOpUGen* unit, int inNumSamples); void neq_1(BinaryOpUGen* unit, int inNumSamples); void neq_aa(BinaryOpUGen* unit, int inNumSamples); void neq_ak(BinaryOpUGen* unit, int inNumSamples); void neq_ka(BinaryOpUGen* unit, int inNumSamples); void neq_ai(BinaryOpUGen* unit, int inNumSamples); void neq_ia(BinaryOpUGen* unit, int inNumSamples); void sumsqr_d(BinaryOpUGen* unit, int inNumSamples); void sumsqr_1(BinaryOpUGen* unit, int inNumSamples); void sumsqr_aa(BinaryOpUGen* unit, int inNumSamples); void sumsqr_ak(BinaryOpUGen* unit, int inNumSamples); void sumsqr_ka(BinaryOpUGen* unit, int inNumSamples); void sumsqr_ai(BinaryOpUGen* unit, int inNumSamples); void sumsqr_ia(BinaryOpUGen* unit, int inNumSamples); void difsqr_d(BinaryOpUGen* unit, int inNumSamples); void difsqr_1(BinaryOpUGen* unit, int inNumSamples); void difsqr_aa(BinaryOpUGen* unit, int inNumSamples); void difsqr_ak(BinaryOpUGen* unit, int inNumSamples); void difsqr_ka(BinaryOpUGen* unit, int inNumSamples); void difsqr_ai(BinaryOpUGen* unit, int inNumSamples); void difsqr_ia(BinaryOpUGen* unit, int inNumSamples); void sqrsum_d(BinaryOpUGen* unit, int inNumSamples); void sqrsum_1(BinaryOpUGen* unit, int inNumSamples); void sqrsum_aa(BinaryOpUGen* unit, int inNumSamples); void sqrsum_ak(BinaryOpUGen* unit, int inNumSamples); void sqrsum_ka(BinaryOpUGen* unit, int inNumSamples); void sqrsum_ai(BinaryOpUGen* unit, int inNumSamples); void sqrsum_ia(BinaryOpUGen* unit, int inNumSamples); void sqrdif_d(BinaryOpUGen* unit, int inNumSamples); void sqrdif_1(BinaryOpUGen* unit, int inNumSamples); void sqrdif_aa(BinaryOpUGen* unit, int inNumSamples); void sqrdif_ak(BinaryOpUGen* unit, int inNumSamples); void sqrdif_ka(BinaryOpUGen* unit, int inNumSamples); void sqrdif_ai(BinaryOpUGen* unit, int inNumSamples); void sqrdif_ia(BinaryOpUGen* unit, int inNumSamples); void absdif_d(BinaryOpUGen* unit, int inNumSamples); void absdif_1(BinaryOpUGen* unit, int inNumSamples); void absdif_aa(BinaryOpUGen* unit, int inNumSamples); void absdif_ak(BinaryOpUGen* unit, int inNumSamples); void absdif_ka(BinaryOpUGen* unit, int inNumSamples); void absdif_ai(BinaryOpUGen* unit, int inNumSamples); void absdif_ia(BinaryOpUGen* unit, int inNumSamples); void round_d(BinaryOpUGen* unit, int inNumSamples); void round_1(BinaryOpUGen* unit, int inNumSamples); void round_aa(BinaryOpUGen* unit, int inNumSamples); void round_ak(BinaryOpUGen* unit, int inNumSamples); void round_ka(BinaryOpUGen* unit, int inNumSamples); void round_ai(BinaryOpUGen* unit, int inNumSamples); void round_ia(BinaryOpUGen* unit, int inNumSamples); void roundUp_d(BinaryOpUGen* unit, int inNumSamples); void roundUp_1(BinaryOpUGen* unit, int inNumSamples); void roundUp_aa(BinaryOpUGen* unit, int inNumSamples); void roundUp_ak(BinaryOpUGen* unit, int inNumSamples); void roundUp_ka(BinaryOpUGen* unit, int inNumSamples); void roundUp_ai(BinaryOpUGen* unit, int inNumSamples); void roundUp_ia(BinaryOpUGen* unit, int inNumSamples); void trunc_d(BinaryOpUGen* unit, int inNumSamples); void trunc_1(BinaryOpUGen* unit, int inNumSamples); void trunc_aa(BinaryOpUGen* unit, int inNumSamples); void trunc_ak(BinaryOpUGen* unit, int inNumSamples); void trunc_ka(BinaryOpUGen* unit, int inNumSamples); void trunc_ai(BinaryOpUGen* unit, int inNumSamples); void trunc_ia(BinaryOpUGen* unit, int inNumSamples); void atan2_d(BinaryOpUGen* unit, int inNumSamples); void atan2_1(BinaryOpUGen* unit, int inNumSamples); void atan2_aa(BinaryOpUGen* unit, int inNumSamples); void atan2_ak(BinaryOpUGen* unit, int inNumSamples); void atan2_ka(BinaryOpUGen* unit, int inNumSamples); void atan2_ai(BinaryOpUGen* unit, int inNumSamples); void atan2_ia(BinaryOpUGen* unit, int inNumSamples); void hypot_d(BinaryOpUGen* unit, int inNumSamples); void hypot_1(BinaryOpUGen* unit, int inNumSamples); void hypot_aa(BinaryOpUGen* unit, int inNumSamples); void hypot_ak(BinaryOpUGen* unit, int inNumSamples); void hypot_ka(BinaryOpUGen* unit, int inNumSamples); void hypot_ai(BinaryOpUGen* unit, int inNumSamples); void hypot_ia(BinaryOpUGen* unit, int inNumSamples); void hypotx_d(BinaryOpUGen* unit, int inNumSamples); void hypotx_1(BinaryOpUGen* unit, int inNumSamples); void hypotx_aa(BinaryOpUGen* unit, int inNumSamples); void hypotx_ak(BinaryOpUGen* unit, int inNumSamples); void hypotx_ka(BinaryOpUGen* unit, int inNumSamples); void hypotx_ai(BinaryOpUGen* unit, int inNumSamples); void hypotx_ia(BinaryOpUGen* unit, int inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// static bool ChooseOperatorFunc(BinaryOpUGen* unit); void BinaryOpUGen_Ctor(BinaryOpUGen* unit) { unit->mPrevA = ZIN0(0); unit->mPrevB = ZIN0(1); bool initialized = ChooseOperatorFunc(unit); if (unit->mCalcRate == calc_DemandRate) { OUT0(0) = 0.f; } else { if (!initialized) (unit->mCalcFunc)(unit, 1); } } /* void zero_d(BinaryOpUGen *unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : 0.f; } else { RESETINPUT(0); RESETINPUT(1); } } */ void firstarg_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : a; } else { RESETINPUT(0); RESETINPUT(1); } } void secondarg_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : b; } else { RESETINPUT(0); RESETINPUT(1); } } void add_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : a + b; } else { RESETINPUT(0); RESETINPUT(1); } } void sub_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : a - b; } else { RESETINPUT(0); RESETINPUT(1); } } void mul_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : a * b; } else { RESETINPUT(0); RESETINPUT(1); } } void div_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : a / b; } else { RESETINPUT(0); RESETINPUT(1); } } void idiv_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : floor(a / b); } else { RESETINPUT(0); RESETINPUT(1); } } void mod_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_mod(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void max_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_max(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void min_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_min(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void and_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_andt(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void or_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_ort(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void xor_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_xort(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void rightShift_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_rst(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void leftShift_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_lst(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void lcm_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_lcm(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void gcd_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_gcd(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void amclip_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_amclip(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void scaleneg_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_scaleneg(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void pow_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : (a < 0.f ? -pow(-a, b) : pow(a, b)); } else { RESETINPUT(0); RESETINPUT(1); } } void ring1_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : a * b + a; } else { RESETINPUT(0); RESETINPUT(1); } } void ring2_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : a * b + a + b; } else { RESETINPUT(0); RESETINPUT(1); } } void ring3_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : a * a * b; } else { RESETINPUT(0); RESETINPUT(1); } } void ring4_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : a * a * b - a * b * b; } else { RESETINPUT(0); RESETINPUT(1); } } void thresh_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_thresh(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void clip2_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_clip2(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void excess_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_excess(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void lt_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : (a < b ? 1.f : 0.f); } else { RESETINPUT(0); RESETINPUT(1); } } void gt_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : (a > b ? 1.f : 0.f); } else { RESETINPUT(0); RESETINPUT(1); } } void le_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : (a <= b ? 1.f : 0.f); } else { RESETINPUT(0); RESETINPUT(1); } } void ge_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : (a >= b ? 1.f : 0.f); } else { RESETINPUT(0); RESETINPUT(1); } } void eq_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : (a == b ? 1.f : 0.f); } else { RESETINPUT(0); RESETINPUT(1); } } void neq_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : (a != b ? 1.f : 0.f); } else { RESETINPUT(0); RESETINPUT(1); } } void sumsqr_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : a * a + b * b; } else { RESETINPUT(0); RESETINPUT(1); } } void difsqr_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : a * a - b * b; } else { RESETINPUT(0); RESETINPUT(1); } } void sqrsum_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); float z; OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : (z = a + b, z * z); } else { RESETINPUT(0); RESETINPUT(1); } } void sqrdif_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); float z; OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : (z = a - b, z * z); } else { RESETINPUT(0); RESETINPUT(1); } } void absdif_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : fabs(a - b); } else { RESETINPUT(0); RESETINPUT(1); } } void round_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_round(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void roundUp_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_roundUp(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void trunc_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_trunc(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void fold2_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_fold2(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void wrap2_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_wrap2(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void atan2_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : atan2(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void hypot_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : hypot(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void hypotx_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float a = DEMANDINPUT_A(0, inNumSamples); float b = DEMANDINPUT_A(1, inNumSamples); OUT0(0) = sc_isnan(a) || sc_isnan(b) ? NAN : sc_hypotx(a, b); } else { RESETINPUT(0); RESETINPUT(1); } } void rrand_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float xa = DEMANDINPUT_A(0, inNumSamples); float xb = DEMANDINPUT_A(1, inNumSamples); RGen& rgen = *unit->mParent->mRGen; OUT0(0) = sc_isnan(xa) || sc_isnan(xb) ? NAN : xb > xa ? xa + rgen.frand() * (xb - xa) : (xb + rgen.frand() * (xa - xb)); } else { RESETINPUT(0); RESETINPUT(1); } } void exprand_d(BinaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float xa = DEMANDINPUT_A(0, inNumSamples); float xb = DEMANDINPUT_A(1, inNumSamples); RGen& rgen = *unit->mParent->mRGen; OUT0(0) = sc_isnan(xa) || sc_isnan(xb) ? NAN : xb > xa ? rgen.exprandrng(xa, xb) : rgen.exprandrng(xb, xa); } else { RESETINPUT(0); RESETINPUT(1); } } void zero_1(BinaryOpUGen* unit, int inNumSamples) { ZOUT0(0) = 0.f; } void firstarg_1(BinaryOpUGen* unit, int inNumSamples) { ZOUT0(0) = ZIN0(0); } void secondarg_1(BinaryOpUGen* unit, int inNumSamples) { ZOUT0(0) = ZIN0(1); } void add_1(BinaryOpUGen* unit, int inNumSamples) { ZOUT0(0) = ZIN0(0) + ZIN0(1); } void sub_1(BinaryOpUGen* unit, int inNumSamples) { ZOUT0(0) = ZIN0(0) - ZIN0(1); } void mul_1(BinaryOpUGen* unit, int inNumSamples) { ZOUT0(0) = ZIN0(0) * ZIN0(1); } void div_1(BinaryOpUGen* unit, int inNumSamples) { ZOUT0(0) = ZIN0(0) / ZIN0(1); } void idiv_1(BinaryOpUGen* unit, int inNumSamples) { ZOUT0(0) = floor(ZIN0(0) / ZIN0(1)); } void mod_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = sc_mod(xa, xb); } void max_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = sc_max(xa, xb); } void min_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = sc_min(xa, xb); } void and_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = sc_andt(xa, xb); } void or_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = sc_ort(xa, xb); } void xor_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = sc_xort(xa, xb); } void rightShift_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = sc_rst(xa, xb); } void leftShift_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = sc_lst(xa, xb); } void lcm_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = sc_lcm(xa, xb); } void gcd_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = sc_gcd(xa, xb); } void amclip_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = sc_amclip(xa, xb); } void scaleneg_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = xa >= 0.f ? xa : xa * xb; } void pow_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = xa >= 0.f ? pow(xa, xb) : -pow(-xa, xb); } void ring1_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = xa * xb + xa; } void ring2_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = xa * xb + xa + xb; } void ring3_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = xa * xa * xb; } void ring4_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = xa * xa * xb - xa * xb * xb; } void thresh_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = xa < xb ? 0.f : xa; } void clip2_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = xa > xb ? xb : (xa < -xb ? -xb : xa); } void excess_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = xa > xb ? xa - xb : (xa < -xb ? xa + xb : 0.f); } void lt_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = xa < xb ? 1.f : 0.f; } void le_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = xa <= xb ? 1.f : 0.f; } void gt_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = xa > xb ? 1.f : 0.f; } void ge_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = xa >= xb ? 1.f : 0.f; } void eq_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = xa == xb ? 1.f : 0.f; } void neq_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = xa != xb ? 1.f : 0.f; } void sumsqr_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = xa * xa + xb * xb; } void difsqr_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = xa * xa - xb * xb; } void sqrsum_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); float sum = xa + xb; ZOUT0(0) = sum * sum; } void sqrdif_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); float dif = xa - xb; ZOUT0(0) = dif * dif; } void absdif_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = fabs(xa - xb); } void round_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = sc_round(xa, xb); } void roundUp_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = sc_roundUp(xa, xb); } void trunc_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = sc_trunc(xa, xb); } void fold2_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = sc_fold(xa, -xb, xb); } void wrap2_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = sc_wrap(xa, -xb, xb); } void atan2_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = atan2(xa, xb); } void hypot_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = hypot(xa, xb); } void hypotx_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); ZOUT0(0) = sc_hypotx(xa, xb); } void rrand_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); RGen& rgen = *unit->mParent->mRGen; ZOUT0(0) = xb > xa ? xa + rgen.frand() * (xb - xa) : (xb + rgen.frand() * (xa - xb)); } void exprand_1(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); float xb = ZIN0(1); RGen& rgen = *unit->mParent->mRGen; ZOUT0(0) = xb > xa ? rgen.exprandrng(xa, xb) : rgen.exprandrng(xb, xa); } void zero_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); ZClear(inNumSamples, out); } void firstarg_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); ZCopy(inNumSamples, out, a); } #ifdef NOVA_SIMD FLATTEN void firstarg_aa_nova(BinaryOpUGen* unit, int inNumSamples) { nova::copyvec_simd(OUT(0), IN(0), inNumSamples); } #endif void secondarg_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* b = ZIN(1); ZCopy(inNumSamples, out, b); } #ifdef NOVA_SIMD FLATTEN void secondarg_aa_nova(BinaryOpUGen* unit, int inNumSamples) { nova::copyvec_simd(OUT(0), IN(1), inNumSamples); } #endif void add_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, ZXP(out) = ZXP(a) + ZXP(b);); } void add_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { if (xb == 0.f) { ZCopy(inNumSamples, out, a); } else { float* out = ZOUT(0); float* a = ZIN(0); LOOP1(inNumSamples, ZXP(out) = ZXP(a) + xb;); } } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, ZXP(out) = ZXP(a) + xb; xb += slope;); unit->mPrevB = xb; } } void add_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { if (xa == 0.f) { ZCopy(inNumSamples, out, b); } else { LOOP1(inNumSamples, ZXP(out) = xa + ZXP(b);); } } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, ZXP(out) = xa + ZXP(b); xa += slope;); unit->mPrevA = xa; } } void add_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, ZXP(out) = xa + ZXP(b);); unit->mPrevA = xa; } void add_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, ZXP(out) = ZXP(a) + xb;); unit->mPrevB = xb; } #ifdef NOVA_SIMD NOVA_BINARY_WRAPPER(add, plus) FLATTEN void add_ak_nova(BinaryOpUGen* unit, int inNumSamples) { float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { if (xb == 0.f) nova::copyvec_simd(OUT(0), IN(0), inNumSamples); else nova::plus_vec_simd(OUT(0), IN(0), xb, inNumSamples); } else { float slope = CALCSLOPE(next_b, xb); nova::plus_vec_simd(OUT(0), IN(0), slope_argument(xb, slope), inNumSamples); unit->mPrevB = next_b; } } FLATTEN void add_ak_nova_64(BinaryOpUGen* unit, int inNumSamples) { float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { if (xb == 0.f) nova::copyvec_simd<64>(OUT(0), IN(0)); else nova::plus_vec_simd<64>(OUT(0), IN(0), xb); } else { float slope = CALCSLOPE(next_b, xb); nova::plus_vec_simd(OUT(0), IN(0), slope_argument(xb, slope), inNumSamples); unit->mPrevB = next_b; } } FLATTEN void add_ka_nova(BinaryOpUGen* unit, int inNumSamples) { float xa = unit->mPrevA; float next_a = ZIN0(0); if (xa == next_a) { if (xa == 0.f) nova::copyvec_simd(OUT(0), IN(1), inNumSamples); else nova::plus_vec_simd(OUT(0), IN(1), xa, inNumSamples); } else { float slope = CALCSLOPE(next_a, xa); nova::plus_vec_simd(OUT(0), IN(1), slope_argument(xa, slope), inNumSamples); unit->mPrevA = next_a; } } FLATTEN void add_ka_nova_64(BinaryOpUGen* unit, int inNumSamples) { float xa = unit->mPrevA; float next_a = ZIN0(0); if (xa == next_a) { if (xa == 0.f) nova::copyvec_simd<64>(OUT(0), IN(1)); else nova::plus_vec_simd<64>(OUT(0), IN(1), xa); } else { float slope = CALCSLOPE(next_a, xa); nova::plus_vec_simd(OUT(0), IN(1), slope_argument(xa, slope), inNumSamples); unit->mPrevA = next_a; } } #endif ///////////////////////// void sub_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, ZXP(out) = ZXP(a) - ZXP(b);); } void sub_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { if (xb == 0.f) { ZCopy(inNumSamples, out, a); } else { LOOP1(inNumSamples, ZXP(out) = ZXP(a) - xb;); } } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, ZXP(out) = ZXP(a) - xb; xb += slope;); unit->mPrevB = xb; } } void sub_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { if (xa == 0.f) { ZCopy(inNumSamples, out, b); } else { LOOP1(inNumSamples, ZXP(out) = xa - ZXP(b);); } } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, ZXP(out) = xa - ZXP(b); xa += slope;); unit->mPrevA = xa; } } void sub_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, ZXP(out) = xa - ZXP(b);); unit->mPrevA = xa; } void sub_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, ZXP(out) = ZXP(a) - xb;); unit->mPrevB = xb; } #ifdef NOVA_SIMD NOVA_BINARY_WRAPPER(sub, minus) FLATTEN void sub_ak_nova(BinaryOpUGen* unit, int inNumSamples) { float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { if (xb == 0.f) nova::copyvec_simd(OUT(0), IN(0), inNumSamples); else nova::minus_vec_simd(OUT(0), IN(0), xb, inNumSamples); } else { float slope = CALCSLOPE(next_b, xb); nova::minus_vec_simd(OUT(0), IN(0), slope_argument(xb, slope), inNumSamples); unit->mPrevB = next_b; } } FLATTEN void sub_ak_nova_64(BinaryOpUGen* unit, int inNumSamples) { float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { if (xb == 0.f) nova::copyvec_aa_simd<64>(OUT(0), IN(0)); else nova::minus_vec_simd<64>(OUT(0), IN(0), xb); } else { float slope = CALCSLOPE(next_b, xb); nova::minus_vec_simd(OUT(0), IN(0), slope_argument(xb, slope), inNumSamples); unit->mPrevB = next_b; } } FLATTEN void sub_ka_nova(BinaryOpUGen* unit, int inNumSamples) { float xa = unit->mPrevA; float next_a = ZIN0(0); if (xa == next_a) { nova::minus_vec_simd(OUT(0), xa, IN(1), inNumSamples); } else { float slope = CALCSLOPE(next_a, xa); nova::minus_vec_simd(OUT(0), slope_argument(xa, slope), IN(1), inNumSamples); unit->mPrevA = next_a; } } FLATTEN void sub_ka_nova_64(BinaryOpUGen* unit, int inNumSamples) { float xa = unit->mPrevA; float next_a = ZIN0(0); if (xa == next_a) { nova::minus_vec_simd<64>(OUT(0), xa, IN(1)); } else { float slope = CALCSLOPE(next_a, xa); nova::minus_vec_simd(OUT(0), slope_argument(xa, slope), IN(1), inNumSamples); unit->mPrevA = next_a; } } #endif void mul_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, ZXP(out) = ZXP(a) * ZXP(b);); } void mul_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { if (xb == 0.f) { ZClear(inNumSamples, out); } else if (xb == 1.f) { ZCopy(inNumSamples, out, a); } else { LOOP1(inNumSamples, ZXP(out) = ZXP(a) * xb;); } } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, ZXP(out) = ZXP(a) * xb; xb += slope;); unit->mPrevB = xb; } } void mul_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { if (xa == 0.f) { ZClear(inNumSamples, out); } else if (xa == 1.f) { ZCopy(inNumSamples, out, b); } else { LOOP1(inNumSamples, ZXP(out) = xa * ZXP(b);); } } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, ZXP(out) = xa * ZXP(b); xa += slope;); unit->mPrevA = xa; } } void mul_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, ZXP(out) = ZXP(a) * xb;); unit->mPrevB = xb; } void mul_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, ZXP(out) = xa * ZXP(b);); unit->mPrevA = xa; } #ifdef NOVA_SIMD NOVA_BINARY_WRAPPER(mul, times) FLATTEN void mul_ka_nova(BinaryOpUGen* unit, int inNumSamples) { float xa = unit->mPrevA; float next_a = ZIN0(0); if (xa == next_a) { if (xa == 0.f) nova::zerovec_simd(OUT(0), inNumSamples); else if (xa == 1.f) nova::copyvec_simd(OUT(0), IN(1), inNumSamples); else nova::times_vec_simd(OUT(0), IN(1), xa, inNumSamples); } else { float slope = CALCSLOPE(next_a, xa); unit->mPrevA = next_a; nova::times_vec_simd(OUT(0), IN(1), slope_argument(xa, slope), inNumSamples); } } FLATTEN void mul_ka_nova_64(BinaryOpUGen* unit, int inNumSamples) { float xa = unit->mPrevA; float next_a = ZIN0(0); if (xa == next_a) { if (xa == 0.f) nova::zerovec_simd<64>(OUT(0)); else if (xa == 1.f) nova::copyvec_simd<64>(OUT(0), IN(1)); else nova::times_vec_simd<64>(OUT(0), IN(1), xa); } else { float slope = CALCSLOPE(next_a, xa); unit->mPrevA = next_a; nova::times_vec_simd(OUT(0), IN(1), slope_argument(xa, slope), inNumSamples); } } FLATTEN void mul_ak_nova(BinaryOpUGen* unit, int inNumSamples) { float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { if (xb == 0.f) nova::zerovec_simd(OUT(0), inNumSamples); else if (xb == 1.f) nova::copyvec_simd(OUT(0), IN(0), inNumSamples); else nova::times_vec_simd(OUT(0), IN(0), xb, inNumSamples); } else { float slope = CALCSLOPE(next_b, xb); unit->mPrevB = next_b; nova::times_vec_simd(OUT(0), IN(0), slope_argument(xb, slope), inNumSamples); } } FLATTEN void mul_ak_nova_64(BinaryOpUGen* unit, int inNumSamples) { float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { if (xb == 0.f) nova::zerovec_simd<64>(OUT(0)); else if (xb == 1.f) nova::copyvec_simd<64>(OUT(0), IN(0)); else nova::times_vec_simd<64>(OUT(0), IN(0), xb); } else { float slope = CALCSLOPE(next_b, xb); unit->mPrevB = next_b; nova::times_vec_simd(OUT(0), IN(0), slope_argument(xb, slope), inNumSamples); } } #endif void div_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, ZXP(out) = ZXP(a) / ZXP(b);); } void div_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { if (xb == 0.f) { ZClear(inNumSamples, out); } else if (xb == 1.f) { ZCopy(inNumSamples, out, a); } else { float recip = 1.f / xb; LOOP1(inNumSamples, ZXP(out) = ZXP(a) * recip;); } } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, ZXP(out) = ZXP(a) / xb; xb += slope;); unit->mPrevB = xb; } } void div_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { if (xa == 0.f) { ZClear(inNumSamples, out); } else { LOOP1(inNumSamples, ZXP(out) = xa / ZXP(b);); } } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, ZXP(out) = xa / ZXP(b); xa += slope;); unit->mPrevA = xa; } } void div_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, ZXP(out) = xa / ZXP(b);); unit->mPrevA = xa; } void div_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); float rxb = 1.f / xb; LOOP1(inNumSamples, ZXP(out) = ZXP(a) * rxb;); unit->mPrevB = xb; } #ifdef NOVA_SIMD FLATTEN void div_aa_nova(BinaryOpUGen* unit, int inNumSamples) { nova::over_vec_simd(OUT(0), IN(0), IN(1), inNumSamples); } FLATTEN void div_ia_nova(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); nova::over_vec_simd(OUT(0), xa, IN(1), inNumSamples); unit->mPrevA = xa; } FLATTEN void div_ai_nova(BinaryOpUGen* unit, int inNumSamples) { float xb = ZIN0(1); nova::times_vec_simd(OUT(0), IN(0), sc_reciprocal(xb), inNumSamples); unit->mPrevB = xb; } FLATTEN void div_ak_nova(BinaryOpUGen* unit, int inNumSamples) { float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { if (xb == 0.f) nova::zerovec_simd(OUT(0), inNumSamples); else if (xb == 1.f) nova::copyvec_simd(OUT(0), IN(0), inNumSamples); else { float recip = 1.f / xb; nova::times_vec_simd(OUT(0), IN(0), recip, inNumSamples); } } else { float slope = CALCSLOPE(next_b, xb); nova::over_vec_simd(OUT(0), IN(0), slope_argument(xb, slope), inNumSamples); unit->mPrevB = next_b; } } FLATTEN void div_ka_nova(BinaryOpUGen* unit, int inNumSamples) { float xa = unit->mPrevA; float next_a = ZIN0(0); if (xa == next_a) { if (xa == 0.f) nova::zerovec_simd(OUT(0), inNumSamples); else nova::over_vec_simd(OUT(0), xa, IN(1), inNumSamples); } else { float slope = CALCSLOPE(next_a, xa); nova::over_vec_simd(OUT(0), slope_argument(xa, slope), IN(1), inNumSamples); unit->mPrevA = next_a; } } #endif void idiv_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, ZXP(out) = floor(ZXP(a) / ZXP(b));); } void idiv_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { ZXP(out) = floor(ZXP(a) / xb); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, ZXP(out) = floor(ZXP(a) / xb); xb += slope;); unit->mPrevB = xb; } } void idiv_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { if (xa == 0.f) { ZClear(inNumSamples, out); } else { LOOP1(inNumSamples, ZXP(out) = floor(xa / ZXP(b));); } } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, ZXP(out) = floor(xa / ZXP(b)); xa += slope;); unit->mPrevA = xa; } } void idiv_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, ZXP(out) = floor(xa / ZXP(b));); } void idiv_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, ZXP(out) = floor(ZXP(a) / xb);); } void mod_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = sc_mod(xa, xb);); } void mod_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { if (xb == 0.f) { ZCopy(inNumSamples, out, a); } else { LOOP1(inNumSamples, ZXP(out) = sc_mod(ZXP(a), xb);); } } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, ZXP(out) = sc_mod(ZXP(a), xb); xb += slope;); unit->mPrevB = xb; } } void mod_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { if (xa == 0.f) { ZClear(inNumSamples, out); } else { LOOP1(inNumSamples, ZXP(out) = sc_mod(xa, ZXP(b));); } } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, ZXP(out) = sc_mod(xa, ZXP(b)); xa += slope;); unit->mPrevA = xa; } } void mod_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, ZXP(out) = sc_mod(xa, ZXP(b));); unit->mPrevA = xa; } void mod_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, ZXP(out) = sc_mod(ZXP(a), xb);); unit->mPrevB = xb; } void max_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = sc_max(xa, xb);); } void max_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_max(xa, xb);); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_max(xa, xb); xb += slope;); unit->mPrevB = xb; } } void max_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_max(xa, xb);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_max(xa, xb); xa += slope;); unit->mPrevA = xa; } } void max_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_max(xa, xb);); unit->mPrevA = xa; } void max_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_max(xa, xb);); unit->mPrevB = xb; } #ifdef NOVA_SIMD NOVA_BINARY_WRAPPER_K(max, max) #endif void min_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = sc_min(xa, xb);); } void min_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_min(xa, xb);); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_min(xa, xb); xb += slope;); unit->mPrevB = xb; } } void min_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_min(xa, xb);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_min(xa, xb); xa += slope;); unit->mPrevA = xa; } } void min_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_min(xa, xb);); unit->mPrevA = xa; } void min_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_min(xa, xb);); unit->mPrevB = xb; } #ifdef NOVA_SIMD NOVA_BINARY_WRAPPER_K(min, min) #endif void and_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = sc_andt(xa, xb);); } void and_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_andt(xa, xb);); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_andt(xa, xb); xb += slope;); unit->mPrevB = xb; } } void and_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_andt(xa, xb);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_andt(xa, xb); xa += slope;); unit->mPrevA = xa; } } void and_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_andt(xa, xb);); unit->mPrevA = xa; } void and_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_andt(xa, xb);); unit->mPrevB = xb; } void or_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = sc_ort(xa, xb);); } void or_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_ort(xa, xb);); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_ort(xa, xb); xb += slope;); unit->mPrevB = xb; } } void or_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_ort(xa, xb);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_ort(xa, xb); xa += slope;); unit->mPrevA = xa; } } void or_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_ort(xa, xb);); unit->mPrevA = xa; } void or_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_ort(xa, xb);); unit->mPrevB = xb; } void xor_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = sc_xort(xa, xb);); } void xor_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_xort(xa, xb);); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_xort(xa, xb); xb += slope;); unit->mPrevB = xb; } } void xor_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_xort(xa, xb);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_xort(xa, xb); xa += slope;); unit->mPrevA = xa; } } void xor_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_xort(xa, xb);); unit->mPrevA = xa; } void xor_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_xort(xa, xb);); unit->mPrevB = xb; } void rightShift_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = sc_rst(xa, xb);); } void rightShift_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_rst(xa, xb);); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_rst(xa, xb); xb += slope;); unit->mPrevB = xb; } } void rightShift_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_rst(xa, xb);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_rst(xa, xb); xa += slope;); unit->mPrevA = xa; } } void rightShift_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_rst(xa, xb);); unit->mPrevA = xa; } void rightShift_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_rst(xa, xb);); unit->mPrevB = xb; } void leftShift_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = sc_lst(xa, xb);); } void leftShift_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_lst(xa, xb);); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_lst(xa, xb); xb += slope;); unit->mPrevB = xb; } } void leftShift_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_lst(xa, xb);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_lst(xa, xb); xa += slope;); unit->mPrevA = xa; } } void leftShift_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_lst(xa, xb);); unit->mPrevA = xa; } void leftShift_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_lst(xa, xb);); unit->mPrevB = xb; } void lcm_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = sc_lcm(xa, xb);); } void lcm_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_lcm(xa, xb);); unit->mPrevB = xb; } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_lcm(xa, xb); xb += slope;); unit->mPrevB = xb; } } void lcm_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_lcm(xa, xb);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_lcm(xa, xb); xa += slope;); unit->mPrevA = xa; } } void lcm_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_lcm(xa, xb);); unit->mPrevA = xa; } void lcm_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_lcm(xa, xb);); unit->mPrevB = xb; } void gcd_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = sc_gcd(xa, xb);); } void gcd_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_gcd(xa, xb);); unit->mPrevB = xb; } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_gcd(xa, xb); xb += slope;); unit->mPrevB = xb; } } void gcd_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_gcd(xa, xb);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_gcd(xa, xb); xa += slope;); unit->mPrevA = xa; } } void gcd_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_gcd(xa, xb);); unit->mPrevA = xa; } void gcd_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_gcd(xa, xb);); unit->mPrevB = xb; } void amclip_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = sc_amclip(xa, xb);); } void amclip_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { if (xb > 0.f) { LOOP1(inNumSamples, ZXP(out) = ZXP(a) * xb;); } else { ZClear(inNumSamples, out); } } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_amclip(xa, xb); xb += slope;); unit->mPrevB = xb; } } void amclip_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_amclip(xa, xb);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_amclip(xa, xb); xa += slope;); unit->mPrevA = xa; } } void amclip_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_amclip(xa, xb);); unit->mPrevA = xa; } void amclip_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_amclip(xa, xb);); unit->mPrevB = xb; } void scaleneg_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = xa >= 0.f ? xa : xa * xb;); } void scaleneg_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa >= 0.f ? xa : xa * xb;); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa >= 0.f ? xa : xa * xb; xb += slope;); unit->mPrevB = xb; } } void scaleneg_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { if (xa >= 0.f) { LOOP1(inNumSamples, ZXP(out) = xa;); } else { LOOP1(inNumSamples, ZXP(out) = xa * ZXP(b);); } } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa >= 0.f ? xa : xa * xb; xa += slope;); unit->mPrevA = xa; } } void scaleneg_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa >= 0.f ? xa : xa * xb;); unit->mPrevA = xa; } void scaleneg_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa >= 0.f ? xa : xa * xb;); unit->mPrevB = xb; } void pow_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = xa >= 0.f ? pow(xa, xb) : -pow(-xa, xb);); } void pow_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa >= 0.f ? pow(xa, xb) : -pow(-xa, xb);); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa >= 0.f ? pow(xa, xb) : -pow(-xa, xb); xb += slope;); unit->mPrevB = xb; } } void pow_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { if (xa >= 0.f) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = pow(xa, xb);); } else { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = -pow(-xa, xb);); } } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa >= 0.f ? pow(xa, xb) : -pow(-xa, xb); xa += slope;); unit->mPrevA = xa; } } void pow_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa >= 0.f ? pow(xa, xb) : -pow(-xa, xb);); unit->mPrevA = xa; } void pow_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa >= 0.f ? pow(xa, xb) : -pow(-xa, xb);); unit->mPrevB = xb; } #ifdef NOVA_SIMD FLATTEN void pow_aa_nova(BinaryOpUGen* unit, int inNumSamples) { nova::spow_vec_simd(OUT(0), IN(0), IN(1), inNumSamples); } FLATTEN void pow_ak_nova(BinaryOpUGen* unit, int inNumSamples) { float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) nova::spow_vec_simd(OUT(0), IN(0), xb, inNumSamples); else { float slope = CALCSLOPE(next_b, xb); nova::spow_vec_simd(OUT(0), IN(0), slope_argument(xb, slope), inNumSamples); unit->mPrevB = next_b; } } FLATTEN void pow_ka_nova(BinaryOpUGen* unit, int inNumSamples) { float xa = unit->mPrevA; float next_a = ZIN0(0); if (xa == next_a) { if (xa >= 0.f) nova::pow_vec_simd(OUT(0), xa, IN(1), inNumSamples); else nova::spow_vec_simd(OUT(0), xa, IN(1), inNumSamples); } else { float slope = CALCSLOPE(next_a, xa); nova::spow_vec_simd(OUT(0), slope_argument(xa, slope), IN(1), inNumSamples); unit->mPrevA = next_a; } } FLATTEN void pow_ia_nova(BinaryOpUGen* unit, int inNumSamples) { float xa = ZIN0(0); if (xa > 0.f) nova::pow_vec_simd(OUT(0), xa, IN(1), inNumSamples); else nova::spow_vec_simd(OUT(0), xa, IN(1), inNumSamples); unit->mPrevA = xa; } FLATTEN void pow_ai_nova(BinaryOpUGen* unit, int inNumSamples) { float xb = ZIN0(1); nova::spow_vec_simd(OUT(0), IN(0), xb, inNumSamples); } #endif #ifdef NOVA_SIMD NOVA_BINARY_WRAPPER(ring1, sc_ring1) NOVA_BINARY_WRAPPER(ring2, sc_ring2) NOVA_BINARY_WRAPPER(ring3, sc_ring3) NOVA_BINARY_WRAPPER(ring4, sc_ring4) #endif void ring1_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = xa * xb + xa;); } void ring1_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { if (xb == 0.f) { ZCopy(inNumSamples, out, a); } else if (xb == 1.f) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa + xa;); } else { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa * xb + xa;); } } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa * xb + xa; xb += slope;); unit->mPrevB = xb; } } void ring1_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { if (xa == 0.f) { LOOP1(inNumSamples, ZXP(out) = 0.f;); } else { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa * xb + xa;); } } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa * xb + xa; xa += slope;); unit->mPrevA = xa; } } void ring1_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa * xb + xa;); unit->mPrevA = xa; } void ring1_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa * xb + xa;); unit->mPrevB = xb; } void ring2_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = xa * xb + xa + xb;); } void ring2_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { if (xb == 0.f) { ZCopy(inNumSamples, out, a); } else { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa * xb + xa + xb;); } } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa * xb + xa + xb; xb += slope;); unit->mPrevB = xb; } } void ring2_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { if (xa == 0.f) { ZCopy(inNumSamples, out, b); } else { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa * xb + xa + xb;); } } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa * xb + xa + xb; xa += slope;); unit->mPrevA = xa; } } void ring2_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa * xb + xa + xb;); unit->mPrevA = xa; } void ring2_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa * xb + xa + xb;); unit->mPrevB = xb; } void ring3_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = xa * xa * xb;); } void ring3_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { if (xb == 0.f) { ZClear(inNumSamples, out); } else if (xb == 1.f) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa * xa;); } else { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa * xa * xb;); } } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa * xa * xb; xb += slope;); unit->mPrevB = xb; } } void ring3_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { if (xa == 0.f) { ZClear(inNumSamples, out); } else if (xa == 1.f) { ZCopy(inNumSamples, out, b); } else { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa * xa * xb;); } } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa * xa * xb; xa += slope;); unit->mPrevA = xa; } } void ring3_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa * xa * xb;); unit->mPrevA = xa; } void ring3_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa * xa * xb;); unit->mPrevB = xb; } void ring4_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = xa * xa * xb - xa * xb * xb;); } void ring4_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { if (xb == 0.f) { ZClear(inNumSamples, out); } else if (xb == 1.f) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa * xa - xa;); } else { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa * xa * xb - xa * xb * xb;); } } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa * xa * xb - xa * xb * xb; xb += slope;); unit->mPrevB = xb; } } void ring4_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { if (xa == 0.f) { ZClear(inNumSamples, out); } else if (xa == 1.f) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xb - xb * xb;); } else { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa * xa * xb - xa * xb * xb;); } } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa * xa * xb - xa * xb * xb; xa += slope;); unit->mPrevA = xa; } } void ring4_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa * xa * xb - xa * xb * xb;); unit->mPrevA = xa; } void ring4_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa * xa * xb - xa * xb * xb;); unit->mPrevB = xb; } void thresh_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = xa < xb ? 0.f : xa;); } void thresh_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa < xb ? 0.f : xa;); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa < xb ? 0.f : xa; xb += slope;); unit->mPrevB = xb; } } void thresh_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa < xb ? 0.f : xa;); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa < xb ? 0.f : xa; xa += slope;); unit->mPrevA = xa; } } void thresh_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa < xb ? 0.f : xa;); unit->mPrevA = xa; } void thresh_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa < xb ? 0.f : xa;); unit->mPrevB = xb; } void clip2_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = xa > xb ? xb : (xa < -xb ? -xb : xa);); } void clip2_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa > xb ? xb : (xa < -xb ? -xb : xa);); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa > xb ? xb : (xa < -xb ? -xb : xa); xb += slope;); unit->mPrevB = xb; } } void clip2_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa > xb ? xb : (xa < -xb ? -xb : xa);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa > xb ? xb : (xa < -xb ? -xb : xa); xa += slope;); unit->mPrevA = xa; } } void clip2_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa > xb ? xb : (xa < -xb ? -xb : xa);); unit->mPrevA = xa; } void clip2_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa > xb ? xb : (xa < -xb ? -xb : xa);); unit->mPrevB = xb; } #ifdef NOVA_SIMD NOVA_BINARY_WRAPPER_K(clip2, clip2) #endif void excess_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = xa > xb ? xa - xb : (xa < -xb ? xa + xb : 0.f);); } void excess_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa > xb ? xa - xb : (xa < -xb ? xa + xb : 0.f);); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa > xb ? xa - xb : (xa < -xb ? xa + xb : 0.f); xb += slope;); unit->mPrevB = xb; } } void excess_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa > xb ? xa - xb : (xa < -xb ? xa + xb : 0.f);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa > xb ? xa - xb : (xa < -xb ? xa + xb : 0.f); xa += slope;); unit->mPrevA = xa; } } void excess_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa > xb ? xa - xb : (xa < -xb ? xa + xb : 0.f);); unit->mPrevA = xa; } void excess_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa > xb ? xa - xb : (xa < -xb ? xa + xb : 0.f);); unit->mPrevB = xb; } void rrand_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); RGET LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = xb > xa ? xa + frand2(s1, s2, s3) * (xb - xa) : (xb + frand2(s1, s2, s3) * (xa - xb));); RPUT } void rrand_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); RGET if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xb > xa ? xa + frand2(s1, s2, s3) * (xb - xa) : (xb + frand2(s1, s2, s3) * (xa - xb));); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xb > xa ? xa + frand2(s1, s2, s3) * (xb - xa) : (xb + frand2(s1, s2, s3) * (xa - xb)); xb += slope;); unit->mPrevB = xb; } RPUT } void rrand_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); RGET if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xb > xa ? xa + frand2(s1, s2, s3) * (xb - xa) : (xb + frand2(s1, s2, s3) * (xa - xb));); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xb > xa ? xa + frand2(s1, s2, s3) * (xb - xa) : (xb + frand2(s1, s2, s3) * (xa - xb)); xa += slope;); unit->mPrevA = xa; } RPUT } void rrand_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); RGET LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xb > xa ? xa + frand2(s1, s2, s3) * (xb - xa) : (xb + frand2(s1, s2, s3) * (xa - xb));); unit->mPrevA = xa; RPUT } void rrand_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); RGET LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xb > xa ? xa + frand2(s1, s2, s3) * (xb - xa) : (xb + frand2(s1, s2, s3) * (xa - xb));); RPUT unit->mPrevB = xb; } void exprand_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); RGen& rgen = *unit->mParent->mRGen; ZXP(out) = xb > xa ? rgen.exprandrng(xa, xb) : rgen.exprandrng(xb, xa);); } void exprand_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); RGen& rgen = *unit->mParent->mRGen; if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xb > xa ? rgen.exprandrng(xa, xb) : rgen.exprandrng(xb, xa);); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xb > xa ? rgen.exprandrng(xa, xb) : rgen.exprandrng(xb, xa); xb += slope;); unit->mPrevB = xb; } } void exprand_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); RGen& rgen = *unit->mParent->mRGen; if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xb > xa ? rgen.exprandrng(xa, xb) : rgen.exprandrng(xb, xa);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xb > xa ? rgen.exprandrng(xa, xb) : rgen.exprandrng(xb, xa); xa += slope;); unit->mPrevA = xa; } } void exprand_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); RGen& rgen = *unit->mParent->mRGen; ZXP(out) = xb > xa ? rgen.exprandrng(xa, xb) : rgen.exprandrng(xb, xa);); unit->mPrevA = xa; } void exprand_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); RGen& rgen = *unit->mParent->mRGen; ZXP(out) = xb > xa ? rgen.exprandrng(xa, xb) : rgen.exprandrng(xb, xa);); unit->mPrevB = xb; } void lt_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = xa < xb ? 1.f : 0.f;); } #ifdef NOVA_SIMD NOVA_BINARY_WRAPPER_K(lt, less) #endif void lt_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa < xb ? 1.f : 0.f;); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa < xb ? 1.f : 0.f; xb += slope;); unit->mPrevB = xb; } } void lt_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa < xb ? 1.f : 0.f;); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa < xb ? 1.f : 0.f; xa += slope;); unit->mPrevA = xa; } } void lt_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa < xb ? 1.f : 0.f;); unit->mPrevA = xa; } void lt_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa < xb ? 1.f : 0.f;); unit->mPrevB = xb; } void le_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = xa <= xb ? 1.f : 0.f;); } #ifdef NOVA_SIMD NOVA_BINARY_WRAPPER_K(le, less_equal) #endif void le_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa <= xb ? 1.f : 0.f;); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa <= xb ? 1.f : 0.f; xb += slope;); unit->mPrevB = xb; } } void le_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa <= xb ? 1.f : 0.f;); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa <= xb ? 1.f : 0.f; xa += slope;); unit->mPrevA = xa; } } void le_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa <= xb ? 1.f : 0.f;); unit->mPrevA = xa; } void le_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa <= xb ? 1.f : 0.f;); unit->mPrevB = xb; } void gt_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = xa > xb ? 1.f : 0.f;); } #ifdef NOVA_SIMD NOVA_BINARY_WRAPPER_K(gt, greater) #endif void gt_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa > xb ? 1.f : 0.f;); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa > xb ? 1.f : 0.f; xb += slope;); unit->mPrevB = xb; } } void gt_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa > xb ? 1.f : 0.f;); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa > xb ? 1.f : 0.f; xa += slope;); unit->mPrevA = xa; } } void gt_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa > xb ? 1.f : 0.f;); unit->mPrevA = xa; } void gt_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa > xb ? 1.f : 0.f;); unit->mPrevB = xb; } void ge_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = xa >= xb ? 1.f : 0.f;); } #ifdef NOVA_SIMD NOVA_BINARY_WRAPPER_K(ge, greater_equal) #endif void ge_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa >= xb ? 1.f : 0.f;); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa >= xb ? 1.f : 0.f; xb += slope;); unit->mPrevB = xb; } } void ge_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa >= xb ? 1.f : 0.f;); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa >= xb ? 1.f : 0.f; xa += slope;); unit->mPrevA = xa; } } void ge_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa >= xb ? 1.f : 0.f;); unit->mPrevA = xa; } void ge_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa >= xb ? 1.f : 0.f;); unit->mPrevB = xb; } void eq_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = xa == xb ? 1.f : 0.f;); } #ifdef NOVA_SIMD NOVA_BINARY_WRAPPER_K(eq, equal) #endif void eq_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa == xb ? 1.f : 0.f;); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa == xb ? 1.f : 0.f; xb += slope;); unit->mPrevB = xb; } } void eq_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa == xb ? 1.f : 0.f;); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa == xb ? 1.f : 0.f; xa += slope;); unit->mPrevA = xa; } } void eq_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa == xb ? 1.f : 0.f;); unit->mPrevA = xa; } void eq_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa == xb ? 1.f : 0.f;); unit->mPrevB = xb; } void neq_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = xa != xb ? 1.f : 0.f;); } #ifdef NOVA_SIMD NOVA_BINARY_WRAPPER_K(neq, notequal) #endif void neq_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa != xb ? 1.f : 0.f;); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa != xb ? 1.f : 0.f; xb += slope;); unit->mPrevB = xb; } } void neq_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa != xb ? 1.f : 0.f;); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa != xb ? 1.f : 0.f; xa += slope;); unit->mPrevA = xa; } } void neq_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa != xb ? 1.f : 0.f;); unit->mPrevA = xa; } void neq_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa != xb ? 1.f : 0.f;); unit->mPrevB = xb; } #ifdef NOVA_SIMD NOVA_BINARY_WRAPPER_K(sumsqr, sc_sumsqr) NOVA_BINARY_WRAPPER_K(difsqr, sc_difsqr) NOVA_BINARY_WRAPPER_K(sqrsum, sc_sqrsum) NOVA_BINARY_WRAPPER_K(sqrdif, sc_sqrdif) #endif void sumsqr_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = xa * xa + xb * xb;); } void sumsqr_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa * xa + xb * xb;); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa * xa + xb * xb; xb += slope;); unit->mPrevB = xb; } } void sumsqr_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa * xa + xb * xb;); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa * xa + xb * xb; xa += slope;); unit->mPrevA = xa; } } void sumsqr_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa * xa + xb * xb;); unit->mPrevA = xa; } void sumsqr_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa * xa + xb * xb;); unit->mPrevB = xb; } void difsqr_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = xa * xa - xb * xb;); } void difsqr_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa * xa - xb * xb;); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa * xa - xb * xb; xb += slope;); unit->mPrevB = xb; } } void difsqr_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa * xa - xb * xb;); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa * xa - xb * xb; xa += slope;); unit->mPrevA = xa; } } void difsqr_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = xa * xa - xb * xb;); unit->mPrevA = xa; } void difsqr_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = xa * xa - xb * xb;); unit->mPrevB = xb; } void sqrsum_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float sum = ZXP(a) + ZXP(b); ZXP(out) = sum * sum;); } void sqrsum_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); float sum = xa + xb; ZXP(out) = sum * sum;); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); float sum = xa + xb; ZXP(out) = sum * sum; xb += slope;); unit->mPrevB = xb; } } void sqrsum_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); float sum = xa + xb; ZXP(out) = sum * sum;); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); float sum = xa + xb; ZXP(out) = sum * sum; xa += slope;); unit->mPrevA = xa; } } void sqrsum_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); float sum = xa + xb; ZXP(out) = sum * sum;); unit->mPrevA = xa; } void sqrsum_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); float sum = xa + xb; ZXP(out) = sum * sum;); unit->mPrevB = xb; } void sqrdif_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float dif = ZXP(a) - ZXP(b); ZXP(out) = dif * dif;); } void sqrdif_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); float dif = xa - xb; ZXP(out) = dif * dif;); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); float dif = xa - xb; ZXP(out) = dif * dif; xb += slope;); unit->mPrevB = xb; } } void sqrdif_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); float dif = xa - xb; ZXP(out) = dif * dif;); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); float dif = xa - xb; ZXP(out) = dif * dif; xa += slope;); unit->mPrevA = xa; } } void sqrdif_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); float dif = xa - xb; ZXP(out) = dif * dif;); unit->mPrevA = xa; } void sqrdif_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); float dif = xa - xb; ZXP(out) = dif * dif;); unit->mPrevB = xb; } void absdif_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float dif = ZXP(a) - ZXP(b); ZXP(out) = fabs(dif);); } void absdif_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); float dif = xa - xb; ZXP(out) = fabs(dif);); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); float dif = xa - xb; ZXP(out) = fabs(dif); xb += slope;); unit->mPrevB = xb; } } void absdif_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); float dif = xa - xb; ZXP(out) = fabs(dif);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); float dif = xa - xb; ZXP(out) = fabs(dif); xa += slope;); unit->mPrevA = xa; } } void absdif_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); float dif = xa - xb; ZXP(out) = fabs(dif);); unit->mPrevA = xa; } void absdif_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); float dif = xa - xb; ZXP(out) = fabs(dif);); unit->mPrevB = xb; } void round_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = sc_round(xa, xb);); } void round_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_round(xa, xb);); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_round(xa, xb); xb += slope;); unit->mPrevB = xb; } } void round_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_round(xa, xb);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_round(xa, xb); xa += slope;); unit->mPrevA = xa; } } void round_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_round(xa, xb);); unit->mPrevA = xa; } void round_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_round(xa, xb);); unit->mPrevB = xb; } void roundUp_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = sc_roundUp(xa, xb);); } void roundUp_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_roundUp(xa, xb);); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_roundUp(xa, xb); xb += slope;); unit->mPrevB = xb; } } void roundUp_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_roundUp(xa, xb);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_roundUp(xa, xb); xa += slope;); unit->mPrevA = xa; } } void roundUp_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_roundUp(xa, xb);); unit->mPrevA = xa; } void roundUp_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_roundUp(xa, xb);); unit->mPrevB = xb; } void trunc_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = sc_trunc(xa, xb);); } void trunc_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_trunc(xa, xb);); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_trunc(xa, xb); xb += slope;); unit->mPrevB = xb; } } void trunc_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_trunc(xa, xb);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_trunc(xa, xb); xa += slope;); unit->mPrevA = xa; } } void trunc_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_trunc(xa, xb);); unit->mPrevA = xa; } void trunc_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_trunc(xa, xb);); unit->mPrevB = xb; } void fold2_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = sc_fold(xa, -xb, xb);); } void fold2_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_fold(xa, -xb, xb);); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_fold(xa, -xb, xb); xb += slope;); unit->mPrevB = xb; } } void fold2_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_fold(xa, -xb, xb);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_fold(xa, -xb, xb); xa += slope;); unit->mPrevA = xa; } } void fold2_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_fold(xa, -xb, xb);); unit->mPrevA = xa; } void fold2_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_fold(xa, -xb, xb);); unit->mPrevB = xb; } void wrap2_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = sc_wrap(xa, -xb, xb);); } void wrap2_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_wrap(xa, -xb, xb);); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_wrap(xa, -xb, xb); xb += slope;); unit->mPrevB = xb; } } void wrap2_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_wrap(xa, -xb, xb);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_wrap(xa, -xb, xb); xa += slope;); unit->mPrevA = xa; } } void wrap2_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_wrap(xa, -xb, xb);); unit->mPrevA = xa; } void wrap2_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_wrap(xa, -xb, xb);); unit->mPrevB = xb; } void atan2_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = atan2(xa, xb);); } void atan2_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = atan2(xa, xb);); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = atan2(xa, xb); xb += slope;); unit->mPrevB = xb; } } void atan2_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = atan2(xa, xb);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = atan2(xa, xb); xa += slope;); unit->mPrevA = xa; } } void atan2_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = atan2(xa, xb);); unit->mPrevA = xa; } void atan2_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = atan2(xa, xb);); unit->mPrevB = xb; } void hypot_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = hypotf(xa, xb);); } void hypot_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = hypotf(xa, xb);); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = hypotf(xa, xb); xb += slope;); unit->mPrevB = xb; } } void hypot_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = hypotf(xa, xb);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = hypotf(xa, xb); xa += slope;); unit->mPrevA = xa; } } void hypot_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = hypotf(xa, xb);); unit->mPrevA = xa; } void hypot_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = hypotf(xa, xb);); unit->mPrevB = xb; } void hypotx_aa(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); LOOP1(inNumSamples, float xa = ZXP(a); float xb = ZXP(b); ZXP(out) = sc_hypotx(xa, xb);); } void hypotx_ak(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = unit->mPrevB; float next_b = ZIN0(1); if (xb == next_b) { LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_hypotx(xa, xb);); } else { float slope = CALCSLOPE(next_b, xb); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_hypotx(xa, xb); xb += slope;); unit->mPrevB = xb; } } void hypotx_ka(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = unit->mPrevA; float* b = ZIN(1); float next_a = ZIN0(0); if (xa == next_a) { LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_hypotx(xa, xb);); } else { float slope = CALCSLOPE(next_a, xa); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_hypotx(xa, xb); xa += slope;); unit->mPrevA = xa; } } void hypotx_ia(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); LOOP1(inNumSamples, float xb = ZXP(b); ZXP(out) = sc_hypotx(xa, xb);); unit->mPrevA = xa; } void hypotx_ai(BinaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); LOOP1(inNumSamples, float xa = ZXP(a); ZXP(out) = sc_hypotx(xa, xb);); unit->mPrevB = xb; } static BinaryOpFunc ChooseOneSampleFunc(BinaryOpUGen* unit) { BinaryOpFunc func = &zero_1; switch (unit->mSpecialIndex) { // case opSilence2 : func = &zero_1; break; case opAdd: func = &add_1; break; case opSub: func = &sub_1; break; case opMul: func = &mul_1; break; case opFDiv: func = &div_1; break; case opIDiv: func = &idiv_1; break; case opMod: func = &mod_1; break; case opEQ: func = &eq_1; break; case opNE: func = &neq_1; break; case opLT: func = &lt_1; break; case opGT: func = &gt_1; break; case opLE: func = &le_1; break; case opGE: func = &ge_1; break; case opMin: func = &min_1; break; case opMax: func = &max_1; break; case opBitAnd: func = &and_1; break; case opBitOr: func = &or_1; break; case opBitXor: func = &xor_1; break; case opShiftRight: func = &rightShift_1; break; case opShiftLeft: func = &leftShift_1; break; case opLCM: func = &lcm_1; break; case opGCD: func = &gcd_1; break; case opRound: func = &round_1; break; case opRoundUp: func = &roundUp_1; break; case opTrunc: func = &trunc_1; break; case opAtan2: func = &atan2_1; break; case opHypot: func = &hypot_1; break; case opHypotx: func = &hypotx_1; break; case opPow: func = &pow_1; break; case opRing1: func = &ring1_1; break; case opRing2: func = &ring2_1; break; case opRing3: func = &ring3_1; break; case opRing4: func = &ring4_1; break; case opDifSqr: func = &difsqr_1; break; case opSumSqr: func = &sumsqr_1; break; case opSqrSum: func = &sqrsum_1; break; case opSqrDif: func = &sqrdif_1; break; case opAbsDif: func = &absdif_1; break; case opThresh: func = &thresh_1; break; case opAMClip: func = &amclip_1; break; case opScaleNeg: func = &scaleneg_1; break; case opClip2: func = &clip2_1; break; case opFold2: func = &fold2_1; break; case opWrap2: func = &wrap2_1; break; case opExcess: func = &excess_1; break; case opFirstArg: func = &firstarg_1; break; case opRandRange: func = &rrand_1; break; case opExpRandRange: func = &exprand_1; break; // case opSecondArg : func = &secondarg_1; break; default: func = &add_1; break; } return func; } static BinaryOpFunc ChooseDemandFunc(BinaryOpUGen* unit) { BinaryOpFunc func = &zero_1; switch (unit->mSpecialIndex) { // case opSilence2 : func = &zero_d; break; case opAdd: func = &add_d; break; case opSub: func = &sub_d; break; case opMul: func = &mul_d; break; case opFDiv: func = &div_d; break; case opIDiv: func = &idiv_d; break; case opMod: func = &mod_d; break; case opEQ: func = &eq_d; break; case opNE: func = &neq_d; break; case opLT: func = &lt_d; break; case opGT: func = &gt_d; break; case opLE: func = &le_d; break; case opGE: func = &ge_d; break; case opMin: func = &min_d; break; case opMax: func = &max_d; break; case opBitAnd: func = &and_d; break; case opBitOr: func = &or_d; break; case opBitXor: func = &xor_d; break; case opShiftRight: func = &rightShift_d; break; case opShiftLeft: func = &leftShift_d; break; case opLCM: func = &lcm_d; break; case opGCD: func = &gcd_d; break; case opRound: func = &round_d; break; case opRoundUp: func = &roundUp_d; break; case opTrunc: func = &trunc_d; break; case opAtan2: func = &atan2_d; break; case opHypot: func = &hypot_d; break; case opHypotx: func = &hypotx_d; break; case opPow: func = &pow_d; break; case opRing1: func = &ring1_d; break; case opRing2: func = &ring2_d; break; case opRing3: func = &ring3_d; break; case opRing4: func = &ring4_d; break; case opDifSqr: func = &difsqr_d; break; case opSumSqr: func = &sumsqr_d; break; case opSqrSum: func = &sqrsum_d; break; case opSqrDif: func = &sqrdif_d; break; case opAbsDif: func = &absdif_d; break; case opThresh: func = &thresh_d; break; case opAMClip: func = &amclip_d; break; case opScaleNeg: func = &scaleneg_d; break; case opClip2: func = &clip2_d; break; case opFold2: func = &fold2_d; break; case opWrap2: func = &wrap2_d; break; case opExcess: func = &excess_d; break; case opFirstArg: func = &firstarg_d; break; case opRandRange: func = &rrand_d; break; case opExpRandRange: func = &exprand_d; break; // case opSecondArg : func = &secondarg_d; break; default: func = &add_d; break; } return func; } static BinaryOpFunc ChooseNormalFunc(BinaryOpUGen* unit) { BinaryOpFunc func = &zero_1; int rateA = INRATE(0); int rateB = INRATE(1); switch (rateA) { case calc_FullRate: switch (rateB) { case calc_FullRate: switch (unit->mSpecialIndex) { // case opSilence2 : func = &zero_aa; break; case opAdd: func = &add_aa; break; case opSub: func = &sub_aa; break; case opMul: func = &mul_aa; break; case opFDiv: func = &div_aa; break; case opIDiv: func = &idiv_aa; break; case opMod: func = &mod_aa; break; case opEQ: func = &eq_aa; break; case opNE: func = &neq_aa; break; case opLT: func = &lt_aa; break; case opGT: func = &gt_aa; break; case opLE: func = &le_aa; break; case opGE: func = &ge_aa; break; case opMin: func = &min_aa; break; case opMax: func = &max_aa; break; case opBitAnd: func = &and_aa; break; case opBitOr: func = &or_aa; break; case opBitXor: func = &xor_aa; break; case opShiftRight: func = &rightShift_aa; break; case opShiftLeft: func = &leftShift_aa; break; case opLCM: func = &lcm_aa; break; case opGCD: func = &gcd_aa; break; case opRound: func = &round_aa; break; case opRoundUp: func = &roundUp_aa; break; case opTrunc: func = &trunc_aa; break; case opAtan2: func = &atan2_aa; break; case opHypot: func = &hypot_aa; break; case opHypotx: func = &hypotx_aa; break; case opPow: func = &pow_aa; break; case opRing1: func = &ring1_aa; break; case opRing2: func = &ring2_aa; break; case opRing3: func = &ring3_aa; break; case opRing4: func = &ring4_aa; break; case opDifSqr: func = &difsqr_aa; break; case opSumSqr: func = &sumsqr_aa; break; case opSqrSum: func = &sqrsum_aa; break; case opSqrDif: func = &sqrdif_aa; break; case opAbsDif: func = &absdif_aa; break; case opThresh: func = &thresh_aa; break; case opAMClip: func = &amclip_aa; break; case opScaleNeg: func = &scaleneg_aa; break; case opClip2: func = &clip2_aa; break; case opFold2: func = &fold2_aa; break; case opWrap2: func = &wrap2_aa; break; case opExcess: func = &excess_aa; break; case opRandRange: func = &rrand_aa; break; case opExpRandRange: func = &exprand_aa; break; case opFirstArg: func = &firstarg_aa; break; // case opSecondArg : func = &secondarg_aa; break; default: func = &add_aa; break; } break; case calc_BufRate: switch (unit->mSpecialIndex) { // case opSilence2 : func = &zero_aa; break; case opAdd: func = &add_ak; break; case opSub: func = &sub_ak; break; case opMul: func = &mul_ak; break; case opFDiv: func = &div_ak; break; case opIDiv: func = &idiv_ak; break; case opMod: func = &mod_ak; break; case opEQ: func = &eq_ak; break; case opNE: func = &neq_ak; break; case opLT: func = &lt_ak; break; case opGT: func = &gt_ak; break; case opLE: func = &le_ak; break; case opGE: func = &ge_ak; break; case opMin: func = &min_ak; break; case opMax: func = &max_ak; break; case opBitAnd: func = &and_ak; break; case opBitOr: func = &or_ak; break; case opBitXor: func = &xor_ak; break; case opShiftRight: func = &rightShift_ak; break; case opShiftLeft: func = &leftShift_ak; break; case opLCM: func = &lcm_ak; break; case opGCD: func = &gcd_ak; break; case opRound: func = &round_ak; break; case opRoundUp: func = &roundUp_ak; break; case opTrunc: func = &trunc_ak; break; case opAtan2: func = &atan2_ak; break; case opHypot: func = &hypot_ak; break; case opHypotx: func = &hypotx_ak; break; case opPow: func = &pow_ak; break; case opRing1: func = &ring1_ak; break; case opRing2: func = &ring2_ak; break; case opRing3: func = &ring3_ak; break; case opRing4: func = &ring4_ak; break; case opDifSqr: func = &difsqr_ak; break; case opSumSqr: func = &sumsqr_ak; break; case opSqrSum: func = &sqrsum_ak; break; case opSqrDif: func = &sqrdif_ak; break; case opAbsDif: func = &absdif_ak; break; case opThresh: func = &thresh_ak; break; case opAMClip: func = &amclip_ak; break; case opScaleNeg: func = &scaleneg_ak; break; case opClip2: func = &clip2_ak; break; case opFold2: func = &fold2_ak; break; case opWrap2: func = &wrap2_ak; break; case opExcess: func = &excess_ak; break; case opRandRange: func = &rrand_ak; break; case opExpRandRange: func = &exprand_ak; break; case opFirstArg: func = &firstarg_aa; break; // case opSecondArg : func = &secondarg_aa; break; default: func = &add_ak; break; } break; case calc_ScalarRate: switch (unit->mSpecialIndex) { // case opSilence2 : func = &zero_aa; break; case opAdd: func = &add_ai; break; case opSub: func = &sub_ai; break; case opMul: func = &mul_ai; break; case opFDiv: func = &div_ai; break; case opIDiv: func = &idiv_ai; break; case opMod: func = &mod_ai; break; case opEQ: func = &eq_ai; break; case opNE: func = &neq_ai; break; case opLT: func = &lt_ai; break; case opGT: func = &gt_ai; break; case opLE: func = &le_ai; break; case opGE: func = &ge_ai; break; case opMin: func = &min_ai; break; case opMax: func = &max_ai; break; case opBitAnd: func = &and_ai; break; case opBitOr: func = &or_ai; break; case opBitXor: func = &xor_ai; break; case opShiftRight: func = &rightShift_ai; break; case opShiftLeft: func = &leftShift_ai; break; case opLCM: func = &lcm_ai; break; case opGCD: func = &gcd_ai; break; case opRound: func = &round_ai; break; case opRoundUp: func = &roundUp_ai; break; case opTrunc: func = &trunc_ai; break; case opAtan2: func = &atan2_ai; break; case opHypot: func = &hypot_ai; break; case opHypotx: func = &hypotx_ai; break; case opPow: func = &pow_ai; break; case opRing1: func = &ring1_ai; break; case opRing2: func = &ring2_ai; break; case opRing3: func = &ring3_ai; break; case opRing4: func = &ring4_ai; break; case opDifSqr: func = &difsqr_ai; break; case opSumSqr: func = &sumsqr_ai; break; case opSqrSum: func = &sqrsum_ai; break; case opSqrDif: func = &sqrdif_ai; break; case opAbsDif: func = &absdif_ai; break; case opThresh: func = &thresh_ai; break; case opAMClip: func = &amclip_ai; break; case opScaleNeg: func = &scaleneg_ai; break; case opClip2: func = &clip2_ai; break; case opFold2: func = &fold2_ai; break; case opWrap2: func = &wrap2_ai; break; case opExcess: func = &excess_ai; break; case opRandRange: func = &rrand_ai; break; case opExpRandRange: func = &exprand_ai; break; case opFirstArg: func = &firstarg_aa; break; // case opSecondArg : func = &secondarg_aa; break; default: func = &add_ai; break; } } break; case calc_BufRate: if (rateB == calc_FullRate) { switch (unit->mSpecialIndex) { // case opSilence2 : func = &zero_aa; break; case opAdd: func = &add_ka; break; case opSub: func = &sub_ka; break; case opMul: func = &mul_ka; break; case opFDiv: func = &div_ka; break; case opIDiv: func = &idiv_ka; break; case opMod: func = &mod_ka; break; case opEQ: func = &eq_ka; break; case opNE: func = &neq_ka; break; case opLT: func = &lt_ka; break; case opGT: func = &gt_ka; break; case opLE: func = &le_ka; break; case opGE: func = &ge_ka; break; case opMin: func = &min_ka; break; case opMax: func = &max_ka; break; case opBitAnd: func = &and_ka; break; case opBitOr: func = &or_ka; break; case opBitXor: func = &xor_ka; break; case opShiftRight: func = &rightShift_ka; break; case opShiftLeft: func = &leftShift_ka; break; case opLCM: func = &lcm_ka; break; case opGCD: func = &gcd_ka; break; case opRound: func = &round_ka; break; case opRoundUp: func = &roundUp_ka; break; case opTrunc: func = &trunc_ka; break; case opAtan2: func = &atan2_ka; break; case opHypot: func = &hypot_ka; break; case opHypotx: func = &hypotx_ka; break; case opPow: func = &pow_ka; break; case opRing1: func = &ring1_ka; break; case opRing2: func = &ring2_ka; break; case opRing3: func = &ring3_ka; break; case opRing4: func = &ring4_ka; break; case opDifSqr: func = &difsqr_ka; break; case opSumSqr: func = &sumsqr_ka; break; case opSqrSum: func = &sqrsum_ka; break; case opSqrDif: func = &sqrdif_ka; break; case opAbsDif: func = &absdif_ka; break; case opThresh: func = &thresh_ka; break; case opAMClip: func = &amclip_ka; break; case opScaleNeg: func = &scaleneg_ka; break; case opClip2: func = &clip2_ka; break; case opFold2: func = &fold2_ka; break; case opWrap2: func = &wrap2_ka; break; case opExcess: func = &excess_ka; break; case opRandRange: func = &rrand_ka; break; case opExpRandRange: func = &exprand_ka; break; // case opFirstArg : func = &firstarg_aa; break; // case opSecondArg : func = &secondarg_aa; break; default: func = &add_ka; break; } } else { // this should have been caught by mBufLength == 1 func = &zero_aa; } break; case calc_ScalarRate: if (rateB == calc_FullRate) { switch (unit->mSpecialIndex) { // case opSilence2 : func = &zero_aa; break; case opAdd: func = &add_ia; break; case opSub: func = &sub_ia; break; case opMul: func = &mul_ia; break; case opFDiv: func = &div_ia; break; case opIDiv: func = &idiv_ia; break; case opMod: func = &mod_ia; break; case opEQ: func = &eq_ia; break; case opNE: func = &neq_ia; break; case opLT: func = &lt_ia; break; case opGT: func = &gt_ia; break; case opLE: func = &le_ia; break; case opGE: func = &ge_ia; break; case opMin: func = &min_ia; break; case opMax: func = &max_ia; break; case opBitAnd: func = &and_ia; break; case opBitOr: func = &or_ia; break; case opBitXor: func = &xor_ia; break; case opShiftRight: func = &rightShift_ia; break; case opShiftLeft: func = &leftShift_ia; break; case opLCM: func = &lcm_ia; break; case opGCD: func = &gcd_ia; break; case opRound: func = &round_ia; break; case opRoundUp: func = &roundUp_ia; break; case opTrunc: func = &trunc_ia; break; case opAtan2: func = &atan2_ia; break; case opHypot: func = &hypot_ia; break; case opHypotx: func = &hypotx_ia; break; case opPow: func = &pow_ia; break; case opRing1: func = &ring1_ia; break; case opRing2: func = &ring2_ia; break; case opRing3: func = &ring3_ia; break; case opRing4: func = &ring4_ia; break; case opDifSqr: func = &difsqr_ia; break; case opSumSqr: func = &sumsqr_ia; break; case opSqrSum: func = &sqrsum_ia; break; case opSqrDif: func = &sqrdif_ia; break; case opAbsDif: func = &absdif_ia; break; case opThresh: func = &thresh_ia; break; case opAMClip: func = &amclip_ia; break; case opScaleNeg: func = &scaleneg_ia; break; case opClip2: func = &clip2_ia; break; case opFold2: func = &fold2_ia; break; case opWrap2: func = &wrap2_ia; break; case opExcess: func = &excess_ia; break; case opRandRange: func = &rrand_ia; break; case opExpRandRange: func = &exprand_ia; break; // case opFirstArg : func = &firstarg_aa; break; // case opSecondArg : func = &secondarg_aa; break; default: func = &add_ia; break; } } else { // this should have been caught by mBufLength == 1 func = &zero_aa; } break; } return func; } #ifdef NOVA_SIMD static BinaryOpFunc ChooseNovaSimdFunc_64(BinaryOpUGen* unit) { BinaryOpFunc func = &zero_1; int rateA = INRATE(0); int rateB = INRATE(1); switch (rateA) { case calc_FullRate: switch (rateB) { case calc_FullRate: switch (unit->mSpecialIndex) { // case opSilence2 : func = &zero_aa; break; case opAdd: func = &add_aa_nova_64; break; case opSub: func = &sub_aa_nova_64; break; case opMul: func = &mul_aa_nova_64; break; case opFDiv: func = &div_aa_nova; break; case opIDiv: func = &idiv_aa; break; case opMod: func = &mod_aa; break; case opEQ: func = &eq_aa_nova_64; break; case opNE: func = &neq_aa_nova_64; break; case opLT: func = &lt_aa_nova_64; break; case opGT: func = &gt_aa_nova_64; break; case opLE: func = &le_aa_nova_64; break; case opGE: func = &ge_aa_nova_64; break; case opMin: func = &min_aa_nova_64; break; case opMax: func = &max_aa_nova_64; break; case opBitAnd: func = &and_aa; break; case opBitOr: func = &or_aa; break; case opBitXor: func = &xor_aa; break; case opShiftRight: func = &rightShift_aa; break; case opShiftLeft: func = &leftShift_aa; break; case opLCM: func = &lcm_aa; break; case opGCD: func = &gcd_aa; break; case opRound: func = &round_aa; break; case opRoundUp: func = &roundUp_aa; break; case opTrunc: func = &trunc_aa; break; case opAtan2: func = &atan2_aa; break; case opHypot: func = &hypot_aa; break; case opHypotx: func = &hypotx_aa; break; case opPow: func = &pow_aa_nova; break; case opRing1: func = &ring1_aa_nova_64; break; case opRing2: func = &ring2_aa_nova_64; break; case opRing3: func = &ring3_aa_nova_64; break; case opRing4: func = &ring4_aa_nova_64; break; case opDifSqr: func = &difsqr_aa_nova_64; break; case opSumSqr: func = &sumsqr_aa_nova_64; break; case opSqrSum: func = &sqrsum_aa_nova_64; break; case opSqrDif: func = &sqrdif_aa_nova_64; break; case opAbsDif: func = &absdif_aa; break; case opThresh: func = &thresh_aa; break; case opAMClip: func = &amclip_aa; break; case opScaleNeg: func = &scaleneg_aa; break; case opClip2: func = &clip2_aa_nova_64; break; case opFold2: func = &fold2_aa; break; case opWrap2: func = &wrap2_aa; break; case opExcess: func = &excess_aa; break; case opRandRange: func = &rrand_aa; break; case opExpRandRange: func = &exprand_aa; break; case opFirstArg: func = &firstarg_aa_nova; break; // case opSecondArg : func = &secondarg_aa_nova; break; default: func = &add_aa; break; } break; case calc_BufRate: switch (unit->mSpecialIndex) { // case opSilence2 : func = &zero_aa; break; case opAdd: func = &add_ak_nova_64; break; case opSub: func = &sub_ak_nova_64; break; case opMul: func = &mul_ak_nova_64; break; case opFDiv: func = &div_ak_nova; break; case opIDiv: func = &idiv_ak; break; case opMod: func = &mod_ak; break; case opEQ: func = &eq_ak_nova_64; break; case opNE: func = &neq_ak_nova_64; break; case opLT: func = &lt_ak_nova_64; break; case opGT: func = &gt_ak_nova_64; break; case opLE: func = &le_ak_nova_64; break; case opGE: func = &ge_ak_nova_64; break; case opMin: func = &min_ak_nova_64; break; case opMax: func = &max_ak_nova_64; break; case opBitAnd: func = &and_ak; break; case opBitOr: func = &or_ak; break; case opBitXor: func = &xor_ak; break; case opShiftRight: func = &rightShift_ak; break; case opShiftLeft: func = &leftShift_ak; break; case opLCM: func = &lcm_ak; break; case opGCD: func = &gcd_ak; break; case opRound: func = &round_ak; break; case opRoundUp: func = &roundUp_ak; break; case opTrunc: func = &trunc_ak; break; case opAtan2: func = &atan2_ak; break; case opHypot: func = &hypot_ak; break; case opHypotx: func = &hypotx_ak; break; case opPow: func = &pow_ak_nova; break; case opRing1: func = &ring1_ak; break; case opRing2: func = &ring2_ak; break; case opRing3: func = &ring3_ak; break; case opRing4: func = &ring4_ak; break; case opDifSqr: func = &difsqr_ak_nova_64; break; case opSumSqr: func = &sumsqr_ak_nova_64; break; case opSqrSum: func = &sqrsum_ak_nova_64; break; case opSqrDif: func = &sqrdif_ak_nova_64; break; case opAbsDif: func = &absdif_ak; break; case opThresh: func = &thresh_ak; break; case opAMClip: func = &amclip_ak; break; case opScaleNeg: func = &scaleneg_ak; break; case opClip2: func = &clip2_ak_nova_64; break; case opFold2: func = &fold2_ak; break; case opWrap2: func = &wrap2_ak; break; case opExcess: func = &excess_ak; break; case opRandRange: func = &rrand_ak; break; case opExpRandRange: func = &exprand_ak; break; case opFirstArg: func = &firstarg_aa; break; // case opSecondArg : func = &secondarg_aa; break; default: func = &add_ak; break; } break; case calc_ScalarRate: switch (unit->mSpecialIndex) { // case opSilence2 : func = &zero_aa; break; case opAdd: func = &add_ai_nova_64; break; case opSub: func = &sub_ai_nova_64; break; case opMul: func = &mul_ai_nova_64; break; case opFDiv: func = &div_ai_nova; break; case opIDiv: func = &idiv_ai; break; case opMod: func = &mod_ai; break; case opEQ: func = &eq_ai_nova_64; break; case opNE: func = &neq_ai_nova_64; break; case opLT: func = &lt_ai_nova_64; break; case opGT: func = &gt_ai_nova_64; break; case opLE: func = &le_ai_nova_64; break; case opGE: func = &ge_ai_nova_64; break; case opMin: func = &min_ai_nova_64; break; case opMax: func = &max_ai_nova_64; break; case opBitAnd: func = &and_ai; break; case opBitOr: func = &or_ai; break; case opBitXor: func = &xor_ai; break; case opShiftRight: func = &rightShift_ai; break; case opShiftLeft: func = &leftShift_ai; break; case opLCM: func = &lcm_ai; break; case opGCD: func = &gcd_ai; break; case opRound: func = &round_ai; break; case opRoundUp: func = &roundUp_ai; break; case opTrunc: func = &trunc_ai; break; case opAtan2: func = &atan2_ai; break; case opHypot: func = &hypot_ai; break; case opHypotx: func = &hypotx_ai; break; case opPow: func = &pow_ai_nova; break; case opRing1: func = &ring1_ai_nova_64; break; case opRing2: func = &ring2_ai_nova_64; break; case opRing3: func = &ring3_ai_nova_64; break; case opRing4: func = &ring4_ai_nova_64; break; case opDifSqr: func = &difsqr_ai_nova_64; break; case opSumSqr: func = &sumsqr_ai_nova_64; break; case opSqrSum: func = &sqrsum_ai_nova_64; break; case opSqrDif: func = &sqrdif_ai_nova_64; break; case opAbsDif: func = &absdif_ai; break; case opThresh: func = &thresh_ai; break; case opAMClip: func = &amclip_ai; break; case opScaleNeg: func = &scaleneg_ai; break; case opClip2: func = &clip2_ai_nova_64; break; case opFold2: func = &fold2_ai; break; case opWrap2: func = &wrap2_ai; break; case opExcess: func = &excess_ai; break; case opRandRange: func = &rrand_ai; break; case opExpRandRange: func = &exprand_ai; break; case opFirstArg: func = &firstarg_aa; break; // case opSecondArg : func = &secondarg_aa; break; default: func = &add_ai; break; } } break; case calc_BufRate: if (rateB == calc_FullRate) { switch (unit->mSpecialIndex) { // case opSilence2 : func = &zero_aa; break; case opAdd: func = &add_ka_nova_64; break; case opSub: func = &sub_ka_nova_64; break; case opMul: func = &mul_ka_nova_64; break; case opFDiv: func = &div_ka_nova; break; case opIDiv: func = &idiv_ka; break; case opMod: func = &mod_ka; break; case opEQ: func = &eq_ka_nova_64; break; case opNE: func = &neq_ka_nova_64; break; case opLT: func = &lt_ka_nova_64; break; case opGT: func = &gt_ka_nova_64; break; case opLE: func = &le_ka_nova_64; break; case opGE: func = &ge_ka_nova_64; break; case opMin: func = &min_ka_nova_64; break; case opMax: func = &max_ka_nova_64; break; case opBitAnd: func = &and_ka; break; case opBitOr: func = &or_ka; break; case opBitXor: func = &xor_ka; break; case opShiftRight: func = &rightShift_ka; break; case opShiftLeft: func = &leftShift_ka; break; case opLCM: func = &lcm_ka; break; case opGCD: func = &gcd_ka; break; case opRound: func = &round_ka; break; case opRoundUp: func = &roundUp_ka; break; case opTrunc: func = &trunc_ka; break; case opAtan2: func = &atan2_ka; break; case opHypot: func = &hypot_ka; break; case opHypotx: func = &hypotx_ka; break; case opPow: func = &pow_ka_nova; break; case opRing1: func = &ring1_ka; break; case opRing2: func = &ring2_ka; break; case opRing3: func = &ring3_ka; break; case opRing4: func = &ring4_ka; break; case opDifSqr: func = &difsqr_ka_nova_64; break; case opSumSqr: func = &sumsqr_ka_nova_64; break; case opSqrSum: func = &sqrsum_ka_nova_64; break; case opSqrDif: func = &sqrdif_ka_nova_64; break; case opAbsDif: func = &absdif_ka; break; case opThresh: func = &thresh_ka; break; case opAMClip: func = &amclip_ka; break; case opScaleNeg: func = &scaleneg_ka; break; case opClip2: func = &clip2_ka_nova_64; break; case opFold2: func = &fold2_ka; break; case opWrap2: func = &wrap2_ka; break; case opExcess: func = &excess_ka; break; case opRandRange: func = &rrand_ka; break; case opExpRandRange: func = &exprand_ka; break; // case opFirstArg : func = &firstarg_aa; break; // case opSecondArg : func = &secondarg_aa; break; default: func = &add_ka; break; } } else { // this should have been caught by mBufLength == 1 func = &zero_aa; } break; case calc_ScalarRate: if (rateB == calc_FullRate) { switch (unit->mSpecialIndex) { // case opSilence2 : func = &zero_aa; break; case opAdd: func = &add_ia_nova_64; break; case opSub: func = &sub_ia_nova_64; break; case opMul: func = &mul_ia_nova_64; break; case opFDiv: func = &div_ia_nova; break; case opIDiv: func = &idiv_ia; break; case opMod: func = &mod_ia; break; case opEQ: func = &eq_ia_nova_64; break; case opNE: func = &neq_ia_nova_64; break; case opLT: func = &lt_ia_nova_64; break; case opGT: func = &gt_ia_nova_64; break; case opLE: func = &le_ia_nova_64; break; case opGE: func = &ge_ia_nova_64; break; case opMin: func = &min_ia_nova_64; break; case opMax: func = &max_ia_nova_64; break; case opBitAnd: func = &and_ia; break; case opBitOr: func = &or_ia; break; case opBitXor: func = &xor_ia; break; case opShiftRight: func = &rightShift_ia; break; case opShiftLeft: func = &leftShift_ia; break; case opLCM: func = &lcm_ia; break; case opGCD: func = &gcd_ia; break; case opRound: func = &round_ia; break; case opRoundUp: func = &roundUp_ia; break; case opTrunc: func = &trunc_ia; break; case opAtan2: func = &atan2_ia; break; case opHypot: func = &hypot_ia; break; case opHypotx: func = &hypotx_ia; break; case opPow: func = &pow_ia_nova; break; case opRing1: func = &ring1_ia_nova_64; break; case opRing2: func = &ring2_ia_nova_64; break; case opRing3: func = &ring3_ia_nova_64; break; case opRing4: func = &ring4_ia_nova_64; break; case opDifSqr: func = &difsqr_ia_nova_64; break; case opSumSqr: func = &sumsqr_ia_nova_64; break; case opSqrSum: func = &sqrsum_ia_nova_64; break; case opSqrDif: func = &sqrdif_ia_nova_64; break; case opAbsDif: func = &absdif_ia; break; case opThresh: func = &thresh_ia; break; case opAMClip: func = &amclip_ia; break; case opScaleNeg: func = &scaleneg_ia; break; case opClip2: func = &clip2_ia_nova_64; break; case opFold2: func = &fold2_ia; break; case opWrap2: func = &wrap2_ia; break; case opExcess: func = &excess_ia; break; case opRandRange: func = &rrand_ia; break; case opExpRandRange: func = &exprand_ia; break; // case opFirstArg : func = &firstarg_aa; break; // case opSecondArg : func = &secondarg_aa; break; default: func = &add_ia; break; } } else { // this should have been caught by mBufLength == 1 func = &zero_aa; } break; } return func; } static BinaryOpFunc ChooseNovaSimdFunc(BinaryOpUGen* unit) { if (BUFLENGTH == 64) return ChooseNovaSimdFunc_64(unit); BinaryOpFunc func = &zero_1; int rateA = INRATE(0); int rateB = INRATE(1); switch (rateA) { case calc_FullRate: switch (rateB) { case calc_FullRate: switch (unit->mSpecialIndex) { // case opSilence2 : func = &zero_aa; break; case opAdd: func = &add_aa_nova; break; case opSub: func = &sub_aa_nova; break; case opMul: func = &mul_aa_nova; break; case opFDiv: func = &div_aa_nova; break; case opIDiv: func = &idiv_aa; break; case opMod: func = &mod_aa; break; case opEQ: func = &eq_aa_nova; break; case opNE: func = &neq_aa_nova; break; case opLT: func = &lt_aa_nova; break; case opGT: func = &gt_aa_nova; break; case opLE: func = &le_aa_nova; break; case opGE: func = &ge_aa_nova; break; case opMin: func = &min_aa_nova; break; case opMax: func = &max_aa_nova; break; case opBitAnd: func = &and_aa; break; case opBitOr: func = &or_aa; break; case opBitXor: func = &xor_aa; break; case opShiftRight: func = &rightShift_aa; break; case opShiftLeft: func = &leftShift_aa; break; case opLCM: func = &lcm_aa; break; case opGCD: func = &gcd_aa; break; case opRound: func = &round_aa; break; case opRoundUp: func = &roundUp_aa; break; case opTrunc: func = &trunc_aa; break; case opAtan2: func = &atan2_aa; break; case opHypot: func = &hypot_aa; break; case opHypotx: func = &hypotx_aa; break; case opPow: func = &pow_aa_nova; break; case opRing1: func = &ring1_aa_nova; break; case opRing2: func = &ring2_aa_nova; break; case opRing3: func = &ring3_aa_nova; break; case opRing4: func = &ring4_aa_nova; break; case opDifSqr: func = &difsqr_aa_nova; break; case opSumSqr: func = &sumsqr_aa_nova; break; case opSqrSum: func = &sqrsum_aa_nova; break; case opSqrDif: func = &sqrdif_aa_nova; break; case opAbsDif: func = &absdif_aa; break; case opThresh: func = &thresh_aa; break; case opAMClip: func = &amclip_aa; break; case opScaleNeg: func = &scaleneg_aa; break; case opClip2: func = &clip2_aa_nova; break; case opFold2: func = &fold2_aa; break; case opWrap2: func = &wrap2_aa; break; case opExcess: func = &excess_aa; break; case opRandRange: func = &rrand_aa; break; case opExpRandRange: func = &exprand_aa; break; case opFirstArg: func = &firstarg_aa_nova; break; // case opSecondArg : func = &secondarg_aa_nova; break; default: func = &add_aa; break; } break; case calc_BufRate: switch (unit->mSpecialIndex) { // case opSilence2 : func = &zero_aa; break; case opAdd: func = &add_ak_nova; break; case opSub: func = &sub_ak_nova; break; case opMul: func = &mul_ak_nova; break; case opFDiv: func = &div_ak_nova; break; case opIDiv: func = &idiv_ak; break; case opMod: func = &mod_ak; break; case opEQ: func = &eq_ak_nova; break; case opNE: func = &neq_ak_nova; break; case opLT: func = &lt_ak_nova; break; case opGT: func = &gt_ak_nova; break; case opLE: func = &le_ak_nova; break; case opGE: func = &ge_ak_nova; break; case opMin: func = &min_ak_nova; break; case opMax: func = &max_ak_nova; break; case opBitAnd: func = &and_ak; break; case opBitOr: func = &or_ak; break; case opBitXor: func = &xor_ak; break; case opShiftRight: func = &rightShift_ak; break; case opShiftLeft: func = &leftShift_ak; break; case opLCM: func = &lcm_ak; break; case opGCD: func = &gcd_ak; break; case opRound: func = &round_ak; break; case opRoundUp: func = &roundUp_ak; break; case opTrunc: func = &trunc_ak; break; case opAtan2: func = &atan2_ak; break; case opHypot: func = &hypot_ak; break; case opHypotx: func = &hypotx_ak; break; case opPow: func = &pow_ak_nova; break; case opRing1: func = &ring1_ak; break; case opRing2: func = &ring2_ak; break; case opRing3: func = &ring3_ak; break; case opRing4: func = &ring4_ak; break; case opDifSqr: func = &difsqr_ak_nova; break; case opSumSqr: func = &sumsqr_ak_nova; break; case opSqrSum: func = &sqrsum_ak_nova; break; case opSqrDif: func = &sqrdif_ak_nova; break; case opAbsDif: func = &absdif_ak; break; case opThresh: func = &thresh_ak; break; case opAMClip: func = &amclip_ak; break; case opScaleNeg: func = &scaleneg_ak; break; case opClip2: func = &clip2_ak_nova; break; case opFold2: func = &fold2_ak; break; case opWrap2: func = &wrap2_ak; break; case opExcess: func = &excess_ak; break; case opRandRange: func = &rrand_ak; break; case opExpRandRange: func = &exprand_ak; break; case opFirstArg: func = &firstarg_aa; break; // case opSecondArg : func = &secondarg_aa; break; default: func = &add_ak; break; } break; case calc_ScalarRate: switch (unit->mSpecialIndex) { // case opSilence2 : func = &zero_aa; break; case opAdd: func = &add_ai_nova; break; case opSub: func = &sub_ai_nova; break; case opMul: func = &mul_ai_nova; break; case opFDiv: func = &div_ai_nova; break; case opIDiv: func = &idiv_ai; break; case opMod: func = &mod_ai; break; case opEQ: func = &eq_ai_nova; break; case opNE: func = &neq_ai_nova; break; case opLT: func = &lt_ai_nova; break; case opGT: func = &gt_ai_nova; break; case opLE: func = &le_ai_nova; break; case opGE: func = &ge_ai_nova; break; case opMin: func = &min_ai_nova; break; case opMax: func = &max_ai_nova; break; case opBitAnd: func = &and_ai; break; case opBitOr: func = &or_ai; break; case opBitXor: func = &xor_ai; break; case opShiftRight: func = &rightShift_ai; break; case opShiftLeft: func = &leftShift_ai; break; case opLCM: func = &lcm_ai; break; case opGCD: func = &gcd_ai; break; case opRound: func = &round_ai; break; case opRoundUp: func = &roundUp_ai; break; case opTrunc: func = &trunc_ai; break; case opAtan2: func = &atan2_ai; break; case opHypot: func = &hypot_ai; break; case opHypotx: func = &hypotx_ai; break; case opPow: func = &pow_ai_nova; break; case opRing1: func = &ring1_ai_nova; break; case opRing2: func = &ring2_ai_nova; break; case opRing3: func = &ring3_ai_nova; break; case opRing4: func = &ring4_ai_nova; break; case opDifSqr: func = &difsqr_ai_nova; break; case opSumSqr: func = &sumsqr_ai_nova; break; case opSqrSum: func = &sqrsum_ai_nova; break; case opSqrDif: func = &sqrdif_ai_nova; break; case opAbsDif: func = &absdif_ai; break; case opThresh: func = &thresh_ai; break; case opAMClip: func = &amclip_ai; break; case opScaleNeg: func = &scaleneg_ai; break; case opClip2: func = &clip2_ai_nova; break; case opFold2: func = &fold2_ai; break; case opWrap2: func = &wrap2_ai; break; case opExcess: func = &excess_ai; break; case opRandRange: func = &rrand_ai; break; case opExpRandRange: func = &exprand_ai; break; case opFirstArg: func = &firstarg_aa; break; // case opSecondArg : func = &secondarg_aa; break; default: func = &add_ai; break; } } break; case calc_BufRate: if (rateB == calc_FullRate) { switch (unit->mSpecialIndex) { // case opSilence2 : func = &zero_aa; break; case opAdd: func = &add_ka_nova; break; case opSub: func = &sub_ka_nova; break; case opMul: func = &mul_ka_nova; break; case opFDiv: func = &div_ka_nova; break; case opIDiv: func = &idiv_ka; break; case opMod: func = &mod_ka; break; case opEQ: func = &eq_ka_nova; break; case opNE: func = &neq_ka_nova; break; case opLT: func = &lt_ka_nova; break; case opGT: func = &gt_ka_nova; break; case opLE: func = &le_ka_nova; break; case opGE: func = &ge_ka_nova; break; case opMin: func = &min_ka_nova; break; case opMax: func = &max_ka_nova; break; case opBitAnd: func = &and_ka; break; case opBitOr: func = &or_ka; break; case opBitXor: func = &xor_ka; break; case opShiftRight: func = &rightShift_ka; break; case opShiftLeft: func = &leftShift_ka; break; case opLCM: func = &lcm_ka; break; case opGCD: func = &gcd_ka; break; case opRound: func = &round_ka; break; case opRoundUp: func = &roundUp_ka; break; case opTrunc: func = &trunc_ka; break; case opAtan2: func = &atan2_ka; break; case opHypot: func = &hypot_ka; break; case opHypotx: func = &hypotx_ka; break; case opPow: func = &pow_ka_nova; break; case opRing1: func = &ring1_ka; break; case opRing2: func = &ring2_ka; break; case opRing3: func = &ring3_ka; break; case opRing4: func = &ring4_ka; break; case opDifSqr: func = &difsqr_ka_nova; break; case opSumSqr: func = &sumsqr_ka_nova; break; case opSqrSum: func = &sqrsum_ka_nova; break; case opSqrDif: func = &sqrdif_ka_nova; break; case opAbsDif: func = &absdif_ka; break; case opThresh: func = &thresh_ka; break; case opAMClip: func = &amclip_ka; break; case opScaleNeg: func = &scaleneg_ka; break; case opClip2: func = &clip2_ka_nova; break; case opFold2: func = &fold2_ka; break; case opWrap2: func = &wrap2_ka; break; case opExcess: func = &excess_ka; break; case opRandRange: func = &rrand_ka; break; case opExpRandRange: func = &exprand_ka; break; // case opFirstArg : func = &firstarg_aa; break; // case opSecondArg : func = &secondarg_aa; break; default: func = &add_ka; break; } } else { // this should have been caught by mBufLength == 1 func = &zero_aa; } break; case calc_ScalarRate: if (rateB == calc_FullRate) { switch (unit->mSpecialIndex) { // case opSilence2 : func = &zero_aa; break; case opAdd: func = &add_ia_nova; break; case opSub: func = &sub_ia_nova; break; case opMul: func = &mul_ia_nova; break; case opFDiv: func = &div_ia_nova; break; case opIDiv: func = &idiv_ia; break; case opMod: func = &mod_ia; break; case opEQ: func = &eq_ia_nova; break; case opNE: func = &neq_ia_nova; break; case opLT: func = &lt_ia_nova; break; case opGT: func = &gt_ia_nova; break; case opLE: func = &le_ia_nova; break; case opGE: func = &ge_ia_nova; break; case opMin: func = &min_ia_nova; break; case opMax: func = &max_ia_nova; break; case opBitAnd: func = &and_ia; break; case opBitOr: func = &or_ia; break; case opBitXor: func = &xor_ia; break; case opShiftRight: func = &rightShift_ia; break; case opShiftLeft: func = &leftShift_ia; break; case opLCM: func = &lcm_ia; break; case opGCD: func = &gcd_ia; break; case opRound: func = &round_ia; break; case opRoundUp: func = &roundUp_ia; break; case opTrunc: func = &trunc_ia; break; case opAtan2: func = &atan2_ia; break; case opHypot: func = &hypot_ia; break; case opHypotx: func = &hypotx_ia; break; case opPow: func = &pow_ia_nova; break; case opRing1: func = &ring1_ia_nova; break; case opRing2: func = &ring2_ia_nova; break; case opRing3: func = &ring3_ia_nova; break; case opRing4: func = &ring4_ia_nova; break; case opDifSqr: func = &difsqr_ia_nova; break; case opSumSqr: func = &sumsqr_ia_nova; break; case opSqrSum: func = &sqrsum_ia_nova; break; case opSqrDif: func = &sqrdif_ia_nova; break; case opAbsDif: func = &absdif_ia; break; case opThresh: func = &thresh_ia; break; case opAMClip: func = &amclip_ia; break; case opScaleNeg: func = &scaleneg_ia; break; case opClip2: func = &clip2_ia_nova; break; case opFold2: func = &fold2_ia; break; case opWrap2: func = &wrap2_ia; break; case opExcess: func = &excess_ia; break; case opRandRange: func = &rrand_ia; break; case opExpRandRange: func = &rrand_ia; break; // case opFirstArg : func = &firstarg_aa; break; // case opSecondArg : func = &secondarg_aa; break; default: func = &add_ia; break; } } else { // this should have been caught by mBufLength == 1 func = &zero_aa; } break; } return func; } #endif bool ChooseOperatorFunc(BinaryOpUGen* unit) { // Print("->ChooseOperatorFunc %d\n", unit->mSpecialIndex); BinaryOpFunc func = &zero_aa; bool ret = false; if (BUFLENGTH == 1) { if (unit->mCalcRate == calc_DemandRate) { func = ChooseDemandFunc(unit); } else { func = ChooseOneSampleFunc(unit); } #if defined(NOVA_SIMD) } else if (boost::alignment::is_aligned(BUFLENGTH, 16)) { /* select normal function for initialization */ func = ChooseNormalFunc(unit); func(unit, 1); /* select simd function */ func = ChooseNovaSimdFunc(unit); ret = true; #endif } else { func = ChooseNormalFunc(unit); } unit->mCalcFunc = (UnitCalcFunc)func; // Print("<-ChooseOperatorFunc %p\n", func); // Print("calc %d\n", unit->mCalcRate); return ret; } //////////////////////////////////////////////////////////////////////////////////////////////////////// PluginLoad(BinaryOp) { ft = inTable; DefineSimpleUnit(BinaryOpUGen); }
218,608
C++
.cpp
6,514
24.192355
120
0.493657
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,957
MFCC.cpp
supercollider_supercollider/server/plugins/MFCC.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // This MFCC UGen combines work by Dan Stowell (influenced also by Jamie Bullock's work on libxtract) and independent // work by Nick Collins // Mel scale based frequency warping of spectrum, powers combined discrete cosine transform (DCT-II) via brute force // calculation see academic refs, wikipedia and // http://www.fftw.org/fftw3_doc/Real-even_002fodd-DFTs-_0028cosine_002fsine-transforms_0029.html#Real-even_002fodd-DFTs-_0028cosine_002fsine-transforms_0029 #include "ML.h" #include "FFT_UGens.h" // The plugin could be generalised to pass alternative scale data (corresponding to Barks, ERBs and different FFT sizes // etc) via a buffer For the moment, the data below is used and only 1024 FFT supported. For the associated Mel scale // spacing generation code see the bottom of the MFCC help file int g_startbin44100[42] = { 0, 2, 4, 5, 7, 9, 11, 13, 15, 17, 20, 23, 26, 29, 33, 36, 41, 45, 50, 55, 60, 66, 73, 80, 87, 96, 104, 114, 124, 135, 147, 159, 173, 188, 204, 221, 240, 260, 282, 305, 330, 357 }; // int g_endbin44100[42]= { 2, 3, 5, 7, 9, 11, 13, 15, 18, 21, 24, 27, 31, 34, 39, 43, 48, 53, 58, 64, 71, 78, 85, 94, // 102, 112, 122, 133, 145, 157, 171, 186, 202, 219, 238, 258, 280, 303, 328, 355, 385, 416 }; efficiency trick; one // above actual endbin, allows for loop to test only < and not <= int g_endbin44100[42] = { 3, 4, 6, 8, 10, 12, 14, 16, 19, 22, 25, 28, 32, 35, 40, 44, 49, 54, 59, 65, 72, 79, 86, 95, 103, 113, 123, 134, 146, 158, 172, 187, 203, 220, 239, 259, 281, 304, 329, 356, 386, 417 }; int g_cumulindex44100[43] = { 0, 3, 5, 7, 10, 13, 16, 19, 22, 26, 31, 36, 41, 47, 53, 60, 68, 76, 85, 94, 104, 116, 129, 142, 157, 173, 190, 209, 229, 251, 274, 299, 327, 357, 389, 424, 462, 503, 547, 594, 645, 701, 760 }; float g_melbandweights44100[761] = { 0.5, 1, 0.5, 0.5, 1, 1, 0.5, 0.5, 1, 0.5, 0.5, 1, 0.5, 0.5, 1, 0.5, 0.5, 1, 0.5, 0.5, 1, 0.5, 0.5, 1, 0.66666666666667, 0.33333333333333, 0.33333333333333, 0.66666666666667, 1, 0.66666666666667, 0.33333333333333, 0.33333333333333, 0.66666666666667, 1, 0.66666666666667, 0.33333333333333, 0.33333333333333, 0.66666666666667, 1, 0.66666666666667, 0.33333333333333, 0.33333333333333, 0.66666666666667, 1, 0.75, 0.5, 0.25, 0.25, 0.5, 0.75, 1, 0.66666666666667, 0.33333333333333, 0.33333333333333, 0.66666666666667, 1, 0.8, 0.6, 0.4, 0.2, 0.2, 0.4, 0.6, 0.8, 1, 0.75, 0.5, 0.25, 0.25, 0.5, 0.75, 1, 0.8, 0.6, 0.4, 0.2, 0.2, 0.4, 0.6, 0.8, 1, 0.8, 0.6, 0.4, 0.2, 0.2, 0.4, 0.6, 0.8, 1, 0.8, 0.6, 0.4, 0.2, 0.2, 0.4, 0.6, 0.8, 1, 0.83333333333333, 0.66666666666667, 0.5, 0.33333333333333, 0.16666666666667, 0.16666666666667, 0.33333333333333, 0.5, 0.66666666666667, 0.83333333333333, 1, 0.85714285714286, 0.71428571428571, 0.57142857142857, 0.42857142857143, 0.28571428571429, 0.14285714285714, 0.14285714285714, 0.28571428571429, 0.42857142857143, 0.57142857142857, 0.71428571428571, 0.85714285714286, 1, 0.85714285714286, 0.71428571428571, 0.57142857142857, 0.42857142857143, 0.28571428571429, 0.14285714285714, 0.14285714285714, 0.28571428571429, 0.42857142857143, 0.57142857142857, 0.71428571428571, 0.85714285714286, 1, 0.85714285714286, 0.71428571428571, 0.57142857142857, 0.42857142857143, 0.28571428571429, 0.14285714285714, 0.14285714285714, 0.28571428571429, 0.42857142857143, 0.57142857142857, 0.71428571428571, 0.85714285714286, 1, 0.88888888888889, 0.77777777777778, 0.66666666666667, 0.55555555555556, 0.44444444444444, 0.33333333333333, 0.22222222222222, 0.11111111111111, 0.11111111111111, 0.22222222222222, 0.33333333333333, 0.44444444444444, 0.55555555555556, 0.66666666666667, 0.77777777777778, 0.88888888888889, 1, 0.875, 0.75, 0.625, 0.5, 0.375, 0.25, 0.125, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 0.90909090909091, 0.81818181818182, 0.72727272727273, 0.63636363636364, 0.54545454545455, 0.45454545454545, 0.36363636363636, 0.27272727272727, 0.18181818181818, 0.090909090909091, 0.090909090909091, 0.18181818181818, 0.27272727272727, 0.36363636363636, 0.45454545454545, 0.54545454545455, 0.63636363636364, 0.72727272727273, 0.81818181818182, 0.90909090909091, 1, 0.91666666666667, 0.83333333333333, 0.75, 0.66666666666667, 0.58333333333333, 0.5, 0.41666666666667, 0.33333333333333, 0.25, 0.16666666666667, 0.083333333333333, 0.083333333333333, 0.16666666666667, 0.25, 0.33333333333333, 0.41666666666667, 0.5, 0.58333333333333, 0.66666666666667, 0.75, 0.83333333333333, 0.91666666666667, 1, 0.91666666666667, 0.83333333333333, 0.75, 0.66666666666667, 0.58333333333333, 0.5, 0.41666666666667, 0.33333333333333, 0.25, 0.16666666666667, 0.083333333333333, 0.083333333333333, 0.16666666666667, 0.25, 0.33333333333333, 0.41666666666667, 0.5, 0.58333333333333, 0.66666666666667, 0.75, 0.83333333333333, 0.91666666666667, 1, 0.92857142857143, 0.85714285714286, 0.78571428571429, 0.71428571428571, 0.64285714285714, 0.57142857142857, 0.5, 0.42857142857143, 0.35714285714286, 0.28571428571429, 0.21428571428571, 0.14285714285714, 0.071428571428572, 0.071428571428571, 0.14285714285714, 0.21428571428571, 0.28571428571429, 0.35714285714286, 0.42857142857143, 0.5, 0.57142857142857, 0.64285714285714, 0.71428571428571, 0.78571428571429, 0.85714285714286, 0.92857142857143, 1, 0.93333333333333, 0.86666666666667, 0.8, 0.73333333333333, 0.66666666666667, 0.6, 0.53333333333333, 0.46666666666667, 0.4, 0.33333333333333, 0.26666666666667, 0.2, 0.13333333333333, 0.066666666666667, 0.066666666666667, 0.13333333333333, 0.2, 0.26666666666667, 0.33333333333333, 0.4, 0.46666666666667, 0.53333333333333, 0.6, 0.66666666666667, 0.73333333333333, 0.8, 0.86666666666667, 0.93333333333333, 1, 0.9375, 0.875, 0.8125, 0.75, 0.6875, 0.625, 0.5625, 0.5, 0.4375, 0.375, 0.3125, 0.25, 0.1875, 0.125, 0.0625, 0.0625, 0.125, 0.1875, 0.25, 0.3125, 0.375, 0.4375, 0.5, 0.5625, 0.625, 0.6875, 0.75, 0.8125, 0.875, 0.9375, 1, 0.94117647058824, 0.88235294117647, 0.82352941176471, 0.76470588235294, 0.70588235294118, 0.64705882352941, 0.58823529411765, 0.52941176470588, 0.47058823529412, 0.41176470588235, 0.35294117647059, 0.29411764705882, 0.23529411764706, 0.17647058823529, 0.11764705882353, 0.058823529411765, 0.058823529411765, 0.11764705882353, 0.17647058823529, 0.23529411764706, 0.29411764705882, 0.35294117647059, 0.41176470588235, 0.47058823529412, 0.52941176470588, 0.58823529411765, 0.64705882352941, 0.70588235294118, 0.76470588235294, 0.82352941176471, 0.88235294117647, 0.94117647058824, 1, 0.94736842105263, 0.89473684210526, 0.84210526315789, 0.78947368421053, 0.73684210526316, 0.68421052631579, 0.63157894736842, 0.57894736842105, 0.52631578947368, 0.47368421052632, 0.42105263157895, 0.36842105263158, 0.31578947368421, 0.26315789473684, 0.21052631578947, 0.15789473684211, 0.10526315789474, 0.052631578947369, 0.052631578947368, 0.10526315789474, 0.15789473684211, 0.21052631578947, 0.26315789473684, 0.31578947368421, 0.36842105263158, 0.42105263157895, 0.47368421052632, 0.52631578947368, 0.57894736842105, 0.63157894736842, 0.68421052631579, 0.73684210526316, 0.78947368421053, 0.84210526315789, 0.89473684210526, 0.94736842105263, 1, 0.95, 0.9, 0.85, 0.8, 0.75, 0.7, 0.65, 0.6, 0.55, 0.5, 0.45, 0.4, 0.35, 0.3, 0.25, 0.2, 0.15, 0.1, 0.05, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1, 0.95454545454545, 0.90909090909091, 0.86363636363636, 0.81818181818182, 0.77272727272727, 0.72727272727273, 0.68181818181818, 0.63636363636364, 0.59090909090909, 0.54545454545455, 0.5, 0.45454545454545, 0.40909090909091, 0.36363636363636, 0.31818181818182, 0.27272727272727, 0.22727272727273, 0.18181818181818, 0.13636363636364, 0.090909090909091, 0.045454545454545, 0.045454545454545, 0.090909090909091, 0.13636363636364, 0.18181818181818, 0.22727272727273, 0.27272727272727, 0.31818181818182, 0.36363636363636, 0.40909090909091, 0.45454545454545, 0.5, 0.54545454545455, 0.59090909090909, 0.63636363636364, 0.68181818181818, 0.72727272727273, 0.77272727272727, 0.81818181818182, 0.86363636363636, 0.90909090909091, 0.95454545454545, 1, 0.95652173913043, 0.91304347826087, 0.8695652173913, 0.82608695652174, 0.78260869565217, 0.73913043478261, 0.69565217391304, 0.65217391304348, 0.60869565217391, 0.56521739130435, 0.52173913043478, 0.47826086956522, 0.43478260869565, 0.39130434782609, 0.34782608695652, 0.30434782608696, 0.26086956521739, 0.21739130434783, 0.17391304347826, 0.1304347826087, 0.08695652173913, 0.043478260869565, 0.043478260869565, 0.08695652173913, 0.1304347826087, 0.17391304347826, 0.21739130434783, 0.26086956521739, 0.30434782608696, 0.34782608695652, 0.39130434782609, 0.43478260869565, 0.47826086956522, 0.52173913043478, 0.56521739130435, 0.60869565217391, 0.65217391304348, 0.69565217391304, 0.73913043478261, 0.78260869565217, 0.82608695652174, 0.8695652173913, 0.91304347826087, 0.95652173913043, 1, 0.96, 0.92, 0.88, 0.84, 0.8, 0.76, 0.72, 0.68, 0.64, 0.6, 0.56, 0.52, 0.48, 0.44, 0.4, 0.36, 0.32, 0.28, 0.24, 0.2, 0.16, 0.12, 0.08, 0.04, 0.04, 0.08, 0.12, 0.16, 0.2, 0.24, 0.28, 0.32, 0.36, 0.4, 0.44, 0.48, 0.52, 0.56, 0.6, 0.64, 0.68, 0.72, 0.76, 0.8, 0.84, 0.88, 0.92, 0.96, 1, 0.96296296296296, 0.92592592592593, 0.88888888888889, 0.85185185185185, 0.81481481481481, 0.77777777777778, 0.74074074074074, 0.7037037037037, 0.66666666666667, 0.62962962962963, 0.59259259259259, 0.55555555555556, 0.51851851851852, 0.48148148148148, 0.44444444444444, 0.40740740740741, 0.37037037037037, 0.33333333333333, 0.2962962962963, 0.25925925925926, 0.22222222222222, 0.18518518518519, 0.14814814814815, 0.11111111111111, 0.074074074074074, 0.037037037037037, 0.037037037037037, 0.074074074074074, 0.11111111111111, 0.14814814814815, 0.18518518518519, 0.22222222222222, 0.25925925925926, 0.2962962962963, 0.33333333333333, 0.37037037037037, 0.40740740740741, 0.44444444444444, 0.48148148148148, 0.51851851851852, 0.55555555555556, 0.59259259259259, 0.62962962962963, 0.66666666666667, 0.7037037037037, 0.74074074074074, 0.77777777777778, 0.81481481481481, 0.85185185185185, 0.88888888888889, 0.92592592592593, 0.96296296296296, 1, 0.96666666666667, 0.93333333333333, 0.9, 0.86666666666667, 0.83333333333333, 0.8, 0.76666666666667, 0.73333333333333, 0.7, 0.66666666666667, 0.63333333333333, 0.6, 0.56666666666667, 0.53333333333333, 0.5, 0.46666666666667, 0.43333333333333, 0.4, 0.36666666666667, 0.33333333333333, 0.3, 0.26666666666667, 0.23333333333333, 0.2, 0.16666666666667, 0.13333333333333, 0.1, 0.066666666666667, 0.033333333333333, 0.033333333333333, 0.066666666666667, 0.1, 0.13333333333333, 0.16666666666667, 0.2, 0.23333333333333, 0.26666666666667, 0.3, 0.33333333333333, 0.36666666666667, 0.4, 0.43333333333333, 0.46666666666667, 0.5, 0.53333333333333, 0.56666666666667, 0.6, 0.63333333333333, 0.66666666666667, 0.7, 0.73333333333333, 0.76666666666667, 0.8, 0.83333333333333, 0.86666666666667, 0.9, 0.93333333333333, 0.96666666666667, 1, 0.96774193548387, 0.93548387096774, 0.90322580645161, 0.87096774193548, 0.83870967741935, 0.80645161290323, 0.7741935483871, 0.74193548387097, 0.70967741935484, 0.67741935483871, 0.64516129032258, 0.61290322580645, 0.58064516129032, 0.54838709677419, 0.51612903225806, 0.48387096774194, 0.45161290322581, 0.41935483870968, 0.38709677419355, 0.35483870967742, 0.32258064516129, 0.29032258064516, 0.25806451612903, 0.2258064516129, 0.19354838709677, 0.16129032258065, 0.12903225806452, 0.096774193548387, 0.064516129032258, 0.032258064516129 }; int g_startbin48000[42] = { 0, 2, 4, 5, 6, 8, 10, 12, 14, 16, 18, 21, 24, 27, 30, 34, 37, 41, 46, 51, 56, 61, 67, 73, 80, 88, 96, 104, 114, 124, 135, 147, 159, 173, 188, 203, 220, 239, 259, 280, 304, 328 }; // int g_endbin48000[42]= { 2, 3, 4, 6, 8, 10, 12, 14, 16, 19, 22, 25, 28, 32, 35, 39, 44, 49, 54, 59, 65, 71, 78, 86, // 94, 102, 112, 122, 133, 145, 157, 171, 186, 201, 218, 237, 257, 278, 302, 326, 353, 383 }; with efficiency trick int g_endbin48000[42] = { 3, 4, 5, 7, 9, 11, 13, 15, 17, 20, 23, 26, 29, 33, 36, 40, 45, 50, 55, 60, 66, 72, 79, 87, 95, 103, 113, 123, 134, 146, 158, 172, 187, 202, 219, 238, 258, 279, 303, 327, 354, 384 }; int g_cumulindex48000[43] = { 0, 3, 5, 6, 8, 11, 14, 17, 20, 23, 27, 32, 37, 42, 48, 54, 60, 68, 77, 86, 95, 105, 116, 128, 142, 157, 172, 189, 208, 228, 250, 273, 298, 326, 355, 386, 421, 459, 499, 543, 590, 640, 695 }; float g_melbandweights48000[761] = { 0.5, 1, 0.5, 0.5, 1, 1, 1, 0.5, 0.5, 1, 0.5, 0.5, 1, 0.5, 0.5, 1, 0.5, 0.5, 1, 0.5, 0.5, 1, 0.5, 0.5, 1, 0.66666666666667, 0.33333333333333, 0.33333333333333, 0.66666666666667, 1, 0.66666666666667, 0.33333333333333, 0.33333333333333, 0.66666666666667, 1, 0.66666666666667, 0.33333333333333, 0.33333333333333, 0.66666666666667, 1, 0.66666666666667, 0.33333333333333, 0.33333333333333, 0.66666666666667, 1, 0.75, 0.5, 0.25, 0.25, 0.5, 0.75, 1, 0.66666666666667, 0.33333333333333, 0.33333333333333, 0.66666666666667, 1, 0.75, 0.5, 0.25, 0.25, 0.5, 0.75, 1, 0.8, 0.6, 0.4, 0.2, 0.2, 0.4, 0.6, 0.8, 1, 0.8, 0.6, 0.4, 0.2, 0.2, 0.4, 0.6, 0.8, 1, 0.8, 0.6, 0.4, 0.2, 0.2, 0.4, 0.6, 0.8, 1, 0.8, 0.6, 0.4, 0.2, 0.2, 0.4, 0.6, 0.8, 1, 0.83333333333333, 0.66666666666667, 0.5, 0.33333333333333, 0.16666666666667, 0.16666666666667, 0.33333333333333, 0.5, 0.66666666666667, 0.83333333333333, 1, 0.83333333333333, 0.66666666666667, 0.5, 0.33333333333333, 0.16666666666667, 0.16666666666667, 0.33333333333333, 0.5, 0.66666666666667, 0.83333333333333, 1, 0.85714285714286, 0.71428571428571, 0.57142857142857, 0.42857142857143, 0.28571428571429, 0.14285714285714, 0.14285714285714, 0.28571428571429, 0.42857142857143, 0.57142857142857, 0.71428571428571, 0.85714285714286, 1, 0.875, 0.75, 0.625, 0.5, 0.375, 0.25, 0.125, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1, 0.875, 0.75, 0.625, 0.5, 0.375, 0.25, 0.125, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1, 0.875, 0.75, 0.625, 0.5, 0.375, 0.25, 0.125, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 0.90909090909091, 0.81818181818182, 0.72727272727273, 0.63636363636364, 0.54545454545455, 0.45454545454545, 0.36363636363636, 0.27272727272727, 0.18181818181818, 0.090909090909091, 0.090909090909091, 0.18181818181818, 0.27272727272727, 0.36363636363636, 0.45454545454545, 0.54545454545455, 0.63636363636364, 0.72727272727273, 0.81818181818182, 0.90909090909091, 1, 0.91666666666667, 0.83333333333333, 0.75, 0.66666666666667, 0.58333333333333, 0.5, 0.41666666666667, 0.33333333333333, 0.25, 0.16666666666667, 0.083333333333333, 0.083333333333333, 0.16666666666667, 0.25, 0.33333333333333, 0.41666666666667, 0.5, 0.58333333333333, 0.66666666666667, 0.75, 0.83333333333333, 0.91666666666667, 1, 0.91666666666667, 0.83333333333333, 0.75, 0.66666666666667, 0.58333333333333, 0.5, 0.41666666666667, 0.33333333333333, 0.25, 0.16666666666667, 0.083333333333333, 0.083333333333333, 0.16666666666667, 0.25, 0.33333333333333, 0.41666666666667, 0.5, 0.58333333333333, 0.66666666666667, 0.75, 0.83333333333333, 0.91666666666667, 1, 0.92857142857143, 0.85714285714286, 0.78571428571429, 0.71428571428571, 0.64285714285714, 0.57142857142857, 0.5, 0.42857142857143, 0.35714285714286, 0.28571428571429, 0.21428571428571, 0.14285714285714, 0.071428571428572, 0.071428571428571, 0.14285714285714, 0.21428571428571, 0.28571428571429, 0.35714285714286, 0.42857142857143, 0.5, 0.57142857142857, 0.64285714285714, 0.71428571428571, 0.78571428571429, 0.85714285714286, 0.92857142857143, 1, 0.93333333333333, 0.86666666666667, 0.8, 0.73333333333333, 0.66666666666667, 0.6, 0.53333333333333, 0.46666666666667, 0.4, 0.33333333333333, 0.26666666666667, 0.2, 0.13333333333333, 0.066666666666667, 0.066666666666667, 0.13333333333333, 0.2, 0.26666666666667, 0.33333333333333, 0.4, 0.46666666666667, 0.53333333333333, 0.6, 0.66666666666667, 0.73333333333333, 0.8, 0.86666666666667, 0.93333333333333, 1, 0.93333333333333, 0.86666666666667, 0.8, 0.73333333333333, 0.66666666666667, 0.6, 0.53333333333333, 0.46666666666667, 0.4, 0.33333333333333, 0.26666666666667, 0.2, 0.13333333333333, 0.066666666666667, 0.066666666666667, 0.13333333333333, 0.2, 0.26666666666667, 0.33333333333333, 0.4, 0.46666666666667, 0.53333333333333, 0.6, 0.66666666666667, 0.73333333333333, 0.8, 0.86666666666667, 0.93333333333333, 1, 0.94117647058824, 0.88235294117647, 0.82352941176471, 0.76470588235294, 0.70588235294118, 0.64705882352941, 0.58823529411765, 0.52941176470588, 0.47058823529412, 0.41176470588235, 0.35294117647059, 0.29411764705882, 0.23529411764706, 0.17647058823529, 0.11764705882353, 0.058823529411765, 0.058823529411765, 0.11764705882353, 0.17647058823529, 0.23529411764706, 0.29411764705882, 0.35294117647059, 0.41176470588235, 0.47058823529412, 0.52941176470588, 0.58823529411765, 0.64705882352941, 0.70588235294118, 0.76470588235294, 0.82352941176471, 0.88235294117647, 0.94117647058824, 1, 0.94736842105263, 0.89473684210526, 0.84210526315789, 0.78947368421053, 0.73684210526316, 0.68421052631579, 0.63157894736842, 0.57894736842105, 0.52631578947368, 0.47368421052632, 0.42105263157895, 0.36842105263158, 0.31578947368421, 0.26315789473684, 0.21052631578947, 0.15789473684211, 0.10526315789474, 0.052631578947369, 0.052631578947368, 0.10526315789474, 0.15789473684211, 0.21052631578947, 0.26315789473684, 0.31578947368421, 0.36842105263158, 0.42105263157895, 0.47368421052632, 0.52631578947368, 0.57894736842105, 0.63157894736842, 0.68421052631579, 0.73684210526316, 0.78947368421053, 0.84210526315789, 0.89473684210526, 0.94736842105263, 1, 0.95, 0.9, 0.85, 0.8, 0.75, 0.7, 0.65, 0.6, 0.55, 0.5, 0.45, 0.4, 0.35, 0.3, 0.25, 0.2, 0.15, 0.1, 0.05, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1, 0.95238095238095, 0.9047619047619, 0.85714285714286, 0.80952380952381, 0.76190476190476, 0.71428571428571, 0.66666666666667, 0.61904761904762, 0.57142857142857, 0.52380952380952, 0.47619047619048, 0.42857142857143, 0.38095238095238, 0.33333333333333, 0.28571428571429, 0.23809523809524, 0.19047619047619, 0.14285714285714, 0.095238095238095, 0.047619047619048, 0.047619047619048, 0.095238095238095, 0.14285714285714, 0.19047619047619, 0.23809523809524, 0.28571428571429, 0.33333333333333, 0.38095238095238, 0.42857142857143, 0.47619047619048, 0.52380952380952, 0.57142857142857, 0.61904761904762, 0.66666666666667, 0.71428571428571, 0.76190476190476, 0.80952380952381, 0.85714285714286, 0.9047619047619, 0.95238095238095, 1, 0.95833333333333, 0.91666666666667, 0.875, 0.83333333333333, 0.79166666666667, 0.75, 0.70833333333333, 0.66666666666667, 0.625, 0.58333333333333, 0.54166666666667, 0.5, 0.45833333333333, 0.41666666666667, 0.375, 0.33333333333333, 0.29166666666667, 0.25, 0.20833333333333, 0.16666666666667, 0.125, 0.083333333333333, 0.041666666666667, 0.041666666666667, 0.083333333333333, 0.125, 0.16666666666667, 0.20833333333333, 0.25, 0.29166666666667, 0.33333333333333, 0.375, 0.41666666666667, 0.45833333333333, 0.5, 0.54166666666667, 0.58333333333333, 0.625, 0.66666666666667, 0.70833333333333, 0.75, 0.79166666666667, 0.83333333333333, 0.875, 0.91666666666667, 0.95833333333333, 1, 0.95833333333333, 0.91666666666667, 0.875, 0.83333333333333, 0.79166666666667, 0.75, 0.70833333333333, 0.66666666666667, 0.625, 0.58333333333333, 0.54166666666667, 0.5, 0.45833333333333, 0.41666666666667, 0.375, 0.33333333333333, 0.29166666666667, 0.25, 0.20833333333333, 0.16666666666667, 0.125, 0.083333333333333, 0.041666666666667, 0.041666666666667, 0.083333333333333, 0.125, 0.16666666666667, 0.20833333333333, 0.25, 0.29166666666667, 0.33333333333333, 0.375, 0.41666666666667, 0.45833333333333, 0.5, 0.54166666666667, 0.58333333333333, 0.625, 0.66666666666667, 0.70833333333333, 0.75, 0.79166666666667, 0.83333333333333, 0.875, 0.91666666666667, 0.95833333333333, 1, 0.96296296296296, 0.92592592592593, 0.88888888888889, 0.85185185185185, 0.81481481481481, 0.77777777777778, 0.74074074074074, 0.7037037037037, 0.66666666666667, 0.62962962962963, 0.59259259259259, 0.55555555555556, 0.51851851851852, 0.48148148148148, 0.44444444444444, 0.40740740740741, 0.37037037037037, 0.33333333333333, 0.2962962962963, 0.25925925925926, 0.22222222222222, 0.18518518518519, 0.14814814814815, 0.11111111111111, 0.074074074074074, 0.037037037037037, 0.037037037037037, 0.074074074074074, 0.11111111111111, 0.14814814814815, 0.18518518518519, 0.22222222222222, 0.25925925925926, 0.2962962962963, 0.33333333333333, 0.37037037037037, 0.40740740740741, 0.44444444444444, 0.48148148148148, 0.51851851851852, 0.55555555555556, 0.59259259259259, 0.62962962962963, 0.66666666666667, 0.7037037037037, 0.74074074074074, 0.77777777777778, 0.81481481481481, 0.85185185185185, 0.88888888888889, 0.92592592592593, 0.96296296296296, 1, 0.96666666666667, 0.93333333333333, 0.9, 0.86666666666667, 0.83333333333333, 0.8, 0.76666666666667, 0.73333333333333, 0.7, 0.66666666666667, 0.63333333333333, 0.6, 0.56666666666667, 0.53333333333333, 0.5, 0.46666666666667, 0.43333333333333, 0.4, 0.36666666666667, 0.33333333333333, 0.3, 0.26666666666667, 0.23333333333333, 0.2, 0.16666666666667, 0.13333333333333, 0.1, 0.066666666666667, 0.033333333333333 }; // generated in SC using: // a= Array.fill(42, {|i| cos(pi/42.0*((0..41)+0.5)*(i+1))}); // Post << a.flatten << nl; // up to 42 coefficients, each with 42 multipliers for each of 42 bands float dct[1764] = { 0.9993007047884, 0.99371220989324, 0.98256647323329, 0.96592582628907, 0.94388333030837, 0.91656225586998, 0.88411539350461, 0.84672419922828, 0.80459777976667, 0.75797172314545, 0.70710678118655, 0.65228741127812, 0.5938201855735, 0.53203207651534, 0.46726862827306, 0.39989202431974, 0.33027906195517, 0.25881904510252, 0.18591160716291, 0.11196447610331, 0.037391194276326, -0.037391194276326, -0.11196447610331, -0.18591160716291, -0.25881904510252, -0.33027906195517, -0.39989202431974, -0.46726862827306, -0.53203207651534, -0.5938201855735, -0.65228741127812, -0.70710678118655, -0.75797172314545, -0.80459777976667, -0.84672419922828, -0.88411539350461, -0.91656225586998, -0.94388333030837, -0.96592582628907, -0.98256647323329, -0.99371220989324, -0.9993007047884, 0.99720379718118, 0.97492791218182, 0.9308737486442, 0.86602540378444, 0.78183148246803, 0.68017273777092, 0.56332005806362, 0.43388373911756, 0.2947551744109, 0.14904226617617, 6.1232339957368e-17, -0.14904226617617, -0.2947551744109, -0.43388373911756, -0.56332005806362, -0.68017273777092, -0.78183148246803, -0.86602540378444, -0.9308737486442, -0.97492791218182, -0.99720379718118, -0.99720379718118, -0.97492791218182, -0.9308737486442, -0.86602540378444, -0.78183148246803, -0.68017273777092, -0.56332005806362, -0.43388373911756, -0.2947551744109, -0.14904226617617, -1.836970198721e-16, 0.14904226617617, 0.2947551744109, 0.43388373911756, 0.56332005806362, 0.68017273777092, 0.78183148246803, 0.86602540378444, 0.9308737486442, 0.97492791218182, 0.99720379718118, 0.99371220989324, 0.94388333030837, 0.84672419922828, 0.70710678118655, 0.53203207651534, 0.33027906195517, 0.11196447610331, -0.11196447610331, -0.33027906195517, -0.53203207651534, -0.70710678118655, -0.84672419922828, -0.94388333030837, -0.99371220989324, -0.99371220989324, -0.94388333030837, -0.84672419922828, -0.70710678118655, -0.53203207651534, -0.33027906195517, -0.11196447610331, 0.11196447610331, 0.33027906195517, 0.53203207651534, 0.70710678118655, 0.84672419922828, 0.94388333030837, 0.99371220989324, 0.99371220989324, 0.94388333030837, 0.84672419922828, 0.70710678118655, 0.53203207651534, 0.33027906195517, 0.11196447610331, -0.11196447610331, -0.33027906195517, -0.53203207651534, -0.70710678118655, -0.84672419922828, -0.94388333030837, -0.99371220989324, 0.98883082622513, 0.90096886790242, 0.73305187182983, 0.5, 0.22252093395631, -0.074730093586424, -0.3653410243664, -0.62348980185873, -0.82623877431599, -0.95557280578614, -1, -0.95557280578614, -0.82623877431599, -0.62348980185873, -0.36534102436639, -0.074730093586424, 0.22252093395631, 0.5, 0.73305187182983, 0.90096886790242, 0.98883082622513, 0.98883082622513, 0.90096886790242, 0.73305187182983, 0.5, 0.22252093395631, -0.074730093586424, -0.3653410243664, -0.62348980185873, -0.826238774316, -0.95557280578614, -1, -0.95557280578614, -0.82623877431599, -0.62348980185873, -0.36534102436639, -0.074730093586424, 0.22252093395631, 0.5, 0.73305187182983, 0.90096886790242, 0.98883082622513, 0.98256647323329, 0.84672419922828, 0.5938201855735, 0.25881904510252, -0.11196447610331, -0.46726862827306, -0.75797172314545, -0.94388333030837, -0.9993007047884, -0.91656225586998, -0.70710678118655, -0.39989202431974, -0.037391194276326, 0.33027906195517, 0.65228741127812, 0.88411539350461, 0.99371220989324, 0.96592582628907, 0.80459777976667, 0.53203207651534, 0.18591160716291, -0.18591160716291, -0.53203207651534, -0.80459777976667, -0.96592582628907, -0.99371220989324, -0.88411539350461, -0.65228741127812, -0.33027906195517, 0.037391194276327, 0.39989202431974, 0.70710678118655, 0.91656225586998, 0.9993007047884, 0.94388333030837, 0.75797172314545, 0.46726862827306, 0.11196447610331, -0.25881904510252, -0.5938201855735, -0.84672419922828, -0.98256647323329, 0.97492791218182, 0.78183148246803, 0.43388373911756, -1.6081226496766e-16, -0.43388373911756, -0.78183148246803, -0.97492791218182, -0.97492791218182, -0.78183148246803, -0.43388373911756, -1.836970198721e-16, 0.43388373911756, 0.78183148246803, 0.97492791218182, 0.97492791218182, 0.78183148246803, 0.43388373911756, 3.0616169978684e-16, -0.43388373911756, -0.78183148246803, -0.97492791218182, -0.97492791218182, -0.78183148246803, -0.43388373911756, 1.3477304596987e-15, 0.43388373911756, 0.78183148246803, 0.97492791218182, 0.97492791218182, 0.78183148246803, 0.43388373911756, 5.5109105961631e-16, -0.43388373911756, -0.78183148246803, -0.97492791218182, -0.97492791218182, -0.78183148246803, -0.43388373911756, 1.1028010998692e-15, 0.43388373911756, 0.78183148246803, 0.97492791218182, 0.96592582628907, 0.70710678118655, 0.25881904510252, -0.25881904510252, -0.70710678118655, -0.96592582628907, -0.96592582628907, -0.70710678118655, -0.25881904510252, 0.25881904510252, 0.70710678118655, 0.96592582628907, 0.96592582628907, 0.70710678118655, 0.25881904510252, -0.25881904510252, -0.70710678118655, -0.96592582628907, -0.96592582628907, -0.70710678118655, -0.25881904510252, 0.25881904510252, 0.70710678118655, 0.96592582628907, 0.96592582628907, 0.70710678118655, 0.25881904510252, -0.25881904510252, -0.70710678118655, -0.96592582628907, -0.96592582628907, -0.70710678118655, -0.25881904510252, 0.25881904510252, 0.70710678118655, 0.96592582628907, 0.96592582628907, 0.70710678118655, 0.25881904510252, -0.25881904510252, -0.70710678118655, -0.96592582628907, 0.95557280578614, 0.62348980185873, 0.074730093586424, -0.5, -0.90096886790242, -0.98883082622513, -0.73305187182983, -0.22252093395631, 0.3653410243664, 0.82623877431599, 1, 0.82623877431599, 0.3653410243664, -0.22252093395631, -0.73305187182983, -0.98883082622513, -0.90096886790242, -0.5, 0.074730093586425, 0.62348980185873, 0.95557280578614, 0.95557280578614, 0.62348980185873, 0.074730093586424, -0.5, -0.90096886790242, -0.98883082622513, -0.73305187182983, -0.22252093395632, 0.3653410243664, 0.826238774316, 1, 0.82623877431599, 0.36534102436639, -0.22252093395631, -0.73305187182983, -0.98883082622513, -0.90096886790242, -0.5, 0.074730093586425, 0.62348980185873, 0.95557280578614, 0.94388333030837, 0.53203207651534, -0.11196447610331, -0.70710678118655, -0.99371220989324, -0.84672419922828, -0.33027906195517, 0.33027906195517, 0.84672419922828, 0.99371220989324, 0.70710678118655, 0.11196447610331, -0.53203207651534, -0.94388333030837, -0.94388333030837, -0.53203207651534, 0.11196447610331, 0.70710678118655, 0.99371220989324, 0.84672419922828, 0.33027906195517, -0.33027906195517, -0.84672419922828, -0.99371220989324, -0.70710678118655, -0.11196447610331, 0.53203207651534, 0.94388333030837, 0.94388333030837, 0.53203207651534, -0.11196447610331, -0.70710678118655, -0.99371220989324, -0.84672419922828, -0.33027906195517, 0.33027906195517, 0.84672419922828, 0.99371220989324, 0.70710678118655, 0.11196447610331, -0.53203207651534, -0.94388333030837, 0.9308737486442, 0.43388373911756, -0.2947551744109, -0.86602540378444, -0.97492791218182, -0.56332005806362, 0.14904226617617, 0.78183148246803, 0.99720379718118, 0.68017273777092, 3.0616169978684e-16, -0.68017273777092, -0.99720379718118, -0.78183148246803, -0.14904226617617, 0.56332005806362, 0.97492791218182, 0.86602540378444, 0.2947551744109, -0.43388373911756, -0.9308737486442, -0.9308737486442, -0.43388373911756, 0.2947551744109, 0.86602540378444, 0.97492791218182, 0.56332005806362, -0.14904226617617, -0.78183148246803, -0.99720379718118, -0.68017273777092, -2.6948419387608e-15, 0.68017273777092, 0.99720379718118, 0.78183148246803, 0.14904226617617, -0.56332005806362, -0.97492791218182, -0.86602540378444, -0.2947551744109, 0.43388373911756, 0.9308737486442, 0.91656225586998, 0.33027906195517, -0.46726862827306, -0.96592582628907, -0.84672419922828, -0.18591160716291, 0.5938201855735, 0.99371220989324, 0.75797172314545, 0.037391194276326, -0.70710678118655, -0.9993007047884, -0.65228741127812, 0.11196447610331, 0.80459777976667, 0.98256647323329, 0.53203207651534, -0.25881904510252, -0.88411539350461, -0.94388333030837, -0.39989202431974, 0.39989202431974, 0.94388333030837, 0.88411539350461, 0.25881904510252, -0.53203207651534, -0.98256647323329, -0.80459777976667, -0.11196447610331, 0.65228741127812, 0.9993007047884, 0.70710678118655, -0.03739119427633, -0.75797172314545, -0.99371220989324, -0.5938201855735, 0.18591160716291, 0.84672419922828, 0.96592582628907, 0.46726862827306, -0.33027906195517, -0.91656225586998, 0.90096886790242, 0.22252093395631, -0.62348980185873, -1, -0.62348980185873, 0.22252093395631, 0.90096886790242, 0.90096886790242, 0.22252093395631, -0.62348980185873, -1, -0.62348980185873, 0.22252093395631, 0.90096886790242, 0.90096886790242, 0.22252093395631, -0.62348980185873, -1, -0.62348980185873, 0.22252093395631, 0.90096886790242, 0.90096886790242, 0.22252093395632, -0.62348980185873, -1, -0.62348980185873, 0.22252093395631, 0.90096886790242, 0.90096886790242, 0.22252093395631, -0.62348980185874, -1, -0.62348980185873, 0.22252093395632, 0.90096886790242, 0.90096886790242, 0.22252093395631, -0.62348980185874, -1, -0.62348980185873, 0.22252093395631, 0.90096886790242, 0.88411539350461, 0.11196447610331, -0.75797172314545, -0.96592582628907, -0.33027906195517, 0.5938201855735, 0.9993007047884, 0.53203207651534, -0.39989202431974, -0.98256647323329, -0.70710678118655, 0.18591160716291, 0.91656225586998, 0.84672419922828, 0.037391194276326, -0.80459777976667, -0.94388333030837, -0.25881904510252, 0.65228741127812, 0.99371220989324, 0.46726862827306, -0.46726862827306, -0.99371220989324, -0.65228741127812, 0.25881904510252, 0.94388333030837, 0.80459777976667, -0.037391194276326, -0.84672419922828, -0.91656225586998, -0.18591160716291, 0.70710678118655, 0.98256647323329, 0.39989202431974, -0.53203207651534, -0.9993007047884, -0.5938201855735, 0.33027906195516, 0.96592582628907, 0.75797172314545, -0.1119644761033, -0.88411539350461, 0.86602540378444, 6.1232339957368e-17, -0.86602540378444, -0.86602540378444, -1.836970198721e-16, 0.86602540378444, 0.86602540378444, 3.0616169978684e-16, -0.86602540378444, -0.86602540378444, -4.2862637970157e-16, 0.86602540378444, 0.86602540378444, 5.5109105961631e-16, -0.86602540378444, -0.86602540378444, -2.4499125789313e-15, 0.86602540378444, 0.86602540378444, -9.8033641995447e-16, -0.86602540378444, -0.86602540378444, -2.6948419387608e-15, 0.86602540378444, 0.86602540378444, -7.35407060125e-16, -0.86602540378444, -0.86602540378444, -2.9397712985902e-15, 0.86602540378444, 0.86602540378444, -4.9047770029553e-16, -0.86602540378444, -0.86602540378444, -3.1847006584197e-15, 0.86602540378444, 0.86602540378444, -2.4554834046606e-16, -0.86602540378444, -0.86602540378444, -3.4296300182492e-15, 0.86602540378444, 0.84672419922828, -0.11196447610331, -0.94388333030837, -0.70710678118655, 0.33027906195517, 0.99371220989324, 0.53203207651534, -0.53203207651534, -0.99371220989324, -0.33027906195517, 0.70710678118655, 0.94388333030837, 0.11196447610331, -0.84672419922828, -0.84672419922828, 0.11196447610331, 0.94388333030837, 0.70710678118655, -0.33027906195517, -0.99371220989324, -0.53203207651534, 0.53203207651534, 0.99371220989324, 0.33027906195517, -0.70710678118655, -0.94388333030837, -0.11196447610331, 0.84672419922828, 0.84672419922829, -0.11196447610331, -0.94388333030837, -0.70710678118655, 0.33027906195517, 0.99371220989324, 0.53203207651534, -0.53203207651534, -0.99371220989324, -0.33027906195517, 0.70710678118655, 0.94388333030837, 0.11196447610331, -0.84672419922829, 0.82623877431599, -0.22252093395631, -0.98883082622513, -0.5, 0.62348980185873, 0.95557280578614, 0.074730093586424, -0.90096886790242, -0.73305187182983, 0.3653410243664, 1, 0.36534102436639, -0.73305187182983, -0.90096886790242, 0.074730093586425, 0.95557280578614, 0.62348980185873, -0.5, -0.98883082622513, -0.22252093395632, 0.826238774316, 0.82623877431599, -0.22252093395631, -0.98883082622513, -0.5, 0.62348980185874, 0.95557280578614, 0.074730093586423, -0.90096886790242, -0.73305187182982, 0.3653410243664, 1, 0.36534102436639, -0.73305187182983, -0.90096886790242, 0.074730093586427, 0.95557280578614, 0.62348980185873, -0.5, -0.98883082622513, -0.22252093395632, 0.826238774316, 0.80459777976667, -0.33027906195517, -0.9993007047884, -0.25881904510252, 0.84672419922828, 0.75797172314545, -0.39989202431974, -0.99371220989324, -0.18591160716291, 0.88411539350461, 0.70710678118655, -0.46726862827306, -0.98256647323329, -0.11196447610331, 0.91656225586998, 0.65228741127812, -0.53203207651534, -0.96592582628907, -0.037391194276324, 0.94388333030837, 0.5938201855735, -0.5938201855735, -0.94388333030837, 0.037391194276326, 0.96592582628907, 0.53203207651534, -0.65228741127812, -0.91656225586998, 0.11196447610331, 0.98256647323329, 0.46726862827306, -0.70710678118655, -0.88411539350461, 0.18591160716291, 0.99371220989324, 0.39989202431973, -0.75797172314546, -0.84672419922828, 0.25881904510253, 0.9993007047884, 0.33027906195517, -0.80459777976667, 0.78183148246803, -0.43388373911756, -0.97492791218182, 7.0448139982802e-16, 0.97492791218182, 0.43388373911756, -0.78183148246803, -0.78183148246803, 0.43388373911756, 0.97492791218182, 5.5109105961631e-16, -0.97492791218182, -0.43388373911756, 0.78183148246803, 0.78183148246803, -0.43388373911756, -0.97492791218182, 8.5787174003974e-16, 0.97492791218182, 0.43388373911756, -0.78183148246803, -0.78183148246803, 0.43388373911756, 0.97492791218182, -4.9047770029553e-16, -0.97492791218182, -0.43388373911756, 0.78183148246803, 0.78183148246803, -0.43388373911756, -0.97492791218182, -3.4296300182492e-15, 0.97492791218182, 0.43388373911755, -0.78183148246803, -0.78183148246803, 0.43388373911756, 0.97492791218182, -6.8611169784081e-15, -0.97492791218182, -0.43388373911756, 0.78183148246803, 0.75797172314545, -0.53203207651534, -0.91656225586998, 0.25881904510252, 0.99371220989324, 0.037391194276326, -0.98256647323329, -0.33027906195517, 0.88411539350461, 0.5938201855735, -0.70710678118655, -0.80459777976667, 0.46726862827306, 0.94388333030837, -0.18591160716291, -0.9993007047884, -0.11196447610331, 0.96592582628907, 0.39989202431974, -0.84672419922828, -0.65228741127812, 0.65228741127812, 0.84672419922829, -0.39989202431974, -0.96592582628907, 0.11196447610331, 0.9993007047884, 0.18591160716292, -0.94388333030837, -0.46726862827306, 0.80459777976667, 0.70710678118655, -0.59382018557351, -0.88411539350461, 0.33027906195516, 0.98256647323329, -0.037391194276329, -0.99371220989324, -0.25881904510252, 0.91656225586998, 0.53203207651534, -0.75797172314546, 0.73305187182983, -0.62348980185873, -0.82623877431599, 0.5, 0.90096886790242, -0.3653410243664, -0.95557280578614, 0.22252093395631, 0.98883082622513, -0.074730093586425, -1, -0.074730093586423, 0.98883082622513, 0.22252093395632, -0.95557280578614, -0.36534102436639, 0.90096886790242, 0.5, -0.82623877431599, -0.62348980185873, 0.73305187182983, 0.73305187182983, -0.62348980185874, -0.826238774316, 0.5, 0.90096886790242, -0.36534102436639, -0.95557280578614, 0.22252093395632, 0.98883082622513, -0.074730093586424, -1, -0.07473009358642, 0.98883082622513, 0.22252093395631, -0.95557280578614, -0.3653410243664, 0.90096886790242, 0.5, -0.82623877431599, -0.62348980185873, 0.73305187182983, 0.70710678118655, -0.70710678118655, -0.70710678118655, 0.70710678118655, 0.70710678118655, -0.70710678118655, -0.70710678118655, 0.70710678118655, 0.70710678118655, -0.70710678118655, -0.70710678118655, 0.70710678118655, 0.70710678118655, -0.70710678118655, -0.70710678118655, 0.70710678118655, 0.70710678118655, -0.70710678118655, -0.70710678118655, 0.70710678118655, 0.70710678118655, -0.70710678118655, -0.70710678118655, 0.70710678118655, 0.70710678118655, -0.70710678118655, -0.70710678118655, 0.70710678118655, 0.70710678118655, -0.70710678118655, -0.70710678118655, 0.70710678118655, 0.70710678118655, -0.70710678118655, -0.70710678118655, 0.70710678118655, 0.70710678118655, -0.70710678118655, -0.70710678118654, 0.70710678118655, 0.70710678118655, -0.70710678118655, 0.68017273777092, -0.78183148246803, -0.56332005806362, 0.86602540378444, 0.43388373911756, -0.9308737486442, -0.2947551744109, 0.97492791218182, 0.14904226617617, -0.99720379718118, -2.4499125789313e-15, 0.99720379718118, -0.14904226617617, -0.97492791218182, 0.29475517441091, 0.9308737486442, -0.43388373911756, -0.86602540378444, 0.56332005806362, 0.78183148246803, -0.68017273777092, -0.68017273777092, 0.78183148246803, 0.56332005806362, -0.86602540378444, -0.43388373911756, 0.9308737486442, 0.2947551744109, -0.97492791218182, -0.14904226617617, 0.99720379718118, 2.4431037919288e-16, -0.99720379718118, 0.14904226617618, 0.97492791218182, -0.29475517441091, -0.9308737486442, 0.43388373911756, 0.86602540378444, -0.56332005806362, -0.78183148246803, 0.68017273777092, 0.65228741127812, -0.84672419922828, -0.39989202431974, 0.96592582628907, 0.11196447610331, -0.9993007047884, 0.18591160716291, 0.94388333030837, -0.46726862827306, -0.80459777976667, 0.70710678118655, 0.5938201855735, -0.88411539350461, -0.33027906195517, 0.98256647323329, 0.037391194276325, -0.99371220989324, 0.25881904510252, 0.91656225586998, -0.53203207651534, -0.75797172314545, 0.75797172314545, 0.53203207651534, -0.91656225586998, -0.25881904510252, 0.99371220989324, -0.037391194276329, -0.98256647323329, 0.33027906195516, 0.88411539350461, -0.5938201855735, -0.70710678118655, 0.80459777976667, 0.46726862827306, -0.94388333030837, -0.18591160716291, 0.9993007047884, -0.11196447610331, -0.96592582628907, 0.39989202431974, 0.84672419922829, -0.65228741127812, 0.62348980185873, -0.90096886790242, -0.22252093395631, 1, -0.22252093395631, -0.90096886790242, 0.62348980185873, 0.62348980185873, -0.90096886790242, -0.22252093395632, 1, -0.22252093395631, -0.90096886790242, 0.62348980185873, 0.62348980185873, -0.90096886790242, -0.22252093395632, 1, -0.22252093395632, -0.90096886790242, 0.62348980185873, 0.62348980185873, -0.90096886790242, -0.22252093395632, 1, -0.22252093395632, -0.90096886790242, 0.62348980185874, 0.62348980185874, -0.90096886790242, -0.22252093395631, 1, -0.22252093395632, -0.90096886790242, 0.62348980185873, 0.62348980185873, -0.90096886790242, -0.22252093395631, 1, -0.22252093395632, -0.90096886790242, 0.62348980185874, 0.5938201855735, -0.94388333030837, -0.037391194276326, 0.96592582628907, -0.53203207651534, -0.65228741127812, 0.91656225586998, 0.11196447610331, -0.98256647323329, 0.46726862827306, 0.70710678118655, -0.88411539350461, -0.18591160716292, 0.99371220989324, -0.39989202431974, -0.75797172314545, 0.84672419922828, 0.25881904510252, -0.9993007047884, 0.33027906195516, 0.80459777976667, -0.80459777976667, -0.33027906195517, 0.9993007047884, -0.25881904510252, -0.84672419922828, 0.75797172314545, 0.39989202431974, -0.99371220989324, 0.18591160716292, 0.88411539350461, -0.70710678118655, -0.46726862827306, 0.98256647323329, -0.11196447610331, -0.91656225586997, 0.65228741127812, 0.53203207651534, -0.96592582628907, 0.037391194276331, 0.94388333030837, -0.59382018557351, 0.56332005806362, -0.97492791218182, 0.14904226617617, 0.86602540378444, -0.78183148246803, -0.2947551744109, 0.99720379718118, -0.43388373911756, -0.68017273777092, 0.9308737486442, -9.8033641995447e-16, -0.9308737486442, 0.68017273777092, 0.43388373911756, -0.99720379718118, 0.29475517441091, 0.78183148246803, -0.86602540378444, -0.14904226617617, 0.97492791218182, -0.56332005806362, -0.56332005806362, 0.97492791218182, -0.14904226617617, -0.86602540378444, 0.78183148246803, 0.2947551744109, -0.99720379718118, 0.43388373911756, 0.68017273777092, -0.93087374864421, -4.1644180977376e-15, 0.9308737486442, -0.68017273777092, -0.43388373911756, 0.99720379718118, -0.2947551744109, -0.78183148246803, 0.86602540378444, 0.14904226617617, -0.97492791218183, 0.56332005806363, 0.53203207651534, -0.99371220989324, 0.33027906195517, 0.70710678118655, -0.94388333030837, 0.11196447610331, 0.84672419922828, -0.84672419922828, -0.11196447610331, 0.94388333030837, -0.70710678118655, -0.33027906195517, 0.99371220989324, -0.53203207651534, -0.53203207651534, 0.99371220989324, -0.33027906195517, -0.70710678118655, 0.94388333030837, -0.1119644761033, -0.84672419922828, 0.84672419922828, 0.11196447610331, -0.94388333030837, 0.70710678118655, 0.33027906195516, -0.99371220989324, 0.53203207651534, 0.53203207651534, -0.99371220989324, 0.33027906195517, 0.70710678118655, -0.94388333030837, 0.11196447610331, 0.84672419922829, -0.84672419922829, -0.1119644761033, 0.94388333030837, -0.70710678118655, -0.33027906195517, 0.99371220989324, -0.53203207651534, 0.5, -1, 0.5, 0.5, -1, 0.5, 0.5, -1, 0.5, 0.5, -1, 0.5, 0.5, -1, 0.5, 0.5, -1, 0.5, 0.5, -1, 0.5, 0.5, -1, 0.5, 0.5, -1, 0.5, 0.5, -1, 0.50000000000001, 0.5, -1, 0.50000000000001, 0.5, -1, 0.5, 0.5, -1, 0.5, 0.5, -1, 0.5, 0.46726862827306, -0.99371220989324, 0.65228741127812, 0.25881904510252, -0.94388333030837, 0.80459777976667, 0.037391194276326, -0.84672419922829, 0.91656225586998, -0.18591160716291, -0.70710678118655, 0.98256647323329, -0.39989202431974, -0.53203207651534, 0.9993007047884, -0.59382018557351, -0.33027906195517, 0.96592582628907, -0.75797172314546, -0.11196447610331, 0.88411539350461, -0.88411539350461, 0.11196447610331, 0.75797172314545, -0.96592582628907, 0.33027906195517, 0.5938201855735, -0.9993007047884, 0.53203207651533, 0.39989202431974, -0.98256647323329, 0.70710678118654, 0.1859116071629, -0.91656225586998, 0.84672419922828, -0.037391194276335, -0.80459777976667, 0.94388333030837, -0.25881904510253, -0.65228741127812, 0.99371220989324, -0.46726862827307, 0.43388373911756, -0.97492791218182, 0.78183148246803, -5.8201671991329e-16, -0.78183148246803, 0.97492791218182, -0.43388373911756, -0.43388373911756, 0.97492791218182, -0.78183148246803, -2.6948419387608e-15, 0.78183148246803, -0.97492791218182, 0.43388373911756, 0.43388373911755, -0.97492791218182, 0.78183148246803, -2.4554834046606e-16, -0.78183148246803, 0.97492791218182, -0.43388373911756, -0.43388373911756, 0.97492791218182, -0.78183148246803, 3.1859386196929e-15, 0.78183148246803, -0.97492791218182, 0.43388373911756, 0.43388373911756, -0.97492791218182, 0.78183148246803, 9.7909845868129e-16, -0.78183148246802, 0.97492791218182, -0.43388373911756, -0.43388373911756, 0.97492791218182, -0.78183148246802, 1.9612918205455e-15, 0.78183148246803, -0.97492791218182, 0.43388373911756, 0.39989202431974, -0.94388333030837, 0.88411539350461, -0.25881904510252, -0.53203207651534, 0.98256647323329, -0.80459777976667, 0.11196447610331, 0.65228741127812, -0.9993007047884, 0.70710678118655, 0.037391194276325, -0.75797172314545, 0.99371220989324, -0.5938201855735, -0.18591160716291, 0.84672419922829, -0.96592582628907, 0.46726862827306, 0.33027906195517, -0.91656225586998, 0.91656225586998, -0.33027906195517, -0.46726862827306, 0.96592582628907, -0.84672419922829, 0.18591160716291, 0.5938201855735, -0.99371220989324, 0.75797172314545, -0.037391194276328, -0.70710678118655, 0.9993007047884, -0.65228741127812, -0.11196447610331, 0.80459777976667, -0.98256647323329, 0.53203207651533, 0.25881904510251, -0.88411539350461, 0.94388333030837, -0.39989202431975, 0.36534102436639, -0.90096886790242, 0.95557280578614, -0.5, -0.22252093395631, 0.82623877431599, -0.98883082622513, 0.62348980185873, 0.074730093586423, -0.73305187182983, 1, -0.73305187182983, 0.074730093586424, 0.62348980185873, -0.98883082622513, 0.826238774316, -0.22252093395631, -0.5, 0.95557280578614, -0.90096886790242, 0.3653410243664, 0.36534102436639, -0.90096886790242, 0.95557280578614, -0.5, -0.22252093395631, 0.82623877431599, -0.98883082622513, 0.62348980185873, 0.074730093586418, -0.73305187182983, 1, -0.73305187182983, 0.074730093586426, 0.62348980185874, -0.98883082622513, 0.826238774316, -0.22252093395631, -0.49999999999999, 0.95557280578614, -0.90096886790242, 0.3653410243664, 0.33027906195517, -0.84672419922828, 0.99371220989324, -0.70710678118655, 0.11196447610331, 0.53203207651534, -0.94388333030837, 0.94388333030837, -0.53203207651534, -0.11196447610331, 0.70710678118655, -0.99371220989324, 0.84672419922828, -0.33027906195517, -0.33027906195516, 0.84672419922828, -0.99371220989324, 0.70710678118655, -0.11196447610331, -0.53203207651534, 0.94388333030837, -0.94388333030837, 0.53203207651533, 0.11196447610331, -0.70710678118654, 0.99371220989324, -0.84672419922828, 0.33027906195516, 0.33027906195517, -0.84672419922828, 0.99371220989324, -0.70710678118655, 0.11196447610331, 0.53203207651533, -0.94388333030837, 0.94388333030837, -0.53203207651533, -0.11196447610331, 0.70710678118655, -0.99371220989324, 0.84672419922828, -0.33027906195517, 0.2947551744109, -0.78183148246803, 0.99720379718118, -0.86602540378444, 0.43388373911756, 0.14904226617617, -0.68017273777092, 0.97492791218182, -0.93087374864421, 0.56332005806362, -7.35407060125e-16, -0.56332005806362, 0.9308737486442, -0.97492791218182, 0.68017273777092, -0.14904226617618, -0.43388373911756, 0.86602540378444, -0.99720379718118, 0.78183148246803, -0.2947551744109, -0.2947551744109, 0.78183148246803, -0.99720379718118, 0.86602540378444, -0.43388373911756, -0.14904226617618, 0.68017273777092, -0.97492791218182, 0.93087374864421, -0.56332005806362, -4.899206177226e-15, 0.56332005806362, -0.93087374864421, 0.97492791218182, -0.68017273777093, 0.14904226617618, 0.43388373911756, -0.86602540378443, 0.99720379718118, -0.78183148246803, 0.29475517441091, 0.25881904510252, -0.70710678118655, 0.96592582628907, -0.96592582628907, 0.70710678118655, -0.25881904510252, -0.25881904510252, 0.70710678118655, -0.96592582628907, 0.96592582628907, -0.70710678118655, 0.25881904510252, 0.25881904510252, -0.70710678118655, 0.96592582628907, -0.96592582628907, 0.70710678118655, -0.25881904510252, -0.25881904510252, 0.70710678118655, -0.96592582628907, 0.96592582628907, -0.70710678118655, 0.25881904510252, 0.25881904510252, -0.70710678118655, 0.96592582628907, -0.96592582628907, 0.70710678118655, -0.25881904510252, -0.25881904510252, 0.70710678118655, -0.96592582628907, 0.96592582628907, -0.70710678118655, 0.25881904510252, 0.25881904510252, -0.70710678118655, 0.96592582628907, -0.96592582628907, 0.70710678118654, -0.25881904510253, 0.22252093395631, -0.62348980185873, 0.90096886790242, -1, 0.90096886790242, -0.62348980185873, 0.22252093395631, 0.22252093395632, -0.62348980185873, 0.90096886790242, -1, 0.90096886790242, -0.62348980185874, 0.22252093395631, 0.22252093395631, -0.62348980185873, 0.90096886790242, -1, 0.90096886790242, -0.62348980185873, 0.22252093395632, 0.22252093395631, -0.62348980185873, 0.90096886790242, -1, 0.90096886790242, -0.62348980185873, 0.22252093395632, 0.22252093395631, -0.62348980185873, 0.90096886790242, -1, 0.90096886790242, -0.62348980185874, 0.22252093395631, 0.22252093395631, -0.62348980185873, 0.90096886790242, -1, 0.90096886790242, -0.62348980185873, 0.22252093395632, 0.18591160716291, -0.53203207651534, 0.80459777976667, -0.96592582628907, 0.99371220989324, -0.88411539350461, 0.65228741127812, -0.33027906195517, -0.037391194276324, 0.39989202431974, -0.70710678118655, 0.91656225586998, -0.9993007047884, 0.94388333030837, -0.75797172314546, 0.46726862827306, -0.1119644761033, -0.25881904510252, 0.5938201855735, -0.84672419922828, 0.98256647323329, -0.98256647323329, 0.84672419922828, -0.59382018557351, 0.25881904510252, 0.1119644761033, -0.46726862827306, 0.75797172314545, -0.94388333030837, 0.9993007047884, -0.91656225586998, 0.70710678118655, -0.39989202431975, 0.037391194276323, 0.33027906195517, -0.65228741127811, 0.88411539350461, -0.99371220989324, 0.96592582628907, -0.80459777976667, 0.53203207651533, -0.18591160716292, 0.14904226617617, -0.43388373911756, 0.68017273777092, -0.86602540378444, 0.97492791218182, -0.99720379718118, 0.93087374864421, -0.78183148246803, 0.56332005806362, -0.29475517441091, -2.9397712985902e-15, 0.2947551744109, -0.56332005806362, 0.78183148246803, -0.9308737486442, 0.99720379718118, -0.97492791218182, 0.86602540378444, -0.68017273777092, 0.43388373911756, -0.14904226617617, -0.14904226617617, 0.43388373911756, -0.68017273777092, 0.86602540378443, -0.97492791218182, 0.99720379718118, -0.9308737486442, 0.78183148246803, -0.56332005806363, 0.2947551744109, 8.8193138957707e-15, -0.29475517441089, 0.56332005806362, -0.78183148246803, 0.9308737486442, -0.99720379718118, 0.97492791218182, -0.86602540378444, 0.68017273777092, -0.43388373911756, 0.14904226617618, 0.11196447610331, -0.33027906195517, 0.53203207651534, -0.70710678118655, 0.84672419922828, -0.94388333030837, 0.99371220989324, -0.99371220989324, 0.94388333030837, -0.84672419922828, 0.70710678118655, -0.53203207651534, 0.33027906195516, -0.1119644761033, -0.11196447610331, 0.33027906195516, -0.53203207651534, 0.70710678118655, -0.84672419922828, 0.94388333030837, -0.99371220989324, 0.99371220989324, -0.94388333030837, 0.84672419922828, -0.70710678118654, 0.53203207651534, -0.33027906195517, 0.11196447610331, 0.1119644761033, -0.33027906195517, 0.53203207651534, -0.70710678118655, 0.84672419922828, -0.94388333030837, 0.99371220989324, -0.99371220989324, 0.94388333030837, -0.84672419922828, 0.70710678118656, -0.53203207651533, 0.33027906195516, -0.11196447610331, 0.074730093586424, -0.22252093395631, 0.36534102436639, -0.5, 0.62348980185873, -0.73305187182983, 0.82623877431599, -0.90096886790242, 0.95557280578614, -0.98883082622513, 1, -0.98883082622513, 0.95557280578614, -0.90096886790242, 0.826238774316, -0.73305187182983, 0.62348980185873, -0.5, 0.3653410243664, -0.22252093395631, 0.074730093586427, 0.074730093586424, -0.22252093395631, 0.3653410243664, -0.5, 0.62348980185873, -0.73305187182983, 0.826238774316, -0.90096886790242, 0.95557280578614, -0.98883082622513, 1, -0.98883082622513, 0.95557280578614, -0.90096886790242, 0.826238774316, -0.73305187182983, 0.62348980185872, -0.50000000000001, 0.36534102436639, -0.22252093395632, 0.074730093586431, 0.037391194276326, -0.11196447610331, 0.18591160716291, -0.25881904510252, 0.33027906195517, -0.39989202431974, 0.46726862827306, -0.53203207651534, 0.5938201855735, -0.65228741127812, 0.70710678118655, -0.75797172314545, 0.80459777976667, -0.84672419922828, 0.88411539350461, -0.91656225586998, 0.94388333030837, -0.96592582628907, 0.98256647323329, -0.99371220989324, 0.9993007047884, -0.9993007047884, 0.99371220989324, -0.98256647323329, 0.96592582628907, -0.94388333030837, 0.91656225586997, -0.88411539350461, 0.84672419922828, -0.80459777976668, 0.75797172314545, -0.70710678118654, 0.65228741127813, -0.5938201855735, 0.53203207651534, -0.46726862827307, 0.39989202431975, -0.33027906195516, 0.25881904510252, -0.18591160716291, 0.1119644761033, -0.037391194276333, 6.1232339957368e-17, -1.836970198721e-16, -5.8201671991329e-16, 1.3477304596987e-15, 5.5109105961631e-16, 1.1028010998692e-15, -9.8033641995447e-16, -2.6948419387608e-15, -7.35407060125e-16, 6.1294238021026e-16, -4.9047770029553e-16, 3.9207266991813e-15, -2.4554834046606e-16, -3.4296300182492e-15, -6.1898063658838e-19, 3.4308679795224e-15, 2.4431037919288e-16, 3.1859386196929e-15, -6.6161876185786e-15, -4.1644180977376e-15, -6.3712582587492e-15, 9.8015072576349e-15, 9.7909845868129e-16, 2.4511505402045e-15, -5.8813995390902e-15, 9.311648537976e-15, 1.4689571783402e-15, 1.9612918205455e-15, 8.8193138957707e-15, 8.8217898183171e-15, 1.9588158979992e-15, 1.4714331008866e-15, -4.9016820997724e-15, 8.3319310986581e-15, 2.4486746176581e-15, 1.519242909643e-14, -4.4118233801134e-15, -6.3687823362028e-15, -1.1272321377885e-14, 4.9171566156871e-16, 1.0288890054748e-14, 7.3522136593402e-15 }; // other functions static void MFCC_dofft(MFCC*, uint32); static float MFCC_prepareMel(MFCC*, float*); // float MFCC_prepareERB(MFCC *, float *); void MFCC_Ctor(MFCC* unit) { // may want to check sampling rate here! unit->m_srate = unit->mWorld->mFullRate.mSampleRate; // if sample rate is 88200 or 96000, assume taking double size FFT to start with if (unit->m_srate > (44100.0 * 1.5)) unit->m_srate = unit->m_srate * 0.5; if (((int)(unit->m_srate + 0.01)) == 44100) { unit->m_startbin = g_startbin44100; unit->m_endbin = g_endbin44100; unit->m_cumulindex = g_cumulindex44100; unit->m_bandweights = g_melbandweights44100; } else // else 48000; potentially dangerous if it isn't! Fortunately, shouldn't write any data to unknown memory { unit->m_startbin = g_startbin48000; unit->m_endbin = g_endbin48000; unit->m_cumulindex = g_cumulindex48000; unit->m_bandweights = g_melbandweights48000; } // fixed for now unit->m_numbands = 42; unit->m_numcoefficients = (int)ZIN0(1); // range checks if (unit->m_numcoefficients < 1) { unit->m_numcoefficients = 1; } if (unit->m_numcoefficients > 42) { unit->m_numcoefficients = 42; } unit->m_bands = (float*)RTAlloc(unit->mWorld, unit->m_numbands * sizeof(float)); unit->m_mfcc = (float*)RTAlloc(unit->mWorld, unit->m_numcoefficients * sizeof(float)); ClearUnitIfMemFailed(unit->m_bands && unit->m_mfcc); Clear(unit->m_numbands, unit->m_bands); Clear(unit->m_numcoefficients, unit->m_mfcc); for (int j = 0; j < unit->m_numcoefficients; ++j) ZOUT0(j) = 0.f; unit->mCalcFunc = (UnitCalcFunc)&MFCC_next; } void MFCC_Dtor(MFCC* unit) { if (unit->m_mfcc) RTFree(unit->mWorld, unit->m_mfcc); if (unit->m_bands) RTFree(unit->mWorld, unit->m_bands); } void MFCC_next(MFCC* unit, int wrongNumSamples) { float fbufnum = ZIN0(0); // next FFT bufffer ready, update // assuming at this point that buffer precalculated for any resampling if (fbufnum > -0.01f) MFCC_dofft(unit, (uint32)fbufnum); // always output sones // float outval= unit->m_sones; // printf("sones %f phontotal %f \n",outval, unit->m_phontotal); // number of outputs depends on numcoefficients // control rate output // ZOUT0(0)=unit->m_sones; for (int k = 0; k < unit->m_numcoefficients; ++k) ZOUT0(k) = unit->m_mfcc[k]; } // calculation function once FFT data ready void MFCC_dofft(MFCC* unit, uint32 ibufnum) { World* world = unit->mWorld; SndBuf* buf; if (ibufnum >= world->mNumSndBufs) { int localBufNum = ibufnum - world->mNumSndBufs; Graph* parent = unit->mParent; if (localBufNum <= parent->localBufNum) { buf = parent->mLocalSndBufs + localBufNum; } else { buf = world->mSndBufs; } } else { buf = world->mSndBufs + ibufnum; } LOCK_SNDBUF(buf); // int numbins = buf->samples - 2 >> 1; // assumed in this representation ToComplexApx(buf); float* data = buf->data; float mult = MFCC_prepareMel(unit, data); // MFCC_prepareERB float* pbands = unit->m_bands; // now use cosine basis for transform; approximates principal components, compresses information into a smaller // number of bands FFT is actually more expensive here, easiest just to calculate the basis decomposition straight // off // hard coded 42 = max num bands because this is how the indexing in the dct source is set up for (int k = 0; k < unit->m_numcoefficients; ++k) { float sum = 0.0; int base = k * 42; for (int j = 0; j < unit->m_numbands; ++j) { int index = base + j; // sum+= (0.5*dct[index]+0.5)*pbands[j]; sum += (dct[index]) * pbands[j]; } // could also divide by numcoefficients, but left off for compatibility between MFCCs extracted in different // ways unit->m_mfcc[k] = 0.25f * ((sum * mult) + 1.0f); // 0.5*(0.5*(sum*mult)+0.5); } } float MFCC_prepareMel(MFCC* unit, float* data) { float* pbands = unit->m_bands; int* startbin = unit->m_startbin; int* endbin = unit->m_endbin; int* cumulindex = unit->m_cumulindex; float* weights = unit->m_bandweights; for (int k = 0; k < unit->m_numbands; ++k) { int bandstart = startbin[k]; int bandend = endbin[k]; // p1 = endbin[k]+1; float bsum = 0.f; float real, imag, power; int index, index2; // float lastpower=0.0; index2 = cumulindex[k] - bandstart; for (int j = bandstart; j < bandend; ++j) { index = j + j; real = data[index]; imag = data[index + 1]; if (j == 0) power = real * real; // sc_abs(real); //dc else power = real * real + imag * imag; // sqrt((real*real) + (imag*imag)); float multiplier = weights[index2 + j]; //[cumulindex[k] + (j-bandstart)] bsum += (power * multiplier); } // either keep as double to preserve the small value // pbands[k] = 10.f * (sc_log10((bsum< 1e-42? 1e-42: bsum)) + 5.f); // or make sure value works as a float: // pbands[k] = 10.f * (sc_log10((bsum< 1e-20f? 1e-20f: bsum)) + 5.f); // want to avoid negative values, dynamic range roughly around 11 powers of ten (110dB) // pbands[k] = 10.f * (std::log10((bsum< 1e-5f? 1e-5f: bsum)) + 5.f); pbands[k] = 10.f * (std::log10(sc_max(1e-5f, bsum)) + 5.f); } // float mult= 0.01; //(1.0/((float)unit->m_numcoefficients)); //0.01*(1.0/((float)unit->m_numcoefficients)); return 0.01f; } // Original draft for EFCC // temporal masking over ERB bands: peaks take a while to decay // spectral masking over which bins summed as contributors for ERB bands; spreading activation function actually implies // that the overall power is greater from spread? masking not triangular but slanted towards masking higher frequency // content (ie, lower freq bins mask upper) // // for true MP3 style compression would have to see if each FFT bin was noise like or sine like (transient measure on // instantaneous frequency for example), and use the appropriate masking curve efficiency is preferred here // // thus can calculate squared powers as you go? cheapest if only have effect of spectral masking above, covering a fixed // number of bins? but then, frequency biased loudness based on ERB band centre frequency! // float MFCC_prepareERB(MFCC * unit, float * data) { // // int j,k; // // float * pbands= unit->m_bands; // // for (k=0; k<unit->m_numbands; ++k){ // // int bandstart=eqlbandbins[k]; // //int bandend=eqlbandbins[k+1]; // int bandsize= eqlbandsizes[k]; // int bandend= bandstart+bandsize; // // float bsum=0.0; // float real, imag, power; // int index; // //float lastpower=0.0; // // for (j=bandstart; j<bandend;++j) { // index = 2*j; // real= data[index]; // imag= data[index+1]; // // power = (real*real) + (imag*imag); // // //power of three combination // bsum= bsum+(power*power*power); // // } // // float db= 10*((0.33334*log10(bsum)) + 4.8810017610244); //correct multipler until you get loudness output of 1! // // //convert via contour // if(db<contours[k][0]) db=0; // else if (db>contours[k][10]) db=phons[10]; // else { // // float prop=0.0; // // for (j=1; j<11; ++j) { // if(db<contours[k][j]) { // prop= (db-contours[k][j-1])/(contours[k][j]-contours[k][j-1]); // break; // } // // if(j==10) // prop=1.0; // } // // db= (1.0-prop)*phons[j-1]+ prop*phons[j]; // //printf("prop %f db %f j %d\n",prop,db,j); // // } // // //spectralmasking, 6dB drop per frame? // //try also with just take db // pbands[k] = db; //sc_max(db, (unit->m_bands[k]) - tmask); // // } // // // //now use cosine basis for transform; approximates principal components, compresses information into a smaller // number of bands // //FFT is actually more expensive here, easiest just to calculate the basis decomposition straight off // float mult= 0.01*(1.0/((float)unit->m_numcoefficients)); // // return mult; //} //
151,896
C++
.cpp
3,492
16.636312
157
0.317653
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,958
ML.cpp
supercollider_supercollider/server/plugins/ML.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // machine listening plug-ins adapted for SuperCollider core #include "ML.h" #include "FFT_UGens.h" InterfaceTable* ft; PluginLoad(ML_UGens) { ft = inTable; DefineDtorCantAliasUnit(BeatTrack); DefineDtorUnit(Loudness); DefineDtorUnit(KeyTrack); DefineDtorUnit(MFCC); DefineDtorUnit(Onsets); DefineDtorCantAliasUnit(BeatTrack2); DefineSimpleUnit(SpecFlatness); DefineDtorUnit(SpecPcile); DefineSimpleUnit(SpecCentroid); }
1,308
C++
.cpp
32
37.59375
78
0.785601
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,959
LFUGens.cpp
supercollider_supercollider/server/plugins/LFUGens.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "SC_PlugIn.h" #include "SIMD_Unit.hpp" #include <limits.h> #include <cstdio> #include "function_attributes.h" #include <boost/align/is_aligned.hpp> static InterfaceTable* ft; struct Vibrato : public Unit { double mPhase, m_attackSlope, m_attackLevel; float mFreqMul, m_scaleA, m_scaleB, mFreq; int m_delay, m_attack; float trig; }; struct LFPulse : public Unit { double mPhase; float mFreqMul, mDuty; }; struct LFSaw : public Unit { double mPhase; float mFreqMul; }; struct LFPar : public Unit { double mPhase; float mFreqMul; }; struct LFCub : public Unit { double mPhase; float mFreqMul; }; struct LFTri : public Unit { double mPhase; float mFreqMul; }; struct LFGauss : public Unit { double mPhase; float mDurMul; }; struct Impulse : public Unit { double mPhase, mPhaseOffset, mPhaseIncrement; float mFreqMul; }; struct VarSaw : public Unit { double mPhase; float mFreqMul, mDuty, mInvDuty, mInv1Duty; }; struct SyncSaw : public Unit { double mPhase1, mPhase2; float mFreqMul; }; struct Line : public Unit { double mLevel, mSlope; float mEndLevel; int mCounter; }; struct XLine : public Unit { double mLevel, mGrowth; float mEndLevel; int mCounter; }; struct Cutoff : public Unit { double mLevel, mSlope; int mWaitCounter; }; struct LinExp : public Unit { float m_dstratio, m_rsrcrange, m_rrminuslo, m_dstlo; }; struct Clip : public Unit { float m_lo, m_hi; }; struct Wrap : public Unit { float m_lo, m_hi; }; struct Fold : public Unit { float m_lo, m_hi, m_range; }; struct Unwrap : public Unit { float m_range, m_half, m_offset, m_prev; }; struct ModDif : public Unit { float m_dif, m_mod; }; struct AmpComp : public Unit { float m_rootmul, m_exponent; }; struct AmpCompA : public Unit { double m_scale, m_offset; }; struct InRange : public Unit { // nothing }; struct InRect : public Unit { // nothing }; // struct Trapezoid : public Unit //{ // float m_leftScale, m_rightScale, m_a, m_b, m_c, m_d; //}; struct A2K : public Unit {}; struct T2K : public Unit {}; struct T2A : public Unit { float mLevel; }; struct EnvGen : public Unit { double m_a1, m_a2, m_b1, m_y1, m_y2, m_grow, m_level, m_endLevel; int m_counter, m_stage, m_shape, m_releaseNode; float m_prevGate; bool m_released; }; struct Linen : public Unit { float m_endLevel; double m_slope, m_level; int m_counter, m_stage; float m_prevGate; }; ////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" { void Vibrato_next(Vibrato* unit, int inNumSamples); void Vibrato_Ctor(Vibrato* unit); void LFPulse_next_a(LFPulse* unit, int inNumSamples); void LFPulse_next_k(LFPulse* unit, int inNumSamples); void LFPulse_Ctor(LFPulse* unit); void LFSaw_next_a(LFSaw* unit, int inNumSamples); void LFSaw_next_k(LFSaw* unit, int inNumSamples); void LFSaw_Ctor(LFSaw* unit); void LFTri_next_a(LFTri* unit, int inNumSamples); void LFTri_next_k(LFTri* unit, int inNumSamples); void LFTri_Ctor(LFTri* unit); void LFPar_next_a(LFPar* unit, int inNumSamples); void LFPar_next_k(LFPar* unit, int inNumSamples); void LFPar_Ctor(LFPar* unit); void LFCub_next_a(LFCub* unit, int inNumSamples); void LFCub_next_k(LFCub* unit, int inNumSamples); void LFCub_Ctor(LFCub* unit); void LFGauss_next_a(LFGauss* unit, int inNumSamples); void LFGauss_next_k(LFGauss* unit, int inNumSamples); void LFGauss_next_aa(LFGauss* unit, int inNumSamples); void LFGauss_Ctor(LFGauss* unit); void VarSaw_next_a(VarSaw* unit, int inNumSamples); void VarSaw_next_k(VarSaw* unit, int inNumSamples); void VarSaw_Ctor(VarSaw* unit); void Impulse_next_aa(Impulse* unit, int inNumSamples); void Impulse_next_ak(Impulse* unit, int inNumSamples); void Impulse_next_ai(Impulse* unit, int inNumSamples); void Impulse_next_kk(Impulse* unit, int inNumSamples); void Impulse_next_ki(Impulse* unit, int inNumSamples); void Impulse_next_ik(Impulse* unit, int inNumSamples); void Impulse_next_ii(Impulse* unit, int inNumSamples); void Impulse_Ctor(Impulse* unit); void SyncSaw_next_aa(SyncSaw* unit, int inNumSamples); void SyncSaw_next_ak(SyncSaw* unit, int inNumSamples); void SyncSaw_next_ka(SyncSaw* unit, int inNumSamples); void SyncSaw_next_kk(SyncSaw* unit, int inNumSamples); void SyncSaw_Ctor(SyncSaw* unit); void A2K_next(A2K* unit, int inNumSamples); void A2K_Ctor(A2K* unit); void T2K_next(T2K* unit, int inNumSamples); void T2K_Ctor(T2K* unit); void T2A_next(T2A* unit, int inNumSamples); void T2A_Ctor(T2A* unit); void Line_next(Line* unit, int inNumSamples); void Line_Ctor(Line* unit); void XLine_next(XLine* unit, int inNumSamples); void XLine_Ctor(XLine* unit); void Wrap_next_kk(Wrap* unit, int inNumSamples); void Wrap_next_ak(Wrap* unit, int inNumSamples); void Wrap_next_ka(Wrap* unit, int inNumSamples); void Wrap_next_aa(Wrap* unit, int inNumSamples); void Wrap_Ctor(Wrap* unit); void Fold_next_kk(Fold* unit, int inNumSamples); void Fold_next_ak(Fold* unit, int inNumSamples); void Fold_next_ka(Fold* unit, int inNumSamples); void Fold_next_aa(Fold* unit, int inNumSamples); void Fold_Ctor(Fold* unit); void Clip_next_kk(Clip* unit, int inNumSamples); void Clip_next_ka(Clip* unit, int inNumSamples); void Clip_next_ak(Clip* unit, int inNumSamples); void Clip_next_aa(Clip* unit, int inNumSamples); void Clip_Ctor(Clip* unit); void Unwrap_next(Unwrap* unit, int inNumSamples); void Unwrap_Ctor(Unwrap* unit); void ModDif_next_kk(ModDif* unit, int inNumSamples); void ModDif_next_ak(ModDif* unit, int inNumSamples); void ModDif_next_ka(ModDif* unit, int inNumSamples); void ModDif_next_aa(ModDif* unit, int inNumSamples); void ModDif_Ctor(ModDif* unit); void AmpComp_next(AmpComp* unit, int inNumSamples); void AmpComp_Ctor(AmpComp* unit); void AmpCompA_next(AmpCompA* unit, int inNumSamples); void AmpCompA_Ctor(AmpCompA* unit); void InRange_next(InRange* unit, int inNumSamples); void InRange_Ctor(InRange* unit); void InRect_next(InRect* unit, int inNumSamples); void InRect_Ctor(InRect* unit); void LinExp_next(LinExp* unit, int inNumSamples); void LinExp_next_kk(LinExp* unit, int inNumSamples); void LinExp_next_ak(LinExp* unit, int inNumSamples); void LinExp_next_ka(LinExp* unit, int inNumSamples); void LinExp_Ctor(LinExp* unit); void EnvGen_next_k(EnvGen* unit, int inNumSamples); void EnvGen_next_aa(EnvGen* unit, int inNumSamples); void EnvGen_next_ak(EnvGen* unit, int inNumSamples); void EnvGen_Ctor(EnvGen* unit); void Linen_next_k(Linen* unit, int inNumSamples); void Linen_Ctor(Linen* unit); } ////////////////////////////////////////////////////////////////////////////////////////////////// void Vibrato_next(Vibrato* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float curtrig = ZIN0(8); if (unit->trig <= 0.f && curtrig > 0.f) { unit->mFreqMul = 4.0 * SAMPLEDUR; unit->mPhase = 4.0 * sc_wrap(ZIN0(7), 0.f, 1.f) - 1.0; RGen& rgen = *unit->mParent->mRGen; float rate = ZIN0(1) * unit->mFreqMul; float depth = ZIN0(2); float rateVariation = ZIN0(5); float depthVariation = ZIN0(6); unit->mFreq = rate * (1.f + rateVariation * rgen.frand2()); unit->m_scaleA = depth * (1.f + depthVariation * rgen.frand2()); unit->m_scaleB = depth * (1.f + depthVariation * rgen.frand2()); unit->m_delay = (int)(ZIN0(3) * SAMPLERATE); unit->m_attack = (int)(ZIN0(4) * SAMPLERATE); unit->m_attackSlope = 1. / (double)(1 + unit->m_attack); unit->m_attackLevel = unit->m_attackSlope; } unit->trig = curtrig; double ffreq = unit->mFreq; double phase = unit->mPhase; float scaleA = unit->m_scaleA; float scaleB = unit->m_scaleB; if (unit->m_delay > 0) { int remain = sc_min(inNumSamples, unit->m_delay); unit->m_delay -= remain; inNumSamples -= remain; LOOP(remain, ZXP(out) = ZXP(in);); if (unit->m_delay <= 0 && inNumSamples > 0) { if (unit->m_attack > 0) goto doAttack; else goto doNormal; } } else if (unit->m_attack) { doAttack: int remain = sc_min(inNumSamples, unit->m_attack); unit->m_attack -= remain; inNumSamples -= remain; double attackSlope = unit->m_attackSlope; double attackLevel = unit->m_attackLevel; LOOP( remain, if (phase < 1.f) { float z = phase; ZXP(out) = ZXP(in) * (1.f + (float)attackLevel * scaleA * (1.f - z * z)); } else if (phase < 3.f) { float z = phase - 2.f; ZXP(out) = ZXP(in) * (1.f + (float)attackLevel * scaleB * (z * z - 1.f)); } else { phase -= 4.f; float z = phase; float depth = ZIN0(2); float rateVariation = ZIN0(5); float depthVariation = ZIN0(6); float rate = ZIN0(1) * unit->mFreqMul; RGen& rgen = *unit->mParent->mRGen; ffreq = rate * (1.f + rateVariation * rgen.frand2()); scaleA = depth * (1.f + depthVariation * rgen.frand2()); scaleB = depth * (1.f + depthVariation * rgen.frand2()); ZXP(out) = ZXP(in) * (1.f + (float)attackLevel * scaleA * (1.f - z * z)); } phase += ffreq; attackLevel += attackSlope;); unit->m_attackLevel = attackLevel; if (unit->m_attack <= 0 && inNumSamples > 0) goto doNormal; } else { doNormal: LOOP1( inNumSamples, if (phase < 1.f) { float z = phase; ZXP(out) = ZXP(in) * (1.f + scaleA * (1.f - z * z)); } else if (phase < 3.f) { float z = phase - 2.f; ZXP(out) = ZXP(in) * (1.f + scaleB * (z * z - 1.f)); } else { phase -= 4.f; float z = phase; float depth = ZIN0(2); float rateVariation = ZIN0(5); float depthVariation = ZIN0(6); float rate = ZIN0(1) * unit->mFreqMul; RGen& rgen = *unit->mParent->mRGen; ffreq = rate * (1.f + rateVariation * rgen.frand2()); scaleA = depth * (1.f + depthVariation * rgen.frand2()); scaleB = depth * (1.f + depthVariation * rgen.frand2()); ZXP(out) = ZXP(in) * (1.f + scaleA * (1.f - z * z)); } phase += ffreq;); } unit->mPhase = phase; unit->mFreq = ffreq; unit->m_scaleA = scaleA; unit->m_scaleB = scaleB; } void Vibrato_Ctor(Vibrato* unit) { unit->mFreqMul = 4.0 * SAMPLEDUR; const double initPhase = unit->mPhase = 4.0 * sc_wrap(ZIN0(7), 0.f, 1.f) - 1.0; RGen& rgen = *unit->mParent->mRGen; float rate = ZIN0(1) * unit->mFreqMul; float depth = ZIN0(2); float rateVariation = ZIN0(5); float depthVariation = ZIN0(6); float initFreq = unit->mFreq = rate * (1.f + rateVariation * rgen.frand2()); float initScaleA = unit->m_scaleA = depth * (1.f + depthVariation * rgen.frand2()); float initScaleB = unit->m_scaleB = depth * (1.f + depthVariation * rgen.frand2()); unit->m_delay = (int)(ZIN0(3) * SAMPLERATE); unit->m_attack = (int)(ZIN0(4) * SAMPLERATE); unit->m_attackSlope = 1. / (double)(1 + unit->m_attack); unit->m_attackLevel = unit->m_attackSlope; unit->trig = 0.0f; SETCALC(Vibrato_next); Vibrato_next(unit, 1); unit->mPhase = initPhase; unit->mFreq = initFreq; unit->m_scaleA = initScaleA; unit->m_scaleB = initScaleB; unit->trig = 0.0f; } ////////////////////////////////////////////////////////////////////////////////////////////////// void LFPulse_next_a(LFPulse* unit, int inNumSamples) { float* out = ZOUT(0); float* freq = ZIN(0); float nextDuty = ZIN0(2); float duty = unit->mDuty; float freqmul = unit->mFreqMul; double phase = unit->mPhase; LOOP1( inNumSamples, float z; if (phase >= 1.f) { phase -= 1.f; duty = unit->mDuty = nextDuty; // output at least one sample from the opposite polarity z = duty <= 0.5f ? 1.f : 0.f; } else { z = phase < duty ? 1.f : 0.f; } phase += ZXP(freq) * freqmul; ZXP(out) = z;); unit->mPhase = phase; } void LFPulse_next_k(LFPulse* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0) * unit->mFreqMul; float nextDuty = ZIN0(2); float duty = unit->mDuty; double phase = unit->mPhase; LOOP1( inNumSamples, float z; if (phase >= 1.f) { phase -= 1.f; duty = unit->mDuty = nextDuty; // output at least one sample from the opposite polarity z = duty <= 0.5f ? 1.f : 0.f; } else { z = phase < duty ? 1.f : 0.f; } phase += freq; ZXP(out) = z;); unit->mPhase = phase; } void LFPulse_Ctor(LFPulse* unit) { if (INRATE(0) == calc_FullRate) { SETCALC(LFPulse_next_a); } else { SETCALC(LFPulse_next_k); } unit->mFreqMul = unit->mRate->mSampleDur; double initPhase = unit->mPhase = ZIN0(1); float initDuty = unit->mDuty = ZIN0(2); LFPulse_next_k(unit, 1); unit->mPhase = initPhase; unit->mDuty = initDuty; } ////////////////////////////////////////////////////////////////////////////////////////////////// void LFSaw_next_a(LFSaw* unit, int inNumSamples) { float* out = ZOUT(0); float* freq = ZIN(0); float freqmul = unit->mFreqMul; double phase = unit->mPhase; LOOP1(inNumSamples, float z = phase; // out must be written last for in place operation phase += ZXP(freq) * freqmul; if (phase >= 1.f) phase -= 2.f; else if (phase <= -1.f) phase += 2.f; ZXP(out) = z;); unit->mPhase = phase; } void LFSaw_next_k(LFSaw* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0) * unit->mFreqMul; double phase = unit->mPhase; if (freq >= 0.f) { LOOP1(inNumSamples, ZXP(out) = phase; phase += freq; if (phase >= 1.f) phase -= 2.f;); } else { LOOP1(inNumSamples, ZXP(out) = phase; phase += freq; if (phase <= -1.f) phase += 2.f;); } unit->mPhase = phase; } void LFSaw_Ctor(LFSaw* unit) { if (INRATE(0) == calc_FullRate) SETCALC(LFSaw_next_a); else SETCALC(LFSaw_next_k); unit->mFreqMul = 2.0 * unit->mRate->mSampleDur; double initPhase = unit->mPhase = ZIN0(1); LFSaw_next_k(unit, 1); unit->mPhase = initPhase; } ////////////////////////////////////////////////////////////////////////////////////////////////// void LFPar_next_a(LFPar* unit, int inNumSamples) { float* out = ZOUT(0); float* freq = ZIN(0); float freqmul = unit->mFreqMul; double phase = unit->mPhase; float z, y; LOOP1( inNumSamples, if (phase < 1.f) { z = phase; y = 1.f - z * z; } else if (phase < 3.f) { z = phase - 2.f; y = z * z - 1.f; } else { phase -= 4.f; z = phase; y = 1.f - z * z; } // Note: the following two lines were originally one, but seems to compile wrong on mac float phaseadd = ZXP(freq); phase += phaseadd * freqmul; ZXP(out) = y;); unit->mPhase = phase; } void LFPar_next_k(LFPar* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0) * unit->mFreqMul; double phase = unit->mPhase; LOOP1( inNumSamples, if (phase < 1.f) { float z = phase; ZXP(out) = 1.f - z * z; } else if (phase < 3.f) { float z = phase - 2.f; ZXP(out) = z * z - 1.f; } else { phase -= 4.f; float z = phase; ZXP(out) = 1.f - z * z; } phase += freq;); unit->mPhase = phase; } void LFPar_Ctor(LFPar* unit) { if (INRATE(0) == calc_FullRate) SETCALC(LFPar_next_a); else SETCALC(LFPar_next_k); unit->mFreqMul = 4.0 * unit->mRate->mSampleDur; double initPhase = unit->mPhase = ZIN0(1); LFPar_next_k(unit, 1); unit->mPhase = initPhase; } ////////////////////////////////////////////////////////////////////////////////////////////////// void LFCub_next_a(LFCub* unit, int inNumSamples) { float* out = ZOUT(0); float* freq = ZIN(0); float freqmul = unit->mFreqMul; double phase = unit->mPhase; LOOP1( inNumSamples, float z; if (phase < 1.f) { z = phase; } else if (phase < 2.f) { z = 2.f - phase; } else { phase -= 2.f; z = phase; } float phaseadd = ZXP(freq); phase += phaseadd * freqmul; ZXP(out) = z * z * (6.f - 4.f * z) - 1.f;); unit->mPhase = phase; } void LFCub_next_k(LFCub* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0) * unit->mFreqMul; double phase = unit->mPhase; LOOP1( inNumSamples, float z; if (phase < 1.f) { z = phase; } else if (phase < 2.f) { z = 2.f - phase; } else { phase -= 2.f; z = phase; } ZXP(out) = z * z * (6.f - 4.f * z) - 1.f; phase += freq;); unit->mPhase = phase; } void LFCub_Ctor(LFCub* unit) { if (INRATE(0) == calc_FullRate) SETCALC(LFCub_next_a); else SETCALC(LFCub_next_k); unit->mFreqMul = 2.0 * unit->mRate->mSampleDur; double initPhase = unit->mPhase = ZIN0(1) + 0.5; LFCub_next_k(unit, 1); unit->mPhase = initPhase; } ////////////////////////////////////////////////////////////////////////////////////////////////// void LFTri_next_a(LFTri* unit, int inNumSamples) { float* out = ZOUT(0); float* freq = ZIN(0); float freqmul = unit->mFreqMul; double phase = unit->mPhase; LOOP1(inNumSamples, float z = phase > 1.f ? 2.f - phase : phase; phase += ZXP(freq) * freqmul; if (phase >= 3.f) phase -= 4.f; ZXP(out) = z;); unit->mPhase = phase; } void LFTri_next_k(LFTri* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0) * unit->mFreqMul; double phase = unit->mPhase; LOOP1(inNumSamples, float z = phase > 1.f ? 2.f - phase : phase; phase += freq; if (phase >= 3.f) phase -= 4.f; ZXP(out) = z;); unit->mPhase = phase; } void LFTri_Ctor(LFTri* unit) { if (INRATE(0) == calc_FullRate) { SETCALC(LFTri_next_a); } else { SETCALC(LFTri_next_k); } unit->mFreqMul = 4.0 * unit->mRate->mSampleDur; double initPhase = unit->mPhase = sc_wrap(static_cast<double>(ZIN0(1)), 0.0, 4.0); LFTri_next_k(unit, 1); unit->mPhase = initPhase; } ////////////////////////////////////////////////////////////////////////////////////////////////// void LFGauss_next_k(LFGauss* unit, int inNumSamples) { float* out = ZOUT(0); float dur = ZIN0(0); float c = ZIN0(1); float b = ZIN0(2); float loop = ZIN0(3); // offset phase by b double x = unit->mPhase - b; // for a full cycle from -1 to 1 in duration, double the step. float step = 2.f / (dur * unit->mRate->mSampleRate); // calculate exponent only once per loop float factor = -1.f / (2.f * c * c); LOOP1( inNumSamples, if (x > 1.f) { if (loop) { x -= 2.f; } else { DoneAction(ZIN0(4), unit); } } ZXP(out) = exp(x * x * factor); x += step;); unit->mPhase = x + b; } void LFGauss_next_a(LFGauss* unit, int inNumSamples) { float* out = ZOUT(0); float* dur = ZIN(0); float c = ZIN0(1); float b = ZIN0(2); float loop = ZIN0(3); float sr = unit->mRate->mSampleRate; // offset phase by b double x = unit->mPhase - b; float factor = -1.f / (2.f * c * c); LOOP1( inNumSamples, if (x > 1.f) { if (loop) { x -= 2.f; } else { DoneAction(ZIN0(4), unit); } } // for a full cycle from -1 to 1 in duration, double the step. float step = 2.f / (ZXP(dur) * sr); ZXP(out) = exp(x * x * factor); x += step;); unit->mPhase = x + b; } void LFGauss_next_aa(LFGauss* unit, int inNumSamples) { float* out = ZOUT(0); float* dur = ZIN(0); float* c = ZIN(1); float b = ZIN0(2); float loop = ZIN0(3); float sr = unit->mRate->mSampleRate; // offset phase by b double x = unit->mPhase - b; LOOP1( inNumSamples, if (x > 1.f) { if (loop) { x -= 2.f; } else { DoneAction(ZIN0(4), unit); } } // for a full cycle from -1 to 1 in duration, double the step. float step = 2.f / (ZXP(dur) * sr); float cval = ZXP(c); float factor = -1.f / (2.f * cval * cval); ZXP(out) = exp(x * x * factor); x += step;); unit->mPhase = x + b; } void LFGauss_Ctor(LFGauss* unit) { if (INRATE(0) == calc_FullRate) { if (INRATE(1) == calc_FullRate) { SETCALC(LFGauss_next_aa); } else { SETCALC(LFGauss_next_a); } } else { SETCALC(LFGauss_next_k); } unit->mPhase = -1.0; LFGauss_next_k(unit, 1); // reset phase unit->mPhase = -1.0; } ////////////////////////////////////////////////////////////////////////////////////////////////// // detect if phasor is out-of-bounds, trigger and wrap [0, 1] static inline float Impulse_testWrapPhase(double prev_inc, double& phase) { if (prev_inc < 0.f) { // negative freqs if (phase <= 0.f) { phase += 1.f; if (phase <= 0.f) { // catch large phase jumps phase -= sc_ceil(phase); } return 1.f; } else { return 0.f; } } else { // positive freqs if (phase >= 1.f) { phase -= 1.f; if (phase >= 1.f) { phase -= sc_floor(phase); } return 1.f; } else { return 0.f; } } } void Impulse_next_ii(Impulse* unit, int inNumSamples) { float* out = ZOUT(0); double phase = unit->mPhase; double inc = unit->mPhaseIncrement; LOOP1(inNumSamples, ZXP(out) = Impulse_testWrapPhase(inc, phase); phase += inc;); unit->mPhase = phase; } void Impulse_next_ik(Impulse* unit, int inNumSamples) { float* out = ZOUT(0); double phase = unit->mPhase; double inc = unit->mPhaseIncrement; double prev_off = unit->mPhaseOffset; double off = ZIN0(1); double phaseSlope = CALCSLOPE(off, prev_off); bool phOffChanged = phaseSlope != 0.f; LOOP1( inNumSamples, ZXP(out) = Impulse_testWrapPhase(inc, phase); if (phOffChanged) { phase += phaseSlope; Impulse_testWrapPhase(inc, phase); } phase += inc;); unit->mPhase = phase; unit->mPhaseOffset = off; } void Impulse_next_ki(Impulse* unit, int inNumSamples) { float* out = ZOUT(0); double phase = unit->mPhase; double prev_inc = unit->mPhaseIncrement; double inc = ZIN0(0) * unit->mFreqMul; double incSlope = CALCSLOPE(inc, prev_inc); LOOP1(inNumSamples, ZXP(out) = Impulse_testWrapPhase(prev_inc, phase); prev_inc += incSlope; phase += prev_inc;); unit->mPhase = phase; unit->mPhaseIncrement = inc; } void Impulse_next_kk(Impulse* unit, int inNumSamples) { float* out = ZOUT(0); double phase = unit->mPhase; double prev_inc = unit->mPhaseIncrement; double inc = ZIN0(0) * unit->mFreqMul; double incSlope = CALCSLOPE(inc, prev_inc); double prev_off = unit->mPhaseOffset; double off = ZIN0(1); double phaseSlope = CALCSLOPE(off, prev_off); bool phOffChanged = phaseSlope != 0.f; LOOP1( inNumSamples, ZXP(out) = Impulse_testWrapPhase(prev_inc, phase); if (phOffChanged) { phase += phaseSlope; Impulse_testWrapPhase(prev_inc, phase); } prev_inc += incSlope; phase += prev_inc;); unit->mPhase = phase; unit->mPhaseOffset = off; unit->mPhaseIncrement = inc; } void Impulse_next_ak(Impulse* unit, int inNumSamples) { float* out = ZOUT(0); double phase = unit->mPhase; double inc = unit->mPhaseIncrement; float* freqIn = ZIN(0); float freqMul = unit->mFreqMul; double prev_off = unit->mPhaseOffset; double off = ZIN0(1); double offSlope = CALCSLOPE(off, prev_off); bool offChanged = offSlope != 0.f; LOOP1( inNumSamples, float z = Impulse_testWrapPhase(inc, phase); if (offChanged) { phase += offSlope; Impulse_testWrapPhase(inc, phase); } inc = ZXP(freqIn) * freqMul; ZXP(out) = z; phase += inc;); unit->mPhase = phase; unit->mPhaseOffset = off; unit->mPhaseIncrement = inc; } void Impulse_next_aa(Impulse* unit, int inNumSamples) { float* out = ZOUT(0); double phase = unit->mPhase; double inc = unit->mPhaseIncrement; float* freqin = ZIN(0); float freqmul = unit->mFreqMul; double prev_off = unit->mPhaseOffset; float* offIn = ZIN(1); LOOP1(inNumSamples, float z = Impulse_testWrapPhase(inc, phase); float off = ZXP(offIn); float offInc = off - prev_off; phase += offInc; Impulse_testWrapPhase(inc, phase); inc = ZXP(freqin) * freqmul; ZXP(out) = z; phase += inc; prev_off = off;); unit->mPhase = phase; unit->mPhaseOffset = prev_off; unit->mPhaseIncrement = inc; } void Impulse_next_ai(Impulse* unit, int inNumSamples) { float* out = ZOUT(0); double phase = unit->mPhase; double inc = unit->mPhaseIncrement; float* freqin = ZIN(0); float freqmul = unit->mFreqMul; LOOP1(inNumSamples, float z = Impulse_testWrapPhase(inc, phase); inc = ZXP(freqin) * freqmul; ZXP(out) = z; phase += inc;); unit->mPhase = phase; unit->mPhaseIncrement = inc; } // Impulse is based on a wrapping phasor. When the phase wraps, an impulse is // output. Phase _increments_ according to its frequency and an additional phase // _offset_ is applied. // Order of operations: // 1. Phase _offset_ is applied to the current phase (if offset has changed). // 2. Phase is wrapped into range. // 3. Phase _increment_ is added (according to the frequency). // 4. Phase is checked for being out of range, in which case a trigger is fired // and the phase is again wrapped. // Therefore, phase increment (freq) triggers an impulse, but not phase offset. void Impulse_Ctor(Impulse* unit) { unit->mPhaseOffset = ZIN0(1); unit->mFreqMul = unit->mRate->mSampleDur; unit->mPhaseIncrement = ZIN0(0) * unit->mFreqMul; double initOff = unit->mPhaseOffset; double initInc = unit->mPhaseIncrement; double initPhase = sc_wrap(initOff, 0.0, 1.0); // Initial phase offset of 0 means output of 1 on first sample. // Set phase to wrap point to trigger impulse on first sample if (initPhase == 0.0 && initInc >= 0.0) { initPhase = 1.0; // positive frequency trigger/wrap position } unit->mPhase = initPhase; UnitCalcFunc func; switch (INRATE(0)) { case calc_FullRate: switch (INRATE(1)) { case calc_ScalarRate: func = (UnitCalcFunc)Impulse_next_ai; break; case calc_BufRate: func = (UnitCalcFunc)Impulse_next_ak; break; case calc_FullRate: func = (UnitCalcFunc)Impulse_next_aa; break; } break; case calc_BufRate: if (INRATE(1) == calc_ScalarRate) { func = (UnitCalcFunc)Impulse_next_ki; } else { func = (UnitCalcFunc)Impulse_next_kk; } break; case calc_ScalarRate: if (INRATE(1) == calc_ScalarRate) { func = (UnitCalcFunc)Impulse_next_ii; } else { func = (UnitCalcFunc)Impulse_next_ik; } break; } unit->mCalcFunc = func; func(unit, 1); unit->mPhase = initPhase; unit->mPhaseOffset = initOff; unit->mPhaseIncrement = initInc; } ////////////////////////////////////////////////////////////////////////////////////////////////// void VarSaw_next_a(VarSaw* unit, int inNumSamples) { float* out = ZOUT(0); float* freq = ZIN(0); float nextDuty = ZIN0(2); float duty = unit->mDuty; float invduty = unit->mInvDuty; float inv1duty = unit->mInv1Duty; float freqmul = unit->mFreqMul; double phase = unit->mPhase; LOOP1( inNumSamples, if (phase >= 1.f) { phase -= 1.f; duty = unit->mDuty = sc_clip(nextDuty, 0.001, 0.999); invduty = unit->mInvDuty = 2.f / duty; inv1duty = unit->mInv1Duty = 2.f / (1.f - duty); } float z = phase < duty ? phase * invduty : (1.f - phase) * inv1duty; phase += ZXP(freq) * freqmul; ZXP(out) = z - 1.f;); unit->mPhase = phase; } void VarSaw_next_k(VarSaw* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0) * unit->mFreqMul; float nextDuty = ZIN0(2); float duty = unit->mDuty; float invduty = unit->mInvDuty; float inv1duty = unit->mInv1Duty; double phase = unit->mPhase; LOOP1( inNumSamples, if (phase >= 1.f) { phase -= 1.f; duty = unit->mDuty = sc_clip(nextDuty, 0.001, 0.999); invduty = unit->mInvDuty = 2.f / duty; inv1duty = unit->mInv1Duty = 2.f / (1.f - duty); } float z = phase < duty ? phase * invduty : (1.f - phase) * inv1duty; phase += freq; ZXP(out) = z - 1.f;); unit->mPhase = phase; } void VarSaw_Ctor(VarSaw* unit) { if (INRATE(0) == calc_FullRate) { SETCALC(VarSaw_next_a); } else { SETCALC(VarSaw_next_k); } unit->mFreqMul = unit->mRate->mSampleDur; unit->mPhase = ZIN0(1); float duty = ZIN0(2); duty = unit->mDuty = sc_clip(duty, 0.001, 0.999); unit->mInvDuty = 2.f / duty; unit->mInv1Duty = 2.f / (1.f - duty); ZOUT0(0) = 0.f; } ////////////////////////////////////////////////////////////////////////////////////////////////// void SyncSaw_next_aa(SyncSaw* unit, int inNumSamples) { float freqmul = unit->mFreqMul; float* out = ZOUT(0); float* freq1 = ZIN(0); float* freq2 = ZIN(1); double phase1 = unit->mPhase1; double phase2 = unit->mPhase2; LOOP1( inNumSamples, float freq1x = ZXP(freq1) * freqmul; float freq2x = ZXP(freq2) * freqmul; float z = phase2; phase2 += freq2x; if (phase2 >= 1.f) phase2 -= 2.f; phase1 += freq1x; if (phase1 >= 1.f) { phase1 -= 2.f; phase2 = (phase1 + 1.f) * freq2x / freq1x - 1.f; } ZXP(out) = z;); unit->mPhase1 = phase1; unit->mPhase2 = phase2; } void SyncSaw_next_ak(SyncSaw* unit, int inNumSamples) { float freqmul = unit->mFreqMul; float* out = ZOUT(0); float* freq1 = ZIN(0); float freq2x = ZIN0(1) * freqmul; double phase1 = unit->mPhase1; double phase2 = unit->mPhase2; LOOP1( inNumSamples, float freq1x = ZXP(freq1) * freqmul; float z = phase2; phase2 += freq2x; if (phase2 >= 1.f) phase2 -= 2.f; phase1 += freq1x; if (phase1 >= 1.f) { phase1 -= 2.f; phase2 = (phase1 + 1.f) * freq2x / freq1x - 1.f; } ZXP(out) = z;); unit->mPhase1 = phase1; unit->mPhase2 = phase2; } void SyncSaw_next_ka(SyncSaw* unit, int inNumSamples) { float freqmul = unit->mFreqMul; float* out = ZOUT(0); float freq1x = ZIN0(0) * freqmul; float* freq2 = ZIN(1); double phase1 = unit->mPhase1; double phase2 = unit->mPhase2; LOOP1( inNumSamples, float freq2x = ZXP(freq2) * freqmul; float z = phase2; phase2 += freq2x; if (phase2 >= 1.f) phase2 -= 2.f; phase1 += freq1x; if (phase1 >= 1.f) { phase1 -= 2.f; phase2 = (phase1 + 1.f) * freq2x / freq1x - 1.f; } ZXP(out) = z;); unit->mPhase1 = phase1; unit->mPhase2 = phase2; } void SyncSaw_next_kk(SyncSaw* unit, int inNumSamples) { float* out = ZOUT(0); float freq1x = ZIN0(0) * unit->mFreqMul; float freq2x = ZIN0(1) * unit->mFreqMul; double phase1 = unit->mPhase1; double phase2 = unit->mPhase2; LOOP1( inNumSamples, float z = phase2; phase2 += freq2x; if (phase2 >= 1.f) phase2 -= 2.f; phase1 += freq1x; if (phase1 >= 1.f) { phase1 -= 2.f; phase2 = (phase1 + 1.f) * freq2x / freq1x - 1.f; } ZXP(out) = z;); unit->mPhase1 = phase1; unit->mPhase2 = phase2; } void SyncSaw_Ctor(SyncSaw* unit) { if (INRATE(0) == calc_FullRate) { if (INRATE(1) == calc_FullRate) { SETCALC(SyncSaw_next_aa); } else { SETCALC(SyncSaw_next_ak); } } else { if (INRATE(1) == calc_FullRate) { SETCALC(SyncSaw_next_ka); } else { SETCALC(SyncSaw_next_kk); } } unit->mFreqMul = 2.0 * unit->mRate->mSampleDur; unit->mPhase1 = 0.; unit->mPhase2 = 0.; SyncSaw_next_kk(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// struct K2A : SIMD_Unit { ControlRateInput<0> mLevel; K2A(void) { mLevel.init(this); if (inRate(0) == calc_ScalarRate) set_unrolled_calc_function<K2A, &K2A::next_i<unrolled_64>, &K2A::next_i<unrolled>, &K2A::next_i<scalar>>(); else set_unrolled_calc_function<K2A, &K2A::next_k<unrolled_64>, &K2A::next_k<unrolled>, &K2A::next_k<scalar>>(); } template <int type> void next_k(int inNumSamples) { if (mLevel.changed(this)) slope_vec<type>(out(0), mLevel.slope(this), inNumSamples); else next_i<type>(inNumSamples); } template <int type> void next_i(int inNumSamples) { set_vec<type>(out(0), mLevel, inNumSamples); } }; ////////////////////////////////////////////////////////////////////////////////////////////////// void A2K_next(A2K* unit, int inNumSamples) { ZOUT0(0) = ZIN0(0); // return first sample in block } void A2K_Ctor(A2K* unit) { SETCALC(A2K_next); A2K_next(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// void T2K_next(T2K* unit, int inNumSamples) { float out = 0.f, val; float* in = ZIN(0); int n = unit->mWorld->mBufLength; LOOP1(n, val = ZXP(in); if (val > out) out = val;); ZOUT0(0) = out; } void T2K_Ctor(T2K* unit) { SETCALC(T2K_next); ZOUT0(0) = ZIN0(0); } ////////////////////////////////////////////////////////////////////////////////////////////////// static inline void T2A_write_trigger(T2A* unit, float level) { float* out = OUT(0); int offset = (int)IN0(1); out[offset] = level; } void T2A_next(T2A* unit, int inNumSamples) { float level = IN0(0); ZClear(inNumSamples, ZOUT(0)); if ((unit->mLevel <= 0.f && level > 0.f)) T2A_write_trigger(unit, level); unit->mLevel = level; } #ifdef NOVA_SIMD FLATTEN void T2A_next_nova(T2A* unit, int inNumSamples) { float level = IN0(0); nova::zerovec_simd(OUT(0), inNumSamples); if ((unit->mLevel <= 0.f && level > 0.f)) T2A_write_trigger(unit, level); unit->mLevel = level; } FLATTEN void T2A_next_nova_64(T2A* unit, int inNumSamples) { float level = IN0(0); nova::zerovec_simd<64>(OUT(0)); if ((unit->mLevel <= 0.f && level > 0.f)) T2A_write_trigger(unit, level); unit->mLevel = level; } #endif void T2A_Ctor(T2A* unit) { #ifdef NOVA_SIMD if (BUFLENGTH == 64) SETCALC(T2A_next_nova_64); else if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(T2A_next_nova); else #endif SETCALC(T2A_next); T2A_next(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// struct DC : SIMD_Unit { float value; DC(void) { value = in0(0); if (value == 0) set_unrolled_calc_function<DC, &DC::next_i<unrolled_64, true>, &DC::next_i<unrolled, true>, &DC::next_i<scalar, true>>(); else set_unrolled_calc_function<DC, &DC::next_i<unrolled_64, false>, &DC::next_i<unrolled, false>, &DC::next_i<scalar, false>>(); } template <int type, bool isZero> void next_i(int inNumSamples) { if (isZero) zero_vec<type>(out(0), inNumSamples); else set_vec<type>(out(0), value, inNumSamples); } }; ////////////////////////////////////////////////////////////////////////////////////////////////// static inline void Line_next_loop(Line* unit, int& counter, int remain, double& level) { float* out = ZOUT(0); double slope = unit->mSlope; do { if (counter == 0) { int nsmps = remain; remain = 0; float endlevel = unit->mEndLevel; LOOP(nsmps, ZXP(out) = endlevel;); } else { int nsmps = sc_min(remain, counter); counter -= nsmps; remain -= nsmps; LOOP(nsmps, ZXP(out) = level; level += slope;); if (counter == 0) { unit->mDone = true; int doneAction = (int)ZIN0(3); DoneAction(doneAction, unit); } } } while (remain); } void Line_next(Line* unit, int inNumSamples) { double level = unit->mLevel; int counter = unit->mCounter; Line_next_loop(unit, counter, inNumSamples, level); unit->mCounter = counter; unit->mLevel = level; } #ifdef NOVA_SIMD FLATTEN void Line_next_nova(Line* unit, int inNumSamples) { double level = unit->mLevel; int counter = unit->mCounter; if (counter == 0) { nova::setvec_simd(OUT(0), unit->mEndLevel, inNumSamples); return; } if (counter > inNumSamples) { double slope = unit->mSlope; nova::set_slope_vec_simd(OUT(0), (float)level, (float)slope, inNumSamples); unit->mLevel = level + inNumSamples * slope; unit->mCounter = counter - inNumSamples; return; } Line_next_loop(unit, counter, inNumSamples, level); unit->mCounter = counter; unit->mLevel = level; } FLATTEN void Line_next_nova_64(Line* unit, int inNumSamples) { double level = unit->mLevel; int counter = unit->mCounter; if (counter == 0) { nova::setvec_simd<64>(OUT(0), unit->mEndLevel); return; } if (counter > inNumSamples) { double slope = unit->mSlope; nova::set_slope_vec_simd(OUT(0), (float)level, (float)slope, 64); unit->mLevel = level + inNumSamples * slope; unit->mCounter = counter - inNumSamples; return; } Line_next_loop(unit, counter, inNumSamples, level); unit->mCounter = counter; unit->mLevel = level; } #endif void Line_Ctor(Line* unit) { #ifdef NOVA_SIMD if (BUFLENGTH == 64) SETCALC(Line_next_nova_64); else if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(Line_next_nova); else #endif SETCALC(Line_next); double start = ZIN0(0); double end = ZIN0(1); double dur = ZIN0(2); int counter = (int)(dur * unit->mRate->mSampleRate + .5f); unit->mCounter = sc_max(1, counter); if (counter == 0) { unit->mLevel = end; unit->mSlope = 0.; } else { unit->mLevel = start; unit->mSlope = (end - start) / unit->mCounter; } unit->mEndLevel = end; ZOUT0(0) = unit->mLevel; } ////////////////////////////////////////////////////////////////////////////////////////////////// static inline void Xline_next_loop(XLine* unit, int& counter, int remain, double& level) { float* out = ZOUT(0); double grow = unit->mGrowth; do { if (counter == 0) { int nsmps = remain; remain = 0; LOOP(nsmps, ZXP(out) = level;); } else { int nsmps = sc_min(remain, counter); counter -= nsmps; remain -= nsmps; LOOP(nsmps, ZXP(out) = level; level *= grow;); if (counter == 0) { level = unit->mEndLevel; unit->mDone = true; int doneAction = (int)ZIN0(3); DoneAction(doneAction, unit); } } } while (remain); } void XLine_next(XLine* unit, int inNumSamples) { double level = unit->mLevel; int counter = unit->mCounter; Xline_next_loop(unit, counter, inNumSamples, level); unit->mCounter = counter; unit->mLevel = level; } #ifdef NOVA_SIMD FLATTEN void XLine_next_nova(XLine* unit, int inNumSamples) { double level = unit->mLevel; int counter = unit->mCounter; if (counter == 0) { nova::setvec_simd(OUT(0), (float)level, inNumSamples); return; } if (counter > inNumSamples) { double grow = unit->mGrowth; nova::set_exp_vec_simd(OUT(0), (float)level, (float)grow, inNumSamples); level *= sc_powi(grow, inNumSamples); counter -= inNumSamples; } else Xline_next_loop(unit, counter, inNumSamples, level); unit->mCounter = counter; unit->mLevel = level; } FLATTEN void XLine_next_nova_64(XLine* unit, int inNumSamples) { double level = unit->mLevel; int counter = unit->mCounter; if (counter == 0) { nova::setvec_simd<64>(OUT(0), (float)level); return; } if (counter > 64) { double grow = unit->mGrowth; nova::set_exp_vec_simd(OUT(0), (float)level, (float)grow, 64); level *= sc_powi(grow, inNumSamples); counter -= inNumSamples; } else Xline_next_loop(unit, counter, inNumSamples, level); unit->mCounter = counter; unit->mLevel = level; } #endif void XLine_Ctor(XLine* unit) { #ifdef NOVA_SIMD if (BUFLENGTH == 64) SETCALC(XLine_next_nova_64); else if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(XLine_next_nova); else #endif SETCALC(XLine_next); double start = ZIN0(0); double end = ZIN0(1); double dur = ZIN0(2); int counter = (int)(dur * unit->mRate->mSampleRate + .5f); unit->mEndLevel = end; if (counter == 0) { ZOUT0(0) = end; unit->mLevel = end; unit->mCounter = 0; unit->mGrowth = 0; } else { ZOUT0(0) = start; unit->mCounter = counter; unit->mGrowth = pow(end / start, 1.0 / counter); unit->mLevel = start; } } ////////////////////////////////////////////////////////////////////////////////////////////////// /* void Wrap_next(Wrap* unit, int inNumSamples) { float *out = ZOUT(0); float *in = ZIN(0); float lo = unit->m_lo; float hi = unit->m_hi; float range = unit->m_range; LOOP1(inNumSamples, ZXP(out) = sc_wrap(ZXP(in), lo, hi, range); ); } void Wrap_Ctor(Wrap* unit) { SETCALC(Wrap_next); unit->m_lo = ZIN0(1); unit->m_hi = ZIN0(2); if (unit->m_lo > unit->m_hi) { float temp = unit->m_lo; unit->m_lo = unit->m_hi; unit->m_hi = temp; } unit->m_range = unit->m_hi - unit->m_lo; Wrap_next(unit, 1); } */ void Wrap_next_kk(Wrap* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float next_lo = ZIN0(1); float next_hi = ZIN0(2); float lo = unit->m_lo; float lo_slope = CALCSLOPE(next_lo, lo); float hi = unit->m_hi; float hi_slope = CALCSLOPE(next_hi, hi); LOOP1(inNumSamples, float range = hi - lo; ZXP(out) = sc_wrap(ZXP(in), lo, hi, range); lo += lo_slope; hi += hi_slope;); unit->m_lo = lo; unit->m_hi = hi; } void Wrap_next_ka(Wrap* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float next_lo = ZIN0(1); float* hi = ZIN(2); float lo = unit->m_lo; float lo_slope = CALCSLOPE(next_lo, lo); LOOP1(inNumSamples, float curhi = ZXP(hi); ZXP(out) = sc_wrap(ZXP(in), lo, curhi, curhi - lo); lo += lo_slope;); unit->m_lo = lo; } void Wrap_next_ak(Wrap* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* lo = ZIN(1); float next_hi = ZIN0(2); float hi = unit->m_hi; float hi_slope = CALCSLOPE(next_hi, hi); LOOP1(inNumSamples, float curlo = ZXP(lo); ZXP(out) = sc_wrap(ZXP(in), curlo, hi, hi - curlo); hi += hi_slope;); unit->m_hi = hi; } void Wrap_next_aa(Wrap* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* lo = ZIN(1); float* hi = ZIN(2); LOOP1(inNumSamples, float curhi = ZXP(hi); float curlo = ZXP(lo); ZXP(out) = sc_wrap(ZXP(in), curlo, curhi, curhi - curlo);); } void Wrap_Ctor(Wrap* unit) { if (BUFLENGTH == 1) { // _aa? Well, yes - that calc func doesn't interpolate // and interpolation is not needed for kr (1 sample/block) SETCALC(Wrap_next_aa); } else { if (INRATE(1) == calc_FullRate) { if (INRATE(2) == calc_FullRate) SETCALC(Wrap_next_aa); else SETCALC(Wrap_next_ak); } else { if (INRATE(2) == calc_FullRate) SETCALC(Wrap_next_ka); else SETCALC(Wrap_next_kk); } } unit->m_lo = ZIN0(1); unit->m_hi = ZIN0(2); Wrap_next_kk(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// /* void Fold_next(Fold* unit, int inNumSamples) { float *out = ZOUT(0); float *in = ZIN(0); float lo = unit->m_lo; float hi = unit->m_hi; float range = unit->m_range; float range2 = unit->m_range2; LOOP1(inNumSamples, ZXP(out) = sc_fold(ZXP(in), lo, hi, range, range2); ); } void Fold_Ctor(Fold* unit) { SETCALC(Fold_next); unit->m_lo = ZIN0(1); unit->m_hi = ZIN0(2); if (unit->m_lo > unit->m_hi) { float temp = unit->m_lo; unit->m_lo = unit->m_hi; unit->m_hi = temp; } unit->m_range = unit->m_hi - unit->m_lo; unit->m_range2 = 2.f * unit->m_range; Fold_next(unit, 1); } */ void Fold_next_kk(Fold* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float next_lo = ZIN0(1); float next_hi = ZIN0(2); float lo = unit->m_lo; float lo_slope = CALCSLOPE(next_lo, lo); float hi = unit->m_hi; float hi_slope = CALCSLOPE(next_hi, hi); LOOP1(inNumSamples, float range = hi - lo; float range2 = range * 2.f; ZXP(out) = sc_fold(ZXP(in), lo, hi, range, range2); lo += lo_slope; hi += hi_slope;); unit->m_lo = lo; unit->m_hi = hi; } void Fold_next_ka(Fold* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float next_lo = ZIN0(1); float* hi = ZIN(2); float lo = unit->m_lo; float lo_slope = CALCSLOPE(next_lo, lo); LOOP1(inNumSamples, float curhi = ZXP(hi); float range = curhi - lo; float range2 = range * 2.f; ZXP(out) = sc_fold(ZXP(in), lo, curhi, range, range2); lo += lo_slope;); unit->m_lo = lo; } void Fold_next_ak(Fold* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* lo = ZIN(1); float next_hi = ZIN0(2); float hi = unit->m_hi; float hi_slope = CALCSLOPE(next_hi, hi); LOOP1(inNumSamples, float curlo = ZXP(lo); float range = hi - curlo; float range2 = range * 2.f; ZXP(out) = sc_fold(ZXP(in), curlo, hi, range, range2); hi += hi_slope;); unit->m_hi = hi; } void Fold_next_aa(Fold* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* lo = ZIN(1); float* hi = ZIN(2); LOOP1(inNumSamples, float curhi = ZXP(hi); float curlo = ZXP(lo); float range = curhi - curlo; float range2 = range * 2.0; ZXP(out) = sc_fold(ZXP(in), curlo, curhi, range, range2);); } void Fold_Ctor(Fold* unit) { if (BUFLENGTH == 1) { // _aa? Well, yes - that calc func doesn't interpolate // and interpolation is not needed for kr (1 sample/block) SETCALC(Fold_next_aa); } else { if (INRATE(1) == calc_FullRate) { if (INRATE(2) == calc_FullRate) SETCALC(Fold_next_aa); else SETCALC(Fold_next_ak); } else { if (INRATE(2) == calc_FullRate) SETCALC(Fold_next_ka); else SETCALC(Fold_next_kk); } } unit->m_lo = ZIN0(1); unit->m_hi = ZIN0(2); Fold_next_kk(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// void Clip_next_ii(Clip* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float lo = unit->m_lo; float hi = unit->m_hi; LOOP1(inNumSamples, ZXP(out) = sc_clip(ZXP(in), lo, hi);); } void Clip_next_kk(Clip* unit, int inNumSamples) { float next_lo = ZIN0(1); float next_hi = ZIN0(2); float lo = unit->m_lo; float hi = unit->m_hi; if (lo == next_lo && hi == next_hi) { Clip_next_ii(unit, inNumSamples); return; } float* out = ZOUT(0); float* in = ZIN(0); float lo_slope = CALCSLOPE(next_lo, lo); float hi_slope = CALCSLOPE(next_hi, hi); LOOP1(inNumSamples, ZXP(out) = sc_clip(ZXP(in), lo, hi); lo += lo_slope; hi += hi_slope;); unit->m_lo = lo; unit->m_hi = hi; } void Clip_next_ka(Clip* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float next_lo = ZIN0(1); float* hi = ZIN(2); float lo = unit->m_lo; float lo_slope = CALCSLOPE(next_lo, lo); LOOP1(inNumSamples, ZXP(out) = sc_clip(ZXP(in), lo, ZXP(hi)); lo += lo_slope;); unit->m_lo = lo; } void Clip_next_ak(Clip* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* lo = ZIN(1); float next_hi = ZIN0(2); float hi = unit->m_hi; float hi_slope = CALCSLOPE(next_hi, hi); LOOP1(inNumSamples, ZXP(out) = sc_clip(ZXP(in), ZXP(lo), hi); hi += hi_slope;); unit->m_hi = hi; } void Clip_next_aa(Clip* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* lo = ZIN(1); float* hi = ZIN(2); LOOP1(inNumSamples, ZXP(out) = sc_clip(ZXP(in), ZXP(lo), ZXP(hi));); } void Clip_next_k(Clip* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float lo = ZIN0(1); float hi = ZIN0(2); ZXP(out) = sc_clip(ZXP(in), lo, hi); } #ifdef NOVA_SIMD void Clip_next_nova_ii(Clip* unit, int inNumSamples) { float lo = unit->m_lo; float hi = unit->m_hi; nova::clip_vec_simd(OUT(0), IN(0), lo, hi, inNumSamples); } void Clip_next_nova_ki(Clip* unit, int inNumSamples) { float next_lo = ZIN0(1); float lo = unit->m_lo; float hi = unit->m_hi; if (lo == next_lo) { Clip_next_nova_ii(unit, inNumSamples); return; } float lo_slope = CALCSLOPE(next_lo, lo); nova::clip_vec_simd(OUT(0), IN(0), slope_argument(lo, lo_slope), hi, inNumSamples); unit->m_lo = next_lo; } void Clip_next_nova_ik(Clip* unit, int inNumSamples) { float next_hi = ZIN0(2); float lo = unit->m_lo; float hi = unit->m_hi; if (hi == next_hi) { Clip_next_nova_ii(unit, inNumSamples); return; } float hi_slope = CALCSLOPE(next_hi, hi); nova::clip_vec_simd(OUT(0), IN(0), lo, slope_argument(hi, hi_slope), inNumSamples); unit->m_hi = next_hi; } void Clip_next_nova_kk(Clip* unit, int inNumSamples) { float next_lo = ZIN0(1); float next_hi = ZIN0(2); float lo = unit->m_lo; float hi = unit->m_hi; if (lo == next_lo && hi == next_hi) { Clip_next_nova_ii(unit, inNumSamples); return; } if (lo == next_lo) { Clip_next_nova_ik(unit, inNumSamples); return; } if (hi == next_hi) { Clip_next_nova_ki(unit, inNumSamples); return; } float lo_slope = CALCSLOPE(next_lo, lo); float hi_slope = CALCSLOPE(next_hi, hi); nova::clip_vec_simd(OUT(0), IN(0), slope_argument(lo, lo_slope), slope_argument(hi, hi_slope), inNumSamples); unit->m_lo = next_lo; unit->m_hi = next_hi; } void Clip_next_nova_ai(Clip* unit, int inNumSamples) { float hi = unit->m_hi; nova::clip_vec_simd(OUT(0), IN(0), IN(1), hi, inNumSamples); } void Clip_next_nova_ak(Clip* unit, int inNumSamples) { float next_hi = ZIN0(2); float hi = unit->m_hi; if (hi == next_hi) { Clip_next_nova_ai(unit, inNumSamples); return; } float hi_slope = CALCSLOPE(next_hi, hi); nova::clip_vec_simd(OUT(0), IN(0), IN(1), slope_argument(hi, hi_slope), inNumSamples); unit->m_hi = next_hi; } void Clip_next_nova_ia(Clip* unit, int inNumSamples) { float lo = unit->m_lo; nova::clip_vec_simd(OUT(0), IN(0), lo, IN(2), inNumSamples); } void Clip_next_nova_ka(Clip* unit, int inNumSamples) { float next_lo = ZIN0(1); float lo = unit->m_lo; if (lo == next_lo) { Clip_next_nova_ia(unit, inNumSamples); return; } float lo_slope = CALCSLOPE(next_lo, lo); nova::clip_vec_simd(OUT(0), IN(0), slope_argument(lo, lo_slope), IN(2), inNumSamples); unit->m_lo = next_lo; } void Clip_next_nova_aa(Clip* unit, int inNumSamples) { nova::clip_vec_simd(OUT(0), IN(0), IN(1), IN(2), inNumSamples); } #endif typedef void (*ClipCalcFunc)(Clip*, int); static ClipCalcFunc Clip_SelectCalc(Clip* unit) { if (BUFLENGTH == 1) return Clip_next_k; int loRate = INRATE(1); int hiRate = INRATE(2); #ifdef NOVA_SIMD if (boost::alignment::is_aligned(BUFLENGTH, 16)) { switch (loRate) { case calc_FullRate: switch (hiRate) { case calc_FullRate: return Clip_next_nova_aa; case calc_BufRate: return Clip_next_nova_ak; case calc_ScalarRate: return Clip_next_nova_ai; } break; case calc_BufRate: switch (hiRate) { case calc_FullRate: return Clip_next_nova_ka; case calc_BufRate: return Clip_next_nova_kk; case calc_ScalarRate: return Clip_next_nova_ki; } break; case calc_ScalarRate: switch (hiRate) { case calc_FullRate: return Clip_next_nova_ia; case calc_BufRate: return Clip_next_nova_ik; case calc_ScalarRate: return Clip_next_nova_ii; } break; } } #endif if (loRate == calc_FullRate && hiRate == calc_FullRate) return Clip_next_aa; if (loRate == calc_ScalarRate && hiRate == calc_ScalarRate) return Clip_next_ii; if (loRate == calc_FullRate && hiRate != calc_FullRate) return Clip_next_ak; if (loRate != calc_FullRate && hiRate == calc_FullRate) return Clip_next_ak; return Clip_next_kk; } void Clip_Ctor(Clip* unit) { ClipCalcFunc fn = Clip_SelectCalc(unit); unit->mCalcFunc = (UnitCalcFunc)fn; unit->m_lo = ZIN0(1); unit->m_hi = ZIN0(2); Clip_next_ii(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// void Unwrap_next(Unwrap* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float range = unit->m_range; float half = unit->m_half; float prev = unit->m_prev; float offset = unit->m_offset; LOOP1( inNumSamples, float zin = ZXP(in); float diff = zin - prev; if (fabs(diff) > half) { if (zin < prev) offset += range; else offset -= range; } ZXP(out) = zin + offset; prev = zin;); unit->m_prev = prev; unit->m_offset = offset; } void Unwrap_Ctor(Unwrap* unit) { SETCALC(Unwrap_next); float in = ZIN0(0); float lo = ZIN0(1); float hi = ZIN0(2); if (lo > hi) { float temp = lo; lo = hi; hi = temp; } unit->m_range = fabs(hi - lo); unit->m_half = unit->m_range * 0.5f; if (in < lo || in >= hi) unit->m_offset = floor((lo - in) / unit->m_range) * unit->m_range; else unit->m_offset = 0.f; Unwrap_next(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// void ModDif_next_kk(ModDif* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float next_dif = ZIN0(1); float next_mod = ZIN0(2); float dif = unit->m_dif; float dif_slope = CALCSLOPE(next_dif, dif); float mod = unit->m_mod; float mod_slope = CALCSLOPE(next_mod, mod); LOOP1(inNumSamples, float inval = ZXP(in); float diff = std::fmod(std::abs(inval - dif), mod); float modhalf = mod * 0.5; ZXP(out) = modhalf - std::fabs(diff - modhalf); dif += dif_slope; mod += mod_slope;); unit->m_dif = dif; unit->m_mod = mod; } void ModDif_next_ka(ModDif* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float next_dif = ZIN0(1); float* mod = ZIN(2); float dif = unit->m_dif; float dif_slope = CALCSLOPE(next_dif, dif); LOOP1(inNumSamples, float inval = ZXP(in); float curmod = ZXP(mod); float diff = std::fmod(std::abs(inval - dif), curmod); float modhalf = curmod * 0.5; ZXP(out) = modhalf - std::abs(diff - modhalf); dif += dif_slope;); unit->m_dif = dif; } void ModDif_next_ak(ModDif* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* dif = ZIN(1); float next_mod = ZIN0(2); float mod = unit->m_mod; float mod_slope = CALCSLOPE(next_mod, mod); LOOP1(inNumSamples, float inval = ZXP(in); float diff = std::fmod(std::abs(inval - ZXP(dif)), mod); float modhalf = mod * 0.5; ZXP(out) = modhalf - std::abs(diff - modhalf); mod += mod_slope;); unit->m_mod = mod; } void ModDif_next_aa(ModDif* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* dif = ZIN(1); float* mod = ZIN(2); LOOP1(inNumSamples, float inval = ZXP(in); float curmod = ZXP(mod); float diff = std::fmod(std::abs(inval - ZXP(dif)), curmod); float modhalf = curmod * 0.5; ZXP(out) = modhalf - std::abs(diff - modhalf);); } void ModDif_Ctor(ModDif* unit) { if (BUFLENGTH == 1) { // _aa? Well, yes - that calc func doesn't interpolate // and interpolation is not needed for kr (1 sample/block) SETCALC(ModDif_next_aa); } else { if (INRATE(1) == calc_FullRate) { if (INRATE(2) == calc_FullRate) SETCALC(ModDif_next_aa); else SETCALC(ModDif_next_ak); } else { if (INRATE(2) == calc_FullRate) SETCALC(ModDif_next_ka); else SETCALC(ModDif_next_kk); } } unit->m_dif = ZIN0(1); unit->m_mod = ZIN0(2); ModDif_next_kk(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// void AmpComp_next(AmpComp* unit, int inNumSamples) { float* out = ZOUT(0); float* freq = ZIN(0); float rootmul = unit->m_rootmul; float xb = unit->m_exponent; LOOP1(inNumSamples, float xa = ZXP(freq); ZXP(out) = xa >= 0.f ? pow(xa, xb) * rootmul : -pow(-xa, xb) * rootmul;); } void AmpComp_next_kk(AmpComp* unit, int inNumSamples) { float* out = ZOUT(0); float* freq = ZIN(0); float root = ZIN0(1); float xb = ZIN0(2); LOOP1(inNumSamples, float xa = root / ZXP(freq); ZXP(out) = xa >= 0.f ? pow(xa, xb) : -pow(-xa, xb);); } void AmpComp_Ctor(AmpComp* unit) { if (INRATE(1) != calc_ScalarRate || INRATE(2) != calc_ScalarRate) { SETCALC(AmpComp_next_kk); } else { float exp = ZIN0(2); unit->m_rootmul = pow(ZIN0(1), exp); unit->m_exponent = -1.f * exp; SETCALC(AmpComp_next); } AmpComp_next(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// const double AMPCOMP_K = 3.5041384 * 10e15; const double AMPCOMP_C1 = 20.598997 * 20.598997; const double AMPCOMP_C2 = 107.65265 * 107.65265; const double AMPCOMP_C3 = 737.86223 * 737.86223; const double AMPCOMP_C4 = 12194.217 * 12194.217; const double AMPCOMP_MINLEVEL = -0.1575371167435; double AmpCompA_calcLevel(double freq) { double r = freq * freq; double level = (AMPCOMP_K * r * r * r * r); double n1 = AMPCOMP_C1 + r; double n2 = AMPCOMP_C4 + r; level = level / (n1 * n1 * (AMPCOMP_C2 + r) * (AMPCOMP_C3 + r) * n2 * n2); level = 1. - sqrt(level); return level; } void AmpCompA_next(AmpCompA* unit, int inNumSamples) { float* out = ZOUT(0); float* freq = ZIN(0); double scale = unit->m_scale; double offset = unit->m_offset; LOOP1(inNumSamples, ZXP(out) = AmpCompA_calcLevel(ZXP(freq)) * scale + offset;); } void AmpCompA_Ctor(AmpCompA* unit) { double rootFreq = ZIN0(1); double rootLevel = AmpCompA_calcLevel(rootFreq); float minLevel = ZIN0(2); unit->m_scale = (ZIN0(3) - minLevel) / (rootLevel - AMPCOMP_MINLEVEL); unit->m_offset = minLevel - unit->m_scale * AMPCOMP_MINLEVEL; SETCALC(AmpCompA_next); AmpCompA_next(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// void InRange_next(InRange* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float lo = ZIN0(1); float hi = ZIN0(2); LOOP1(inNumSamples, float zin = ZXP(in); ZXP(out) = zin >= lo && zin <= hi ? 1.f : 0.f;); } void InRange_Ctor(InRange* unit) { SETCALC(InRange_next); InRange_next(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// void InRect_next(InRect* unit, int inNumSamples) { float* out = ZOUT(0); float* inx = ZIN(0); float* iny = ZIN(1); float left = ZIN0(2); float top = ZIN0(3); float right = ZIN0(4); float bottom = ZIN0(5); LOOP1(inNumSamples, float x = ZXP(inx); float y = ZXP(iny); ZXP(out) = x >= left && x <= right && y >= top && y <= bottom ? 1.f : 0.f;); } void InRect_Ctor(InRect* unit) { SETCALC(InRect_next); InRect_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void LinExp_next(LinExp* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float dstlo = unit->m_dstlo; float dstratio = unit->m_dstratio; float rsrcrange = unit->m_rsrcrange; float rrminuslo = unit->m_rrminuslo; LOOP1(inNumSamples, ZXP(out) = dstlo * pow(dstratio, ZXP(in) * rsrcrange + rrminuslo);); } #ifdef NOVA_SIMD static inline void LinExp_next_nova_loop(float* out, const float* in, int inNumSamples, nova::vec<float> dstlo, nova::vec<float> dstratio, nova::vec<float> rsrcrange, nova::vec<float> rrminuslo) { const int vecSize = nova::vec<float>::size; int unroll = inNumSamples / (2 * vecSize); do { nova::vec<float> val0, val1; val0.load_aligned(in); val1.load_aligned(in + vecSize); val0 = dstlo * pow(dstratio, val0 * rsrcrange + rrminuslo); val1 = dstlo * pow(dstratio, val1 * rsrcrange + rrminuslo); val0.store_aligned(out); val1.store_aligned(out + vecSize); in += 2 * vecSize; out += 2 * vecSize; } while (--unroll); } FLATTEN static void LinExp_next_nova(LinExp* unit, int inNumSamples) { float* out = OUT(0); float* in = IN(0); LinExp_next_nova_loop(out, in, inNumSamples, unit->m_dstlo, unit->m_dstratio, unit->m_rsrcrange, unit->m_rrminuslo); } FLATTEN static void LinExp_next_nova_kk(LinExp* unit, int inNumSamples) { float* out = OUT(0); float* in = IN(0); float srclo = ZIN0(1); float srchi = ZIN0(2); float dstlo = ZIN0(3); float dsthi = ZIN0(4); float dstratio = dsthi / dstlo; float rsrcrange = sc_reciprocal(srchi - srclo); float rrminuslo = rsrcrange * -srclo; LinExp_next_nova_loop(out, in, inNumSamples, dstlo, dstratio, rsrcrange, rrminuslo); } #endif void LinExp_next_kk(LinExp* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float srclo = ZIN0(1); float srchi = ZIN0(2); float dstlo = ZIN0(3); float dsthi = ZIN0(4); float dstratio = dsthi * sc_reciprocal(dstlo); float rsrcrange = sc_reciprocal(srchi - srclo); float rrminuslo = rsrcrange * -srclo; LOOP1(inNumSamples, ZXP(out) = dstlo * pow(dstratio, ZXP(in) * rsrcrange + rrminuslo);); } void LinExp_next_aa(LinExp* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* srclo = ZIN(1); float* srchi = ZIN(2); float* dstlo = ZIN(3); float* dsthi = ZIN(4); LOOP1(inNumSamples, float zdsthi = ZXP(dsthi); float zdstlo = ZXP(dstlo); float zsrchi = ZXP(srchi); float zsrclo = ZXP(srclo); float dstratio = zdsthi / zdstlo; float rsrcrange = sc_reciprocal(zsrchi - zsrclo); float rrminuslo = rsrcrange * -zsrclo; ZXP(out) = zdstlo * pow(dstratio, ZXP(in) * rsrcrange + rrminuslo);); } void LinExp_next_ak(LinExp* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* srclo = ZIN(1); float* srchi = ZIN(2); float dstlo = ZIN0(3); float dsthi = ZIN0(4); float dstratio = dsthi / dstlo; LOOP1(inNumSamples, float zsrchi = ZXP(srchi); float zsrclo = ZXP(srclo); float rsrcrange = sc_reciprocal(zsrchi - zsrclo); float rrminuslo = rsrcrange * -zsrclo; ZXP(out) = dstlo * pow(dstratio, ZXP(in) * rsrcrange + rrminuslo);); } void LinExp_next_ka(LinExp* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float srclo = ZIN0(1); float srchi = ZIN0(2); float* dstlo = ZIN(3); float* dsthi = ZIN(4); float rsrcrange = sc_reciprocal(srchi - srclo); float rrminuslo = rsrcrange * -srclo; LOOP1(inNumSamples, float zdsthi = ZXP(dsthi); float zdstlo = ZXP(dstlo); float dstratio = zdsthi / zdstlo; ZXP(out) = zdstlo * pow(dstratio, ZXP(in) * rsrcrange + rrminuslo);); } static void LinExp_SetCalc(LinExp* unit) { if (INRATE(1) == calc_FullRate || INRATE(2) == calc_FullRate) { if (INRATE(3) == calc_FullRate || INRATE(4) == calc_FullRate) { SETCALC(LinExp_next_aa); return; } else { SETCALC(LinExp_next_ak); return; } } else { if (INRATE(3) == calc_FullRate || INRATE(4) == calc_FullRate) { SETCALC(LinExp_next_ka); return; } } bool allScalar = true; for (int i = 1; i < 5; i++) { if (INRATE(i) != calc_ScalarRate) { allScalar = false; break; } }; #ifdef NOVA_SIMD if ((BUFLENGTH % (2 * nova::vec<float>::size)) == 0) if (allScalar) SETCALC(LinExp_next_nova); else SETCALC(LinExp_next_nova_kk); else #endif if (allScalar) SETCALC(LinExp_next); else SETCALC(LinExp_next_kk); if (!allScalar) return; float srclo = ZIN0(1); float srchi = ZIN0(2); float dstlo = ZIN0(3); float dsthi = ZIN0(4); unit->m_dstlo = dstlo; unit->m_dstratio = dsthi / dstlo; unit->m_rsrcrange = sc_reciprocal(srchi - srclo); unit->m_rrminuslo = unit->m_rsrcrange * -srclo; } void LinExp_Ctor(LinExp* unit) { LinExp_SetCalc(unit); float srclo = ZIN0(1); float srchi = ZIN0(2); float dstlo = ZIN0(3); float dsthi = ZIN0(4); unit->m_dstlo = dstlo; unit->m_dstratio = dsthi / dstlo; unit->m_rsrcrange = 1. / (srchi - srclo); unit->m_rrminuslo = unit->m_rsrcrange * -srclo; LinExp_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// enum { kEnvGen_gate, kEnvGen_levelScale, kEnvGen_levelBias, kEnvGen_timeScale, kEnvGen_doneAction, kEnvGen_initLevel, kEnvGen_numStages, kEnvGen_releaseNode, kEnvGen_loopNode, // 'kEnvGen_nodeOffset' must always be last // if you need to add an arg, put it before this one kEnvGen_nodeOffset }; enum { shape_Step, shape_Linear, shape_Exponential, shape_Sine, shape_Welch, shape_Curve, shape_Squared, shape_Cubed, shape_Hold, shape_Sustain = 9999 }; #ifdef NOVA_SIMD void EnvGen_next_ak_nova(EnvGen* unit, int inNumSamples); #endif #define ENVGEN_NOT_STARTED 1000000000 void EnvGen_Ctor(EnvGen* unit) { // Print("EnvGen_Ctor A\n"); if (unit->mCalcRate == calc_FullRate) { if (INRATE(0) == calc_FullRate) { SETCALC(EnvGen_next_aa); } else { #ifdef NOVA_SIMD if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(EnvGen_next_ak_nova); else #endif SETCALC(EnvGen_next_ak); } } else { SETCALC(EnvGen_next_k); } // gate = 1.0, levelScale = 1.0, levelBias = 0.0, timeScale // level0, numstages, releaseNode, loopNode, // [level, dur, shape, curve] unit->m_endLevel = unit->m_level = ZIN0(kEnvGen_initLevel) * ZIN0(kEnvGen_levelScale) + ZIN0(kEnvGen_levelBias); unit->m_counter = 0; unit->m_stage = ENVGEN_NOT_STARTED; unit->m_shape = shape_Hold; unit->m_prevGate = 0.f; unit->m_released = false; unit->m_releaseNode = (int)ZIN0(kEnvGen_releaseNode); float** envPtr = unit->mInBuf + kEnvGen_nodeOffset; const int initialShape = (int32)*envPtr[2]; if (initialShape == shape_Hold) unit->m_level = *envPtr[0]; // we start at the end level; EnvGen_next_k(unit, 1); } // called by nextSegment and check_gate: // - counter: num samples to next segment // - level: current envelope value // - dur: if supplied and >= 0, stretch segment to last dur seconds (used in forced release) static bool EnvGen_initSegment(EnvGen* unit, int& counter, double& level, double dur = -1) { // Print("stage %d\n", unit->m_stage); // Print("initSegment\n"); // out = unit->m_level; int stageOffset = (unit->m_stage << 2) + kEnvGen_nodeOffset; if (stageOffset + 4 > unit->mNumInputs) { // oops. Print("envelope went past end of inputs.\n"); ClearUnitOutputs(unit, 1); NodeEnd(&unit->mParent->mNode); return false; } float previousEndLevel = unit->m_endLevel; if (unit->m_shape == shape_Hold) level = previousEndLevel; float** envPtr = unit->mInBuf + stageOffset; double endLevel = *envPtr[0] * ZIN0(kEnvGen_levelScale) + ZIN0(kEnvGen_levelBias); // scale levels if (dur < 0) dur = *envPtr[1] * ZIN0(kEnvGen_timeScale); unit->m_shape = (int32)*envPtr[2]; double curve = *envPtr[3]; unit->m_endLevel = endLevel; counter = (int32)(dur * SAMPLERATE); counter = sc_max(1, counter); // Print("counter %d stageOffset %d level %g endLevel %g dur %g shape %d curve %g\n", counter, // stageOffset, level, endLevel, dur, unit->m_shape, curve); Print("SAMPLERATE %g\n", SAMPLERATE); if (counter == 1) unit->m_shape = 1; // shape_Linear // Print("new counter = %d shape = %d\n", counter, unit->m_shape); switch (unit->m_shape) { case shape_Step: { level = endLevel; } break; case shape_Hold: { level = previousEndLevel; } break; case shape_Linear: { unit->m_grow = (endLevel - level) / counter; // Print("grow %g\n", unit->m_grow); } break; case shape_Exponential: { unit->m_grow = pow(endLevel / level, 1.0 / counter); } break; case shape_Sine: { double w = pi / counter; unit->m_a2 = (endLevel + level) * 0.5; unit->m_b1 = 2. * cos(w); unit->m_y1 = (endLevel - level) * 0.5; unit->m_y2 = unit->m_y1 * sin(pi * 0.5 - w); level = unit->m_a2 - unit->m_y1; } break; case shape_Welch: { double w = (pi * 0.5) / counter; unit->m_b1 = 2. * cos(w); if (endLevel >= level) { unit->m_a2 = level; unit->m_y1 = 0.; unit->m_y2 = -sin(w) * (endLevel - level); } else { unit->m_a2 = endLevel; unit->m_y1 = level - endLevel; unit->m_y2 = cos(w) * (level - endLevel); } level = unit->m_a2 + unit->m_y1; } break; case shape_Curve: { if (fabs(curve) < 0.001) { unit->m_shape = 1; // shape_Linear unit->m_grow = (endLevel - level) / counter; } else { double a1 = (endLevel - level) / (1.0 - exp(curve)); unit->m_a2 = level + a1; unit->m_b1 = a1; unit->m_grow = exp(curve / counter); } } break; case shape_Squared: { unit->m_y1 = sqrt(level); unit->m_y2 = sqrt(endLevel); unit->m_grow = (unit->m_y2 - unit->m_y1) / counter; } break; case shape_Cubed: { unit->m_y1 = pow(level, 1.0 / 3.0); // 0.33333333); unit->m_y2 = pow(endLevel, 1.0 / 3.0); unit->m_grow = (unit->m_y2 - unit->m_y1) / counter; } break; }; return true; } static bool check_gate(EnvGen* unit, float prevGate, float gate, int& counter, double level, int counterOffset = 0) { if (prevGate <= 0.f && gate > 0.f) { unit->m_stage = -1; unit->m_released = false; unit->mDone = false; counter = counterOffset; return false; } else if (gate <= -1.f && prevGate > -1.f) { // forced release: jump to last segment overriding its duration double dur = -gate - 1.f; counter = (int32)(dur * SAMPLERATE); counter = sc_max(1, counter) + counterOffset; unit->m_stage = static_cast<int>(ZIN0(kEnvGen_numStages) - 1); unit->m_released = true; EnvGen_initSegment(unit, counter, level, dur); return false; } else if (prevGate > 0.f && gate <= 0.f && unit->m_releaseNode >= 0 && !unit->m_released) { counter = counterOffset; unit->m_stage = unit->m_releaseNode - 1; unit->m_released = true; return false; } return true; } static inline bool check_gate_ar(EnvGen* unit, int i, float& prevGate, float*& gatein, int& nsmps, int& counter, double level) { const float gate = ZXP(gatein); const bool result = check_gate(unit, prevGate, gate, counter, level, i); if (!result) { --gatein; nsmps = i; } prevGate = gate; return result; } static inline bool EnvGen_nextSegment(EnvGen* unit, int& counter, double& level) { // Print("stage %d rel %d\n", unit->m_stage, (int)ZIN0(kEnvGen_releaseNode)); int numstages = (int)ZIN0(kEnvGen_numStages); // Print("stage %d numstages %d\n", unit->m_stage, numstages); if (unit->m_stage + 1 >= numstages) { // num stages // Print("stage+1 > num stages\n"); counter = INT_MAX; unit->m_shape = 0; level = unit->m_endLevel; unit->mDone = true; int doneAction = (int)ZIN0(kEnvGen_doneAction); DoneAction(doneAction, unit); } else if (unit->m_stage == ENVGEN_NOT_STARTED) { counter = INT_MAX; return true; } else if (unit->m_stage + 1 == (int)ZIN0(kEnvGen_releaseNode) && !unit->m_released) { // sustain stage int loopNode = (int)ZIN0(kEnvGen_loopNode); if (loopNode >= 0 && loopNode < numstages) { unit->m_stage = loopNode; return EnvGen_initSegment(unit, counter, level); } else { counter = INT_MAX; unit->m_shape = shape_Sustain; level = unit->m_endLevel; } // Print("sustain\n"); } else { unit->m_stage++; return EnvGen_initSegment(unit, counter, level); } return true; } template <bool CheckGateOnSustain, typename GateCheck> static inline void EnvGen_perform(EnvGen* unit, float*& out, double& level, int& nsmps, GateCheck const& gateCheck) { switch (unit->m_shape) { case shape_Step: case shape_Hold: { for (int i = 0; i < nsmps; ++i) { if (!gateCheck(i)) break; ZXP(out) = level; } } break; case shape_Linear: { double grow = unit->m_grow; for (int i = 0; i < nsmps; ++i) { if (!gateCheck(i)) break; ZXP(out) = level; level += grow; } } break; case shape_Exponential: { double grow = unit->m_grow; for (int i = 0; i < nsmps; ++i) { if (!gateCheck(i)) break; ZXP(out) = level; level *= grow; } } break; case shape_Sine: { double a2 = unit->m_a2; double b1 = unit->m_b1; double y2 = unit->m_y2; double y1 = unit->m_y1; for (int i = 0; i < nsmps; ++i) { if (!gateCheck(i)) break; ZXP(out) = level; double y0 = b1 * y1 - y2; level = a2 - y0; y2 = y1; y1 = y0; } unit->m_y1 = y1; unit->m_y2 = y2; } break; case shape_Welch: { double a2 = unit->m_a2; double b1 = unit->m_b1; double y2 = unit->m_y2; double y1 = unit->m_y1; for (int i = 0; i < nsmps; ++i) { if (!gateCheck(i)) break; ZXP(out) = level; double y0 = b1 * y1 - y2; level = a2 + y0; y2 = y1; y1 = y0; } unit->m_y1 = y1; unit->m_y2 = y2; } break; case shape_Curve: { double a2 = unit->m_a2; double b1 = unit->m_b1; double grow = unit->m_grow; for (int i = 0; i < nsmps; ++i) { if (!gateCheck(i)) break; ZXP(out) = level; b1 *= grow; level = a2 - b1; } unit->m_b1 = b1; } break; case shape_Squared: { double grow = unit->m_grow; double y1 = unit->m_y1; for (int i = 0; i < nsmps; ++i) { if (!gateCheck(i)) break; ZXP(out) = level; y1 += grow; level = y1 * y1; } unit->m_y1 = y1; } break; case shape_Cubed: { double grow = unit->m_grow; double y1 = unit->m_y1; for (int i = 0; i < nsmps; ++i) { if (!gateCheck(i)) break; ZXP(out) = level; y1 += grow; y1 = sc_max(y1, 0); level = y1 * y1 * y1; } unit->m_y1 = y1; } break; case shape_Sustain: { for (int i = 0; i < nsmps; ++i) { if (CheckGateOnSustain) { if (gateCheck(i)) ZXP(out) = level; } else ZXP(out) = level; } } break; } } static inline void EnvGen_perform(EnvGen* unit, float*& out, double& level, int nsmps) { EnvGen_perform<false>(unit, out, level, nsmps, [](int i) { return true; }); } void EnvGen_next_k(EnvGen* unit, int inNumSamples) { float gate = ZIN0(kEnvGen_gate); // Print("->EnvGen_next_k gate %g\n", gate); int counter = unit->m_counter; double level = unit->m_level; check_gate(unit, unit->m_prevGate, gate, counter, level); unit->m_prevGate = gate; // gate = 1.0, levelScale = 1.0, levelBias = 0.0, timeScale // level0, numstages, releaseNode, loopNode, // [level, dur, shape, curve] if (counter <= 0) { bool success = EnvGen_nextSegment(unit, counter, level); if (!success) return; } float* out = ZOUT(0); EnvGen_perform(unit, out, level, 1); // Print("x %d %d %d %g\n", unit->m_stage, counter, unit->m_shape, *out); unit->m_level = level; unit->m_counter = counter - 1; } void EnvGen_next_ak(EnvGen* unit, int inNumSamples) { float* out = ZOUT(0); float gate = ZIN0(kEnvGen_gate); int counter = unit->m_counter; double level = unit->m_level; check_gate(unit, unit->m_prevGate, gate, counter, level); unit->m_prevGate = gate; int remain = inNumSamples; while (remain) { if (counter <= 0) { bool success = EnvGen_nextSegment(unit, counter, level); if (!success) return; } int nsmps = sc_min(remain, counter); EnvGen_perform(unit, out, level, nsmps); remain -= nsmps; counter -= nsmps; } // Print("x %d %d %d %g\n", unit->m_stage, counter, unit->m_shape, ZOUT0(0)); unit->m_level = level; unit->m_counter = counter; } #ifdef NOVA_SIMD FLATTEN void EnvGen_next_ak_nova(EnvGen* unit, int inNumSamples) { float* out = ZOUT(0); float gate = ZIN0(kEnvGen_gate); int counter = unit->m_counter; double level = unit->m_level; check_gate(unit, unit->m_prevGate, gate, counter, level); unit->m_prevGate = gate; int remain = inNumSamples; if (counter > inNumSamples) { switch (unit->m_shape) { case shape_Step: case shape_Hold: case shape_Sustain: nova::setvec_simd(OUT(0), (float)level, inNumSamples); remain = 0; counter -= inNumSamples; break; case shape_Linear: { double slope = unit->m_grow; nova::set_slope_vec_simd(OUT(0), (float)level, (float)slope, inNumSamples); level += inNumSamples * slope; remain = 0; counter -= inNumSamples; } break; case shape_Exponential: { double grow = unit->m_grow; nova::set_exp_vec_simd(OUT(0), (float)level, (float)grow, inNumSamples); level *= sc_powi(grow, inNumSamples); remain = 0; counter -= inNumSamples; } break; } } while (remain) { if (counter <= 0) { bool success = EnvGen_nextSegment(unit, counter, level); if (!success) return; } int nsmps = sc_min(remain, counter); EnvGen_perform(unit, out, level, nsmps); remain -= nsmps; counter -= nsmps; } // Print("x %d %d %d %g\n", unit->m_stage, counter, unit->m_shape, ZOUT0(0)); unit->m_level = level; unit->m_counter = counter; } #endif void EnvGen_next_aa(EnvGen* unit, int inNumSamples) { float* out = ZOUT(0); float* gatein = ZIN(kEnvGen_gate); int counter = unit->m_counter; double level = unit->m_level; float gate = unit->m_prevGate; int remain = inNumSamples; while (remain) { if (counter <= 0) { bool success = EnvGen_nextSegment(unit, counter, level); if (!success) return; } int nsmps = sc_min(remain, counter); EnvGen_perform<true>(unit, out, level, nsmps, [&](int i) { return check_gate_ar(unit, i, gate, gatein, nsmps, counter, level); }); remain -= nsmps; counter -= nsmps; } unit->m_level = level; unit->m_counter = counter; unit->m_prevGate = gate; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Linen_Ctor(Linen* unit) { // gate attack level release SETCALC(Linen_next_k); unit->m_level = 0.f; unit->m_stage = 4; unit->m_prevGate = 0.f; if (ZIN0(0) <= -1.f) { unit->m_stage = 1; } // early release Linen_next_k(unit, 1); } void Linen_next_k(Linen* unit, int inNumSamples) { float gate = ZIN0(0); float* out = OUT(0); if (unit->m_prevGate <= 0.f && gate > 0.f) { unit->mDone = false; unit->m_stage = 0; float attackTime = ZIN0(1); float susLevel = ZIN0(2); int counter = (int)(attackTime * SAMPLERATE); counter = sc_max(1, counter); unit->m_slope = (susLevel - unit->m_level) / counter; unit->m_counter = counter; } switch (unit->m_stage) { case 0: case 2: *out = unit->m_level; unit->m_level += unit->m_slope; if (--unit->m_counter == 0) unit->m_stage++; break; case 1: *out = unit->m_level; if (gate <= -1.f) { // cutoff unit->m_stage = 2; float releaseTime = -gate - 1.f; int counter = (int)(releaseTime * SAMPLERATE); counter = sc_max(1, counter); unit->m_slope = -unit->m_level / counter; unit->m_counter = counter; } else if (gate <= 0.f) { unit->m_stage = 2; float releaseTime = ZIN0(3); int counter = (int)(releaseTime * SAMPLERATE); counter = sc_max(1, counter); unit->m_slope = -unit->m_level / counter; unit->m_counter = counter; // Print("release %d %d\n", unit->mParent->mNode.mID, counter); } break; case 3: { *out = 0.f; // Print("done %d\n", unit->mParent->mNode.mID); unit->mDone = true; unit->m_stage++; int doneAction = (int)ZIN0(4); DoneAction(doneAction, unit); } break; case 4: *out = 0.f; break; } unit->m_prevGate = gate; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void EnvFill(World* world, struct SndBuf* buf, struct sc_msg_iter* msg) { if (buf->channels != 1) return; int size = buf->samples; int byteSize = size * sizeof(float); float* data = (float*)malloc(byteSize); double level = msg->getf(); int numStages = msg->geti(); /*int releaseNode =*/msg->geti(); // ignored /*int loopNode =*/msg->geti(); // ignored double pos = 0.; int32 index = 0; int32 remain = size; for (int j = 0; j < numStages; ++j) { double endLevel = msg->getf(); double dur = msg->getf(); int shape = msg->geti(); double curve = msg->getf(); int32 ipos = (int32)pos; double smpdur = dur * size; int32 nsmps = (int32)smpdur - ipos; nsmps = sc_min(nsmps, remain); switch (shape) { case shape_Step: { level = endLevel; for (int i = 0; i < nsmps; ++i) { data[index++] = level; } } break; case shape_Hold: { for (int i = 0; i < nsmps; ++i) { data[index++] = level; } level = endLevel; } break; case shape_Linear: { double grow = (endLevel - level) / nsmps; for (int i = 0; i < nsmps; ++i) { data[index++] = level; level += grow; } } break; case shape_Exponential: { double grow = pow(endLevel / level, 1.0 / nsmps); for (int i = 0; i < nsmps; ++i) { data[index++] = level; level *= grow; } } break; case shape_Sine: { double w = pi / nsmps; double a2 = (endLevel + level) * 0.5; double b1 = 2. * cos(w); double y1 = (endLevel - level) * 0.5; double y2 = y1 * sin(pi * 0.5 - w); level = a2 - y1; for (int i = 0; i < nsmps; ++i) { data[index++] = level; double y0 = b1 * y1 - y2; level = a2 - y0; y2 = y1; y1 = y0; } } break; case shape_Welch: { double w = (pi * 0.5) / nsmps; double b1 = 2. * cos(w); double a2, y1, y2; if (endLevel >= level) { a2 = level; y1 = 0.; y2 = -sin(w) * (endLevel - level); } else { a2 = endLevel; y1 = level - endLevel; y2 = cos(w) * (level - endLevel); } level = a2 + y1; for (int i = 0; i < nsmps; ++i) { data[index++] = level; double y0 = b1 * y1 - y2; level = a2 - y0; y2 = y1; y1 = y0; } } break; case shape_Curve: { if (fabs(curve) < 0.001) { double grow = (endLevel - level) / nsmps; for (int i = 0; i < nsmps; ++i) { data[index++] = level; level += grow; } } else { double a1 = (endLevel - level) / (1.0 - exp(curve)); double a2 = level + a1; double b1 = a1; double grow = exp(curve / nsmps); for (int i = 0; i < nsmps; ++i) { data[index++] = level; b1 *= grow; level = a2 - b1; } } } break; case shape_Squared: { double y1 = sqrt(level); double y2 = sqrt(endLevel); double grow = (y2 - y1) / nsmps; for (int i = 0; i < nsmps; ++i) { data[index++] = level; y1 += grow; level = y1 * y1; } } break; case shape_Cubed: { double y1 = pow(level, 0.33333333); double y2 = pow(endLevel, 0.33333333); double grow = (y2 - y1) / nsmps; for (int i = 0; i < nsmps; ++i) { data[index++] = level; y1 += grow; level = y1 * y1 * y1; } } break; } pos += smpdur; level = endLevel; remain -= nsmps; } memcpy(buf->data, data, byteSize); free(data); } //////////////////// Add IEnvGen 06/06/2007 ///////////////////////////////// struct IEnvGen : public Unit { float m_level, m_offset; float m_startpoint, m_numvals, m_pointin; float* m_envvals; }; extern "C" { void IEnvGen_next_a(IEnvGen* unit, int inNumSamples); void IEnvGen_next_k(IEnvGen* unit, int inNumSamples); void IEnvGen_Ctor(IEnvGen* unit); void IEnvGen_Dtor(IEnvGen* unit); } #define GET_ENV_VAL \ switch (shape) { \ case shape_Step: \ level = unit->m_level = endLevel; \ break; \ case shape_Hold: \ level = unit->m_level; \ unit->m_level = endLevel; \ break; \ case shape_Linear: \ default: \ level = unit->m_level = pos * (endLevel - begLevel) + begLevel; \ break; \ case shape_Exponential: \ level = unit->m_level = begLevel * pow(endLevel / begLevel, pos); \ break; \ case shape_Sine: \ level = unit->m_level = begLevel + (endLevel - begLevel) * (-cos(pi * pos) * 0.5 + 0.5); \ break; \ case shape_Welch: { \ if (begLevel < endLevel) \ level = unit->m_level = begLevel + (endLevel - begLevel) * sin(pi2 * pos); \ else \ level = unit->m_level = endLevel - (endLevel - begLevel) * sin(pi2 - pi2 * pos); \ break; \ } \ case shape_Curve: \ if (fabs((float)curve) < 0.0001) { \ level = unit->m_level = pos * (endLevel - begLevel) + begLevel; \ } else { \ double denom = 1. - exp((float)curve); \ double numer = 1. - exp((float)(pos * curve)); \ level = unit->m_level = begLevel + (endLevel - begLevel) * (numer / denom); \ } \ break; \ case shape_Squared: { \ double sqrtBegLevel = sqrt(begLevel); \ double sqrtEndLevel = sqrt(endLevel); \ double sqrtLevel = pos * (sqrtEndLevel - sqrtBegLevel) + sqrtBegLevel; \ level = unit->m_level = sqrtLevel * sqrtLevel; \ break; \ } \ case shape_Cubed: { \ double cbrtBegLevel = pow(begLevel, 0.3333333f); \ double cbrtEndLevel = pow(endLevel, 0.3333333f); \ double cbrtLevel = pos * (cbrtEndLevel - cbrtBegLevel) + cbrtBegLevel; \ level = unit->m_level = cbrtLevel * cbrtLevel * cbrtLevel; \ break; \ } \ } void IEnvGen_Ctor(IEnvGen* unit) { if (INRATE(0) == calc_FullRate) { SETCALC(IEnvGen_next_a); } else { SETCALC(IEnvGen_next_k); } // pointer, offset // initlevel, numstages, totaldur, // [dur, shape, curve, level] * numvals int numStages = (int)IN0(3); int numvals = numStages * 4; // initlevel + (levels, dur, shape, curves) * stages float offset = unit->m_offset = IN0(1); float point = unit->m_pointin = IN0(0) - offset; unit->m_envvals = (float*)RTAlloc(unit->mWorld, (int)(numvals + 1.) * sizeof(float)); ClearUnitIfMemFailed(unit->m_envvals); unit->m_envvals[0] = IN0(2); // Print("offset of and initial values %3,3f, %3.3f\n", offset, unit->m_envvals[0]); // fill m_envvals with the values; for (int i = 1; i <= numvals; i++) { unit->m_envvals[i] = IN0(4 + i); // Print("val for: %d, %3.3f\n", i, unit->m_envvals[i]); } // float out = OUT0(0); float totalDur = IN0(4); float level = 0.f; float newtime = 0.f; int stage = 0; float seglen = 0.f; if (point >= totalDur) { unit->m_level = level = unit->m_envvals[numStages * 4]; // grab the last value } else { if (point <= 0.0) { unit->m_level = level = unit->m_envvals[0]; } else { float segpos = point; // determine which segment the current time pointer needs calculated for (int j = 0; point >= newtime; j++) { seglen = unit->m_envvals[(j * 4) + 1]; newtime += seglen; segpos -= seglen; stage = j; } segpos = segpos + seglen; float begLevel = unit->m_envvals[(stage * 4)]; int shape = (int)unit->m_envvals[(stage * 4) + 2]; int curve = (int)unit->m_envvals[(stage * 4) + 3]; float endLevel = unit->m_envvals[(stage * 4) + 4]; float pos = (segpos / seglen); GET_ENV_VAL } } OUT0(0) = level; } void IEnvGen_Dtor(IEnvGen* unit) { RTFree(unit->mWorld, unit->m_envvals); } void IEnvGen_next_a(IEnvGen* unit, int inNumSamples) { float* out = OUT(0); float level = unit->m_level; float* pointin = IN(0); float offset = unit->m_offset; int numStages = (int)IN0(3); float point; // = unit->m_pointin; float totalDur = IN0(4); int stagemul; // pointer, offset // level0, numstages, totaldur, // [initval, [dur, shape, curve, level] * N ] for (int i = 0; i < inNumSamples; i++) { if (pointin[i] == unit->m_pointin) { out[i] = level; } else { unit->m_pointin = point = sc_max(pointin[i] - offset, 0.0); float newtime = 0.f; int stage = 0; float seglen = 0.f; if (point >= totalDur) { unit->m_level = level = unit->m_envvals[numStages * 4]; // grab the last value } else { if (point <= 0.0) { unit->m_level = level = unit->m_envvals[0]; } else { float segpos = point; // determine which segment the current time pointer needs for (int j = 0; point >= newtime; j++) { seglen = unit->m_envvals[(j * 4) + 1]; newtime += seglen; segpos -= seglen; stage = j; } stagemul = stage * 4; segpos = segpos + seglen; float begLevel = unit->m_envvals[stagemul]; int shape = (int)unit->m_envvals[stagemul + 2]; int curve = (int)unit->m_envvals[stagemul + 3]; float endLevel = unit->m_envvals[stagemul + 4]; float pos = (segpos / seglen); GET_ENV_VAL } } out[i] = level; } } } void IEnvGen_next_k(IEnvGen* unit, int inNumSamples) { float* out = OUT(0); float level = unit->m_level; float pointin = IN0(0); float offset = unit->m_offset; int numStages = (int)IN0(3); float point; // = unit->m_pointin; float totalDur = IN0(4); int stagemul; // pointer, offset // level0, numstages, totaldur, // [initval, [dur, shape, curve, level] * N ] for (int i = 0; i < inNumSamples; i++) { if (pointin == unit->m_pointin) { out[i] = level; } else { unit->m_pointin = point = sc_max(pointin - offset, 0.0); float newtime = 0.f; int stage = 0; float seglen = 0.f; if (point >= totalDur) { unit->m_level = level = unit->m_envvals[numStages * 4]; // grab the last value } else { if (point <= 0.0) { unit->m_level = level = unit->m_envvals[0]; } else { float segpos = point; // determine which segment the current time pointer needs for (int j = 0; point >= newtime; j++) { seglen = unit->m_envvals[(j * 4) + 1]; newtime += seglen; segpos -= seglen; stage = j; } stagemul = stage * 4; segpos = segpos + seglen; float begLevel = unit->m_envvals[stagemul]; int shape = (int)unit->m_envvals[stagemul + 2]; int curve = (int)unit->m_envvals[stagemul + 3]; float endLevel = unit->m_envvals[stagemul + 4]; float pos = (segpos / seglen); GET_ENV_VAL } } out[i] = level; } } } //////////////////////////////////////////////////////////////////////////////////////////////////////// PluginLoad(LF) { ft = inTable; DefineSimpleUnit(Vibrato); DefineSimpleUnit(LFPulse); DefineSimpleUnit(LFSaw); DefineSimpleUnit(LFPar); DefineSimpleUnit(LFCub); DefineSimpleUnit(LFTri); DefineSimpleUnit(LFGauss); DefineSimpleUnit(Impulse); DefineSimpleUnit(VarSaw); DefineSimpleUnit(SyncSaw); registerUnit<K2A>(ft, "K2A"); DefineSimpleUnit(A2K); DefineSimpleUnit(T2K); DefineSimpleUnit(T2A); registerUnit<DC>(ft, "DC"); DefineSimpleUnit(Line); DefineSimpleUnit(XLine); DefineSimpleUnit(Wrap); DefineSimpleUnit(Fold); DefineSimpleUnit(Clip); DefineSimpleUnit(Unwrap); DefineSimpleUnit(ModDif); DefineSimpleUnit(AmpComp); DefineSimpleUnit(AmpCompA); DefineSimpleUnit(InRange); DefineSimpleUnit(InRect); DefineSimpleUnit(LinExp); DefineSimpleUnit(EnvGen); DefineSimpleUnit(Linen); DefineBufGen("env", EnvFill); DefineDtorUnit(IEnvGen); }
104,881
C++
.cpp
2,873
29.426036
120
0.529295
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,960
BeatTrack.cpp
supercollider_supercollider/server/plugins/BeatTrack.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // BeatTrack UGen implemented by Nick Collins (http://www.informatics.sussex.ac.uk/users/nc81/) // post FFT UGen version 1 Nov 2007 // conversion of Matthew Davies autocorrelation beat tracking model, adapted for real-time use // currently using QMUL complex domain onset detection function model //#include "SC_PlugIn.h" //#include <vecLib/vecLib.h> //#include <string.h> //#include <math.h> //#include <stdlib.h> //#include <stdio.h> #include "ML.h" // FFT data //#define N 1024 //FFT size // FFT size over 2 #define NOVER2 512 //#define NOVER4 256 //FFT size //#define OVERLAP 512 //#define OVERLAPINDEX 512 //#define HOPSIZE 512 //#define FS 44100 //assumes fixed sampling rate //#define FRAMESR 86.1328 // converted for different sampling rates #define FRAMEPERIOD 0.01161 #define SKIP 128 //#define TIMEELAPSED 1.48608 // this data assumes LAGS is 128 static float g_m[128] = { 0.00054069, 0.00108050, 0.00161855, 0.00215399, 0.00268594, 0.00321356, 0.00373600, 0.00425243, 0.00476204, 0.00526404, 0.00575765, 0.00624213, 0.00671675, 0.00718080, 0.00763362, 0.00807455, 0.00850299, 0.00891836, 0.00932010, 0.00970771, 0.01008071, 0.01043866, 0.01078115, 0.01110782, 0.01141834, 0.01171242, 0.01198982, 0.01225033, 0.01249378, 0.01272003, 0.01292899, 0.01312061, 0.01329488, 0.01345182, 0.01359148, 0.01371396, 0.01381939, 0.01390794, 0.01397980, 0.01403520, 0.01407439, 0.01409768, 0.01410536, 0.01409780, 0.01407534, 0.01403838, 0.01398734, 0.01392264, 0.01384474, 0.01375410, 0.01365120, 0.01353654, 0.01341062, 0.01327397, 0.01312710, 0.01297054, 0.01280484, 0.01263053, 0.01244816, 0.01225827, 0.01206139, 0.01185807, 0.01164884, 0.01143424, 0.01121478, 0.01099099, 0.01076337, 0.01053241, 0.01029861, 0.01006244, 0.00982437, 0.00958484, 0.00934429, 0.00910314, 0.00886181, 0.00862067, 0.00838011, 0.00814049, 0.00790214, 0.00766540, 0.00743057, 0.00719793, 0.00696778, 0.00674036, 0.00651591, 0.00629466, 0.00607682, 0.00586256, 0.00565208, 0.00544551, 0.00524301, 0.00504470, 0.00485070, 0.00466109, 0.00447597, 0.00429540, 0.00411944, 0.00394813, 0.00378151, 0.00361959, 0.00346238, 0.00330989, 0.00316210, 0.00301899, 0.00288053, 0.00274669, 0.00261741, 0.00249266, 0.00237236, 0.00225646, 0.00214488, 0.00203755, 0.00193440, 0.00183532, 0.00174025, 0.00164909, 0.00156174, 0.00147811, 0.00139810, 0.00132161, 0.00124854, 0.00117880, 0.00111228, 0.00104887, 0.00098848, 0.00093100, 0.00087634, 0.00082438, }; static float g_mg[257] = { 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000004, 0.00000055, 0.00000627, 0.00005539, 0.00037863, 0.00200318, 0.00820201, 0.02599027, 0.06373712, 0.12096648, 0.17767593, 0.20196826, 0.17767593, 0.12096648, 0.06373712, 0.02599027, 0.00820201, 0.00200318, 0.00037863, 0.00005539, 0.00000627, 0.00000055, 0.00000004, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, }; // other functions static void BeatTrack_dofft(BeatTrack* unit, uint32); static void complexdf(BeatTrack* unit); static void finaldecision(BeatTrack* unit); // amortisation static void autocorr(BeatTrack* unit, int j); static void beatperiod(BeatTrack* unit, int j, int whichm); static float findtor(BeatTrack* unit); // as many amortisation steps as tor static void findphase(BeatTrack* unit, int j, int gaussflag, int predicted); static int detectperiodchange(BeatTrack* unit); static void findmeter(BeatTrack* unit); static void setupphaseexpectation(BeatTrack* unit); // create Gaussian focussed matrix for phase void BeatTrack_Ctor(BeatTrack* unit) { /////// // check sampling rate and establish multipliers on estimates and FFT window size // down sampling by factor of two automatic unit->m_srate = unit->mWorld->mFullRate.mSampleRate; // if sample rate is 88200 or 96000, assume taking double size FFT to start with if (unit->m_srate > (44100.0 * 1.5)) unit->m_srate = unit->m_srate * 0.5; unit->m_srateconversion = unit->m_srate / 44100.0; // assumes base of 1024 FFT unit->m_frameperiod = (FRAMEPERIOD / unit->m_srateconversion); // in seconds //(int) ((FRAMEPERIOD/unit->m_srateconversion) +0.5); printf("srate %f conversion factor %f frame period %f \n", unit->m_srate, unit->m_srateconversion, unit->m_frameperiod); unit->m_prevmag = (float*)RTAlloc(unit->mWorld, NOVER2 * sizeof(float)); unit->m_prevphase = (float*)RTAlloc(unit->mWorld, NOVER2 * sizeof(float)); unit->m_predict = (float*)RTAlloc(unit->mWorld, NOVER2 * sizeof(float)); ClearUnitIfMemFailed(unit->m_prevmag && unit->m_prevphase && unit->m_predict); ////////time positions////////// unit->m_frame = 1; // don't decide immediately, wait for maximum period! /////////df//////// unit->m_dfcounter = DFSTORE - 1; // random uncorrelated noise df store for initialisation // RGen& rgen = *unit->mParent->mRGen; // don't want this noise, want consistent starting point! for (int j = 0; j < DFSTORE; ++j) { unit->m_df[j] = 0.0; //(2*rgen.frand() - 1.0); } unit->m_dfmemorycounter = 14; Clear(15, unit->m_dfmemory); /////////tempo assess/////////// unit->m_currtempo = 2; ////////phase assess/////////// unit->m_currphase = 0.0; unit->m_phase = 0.0; // default of 2bps unit->m_phaseperblock = ((float)unit->mWorld->mFullRate.mBufLength * 2) / ((float)unit->mWorld->mSampleRate); unit->m_outputphase = unit->m_phase; unit->m_outputtempo = unit->m_currtempo; unit->m_outputphaseperblock = unit->m_phaseperblock; unit->halftrig = 0; unit->q1trig = 0; unit->q2trig = 0; // amortisation and states unit->m_amortisationstate = 0; // off unit->m_stateflag = 0; unit->m_timesig = 4; unit->m_flagstep = 0; unit->mCalcFunc = (UnitCalcFunc)&BeatTrack_next; // initialize outputs ZOUT0(0) = 0.0; ZOUT0(1) = 0.0; ZOUT0(2) = 0.0; ZOUT0(3) = unit->m_outputtempo; } void BeatTrack_Dtor(BeatTrack* unit) { RTFree(unit->mWorld, unit->m_prevmag); RTFree(unit->mWorld, unit->m_prevphase); RTFree(unit->mWorld, unit->m_predict); } void BeatTrack_next(BeatTrack* unit, int wrongNumSamples) { // float *in = IN(0); // printf("%d \n",wrongNumSamples); // int numSamples = unit->mWorld->mFullRate.mBufLength; // conditions in reverse order to avoid immediate spillover // printf("state %d \n",unit->m_amortisationstate); // keeps incrementing but will be reset with each calculation run unit->m_amortisationsteps = unit->m_amortisationsteps + 1; // if state nonzero do something switch (unit->m_amortisationstate) { case 0: break; // do nothing case case 1: // calculate acf autocorr(unit, unit->m_amortcount); unit->m_amortcount = unit->m_amortcount + 1; if (unit->m_amortcount == unit->m_amortlength) { unit->m_amortisationstate = 2; unit->m_amortlength = 128; unit->m_amortcount = 0; unit->m_bestcolumn = 0; unit->m_besttorsum = -1000.0; } break; case 2: // periodp beatperiod(unit, unit->m_amortcount, 0); unit->m_amortcount = unit->m_amortcount + 1; if (unit->m_amortcount == unit->m_amortlength) { unit->m_periodp = findtor(unit); if (unit->m_stateflag == 1) { unit->m_amortisationstate = 3; unit->m_amortlength = 128; unit->m_amortcount = 0; unit->m_bestcolumn = 0; unit->m_besttorsum = -1000.0; } else { unit->m_periodg = -1000; // will always trigger initially unit->m_amortisationstate = 4; } } break; case 3: // periodg beatperiod(unit, unit->m_amortcount, 1); unit->m_amortcount = unit->m_amortcount + 1; if (unit->m_amortcount == unit->m_amortlength) { unit->m_periodg = findtor(unit); unit->m_amortisationstate = 4; } break; case 4: // stepdetect/constdetect if (detectperiodchange(unit)) { unit->m_amortisationstate = 5; unit->m_amortlength = 128; unit->m_amortcount = 0; unit->m_bestcolumn = 0; unit->m_besttorsum = -1000.0; unit->m_stateflag = 1; findmeter(unit); // set up Gaussian weighting centred on periodp int startindex = 128 - ((int)(unit->m_periodp + 0.5)); float* mg = unit->m_mg; for (int ii = 0; ii < 128; ++ii) { mg[ii] = g_mg[startindex + ii]; } } else { if (unit->m_stateflag == 1) unit->m_tor = unit->m_periodg; else unit->m_tor = unit->m_periodp; unit->m_torround = int(unit->m_tor + 0.5); unit->m_amortisationstate = 7; unit->m_amortlength = unit->m_torround; unit->m_amortcount = 0; } break; case 5: // redo periodg calculation beatperiod(unit, unit->m_amortcount, 1); unit->m_amortcount = unit->m_amortcount + 1; if (unit->m_amortcount == unit->m_amortlength) { unit->m_periodg = findtor(unit); unit->m_tor = unit->m_periodg; unit->m_torround = int(unit->m_tor + 0.5f); unit->m_amortisationstate = 6; unit->m_amortlength = unit->m_torround; unit->m_amortcount = 0; setupphaseexpectation(unit); // don't need to reset change flag since it isn't stored } break; case 6: // flat phase calc after move to context, avoids bias findphase(unit, unit->m_amortcount, 0, 0); unit->m_amortcount = unit->m_amortcount + 1; if (unit->m_amortcount == unit->m_amortlength) { unit->m_amortisationstate = 8; // final state } break; case 7: // phase calc with possible gaussian narrowing of the allowed phases findphase(unit, unit->m_amortcount, unit->m_stateflag, (int)(unit->m_currphase * unit->m_torround + 0.5f)); unit->m_amortcount = unit->m_amortcount + 1; if (unit->m_amortcount == unit->m_amortlength) { unit->m_amortisationstate = 8; // final state } break; case 8: finaldecision(unit); unit->m_amortisationstate = 0; break; default: break; } // MUST CHECK IF INCIDENT FFT IS >1, if so update buffer with appropriate coefficients float fbufnum = ZIN0(0); // next FFT bufffer ready, update // assuming at this point that buffer precalculated for any resampling if (!(fbufnum < 0)) { unit->m_frame = unit->m_frame + 1; BeatTrack_dofft(unit, (uint32)fbufnum); } // test if impulse to output unit->m_phase += unit->m_phaseperblock; // if not locked, update output phase from model phase, else keep a separate output phase float lock = ZIN0(1); // printf("lock %f \n",lock); if (lock < 0.5f) { unit->m_outputphase = unit->m_phase; unit->m_outputtempo = unit->m_currtempo; unit->m_outputphaseperblock = unit->m_phaseperblock; } else unit->m_outputphase += unit->m_outputphaseperblock; if (unit->m_phase >= 1.f) unit->m_phase -= 1.f; // 0 is beat, 1 is quaver, 2 is semiquaver, 3 is actual current tempo in bps // so no audio accuracy with beats, just asap, may as well be control rate ZOUT0(0) = 0.0; ZOUT0(1) = 0.0; ZOUT0(2) = 0.0; ZOUT0(3) = unit->m_outputtempo; //*0.016666667; // output beat if (unit->m_outputphase >= 1.f) { // printf("beat \n"); unit->m_outputphase -= 1.f; ZOUT0(0) = 1.0; ZOUT0(1) = 1.0; ZOUT0(2) = 1.0; unit->halftrig = 0; unit->q1trig = 0; unit->q2trig = 0; } if (unit->m_outputphase >= 0.5f && unit->halftrig == 0) { ZOUT0(1) = 1.0; ZOUT0(2) = 1.0; unit->halftrig = 1; } if (unit->m_outputphase >= 0.25f && unit->q1trig == 0) { ZOUT0(2) = 1.0; unit->q1trig = 1; } if (unit->m_outputphase >= 0.75f && unit->q2trig == 0) { ZOUT0(2) = 1.0; unit->q2trig = 1; } } // // calculation function once FFT data ready void BeatTrack_dofft(BeatTrack* unit, uint32 ibufnum) { World* world = unit->mWorld; SndBuf* buf; if (ibufnum >= world->mNumSndBufs) { int localBufNum = ibufnum - world->mNumSndBufs; Graph* parent = unit->mParent; if (localBufNum <= parent->localBufNum) { buf = parent->mLocalSndBufs + localBufNum; } else { buf = world->mSndBufs; } } else { buf = world->mSndBufs + ibufnum; } LOCK_SNDBUF(buf); // int numbins = buf->samples - 2 >> 1; unit->m_FFTBuf = buf->data; // just assign it! // transfer data to fftbuf in the format expected by this plugin // ideally, should do this part separate to plug-in as well, so can compare different detection functions; // also, can run multiple in parallel with own autocorrelations; committee? Committee.ar(period1, phase1, period2, // phase2, period3, phase3)... chooses predominant estimate? feature detection function complexdf(unit); if (unit->m_frame % SKIP == 0) { // printf("amortisation time \n"); // amortisation- 8 control periods in a frame // have 2000 calcs to do, split over 100 control periods = 6400 samples, ie one tempo per control period unit->m_bestcolumn = 0; unit->m_besttorsum = -1000.0; unit->m_bestphasescore = -1000.0; unit->m_bestphase = 0; // state 0 is do nothing unit->m_amortisationstate = 1; unit->m_amortcount = 0; unit->m_amortlength = 128; unit->m_amortisationsteps = 0; // fix time reference for calculations, so it doesn't update during the amortisation- this is the beginning of // the df frame unit->m_storedfcounter = unit->m_dfcounter + DFSTORE - DFFRAMELENGTH; // ref for phase calculations unit->m_storedfcounterend = unit->m_dfcounter; // unit->m_fftstoreposhold= unit->m_fftstorepos; unit->m_currphase = unit->m_phase; } } void autocorr(BeatTrack* unit, int j) { int baseframe = unit->m_storedfcounter + DFSTORE; float* df = unit->m_df; float* acf = unit->m_acf; // work out four lags each time for (int k = 0; k < 4; ++k) { int lag = 4 * j + k; int correction = abs(lag - DFFRAMELENGTH); float sum = 0.0; for (int i = lag; i < DFFRAMELENGTH; ++i) { float val1 = df[(i + baseframe) % DFSTORE]; float val2 = df[(i + baseframe - lag) % DFSTORE]; sum += val1 * val2; } acf[lag] = sum * correction; } } // timesig 4 has one more sum term // indices as MATLAB but need to correct maxinds to be in range of tested, not in global range float findtor(BeatTrack* unit) { float maxval, val; int ind2, ind3, ind4; // put into MATLAB indexing, from 1 to 512 int ind = unit->m_bestcolumn + 1; float* acf = unit->m_acf - 1; ind2 = 0; maxval = -1000; for (int i = 2 * ind - 1; i <= (2 * ind + 1); ++i) { val = acf[i]; if (val > maxval) { maxval = val; ind2 = i - (2 * ind - 1) + 1; } } //[val2,ind2] = max(acf(2*ind-1:2*ind+1)); ind2 = ind2 + 2 * (ind + 1) - 2; ind3 = 0; maxval = -1000; for (int i = 3 * ind - 2; i <= (3 * ind + 2); ++i) { val = acf[i]; if (val > maxval) { maxval = val; ind3 = i - (3 * ind - 2) + 1; } } //[val3,ind3] = max(acf(3*ind-2:3*ind+2)); ind3 = ind3 + 3 * ind - 4; float period; if (unit->m_timesig == 4) { ind4 = 0; maxval = -1000; for (int i = 4 * ind - 3; i <= 4 * ind + 3; ++i) { val = acf[i]; if (val > maxval) { maxval = val; ind4 = i - (4 * ind - 3) + 1; } } //[val4,ind4] = max(acf(4*ind-3:4*ind+3)); ind4 = ind4 + 4 * ind - 9; period = (ind + ind2 * 0.5 + ind3 / 3.f + ind4 * 0.25) * 0.25; } else period = (ind + ind2 * 0.5 + ind3 / 3.f) * 0.3333333; // printf("period %f ind %d ind2 %d ind3 %d ind4 %d \n",period, ind,ind2,ind3,ind4); // unit->m_tor=period; // unit->m_torround= int(period+0.5); // return period; } // 128 calculation calls for multiplying M and acf, calculates M as it goes apart from precalculated Gaussian or Raleigh // distribution void beatperiod(BeatTrack* unit, int j, int whichm) { float* acf = unit->m_acf; // int startindex= 512*j; // int endindex=startindex+512; float sum = 0.0; // unit->m_timesig harmonics for (int i = 1; i <= (unit->m_timesig); ++i) { int num = 2 * i - 1; float wt = 1.0 / (float)num; for (int k = 0; k < num; ++k) { int pos = k + (i * j); // m[startindex+pos] if (pos < 512) sum += acf[pos] * wt; } } // assumes Mg appropriately rotated already float* m; if (whichm) m = g_m; // Gaussian weighted context model else m = unit->m_mg; // general model even weighting sum = sum * m[j]; if (sum > unit->m_besttorsum) { unit->m_besttorsum = sum; unit->m_bestcolumn = j; } } // j out of unit->m_torround // differs to Davies original in that weight the most recent events more- want minimum reaction time void findphase(BeatTrack* unit, int j, int gaussflag, int predicted) { float* df = unit->m_df; int period = unit->m_torround; int baseframe = unit->m_storedfcounterend + DFSTORE; int numfit = -1; if (period != 0) // round down numfit = (int)(DFFRAMELENGTH / period) - 1; // testing backwards from the baseframe, weighting goes down as 1/k float sum = 0.0; for (int k = 0; k < numfit; ++k) { // j is phase to test int location = (baseframe - (period * k) - j) % DFSTORE; sum += df[location] / ((float)(k + 1)); } // Gaussian focus weighting if desired if (gaussflag) { // difference of predicted from j, min distance within period int diff = sc_min(abs(predicted - j), abs(period - predicted + j)); sum *= unit->m_phaseweights[diff]; } if (sum > unit->m_bestphasescore) { unit->m_bestphasescore = sum; unit->m_bestphase = j; } } //, int predicted void setupphaseexpectation(BeatTrack* unit) // create Gaussian focussed matrix for phase { float* wts = unit->m_phaseweights; float sigma = unit->m_torround * 0.25f; // float mu=period; float mult = 1.0 / (2.5066283 * sigma); float mult2 = 1.0 / (2.0 * sigma * sigma); // unit->m_torround for (int i = 0; i < 128; ++i) { wts[i] = mult * (exp(-(i * i) * mult2)); } } // why force a countdown each time? Why not keep a continuous buffer of previous periodp, periodg? int detectperiodchange(BeatTrack* unit) { // stepthresh = 3.9017; if (unit->m_flagstep == 0) { if (fabs(unit->m_periodg - unit->m_periodp) > 3.9017f) { unit->m_flagstep = 3; } } else { unit->m_flagstep = unit->m_flagstep - 1; } if (unit->m_flagstep) { unit->m_prevperiodp[unit->m_flagstep - 1] = unit->m_periodp; } if (unit->m_flagstep == 1) { unit->m_flagstep = 0; if (fabs(2 * unit->m_prevperiodp[0] - unit->m_prevperiodp[1] - unit->m_prevperiodp[2]) < 7.8034f) //(2*3.9017) return 1; } return 0; } // add test void findmeter(BeatTrack* unit) { // int i; // float * acf= unit->m_acf; // float * acf= unit->m_acf-1; // // // int period = ((int)(unit->m_periodp+0.5)); // // float three_energy=0.0; // float four_energy=0.0; // // for(i=(3*period-2);i<(3*period+3);++i) // three_energy += acf[i]; // // for(i=(4*period-2);i<(4*period+3);++i) // four_energy += acf[i]; // // if((6*period+2)<512) { // // for(i=(6*period-2);i<(6*period+3);++i) // three_energy += acf[i]; // // for(i=(2*period-2);i<(2*period+3);++i) // four_energy += acf[i]; // } // // if (three_energy > four_energy) // unit->m_timesig = 3; // else // worked better in evaluation without any 3/4 at all! unit->m_timesig = 4; // printf("time sig %d \n",unit->m_timesig); } // period is unit->m_tor, phase is unit->m_bestphase // float m_tor; int m_torround; void finaldecision(BeatTrack* unit) { // int i,j; unit->m_currtempo = 1.0 / (unit->m_tor * unit->m_frameperiod); unit->m_phaseperblock = ((float)unit->mWorld->mFullRate.mBufLength * (unit->m_currtempo)) / ((float)unit->mWorld->mSampleRate); // printf("SAMPLErate %f %f %f", unit->mWorld->mSampleRate,unit->m_phaseperblock,unit->m_currtempo); // unit->m_amortisationstate control periods worth = 512/64 = 8 // float frameselapsed= 0.125*unit->m_amortisationstate; // float timeelapsed= frameselapsed*unit->m_frameperiod; float timeelapsed = ((float)(unit->m_amortisationsteps) * (unit->mWorld->mFullRate.mBufLength) / ((float)unit->mWorld->mSampleRate)); timeelapsed += 7 * unit->m_frameperiod; // compensation for detection function being delayed by 7 frames float phaseelapsed = timeelapsed * (unit->m_currtempo); float phasebeforeamort = ((float)unit->m_bestphase / unit->m_torround); // add phase to compensate for ELAPSEDTIME unit->m_currphase = unit->m_phase = fmod(phasebeforeamort + phaseelapsed, (float)1.0); } // Now the format is standardised for the SC FFT UGen as // dc, nyquist and then real/imag pairs for each bin going up successively in frequency void complexdf(BeatTrack* unit) { float* fftbuf = unit->m_FFTBuf; float* prevmag = unit->m_prevmag; float* prevphase = unit->m_prevphase; float* predict = unit->m_predict; float sum = 0.0; // printf("complex df time \n"); // sum bins 2 to 256 for (int k = 1; k < NOVER2; ++k) { // Change to fftw int index = 2 * k; // k; //2*k; float real = fftbuf[index]; // N=1024 conventionally here float imag = fftbuf[index + 1]; // fftbuf[N-index]; float mag = sqrt( real * real + imag * imag); // was 0.5*sqrt(real*real+ imag*imag); reduce by factor of 2 because of altivec side effect float qmag = prevmag[k]; prevmag[k] = mag; float phase = atan2(imag, real); float oldphase = predict[k]; predict[k] = 2 * phase - prevphase[k]; prevphase[k] = phase; float phasediff = phase - oldphase; // if(k==2) printf("%f %f\n",phase, phasediff); // tables for cos/sin/sqrt speeds up? sqrt(1-c*c) slower than sin float realpart = (qmag - (mag * cos(phasediff))); float imagpart = (mag * sin(phasediff)); // no need for negative float detect = sqrt(realpart * realpart + imagpart * imagpart); // detect is always positive // if(k==1) sum += detect; //(fmod(phase+(16*pi),twopi)); //detect; // if(k==1) sum+=mag; } // smoothing and peak picking operation, delay of 8 frames, must be taken account of in final phase correction unit->m_dfmemorycounter = (unit->m_dfmemorycounter + 1) % 15; unit->m_dfmemory[unit->m_dfmemorycounter] = sum; // divide by num of bands to get a dB answer float rating = 0.0; float* dfmemory = unit->m_dfmemory; int refpos = unit->m_dfmemorycounter + 15; int centrepos = (refpos - 7) % 15; float centreval = dfmemory[centrepos]; for (int k = 0; k < 15; ++k) { int pos = (refpos - k) % 15; float nextval = centreval - dfmemory[pos]; if (nextval < 0.0) nextval = nextval * 10; rating += nextval; } if (rating < 0.0) rating = 0.0; // increment first so this frame is unit->m_loudnesscounterdfcounter unit->m_dfcounter = (unit->m_dfcounter + 1) % DFSTORE; unit->m_df[unit->m_dfcounter] = rating * 0.1f; // sum //divide by num of bands to get a dB answer }
28,276
C++
.cpp
640
37.385938
120
0.621789
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,961
NoiseUGens.cpp
supercollider_supercollider/server/plugins/NoiseUGens.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "SC_PlugIn.h" static InterfaceTable* ft; struct WhiteNoise : public Unit {}; struct ClipNoise : public Unit {}; struct BrownNoise : public Unit { float mLevel; }; struct PinkNoise : public Unit { uint32 mDice[16]; int32 mTotal; }; struct Dust : public Unit { float m_density, m_thresh, m_scale; }; struct Dust2 : public Unit { float m_density, m_thresh, m_scale; }; struct GrayNoise : public Unit { int32 mCounter; }; struct Crackle : public Unit { double m_y1, m_y2; }; struct Logistic : public Unit { double m_y1; int mCounter; }; struct Hasher : public Unit {}; struct MantissaMask : public Unit {}; struct IRand : public Unit {}; struct Rand : public Unit {}; struct TRand : public Unit { float m_trig, m_value; }; struct TIRand : public Unit { float m_trig, m_value; }; struct TExpRand : public Unit { float m_trig, m_value; }; struct NRand : public Unit {}; struct LinRand : public Unit {}; struct ExpRand : public Unit {}; struct CoinGate : public Unit { float m_trig; }; struct LFClipNoise : public Unit { float mLevel; int mCounter; }; struct LFNoise0 : public Unit { float mLevel; int mCounter; }; struct LFNoise1 : public Unit { float mLevel, mSlope; int mCounter; }; struct LFNoise2 : public Unit { float mLevel, mSlope, mCurve; float m_nextvalue, m_nextmidpt; int mCounter; }; struct RandSeed : public Unit { float m_trig; }; struct RandID : public Unit { float m_id; }; ////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" { void WhiteNoise_next(WhiteNoise* unit, int inNumSamples); void WhiteNoise_Ctor(WhiteNoise* unit); void GrayNoise_next(GrayNoise* unit, int inNumSamples); void GrayNoise_Ctor(GrayNoise* unit); void ClipNoise_next(ClipNoise* unit, int inNumSamples); void ClipNoise_Ctor(ClipNoise* unit); void PinkNoise_next(PinkNoise* unit, int inNumSamples); void PinkNoise_Ctor(PinkNoise* unit); void BrownNoise_next(BrownNoise* unit, int inNumSamples); void BrownNoise_Ctor(BrownNoise* unit); void Dust_next(Dust* unit, int inNumSamples); void Dust_Ctor(Dust* unit); void Dust2_next(Dust2* unit, int inNumSamples); void Dust2_Ctor(Dust2* unit); void Crackle_next(Crackle* unit, int inNumSamples); void Crackle_Ctor(Crackle* unit); void Hasher_next(Hasher* unit, int inNumSamples); void Hasher_Ctor(Hasher* unit); void MantissaMask_next(MantissaMask* unit, int inNumSamples); void MantissaMask_Ctor(MantissaMask* unit); void IRand_Ctor(IRand* unit); void Rand_Ctor(Rand* unit); void LinRand_Ctor(LinRand* unit); void NRand_Ctor(NRand* unit); void ExpRand_Ctor(ExpRand* unit); void CoinGate_Ctor(CoinGate* unit); void CoinGate_next_k(CoinGate* unit, int inNumSamples); void CoinGate_next(CoinGate* unit, int inNumSamples); void TIRand_next_a(TIRand* unit, int inNumSamples); void TIRand_next_k(TIRand* unit, int inNumSamples); void TIRand_Ctor(TIRand* unit); void TRand_next_a(TRand* unit, int inNumSamples); void TRand_next_k(TRand* unit, int inNumSamples); void TRand_Ctor(TRand* unit); void TExpRand_next_a(TExpRand* unit, int inNumSamples); void TExpRand_next_k(TExpRand* unit, int inNumSamples); void TExpRand_Ctor(TExpRand* unit); void Logistic_next_1(Logistic* unit, int inNumSamples); void Logistic_next_k(Logistic* unit, int inNumSamples); void Logistic_Ctor(Logistic* unit); void LFClipNoise_next(LFClipNoise* unit, int inNumSamples); void LFClipNoise_Ctor(LFClipNoise* unit); void LFNoise0_next(LFNoise0* unit, int inNumSamples); void LFNoise0_Ctor(LFNoise0* unit); void LFNoise1_next(LFNoise1* unit, int inNumSamples); void LFNoise1_Ctor(LFNoise1* unit); void LFNoise2_next(LFNoise2* unit, int inNumSamples); void LFNoise2_Ctor(LFNoise2* unit); void RandSeed_next(RandSeed* unit, int inNumSamples); void RandSeed_next_k(RandSeed* unit, int inNumSamples); void RandSeed_Ctor(RandSeed* unit); void RandID_next(RandID* unit, int inNumSamples); void RandID_Ctor(RandID* unit); } ////////////////////////////////////////////////////////////////////////////////////////////////// void ClipNoise_next(ClipNoise* unit, int inNumSamples) { float* out = ZOUT(0); RGET LOOP1(inNumSamples, ZXP(out) = fcoin(s1, s2, s3);); RPUT } void ClipNoise_Ctor(ClipNoise* unit) { SETCALC(ClipNoise_next); ClipNoise_next(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// void GrayNoise_next(GrayNoise* unit, int inNumSamples) { float* out = ZOUT(0); RGET int counter = unit->mCounter; LOOP1(inNumSamples, counter ^= 1L << (trand(s1, s2, s3) & 31); ZXP(out) = counter * 4.65661287308e-10f;); unit->mCounter = counter; RPUT } void GrayNoise_Ctor(GrayNoise* unit) { SETCALC(GrayNoise_next); unit->mCounter = 0; GrayNoise_next(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// void WhiteNoise_next(WhiteNoise* unit, int inNumSamples) { float* out = ZOUT(0); RGET LOOP1(inNumSamples, ZXP(out) = frand2(s1, s2, s3);); RPUT } void WhiteNoise_Ctor(WhiteNoise* unit) { SETCALC(WhiteNoise_next); WhiteNoise_next(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// void PinkNoise_next(PinkNoise* unit, int inNumSamples) { float* out = ZOUT(0); RGET uint32 total = unit->mTotal; uint32* dice = unit->mDice; LOOP1(inNumSamples, uint32 counter = trand(s1, s2, s3); // Magnus Jonsson's suggestion. uint32 newrand = counter >> 13; int k = (CTZ(counter)) & 15; uint32 prevrand = dice[k]; dice[k] = newrand; total += (newrand - prevrand); newrand = trand(s1, s2, s3) >> 13; elem32 val; // ensure write before read <sk> val.u = (total + newrand) | 0x40000000; ZXP(out) = val.f - 3.0f; counter++;); unit->mTotal = total; RPUT } void PinkNoise_Ctor(PinkNoise* unit) { SETCALC(PinkNoise_next); RGET uint32* dice = unit->mDice; int32 total = 0; for (int i = 0; i < 16; ++i) { uint32 newrand = trand(s1, s2, s3) >> 13; total += newrand; dice[i] = newrand; } unit->mTotal = total; RPUT PinkNoise_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void BrownNoise_next(BrownNoise* unit, int inNumSamples) { float* out = ZOUT(0); RGET float z = unit->mLevel; LOOP1(inNumSamples, z += frand8(s1, s2, s3); if (z > 1.f) z = 2.f - z; else if (z < -1.f) z = -2.f - z; ZXP(out) = z;); unit->mLevel = z; RPUT } void BrownNoise_Ctor(BrownNoise* unit) { SETCALC(BrownNoise_next); unit->mLevel = unit->mParent->mRGen->frand2(); ZOUT0(0) = unit->mLevel; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Dust_Ctor(Dust* unit) { SETCALC(Dust_next); unit->m_density = 0.f; unit->m_scale = 0.f; unit->m_thresh = 0.f; Dust_next(unit, 1); } void Dust_next(Dust* unit, int inNumSamples) { float* out = ZOUT(0); float density = ZIN0(0); float thresh, scale; RGET if (density != unit->m_density) { thresh = unit->m_thresh = density * unit->mRate->mSampleDur; scale = unit->m_scale = thresh > 0.f ? 1.f / thresh : 0.f; unit->m_density = density; } else { thresh = unit->m_thresh; scale = unit->m_scale; } LOOP1(inNumSamples, float z = frand(s1, s2, s3); if (z < thresh) ZXP(out) = z * scale; else ZXP(out) = 0.f;); RPUT } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Dust2_Ctor(Dust2* unit) { SETCALC(Dust2_next); unit->m_density = 0.f; unit->m_scale = 0.f; unit->m_thresh = 0.f; Dust2_next(unit, 1); } void Dust2_next(Dust2* unit, int inNumSamples) { float* out = ZOUT(0); float density = ZIN0(0); float thresh, scale; RGET if (density != unit->m_density) { thresh = unit->m_thresh = density * unit->mRate->mSampleDur; scale = unit->m_scale = thresh > 0.f ? 2.f / thresh : 0.f; unit->m_density = density; } else { thresh = unit->m_thresh; scale = unit->m_scale; } LOOP1(inNumSamples, float z = frand(s1, s2, s3); if (z < thresh) ZXP(out) = z * scale - 1.f; else ZXP(out) = 0.f;); RPUT } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Crackle_next(Crackle* unit, int inNumSamples) { float* out = ZOUT(0); float paramf = ZIN0(0); float y1 = unit->m_y1; float y2 = unit->m_y2; float y0; LOOP1(inNumSamples, ZXP(out) = y0 = fabs(y1 * paramf - y2 - 0.05f); y2 = y1; y1 = y0;); unit->m_y1 = y1; unit->m_y2 = y2; } void Crackle_Ctor(Crackle* unit) { SETCALC(Crackle_next); unit->m_y1 = unit->mParent->mRGen->drand(); unit->m_y2 = 0.f; Crackle_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Logistic_next_1(Logistic* unit, int inNumSamples) { float* out = ZOUT(0); double paramf = ZIN0(0); double y1 = unit->m_y1; LOOP1(inNumSamples, ZXP(out) = y1 = paramf * y1 * (1.0 - y1); // chaotic equation ); unit->m_y1 = y1; } void Logistic_next_k(Logistic* unit, int inNumSamples) { float* out = ZOUT(0); double paramf = ZIN0(0); float freq = ZIN0(1); double y1 = unit->m_y1; int32 counter = unit->mCounter; long remain = inNumSamples; do { if (counter <= 0) { counter = (int32)(unit->mRate->mSampleRate / sc_max(freq, .001f)); counter = sc_max(1, counter); y1 = paramf * y1 * (1.0 - y1); // chaotic equation } long nsmps = sc_min(counter, remain); counter -= nsmps; remain -= nsmps; LOOP(nsmps, ZXP(out) = y1;); } while (remain); unit->m_y1 = y1; unit->mCounter = counter; } void Logistic_Ctor(Logistic* unit) { if (INRATE(0) == calc_ScalarRate && ZIN0(1) >= unit->mRate->mSampleRate) SETCALC(Logistic_next_1); else SETCALC(Logistic_next_k); unit->m_y1 = ZIN0(2); unit->mCounter = 0; Logistic_next_1(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Rand_Ctor(Rand* unit) { float lo = ZIN0(0); float hi = ZIN0(1); float range = hi - lo; RGen& rgen = *unit->mParent->mRGen; ZOUT0(0) = rgen.frand() * range + lo; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void TRand_next_k(TRand* unit, int inNumSamples) { float trig = ZIN0(2); if (trig > 0.f && unit->m_trig <= 0.f) { float lo = ZIN0(0); float hi = ZIN0(1); float range = hi - lo; RGen& rgen = *unit->mParent->mRGen; ZOUT0(0) = unit->m_value = rgen.frand() * range + lo; } else { ZOUT0(0) = unit->m_value; } unit->m_trig = trig; } void TRand_next_a(TRand* unit, int inNumSamples) { float lo = ZIN0(0); float hi = ZIN0(1); float* trig = ZIN(2); float* out = ZOUT(0); float prev = unit->m_trig; float outval = unit->m_value; float next; LOOP1( inNumSamples, next = ZXP(trig); if (next > 0.f && prev <= 0.f) { float range = hi - lo; RGen& rgen = *unit->mParent->mRGen; ZXP(out) = outval = rgen.frand() * range + lo; } else { ZXP(out) = outval; }; prev = next;) unit->m_trig = next; unit->m_value = outval; } void TRand_next_aa(TRand* unit, int inNumSamples) { float* lo = ZIN(0); float* hi = ZIN(1); float* trig = ZIN(2); float* out = ZOUT(0); float prev = unit->m_trig; float outval = unit->m_value; float next; LOOP1( inNumSamples, next = ZXP(trig); float loval = ZXP(lo); float hival = ZXP(hi); if (next > 0.f && prev <= 0.f) { RGen& rgen = *unit->mParent->mRGen; float range = hival - loval; ZXP(out) = outval = rgen.frand() * range + loval; } else { ZXP(out) = outval; }; prev = next;) unit->m_trig = next; unit->m_value = outval; } void TRand_Ctor(TRand* unit) { float lo = ZIN0(0); float hi = ZIN0(1); float range = hi - lo; RGen& rgen = *unit->mParent->mRGen; ZOUT0(0) = unit->m_value = rgen.frand() * range + lo; if (unit->mCalcRate == calc_FullRate) { if (INRATE(0) == calc_FullRate) { SETCALC(TRand_next_aa); } else { SETCALC(TRand_next_a); } } else { SETCALC(TRand_next_k); } unit->m_trig = ZIN0(2); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void TExpRand_next_k(TExpRand* unit, int inNumSamples) { float trig = ZIN0(2); if (trig > 0.f && unit->m_trig <= 0.f) { float lo = ZIN0(0); float hi = ZIN0(1); float ratio = hi / lo; RGen& rgen = *unit->mParent->mRGen; ZOUT0(0) = unit->m_value = pow(ratio, rgen.frand()) * lo; } else { ZOUT0(0) = unit->m_value; } unit->m_trig = trig; } void TExpRand_next_a(TExpRand* unit, int inNumSamples) { float lo = ZIN0(0); float hi = ZIN0(1); float* trig = ZIN(2); float* out = ZOUT(0); float prev = unit->m_trig; float outval = unit->m_value; float next; LOOP1( inNumSamples, next = ZXP(trig); if (next > 0.f && prev <= 0.f) { float ratio = hi / lo; RGen& rgen = *unit->mParent->mRGen; ZXP(out) = outval = pow(ratio, rgen.frand()) * lo; } else { ZXP(out) = outval; }) unit->m_trig = next; unit->m_value = outval; } void TExpRand_next_aa(TExpRand* unit, int inNumSamples) { float* lo = ZIN(0); float* hi = ZIN(1); float* trig = ZIN(2); float* out = ZOUT(0); float prev = unit->m_trig; float outval = unit->m_value; float next; LOOP1( inNumSamples, next = ZXP(trig); float loval = ZXP(lo); float hival = ZXP(hi); if (next > 0.f && prev <= 0.f) { float ratio = hival / loval; RGen& rgen = *unit->mParent->mRGen; ZXP(out) = outval = pow(ratio, rgen.frand()) * loval; } else { ZXP(out) = outval; }) unit->m_trig = next; unit->m_value = outval; } void TExpRand_Ctor(TExpRand* unit) { float lo = ZIN0(0); float hi = ZIN0(1); float ratio = hi / lo; RGen& rgen = *unit->mParent->mRGen; ZOUT0(0) = unit->m_value = pow(ratio, rgen.frand()) * lo; if (unit->mCalcRate == calc_FullRate) { if (INRATE(0) == calc_FullRate) { SETCALC(TExpRand_next_aa); } else { SETCALC(TExpRand_next_a); } } else { SETCALC(TExpRand_next_k); } unit->m_trig = ZIN0(2); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void IRand_Ctor(IRand* unit) { int lo = (int)ZIN0(0); int hi = (int)ZIN0(1); int range = hi - lo + 1; RGen& rgen = *unit->mParent->mRGen; ZOUT0(0) = (float)(rgen.irand(range) + lo); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void TIRand_next_k(TIRand* unit, int inNumSamples) { float trig = ZIN0(2); if (trig > 0.f && unit->m_trig <= 0.f) { int lo = (int)ZIN0(0); int hi = (int)ZIN0(1); int range = hi - lo + 1; RGen& rgen = *unit->mParent->mRGen; ZOUT0(0) = unit->m_value = (float)(rgen.irand(range) + lo); } else { ZOUT0(0) = unit->m_value; } unit->m_trig = trig; } void TIRand_next_a(TIRand* unit, int inNumSamples) { int lo = (int)ZIN0(0); int hi = (int)ZIN0(1); float* trig = ZIN(2); float* out = ZOUT(0); float prev = unit->m_trig; float outval = unit->m_value; float next; LOOP1( inNumSamples, next = ZXP(trig); if (next > 0.f && prev <= 0.f) { int range = hi - lo + 1; RGen& rgen = *unit->mParent->mRGen; ZXP(out) = outval = (float)(rgen.irand(range) + lo); } else { ZXP(out) = outval; }) unit->m_trig = next; unit->m_value = outval; } void TIRand_next_aa(TIRand* unit, int inNumSamples) { float* lo = ZIN(0); float* hi = ZIN(1); float* trig = ZIN(2); float prev = unit->m_trig; float* out = ZOUT(0); float outval = unit->m_value; float next; LOOP1( inNumSamples, next = ZXP(trig); int loval = (int)ZXP(lo); int hival = (int)ZXP(hi); if (next > 0.f && prev <= 0.f) { int range = hival - loval + 1; RGen& rgen = *unit->mParent->mRGen; ZXP(out) = outval = (float)(rgen.irand(range) + loval); } else { ZXP(out) = outval; }) unit->m_trig = next; unit->m_value = outval; } void TIRand_Ctor(TIRand* unit) { int lo = (int)ZIN0(0); int hi = (int)ZIN0(1); int range = hi - lo + 1; RGen& rgen = *unit->mParent->mRGen; ZOUT0(0) = unit->m_value = (float)(rgen.irand(range) + lo); if (unit->mCalcRate == calc_FullRate) { if (INRATE(0) == calc_FullRate) { SETCALC(TIRand_next_aa); } else { SETCALC(TIRand_next_a); } } else { SETCALC(TIRand_next_k); } unit->m_trig = ZIN0(2); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void CoinGate_Ctor(CoinGate* unit) { if (unit->mCalcRate == calc_FullRate) { SETCALC(CoinGate_next); } else { SETCALC(CoinGate_next_k); } unit->m_trig = ZIN0(1); ClearUnitOutputs(unit, 1); } void CoinGate_next_k(CoinGate* unit, int inNumSamples) { float trig = ZIN0(1); float level = 0.f; RGen& rgen = *unit->mParent->mRGen; if (trig > 0.f && unit->m_trig <= 0.f) { if (rgen.frand() < ZIN0(0)) { level = trig; } } ZOUT0(0) = level; unit->m_trig = trig; } void CoinGate_next(CoinGate* unit, int inNumSamples) { float* trig = ZIN(1); float* out = ZOUT(0); float prevtrig = unit->m_trig; float probability = ZIN0(0); RGen& rgen = *unit->mParent->mRGen; LOOP1( inNumSamples, float curtrig = ZXP(trig); float level = 0.f; if (prevtrig <= 0.f && curtrig > 0.f) { if (rgen.frand() < probability) { level = curtrig; } else { level = 0.f; } } prevtrig = curtrig; ZXP(out) = level;) unit->m_trig = prevtrig; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void RandSeed_Ctor(RandSeed* unit) { unit->m_trig = 0.; if (unit->mCalcRate == calc_FullRate) { SETCALC(RandSeed_next); } else { SETCALC(RandSeed_next_k); } RandSeed_next(unit, 1); } void RandSeed_next_k(RandSeed* unit, int inNumSamples) { float trig = ZIN0(0); if (trig > 0.f && unit->m_trig <= 0.f) { RGen& rgen = *unit->mParent->mRGen; int seed = (int)DEMANDINPUT_A(1, inNumSamples); rgen.init(seed); } unit->m_trig = trig; ZOUT0(0) = 0.f; } void RandSeed_next(RandSeed* unit, int inNumSamples) { float* trig = ZIN(0); float* out = ZOUT(0); float prevtrig = unit->m_trig; float curtrig; LOOP1( inNumSamples, curtrig = ZXP(trig); if (curtrig > 0.f && prevtrig <= 0.f) { RGen& rgen = *unit->mParent->mRGen; int seed = (int)DEMANDINPUT_A(1, inNumSamples); rgen.init(seed); } prevtrig = curtrig; ZXP(out) = 0.f; ) unit->m_trig = curtrig; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void RandID_Ctor(RandID* unit) { unit->m_id = -1.; SETCALC(RandID_next); RandID_next(unit, 1); } void RandID_next(RandID* unit, int inNumSamples) { float id = ZIN0(0); if (id != unit->m_id) { unit->m_id = id; uint32 iid = (uint32)id; if (iid < unit->mWorld->mNumRGens) { unit->mParent->mRGen = unit->mWorld->mRGen + iid; } } ZOUT0(0) = 0.f; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void LinRand_Ctor(LinRand* unit) { float lo = ZIN0(0); float hi = ZIN0(1); int n = (int)ZIN0(2); float range = hi - lo; RGen& rgen = *unit->mParent->mRGen; float a, b; a = rgen.frand(); b = rgen.frand(); if (n <= 0) { ZOUT0(0) = sc_min(a, b) * range + lo; } else { ZOUT0(0) = sc_max(a, b) * range + lo; } } //////////////////////////////////////////////////////////////////////////////////////////////////////// void NRand_Ctor(NRand* unit) { float lo = ZIN0(0); float hi = ZIN0(1); int n = (int)ZIN0(2); float range = hi - lo; RGen& rgen = *unit->mParent->mRGen; float sum = 0; for (int i = 0; i < n; ++i) { sum += rgen.frand(); } ZOUT0(0) = (sum / n) * range + lo; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void ExpRand_Ctor(ExpRand* unit) { float lo = ZIN0(0); float hi = ZIN0(1); float ratio = hi / lo; ZOUT0(0) = pow(ratio, unit->mParent->mRGen->frand()) * lo; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Hasher_next(Hasher* unit, int inNumSamples) { int32* in = (int32*)ZIN(0); float* out = ZOUT(0); LOOP1( inNumSamples, union { float f; int i; } u; int z = ZXP(in); u.i = 0x40000000 | ((uint32)Hash(z) >> 9); ZXP(out) = u.f - 3.f;); } void Hasher_Ctor(Hasher* unit) { SETCALC(Hasher_next); Hasher_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void MantissaMask_next(MantissaMask* unit, int inNumSamples) { int32* in = (int32*)ZIN(0); int32 bits = (int32)ZIN0(1); int32* out = (int32*)ZOUT(0); int32 mask = -1 << (23 - bits); LOOP1(inNumSamples, ZXP(out) = mask & ZXP(in);); } void MantissaMask_Ctor(MantissaMask* unit) { SETCALC(MantissaMask_next); MantissaMask_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void LFClipNoise_next(LFClipNoise* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); float level = unit->mLevel; int32 counter = unit->mCounter; RGET int remain = inNumSamples; do { if (counter <= 0) { counter = (int)(unit->mRate->mSampleRate / sc_max(freq, .001f)); counter = sc_max(1, counter); level = fcoin(s1, s2, s3); } int nsmps = sc_min(remain, counter); remain -= nsmps; counter -= nsmps; LOOP(nsmps, ZXP(out) = level;); } while (remain); unit->mLevel = level; unit->mCounter = counter; RPUT } void LFClipNoise_Ctor(LFClipNoise* unit) { SETCALC(LFClipNoise_next); unit->mCounter = 0; unit->mLevel = 0.f; LFClipNoise_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void LFNoise0_next(LFNoise0* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); float level = unit->mLevel; int32 counter = unit->mCounter; RGET int remain = inNumSamples; do { if (counter <= 0) { counter = (int32)(unit->mRate->mSampleRate / sc_max(freq, .001f)); counter = sc_max(1, counter); level = frand2(s1, s2, s3); } int nsmps = sc_min(remain, counter); remain -= nsmps; counter -= nsmps; LOOP(nsmps, ZXP(out) = level;); } while (remain); unit->mLevel = level; unit->mCounter = counter; RPUT } void LFNoise0_next_1(LFNoise0* unit, int inNumSamples) { assert(inNumSamples == 1); float freq = ZIN0(0); float level = unit->mLevel; int32 counter = unit->mCounter; if (counter <= 0) { counter = (int32)(unit->mRate->mSampleRate / sc_max(freq, .001f)); counter = sc_max(1, counter); RGET level = frand2(s1, s2, s3); unit->mLevel = level; RPUT } ZOUT0(0) = level; counter -= 1; unit->mCounter = counter; } void LFNoise0_Ctor(LFNoise0* unit) { if (BUFLENGTH == 1) SETCALC(LFNoise0_next_1); else SETCALC(LFNoise0_next); unit->mCounter = 0; unit->mLevel = 0.f; LFNoise0_next_1(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void LFNoise1_next(LFNoise1* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); float level = unit->mLevel; float slope = unit->mSlope; int32 counter = unit->mCounter; RGET int remain = inNumSamples; do { if (counter <= 0) { counter = (int32)(unit->mRate->mSampleRate / sc_max(freq, .001f)); counter = sc_max(1, counter); float nextlevel = frand2(s1, s2, s3); slope = (nextlevel - level) / counter; } int nsmps = sc_min(remain, counter); remain -= nsmps; counter -= nsmps; LOOP(nsmps, ZXP(out) = level; level += slope;); } while (remain); unit->mLevel = level; unit->mSlope = slope; unit->mCounter = counter; RPUT } void LFNoise1_Ctor(LFNoise1* unit) { SETCALC(LFNoise1_next); unit->mCounter = 0; unit->mLevel = unit->mParent->mRGen->frand2(); unit->mSlope = 0.f; LFNoise1_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void LFNoise2_next(LFNoise2* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); float level = unit->mLevel; float slope = unit->mSlope; float curve = unit->mCurve; int counter = unit->mCounter; RGET int remain = inNumSamples; do { if (counter <= 0) { float value = unit->m_nextvalue; unit->m_nextvalue = frand2(s1, s2, s3); level = unit->m_nextmidpt; unit->m_nextmidpt = (unit->m_nextvalue + value) * .5; counter = (int32)(unit->mRate->mSampleRate / sc_max(freq, .001f)); counter = sc_max(2, counter); float fseglen = (float)counter; curve = 2.f * (unit->m_nextmidpt - level - fseglen * slope) / (fseglen * fseglen + fseglen); } int nsmps = sc_min(remain, counter); remain -= nsmps; counter -= nsmps; LOOP(nsmps, ZXP(out) = level; slope += curve; level += slope;); } while (remain); unit->mLevel = level; unit->mSlope = slope; unit->mCurve = curve; unit->mCounter = counter; RPUT } void LFNoise2_Ctor(LFNoise2* unit) { SETCALC(LFNoise2_next); unit->mCounter = 0; unit->mSlope = 0.f; unit->mLevel = 0.f; unit->m_nextvalue = unit->mParent->mRGen->frand2(); unit->m_nextmidpt = unit->m_nextvalue * .5f; LFNoise2_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void WrapBufRd_next0(Unit* unit, int inNumSamples); void WrapBufRd_next0(Unit* unit, int inNumSamples) { int bufnum = (int)ZIN0(0); float* pos = ZIN(1); const SndBuf* buf = unit->mWorld->mSndBufs + bufnum; int numchan = buf->channels; LOCK_SNDBUF_SHARED(buf); if (numchan != unit->mNumOutputs) { ClearUnitOutputs(unit, inNumSamples); return; } const float* data = buf->data; int numframes = buf->frames; float* out[16]; for (int i = 0; i < numchan; ++i) out[i] = OUT(i); LOOP1( inNumSamples, float fpos = ZXP(pos); int ipos = (int)fpos * numchan; ipos = sc_mod(ipos, numframes); int index = numchan * ipos; for (int i = 0; i < numchan; ++i) { *++(out[i]) = data[index]; index++; }); } void ClipBufRd_next0(Unit* unit, int inNumSamples); void ClipBufRd_next0(Unit* unit, int inNumSamples) { int bufnum = (int)ZIN0(0); float* pos = ZIN(1); const SndBuf* buf = unit->mWorld->mSndBufs + bufnum; LOCK_SNDBUF_SHARED(buf); int numchan = buf->channels; if (numchan != unit->mNumOutputs) { ClearUnitOutputs(unit, inNumSamples); return; } const float* data = buf->data; int numframes = buf->frames; int maxframe = numframes - 2; float* out[16]; for (int i = 0; i < numchan; ++i) out[i] = OUT(i); LOOP1( inNumSamples, float fpos = ZXP(pos); int ipos = (int)fpos * numchan; ipos = sc_clip(ipos, 0, maxframe); int index = numchan * ipos; for (int i = 0; i < numchan; ++i) { *++(out[i]) = data[index]; index++; }); } //////////////////////////////////////////////////////////////////////////////////////////////////////// PluginLoad(Noise) { ft = inTable; DefineSimpleUnit(WhiteNoise); DefineSimpleUnit(GrayNoise); DefineSimpleUnit(ClipNoise); DefineSimpleUnit(PinkNoise); DefineSimpleUnit(BrownNoise); DefineSimpleUnit(Dust); DefineSimpleUnit(Dust2); DefineSimpleUnit(Crackle); DefineSimpleUnit(Logistic); DefineSimpleUnit(Hasher); DefineSimpleUnit(MantissaMask); DefineSimpleUnit(LFClipNoise); DefineSimpleUnit(LFNoise0); DefineSimpleUnit(LFNoise1); DefineSimpleUnit(LFNoise2); DefineSimpleUnit(Rand); DefineSimpleUnit(IRand); DefineSimpleUnit(TRand); DefineSimpleUnit(TExpRand); DefineSimpleUnit(TIRand); DefineSimpleUnit(NRand); DefineSimpleUnit(LinRand); DefineSimpleUnit(ExpRand); DefineSimpleUnit(CoinGate); DefineSimpleUnit(RandSeed); DefineSimpleUnit(RandID); } ////////////////////////////////////////////////////////////////////////////////////////////////////////
31,347
C++
.cpp
923
28.60455
120
0.544455
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,963
BeatTrack2.cpp
supercollider_supercollider/server/plugins/BeatTrack2.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // BeatTrack2 UGen implemented by Nick Collins (http://www.informatics.sussex.ac.uk/users/nc81/) // 6 Nov 2007 #include "ML.h" // need to add bestgroove option to store groove, else remove output which is currently always straight 16ths static const int g_numtempi = 120; static float g_periods[g_numtempi] = { 1, 0.98360655737705, 0.96774193548387, 0.95238095238095, 0.9375, 0.92307692307692, 0.90909090909091, 0.8955223880597, 0.88235294117647, 0.8695652173913, 0.85714285714286, 0.84507042253521, 0.83333333333333, 0.82191780821918, 0.81081081081081, 0.8, 0.78947368421053, 0.77922077922078, 0.76923076923077, 0.75949367088608, 0.75, 0.74074074074074, 0.73170731707317, 0.72289156626506, 0.71428571428571, 0.70588235294118, 0.69767441860465, 0.68965517241379, 0.68181818181818, 0.67415730337079, 0.66666666666667, 0.65934065934066, 0.65217391304348, 0.64516129032258, 0.63829787234043, 0.63157894736842, 0.625, 0.61855670103093, 0.61224489795918, 0.60606060606061, 0.6, 0.59405940594059, 0.58823529411765, 0.58252427184466, 0.57692307692308, 0.57142857142857, 0.56603773584906, 0.5607476635514, 0.55555555555556, 0.55045871559633, 0.54545454545455, 0.54054054054054, 0.53571428571429, 0.53097345132743, 0.52631578947368, 0.52173913043478, 0.51724137931034, 0.51282051282051, 0.50847457627119, 0.50420168067227, 0.5, 0.49586776859504, 0.49180327868852, 0.48780487804878, 0.48387096774194, 0.48, 0.47619047619048, 0.47244094488189, 0.46875, 0.46511627906977, 0.46153846153846, 0.45801526717557, 0.45454545454545, 0.45112781954887, 0.44776119402985, 0.44444444444444, 0.44117647058824, 0.43795620437956, 0.43478260869565, 0.43165467625899, 0.42857142857143, 0.42553191489362, 0.42253521126761, 0.41958041958042, 0.41666666666667, 0.41379310344828, 0.41095890410959, 0.40816326530612, 0.40540540540541, 0.40268456375839, 0.4, 0.39735099337748, 0.39473684210526, 0.3921568627451, 0.38961038961039, 0.38709677419355, 0.38461538461538, 0.38216560509554, 0.37974683544304, 0.37735849056604, 0.375, 0.37267080745342, 0.37037037037037, 0.3680981595092, 0.36585365853659, 0.36363636363636, 0.36144578313253, 0.35928143712575, 0.35714285714286, 0.35502958579882, 0.35294117647059, 0.35087719298246, 0.34883720930233, 0.34682080924855, 0.3448275862069, 0.34285714285714, 0.34090909090909, 0.33898305084746, 0.33707865168539, 0.33519553072626 }; // float g_tempoweight[g_numtempi]= { 0.8, 0.82581988897472, 0.83651483716701, 0.84472135955, 0.85163977794943, // 0.85773502691896, 0.86324555320337, 0.8683130051064, 0.87302967433402, 0.87745966692415, 0.88164965809277, // 0.88563488385777, 0.88944271909999, 0.89309493362513, 0.89660917830793, 0.9, 0.90327955589886, 0.90645812948448, // 0.90954451150103, 0.91254628677423, 0.91547005383793, 0.91832159566199, 0.9211060141639, 0.92382783747338, // 0.92649110640674, 0.92909944487358, 0.93165611772088, 0.93416407864999, 0.93662601021279, 0.93904435743076, // 0.94142135623731, 0.94375905768565, 0.94605934866804, 0.94832396974191, 0.95055453054182, 0.95275252316519, // 0.9549193338483, 0.95705625319186, 0.95916448515084, 0.96124515496597, 0.96329931618555, 0.96532795690183, // 0.96733200530682, 0.969312334656, 0.97126976771554, 0.97320508075689, 0.97511900715418, 0.97701224063136, // 0.97888543819998, 0.98073922282301, 0.98257418583506, 0.98439088914586, 0.98618986725025, 0.98797162906496, // 0.9897366596101, 0.99148542155127, 0.99321835661586, 0.99493588689618, 0.99663841605004, 0.99832633040858, 1, // 0.99832633040858, 0.99663841605004, 0.99493588689618, 0.99321835661586, 0.99148542155127, 0.9897366596101, // 0.98797162906496, 0.98618986725025, 0.98439088914586, 0.98257418583506, 0.98073922282301, 0.97888543819998, // 0.97701224063136, 0.97511900715418, 0.97320508075689, 0.97126976771554, 0.969312334656, 0.96733200530682, // 0.96532795690183, 0.96329931618555, 0.96124515496597, 0.95916448515084, 0.95705625319186, 0.9549193338483, // 0.95275252316519, 0.95055453054182, 0.94832396974191, 0.94605934866804, 0.94375905768565, 0.94142135623731, // 0.93904435743076, 0.93662601021279, 0.93416407864999, 0.93165611772088, 0.92909944487358, 0.92649110640674, // 0.92382783747338, 0.9211060141639, 0.91832159566199, 0.91547005383793, 0.91254628677423, 0.90954451150103, // 0.90645812948448, 0.90327955589886, 0.9, 0.89660917830793, 0.89309493362513, 0.88944271909999, 0.88563488385777, // 0.88164965809277, 0.87745966692415, 0.87302967433402, 0.8683130051064, 0.86324555320337, 0.85773502691896, // 0.85163977794943, 0.84472135955, 0.83651483716701, 0.82581988897472 }; const float g_groove = 0.32; static float g_sep[8] = { 0.0, 0.25, 0.5, 0.75, 0.0, 0.32, 0.5, 0.82 }; // weight for particular step static float g_weight[4] = { 1.0, 0.5, 0.9, 0.6 }; // weight for blurring feature envelope locally static float g_weight2[9] = { 0.05, 0.1, 0.3, 0.7, 1.0, 0.7, 0.3, 0.1, 0.05 }; // void BeatTrack2_dofft(BeatTrack2 *unit, uint32); static void calculatetemplate(BeatTrack2* unit, int which, int j); static void finaldecision(BeatTrack2* unit); void BeatTrack2_Ctor(BeatTrack2* unit) { // unit->m_srate = unit->mWorld->mFullRate.mSampleRate; float kblocklength = unit->mWorld->mFullRate.mBufDuration; // seconds per control block unit->m_krlength = kblocklength; // N features per block over numphases*2 variants for one of 120 tempi, so need at least 120 blocks to complete unit->m_phaseaccuracy = ZIN0(3); // 0.02; //20 msec resolution; could be argument of UGen unit->m_pastfeatures = nullptr; unit->m_scores = unit->bestscore = nullptr; unit->bestphase = unit->besttempo = unit->bestgroove = nullptr; unit->m_numphases = (int*)RTAlloc(unit->mWorld, g_numtempi * sizeof(int)); ClearUnitIfMemFailed(unit->m_numphases); // unit->m_phases = (float**)RTAlloc(unit->mWorld, g_numtempi * sizeof(float*)); for (int j = 0; j < g_numtempi; ++j) { float period = g_periods[j]; int num = (int)(period / unit->m_phaseaccuracy); // maximum will be 1.0/0.02 = 50 unit->m_numphases[j] = num; // // unit->m_phases[j]= (float*)RTAlloc(unit->mWorld, unit->m_numphases[j] * sizeof(float)); // // float phase=0.0; // // for (i=0; i<num; ++i) { // unit->m_phases[j][i] = phase; // phase += unit->m_phaseaccuracy; // } } unit->m_numfeatures = (int)(ZIN0(1) + 0.001); // for efficiency unit->m_scores = (float*)RTAlloc(unit->mWorld, (2 * unit->m_numfeatures) * sizeof(float)); ClearUnitIfMemFailed(unit->m_scores); unit->m_temporalwindowsize = ZIN0(2); // typically small, 2 seconds for fast reactions compared to 6 secs for BeatTrack unit->m_fullwindowsize = unit->m_temporalwindowsize + 1.0 + 0.1; // plus one to cover all phases of the 60bpm based period, and a further 0.1 for indexing safety; ie // looking at areas around the point you're interested in unit->m_buffersize = (int)(unit->m_fullwindowsize / unit->m_krlength); // in control blocks // printf("loading test blocklength %f numfeatures %d temporal %f full %f blocks %d \n",unit->m_krlength, // unit->m_numfeatures, unit->m_temporalwindowsize, unit->m_fullwindowsize, unit->m_buffersize); // float ** m_pastfeatures; //for each feature, a trail of last m_workingmemorysize values unit->m_pastfeatures = (float**)RTAlloc(unit->mWorld, unit->m_numfeatures * sizeof(float*)); ClearUnitIfMemFailed(unit->m_pastfeatures); memset(unit->m_pastfeatures, 0, unit->m_numfeatures * sizeof(float*)); for (int j = 0; j < unit->m_numfeatures; ++j) { unit->m_pastfeatures[j] = (float*)RTAlloc(unit->mWorld, unit->m_buffersize * sizeof(float)); ClearUnitIfMemFailed(unit->m_pastfeatures[j]); Clear(unit->m_buffersize, unit->m_pastfeatures[j]); // set all to zero at first // for (i=0; i<unit->m_buffersize; ++i) { // unit->m_pastfeatures[j][i] = 0.0; // } // } // main counter unit->m_counter = 0; // could avoid allocation by having a hard limit on unit->bestscore = (float*)RTAlloc(unit->mWorld, 4 * unit->m_numfeatures * sizeof(float)); unit->bestphase = (int*)RTAlloc(unit->mWorld, 4 * unit->m_numfeatures * sizeof(int)); unit->besttempo = (int*)RTAlloc(unit->mWorld, 4 * unit->m_numfeatures * sizeof(int)); unit->bestgroove = (int*)RTAlloc(unit->mWorld, 4 * unit->m_numfeatures * sizeof(int)); ClearUnitIfMemFailed(unit->bestscore && unit->bestphase && unit->besttempo && unit->bestgroove); for (int i = 0; i < 4; ++i) { int basepos = i * unit->m_numfeatures; for (int j = 0; j < unit->m_numfeatures; ++j) { unit->bestscore[basepos + j] = -9999.0; unit->bestphase[basepos + j] = 0; unit->besttempo[basepos + j] = 60; unit->bestgroove[basepos + j] = 0; } } unit->m_phase = 0.0; unit->m_period = 0.5; unit->m_groove = 0; unit->m_currtempo = 2; unit->m_phaseperblock = unit->m_krlength / unit->m_period; unit->m_predictphase = 0.4f; unit->m_predictperiod = 0.3f; unit->m_outputphase = unit->m_phase; unit->m_outputtempo = unit->m_currtempo; unit->m_outputgroove = unit->m_groove; unit->m_outputphaseperblock = unit->m_phaseperblock; unit->m_calculationperiod = 0.5; // every half second; could also be additional argument to UGen unit->m_calculationschedule = 0.0; // printf("srate %f conversion factor %f frame period %f \n", unit->m_srate, unit->m_srateconversion, // unit->m_frameperiod); int bufnum = (int)(ZIN0(5) + 0.001f); if (bufnum >= unit->mWorld->mNumSndBufs) bufnum = 0; if (bufnum < 0) unit->m_weightingscheme = bufnum < 2 ? 0 : 1; else { SndBuf* buf = unit->mWorld->mSndBufs + bufnum; unit->m_tempoweights = buf; unit->m_weightingscheme = 2; } // printf("bufnum %d weightingscheme %d check %f %f\n", bufnum, unit->m_weightingscheme, unit->m_tempoweights[0], // unit->m_tempoweights[119]); unit->halftrig = 0; unit->q1trig = 0; unit->q2trig = 0; unit->mCalcFunc = (UnitCalcFunc)&BeatTrack2_next; // initialize outputs ZOUT0(0) = 0.0; ZOUT0(1) = 0.0; ZOUT0(2) = 0.0; ZOUT0(3) = unit->m_outputtempo; ZOUT0(4) = unit->m_outputphase; ZOUT0(5) = unit->m_outputgroove; } void BeatTrack2_Dtor(BeatTrack2* unit) { RTFree(unit->mWorld, unit->m_numphases); RTFree(unit->mWorld, unit->m_scores); RTFree(unit->mWorld, unit->bestscore); RTFree(unit->mWorld, unit->bestphase); RTFree(unit->mWorld, unit->besttempo); RTFree(unit->mWorld, unit->bestgroove); if (unit->m_pastfeatures) { for (int j = 0; j < unit->m_numfeatures; ++j) { RTFree(unit->mWorld, unit->m_pastfeatures[j]); } RTFree(unit->mWorld, unit->m_pastfeatures); } } // over phases and for each groove void calculatetemplate(BeatTrack2* unit, int which, int j) { int tmpindex; int startcounter = unit->m_startcounter; int numphases = unit->m_numphases[which]; float period = g_periods[which]; float blockconvert = unit->m_krlength; float windowsize = unit->m_temporalwindowsize; int buffersize = unit->m_buffersize; // unit->m_fullwindowsize/unit->m_krlength; //in control blocks float** pastfeatures = unit->m_pastfeatures; // unit->m_pastfeatures = (float**)RTAlloc(unit->mWorld, unit->m_numfeatures * sizeof(float*)); int beatsfit = (int)(windowsize / period); // complete beats only, or also fit as many as possible? float weight; // compensation for number of events matched; may alter equation later switch (unit->m_weightingscheme) { case 0: weight = 1.0f; // flat break; case 1: weight = 1.0f / (beatsfit * 4); // compensate for number of time points tested break; case 2: SndBuf* buf = unit->m_tempoweights; if (buf->data) weight = buf->data[which]; // user defined temmpo biases (usually a mask on allowed tempi) else weight = 1.f; break; } int numfeatures = unit->m_numfeatures; float* scores = unit->m_scores; //[2*numfeatures]; float* bestscore = unit->bestscore; int* bestphase = unit->bestphase; int* besttempo = unit->besttempo; int* bestgroove = unit->bestgroove; for (int i = 0; i < numphases; ++i) { // initialise scores // for (j=0; j<2; ++j) for (int k = 0; k < numfeatures; ++k) scores[2 * k + j] = 0.0; float phaseadd = i * unit->m_phaseaccuracy; // calculation for a particular phase of template // for (j=0; j<2; ++j) { for (int h = 0; h < beatsfit; ++h) { for (int l = 0; l < 4; ++l) { float sep = phaseadd + (h * period) + ((g_sep[j * 4 + l]) * period); float weight = g_weight[l]; int blocks = (int)((sep / blockconvert) + 0.5); // round to nearest // convert sep to control periods and find appropriate point in source data int index = (startcounter + buffersize - blocks) % (buffersize); // widen over four either side for (int m = (-4); m < 5; ++m) { int actualindex = (index + buffersize + m) % (buffersize); for (int k = 0; k < numfeatures; ++k) { int scoreindexnow = 2 * k + j; // could widen this value here, even based on cubic interpolation etc scores[scoreindexnow] += weight * (g_weight2[m + 4]) * (pastfeatures[k][actualindex]); } // scores[2*k+j] += weight * (pastfeatures[k][index]); } } } //} // update any winners from scores // for (j=0; j<2; ++j) { for (int k = 0; k < numfeatures; ++k) { float scorenow = (scores[2 * k + j]) * weight; // NEED TO STORE J IF PRESERVING SENSE OF GROOVE if (scorenow > bestscore[k]) { tmpindex = numfeatures + k; // shift up to make room bestscore[tmpindex] = bestscore[k]; bestphase[tmpindex] = bestphase[k]; besttempo[tmpindex] = besttempo[k]; bestgroove[tmpindex] = bestgroove[k]; bestscore[k] = scorenow; bestphase[k] = i; besttempo[k] = which; bestgroove[k] = j; // printf("bestscore %f bestphase %d besttempo %d bestgroove %d \n", // bestscore[k],bestphase[k],besttempo[k], bestgroove[k]); } else if (scorenow > bestscore[numfeatures + k]) { tmpindex = numfeatures + k; bestscore[tmpindex] = scorenow; bestphase[tmpindex] = i; besttempo[tmpindex] = which; bestgroove[tmpindex] = j; } } //} } } // a winner must appear at least twice, across features, and be superior to the secondbest in those features too by some // margins a consistency check could also run to look at change from last time to this void finaldecision(BeatTrack2* unit) { // int foundgood = 0; int bestcandidate = 0; int bestpreviousmatchsum = 0; //(-1); //should be 0, but allowing different for now float excess; //, consistency; // int exactmatches, closematches; //can be out by a few indices on period; could match on tempo but // not phase etc combine these four factors in one overall score? for (int i = 0; i < unit->m_numfeatures; ++i) { int matchsum = 0; float secondbest = unit->bestscore[unit->m_numfeatures + i]; excess = (secondbest != 0) ? (unit->bestscore[i] / secondbest) : unit->bestscore[i]; int tempo = unit->besttempo[i]; // could check consistency too by looking at phase update from last prediction in same feature for (int j = 0; j < unit->m_numfeatures; ++j) { if (j != i) { if (abs(unit->besttempo[j] - tempo) < 5) matchsum++; } // check over all previous features if (abs(unit->besttempo[2 * unit->m_numfeatures + j] - tempo) < 5) matchsum++; } // printf("i %d matchsum %d excess %f \n",i, matchsum, excess); if (secondbest != 0) matchsum += (int)excess; // so must have at least one match //&& (excess>1.03) if ((matchsum > bestpreviousmatchsum)) { bestcandidate = i; bestpreviousmatchsum = matchsum; // foundgood = 1; } } // consistency: could require it to win twice; have a candidatepending which makes a phase prediction; only let // through if prediction fulfilled // unit->m_amortlength will be numtempi *2 = 240 float bestphase = fmod(((unit->bestphase[bestcandidate] * unit->m_phaseaccuracy) + (unit->m_krlength * (unit->m_amortlength))) / (unit->m_period), (float)1.0); // if(unit->m_prediction) { if ((fabs(bestphase - unit->m_predictphase) < ((2 * (unit->m_phaseaccuracy)) / unit->m_predictperiod)) && (fabs((g_periods[unit->besttempo[bestcandidate]]) - unit->m_predictperiod) < 0.04)) { unit->m_period = unit->m_predictperiod; // time elapsed since a known beat is phase of winner in seconds, to calculation start point, plus time for // calculation (120 control blocks) divided by period, modulo 1.0 unit->m_phase = bestphase; unit->m_currtempo = 1.f / unit->m_period; unit->m_phaseperblock = unit->m_krlength / unit->m_period; } //} // unit->m_prediction=false; // if(foundgood) { // if clear winner unit->m_predictperiod = g_periods[unit->besttempo[bestcandidate]]; // time elapsed since a known beat is phase of winner in seconds, to calculation start point, plus time for // calculation (120 control blocks) divided by period, modulo 1.0 unit->m_predictphase = fmod(((unit->bestphase[bestcandidate] * unit->m_phaseaccuracy) + (unit->m_krlength * (unit->m_amortlength)) + unit->m_calculationperiod) / (unit->m_period), (float)1.0); // if(foundgood) { ////if clear winner // // unit->m_period = g_periods[unit->besttempo[bestcandidate]]; ////time elapsed since a known beat is phase of winner in seconds, to calculation start point, plus time for /// calculation (120 control blocks) divided by period, modulo 1.0 // unit->m_phase= fmod( ((unit->bestphase[bestcandidate] * unit->m_phaseaccuracy) + (unit->m_krlength * // 120))/(unit->m_period), 1.0); // // unit->m_currtempo = 1.0/unit->m_period; // unit->m_phaseperblock = unit->m_krlength/unit->m_period; //} } void BeatTrack2_next(BeatTrack2* unit, int wrongNumSamples) { // keep updating feature memories unit->m_counter = (unit->m_counter + 1) % (unit->m_buffersize); int busnum = (int)(ZIN0(0) + 0.001f); // unit->m_features = unit->mWorld->mControlBus + busnum; float* features = unit->mWorld->mControlBus + busnum; // hmm, is this pointer guaranteed to stay the same? may have to update each time... for (int j = 0; j < unit->m_numfeatures; ++j) { unit->m_pastfeatures[j][unit->m_counter] = features[j]; // unit->m_features[j]; } unit->m_calculationschedule += unit->m_krlength; // check for new calculation round if (unit->m_calculationschedule > unit->m_calculationperiod) { unit->m_calculationschedule -= unit->m_calculationperiod; // reset best scores and move old to previous slots for (int i = 0; i < 2; ++i) { int pos1 = (2 + i) * unit->m_numfeatures; int pos2 = i * unit->m_numfeatures; for (int j = 0; j < unit->m_numfeatures; ++j) { unit->bestscore[pos1 + j] = unit->bestscore[pos2 + j]; unit->bestscore[pos2 + j] = -9999.0; unit->bestphase[pos1 + j] = unit->bestphase[pos2 + j]; unit->bestphase[pos2 + j] = 0; unit->besttempo[pos1 + j] = unit->besttempo[pos2 + j]; unit->besttempo[pos2 + j] = 60; } } // state 0 is do nothing unit->m_amortisationstate = 1; unit->m_amortcount = 0; unit->m_amortlength = g_numtempi * 2; // // unit->m_amortisationsteps=0; // store essential data unit->m_startcounter = unit->m_counter; unit->m_currphase = unit->m_phase; } // keeps incrementing but will be reset with each calculation run // unit->m_amortisationsteps=unit->m_amortisationsteps+1; // if state nonzero do something switch (unit->m_amortisationstate) { case 0: break; // do nothing case case 1: // calculate acf calculatetemplate(unit, unit->m_amortcount >> 1, unit->m_amortcount % 2); unit->m_amortcount = unit->m_amortcount + 1; if (unit->m_amortcount == unit->m_amortlength) { unit->m_amortisationstate = 2; // unit->m_amortlength=1; // unit->m_amortcount=0; } break; case 2: // done calculating template matches, now decide whether to follow through finaldecision(unit); unit->m_amortisationstate = 0; break; default: break; } // test if impulse to output unit->m_phase += unit->m_phaseperblock; // if(unit->m_counter%400==0) printf("phase %f period %f\n", unit->m_phase, unit->m_period); // if not locked, update output phase from model phase, else keep a separate output phase float lock = ZIN0(4); // printf("lock %f \n",lock); if (lock < 0.5f) { unit->m_outputphase = unit->m_phase; unit->m_outputtempo = unit->m_currtempo; unit->m_outputgroove = unit->m_groove; unit->m_outputphaseperblock = unit->m_phaseperblock; } else { unit->m_outputphase += unit->m_outputphaseperblock; } if (unit->m_phase >= 1.f) { unit->m_phase -= 1.f; } // 0 is beat, 1 is quaver, 2 is semiquaver, 3 is actual current tempo in bps // so no audio accuracy with beats, just asap, may as well be control rate ZOUT0(0) = 0.0; ZOUT0(1) = 0.0; ZOUT0(2) = 0.0; ZOUT0(3) = unit->m_outputtempo; //*0.016666667; ZOUT0(4) = unit->m_outputphase; ZOUT0(5) = unit->m_outputgroove; // output beat if (unit->m_outputphase >= 1.f) { // printf("beat \n"); unit->m_outputphase -= 1.f; ZOUT0(0) = 1.0; ZOUT0(1) = 1.0; ZOUT0(2) = 1.0; unit->halftrig = 0; unit->q1trig = 0; unit->q2trig = 0; } if (unit->m_outputphase >= 0.5 && unit->halftrig == 0) { ZOUT0(1) = 1.0; ZOUT0(2) = 1.0; unit->halftrig = 1; } float groove = unit->m_outputgroove * 0.07; if (unit->m_outputphase >= (0.25 + groove) && unit->q1trig == 0) { ZOUT0(2) = 1.0; unit->q1trig = 1; } if (unit->m_outputphase >= (0.75 + groove) && unit->q2trig == 0) { ZOUT0(2) = 1.0; unit->q2trig = 1; } }
29,013
C++
.cpp
565
36.59115
120
0.537592
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,964
UIUGens.cpp
supercollider_supercollider/server/plugins/UIUGens.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // ********** this version for windows and linux. for mac see UIUGens.mm #include <SC_Lock.h> #include <atomic> #ifndef _WIN32 # include <X11/Intrinsic.h> #else # include "SC_Win32Utils.h" # include <windows.h> #endif #include "SC_PlugIn.h" static InterfaceTable* ft; struct KeyboardUGenGlobalState { uint8 keys[32]; } gKeyStateGlobals; struct KeyState : public Unit { float m_y1, m_b1, m_lag; }; struct MouseUGenGlobalState { float mouseX, mouseY; bool mouseButton; } gMouseUGenGlobals; struct MouseInputUGen : public Unit { float m_y1, m_b1, m_lag; }; ////////////////////////////////////////////////////////////////////////////////////////////////// std::atomic_bool inputThreadRunning = { false }; #ifdef _WIN32 void gstate_update_func() { POINT p; int mButton; if (GetSystemMetrics(SM_SWAPBUTTON)) mButton = VK_RBUTTON; // if swapped else mButton = VK_LBUTTON; // not swapped (normal) int screenWidth = GetSystemMetrics(SM_CXSCREEN); int screenHeight = GetSystemMetrics(SM_CYSCREEN); // default: SM_CX/CYSCREEN gets the size of a primary screen. // lines uncommented below are just for a specially need on multi-display. // int screenWidth = GetSystemMetrics( SM_CXVIRTUALSCREEN ); // int screenHeight = GetSystemMetrics( SM_CYVIRTUALSCREEN ); float r_screenWidth = 1.f / (float)(screenWidth - 1); float r_screenHeight = 1.f / (float)(screenHeight - 1); while (inputThreadRunning.load(std::memory_order_relaxed)) { // "KeyState" is disabled for now, on Windows... // GetKey((long*)gstate->keys); GetCursorPos(&p); gMouseUGenGlobals.mouseX = (float)p.x * r_screenWidth; gMouseUGenGlobals.mouseY = 1.f - (float)p.y * r_screenHeight; gMouseUGenGlobals.mouseButton = (GetKeyState(mButton) < 0); std::this_thread::sleep_for(std::chrono::milliseconds(17)); } } #else static Display* d = 0; void gstate_update_func() { Window r; struct timespec requested_time, remaining_time; // NOTE: should not be required as this is the only thread accessing the x11 API // but omitting seems to cause troubles. XInitThreads(); d = XOpenDisplay(NULL); if (!d) return; Window rep_root, rep_child; XWindowAttributes attributes; int rep_rootx, rep_rooty; unsigned int rep_mask; int dx, dy; float r_width; float r_height; r = DefaultRootWindow(d); XGetWindowAttributes(d, r, &attributes); r_width = 1.0 / (float)attributes.width; r_height = 1.0 / (float)attributes.height; while (inputThreadRunning.load(std::memory_order_relaxed)) { XQueryKeymap(d, (char*)(gKeyStateGlobals.keys)); XQueryPointer(d, r, &rep_root, &rep_child, &rep_rootx, &rep_rooty, &dx, &dy, &rep_mask); gMouseUGenGlobals.mouseX = (float)dx * r_width; gMouseUGenGlobals.mouseY = 1.f - ((float)dy * r_height); gMouseUGenGlobals.mouseButton = (bool)(rep_mask & Button1Mask); std::this_thread::sleep_for(std::chrono::milliseconds(17)); } } #endif ////////////////////////////////////////////////////////////////////////////////////////////////// void KeyState_next(KeyState* unit, int inNumSamples) { // minval, maxval, warp, lag uint8* keys = (uint8*)gKeyStateGlobals.keys; int keynum = (int)ZIN0(0); int byte = (keynum >> 3) & 31; int bit = keynum & 7; int val = keys[byte] & (1 << bit); float minval = ZIN0(1); float maxval = ZIN0(2); float lag = ZIN0(3); float y1 = unit->m_y1; float b1 = unit->m_b1; if (lag != unit->m_lag) { unit->m_b1 = lag == 0.f ? 0.f : exp(log001 / (lag * unit->mRate->mSampleRate)); unit->m_lag = lag; } float y0 = val ? maxval : minval; ZOUT0(0) = y1 = y0 + b1 * (y1 - y0); unit->m_y1 = zapgremlins(y1); } void KeyState_Ctor(KeyState* unit) { SETCALC(KeyState_next); unit->m_b1 = 0.f; unit->m_lag = 0.f; KeyState_next(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// void MouseX_next(MouseInputUGen* unit, int inNumSamples) { // minval, maxval, warp, lag float minval = ZIN0(0); float maxval = ZIN0(1); float warp = ZIN0(2); float lag = ZIN0(3); float y1 = unit->m_y1; float b1 = unit->m_b1; if (lag != unit->m_lag) { unit->m_b1 = lag == 0.f ? 0.f : (float)exp(log001 / (lag * unit->mRate->mSampleRate)); unit->m_lag = lag; } float y0 = gMouseUGenGlobals.mouseX; if (warp == 0.0) { y0 = (maxval - minval) * y0 + minval; } else { y0 = pow(maxval / minval, y0) * minval; } ZOUT0(0) = y1 = y0 + b1 * (y1 - y0); unit->m_y1 = zapgremlins(y1); } void MouseX_Ctor(MouseInputUGen* unit) { SETCALC(MouseX_next); unit->m_b1 = 0.f; unit->m_lag = 0.f; MouseX_next(unit, 1); } void MouseY_next(MouseInputUGen* unit, int inNumSamples) { // minval, maxval, warp, lag float minval = ZIN0(0); float maxval = ZIN0(1); float warp = ZIN0(2); float lag = ZIN0(3); float y1 = unit->m_y1; float b1 = unit->m_b1; if (lag != unit->m_lag) { unit->m_b1 = lag == 0.f ? 0.f : (float)exp(log001 / (lag * unit->mRate->mSampleRate)); unit->m_lag = lag; } float y0 = gMouseUGenGlobals.mouseY; if (warp == 0.0) { y0 = (maxval - minval) * y0 + minval; } else { y0 = pow(maxval / minval, y0) * minval; } ZOUT0(0) = y1 = y0 + b1 * (y1 - y0); unit->m_y1 = zapgremlins(y1); } void MouseY_Ctor(MouseInputUGen* unit) { SETCALC(MouseY_next); unit->m_b1 = 0.f; unit->m_lag = 0.f; MouseY_next(unit, 1); } void MouseButton_next(MouseInputUGen* unit, int inNumSamples) { // minval, maxval, warp, lag float minval = ZIN0(0); float maxval = ZIN0(1); float lag = ZIN0(2); float y1 = unit->m_y1; float b1 = unit->m_b1; if (lag != unit->m_lag) { unit->m_b1 = lag == 0.f ? 0.f : (float)exp(log001 / (lag * unit->mRate->mSampleRate)); unit->m_lag = lag; } float y0 = gMouseUGenGlobals.mouseButton ? maxval : minval; ZOUT0(0) = y1 = y0 + b1 * (y1 - y0); unit->m_y1 = zapgremlins(y1); } void MouseButton_Ctor(MouseInputUGen* unit) { SETCALC(MouseButton_next); unit->m_b1 = 0.f; unit->m_lag = 0.f; MouseButton_next(unit, 1); } SC_Thread uiListenThread; PluginLoad(UIUGens) { ft = inTable; inputThreadRunning = true; uiListenThread = std::thread(gstate_update_func); DefineSimpleUnit(KeyState); DefineUnit("MouseX", sizeof(MouseInputUGen), (UnitCtorFunc)&MouseX_Ctor, 0, 0); DefineUnit("MouseY", sizeof(MouseInputUGen), (UnitCtorFunc)&MouseY_Ctor, 0, 0); DefineUnit("MouseButton", sizeof(MouseInputUGen), (UnitCtorFunc)&MouseButton_Ctor, 0, 0); } PluginUnload(UIUGens) { inputThreadRunning = false; uiListenThread.join(); #ifndef _WIN32 if (d) XCloseDisplay(d); #endif }
7,923
C++
.cpp
221
31.045249
98
0.623281
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,965
GendynUGens.cpp
supercollider_supercollider/server/plugins/GendynUGens.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // Gendyn UGens implemented by Nick Collins #include "SC_PlugIn.h" static InterfaceTable* ft; struct Gendy1 : public Unit // Iannis Xenakis/Marie-Helene Serra GENDYN simulation { double mPhase; float mFreqMul, mAmp, mNextAmp, mSpeed, mDur; int mMemorySize, mIndex; float* mMemoryAmp; // could hard code as 12 float* mMemoryDur; }; // following Hoffmann paper from CMJ- primary and secondary random walks struct Gendy2 : public Unit { double mPhase; float mFreqMul, mAmp, mNextAmp, mSpeed, mDur; int mMemorySize, mIndex; float* mMemoryAmp; float* mMemoryAmpStep; float* mMemoryDur; float* mMemoryDurStep; }; // Random walks as Gendy1 but works out all breakpoints per cycle and normalises time intervals to desired frequency struct Gendy3 : public Unit { double mPhase, mNextPhase, mLastPhase; float mSpeed, mFreqMul; float mAmp, mNextAmp, mInterpMult; int mMemorySize, mIndex; float* mMemoryAmp; float* mMemoryDur; double* mPhaseList; float* mAmpList; }; extern "C" { void Gendy1_next_k(Gendy1* unit, int inNumSamples); void Gendy1_Ctor(Gendy1* unit); void Gendy1_Dtor(Gendy1* unit); void Gendy2_next_k(Gendy2* unit, int inNumSamples); void Gendy2_Ctor(Gendy2* unit); void Gendy2_Dtor(Gendy2* unit); void Gendy3_next_k(Gendy3* unit, int inNumSamples); void Gendy3_Ctor(Gendy3* unit); void Gendy3_Dtor(Gendy3* unit); } void Gendy1_Ctor(Gendy1* unit) { SETCALC(Gendy1_next_k); unit->mFreqMul = unit->mRate->mSampleDur; unit->mPhase = 1.0; // should immediately decide on new target unit->mAmp = 0.0f; unit->mNextAmp = 0.0f; unit->mSpeed = 100.f; unit->mMemorySize = (int)ZIN0(8); // default is 12 // printf("memsize %d %f", unit->mMemorySize, ZIN0(8)); if (unit->mMemorySize < 1) unit->mMemorySize = 1; unit->mIndex = 0; unit->mMemoryAmp = (float*)RTAlloc(unit->mWorld, unit->mMemorySize * sizeof(float)); unit->mMemoryDur = (float*)RTAlloc(unit->mWorld, unit->mMemorySize * sizeof(float)); ClearUnitIfMemFailed(unit->mMemoryAmp && unit->mMemoryDur); RGen& rgen = *unit->mParent->mRGen; // initialise to zeroes and separations for (int i = 0; i < unit->mMemorySize; ++i) { unit->mMemoryAmp[i] = 2 * rgen.frand() - 1.0f; unit->mMemoryDur[i] = rgen.frand(); } // compute one sample of output to avoid sending garbage memory downstream to other Ctor functions // first sample of the _next output will be the current amplitude (which is 0) OUT0(0) = 0.0f; } void Gendy1_Dtor(Gendy1* unit) { RTFree(unit->mWorld, unit->mMemoryAmp); RTFree(unit->mWorld, unit->mMemoryDur); } // called once per period so OK to work out constants in here static float Gendyn_distribution(int which, float a, float f) { float temp, c; if (a > 1.f) a = 1.f; // a must be in range 0 to 1 if (a < 0.0001f) a = 0.0001f; // for safety with some distributions, don't want divide by zero errors switch (which) { case 0: // LINEAR // linear break; case 1: // CAUCHY // X has a*tan((z-0.5)*pi) // I went back to first principles of the Cauchy distribution and re-integrated with a // normalisation constant // choice of 10 here is such that f=0.95 gives about 0.35 for temp, could go with 2 to make it finer c = atan(10 * a); // PERHAPS CHANGE TO a=1/a; // incorrect- missed out divisor of pi in norm temp= a*tan(c*(2*pi*f - 1)); temp = (1.f / a) * tan(c * (2.f * f - 1.f)); // Cauchy distribution, C is precalculated // printf("cauchy f %f c %f temp %f out %f \n",f, c, temp, temp/10); return temp * 0.1f; //(temp+100)/200; case 2: // LOGIST (ic) // X has -(log((1-z)/z)+b)/a which is not very usable as is c = 0.5f + (0.499f * a); // calculate normalisation constant c = log((1.f - c) / c); // remap into range of valid inputs to avoid infinities in the log // f= ((f-0.5)*0.499*a)+0.5; f = ((f - 0.5f) * 0.998f * a) + 0.5f; //[0,1]->[0.001,0.999]; squashed around midpoint 0.5 by a // Xenakis calls this the LOGIST map, it's from the range [0,1] to [inf,0] where 0.5->1 // than take natural log. to avoid infinities in practise I take [0,1] -> [0.001,0.999]->[6.9,-6.9] // an interesting property is that 0.5-e is the reciprocal of 0.5+e under (1-f)/f // and hence the logs are the negative of each other temp = log((1.f - f) / f) / c; // n range [-1,1] // X also had two constants in his- I don't bother // printf("logist f %f temp %f\n", f, temp); return temp; // a*0.5*(temp+1.0); //to [0,1] case 3: // HYPERBCOS // X original a*log(tan(z*pi/2)) which is [0,1]->[0,pi/2]->[0,inf]->[-inf,inf] // unmanageable in this pure form c = tan(1.5692255f * a); // tan(0.999*a*pi*0.5); //[0, 636.6] maximum range temp = tan(1.5692255f * a * f) / c; //[0,1]->[0,1] temp = log(temp * 0.999f + 0.001f) * (-0.1447648f); // multiplier same as /(-6.9077553); //[0,1]->[0,1] // printf("hyperbcos f %f c %f temp %f\n", f, c, temp); return 2.f * temp - 1.0f; case 4: // ARCSINE // X original a/2*(1-sin((0.5-z)*pi)) aha almost a better behaved one though [0,1]->[2,0]->[a,0] c = sin(1.5707963f * a); // sin(pi*0.5*a); //a as scaling factor of domain of sine input to use temp = sin(pi_f * (f - 0.5f) * a) / c; //[-1,1] which is what I need // printf("arcsine f %f c %f temp %f\n", f, c, temp); return temp; case 5: // EXPON // X original -(log(1-z))/a [0,1]-> [1,0]-> [0,-inf]->[0,inf] c = log(1.f - (0.999f * a)); temp = log(1.f - (f * 0.999f * a)) / c; // printf("expon f %f c %f temp %f\n", f, c, temp); return 2.f * temp - 1.f; case 6: // SINUS // X original a*sin(smp * 2*pi/44100 * b) ie depends on a second oscillator's value- // hmmm, plug this in as a I guess, will automatically accept control rate inputs then! return 2.f * a - 1.f; default: break; } return 2.f * f - 1.f; } void Gendy1_next_k(Gendy1* unit, int inNumSamples) { float* out = ZOUT(0); // distribution choices for amp and dur and constants of distribution int whichamp = (int)ZIN0(0); int whichdur = (int)ZIN0(1); float aamp = ZIN0(2); float adur = ZIN0(3); float minfreq = ZIN0(4); float maxfreq = ZIN0(5); float scaleamp = ZIN0(6); float scaledur = ZIN0(7); float rate = unit->mDur; // phase gives proportion for linear interpolation automatically double phase = unit->mPhase; float amp = unit->mAmp; float nextamp = unit->mNextAmp; float speed = unit->mSpeed; RGen& rgen = *unit->mParent->mRGen; // linear distribution 0.0 to 1.0 using rgen.frand() LOOP1( inNumSamples, float z; if (phase >= 1.0) { phase -= 1.0; int index = unit->mIndex; int num = (int)(ZIN0(9)); //(unit->mMemorySize);(((int)ZIN0(9))%(unit->mMemorySize))+1; if ((num > (unit->mMemorySize)) || (num < 1)) num = unit->mMemorySize; // new code for indexing index = (index + 1) % num; amp = nextamp; unit->mIndex = index; // Gendy dist gives value [-1,1], then use scaleamp // first term was amp before, now must check new memory slot nextamp = (unit->mMemoryAmp[index]) + (scaleamp * Gendyn_distribution(whichamp, aamp, rgen.frand())); // mirroring for bounds- safe version if (nextamp > 1.0f || nextamp < -1.0f) { // printf("mirroring nextamp %f ", nextamp); // to force mirroring to be sensible if (nextamp < 0.0f) nextamp = nextamp + 4.f; nextamp = fmod(nextamp, 4.f); // printf("fmod %f ", nextamp); if (nextamp > 1.0f && nextamp < 3.f) nextamp = 2.f - nextamp; else if (nextamp > 1.0f) nextamp = nextamp - 4.f; // printf("mirrorednextamp %f \n", nextamp); }; unit->mMemoryAmp[index] = nextamp; // Gendy dist gives value [-1,1] rate = (unit->mMemoryDur[index]) + (scaledur * Gendyn_distribution(whichdur, adur, rgen.frand())); if (rate > 1.0f || rate < 0.0f) { if (rate < 0.0) rate = rate + 2.f; rate = fmod(rate, 2.0f); rate = 2.f - rate; } unit->mMemoryDur[index] = rate; // printf("nextamp %f rate %f \n", nextamp, rate); // define range of speeds (say between 20 and 1000 Hz) // can have bounds as fourth and fifth inputs speed = (minfreq + ((maxfreq - minfreq) * rate)) * (unit->mFreqMul); // if there are 12 control points in memory, that is 12 per cycle // the speed is multiplied by 12 //(I don't store this because updating rates must remain in range [0,1] speed *= num; } // linear interpolation could be changed z = ((1.0 - phase) * amp) + (phase * nextamp); phase += speed; ZXP(out) = z;); unit->mPhase = phase; unit->mAmp = amp; unit->mNextAmp = nextamp; unit->mSpeed = speed; unit->mDur = rate; } void Gendy2_Ctor(Gendy2* unit) { SETCALC(Gendy2_next_k); unit->mFreqMul = unit->mRate->mSampleDur; unit->mPhase = 1.0; // should immediately decide on new target unit->mAmp = 0.0f; unit->mNextAmp = 0.0f; unit->mSpeed = 100.f; unit->mMemorySize = (int)ZIN0(8); // default is 12 // printf("memsize %d %f", unit->mMemorySize, ZIN0(8)); if (unit->mMemorySize < 1) unit->mMemorySize = 1; unit->mIndex = 0; unit->mMemoryAmp = (float*)RTAlloc(unit->mWorld, unit->mMemorySize * sizeof(float)); unit->mMemoryDur = (float*)RTAlloc(unit->mWorld, unit->mMemorySize * sizeof(float)); unit->mMemoryAmpStep = (float*)RTAlloc(unit->mWorld, unit->mMemorySize * sizeof(float)); unit->mMemoryDurStep = (float*)RTAlloc(unit->mWorld, unit->mMemorySize * sizeof(float)); ClearUnitIfMemFailed(unit->mMemoryAmp && unit->mMemoryDur && unit->mMemoryAmpStep && unit->mMemoryDurStep); RGen& rgen = *unit->mParent->mRGen; // initialise to zeroes and separations for (int i = 0; i < unit->mMemorySize; ++i) { unit->mMemoryAmp[i] = 2 * rgen.frand() - 1.0f; unit->mMemoryDur[i] = rgen.frand(); unit->mMemoryAmpStep[i] = 2 * rgen.frand() - 1.0f; unit->mMemoryDurStep[i] = 2 * rgen.frand() - 1.0f; } // compute one sample of output to avoid sending garbage memory downstream to other Ctor functions // first sample of the _next output will be the current amplitude (which is 0) OUT0(0) = 0.0f; } void Gendy2_Dtor(Gendy2* unit) { RTFree(unit->mWorld, unit->mMemoryAmp); RTFree(unit->mWorld, unit->mMemoryDur); RTFree(unit->mWorld, unit->mMemoryAmpStep); RTFree(unit->mWorld, unit->mMemoryDurStep); } static float Gendyn_mirroring(float lower, float upper, float in) { // mirroring for bounds- safe version if (in > upper || in < lower) { float range = (upper - lower); if (in < lower) in = (2.0f * upper - lower) - in; in = fmod(in - upper, 2.0f * range); if (in < range) in = upper - in; else in = in - (range); } return in; } void Gendy2_next_k(Gendy2* unit, int inNumSamples) { float* out = ZOUT(0); // distribution choices for amp and dur and constants of distribution int whichamp = (int)ZIN0(0); int whichdur = (int)ZIN0(1); float aamp = ZIN0(2); float adur = ZIN0(3); float minfreq = ZIN0(4); float maxfreq = ZIN0(5); float scaleamp = ZIN0(6); float scaledur = ZIN0(7); float rate = unit->mDur; // phase gives proportion for linear interpolation automatically double phase = unit->mPhase; float amp = unit->mAmp; float nextamp = unit->mNextAmp; float speed = unit->mSpeed; RGen& rgen = *unit->mParent->mRGen; LOOP1( inNumSamples, float z; if (phase >= 1.0) { phase -= 1.0; int index = unit->mIndex; int num = (int)(ZIN0(9)); //(unit->mMemorySize);(((int)ZIN0(9))%(unit->mMemorySize))+1; if ((num > (unit->mMemorySize)) || (num < 1)) num = unit->mMemorySize; // new code for indexing index = (index + 1) % num; // using last amp value as seed // random values made using a lehmer number generator xenakis style float a = ZIN0(10); float c = ZIN0(11); float lehmerxen = fmod(((amp)*a) + c, 1.0f); // printf("lehmer %f \n", lehmerxen); amp = nextamp; unit->mIndex = index; // Gendy dist gives value [-1,1], then use scaleamp // first term was amp before, now must check new memory slot float ampstep = (unit->mMemoryAmpStep[index]) + Gendyn_distribution(whichamp, aamp, fabs(lehmerxen)); ampstep = Gendyn_mirroring(-1.0f, 1.0f, ampstep); unit->mMemoryAmpStep[index] = ampstep; nextamp = (unit->mMemoryAmp[index]) + (scaleamp * ampstep); nextamp = Gendyn_mirroring(-1.0f, 1.0f, nextamp); unit->mMemoryAmp[index] = nextamp; float durstep = (unit->mMemoryDurStep[index]) + Gendyn_distribution(whichdur, adur, rgen.frand()); durstep = Gendyn_mirroring(-1.0f, 1.0f, durstep); unit->mMemoryDurStep[index] = durstep; rate = (unit->mMemoryDur[index]) + (scaledur * durstep); rate = Gendyn_mirroring(0.0f, 1.0f, rate); unit->mMemoryDur[index] = rate; // printf("nextamp %f rate %f \n", nextamp, rate); // define range of speeds (say between 20 and 1000 Hz) // can have bounds as fourth and fifth inputs speed = (minfreq + ((maxfreq - minfreq) * rate)) * (unit->mFreqMul); // if there are 12 control points in memory, that is 12 per cycle // the speed is multiplied by 12 //(I don't store this because updating rates must remain in range [0,1] speed *= num; } // linear interpolation could be changed z = ((1.0 - phase) * amp) + (phase * nextamp); phase += speed; ZXP(out) = z;); unit->mPhase = phase; unit->mAmp = amp; unit->mNextAmp = nextamp; unit->mSpeed = speed; unit->mDur = rate; } void Gendy3_Ctor(Gendy3* unit) { SETCALC(Gendy3_next_k); unit->mFreqMul = unit->mRate->mSampleDur; unit->mPhase = 1.0; // should immediately decide on new target unit->mAmp = 0.0f; unit->mNextAmp = 0.0f; unit->mNextPhase = 0.0; unit->mLastPhase = 0.0; unit->mInterpMult = 1.0f; unit->mSpeed = 100.f; unit->mMemorySize = (int)ZIN0(7); if (unit->mMemorySize < 1) unit->mMemorySize = 1; unit->mIndex = 0; unit->mMemoryAmp = (float*)RTAlloc(unit->mWorld, unit->mMemorySize * sizeof(float)); unit->mMemoryDur = (float*)RTAlloc(unit->mWorld, unit->mMemorySize * sizeof(float)); // one more in amp list for guard (wrap) element unit->mAmpList = (float*)RTAlloc(unit->mWorld, (unit->mMemorySize + 1) * sizeof(float)); unit->mPhaseList = (double*)RTAlloc(unit->mWorld, (unit->mMemorySize + 1) * sizeof(double)); ClearUnitIfMemFailed(unit->mMemoryAmp && unit->mMemoryDur && unit->mAmpList && unit->mPhaseList); RGen& rgen = *unit->mParent->mRGen; // initialise to zeroes and separations for (int i = 0; i < unit->mMemorySize; ++i) { unit->mMemoryAmp[i] = 2 * rgen.frand() - 1.0f; unit->mMemoryDur[i] = rgen.frand(); unit->mAmpList[i] = 2 * rgen.frand() - 1.0f; unit->mPhaseList[i] = 1.0; // will be intialised immediately } unit->mMemoryAmp[0] = 0.0f; // always zeroed first BP // compute one sample of output to avoid sending garbage memory downstream to other Ctor functions // first sample of the _next output will be the current amplitude (which is 0) OUT0(0) = 0.0f; } void Gendy3_Dtor(Gendy3* unit) { RTFree(unit->mWorld, unit->mMemoryAmp); RTFree(unit->mWorld, unit->mMemoryDur); RTFree(unit->mWorld, unit->mAmpList); RTFree(unit->mWorld, unit->mPhaseList); } void Gendy3_next_k(Gendy3* unit, int inNumSamples) { float* out = ZOUT(0); // distribution choices for amp and dur and constants of distribution int whichamp = (int)ZIN0(0); int whichdur = (int)ZIN0(1); float aamp = ZIN0(2); float adur = ZIN0(3); float freq = ZIN0(4); float scaleamp = ZIN0(5); float scaledur = ZIN0(6); double phase = unit->mPhase; float amp = unit->mAmp; float nextamp = unit->mNextAmp; float speed = unit->mSpeed; int index = unit->mIndex; int interpmult = (int)unit->mInterpMult; double lastphase = unit->mLastPhase; double nextphase = unit->mNextPhase; RGen& rgen = *unit->mParent->mRGen; float* amplist = unit->mAmpList; double* phaselist = unit->mPhaseList; LOOP1( inNumSamples, float z; if (phase >= 1.) { // calculate all targets for new period phase -= 1.; int num = (int)(ZIN0(8)); if ((num > (unit->mMemorySize)) || (num < 1)) num = unit->mMemorySize; float dursum = 0.0f; float* memoryamp = unit->mMemoryAmp; float* memorydur = unit->mMemoryDur; for (int j = 0; j < num; ++j) { if (j > 0) { // first BP always stays at 0 float amp = (memoryamp[j]) + (scaleamp * Gendyn_distribution(whichamp, aamp, rgen.frand())); amp = Gendyn_mirroring(-1.0f, 1.0f, amp); memoryamp[j] = amp; } float dur = (memorydur[j]) + (scaledur * Gendyn_distribution(whichdur, adur, rgen.frand())); dur = Gendyn_mirroring(0.01f, 1.0f, dur); // will get normalised in a moment, don't allow zeroes memorydur[j] = dur; dursum += dur; } // normalising constant dursum = 1.f / dursum; int active = 0; // phase duration of a sample float minphase = unit->mFreqMul; speed = freq * minphase; // normalise and discard any too short (even first) for (int j = 0; j < num; ++j) { float dur = memorydur[j]; dur *= dursum; if (dur >= minphase) { amplist[active] = memoryamp[j]; phaselist[active] = dur; ++active; } } // add a zero on the end at active amplist[active] = 0.0f; // guard element phaselist[active] = 2.0; // safety element // lastphase=0.0; // nextphase= phaselist[0]; // amp=amplist[0]; // nextamp=amplist[1]; // index=0; // unit->mIndex=index; // // setup to trigger next block nextphase = 0.0; nextamp = amplist[0]; index = -1; } if (phase >= nextphase) { // are we into a new region? // new code for indexing ++index; //=index+1; //%num; amp = nextamp; unit->mIndex = index; lastphase = nextphase; nextphase = lastphase + phaselist[index]; nextamp = amplist[index + 1]; interpmult = (int)(1.0 / (nextphase - lastphase)); } float interp = (phase - lastphase) * interpmult; // linear interpolation could be changed z = ((1.0f - interp) * amp) + (interp * nextamp); phase += speed; ZXP(out) = z;); unit->mPhase = phase; unit->mSpeed = speed; unit->mInterpMult = interpmult; unit->mAmp = amp; unit->mNextAmp = nextamp; unit->mLastPhase = lastphase; unit->mNextPhase = nextphase; } PluginLoad(Gendyn) { ft = inTable; DefineDtorUnit(Gendy1); DefineDtorUnit(Gendy2); DefineDtorUnit(Gendy3); }
21,508
C++
.cpp
487
35.848049
116
0.589414
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,966
Loudness.cpp
supercollider_supercollider/server/plugins/Loudness.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // Nick Collins 8 Nov 2007 // loudness model #include "ML.h" // perhaps need to have sampling rate choice here: but then, double rate, double fft size, only use bottom 1024 again as // useful spectrum in human hearing range! So should just work? int eqlbandbins[43] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 13, 15, 17, 19, 22, 25, 28, 32, 36, 41, 46, 52, 58, 65, 73, 82, 92, 103, 116, 129, 144, 161, 180, 201, 225, 251, 280, 312, 348, 388, 433, 483, 513 }; int eqlbandsizes[42] = { 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 9, 10, 11, 13, 13, 15, 17, 19, 21, 24, 26, 29, 32, 36, 40, 45, 50, 29 }; // was 30 float contours[42][11] = { { 47.88, 59.68, 68.55, 75.48, 81.71, 87.54, 93.24, 98.84, 104.44, 109.94, 115.31 }, { 29.04, 41.78, 51.98, 60.18, 67.51, 74.54, 81.34, 87.97, 94.61, 101.21, 107.74 }, { 20.72, 32.83, 43.44, 52.18, 60.24, 67.89, 75.34, 82.70, 89.97, 97.23, 104.49 }, { 15.87, 27.14, 37.84, 46.94, 55.44, 63.57, 71.51, 79.34, 87.14, 94.97, 102.37 }, { 12.64, 23.24, 33.91, 43.27, 52.07, 60.57, 68.87, 77.10, 85.24, 93.44, 100.90 }, { 10.31, 20.43, 31.03, 40.54, 49.59, 58.33, 66.89, 75.43, 83.89, 92.34, 100.80 }, { 8.51, 18.23, 28.83, 38.41, 47.65, 56.59, 65.42, 74.16, 82.89, 91.61, 100.33 }, { 7.14, 16.55, 27.11, 36.79, 46.16, 55.27, 64.29, 73.24, 82.15, 91.06, 99.97 }, { 5.52, 14.58, 25.07, 34.88, 44.40, 53.73, 62.95, 72.18, 81.31, 90.44, 99.57 }, { 3.98, 12.69, 23.10, 32.99, 42.69, 52.27, 61.66, 71.15, 80.54, 89.93, 99.31 }, { 2.99, 11.43, 21.76, 31.73, 41.49, 51.22, 60.88, 70.51, 80.11, 89.70, 99.30 }, { 2.35, 10.58, 20.83, 30.86, 40.68, 50.51, 60.33, 70.08, 79.83, 89.58, 99.32 }, { 2.05, 10.12, 20.27, 30.35, 40.22, 50.10, 59.97, 69.82, 79.67, 89.52, 99.38 }, { 2.00, 9.93, 20.00, 30.07, 40.00, 49.93, 59.87, 69.80, 79.73, 89.67, 99.60 }, { 2.19, 10.00, 20.00, 30.00, 40.00, 50.00, 59.99, 69.99, 79.98, 89.98, 99.97 }, { 2.71, 10.56, 20.61, 30.71, 40.76, 50.81, 60.86, 70.96, 81.01, 91.06, 101.17 }, { 3.11, 11.05, 21.19, 31.41, 41.53, 51.64, 61.75, 71.95, 82.05, 92.15, 102.33 }, { 2.39, 10.69, 21.14, 31.52, 41.73, 51.95, 62.11, 72.31, 82.46, 92.56, 102.59 }, { 1.50, 10.11, 20.82, 31.32, 41.62, 51.92, 62.12, 72.32, 82.52, 92.63, 102.56 }, { -0.17, 8.50, 19.27, 29.77, 40.07, 50.37, 60.57, 70.77, 80.97, 91.13, 101.23 }, { -1.80, 6.96, 17.77, 28.29, 38.61, 48.91, 59.13, 69.33, 79.53, 89.71, 99.86 }, { -3.42, 5.49, 16.36, 26.94, 37.31, 47.61, 57.88, 68.08, 78.28, 88.41, 98.39 }, { -4.73, 4.38, 15.34, 25.99, 36.39, 46.71, 57.01, 67.21, 77.41, 87.51, 97.41 }, { -5.73, 3.63, 14.74, 25.48, 35.88, 46.26, 56.56, 66.76, 76.96, 87.06, 96.96 }, { -6.24, 3.33, 14.59, 25.39, 35.84, 46.22, 56.52, 66.72, 76.92, 87.04, 97.00 }, { -6.09, 3.62, 15.03, 25.83, 36.37, 46.70, 57.00, 67.20, 77.40, 87.57, 97.68 }, { -5.32, 4.44, 15.90, 26.70, 37.28, 47.60, 57.90, 68.10, 78.30, 88.52, 98.78 }, { -3.49, 6.17, 17.52, 28.32, 38.85, 49.22, 59.52, 69.72, 79.92, 90.20, 100.61 }, { -0.81, 8.58, 19.73, 30.44, 40.90, 51.24, 61.52, 71.69, 81.87, 92.15, 102.63 }, { 2.91, 11.82, 22.64, 33.17, 43.53, 53.73, 63.96, 74.09, 84.22, 94.45, 104.89 }, { 6.68, 15.19, 25.71, 36.03, 46.25, 56.31, 66.45, 76.49, 86.54, 96.72, 107.15 }, { 10.43, 18.65, 28.94, 39.02, 49.01, 58.98, 68.93, 78.78, 88.69, 98.83, 109.36 }, { 13.56, 21.65, 31.78, 41.68, 51.45, 61.31, 71.07, 80.73, 90.48, 100.51, 111.01 }, { 14.36, 22.91, 33.19, 43.09, 52.71, 62.37, 71.92, 81.38, 90.88, 100.56, 110.56 }, { 15.06, 23.90, 34.23, 44.05, 53.48, 62.90, 72.21, 81.43, 90.65, 99.93, 109.34 }, { 15.36, 23.90, 33.89, 43.31, 52.40, 61.42, 70.29, 79.18, 88.00, 96.69, 105.17 }, { 15.60, 23.90, 33.60, 42.70, 51.50, 60.20, 68.70, 77.30, 85.80, 94.00, 101.70 }, { 15.60, 23.90, 33.60, 42.70, 51.50, 60.20, 68.70, 77.30, 85.80, 94.00, 101.70 }, { 15.60, 23.90, 33.60, 42.70, 51.50, 60.20, 68.70, 77.30, 85.80, 94.00, 101.70 }, { 15.60, 23.90, 33.60, 42.70, 51.50, 60.20, 68.70, 77.30, 85.80, 94.00, 101.70 }, { 15.60, 23.90, 33.60, 42.70, 51.50, 60.20, 68.70, 77.30, 85.80, 94.00, 101.70 }, { 15.60, 23.90, 33.60, 42.70, 51.50, 60.20, 68.70, 77.30, 85.80, 94.00, 101.70 } }; double phons[11] = { 2, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }; // other functions static void Loudness_dofft(Loudness*, uint32); void Loudness_Ctor(Loudness* unit) { // may want to check sampling rate here! unit->m_numbands = 42; unit->m_ERBbands = (float*)RTAlloc(unit->mWorld, unit->m_numbands * sizeof(float)); ClearUnitIfMemFailed(unit->m_ERBbands); Clear(unit->m_numbands, unit->m_ERBbands); unit->m_sones = 0; // unit->m_phontotal=0; unit->mCalcFunc = (UnitCalcFunc)&Loudness_next; Loudness_next(unit, 1); } void Loudness_Dtor(Loudness* unit) { RTFree(unit->mWorld, unit->m_ERBbands); } void Loudness_next(Loudness* unit, int wrongNumSamples) { float fbufnum = ZIN0(0); // next FFT bufffer ready, update // assuming at this point that buffer precalculated for any resampling if (fbufnum > -0.01f) Loudness_dofft(unit, (uint32)fbufnum); // always output sones // float outval= unit->m_sones; // printf("sones %f phontotal %f \n",outval, unit->m_phontotal); // control rate output ZOUT0(0) = unit->m_sones; } // temporal masking over ERB bands: peaks take a while to decay // spectral masking over which bins summed as contributors for ERB bands; spreading activation function actually implies // that the overall power is greater from spread? masking not triangular but slanted towards masking higher frequency // content (ie, lower freq bins mask upper) // for true MP3 style compression would have to see if each FFT bin was noise like or sine like (transient measure on // instantaneous frequency for example), and use the appropriate masking curve efficiency is preferred here // thus can calculate squared powers as you go? cheapest if only have effect of spectral masking above, covering a fixed // number of bins? but then, frequency biased loudness based on ERB band centre frequency! // calculation function once FFT data ready void Loudness_dofft(Loudness* unit, uint32 ibufnum) { World* world = unit->mWorld; // if (ibufnum >= world->mNumSndBufs) ibufnum = 0; SndBuf* buf; // = world->mSndBufs + ibufnum; // int numbins = buf->samples - 2 >> 1; // support LocalBuf if (ibufnum >= world->mNumSndBufs) { int localBufNum = ibufnum - world->mNumSndBufs; Graph* parent = unit->mParent; if (localBufNum <= parent->localBufNum) { buf = parent->mLocalSndBufs + localBufNum; } else { buf = world->mSndBufs; } } else { buf = world->mSndBufs + ibufnum; } LOCK_SNDBUF(buf); float* data = buf->data; float loudsum = 0.0; float smask = ZIN0(1); float tmask = ZIN0(2); for (int k = 0; k < unit->m_numbands; ++k) { int bandstart = eqlbandbins[k]; // int bandend=eqlbandbins[k+1]; int bandsize = eqlbandsizes[k]; int bandend = bandstart + bandsize; float bsum = 0.0; float real, imag, power; int index; float lastpower = 0.0; for (int h = bandstart; h < bandend; ++h) { index = 2 * h; real = data[index]; imag = data[index + 1]; power = (real * real) + (imag * imag); // would involve spectral masking here power = sc_max(lastpower * smask, power); // sideways spectral masking with leaky integration lastpower = power; // psychophysical sensation; within critical band, sum using a p metric, (sum m^p)^(1/p) // compresses the gain // power of three combination // bsum= bsum+(power*power*power); // won't sum up power very well // if(power>bsum) bsum=power; bsum = bsum + power; } // store recips of bandsizes? // why average? surely just take max or sum is better! // bsum= bsum/bandsize; // into dB, avoid log of 0 // float db= 10*log10((bsum*10000000)+0.001); // float db= 10*log10((bsum*32382)+0.001); // empricially derived 32382*2.348 float db = 10 * log10((bsum * 76032.936f) + 0.001f); // correct multipler until you get loudness output of 1! // correcting for power of three combination // bsum=bsum+0.001; // 4.8810017610244 = log10(76032.936) // float db= 10*((0.33334*log10(bsum)) + 4.8810017610244); //correct multipler until you get loudness output of // 1! // printf("bsum %f db %f \n",bsum,db); // convert via contour if (db < contours[k][0]) db = 0; else if (db > contours[k][10]) db = phons[10]; else { float prop = 0.0; int j; for (j = 1; j < 11; ++j) { if (db < contours[k][j]) { prop = (db - contours[k][j - 1]) / (contours[k][j] - contours[k][j - 1]); break; } if (j == 10) { prop = 1.0; break; // avoid j becoming 11 to avoid out-of-bounds access in db calculation } } db = (1.f - prop) * phons[j - 1] + prop * phons[j]; // printf("prop %f db %f j %d\n",prop,db,j); } // spectralmasking, 6dB drop per frame? // try also with just take db unit->m_ERBbands[k] = sc_max(db, (unit->m_ERBbands[k]) - tmask); // printf("db %f erbband %f \n",db, unit->m_ERBbands[k]); // must sum as intensities, not dbs once corrected, pow used to be other way around // loudsum+= ((pow(10, 0.1*unit->m_ERBbands[k])-0.001)*0.0000308813538386); // loudsum += ((pow(10, 0.1 * unit->m_ERBbands[k]) - 0.001)); // multiplier not needed since invert below; can trust no overflow? } // total excitation, correct back to dB scale in phons // float phontotal= 10*log10((loudsum*32382)+0.001); float phontotal = 10 * log10((loudsum) + 0.001); // didn't use divisor above, so no need to restore here // unit->m_phontotal= phontotal; // now to sones: /* from Praat: Excitation.c Sones = 2 ** ((Phones - 40) / 10) */ unit->m_sones = pow(2.f, (phontotal - 40) / 10); // printf("phontotal %f sones %f \n",phontotal, unit->m_sones); // about 5 times per second // if((unit->m_triggerid) && ((unit->m_frame%2==0))) SendTrigger(&unit->mParent->mNode, unit->m_triggerid, bestkey); }
12,631
C++
.cpp
206
49.5
120
0.538368
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
true
false
29,967
FFT2InterfaceTable.cpp
supercollider_supercollider/server/plugins/FFT2InterfaceTable.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // third party Phase Vocoder UGens #include "FFT_UGens.h" InterfaceTable* ft; // these are defined in the relevant files extern void initConvolution(InterfaceTable*); extern void initPV_ThirdParty(InterfaceTable*); extern void initFeatureDetectors(InterfaceTable* it); PluginLoad(PV_ThirdParty) { ft = inTable; initConvolution(inTable); initPV_ThirdParty(inTable); initFeatureDetectors(inTable); }
1,293
C++
.cpp
29
40.793103
81
0.772112
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,968
FeatureDetection.cpp
supercollider_supercollider/server/plugins/FeatureDetection.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // Feature (Onset) Detection implemented by sick lincoln for sc3 // Jensen,K. & Andersen, T. H. (2003). Real-time Beat Estimation Using Feature Extraction. // In Proceedings of the Computer Music Modeling and RetrievalSymposium, Lecture Notes in Computer Science. Springer // Verlag. Hainsworth, S. (2003) Techniques for the Automated Analysis of Musical Audio. PhD, university of cambridge // engineering dept. // possible to make a Goto style Detector for a given band and with history of two samples- // should do separately as PV_GotoBandTrack // next perhaps Duxbury et al/ Mauri et al different conception of high frequency content with ratio of changes #include "FFT_UGens.h" struct PV_OnsetDetectionBase : public Unit { float* m_prevframe; int m_numbins; int m_waiting, m_waitSamp, m_waitLen; }; // FFT onset detector combining 4 advised features from Jensen/Andersen struct PV_JensenAndersen : public PV_OnsetDetectionBase { float m_hfc, m_hfe, m_sc, m_sf; int m_fourkindex; }; // FFT onset detector combining 2 advised features from Hainsworth PhD struct PV_HainsworthFoote : public PV_OnsetDetectionBase { float m_prevNorm; int m_5kindex, m_30Hzindex; }; // for time domain onset detection/RMS struct RunningSum : public Unit { int msamp, mcount; float msum, msum2; // float mmeanmult; float* msquares; }; extern "C" { void PV_OnsetDetectionBase_Ctor(PV_OnsetDetectionBase* unit); void PV_OnsetDetectionBase_Dtor(PV_OnsetDetectionBase* unit); void PV_JensenAndersen_Ctor(PV_JensenAndersen* unit); void PV_JensenAndersen_Dtor(PV_JensenAndersen* unit); void PV_JensenAndersen_next(PV_JensenAndersen* unit, int inNumSamples); void PV_HainsworthFoote_Ctor(PV_HainsworthFoote* unit); void PV_HainsworthFoote_Dtor(PV_HainsworthFoote* unit); void PV_HainsworthFoote_next(PV_HainsworthFoote* unit, int inNumSamples); void RunningSum_next_k(RunningSum* unit, int inNumSamples); void RunningSum_Ctor(RunningSum* unit); void RunningSum_Dtor(RunningSum* unit); } #define PV_FEAT_GET_BUF_UNLOCKED \ uint32 ibufnum = (uint32)fbufnum; \ int bufOK = 1; \ World* world = unit->mWorld; \ SndBuf* buf; \ if (ibufnum >= world->mNumSndBufs) { \ int localBufNum = ibufnum - world->mNumSndBufs; \ Graph* parent = unit->mParent; \ if (localBufNum <= parent->localBufNum) { \ buf = parent->mLocalSndBufs + localBufNum; \ } else { \ bufOK = 0; \ buf = world->mSndBufs; \ if (unit->mWorld->mVerbosity > -1) { \ Print("FFT Ctor error: Buffer number overrun: %i\n", ibufnum); \ } \ } \ } else { \ buf = world->mSndBufs + ibufnum; \ } \ int numbins = (buf->samples - 2) >> 1; \ if (!buf->data) { \ if (unit->mWorld->mVerbosity > -1) { \ Print("FFT Ctor error: Buffer %i not initialised.\n", ibufnum); \ } \ bufOK = 0; \ } #define PV_FEAT_GET_BUF \ PV_FEAT_GET_BUF_UNLOCKED \ LOCK_SNDBUF(buf); void PV_OnsetDetectionBase_Ctor(PV_OnsetDetectionBase* unit) { float fbufnum = ZIN0(0); unit->m_prevframe = nullptr; PV_FEAT_GET_BUF_UNLOCKED unit->m_numbins = numbins; int insize = unit->m_numbins * sizeof(float); if (bufOK) { unit->m_prevframe = (float*)RTAlloc(unit->mWorld, insize); ClearUnitIfMemFailed(unit->m_prevframe); memset(unit->m_prevframe, 0, insize); } unit->m_waiting = 0; unit->m_waitSamp = 0; unit->m_waitLen = 0; ClearUnitOutputs(unit, 1); } void PV_OnsetDetectionBase_Dtor(PV_OnsetDetectionBase* unit) { if (unit->m_prevframe) RTFree(unit->mWorld, unit->m_prevframe); } void PV_JensenAndersen_Ctor(PV_JensenAndersen* unit) { PV_OnsetDetectionBase_Ctor(unit); unit->m_hfc = 0.0; unit->m_hfe = 0.0; unit->m_sf = 0.0; unit->m_sc = 0.0; unit->m_fourkindex = (int)(4000.0 / (unit->mWorld->mSampleRate)) * (unit->m_numbins); SETCALC(PV_JensenAndersen_next); } void PV_JensenAndersen_Dtor(PV_JensenAndersen* unit) { PV_OnsetDetectionBase_Dtor(unit); } void PV_JensenAndersen_next(PV_JensenAndersen* unit, int inNumSamples) { float outval = 0.0; float fbufnum = ZIN0(0); if (unit->m_waiting == 1) { unit->m_waitSamp += inNumSamples; if (unit->m_waitSamp >= unit->m_waitLen) unit->m_waiting = 0; } if (!(fbufnum < 0.f)) // if buffer ready to process { PV_FEAT_GET_BUF SCPolarBuf* p = ToPolarApx(buf); // four spectral features useful for onset detection according to Jensen/Andersen float magsum = 0.0, magsumk = 0.0, magsumkk = 0.0, sfsum = 0.0, hfesum = 0.0; float* q = unit->m_prevframe; int k4 = unit->m_fourkindex; // ignores dc, nyquist for (int i = 0; i < numbins; ++i) { float mag = ((p->bin[i]).mag); int k = i + 1; float qmag = q[i]; magsum += mag; magsumk += k * mag; magsumkk += k * k * mag; sfsum += fabs(mag - (qmag)); if (i > k4) hfesum += mag; } float binmult = 1.f / numbins; // normalise float sc = (magsumk / magsum) * binmult; float hfe = hfesum * binmult; float hfc = magsumkk * binmult * binmult * binmult; float sf = sfsum * binmult; // printf("sc %f hfe %f hfc %f sf %f \n",sc, hfe, hfc, sf); // if(sc<0.0) sc=0.0; // if(hfe<0.0) hfe=0.0; // if(hfc<0.0) hfc=0.0; // if(sf<0.0) sf=0.0; // ratio of current to previous frame perhaps better indicator than first derivative difference float scdiff = sc - (unit->m_sc); float hfediff = hfe - (unit->m_hfe); float hfcdiff = hfc - (unit->m_hfc); float sfdiff = sf - (unit->m_sf); // store as old frame values for taking difference unit->m_sc = sc; unit->m_hfe = hfe; unit->m_hfc = hfc; unit->m_sf = sf; // printf("sc %f hfe %f hfc %f sf %f \n",sc, hfe, hfc, sf); // printf("sc %f hfe %f hfc %f sf %f \n",scdiff, hfediff, hfcdiff, sfdiff); // does this trigger? // may need to take derivatives across previous frames by storing old values float sum = (ZIN0(1) * scdiff) + (ZIN0(2) * hfediff) + (ZIN0(3) * hfcdiff) + (ZIN0(4) * sfdiff); // printf("sum %f thresh %f \n",sum, ZIN0(7)); // if over threshold, may also impose a wait here if (sum > ZIN0(5) && (unit->m_waiting == 0)) { // printf("bang! \n"); outval = 1.0; unit->m_waiting = 1; unit->m_waitSamp = inNumSamples; unit->m_waitLen = (int)(ZIN0(6) * (world->mSampleRate)); } // take copy of this frame's magnitudes as prevframe for (int i = 0; i < numbins; ++i) q[i] = p->bin[i].mag; } Fill(inNumSamples, &ZOUT0(0), outval); } void PV_HainsworthFoote_Ctor(PV_HainsworthFoote* unit) { PV_OnsetDetectionBase_Ctor(unit); World* world = unit->mWorld; unit->m_5kindex = (int)((5000.0 / (world->mSampleRate)) * (unit->m_numbins)); unit->m_30Hzindex = (int)((30.0 / (world->mSampleRate)) * (unit->m_numbins)); unit->m_prevNorm = 1.0; // unit->m_5kindex, unit->m_30Hzindex, // printf("numbins %d sr %d \n", unit->m_numbins, world->mSampleRate); // printf("test %d sr %f 5k %d 30Hz %d\n", unit->m_numbins, world->mSampleRate, unit->m_5kindex, unit->m_30Hzindex); SETCALC(PV_HainsworthFoote_next); } void PV_HainsworthFoote_Dtor(PV_HainsworthFoote* unit) { PV_OnsetDetectionBase_Dtor(unit); } static const float lmult = 1.442695040889; // loge(2) reciprocal void PV_HainsworthFoote_next(PV_HainsworthFoote* unit, int inNumSamples) { float outval = 0.0; float fbufnum = ZIN0(0); if (unit->m_waiting == 1) { unit->m_waitSamp += inNumSamples; if (unit->m_waitSamp >= unit->m_waitLen) { unit->m_waiting = 0; } } if (!(fbufnum < 0.f)) // if buffer ready to process { PV_FEAT_GET_BUF SCPolarBuf* p = ToPolarApx(buf); float dnk, prevmag, mkl = 0.0, footesum = 0.0, norm = 0.0; float* q = unit->m_prevframe; int k5 = unit->m_5kindex; int h30 = unit->m_30Hzindex; for (int i = 0; i < numbins; ++i) { float mag = ((p->bin[i]).mag); float qmag = q[i]; if (i >= h30 && i < k5) { prevmag = qmag; // avoid divide by zero if (prevmag < 0.0001) prevmag = 0.0001; // no log2 in maths library, so use log2(x)= log(x)/log(2) where log is to base e // could just use log and ignore scale factor but hey let's stay accurate to the source for now dnk = log(mag / prevmag) * lmult; if (dnk > 0.0) mkl += dnk; } norm += mag * mag; footesum += mag * qmag; } mkl = mkl / (k5 - h30); // Foote measure- footediv will be zero initially float footediv = ((sqrt(norm)) * (sqrt(unit->m_prevNorm))); if (footediv < 0.0001f) footediv = 0.0001f; float foote = 1.0 - (footesum / footediv); // 1.0 - similarity // printf("mkl %f foote %f \n",mkl, foote); unit->m_prevNorm = norm; float sum = (ZIN0(1) * mkl) + (ZIN0(2) * foote); // printf("sum %f thresh %f \n",sum, ZIN0(7)); // if over threshold, may also impose a 50mS wait here if (sum > ZIN0(3) && (unit->m_waiting == 0)) { outval = 1.0; unit->m_waiting = 1; unit->m_waitSamp = inNumSamples; unit->m_waitLen = (int)(ZIN0(4) * (unit->mWorld->mSampleRate)); } // take copy of this frame's magnitudes as prevframe for (int i = 0; i < numbins; ++i) q[i] = p->bin[i].mag; } Fill(inNumSamples, &ZOUT0(0), outval); } void RunningSum_Ctor(RunningSum* unit) { SETCALC(RunningSum_next_k); unit->msamp = (int)ZIN0(1); // unit->mmeanmult= 1.0f/(unit->msamp); unit->msum = 0.0f; unit->msum2 = 0.0f; unit->mcount = 0; // unit->msamp-1; unit->msquares = (float*)RTAlloc(unit->mWorld, unit->msamp * sizeof(float)); ClearUnitIfMemFailed(unit->msquares); // initialise to zeroes for (int i = 0; i < unit->msamp; ++i) unit->msquares[i] = 0.f; OUT0(0) = 0.f; } void RunningSum_Dtor(RunningSum* unit) { RTFree(unit->mWorld, unit->msquares); } // RMS is easy because convolution kernel can be updated just by deleting oldest sample and adding newest- // half hanning window convolution etc requires updating values for all samples in memory on each iteration void RunningSum_next_k(RunningSum* unit, int inNumSamples) { float* in = ZIN(0); float* out = ZOUT(0); int count = unit->mcount; int samp = unit->msamp; float* data = unit->msquares; float sum = unit->msum; // avoids floating point error accumulation over time- thanks to Ross Bencina float sum2 = unit->msum2; int todo = 0; int done = 0; while (done < inNumSamples) { todo = sc_min(inNumSamples - done, samp - count); for (int j = 0; j < todo; ++j) { sum -= data[count]; float next = ZXP(in); data[count] = next; sum += next; sum2 += next; ZXP(out) = sum; ++count; } done += todo; if (count == samp) { count = 0; sum = sum2; sum2 = 0; } } unit->mcount = count; unit->msum = sum; unit->msum2 = sum2; } void initFeatureDetectors(InterfaceTable* it) { DefineDtorUnit(PV_JensenAndersen); DefineDtorUnit(PV_HainsworthFoote); DefineDtorUnit(RunningSum); }
15,264
C++
.cpp
315
41.266667
120
0.510942
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,969
PhysicalModelingUGens.cpp
supercollider_supercollider/server/plugins/PhysicalModelingUGens.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // some basic physical modeling ugens - julian rohrhuber 1/04 // these are very simple implementations with cartoonification aspects. #include "SC_PlugIn.h" static InterfaceTable* ft; ////////////////////////////////////////////////////////////////////////////////////////////////// struct Spring : public Unit { float m_pos; float m_vel; }; struct Ball : public Unit { float m_pos; float m_vel; float m_prev; }; struct TBall : public Unit { double m_pos; float m_vel; double m_prev; }; extern "C" { void Spring_Ctor(Spring* unit); void Spring_next(Spring* unit, int inNumSamples); // void Friction_Ctor(Friction *unit); // void Friction_next(Friction *unit, int inNumSamples); void Ball_Ctor(Ball* unit); void Ball_next(Ball* unit, int inNumSamples); void TBall_Ctor(TBall* unit); void TBall_next(TBall* unit, int inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Spring_Ctor(Spring* unit) { SETCALC(Spring_next); unit->m_vel = 0.f; unit->m_pos = 0.f; Spring_next(unit, 1); } // in, spring, damping void Spring_next(Spring* unit, int inNumSamples) { float pos = unit->m_pos; float vel = unit->m_vel; float* out = ZOUT(0); // out force float* in = ZIN(0); // in force float spring = ZIN0(1); // spring constant float damping = 1.f - ZIN0(2); // damping float c = SAMPLEDUR; float rc = SAMPLERATE; spring = spring * c; LOOP1(inNumSamples, float force = ZXP(in) * c - pos * spring; vel = (force + vel) * damping; pos += vel; ZXP(out) = force * rc;); unit->m_pos = pos; unit->m_vel = vel; } ////////////////////////////////////////////////////////////////////////////////////////// void Ball_Ctor(Ball* unit) { SETCALC(Ball_next); unit->m_vel = 0.f; unit->m_pos = ZIN0(0); unit->m_prev = ZIN0(0); Ball_next(unit, 1); } void Ball_next(Ball* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); // floor position float g_in = ZIN0(1); // gravity float damping = 1 - ZIN0(2); // damping float k = ZIN0(3); // friction float pos = unit->m_pos; float vel = unit->m_vel; float prev_floor = unit->m_prev; float c = SAMPLEDUR; float maxvel = c * 1000.f; float minvel = 0.f - maxvel; float inter = c * 1000.f; RGen& rgen = *unit->mParent->mRGen; float g = c * g_in; k = (double)k * (double)g_in; // stickyness proportional to gravity LOOP1( inNumSamples, float floor = ZXP(in); float floorvel; float dither; vel -= g; pos += vel; float dist = pos - floor; floorvel = floor - prev_floor; floorvel = sc_clip(floorvel, minvel, maxvel); float vel_diff = floorvel - vel; if (sc_abs(dist) < k) { // sticky friction: maybe vel dependant? if (sc_abs(dist) < (k * 0.005)) { vel = 0.f; pos = floor + g; } else { vel = vel_diff * inter + vel; pos = (floor - pos) * inter + pos; } } else if (dist <= 0.f) { pos = floor - dist; vel = vel_diff; vel *= damping; dither = rgen.frand() * 0.00005f * g_in; // dither to reduce jitter // if(sc_abs(dist) < 0.000001) { vel += dither; } vel += dither; } prev_floor = floor; ZXP(out) = pos;); unit->m_pos = pos; unit->m_vel = vel; unit->m_prev = prev_floor; } ////////////////////////////////////////////////////////////////////////////////////////// void TBall_Ctor(TBall* unit) { SETCALC(TBall_next); unit->m_vel = 0.f; unit->m_pos = ZIN0(0); unit->m_prev = ZIN0(0); TBall_next(unit, 1); } void TBall_next(TBall* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); // floor position float g_in = ZIN0(1); // gravity float damping = 1 - ZIN0(2); // damping float k = ZIN0(3); // friction double pos = unit->m_pos; float vel = unit->m_vel; double prev_floor = unit->m_prev; float c = SAMPLEDUR; float maxvel = c * 1000.f; float minvel = 0.f - maxvel; float inter = c * 10000.f; RGen& rgen = *unit->mParent->mRGen; float g = c * g_in; k = (double)k * (double)g_in; // stickyness proportional to gravity LOOP1( inNumSamples, double floor = ZXP(in); float floorvel; float outval = 0.f; float dither; vel -= g; pos += vel; double dist = pos - floor; floorvel = floor - prev_floor; floorvel = sc_clip(floorvel, minvel, maxvel); float vel_diff = floorvel - vel; if (sc_abs(dist) < k) { // sticky friction: vel dependant? if (sc_abs(dist) < (k * 0.005)) { vel = 0.f; pos = floor + g; } else { vel = vel_diff * inter + vel; pos = (floor - pos) * inter + pos; } } else if (dist <= 0.f) { pos = floor - dist; vel = floorvel - vel; vel *= damping; outval = vel; dither = rgen.frand() * 0.001f * g_in; // dither to reduce sampling jitter // if(sc_abs(dist) < 0.003) { vel += dither; } vel += dither; } prev_floor = floor; ZXP(out) = outval;); unit->m_pos = pos; unit->m_vel = vel; unit->m_prev = prev_floor; } //////////////////////////////////////////////////////////////////////////////////////////////////////// PluginLoad(PhysicalModeling) { ft = inTable; DefineSimpleUnit(Spring); DefineSimpleUnit(Ball); DefineSimpleUnit(TBall); }
6,528
C++
.cpp
172
31.918605
117
0.55545
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,970
DemoUGens.cpp
supercollider_supercollider/server/plugins/DemoUGens.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney and others. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "SC_PlugIn.h" static InterfaceTable* ft; // example of implementing a plug in command with async execution. struct MyPluginData // data for the global instance of the plugin { float a, b; }; struct MyCmdData // data for each command { MyPluginData* myPlugin; float x, y; char* name; }; MyPluginData gMyPlugin; // global bool cmdStage2(World* world, void* inUserData) { // user data is the command. MyCmdData* myCmdData = (MyCmdData*)inUserData; // just print out the values Print("cmdStage2 a %g b %g x %g y %g name %s\n", myCmdData->myPlugin->a, myCmdData->myPlugin->b, myCmdData->x, myCmdData->y, myCmdData->name); return true; } bool cmdStage3(World* world, void* inUserData) { // user data is the command. MyCmdData* myCmdData = (MyCmdData*)inUserData; // just print out the values Print("cmdStage3 a %g b %g x %g y %g name %s\n", myCmdData->myPlugin->a, myCmdData->myPlugin->b, myCmdData->x, myCmdData->y, myCmdData->name); // scsynth will perform completion message after this returns return true; } bool cmdStage4(World* world, void* inUserData) { // user data is the command. MyCmdData* myCmdData = (MyCmdData*)inUserData; // just print out the values Print("cmdStage4 a %g b %g x %g y %g name %s\n", myCmdData->myPlugin->a, myCmdData->myPlugin->b, myCmdData->x, myCmdData->y, myCmdData->name); // scsynth will send /done after this returns return true; } void cmdCleanup(World* world, void* inUserData) { // user data is the command. MyCmdData* myCmdData = (MyCmdData*)inUserData; Print("cmdCleanup a %g b %g x %g y %g name %s\n", myCmdData->myPlugin->a, myCmdData->myPlugin->b, myCmdData->x, myCmdData->y, myCmdData->name); RTFree(world, myCmdData->name); // free the string RTFree(world, myCmdData); // free command data // scsynth will delete the completion message for you. } void cmdDemoFunc(World* inWorld, void* inUserData, struct sc_msg_iter* args, void* replyAddr) { Print("->cmdDemoFunc %p\n", inUserData); // user data is the plug-in's user data. MyPluginData* thePlugInData = (MyPluginData*)inUserData; // allocate command data, free it in cmdCleanup. MyCmdData* myCmdData = (MyCmdData*)RTAlloc(inWorld, sizeof(MyCmdData)); if (!myCmdData) { Print("cmdDemoFunc: memory allocation failed!\n"); return; } myCmdData->myPlugin = thePlugInData; // ..get data from args.. myCmdData->x = 0.; myCmdData->y = 0.; myCmdData->name = 0; // float arguments myCmdData->x = args->getf(); myCmdData->y = args->getf(); // how to pass a string argument: const char* name = args->gets(); // get the string argument if (name) { myCmdData->name = (char*)RTAlloc(inWorld, strlen(name) + 1); // allocate space, free it in cmdCleanup. if (!myCmdData->name) { Print("cmdDemoFunc: memory allocation failed!\n"); return; } strcpy(myCmdData->name, name); // copy the string } // how to pass a completion message int msgSize = args->getbsize(); char* msgData = 0; if (msgSize) { // allocate space for completion message // scsynth will delete the completion message for you. msgData = (char*)RTAlloc(inWorld, msgSize); if (!msgData) { Print("cmdDemoFunc: memory allocation failed!\n"); return; } args->getb(msgData, msgSize); // copy completion message. } DoAsynchronousCommand(inWorld, replyAddr, "cmdDemoFunc", (void*)myCmdData, (AsyncStageFn)cmdStage2, (AsyncStageFn)cmdStage3, (AsyncStageFn)cmdStage4, cmdCleanup, msgSize, msgData); Print("<-cmdDemoFunc\n"); } /* * to test the above, send the server these commands: * * * SynthDef(\sine, { Out.ar(0, SinOsc.ar(800,0,0.2)) }).load(s); * s.sendMsg(\cmd, \pluginCmdDemo, 7, 9, \mno, [\s_new, \sine, 900, 0, 0]); * s.sendMsg(\n_free, 900); * s.sendMsg(\cmd, \pluginCmdDemo, 7, 9, \mno); * s.sendMsg(\cmd, \pluginCmdDemo, 7, 9); * s.sendMsg(\cmd, \pluginCmdDemo, 7); * s.sendMsg(\cmd, \pluginCmdDemo); * */ ////////////////////////////////////////////////////////////////////////////////////////////////// // example of implementing a plug in with unit commands struct UnitCmdDemo : public Unit { float value; }; void UnitCmdDemo_next(UnitCmdDemo* unit, int inNumSamples) { OUT0(0) = unit->value; } void UnitCmdDemo_Ctor(UnitCmdDemo* unit) { SETCALC(UnitCmdDemo_next); unit->value = 0.f; UnitCmdDemo_next(unit, 1); } void UnitCmdDemo_setValue(UnitCmdDemo* unit, sc_msg_iter* args) { unit->value = args->getf(); Print("UnitCmdTest: set value to %f\n", unit->value); } /* * to test the above, send the server these commands: * * * SynthDef(\u_cmd_test, { UnitCmdDemo.kr; }).add; * s.sync; * u = Synth(\u_cmd_test); * // You have to know the index of the UGen within the Synth. * // Here we have a SynthDef with a single UGen and without Synth controls, * // so the index will be 0. * s.sendMsg(\u_cmd, u.nodeID, 0, \setValue, 4.5); * s.sendMsg(\u_cmd, u.nodeID, 0, \setValue, -3.0); * */ PluginLoad(DemoUGens) { ft = inTable; // define a plugin command - example code gMyPlugin.a = 1.2f; gMyPlugin.b = 3.4f; DefinePlugInCmd("pluginCmdDemo", cmdDemoFunc, (void*)&gMyPlugin); // define a unit command - example code DefineSimpleUnit(UnitCmdDemo); DefineUnitCmd("UnitCmdDemo", "setValue", (UnitCmdFunc)&UnitCmdDemo_setValue); }
6,515
C++
.cpp
162
35.512346
119
0.665241
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,971
OscUGens.cpp
supercollider_supercollider/server/plugins/OscUGens.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "SC_PlugIn.h" #include "function_attributes.h" #include <limits> #include <string.h> static InterfaceTable* ft; struct BufUnit : public Unit { SndBuf* m_buf; float m_fbufnum; }; struct TableLookup : public BufUnit { double m_cpstoinc, m_radtoinc; int32 mTableSize; int32 m_lomask; }; struct DegreeToKey : public BufUnit { int32 mPrevIndex; float mPrevKey; int32 mOctave; }; struct Select : public Unit {}; struct TWindex : public Unit { int32 m_prevIndex; float m_trig; float m_maxSum; }; struct Index : public BufUnit {}; struct IndexL : public BufUnit {}; struct WrapIndex : public BufUnit {}; struct FoldIndex : public BufUnit {}; struct IndexInBetween : public BufUnit {}; struct DetectIndex : public BufUnit { float mPrev; float mPrevIn; }; struct Shaper : public BufUnit { float mOffset; float mPrevIn; }; struct FSinOsc : public Unit { double m_b1, m_y1, m_y2, m_freq; }; struct PSinGrain : public Unit { double m_b1, m_y1, m_y2; double m_level, m_slope, m_curve; int32 mCounter; }; struct Osc : public TableLookup { int32 m_phase; float m_phasein; }; struct SinOsc : public TableLookup { int32 m_phase; float m_phasein; }; struct SinOscFB : public TableLookup { int32 m_phase; float m_prevout, m_feedback; }; struct OscN : public TableLookup { int32 m_phase; float m_phasein; }; struct COsc : public TableLookup { int32 m_phase1, m_phase2; }; struct VOsc : public Unit { double m_cpstoinc, m_radtoinc; int32 mTableSize; int32 m_lomask; int32 m_phase, m_phaseoffset; float m_phasein, m_bufpos; }; struct VOsc3 : public Unit { double m_cpstoinc; int32 mTableSize; int32 m_lomask; int32 m_phase1, m_phase2, m_phase3; float m_bufpos; }; struct Formant : public Unit { int32 m_phase1, m_phase2, m_phase3; double m_cpstoinc; }; struct Blip : public Unit { int32 m_phase, m_numharm, m_N; float m_freqin, m_scale; double m_cpstoinc; }; struct Saw : public Unit { int32 m_phase, m_N; float m_freqin, m_scale, m_y1; double m_cpstoinc; }; struct Pulse : public Unit { int32 m_phase, m_phaseoff, m_N; float m_freqin, m_scale, m_y1; double m_cpstoinc; }; struct Klang : public Unit { float* m_coefs; int32 m_numpartials; }; struct Klank : public Unit { float* m_coefs; float* m_buf; float m_x1, m_x2; int32 m_numpartials; }; #define xlomask8 0x000003FC #define xlomask9 0x000007FC #define xlomask10 0x00000FFC #define xlomask11 0x00001FFC #define xlomask12 0x00003FFC #define xlomask13 0x00007FFC #define xlomask8i 0x000007F8 #define xlomask9i 0x00000FF8 #define xlomask10i 0x00001FF8 #define xlomask11i 0x00003FF8 #define xlomask12i 0x00007FF8 #define xlomask13i 0x0000FFF8 #define onecyc13 0x20000000 ////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" { void DegreeToKey_Ctor(DegreeToKey* unit); void DegreeToKey_next_1(DegreeToKey* unit, int inNumSamples); void DegreeToKey_next_k(DegreeToKey* unit, int inNumSamples); void DegreeToKey_next_a(DegreeToKey* unit, int inNumSamples); void Select_Ctor(Select* unit); void Select_next_1(Select* unit, int inNumSamples); void Select_next_k(Select* unit, int inNumSamples); void Select_next_a(Select* unit, int inNumSamples); void TWindex_Ctor(TWindex* unit); void TWindex_next_k(TWindex* unit, int inNumSamples); void TWindex_next_a(TWindex* unit, int inNumSamples); void Index_Ctor(Index* unit); void Index_next_1(Index* unit, int inNumSamples); void Index_next_k(Index* unit, int inNumSamples); void Index_next_a(Index* unit, int inNumSamples); void IndexL_Ctor(IndexL* unit); void IndexL_next_1(IndexL* unit, int inNumSamples); void IndexL_next_k(IndexL* unit, int inNumSamples); void IndexL_next_a(IndexL* unit, int inNumSamples); void FoldIndex_Ctor(FoldIndex* unit); void FoldIndex_next_1(FoldIndex* unit, int inNumSamples); void FoldIndex_next_k(FoldIndex* unit, int inNumSamples); void FoldIndex_next_a(FoldIndex* unit, int inNumSamples); void WrapIndex_Ctor(WrapIndex* unit); void WrapIndex_next_1(WrapIndex* unit, int inNumSamples); void WrapIndex_next_k(WrapIndex* unit, int inNumSamples); void WrapIndex_next_a(WrapIndex* unit, int inNumSamples); void Shaper_Ctor(Shaper* unit); void Shaper_next_1(Shaper* unit, int inNumSamples); void Shaper_next_k(Shaper* unit, int inNumSamples); void Shaper_next_a(Shaper* unit, int inNumSamples); void DetectIndex_Ctor(DetectIndex* unit); void DetectIndex_next_1(DetectIndex* unit, int inNumSamples); void DetectIndex_next_k(DetectIndex* unit, int inNumSamples); void DetectIndex_next_a(DetectIndex* unit, int inNumSamples); void IndexInBetween_Ctor(IndexInBetween* unit); void IndexInBetween_next_1(IndexInBetween* unit, int inNumSamples); void IndexInBetween_next_k(IndexInBetween* unit, int inNumSamples); void IndexInBetween_next_a(IndexInBetween* unit, int inNumSamples); void FSinOsc_Ctor(FSinOsc* unit); void FSinOsc_next(FSinOsc* unit, int inNumSamples); void FSinOsc_next_i(FSinOsc* unit, int inNumSamples); void PSinGrain_Ctor(PSinGrain* unit); void PSinGrain_next(PSinGrain* unit, int inNumSamples); void SinOsc_Ctor(SinOsc* unit); void SinOsc_next_ikk(SinOsc* unit, int inNumSamples); void SinOsc_next_ika(SinOsc* unit, int inNumSamples); void SinOsc_next_iak(SinOsc* unit, int inNumSamples); void SinOsc_next_iaa(SinOsc* unit, int inNumSamples); void Osc_Ctor(Osc* unit); void Osc_next_ikk(Osc* unit, int inNumSamples); void Osc_next_ika(Osc* unit, int inNumSamples); void Osc_next_iak(Osc* unit, int inNumSamples); void Osc_next_iaa(Osc* unit, int inNumSamples); void OscN_Ctor(OscN* unit); void OscN_next_nkk(OscN* unit, int inNumSamples); void OscN_next_nka(OscN* unit, int inNumSamples); void OscN_next_nak(OscN* unit, int inNumSamples); void OscN_next_naa(OscN* unit, int inNumSamples); void COsc_Ctor(COsc* unit); void COsc_next(COsc* unit, int inNumSamples); void VOsc_Ctor(VOsc* unit); void VOsc_next_ikk(VOsc* unit, int inNumSamples); void VOsc_next_ika(VOsc* unit, int inNumSamples); void VOsc3_Ctor(VOsc3* unit); void VOsc3_next_ik(VOsc3* unit, int inNumSamples); void Formant_Ctor(Formant* unit); void Formant_next(Formant* unit, int inNumSamples); void Blip_Ctor(Blip* unit); void Blip_next(Blip* unit, int inNumSamples); void Saw_Ctor(Saw* unit); void Saw_next(Saw* unit, int inNumSamples); void Pulse_Ctor(Pulse* unit); void Pulse_next(Pulse* unit, int inNumSamples); void Klang_Dtor(Klang* unit); void Klang_Ctor(Klang* unit); void Klang_next(Klang* unit, int inNumSamples); void Klank_Dtor(Klank* unit); void Klank_Ctor(Klank* unit); void Klank_next(Klank* unit, int inNumSamples); } ////////////////////////////////////////////////////////////////////////////////////////////////// force_inline bool UnitGetTable(BufUnit* unit, int inNumSamples, const SndBuf*& buf, const float*& bufData, int& tableSize) { float fbufnum = ZIN0(0); if (fbufnum != unit->m_fbufnum) { uint32 bufnum = (uint32)fbufnum; World* world = unit->mWorld; if (bufnum >= world->mNumSndBufs) { uint32 localBufNum = bufnum - world->mNumSndBufs; Graph* parent = unit->mParent; if (localBufNum <= parent->localBufNum) unit->m_buf = parent->mLocalSndBufs + localBufNum; else { bufnum = 0; unit->m_buf = world->mSndBufs + bufnum; } } else unit->m_buf = world->mSndBufs + bufnum; unit->m_fbufnum = fbufnum; } buf = unit->m_buf; if (!buf) { ClearUnitOutputs(unit, inNumSamples); return false; } bufData = buf->data; if (!bufData) { ClearUnitOutputs(unit, inNumSamples); return false; } tableSize = buf->samples; return true; } #define GET_TABLE \ const SndBuf* buf; \ const float* bufData; \ int tableSize; \ do { \ bool tableValid = UnitGetTable(unit, inNumSamples, buf, bufData, tableSize); \ if (!tableValid) \ return; \ } while (0); static inline bool verify_wavetable(Unit* unit, const char* name, int tableSize, int inNumSamples) { // phase computation is not precise for large wavetables. if (tableSize > 131072) { if (unit->mWorld->mVerbosity >= -1) Print("Warning: wave table too big (%s)\n", name); ClearUnitOutputs(unit, inNumSamples); return false; } if (!ISPOWEROFTWO(tableSize)) { if (unit->mWorld->mVerbosity >= -1) Print("Warning: size of wavetable not a power of two (%s)\n", name); ClearUnitOutputs(unit, inNumSamples); return false; } return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////// /* void TableLookup_SetTable(TableLookup* unit, int32 inSize, float* inTable) { unit->mTable0 = inTable; unit->mTable1 = inTable + 1; unit->mTableSize = inSize; unit->mMaxIndex = unit->mTableSize - 1; unit->mFMaxIndex = unit->mMaxIndex; unit->m_radtoinc = unit->mTableSize * (rtwopi * 65536.); unit->m_cpstoinc = unit->mTableSize * SAMPLEDUR * 65536.; //Print("TableLookup_SetTable unit->m_radtoinc %g %d %g\n", m_radtoinc, unit->mTableSize, rtwopi); } */ //////////////////////////////////////////////////////////////////////////////////////////////////////// void DegreeToKey_Ctor(DegreeToKey* unit) { unit->m_fbufnum = std::numeric_limits<float>::quiet_NaN(); if (BUFLENGTH == 1) { SETCALC(DegreeToKey_next_1); } else if (INRATE(1) == calc_FullRate) { SETCALC(DegreeToKey_next_a); } else { SETCALC(DegreeToKey_next_k); } unit->mOctave = (int32)ZIN0(2); unit->mPrevIndex = std::numeric_limits<int32>::max(); unit->mPrevKey = 0.; DegreeToKey_next_1(unit, 1); } void DegreeToKey_next_1(DegreeToKey* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; int32 key, oct; int32 octave = unit->mOctave; float val; int32 index = (int32)floor(ZIN0(1)); if (index == unit->mPrevIndex) { val = unit->mPrevKey; } else if (index < 0) { unit->mPrevIndex = index; key = tableSize + index % tableSize; oct = (index + 1) / tableSize - 1; val = unit->mPrevKey = table[key] + octave * oct; } else if (index > maxindex) { unit->mPrevIndex = index; key = index % tableSize; oct = index / tableSize; val = unit->mPrevKey = table[key] + octave * oct; } else { unit->mPrevIndex = index; val = unit->mPrevKey = table[index]; } ZOUT0(0) = val; } void DegreeToKey_next_k(DegreeToKey* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; float* out = ZOUT(0); int32 key, oct; float octave = unit->mOctave; float val; int32 index = (int32)floor(ZIN0(1)); if (index == unit->mPrevIndex) { val = unit->mPrevKey; } else if (index < 0) { unit->mPrevIndex = index; key = tableSize + index % tableSize; oct = (index + 1) / tableSize - 1; val = unit->mPrevKey = table[key] + octave * oct; } else if (index > maxindex) { unit->mPrevIndex = index; key = index % tableSize; oct = index / tableSize; val = unit->mPrevKey = table[key] + octave * oct; } else { unit->mPrevIndex = index; val = unit->mPrevKey = table[index]; } LOOP1(inNumSamples, ZXP(out) = val;); } void DegreeToKey_next_a(DegreeToKey* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; float* out = ZOUT(0); float* in = ZIN(1); int32 previndex = unit->mPrevIndex; float prevkey = unit->mPrevKey; int32 key, oct; float octave = unit->mOctave; LOOP1( inNumSamples, int32 index = (int32)floor(ZXP(in)); if (index == previndex) { ZXP(out) = prevkey; } else if (index < 0) { previndex = index; key = tableSize + index % tableSize; oct = (index + 1) / tableSize - 1; ZXP(out) = prevkey = table[key] + octave * oct; } else if (index > maxindex) { previndex = index; key = index % tableSize; oct = index / tableSize; ZXP(out) = prevkey = table[key] + octave * oct; } else { previndex = index; ZXP(out) = prevkey = table[index]; }); unit->mPrevIndex = previndex; unit->mPrevKey = prevkey; } //////////////////////////////////////////////////////////////////////////////////// void Select_Ctor(Select* unit) { if (BUFLENGTH == 1) { SETCALC(Select_next_1); } else if (INRATE(0) == calc_FullRate) { SETCALC(Select_next_a); } else { SETCALC(Select_next_k); } Select_next_1(unit, 1); } void Select_next_1(Select* unit, int inNumSamples) { int32 maxindex = unit->mNumInputs - 1; int32 index = (int32)ZIN0(0) + 1; index = sc_clip(index, 1, maxindex); ZOUT0(0) = ZIN0(index); } void Select_next_k(Select* unit, int inNumSamples) { int32 maxindex = unit->mNumInputs - 1; int32 index = (int32)ZIN0(0) + 1; index = sc_clip(index, 1, maxindex); float* out = OUT(0); float* in = IN(index); Copy(inNumSamples, out, in); } void Select_next_a(Select* unit, int inNumSamples) { int32 maxindex = unit->mNumInputs - 1; float* out = ZOUT(0); float* in0 = ZIN(0); float** in = unit->mInBuf; for (int i = 0; i < inNumSamples; ++i) { int32 index = (int32)ZXP(in0) + 1; index = sc_clip(index, 1, maxindex); ZXP(out) = in[index][i]; } } //////////////////////////////////////////////////////////////////////////////////// static int32 TWindex_chooseNewIndex(TWindex* unit) { int maxindex = unit->mNumInputs; int32 index = maxindex; float normalize = ZIN0(1); float maxSum = unit->m_maxSum; if (maxSum < 0.f) { maxSum = 0.f; if (normalize == 1) { for (int32 k = 2; k < maxindex; ++k) { maxSum += ZIN0(k); } } else maxSum = 1.f; unit->m_maxSum = maxSum; } RGen& rgen = *unit->mParent->mRGen; float max = maxSum * rgen.frand(); float sum = 0.f; for (int32 k = 2; k < maxindex; ++k) { sum += ZIN0(k); if (sum >= max) { index = k - 2; break; } } return index; } void TWindex_Ctor(TWindex* unit) { if (INRATE(0) == calc_FullRate) { SETCALC(TWindex_next_a); } else { SETCALC(TWindex_next_k); } unit->m_maxSum = -1.f; // trigger update of maxSum int32 index = TWindex_chooseNewIndex(unit); OUT0(0) = index; unit->m_prevIndex = index; // Ensure a first-sample trigger doesn't cause another rand val // so initialization sample will equal first output sample unit->m_trig = 1.f; } void TWindex_next_k(TWindex* unit, int inNumSamples) { float trig = ZIN0(0); float* out = ZOUT(0); int32 index; unit->m_maxSum = -1.f; if (trig > 0.f && unit->m_trig <= 0.f) { index = TWindex_chooseNewIndex(unit); unit->m_prevIndex = index; } else { index = unit->m_prevIndex; } LOOP1(inNumSamples, ZXP(out) = index;) unit->m_trig = trig; } void TWindex_next_a(TWindex* unit, int inNumSamples) { float* trig = ZIN(0); float* out = ZOUT(0); int32 index; float curtrig; unit->m_maxSum = -1.f; LOOP1( inNumSamples, curtrig = ZXP(trig); if (curtrig > 0.f && unit->m_trig <= 0.f) { index = TWindex_chooseNewIndex(unit); unit->m_prevIndex = index; } else index = unit->m_prevIndex; ZXP(out) = index; unit->m_trig = curtrig;) } //////////////////////////////////////////////////////////////////////////////////// void Index_Ctor(Index* unit) { unit->m_fbufnum = std::numeric_limits<float>::quiet_NaN(); if (BUFLENGTH == 1) { SETCALC(Index_next_1); } else if (INRATE(1) == calc_FullRate) { SETCALC(Index_next_a); } else { SETCALC(Index_next_k); } Index_next_1(unit, 1); } void Index_next_1(Index* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; int32 index = (int32)ZIN0(1); index = sc_clip(index, 0, maxindex); ZOUT0(0) = table[index]; } void Index_next_k(Index* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; float* out = ZOUT(0); int32 index = (int32)ZIN0(1); index = sc_clip(index, 0, maxindex); float val = table[index]; LOOP1(inNumSamples, ZXP(out) = val;); } void Index_next_a(Index* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; float* out = ZOUT(0); float* in = ZIN(1); LOOP1(inNumSamples, int32 index = (int32)ZXP(in); index = sc_clip(index, 0, maxindex); ZXP(out) = table[index];); } //////////////////////////////////////////////////////////////////////////////////// void IndexL_Ctor(IndexL* unit) { unit->m_fbufnum = std::numeric_limits<float>::quiet_NaN(); if (BUFLENGTH == 1) { SETCALC(IndexL_next_1); } else if (INRATE(1) == calc_FullRate) { SETCALC(IndexL_next_a); } else { SETCALC(IndexL_next_k); } IndexL_next_1(unit, 1); } void IndexL_next_1(IndexL* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; float findex = ZIN0(1); float frac = sc_frac(findex); int32 index = (int32)findex; index = sc_clip(index, 0, maxindex); float a = table[index]; float b = table[sc_clip(index + 1, 0, maxindex)]; ZOUT0(0) = lininterp(frac, a, b); } void IndexL_next_k(IndexL* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; float* out = ZOUT(0); float findex = ZIN0(1); float frac = sc_frac(findex); int32 index = (int32)findex; index = sc_clip(index, 0, maxindex); float a = table[index]; float b = table[sc_clip(index + 1, 0, maxindex)]; float val = lininterp(frac, a, b); LOOP1(inNumSamples, ZXP(out) = val;); } void IndexL_next_a(IndexL* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; float* out = ZOUT(0); float* in = ZIN(1); LOOP1(inNumSamples, float findex = ZXP(in); float frac = sc_frac(findex); int32 i1 = sc_clip((int32)findex, 0, maxindex); int32 i2 = sc_clip(i1 + 1, 0, maxindex); float a = table[i1]; float b = table[i2]; ZXP(out) = lininterp(frac, a, b);); } //////////////////////////////////////////////////////////////////////////////////// void FoldIndex_Ctor(FoldIndex* unit) { unit->m_fbufnum = std::numeric_limits<float>::quiet_NaN(); if (BUFLENGTH == 1) { SETCALC(FoldIndex_next_1); } else if (INRATE(1) == calc_FullRate) { SETCALC(FoldIndex_next_a); } else { SETCALC(FoldIndex_next_k); } FoldIndex_next_1(unit, 1); } void FoldIndex_next_1(FoldIndex* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; int32 index = (int32)ZIN0(1); index = sc_fold(index, 0, maxindex); ZOUT0(0) = table[index]; } void FoldIndex_next_k(FoldIndex* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; int32 index = (int32)ZIN0(1); float* out = ZOUT(0); index = sc_fold(index, 0, maxindex); float val = table[index]; LOOP1(inNumSamples, ZXP(out) = val;); } void FoldIndex_next_a(FoldIndex* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; float* out = ZOUT(0); float* in = ZIN(1); LOOP1(inNumSamples, int32 index = (int32)ZXP(in); index = sc_fold(index, 0, maxindex); ZXP(out) = table[index];); } //////////////////////////////////////////////////////////////////////////////////// void WrapIndex_Ctor(WrapIndex* unit) { unit->m_fbufnum = std::numeric_limits<float>::quiet_NaN(); if (BUFLENGTH == 1) { SETCALC(WrapIndex_next_1); } else if (INRATE(1) == calc_FullRate) { SETCALC(WrapIndex_next_a); } else { SETCALC(WrapIndex_next_k); } WrapIndex_next_1(unit, 1); } void WrapIndex_next_1(WrapIndex* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; int32 index = (int32)floor(ZIN0(1)); index = sc_wrap(index, 0, maxindex); ZOUT0(0) = table[index]; } void WrapIndex_next_k(WrapIndex* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; float* out = ZOUT(0); int32 index = (int32)ZIN0(1); index = sc_wrap(index, 0, maxindex); float val = table[index]; LOOP1(inNumSamples, ZXP(out) = val;); } void WrapIndex_next_a(WrapIndex* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; float* out = ZOUT(0); float* in = ZIN(1); LOOP1(inNumSamples, int32 index = (int32)ZXP(in); index = sc_wrap(index, 0, maxindex); ZXP(out) = table[index];); } //////////////////////////////////////////////////////////////////////////////////// static float IndexInBetween_FindIndex(const float* table, float in, int32 maxindex) { for (int32 i = 0; i <= maxindex; i++) { if (table[i] > in) { if (i == 0) { return 0.f; } else { return ((in - table[i - 1]) / (table[i] - table[i - 1]) + i - 1); } } } return (float)maxindex; } void IndexInBetween_Ctor(IndexInBetween* unit) { unit->m_fbufnum = std::numeric_limits<float>::quiet_NaN(); if (BUFLENGTH == 1) { SETCALC(IndexInBetween_next_1); } else if (INRATE(1) == calc_FullRate) { SETCALC(IndexInBetween_next_a); } else { SETCALC(IndexInBetween_next_k); } IndexInBetween_next_1(unit, 1); } void IndexInBetween_next_1(IndexInBetween* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; float in = ZIN0(1); ZOUT0(0) = IndexInBetween_FindIndex(table, in, maxindex); } void IndexInBetween_next_k(IndexInBetween* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; float* out = ZOUT(0); float in = ZIN0(1); float val = IndexInBetween_FindIndex(table, in, maxindex); LOOP1(inNumSamples, ZXP(out) = val;); } void IndexInBetween_next_a(IndexInBetween* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; float* out = ZOUT(0); float* in = ZIN(1); LOOP1(inNumSamples, ZXP(out) = IndexInBetween_FindIndex(table, ZXP(in), maxindex);); } //////////////////////////////////////////////////////////////////////////////////// static int32 DetectIndex_FindIndex(const float* table, float in, int32 maxindex) { int32 index; for (index = 0; index <= maxindex; index += 1) { if (table[index] == in) { return index; } } return -1; } void DetectIndex_Ctor(DetectIndex* unit) { unit->m_fbufnum = std::numeric_limits<float>::quiet_NaN(); if (BUFLENGTH == 1) { SETCALC(DetectIndex_next_1); } else if (INRATE(1) == calc_FullRate) { SETCALC(DetectIndex_next_a); } else { SETCALC(DetectIndex_next_k); } unit->mPrev = -1.f; // ensure in != unit->mPrevIn on first frame unit->mPrevIn = std::numeric_limits<float>::quiet_NaN(); DetectIndex_next_1(unit, 1); } void DetectIndex_next_1(DetectIndex* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; float in = ZIN0(1); int32 index; if (in == unit->mPrevIn) { index = (int32)unit->mPrev; } else { index = DetectIndex_FindIndex(table, in, maxindex); unit->mPrev = index; unit->mPrevIn = in; } ZOUT0(0) = (float)index; } void DetectIndex_next_k(DetectIndex* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; float* out = ZOUT(0); float in = ZIN0(1); int32 index; float val; if (in == unit->mPrevIn) { index = (int32)unit->mPrev; } else { index = DetectIndex_FindIndex(table, in, maxindex); unit->mPrev = index; unit->mPrevIn = in; }; val = (float)index; LOOP1(inNumSamples, ZXP(out) = val;); } void DetectIndex_next_a(DetectIndex* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; int32 maxindex = tableSize - 1; float* out = ZOUT(0); float* in = ZIN(1); float prev = unit->mPrevIn; int32 prevIndex = (int32)unit->mPrev; float inval; LOOP1( inNumSamples, inval = ZXP(in); if (inval != prev) { prevIndex = DetectIndex_FindIndex(table, inval, maxindex); } prev = inval; ZXP(out) = (float)prevIndex;); unit->mPrev = prevIndex; unit->mPrevIn = inval; } //////////////////////////////////////////////////////////////////////////////////// void Shaper_Ctor(Shaper* unit) { unit->m_fbufnum = std::numeric_limits<float>::quiet_NaN(); if (BUFLENGTH == 1) { SETCALC(Shaper_next_1); } else if (INRATE(1) == calc_FullRate) { SETCALC(Shaper_next_a); } else { SETCALC(Shaper_next_k); } unit->mPrevIn = ZIN0(1); Shaper_next_1(unit, 1); } float force_inline ShaperPerform(const float* table0, const float* table1, float in, float offset, float fmaxindex) { float findex = offset + in * offset; findex = sc_clip(findex, 0.f, fmaxindex); int32 index = (int32)findex; float pfrac = findex - (index - 1); index <<= 3; float val1 = *(const float*)((const char*)table0 + index); float val2 = *(const float*)((const char*)table1 + index); float val = val1 + val2 * pfrac; return val; } void Shaper_next_1(Shaper* unit, int inNumSamples) { // get table GET_TABLE const float* table0 = bufData; const float* table1 = table0 + 1; float fmaxindex = (float)(tableSize >> 1) - 0.001; float offset = tableSize * 0.25; ZOUT0(0) = ShaperPerform(table0, table1, ZIN0(1), offset, fmaxindex); } void Shaper_next_k(Shaper* unit, int inNumSamples) { // get table GET_TABLE const float* table0 = bufData; const float* table1 = table0 + 1; float fmaxindex = (float)(tableSize >> 1) - 0.001; float offset = tableSize * 0.25; float* out = ZOUT(0); float fin = ZIN0(1); if (fin == unit->mPrevIn) { LOOP1(inNumSamples, ZXP(out) = ShaperPerform(table0, table1, fin, offset, fmaxindex);); } else { float phaseinc = (fin - unit->mPrevIn) * offset; unit->mPrevIn = fin; LOOP1(inNumSamples, ZXP(out) = ShaperPerform(table0, table1, fin, offset, fmaxindex); fin += phaseinc;); } } void Shaper_next_a(Shaper* unit, int inNumSamples) { // get table GET_TABLE const float* table0 = bufData; const float* table1 = table0 + 1; float fmaxindex = (float)(tableSize >> 1) - 0.001; float offset = tableSize * 0.25; float* out = ZOUT(0); const float* in = ZIN(1); LOOP1(inNumSamples, float fin = ZXP(in); ZXP(out) = ShaperPerform(table0, table1, fin, offset, fmaxindex);); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void FSinOsc_Ctor(FSinOsc* unit) { double b1, y1, y2; if (INRATE(0) == calc_ScalarRate) SETCALC(FSinOsc_next_i); else SETCALC(FSinOsc_next); unit->m_freq = ZIN0(0); float iphase = ZIN0(1); float w = unit->m_freq * unit->mRate->mRadiansPerSample; unit->m_b1 = b1 = 2. * cos(w); unit->m_y1 = y1 = sin(iphase - w); unit->m_y2 = y2 = sin(iphase - 2 * w); ZOUT0(0) = b1 * y1 - y2; } void FSinOsc_next(FSinOsc* unit, int inNumSamples) { float* out = ZOUT(0); double freq = ZIN0(0); double b1; if (freq != unit->m_freq) { unit->m_freq = freq; double w = freq * unit->mRate->mRadiansPerSample; unit->m_b1 = b1 = 2.f * cos(w); } else { b1 = unit->m_b1; } double y0; double y1 = unit->m_y1; double y2 = unit->m_y2; LOOP(unit->mRate->mFilterLoops, ZXP(out) = y0 = b1 * y1 - y2; ZXP(out) = y2 = b1 * y0 - y1; ZXP(out) = y1 = b1 * y2 - y0;); LOOP(unit->mRate->mFilterRemain, ZXP(out) = y0 = b1 * y1 - y2; y2 = y1; y1 = y0;); unit->m_y1 = y1; unit->m_y2 = y2; } void FSinOsc_next_i(FSinOsc* unit, int inNumSamples) { float* __restrict__ out = ZOUT(0); double b1 = unit->m_b1; double y0; double y1 = unit->m_y1; double y2 = unit->m_y2; LOOP(unit->mRate->mFilterLoops, y0 = b1 * y1 - y2; y2 = b1 * y0 - y1; y1 = b1 * y2 - y0; ZXP(out) = y0; ZXP(out) = y2; ZXP(out) = y1;); LOOP(unit->mRate->mFilterRemain, ZXP(out) = y0 = b1 * y1 - y2; y2 = y1; y1 = y0;); unit->m_y1 = y1; unit->m_y2 = y2; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void PSinGrain_Ctor(PSinGrain* unit) { SETCALC(PSinGrain_next); float freq = ZIN0(0); float dur = ZIN0(1); float amp = ZIN0(2); float w = freq * unit->mRate->mRadiansPerSample; float sdur = SAMPLERATE * dur; float rdur = 1.f / sdur; float rdur2 = rdur * rdur; unit->m_level = 0.f; unit->m_slope = 4.0 * (rdur - rdur2); // ampslope unit->m_curve = -8.0 * rdur2; // ampcurve unit->mCounter = (int32)(sdur + .5); /* calc feedback param and initial conditions */ double b1, y1, y2; unit->m_b1 = b1 = 2. * cos(w); unit->m_y1 = y1 = -sin(w) * amp; unit->m_y2 = y2 = -sin(w + w) * amp; ZOUT0(0) = b1 * y1 - y2; } void PSinGrain_next(PSinGrain* unit, int inNumSamples) { float* out = ZOUT(0); float y0; float y1 = unit->m_y1; float y2 = unit->m_y2; float b1 = unit->m_b1; float level = unit->m_level; float slope = unit->m_slope; float curve = unit->m_curve; int32 counter = unit->mCounter; int32 remain = inNumSamples; int32 nsmps; do { if (counter <= 0) { nsmps = remain; remain = 0; LOOP(nsmps, ZXP(out) = 0.f;); // can't use Clear bcs might not be aligned } else { nsmps = sc_min(remain, counter); remain -= nsmps; counter -= nsmps; if (nsmps == inNumSamples) { nsmps = unit->mRate->mFilterLoops; LOOP(nsmps, y0 = b1 * y1 - y2; ZXP(out) = y0 * level; level += slope; slope += curve; y2 = b1 * y0 - y1; ZXP(out) = y2 * level; level += slope; slope += curve; y1 = b1 * y2 - y0; ZXP(out) = y1 * level; level += slope; slope += curve;); nsmps = unit->mRate->mFilterRemain; LOOP(nsmps, y0 = b1 * y1 - y2; y2 = y1; y1 = y0; ZXP(out) = y0 * level; level += slope; slope += curve;); } else { LOOP(nsmps, y0 = b1 * y1 - y2; y2 = y1; y1 = y0; ZXP(out) = y0 * level; level += slope; slope += curve;); } if (counter == 0) { NodeEnd(&unit->mParent->mNode); } } } while (remain > 0); unit->mCounter = counter; unit->m_level = level; unit->m_slope = slope; unit->m_y1 = y1; unit->m_y2 = y2; } //////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename OscType, int FreqInputIndex> force_inline void Osc_ikk_perform(OscType* unit, const float* table0, const float* table1, int inNumSamples) { float* out = ZOUT(0); float freqin = ZIN0(FreqInputIndex); float phasein = ZIN0(FreqInputIndex + 1); int32 phase = unit->m_phase; int32 lomask = unit->m_lomask; int32 freq = (int32)(unit->m_cpstoinc * freqin); int32 phaseinc = freq + (int32)(CALCSLOPE(phasein, unit->m_phasein) * unit->m_radtoinc); unit->m_phasein = phasein; LOOP1(inNumSamples, ZXP(out) = lookupi1(table0, table1, phase, lomask); phase += phaseinc;); unit->m_phase = phase; } void SinOsc_next_ikk(SinOsc* unit, int inNumSamples) { float* table0 = ft->mSineWavetable; float* table1 = table0 + 1; Osc_ikk_perform<SinOsc, 0>(unit, table0, table1, inNumSamples); } template <typename OscType, int FreqInputIndex> force_inline void Osc_ika_perform(OscType* unit, const float* table0, const float* table1, int inNumSamples) { float* out = ZOUT(0); float freqin = ZIN0(FreqInputIndex); float* phasein = ZIN(FreqInputIndex + 1); int32 phase = unit->m_phase; int32 lomask = unit->m_lomask; int32 freq = (int32)(unit->m_cpstoinc * freqin); float radtoinc = unit->m_radtoinc; LOOP1(inNumSamples, int32 phaseoffset = phase + (int32)(radtoinc * ZXP(phasein)); ZXP(out) = lookupi1(table0, table1, phaseoffset, lomask); phase += freq;); unit->m_phase = phase; } void SinOsc_next_ika(SinOsc* unit, int inNumSamples) { const float* table0 = ft->mSineWavetable; const float* table1 = table0 + 1; Osc_ika_perform<SinOsc, 0>(unit, table0, table1, inNumSamples); } template <typename OscType, int FreqInputIndex> force_inline void Osc_iaa_perform(OscType* unit, const float* table0, const float* table1, int inNumSamples) { float* out = ZOUT(0); float* freqin = ZIN(FreqInputIndex); float* phasein = ZIN(FreqInputIndex + 1); int32 phase = unit->m_phase; int32 lomask = unit->m_lomask; float cpstoinc = unit->m_cpstoinc; float radtoinc = unit->m_radtoinc; LOOP1(inNumSamples, float phaseIn = ZXP(phasein); float freqIn = ZXP(freqin); int32 phaseoffset = phase + (int32)(radtoinc * phaseIn); float z = lookupi1(table0, table1, phaseoffset, lomask); phase += (int32)(cpstoinc * freqIn); ZXP(out) = z;); unit->m_phase = phase; } void SinOsc_next_iaa(SinOsc* unit, int inNumSamples) { const float* table0 = ft->mSineWavetable; const float* table1 = table0 + 1; Osc_iaa_perform<SinOsc, 0>(unit, table0, table1, inNumSamples); } template <typename OscType, int FreqInputIndex> force_inline void Osc_iak_perform(OscType* unit, const float* table0, const float* table1, int inNumSamples) { float* out = ZOUT(0); float* freqin = ZIN(FreqInputIndex); float phasein = ZIN0(FreqInputIndex + 1); int32 phase = unit->m_phase; int32 lomask = unit->m_lomask; float cpstoinc = unit->m_cpstoinc; float radtoinc = unit->m_radtoinc; float phasemod = unit->m_phasein; if (phasein != phasemod) { float phaseslope = CALCSLOPE(phasein, phasemod); LOOP1(inNumSamples, int32 pphase = phase + (int32)(radtoinc * phasemod); phasemod += phaseslope; float z = lookupi1(table0, table1, pphase, lomask); phase += (int32)(cpstoinc * ZXP(freqin)); ZXP(out) = z;); } else { LOOP1(inNumSamples, int32 pphase = phase + (int32)(radtoinc * phasemod); float z = lookupi1(table0, table1, pphase, lomask); phase += (int32)(cpstoinc * ZXP(freqin)); ZXP(out) = z;); } unit->m_phase = phase; unit->m_phasein = phasein; } void SinOsc_next_iak(SinOsc* unit, int inNumSamples) { float* table0 = ft->mSineWavetable; float* table1 = table0 + 1; Osc_iak_perform<SinOsc, 0>(unit, table0, table1, inNumSamples); } template <typename OscType, int FreqInputIndex> force_inline void Osc_iai_perform(OscType* unit, const float* table0, const float* table1, int inNumSamples) { float* out = ZOUT(0); float* freqin = ZIN(FreqInputIndex); int32 phase = unit->m_phase; int32 lomask = unit->m_lomask; float cpstoinc = unit->m_cpstoinc; float radtoinc = unit->m_radtoinc; float phasemod = unit->m_phasein; LOOP1(inNumSamples, int32 pphase = phase + (int32)(radtoinc * phasemod); float z = lookupi1(table0, table1, pphase, lomask); phase += (int32)(cpstoinc * ZXP(freqin)); ZXP(out) = z;); unit->m_phase = phase; } void SinOsc_next_iai(SinOsc* unit, int inNumSamples) { float* table0 = ft->mSineWavetable; float* table1 = table0 + 1; Osc_iai_perform<SinOsc, 0>(unit, table0, table1, inNumSamples); } void SinOsc_Ctor(SinOsc* unit) { int tableSize2 = ft->mSineSize; unit->m_phasein = ZIN0(1); unit->m_radtoinc = tableSize2 * (rtwopi * 65536.); unit->m_cpstoinc = tableSize2 * SAMPLEDUR * 65536.; unit->m_lomask = (tableSize2 - 1) << 3; int32 initPhase; if (INRATE(0) == calc_FullRate) { if (INRATE(1) == calc_FullRate) SETCALC(SinOsc_next_iaa); else if (INRATE(1) == calc_BufRate) SETCALC(SinOsc_next_iak); else SETCALC(SinOsc_next_iai); unit->m_phase = initPhase = 0; SinOsc_next_iaa(unit, 1); } else { if (INRATE(1) == calc_FullRate) { SETCALC(SinOsc_next_ika); unit->m_phase = initPhase = 0; SinOsc_next_iaa(unit, 1); } else { SETCALC(SinOsc_next_ikk); unit->m_phase = initPhase = (int32)(unit->m_phasein * unit->m_radtoinc); SinOsc_next_ikk(unit, 1); } } unit->m_phase = initPhase; } //////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////!!! void SinOscFB_next_kk(SinOscFB* unit, int inNumSamples) { float* out = ZOUT(0); float freqin = ZIN0(0); float feedback = unit->m_feedback; float nextFeedback = ZIN0(1) * unit->m_radtoinc; float* table0 = ft->mSineWavetable; float* table1 = table0 + 1; int32 phase = unit->m_phase; int32 lomask = unit->m_lomask; float prevout = unit->m_prevout; float feedback_slope = CALCSLOPE(nextFeedback, feedback); int32 freq = (int32)(unit->m_cpstoinc * freqin); LooP(inNumSamples) { prevout = lookupi1(table0, table1, phase + (int32)(feedback * prevout), lomask); ZXP(out) = prevout; phase += freq; feedback += feedback_slope; } unit->m_phase = phase; unit->m_prevout = prevout; unit->m_feedback = feedback; } void SinOscFB_Ctor(SinOscFB* unit) { SETCALC(SinOscFB_next_kk); int tableSize2 = ft->mSineSize; unit->m_lomask = (tableSize2 - 1) << 3; unit->m_radtoinc = tableSize2 * (rtwopi * 65536.); unit->m_cpstoinc = tableSize2 * SAMPLEDUR * 65536.; unit->m_prevout = 0.; unit->m_feedback = ZIN0(1) * unit->m_radtoinc; unit->m_phase = 0; SinOscFB_next_kk(unit, 1); unit->m_phase = 0; } //////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// void Osc_Ctor(Osc* unit) { unit->mTableSize = -1; float fbufnum = ZIN0(0); uint32 bufnum = (uint32)fbufnum; World* world = unit->mWorld; SndBuf* buf; if (bufnum >= world->mNumSndBufs) { int localBufNum = bufnum - world->mNumSndBufs; Graph* parent = unit->mParent; if (localBufNum <= parent->localBufNum) { buf = unit->m_buf = parent->mLocalSndBufs + localBufNum; } else { buf = unit->m_buf = world->mSndBufs; } } else { buf = unit->m_buf = world->mSndBufs + bufnum; } int tableSize = buf->samples; int tableSize2 = tableSize >> 1; unit->m_radtoinc = tableSize2 * (rtwopi * 65536.); // Osc, OscN, PMOsc unit->m_phasein = ZIN0(2); int32 initphase; if (INRATE(1) == calc_FullRate) { if (INRATE(2) == calc_FullRate) { SETCALC(Osc_next_iaa); } else { SETCALC(Osc_next_iak); } unit->m_phase = initphase = 0; Osc_next_iaa(unit, 1); } else { if (INRATE(2) == calc_FullRate) { SETCALC(Osc_next_ika); unit->m_phase = initphase = 0; Osc_next_iaa(unit, 1); } else { SETCALC(Osc_next_ikk); unit->m_phase = initphase = (int32)(unit->m_phasein * unit->m_radtoinc); Osc_next_ikk(unit, 1); } } unit->m_phase = initphase; } force_inline bool Osc_get_table(Osc* unit, const float*& table0, const float*& table1, int inNumSamples) { const SndBuf* buf; const float* bufData; int tableSize; bool tableValid = UnitGetTable(unit, inNumSamples, buf, bufData, tableSize); if (!tableValid) return false; table0 = bufData; table1 = table0 + 1; if (tableSize != unit->mTableSize) { unit->mTableSize = tableSize; int tableSize2 = tableSize >> 1; unit->m_lomask = (tableSize2 - 1) << 3; // Osc, OscN, COsc, COsc, COsc2, OscX4, OscX2 unit->m_radtoinc = tableSize2 * (rtwopi * 65536.); // Osc, OscN, PMOsc // Osc, OscN, PMOsc, COsc, COsc2, OscX4, OscX2 unit->m_cpstoinc = tableSize2 * SAMPLEDUR * 65536.; } if (!verify_wavetable(unit, "Osc", tableSize, inNumSamples)) return false; return true; } void Osc_next_ikk(Osc* unit, int inNumSamples) { const float* table0; const float* table1; bool tableValid = Osc_get_table(unit, table0, table1, inNumSamples); if (!tableValid) return; Osc_ikk_perform<Osc, 1>(unit, table0, table1, inNumSamples); } void Osc_next_ika(Osc* unit, int inNumSamples) { const float* table0; const float* table1; bool tableValid = Osc_get_table(unit, table0, table1, inNumSamples); if (!tableValid) return; Osc_ika_perform<Osc, 1>(unit, table0, table1, inNumSamples); } void Osc_next_iaa(Osc* unit, int inNumSamples) { const float* table0; const float* table1; bool tableValid = Osc_get_table(unit, table0, table1, inNumSamples); if (!tableValid) return; Osc_iaa_perform<Osc, 1>(unit, table0, table1, inNumSamples); } void Osc_next_iak(Osc* unit, int inNumSamples) { const float* table0; const float* table1; bool tableValid = Osc_get_table(unit, table0, table1, inNumSamples); if (!tableValid) return; Osc_iak_perform<Osc, 1>(unit, table0, table1, inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////////// void OscN_Ctor(OscN* unit) { unit->mTableSize = -1; float fbufnum = ZIN0(0); uint32 bufnum = (uint32)fbufnum; World* world = unit->mWorld; SndBuf* buf; if (bufnum >= world->mNumSndBufs) { int localBufNum = bufnum - world->mNumSndBufs; Graph* parent = unit->mParent; if (localBufNum <= parent->localBufNum) { buf = unit->m_buf = parent->mLocalSndBufs + localBufNum; } else { buf = unit->m_buf = world->mSndBufs; } } else { buf = unit->m_buf = world->mSndBufs + bufnum; } int tableSize = buf->samples; unit->m_radtoinc = tableSize * (rtwopi * 65536.); unit->m_phasein = ZIN0(2); int32 initphase; if (INRATE(1) == calc_FullRate) { if (INRATE(2) == calc_FullRate) { SETCALC(OscN_next_naa); } else { SETCALC(OscN_next_nak); } unit->m_phase = initphase = 0; OscN_next_naa(unit, 1); } else { if (INRATE(2) == calc_FullRate) { SETCALC(OscN_next_nka); unit->m_phase = initphase = 0; OscN_next_naa(unit, 1); } else { SETCALC(OscN_next_nkk); unit->m_phase = initphase = (int32)(unit->m_phasein * unit->m_radtoinc); OscN_next_nkk(unit, 1); } } unit->m_phase = initphase; } void OscN_next_nkk(OscN* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; if (tableSize != unit->mTableSize) { unit->mTableSize = tableSize; unit->m_lomask = (tableSize - 1) << 2; unit->m_radtoinc = tableSize * (rtwopi * 65536.); unit->m_cpstoinc = tableSize * SAMPLEDUR * 65536.; } if (!verify_wavetable(unit, "OscN", tableSize, inNumSamples)) return; float* out = ZOUT(0); float freqin = ZIN0(1); float phasein = ZIN0(2); int32 phase = unit->m_phase; int32 lomask = unit->m_lomask; int32 freq = (int32)(unit->m_cpstoinc * freqin); int32 phaseinc = freq + (int32)(CALCSLOPE(phasein, unit->m_phasein) * unit->m_radtoinc); unit->m_phasein = phasein; LOOP1(inNumSamples, ZXP(out) = *(float*)((char*)table + ((phase >> xlobits) & lomask)); phase += phaseinc;); unit->m_phase = phase; } void OscN_next_nka(OscN* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; if (tableSize != unit->mTableSize) { unit->mTableSize = tableSize; unit->m_lomask = (tableSize - 1) << 2; unit->m_radtoinc = tableSize * (rtwopi * 65536.); unit->m_cpstoinc = tableSize * SAMPLEDUR * 65536.; } if (!verify_wavetable(unit, "OscN", tableSize, inNumSamples)) return; float* out = ZOUT(0); float freqin = ZIN0(1); float* phasein = ZIN(2); int32 phase = unit->m_phase; int32 lomask = unit->m_lomask; int32 freq = (int32)(unit->m_cpstoinc * freqin); float radtoinc = unit->m_radtoinc; LOOP1(inNumSamples, int32 pphase = phase + (int32)(radtoinc * ZXP(phasein)); ZXP(out) = *(float*)((char*)table + ((pphase >> xlobits) & lomask)); phase += freq;); unit->m_phase = phase; } void OscN_next_naa(OscN* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; if (tableSize != unit->mTableSize) { unit->mTableSize = tableSize; unit->m_lomask = (tableSize - 1) << 2; unit->m_radtoinc = tableSize * (rtwopi * 65536.); unit->m_cpstoinc = tableSize * SAMPLEDUR * 65536.; } if (!verify_wavetable(unit, "OscN", tableSize, inNumSamples)) return; float* out = ZOUT(0); float* freqin = ZIN(1); float* phasein = ZIN(2); int32 phase = unit->m_phase; int32 lomask = unit->m_lomask; float cpstoinc = unit->m_cpstoinc; float radtoinc = unit->m_radtoinc; LOOP1(inNumSamples, int32 pphase = phase + (int32)(radtoinc * ZXP(phasein)); float z = *(float*)((char*)table + ((pphase >> xlobits) & lomask)); phase += (int32)(cpstoinc * ZXP(freqin)); ZXP(out) = z;); unit->m_phase = phase; } void OscN_next_nak(OscN* unit, int inNumSamples) { // get table GET_TABLE const float* table = bufData; if (tableSize != unit->mTableSize) { unit->mTableSize = tableSize; unit->m_lomask = (tableSize - 1) << 2; unit->m_radtoinc = tableSize * (rtwopi * 65536.); unit->m_cpstoinc = tableSize * SAMPLEDUR * 65536.; } if (!verify_wavetable(unit, "OscN", tableSize, inNumSamples)) return; float* out = ZOUT(0); float* freqin = ZIN(1); float phasein = ZIN0(2); int32 phase = unit->m_phase; int32 lomask = unit->m_lomask; float cpstoinc = unit->m_cpstoinc; float radtoinc = unit->m_radtoinc; float phasemod = unit->m_phasein; float phaseslope = CALCSLOPE(phasein, phasemod); LOOP1(inNumSamples, int32 pphase = phase + (int32)(radtoinc * phasemod); phasemod += phaseslope; float z = *(float*)((char*)table + ((pphase >> xlobits) & lomask)); phase += (int32)(cpstoinc * ZXP(freqin)); ZXP(out) = z;); unit->m_phase = phase; unit->m_phasein = phasein; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void COsc_Ctor(COsc* unit) { unit->m_fbufnum = std::numeric_limits<float>::quiet_NaN(); SETCALC(COsc_next); unit->m_phase1 = 0; unit->m_phase2 = 0; unit->mTableSize = -1; COsc_next(unit, 1); unit->m_phase1 = 0; unit->m_phase2 = 0; } void COsc_next(COsc* unit, int inNumSamples) { // get table GET_TABLE const float* table0 = bufData; const float* table1 = table0 + 1; if (tableSize != unit->mTableSize) { unit->mTableSize = tableSize; int tableSize2 = tableSize >> 1; unit->m_lomask = (tableSize2 - 1) << 3; // Osc, OscN, COsc, COsc, COsc2, OscX4, OscX2 // Osc, OscN, PMOsc, COsc, COsc2, OscX4, OscX2 unit->m_cpstoinc = tableSize2 * SAMPLEDUR * 65536.; } if (!verify_wavetable(unit, "COsc", tableSize, inNumSamples)) return; float* out = ZOUT(0); float freqin = ZIN0(1); float beats = ZIN0(2) * 0.5f; int32 phase1 = unit->m_phase1; int32 phase2 = unit->m_phase2; int32 lomask = unit->m_lomask; int32 cfreq = (int32)(unit->m_cpstoinc * freqin); int32 beatf = (int32)(unit->m_cpstoinc * beats); int32 freq1 = cfreq + beatf; int32 freq2 = cfreq - beatf; LOOP1(inNumSamples, float a = lookupi1(table0, table1, phase1, lomask); float b = lookupi1(table0, table1, phase2, lomask); ZXP(out) = a + b; phase1 += freq1; phase2 += freq2;); unit->m_phase1 = phase1; unit->m_phase2 = phase2; } //////////////////////////////////////////////////////////////////////////////////////////////////////// static inline const SndBuf* VOscGetBuf(int& bufnum, World* world, Unit* unit) { if (bufnum < 0) bufnum = 0; const SndBuf* bufs; if (bufnum + 1 >= world->mNumSndBufs) { int localBufNum = bufnum - world->mNumSndBufs; Graph* parent = unit->mParent; if (localBufNum <= parent->localBufNum) { bufs = parent->mLocalSndBufs + localBufNum; } else { bufnum = 0; bufs = world->mSndBufs + bufnum; } } else { if (bufnum >= world->mNumSndBufs) bufnum = 0; bufs = world->mSndBufs + sc_max(0, bufnum); } return bufs; } void VOsc_Ctor(VOsc* unit) { float nextbufpos = ZIN0(0); unit->m_bufpos = nextbufpos; int bufnum = sc_floor(nextbufpos); World* world = unit->mWorld; const SndBuf* bufs = VOscGetBuf(bufnum, world, unit); int tableSize = bufs[0].samples; unit->mTableSize = tableSize; int tableSize2 = tableSize >> 1; unit->m_lomask = (tableSize2 - 1) << 3; unit->m_radtoinc = tableSize2 * (rtwopi * 65536.); unit->m_cpstoinc = tableSize2 * SAMPLEDUR * 65536.; unit->m_phasein = ZIN0(2); unit->m_phaseoffset = (int32)(unit->m_phasein * unit->m_radtoinc); double initphase; if (INRATE(2) == calc_FullRate) { SETCALC(VOsc_next_ika); unit->m_phase = initphase = 0; VOsc_next_ika(unit, 1); } else { SETCALC(VOsc_next_ikk); unit->m_phase = initphase = unit->m_phaseoffset; VOsc_next_ikk(unit, 1); } unit->m_phase = initphase; } void VOsc_next_ikk(VOsc* unit, int inNumSamples) { float* out = ZOUT(0); float nextbufpos = ZIN0(0); float freqin = ZIN0(1); float phasein = ZIN0(2); float prevbufpos = unit->m_bufpos; float bufdiff = nextbufpos - prevbufpos; int32 phase = unit->m_phase; int32 lomask = unit->m_lomask; int32 freq = (int32)(unit->m_cpstoinc * freqin); int32 phaseinc = freq + (int32)(CALCSLOPE(phasein, unit->m_phasein) * unit->m_radtoinc); unit->m_phasein = phasein; int tableSize = unit->mTableSize; float cur = prevbufpos; World* world = unit->mWorld; if (bufdiff == 0.f) { float level = cur - sc_floor(cur); int32 bufnum = (int)sc_floor(cur); const SndBuf* bufs = VOscGetBuf(bufnum, world, unit); if (!verify_wavetable(unit, "VOsc", tableSize, inNumSamples)) return; const float* table0 = bufs[0].data; const float* table2 = bufs[1].data; if (!table0 || !table2 || tableSize != bufs[0].samples || tableSize != bufs[1].samples) { ClearUnitOutputs(unit, inNumSamples); return; } const float* table1 = table0 + 1; const float* table3 = table2 + 1; LOOP1(inNumSamples, float pfrac = PhaseFrac1(phase); uint32 index = ((phase >> xlobits1) & lomask); float val0 = *(float*)((char*)table0 + index); float val1 = *(float*)((char*)table1 + index); float val2 = *(float*)((char*)table2 + index); float val3 = *(float*)((char*)table3 + index); float a = val0 + val1 * pfrac; float b = val2 + val3 * pfrac; ZXP(out) = a + level * (b - a); phase += phaseinc;); } else { int nsmps; int donesmps = 0; int remain = inNumSamples; while (remain) { float level = cur - sc_floor(cur); float cut; if (bufdiff > 0.) { cut = sc_min(nextbufpos, sc_floor(cur + 1.f)); } else { cut = sc_max(nextbufpos, sc_ceil(cur - 1.f)); } float sweepdiff = cut - cur; if (cut == nextbufpos) nsmps = remain; else { float sweep = (float)inNumSamples / bufdiff; nsmps = (int)sc_floor(sweep * sweepdiff + 0.5f) - donesmps; nsmps = sc_clip(nsmps, 1, remain); } float slope = sweepdiff / (float)nsmps; int32 bufnum = (int32)sc_floor(cur); const SndBuf* bufs = VOscGetBuf(bufnum, world, unit); if (!verify_wavetable(unit, "VOsc", tableSize, inNumSamples)) return; const float* table0 = bufs[0].data; const float* table2 = bufs[1].data; if (!table0 || !table2 || tableSize != bufs[0].samples || tableSize != bufs[1].samples) { ClearUnitOutputs(unit, inNumSamples); return; } const float* table1 = table0 + 1; const float* table3 = table2 + 1; LOOP(nsmps, float pfrac = PhaseFrac1(phase); uint32 index = ((phase >> xlobits1) & lomask); float val0 = *(float*)((char*)table0 + index); float val1 = *(float*)((char*)table1 + index); float val2 = *(float*)((char*)table2 + index); float val3 = *(float*)((char*)table3 + index); float a = val0 + val1 * pfrac; float b = val2 + val3 * pfrac; ZXP(out) = a + level * (b - a); phase += phaseinc; level += slope;); donesmps += nsmps; remain -= nsmps; cur = cut; } } unit->m_bufpos = nextbufpos; unit->m_phase = phase; } void VOsc_next_ika(VOsc* unit, int inNumSamples) { float* out = ZOUT(0); float nextbufpos = ZIN0(0); float freqin = ZIN0(1); float* phasein = ZIN(2); float prevbufpos = unit->m_bufpos; float bufdiff = nextbufpos - prevbufpos; int32 phase = unit->m_phase; int32 lomask = unit->m_lomask; int32 freq = (int32)(unit->m_cpstoinc * freqin); int32 phaseinc = freq; int tableSize = unit->mTableSize; float cur = prevbufpos; World* world = unit->mWorld; if (bufdiff == 0.f) { float level = cur - sc_floor(cur); int32 bufnum = (int)sc_floor(cur); const SndBuf* bufs = VOscGetBuf(bufnum, world, unit); if (!verify_wavetable(unit, "VOsc", tableSize, inNumSamples)) return; const float* table0 = bufs[0].data; const float* table2 = bufs[1].data; if (!table0 || !table2 || tableSize != bufs[0].samples || tableSize != bufs[1].samples) { ClearUnitOutputs(unit, inNumSamples); return; } const float* table1 = table0 + 1; const float* table3 = table2 + 1; LOOP1(inNumSamples, int32 pphase = phase + (int32)(ZXP(phasein) * unit->m_radtoinc); float pfrac = PhaseFrac1(pphase); uint32 index = ((pphase >> xlobits1) & lomask); float val0 = *(float*)((char*)table0 + index); float val1 = *(float*)((char*)table1 + index); float val2 = *(float*)((char*)table2 + index); float val3 = *(float*)((char*)table3 + index); float a = val0 + val1 * pfrac; float b = val2 + val3 * pfrac; ZXP(out) = a + level * (b - a); phase += phaseinc;); } else { int nsmps; int donesmps = 0; int remain = inNumSamples; while (remain) { float level = cur - sc_floor(cur); float cut; if (bufdiff > 0.) { cut = sc_min(nextbufpos, sc_floor(cur + 1.f)); } else { cut = sc_max(nextbufpos, sc_ceil(cur - 1.f)); } float sweepdiff = cut - cur; if (cut == nextbufpos) nsmps = remain; else { float sweep = (float)inNumSamples / bufdiff; nsmps = (int)sc_floor(sweep * sweepdiff + 0.5f) - donesmps; nsmps = sc_clip(nsmps, 1, remain); } float slope = sweepdiff / (float)nsmps; int32 bufnum = (int32)sc_floor(cur); const SndBuf* bufs = VOscGetBuf(bufnum, world, unit); if (!verify_wavetable(unit, "VOsc", tableSize, inNumSamples)) return; const float* table0 = bufs[0].data; const float* table2 = bufs[1].data; if (!table0 || !table2 || tableSize != bufs[0].samples || tableSize != bufs[1].samples) { ClearUnitOutputs(unit, inNumSamples); return; } const float* table1 = table0 + 1; const float* table3 = table2 + 1; LOOP(nsmps, int32 pphase = phase + (int32)(ZXP(phasein) * unit->m_radtoinc); float pfrac = PhaseFrac1(pphase); uint32 index = ((pphase >> xlobits1) & lomask); float val0 = *(float*)((char*)table0 + index); float val1 = *(float*)((char*)table1 + index); float val2 = *(float*)((char*)table2 + index); float val3 = *(float*)((char*)table3 + index); float a = val0 + val1 * pfrac; float b = val2 + val3 * pfrac; ZXP(out) = a + level * (b - a); phase += phaseinc; level += slope;); donesmps += nsmps; remain -= nsmps; cur = cut; } } unit->m_bufpos = nextbufpos; unit->m_phase = phase; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void VOsc3_Ctor(VOsc3* unit) { SETCALC(VOsc3_next_ik); float nextbufpos = ZIN0(0); unit->m_bufpos = nextbufpos; int32 bufnum = (int32)sc_floor(nextbufpos); World* world = unit->mWorld; const SndBuf* bufs = VOscGetBuf(bufnum, world, unit); int tableSize = bufs[0].samples; unit->mTableSize = tableSize; int tableSize2 = tableSize >> 1; unit->m_lomask = (tableSize2 - 1) << 3; unit->m_cpstoinc = tableSize2 * SAMPLEDUR * 65536.; unit->m_phase1 = 0; unit->m_phase2 = 0; unit->m_phase3 = 0; VOsc3_next_ik(unit, 1); unit->m_phase1 = 0; unit->m_phase2 = 0; unit->m_phase3 = 0; } void VOsc3_next_ik(VOsc3* unit, int inNumSamples) { float* out = ZOUT(0); float nextbufpos = ZIN0(0); float freq1in = ZIN0(1); float freq2in = ZIN0(2); float freq3in = ZIN0(3); float prevbufpos = unit->m_bufpos; float bufdiff = nextbufpos - prevbufpos; int32 phase1 = unit->m_phase1; int32 phase2 = unit->m_phase2; int32 phase3 = unit->m_phase3; int32 freq1 = (int32)(unit->m_cpstoinc * freq1in); int32 freq2 = (int32)(unit->m_cpstoinc * freq2in); int32 freq3 = (int32)(unit->m_cpstoinc * freq3in); int32 lomask = unit->m_lomask; int tableSize = unit->mTableSize; float cur = prevbufpos; World* world = unit->mWorld; if (bufdiff == 0.f) { float level = cur - (int)cur; int bufnum = (int)cur; const SndBuf* bufs = VOscGetBuf(bufnum, world, unit); if (!verify_wavetable(unit, "VOsc3", tableSize, inNumSamples)) return; const float* table0 = bufs[0].data; const float* table2 = bufs[1].data; if (!table0 || !table2 || tableSize != bufs[0].samples || tableSize != bufs[1].samples) { ClearUnitOutputs(unit, inNumSamples); return; } const float* table1 = table0 + 1; const float* table3 = table2 + 1; LOOP1(inNumSamples, float pfrac1 = PhaseFrac1(phase1); float pfrac2 = PhaseFrac1(phase2); float pfrac3 = PhaseFrac1(phase3); int index1 = ((phase1 >> xlobits1) & lomask); int index2 = ((phase2 >> xlobits1) & lomask); int index3 = ((phase3 >> xlobits1) & lomask); phase1 += freq1; phase2 += freq2; phase3 += freq3; float val10 = *(float*)((char*)table0 + index1); float val11 = *(float*)((char*)table1 + index1); float val12 = *(float*)((char*)table2 + index1); float val13 = *(float*)((char*)table3 + index1); float a = val10 + val11 * pfrac1; float b = val12 + val13 * pfrac1; float val20 = *(float*)((char*)table0 + index2); float val21 = *(float*)((char*)table1 + index2); float val22 = *(float*)((char*)table2 + index2); float val23 = *(float*)((char*)table3 + index2); a += val20 + val21 * pfrac2; b += val22 + val23 * pfrac2; float val30 = *(float*)((char*)table0 + index3); float val31 = *(float*)((char*)table1 + index3); float val32 = *(float*)((char*)table2 + index3); float val33 = *(float*)((char*)table3 + index3); a += val30 + val31 * pfrac3; b += val32 + val33 * pfrac3; ZXP(out) = a + level * (b - a);); } else { int nsmps; int donesmps = 0; int remain = inNumSamples; do { float level = cur - sc_trunc(cur); float cut; if (bufdiff >= 0.) cut = sc_min(nextbufpos, sc_trunc(cur + 1.f)); else cut = sc_max(nextbufpos, sc_ceil(cur - 1.f)); float sweepdiff = cut - cur; if (cut == nextbufpos) nsmps = remain; else { float sweep = (float)inNumSamples / bufdiff; nsmps = sc_floor(sweep * sweepdiff + 0.5f) - donesmps; nsmps = sc_clip(nsmps, 1, remain); } float slope = sweepdiff / (float)nsmps; int bufnum = (int)cur; const SndBuf* bufs = VOscGetBuf(bufnum, world, unit); if (!verify_wavetable(unit, "VOsc3", tableSize, inNumSamples)) return; const float* table0 = bufs[0].data; const float* table2 = bufs[1].data; if (!table0 || !table2 || tableSize != bufs[0].samples || tableSize != bufs[1].samples) { ClearUnitOutputs(unit, inNumSamples); return; } const float* table1 = table0 + 1; const float* table3 = table2 + 1; LOOP(nsmps, float pfrac1 = PhaseFrac1(phase1); float pfrac2 = PhaseFrac1(phase2); float pfrac3 = PhaseFrac1(phase3); int index1 = ((phase1 >> xlobits1) & lomask); int index2 = ((phase2 >> xlobits1) & lomask); int index3 = ((phase3 >> xlobits1) & lomask); phase1 += freq1; phase2 += freq2; phase3 += freq3; float val10 = *(float*)((char*)table0 + index1); float val11 = *(float*)((char*)table1 + index1); float val12 = *(float*)((char*)table2 + index1); float val13 = *(float*)((char*)table3 + index1); float a = val10 + val11 * pfrac1; float b = val12 + val13 * pfrac1; float val20 = *(float*)((char*)table0 + index2); float val21 = *(float*)((char*)table1 + index2); float val22 = *(float*)((char*)table2 + index2); float val23 = *(float*)((char*)table3 + index2); a += val20 + val21 * pfrac2; b += val22 + val23 * pfrac2; float val30 = *(float*)((char*)table0 + index3); float val31 = *(float*)((char*)table1 + index3); float val32 = *(float*)((char*)table2 + index3); float val33 = *(float*)((char*)table3 + index3); a += val30 + val31 * pfrac3; b += val32 + val33 * pfrac3; ZXP(out) = a + level * (b - a); level += slope;); donesmps += nsmps; remain -= nsmps; cur = cut; } while (remain); } unit->m_bufpos = nextbufpos; unit->m_phase1 = phase1; unit->m_phase2 = phase2; unit->m_phase3 = phase3; } ////////////////////////////////////////////////////////////////////////////////////////// void Formant_Ctor(Formant* unit) { SETCALC(Formant_next); unit->m_cpstoinc = ft->mSineSize * SAMPLEDUR * 65536.; unit->m_phase1 = 0; unit->m_phase2 = 0; unit->m_phase3 = 0; Formant_next(unit, 1); unit->m_phase1 = 0; unit->m_phase2 = 0; unit->m_phase3 = 0; } #define tqcyc13 0x18000000 void Formant_next(Formant* unit, int inNumSamples) { float* out = ZOUT(0); float freq1in = ZIN0(0); float freq2in = ZIN0(1); float freq3in = ZIN0(2); int32 phase1 = unit->m_phase1; int32 phase2 = unit->m_phase2; int32 phase3 = unit->m_phase3; float cpstoinc = unit->m_cpstoinc; int32 freq1 = (int32)(cpstoinc * freq1in); int32 freq2 = (int32)(cpstoinc * freq2in); int32 freq3 = (int32)(cpstoinc * freq3in); float* sine = ft->mSine; int32 formfreq = sc_max(freq1, freq3); LOOP1( inNumSamples, if (phase3 < onecyc13) { ZXP(out) = (*(float*)((char*)sine + (((phase3 + tqcyc13) >> xlobits) & xlomask13)) + 1.f) * *(float*)((char*)sine + ((phase2 >> xlobits) & xlomask13)); phase3 += formfreq; } else { ZXP(out) = 0.f; } phase1 += freq1; phase2 += freq2; if (phase1 > onecyc13) { phase1 -= onecyc13; phase2 = phase1 * freq2 / freq1; phase3 = phase1 * freq3 / freq1; }); unit->m_phase1 = phase1; unit->m_phase2 = phase2; unit->m_phase3 = phase3; } //////////////////////////////////////////////////////////////////////////////////////////////////////// inline float lookup13(float* table, int32 pphase) { float pfrac = PhaseFrac(pphase); float* tbl = (float*)((char*)table + ((pphase >> xlobits) & xlomask13)); return lininterp(pfrac, tbl[0], tbl[1]); } void Blip_Ctor(Blip* unit) { SETCALC(Blip_next); unit->m_freqin = ZIN0(0); unit->m_numharm = (int32)ZIN0(1); unit->m_cpstoinc = ft->mSineSize * SAMPLEDUR * 65536. * 0.5; int32 N = unit->m_numharm; int32 maxN = (int32)((SAMPLERATE * 0.5) / unit->m_freqin); if (N > maxN) N = maxN; if (N < 1) N = 1; unit->m_N = N; unit->m_scale = 0.5 / N; unit->m_phase = 0; Blip_next(unit, 1); unit->m_N = N; unit->m_scale = 0.5 / N; unit->m_phase = 0; } void Blip_next(Blip* unit, int inNumSamples) { float* out = ZOUT(0); float freqin = ZIN0(0); int numharm = (int32)ZIN0(1); int32 phase = unit->m_phase; float* numtbl = ft->mSine; float* dentbl = ft->mCosecant; int32 freq, N, prevN; float scale, prevscale; bool crossfade; if (numharm != unit->m_numharm || freqin != unit->m_freqin) { N = numharm; int32 maxN = (int32)((SAMPLERATE * 0.5) / freqin); if (N > maxN) { float maxfreqin; N = maxN; maxfreqin = sc_max(unit->m_freqin, freqin); freq = (int32)(unit->m_cpstoinc * maxfreqin); } else { if (N < 1) { N = 1; } freq = (int32)(unit->m_cpstoinc * freqin); } crossfade = N != unit->m_N; prevN = unit->m_N; prevscale = unit->m_scale; unit->m_N = N; unit->m_scale = scale = 0.5 / N; } else { N = unit->m_N; freq = (int32)(unit->m_cpstoinc * freqin); scale = unit->m_scale; crossfade = false; } int32 N2 = 2 * N + 1; if (crossfade) { int32 prevN2 = 2 * prevN + 1; float xfade_slope = unit->mRate->mSlopeFactor; float xfade = 0.f; LOOP1( inNumSamples, float* tbl = (float*)((char*)dentbl + ((phase >> xlobits) & xlomask13)); float t0 = tbl[0]; float t1 = tbl[1]; if (t0 == kBadValue || t1 == kBadValue) { tbl = (float*)((char*)numtbl + ((phase >> xlobits) & xlomask13)); t0 = tbl[0]; t1 = tbl[1]; float pfrac = PhaseFrac(phase); float denom = t0 + (t1 - t0) * pfrac; if (std::abs(denom) < 0.0005f) { ZXP(out) = 1.f; } else { int32 rphase = phase * prevN2; pfrac = PhaseFrac(rphase); tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); float numer = lininterp(pfrac, tbl[0], tbl[1]); float n1 = (numer / denom - 1.f) * prevscale; rphase = phase * N2; pfrac = PhaseFrac(rphase); tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); numer = lininterp(pfrac, tbl[0], tbl[1]); float n2 = (numer / denom - 1.f) * scale; ZXP(out) = lininterp(xfade, n1, n2); } } else { float pfrac = PhaseFrac(phase); float denom = t0 + (t1 - t0) * pfrac; int32 rphase = phase * prevN2; pfrac = PhaseFrac(rphase); float* tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); float numer = lininterp(pfrac, tbl[0], tbl[1]); float n1 = (numer * denom - 1.f) * prevscale; rphase = phase * N2; pfrac = PhaseFrac(rphase); tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); numer = lininterp(pfrac, tbl[0], tbl[1]); float n2 = (numer * denom - 1.f) * scale; ZXP(out) = lininterp(xfade, n1, n2); } phase += freq; xfade += xfade_slope;); } else { // hmm, if freq is above sr/4 then revert to sine table osc w/ no interpolation ? // why bother, it isn't a common choice for a fundamental. LOOP1( inNumSamples, float* tbl = (float*)((char*)dentbl + ((phase >> xlobits) & xlomask13)); float t0 = tbl[0]; float t1 = tbl[1]; if (t0 == kBadValue || t1 == kBadValue) { tbl = (float*)((char*)numtbl + ((phase >> xlobits) & xlomask13)); t0 = tbl[0]; t1 = tbl[1]; float pfrac = PhaseFrac(phase); float denom = t0 + (t1 - t0) * pfrac; if (std::abs(denom) < 0.0005f) { ZXP(out) = 1.f; } else { int32 rphase = phase * N2; pfrac = PhaseFrac(rphase); tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); float numer = lininterp(pfrac, tbl[0], tbl[1]); ZXP(out) = (numer / denom - 1.f) * scale; } } else { float pfrac = PhaseFrac(phase); float denom = t0 + (t1 - t0) * pfrac; int32 rphase = phase * N2; pfrac = PhaseFrac(rphase); tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); float numer = lininterp(pfrac, tbl[0], tbl[1]); ZXP(out) = (numer * denom - 1.f) * scale; } phase += freq;); } unit->m_phase = phase; unit->m_freqin = freqin; unit->m_numharm = numharm; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Saw_Ctor(Saw* unit) { SETCALC(Saw_next); unit->m_freqin = ZIN0(0); unit->m_cpstoinc = ft->mSineSize * SAMPLEDUR * 65536. * 0.5; unit->m_N = (int32)((SAMPLERATE * 0.5) / unit->m_freqin); unit->m_scale = 0.5 / unit->m_N; unit->m_phase = 0; unit->m_y1 = -0.46f; Saw_next(unit, 1); unit->m_scale = 0.5 / unit->m_N; unit->m_phase = 0; unit->m_y1 = -0.46f; } void Saw_next(Saw* unit, int inNumSamples) { float* out = ZOUT(0); float freqin = ZIN0(0); int32 phase = unit->m_phase; float y1 = unit->m_y1; float* numtbl = ft->mSine; float* dentbl = ft->mCosecant; int32 freq, N, prevN; float scale, prevscale; bool crossfade; if (freqin != unit->m_freqin) { N = (int32)((SAMPLERATE * 0.5) / freqin); if (N != unit->m_N) { float maxfreqin; maxfreqin = sc_max(unit->m_freqin, freqin); freq = (int32)(unit->m_cpstoinc * maxfreqin); crossfade = true; } else { freq = (int32)(unit->m_cpstoinc * freqin); crossfade = false; } prevN = unit->m_N; prevscale = unit->m_scale; unit->m_N = N; unit->m_scale = scale = 0.5 / N; } else { N = unit->m_N; freq = (int32)(unit->m_cpstoinc * freqin); scale = unit->m_scale; crossfade = false; } int32 N2 = 2 * N + 1; if (crossfade) { int32 prevN2 = 2 * prevN + 1; float xfade_slope = unit->mRate->mSlopeFactor; float xfade = 0.f; LOOP1( inNumSamples, float* tbl = (float*)((char*)dentbl + ((phase >> xlobits) & xlomask13)); float t0 = tbl[0]; float t1 = tbl[1]; if (t0 == kBadValue || t1 == kBadValue) { tbl = (float*)((char*)numtbl + ((phase >> xlobits) & xlomask13)); t0 = tbl[0]; t1 = tbl[1]; float pfrac = PhaseFrac(phase); float denom = t0 + (t1 - t0) * pfrac; if (std::abs(denom) < 0.0005f) { ZXP(out) = y1 = 1.f + 0.999f * y1; } else { int32 rphase = phase * prevN2; pfrac = PhaseFrac(rphase); tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); float numer = lininterp(pfrac, tbl[0], tbl[1]); float n1 = (numer / denom - 1.f) * prevscale; rphase = phase * N2; pfrac = PhaseFrac(rphase); tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); numer = lininterp(pfrac, tbl[0], tbl[1]); float n2 = (numer / denom - 1.f) * scale; ZXP(out) = y1 = n1 + xfade * (n2 - n1) + 0.999f * y1; } } else { float pfrac = PhaseFrac(phase); float denom = t0 + (t1 - t0) * pfrac; int32 rphase = phase * prevN2; pfrac = PhaseFrac(rphase); tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); float numer = lininterp(pfrac, tbl[0], tbl[1]); float n1 = (numer * denom - 1.f) * prevscale; rphase = phase * N2; pfrac = PhaseFrac(rphase); tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); numer = lininterp(pfrac, tbl[0], tbl[1]); float n2 = (numer * denom - 1.f) * scale; ZXP(out) = y1 = n1 + xfade * (n2 - n1) + 0.999f * y1; } phase += freq; xfade += xfade_slope;); } else { // hmm, if freq is above sr/4 then revert to sine table osc ? // why bother, it isn't a common choice for a fundamental. LOOP1( inNumSamples, float* tbl = (float*)((char*)dentbl + ((phase >> xlobits) & xlomask13)); float t0 = tbl[0]; float t1 = tbl[1]; if (t0 == kBadValue || t1 == kBadValue) { tbl = (float*)((char*)numtbl + ((phase >> xlobits) & xlomask13)); t0 = tbl[0]; t1 = tbl[1]; float pfrac = PhaseFrac(phase); float denom = t0 + (t1 - t0) * pfrac; if (std::abs(denom) < 0.0005f) { ZXP(out) = y1 = 1.f + 0.999f * y1; } else { int32 rphase = phase * N2; pfrac = PhaseFrac(rphase); tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); float numer = lininterp(pfrac, tbl[0], tbl[1]); ZXP(out) = y1 = (numer / denom - 1.f) * scale + 0.999f * y1; } } else { float pfrac = PhaseFrac(phase); float denom = t0 + (t1 - t0) * pfrac; int32 rphase = phase * N2; pfrac = PhaseFrac(rphase); float* tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); float numer = lininterp(pfrac, tbl[0], tbl[1]); ZXP(out) = y1 = (numer * denom - 1.f) * scale + 0.999f * y1; } phase += freq;); } unit->m_y1 = y1; unit->m_phase = phase; unit->m_freqin = freqin; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Pulse_Ctor(Pulse* unit) { SETCALC(Pulse_next); unit->m_freqin = ZIN0(0); unit->m_cpstoinc = ft->mSineSize * SAMPLEDUR * 65536. * 0.5; unit->m_N = (int32)((SAMPLERATE * 0.5) / unit->m_freqin); unit->m_scale = 0.5 / unit->m_N; unit->m_phase = 0; unit->m_phaseoff = 0; unit->m_y1 = 0.f; ZOUT0(0) = 0.f; } void Pulse_next(Pulse* unit, int inNumSamples) { float* out = ZOUT(0); float freqin = ZIN0(0); float duty = ZIN0(1); int32 phase = unit->m_phase; float y1 = unit->m_y1; float* numtbl = ft->mSine; float* dentbl = ft->mCosecant; int32 freq, N, prevN; float scale, prevscale; bool crossfade; if (freqin != unit->m_freqin) { N = (int32)((SAMPLERATE * 0.5) / freqin); if (N != unit->m_N) { float maxfreqin; maxfreqin = sc_max(unit->m_freqin, freqin); freq = (int32)(unit->m_cpstoinc * maxfreqin); crossfade = true; } else { freq = (int32)(unit->m_cpstoinc * freqin); crossfade = false; } prevN = unit->m_N; prevscale = unit->m_scale; unit->m_N = N; unit->m_scale = scale = 0.5 / N; } else { N = unit->m_N; freq = (int32)(unit->m_cpstoinc * freqin); scale = unit->m_scale; crossfade = false; } int32 N2 = 2 * N + 1; int32 phaseoff = unit->m_phaseoff; int32 next_phaseoff = (int32)(duty * (1L << 28)); int32 phaseoff_slope = (int32)((next_phaseoff - phaseoff) * unit->mRate->mSlopeFactor); unit->m_phaseoff = next_phaseoff; float rscale = 1.f / scale + 1.f; float pul1, pul2; if (crossfade) { int32 prevN2 = 2 * prevN + 1; float xfade_slope = unit->mRate->mSlopeFactor; float xfade = 0.f; LOOP1( inNumSamples, float* tbl = (float*)((char*)dentbl + ((phase >> xlobits) & xlomask13)); float t0 = tbl[0]; float t1 = tbl[1]; if (t0 == kBadValue || t1 == kBadValue) { tbl = (float*)((char*)numtbl + ((phase >> xlobits) & xlomask13)); t0 = tbl[0]; t1 = tbl[1]; float pfrac = PhaseFrac(phase); float denom = t0 + (t1 - t0) * pfrac; if (std::abs(denom) < 0.0005f) { pul1 = 1.f; } else { int32 rphase = phase * prevN2; pfrac = PhaseFrac(rphase); tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); float numer = lininterp(pfrac, tbl[0], tbl[1]); float n1 = (numer / denom - 1.f) * prevscale; rphase = phase * N2; pfrac = PhaseFrac(rphase); tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); numer = lininterp(pfrac, tbl[0], tbl[1]); float n2 = (numer / denom - 1.f) * scale; pul1 = lininterp(xfade, n1, n2); } } else { float pfrac = PhaseFrac(phase); float denom = lininterp(pfrac, t0, t1); int32 rphase = phase * prevN2; pfrac = PhaseFrac(rphase); tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); float numer = lininterp(pfrac, tbl[0], tbl[1]); float n1 = (numer * denom - 1.f) * prevscale; rphase = phase * N2; pfrac = PhaseFrac(rphase); tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); numer = lininterp(pfrac, tbl[0], tbl[1]); float n2 = (numer * denom - 1.f) * scale; pul1 = lininterp(xfade, n1, n2); } int32 phase2 = phase + phaseoff; tbl = (float*)((char*)dentbl + ((phase2 >> xlobits) & xlomask13)); t0 = tbl[0]; t1 = tbl[1]; if (t0 == kBadValue || t1 == kBadValue) { tbl = (float*)((char*)numtbl + ((phase2 >> xlobits) & xlomask13)); t0 = tbl[0]; t1 = tbl[1]; float pfrac = PhaseFrac(phase2); float denom = t0 + (t1 - t0) * pfrac; if (std::abs(denom) < 0.0005f) { pul2 = 1.f; } else { int32 rphase = phase2 * prevN2; pfrac = PhaseFrac(rphase); tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); float numer = lininterp(pfrac, tbl[0], tbl[1]); float n1 = (numer / denom - 1.f) * prevscale; rphase = phase2 * N2; pfrac = PhaseFrac(rphase); tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); numer = lininterp(pfrac, tbl[0], tbl[1]); float n2 = (numer / denom - 1.f) * scale; pul2 = lininterp(xfade, n1, n2); } } else { float pfrac = PhaseFrac(phase2); float denom = t0 + (t1 - t0) * pfrac; int32 rphase = phase2 * prevN2; pfrac = PhaseFrac(rphase); tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); float numer = lininterp(pfrac, tbl[0], tbl[1]); float n1 = (numer * denom - 1.f) * prevscale; rphase = phase2 * N2; pfrac = PhaseFrac(rphase); tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); numer = lininterp(pfrac, tbl[0], tbl[1]); float n2 = (numer * denom - 1.f) * scale; pul2 = lininterp(xfade, n1, n2); } ZXP(out) = y1 = pul1 - pul2 + 0.999f * y1; phase += freq; phaseoff += phaseoff_slope; xfade += xfade_slope;); } else { LOOP1( inNumSamples, float* tbl = (float*)((char*)dentbl + ((phase >> xlobits) & xlomask13)); float t0 = tbl[0]; float t1 = tbl[1]; if (t0 == kBadValue || t1 == kBadValue) { tbl = (float*)((char*)numtbl + ((phase >> xlobits) & xlomask13)); t0 = tbl[0]; t1 = tbl[1]; float pfrac = PhaseFrac(phase); float denom = t0 + (t1 - t0) * pfrac; if (std::abs(denom) < 0.0005f) { pul1 = rscale; } else { int32 rphase = phase * N2; pfrac = PhaseFrac(rphase); tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); float numer = lininterp(pfrac, tbl[0], tbl[1]); pul1 = numer / denom; } } else { float pfrac = PhaseFrac(phase); float denom = t0 + (t1 - t0) * pfrac; int32 rphase = phase * N2; pfrac = PhaseFrac(rphase); float* tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); float numer = lininterp(pfrac, tbl[0], tbl[1]); pul1 = (numer * denom); } int32 phase2 = phase + phaseoff; tbl = (float*)((char*)dentbl + ((phase2 >> xlobits) & xlomask13)); t0 = tbl[0]; t1 = tbl[1]; if (t0 == kBadValue || t1 == kBadValue) { tbl = (float*)((char*)numtbl + ((phase2 >> xlobits) & xlomask13)); t0 = tbl[0]; t1 = tbl[1]; float pfrac = PhaseFrac(phase2); float denom = t0 + (t1 - t0) * pfrac; if (std::abs(denom) < 0.0005f) { pul2 = rscale; } else { int32 rphase = phase2 * N2; pfrac = PhaseFrac(rphase); tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); float numer = lininterp(pfrac, tbl[0], tbl[1]); pul2 = numer / denom; } } else { float pfrac = PhaseFrac(phase2); float denom = t0 + (t1 - t0) * pfrac; int32 rphase = phase2 * N2; pfrac = PhaseFrac(rphase); float* tbl = (float*)((char*)numtbl + ((rphase >> xlobits) & xlomask13)); float numer = lininterp(pfrac, tbl[0], tbl[1]); pul2 = (numer * denom); } ZXP(out) = y1 = (pul1 - pul2) * scale + 0.999f * y1; phase += freq; phaseoff += phaseoff_slope;); } unit->m_y1 = y1; unit->m_phase = phase; unit->m_freqin = freqin; } //////////////////////////////////////////////////////////////////////////////////////////////////////// static float Klang_SetCoefs(Klang* unit) { float freqscale = ZIN0(0) * unit->mRate->mRadiansPerSample; float freqoffset = ZIN0(1) * unit->mRate->mRadiansPerSample; float outf = 0.; float* coefs = unit->m_coefs - 1; for (int i = 0, j = 2; i < unit->m_numpartials; ++i, j += 3) { float w = ZIN0(j) * freqscale + freqoffset; float level = ZIN0(j + 1); float phase = ZIN0(j + 2); if (phase != 0.f) { outf += level * sin(phase); *++coefs = level * sin(phase - w); // y1 *++coefs = level * sin(phase - w - w); // y2 } else { *++coefs = level * -sin(w); // y1 *++coefs = level * -sin(w + w); // y2 } *++coefs = 2. * cos(w); // b1 } return outf; } void Klang_Ctor(Klang* unit) { SETCALC(Klang_next); unit->m_numpartials = (unit->mNumInputs - 2) / 3; int numcoefs = unit->m_numpartials * 3; unit->m_coefs = (float*)RTAlloc(unit->mWorld, numcoefs * sizeof(float)); ClearUnitIfMemFailed(unit->m_coefs); ZOUT0(0) = Klang_SetCoefs(unit); } void Klang_Dtor(Klang* unit) { RTFree(unit->mWorld, unit->m_coefs); } void Klang_next(Klang* unit, int inNumSamples) { float* out0 = ZOUT(0); float* out; float y0_0, y1_0, y2_0, b1_0; float y0_1, y1_1, y2_1, b1_1; float y0_2, y1_2, y2_2, b1_2; float y0_3, y1_3, y2_3, b1_3; float outf; float* coefs = unit->m_coefs - 1; int32 numpartials = unit->m_numpartials; switch (numpartials & 3) { case 3: y1_0 = *++coefs; y2_0 = *++coefs; b1_0 = *++coefs; y1_1 = *++coefs; y2_1 = *++coefs; b1_1 = *++coefs; y1_2 = *++coefs; y2_2 = *++coefs; b1_2 = *++coefs; out = out0; LOOP(unit->mRate->mFilterLoops, outf = y0_0 = b1_0 * y1_0 - y2_0; outf += y0_1 = b1_1 * y1_1 - y2_1; outf += y0_2 = b1_2 * y1_2 - y2_2; ZXP(out) = outf; outf = y2_0 = b1_0 * y0_0 - y1_0; outf += y2_1 = b1_1 * y0_1 - y1_1; outf += y2_2 = b1_2 * y0_2 - y1_2; ZXP(out) = outf; outf = y1_0 = b1_0 * y2_0 - y0_0; outf += y1_1 = b1_1 * y2_1 - y0_1; outf += y1_2 = b1_2 * y2_2 - y0_2; ZXP(out) = outf;); LOOP(unit->mRate->mFilterRemain, outf = y0_0 = b1_0 * y1_0 - y2_0; outf += y0_1 = b1_1 * y1_1 - y2_1; outf += y0_2 = b1_2 * y1_2 - y2_2; y2_0 = y1_0; y1_0 = y0_0; y2_1 = y1_1; y1_1 = y0_1; y2_2 = y1_2; y1_2 = y0_2; ZXP(out) = outf;); coefs -= 9; *++coefs = y1_0; *++coefs = y2_0; ++coefs; *++coefs = y1_1; *++coefs = y2_1; ++coefs; *++coefs = y1_2; *++coefs = y2_2; ++coefs; break; case 2: y1_0 = *++coefs; y2_0 = *++coefs; b1_0 = *++coefs; y1_1 = *++coefs; y2_1 = *++coefs; b1_1 = *++coefs; out = out0; LOOP(unit->mRate->mFilterLoops, outf = y0_0 = b1_0 * y1_0 - y2_0; outf += y0_1 = b1_1 * y1_1 - y2_1; ZXP(out) = outf; outf = y2_0 = b1_0 * y0_0 - y1_0; outf += y2_1 = b1_1 * y0_1 - y1_1; ZXP(out) = outf; outf = y1_0 = b1_0 * y2_0 - y0_0; outf += y1_1 = b1_1 * y2_1 - y0_1; ZXP(out) = outf;); LOOP(unit->mRate->mFilterRemain, outf = y0_0 = b1_0 * y1_0 - y2_0; outf += y0_1 = b1_1 * y1_1 - y2_1; y2_0 = y1_0; y1_0 = y0_0; y2_1 = y1_1; y1_1 = y0_1; ZXP(out) = outf;); coefs -= 6; *++coefs = y1_0; *++coefs = y2_0; ++coefs; *++coefs = y1_1; *++coefs = y2_1; ++coefs; break; case 1: y1_0 = *++coefs; y2_0 = *++coefs; b1_0 = *++coefs; out = out0; LOOP(unit->mRate->mFilterLoops, ZXP(out) = y0_0 = b1_0 * y1_0 - y2_0; ZXP(out) = y2_0 = b1_0 * y0_0 - y1_0; ZXP(out) = y1_0 = b1_0 * y2_0 - y0_0;); LOOP(unit->mRate->mFilterRemain, ZXP(out) = y0_0 = b1_0 * y1_0 - y2_0; y2_0 = y1_0; y1_0 = y0_0;); coefs -= 3; *++coefs = y1_0; *++coefs = y2_0; ++coefs; break; case 0: out = out0; ZClear(inNumSamples, out); break; } int32 imax = numpartials >> 2; for (int i = 0; i < imax; ++i) { y1_0 = *++coefs; y2_0 = *++coefs; b1_0 = *++coefs; y1_1 = *++coefs; y2_1 = *++coefs; b1_1 = *++coefs; y1_2 = *++coefs; y2_2 = *++coefs; b1_2 = *++coefs; y1_3 = *++coefs; y2_3 = *++coefs; b1_3 = *++coefs; out = out0; LOOP(unit->mRate->mFilterLoops, outf = y0_0 = b1_0 * y1_0 - y2_0; outf += y0_1 = b1_1 * y1_1 - y2_1; outf += y0_2 = b1_2 * y1_2 - y2_2; outf += y0_3 = b1_3 * y1_3 - y2_3; ZXP(out) += outf; outf = y2_0 = b1_0 * y0_0 - y1_0; outf += y2_1 = b1_1 * y0_1 - y1_1; outf += y2_2 = b1_2 * y0_2 - y1_2; outf += y2_3 = b1_3 * y0_3 - y1_3; ZXP(out) += outf; outf = y1_0 = b1_0 * y2_0 - y0_0; outf += y1_1 = b1_1 * y2_1 - y0_1; outf += y1_2 = b1_2 * y2_2 - y0_2; outf += y1_3 = b1_3 * y2_3 - y0_3; ZXP(out) += outf;); LOOP(unit->mRate->mFilterRemain, outf = y0_0 = b1_0 * y1_0 - y2_0; outf += y0_1 = b1_1 * y1_1 - y2_1; outf += y0_2 = b1_2 * y1_2 - y2_2; outf += y0_3 = b1_3 * y1_3 - y2_3; y2_0 = y1_0; y1_0 = y0_0; y2_1 = y1_1; y1_1 = y0_1; y2_2 = y1_2; y1_2 = y0_2; y2_3 = y1_3; y1_3 = y0_3; ZXP(out) += outf;); coefs -= 12; *++coefs = y1_0; *++coefs = y2_0; ++coefs; *++coefs = y1_1; *++coefs = y2_1; ++coefs; *++coefs = y1_2; *++coefs = y2_2; ++coefs; *++coefs = y1_3; *++coefs = y2_3; ++coefs; } } //////////////////////////////////////////////////////////////////////////////////////////////////////// static void Klank_SetCoefs(Klank* unit) { float freqscale = ZIN0(1) * unit->mRate->mRadiansPerSample; float freqoffset = ZIN0(2) * unit->mRate->mRadiansPerSample; float decayscale = ZIN0(3); float* coefs = unit->m_coefs; int numpartials = unit->m_numpartials; float sampleRate = SAMPLERATE; for (int i = 0, j = 4; i < numpartials; ++i, j += 3) { float w = ZIN0(j) * freqscale + freqoffset; float level = ZIN0(j + 1); float time = ZIN0(j + 2) * decayscale; float R = time == 0.f ? 0.f : exp(log001 / (time * sampleRate)); float twoR = 2.f * R; float R2 = R * R; float cost = (twoR * cos(w)) / (1.f + R2); int k = 20 * (i >> 2) + (i & 3); coefs[k + 0] = 0.f; // y1 coefs[k + 4] = 0.f; // y2 coefs[k + 8] = twoR * cost; // b1 coefs[k + 12] = -R2; // b2 coefs[k + 16] = level * 0.25; // a0 } } void Klank_Ctor(Klank* unit) { SETCALC(Klank_next); unit->m_x1 = unit->m_x2 = 0.f; int numpartials = (unit->mNumInputs - 4) / 3; unit->m_numpartials = numpartials; int numcoefs = ((numpartials + 3) & ~3) * 5; unit->m_coefs = (float*)RTAlloc(unit->mWorld, (numcoefs + unit->mWorld->mBufLength) * sizeof(float)); ClearUnitIfMemFailed(unit->m_coefs); unit->m_buf = unit->m_coefs + numcoefs; Klank_SetCoefs(unit); // generate initial sample int filtLoops = unit->mRate->mFilterLoops; int filtRemain = unit->mRate->mFilterRemain; unit->mRate->mFilterLoops = 0; // supress filter loop unit->mRate->mFilterRemain = 1; // just go through 1 iteration Klank_next(unit, 1); unit->mRate->mFilterLoops = filtLoops; unit->mRate->mFilterRemain = filtRemain; // reset state for first sample unit->m_x1 = unit->m_x2 = 0.f; Klank_SetCoefs(unit); } void Klank_Dtor(Klank* unit) { RTFree(unit->mWorld, unit->m_coefs); } void Klank_next(Klank* unit, int inNumSamples) { float* out0 = ZOUT(0); float* in0 = ZIN(0); float *in, *out; float inf; float y0_0, y1_0, y2_0, a0_0, b1_0, b2_0; float y0_1, y1_1, y2_1, a0_1, b1_1, b2_1; float y0_2, y1_2, y2_2, a0_2, b1_2, b2_2; float y0_3, y1_3, y2_3, a0_3, b1_3, b2_3; int32 numpartials = unit->m_numpartials; int32 imax = numpartials >> 2; float* coefs = unit->m_coefs + imax * 20; switch (numpartials & 3) { case 3: y1_0 = coefs[0]; y2_0 = coefs[4]; b1_0 = coefs[8]; b2_0 = coefs[12]; a0_0 = coefs[16]; y1_1 = coefs[1]; y2_1 = coefs[5]; b1_1 = coefs[9]; b2_1 = coefs[13]; a0_1 = coefs[17]; y1_2 = coefs[2]; y2_2 = coefs[6]; b1_2 = coefs[10]; b2_2 = coefs[14]; a0_2 = coefs[18]; in = in0; out = unit->m_buf - 1; LooP(unit->mRate->mFilterLoops) { inf = *++in; y0_0 = inf + b1_0 * y1_0 + b2_0 * y2_0; y0_1 = inf + b1_1 * y1_1 + b2_1 * y2_1; y0_2 = inf + b1_2 * y1_2 + b2_2 * y2_2; *++out = a0_0 * y0_0 + a0_1 * y0_1 + a0_2 * y0_2; inf = *++in; y2_0 = inf + b1_0 * y0_0 + b2_0 * y1_0; y2_1 = inf + b1_1 * y0_1 + b2_1 * y1_1; y2_2 = inf + b1_2 * y0_2 + b2_2 * y1_2; *++out = a0_0 * y2_0 + a0_1 * y2_1 + a0_2 * y2_2; inf = *++in; y1_0 = inf + b1_0 * y2_0 + b2_0 * y0_0; y1_1 = inf + b1_1 * y2_1 + b2_1 * y0_1; y1_2 = inf + b1_2 * y2_2 + b2_2 * y0_2; *++out = a0_0 * y1_0 + a0_1 * y1_1 + a0_2 * y1_2; } LooP(unit->mRate->mFilterRemain) { inf = *++in; y0_0 = inf + b1_0 * y1_0 + b2_0 * y2_0; y0_1 = inf + b1_1 * y1_1 + b2_1 * y2_1; y0_2 = inf + b1_2 * y1_2 + b2_2 * y2_2; *++out = a0_0 * y0_0 + a0_1 * y0_1 + a0_2 * y0_2; y2_0 = y1_0; y1_0 = y0_0; y2_1 = y1_1; y1_1 = y0_1; y2_2 = y1_2; y1_2 = y0_2; } coefs[0] = zapgremlins(y1_0); coefs[4] = zapgremlins(y2_0); coefs[1] = zapgremlins(y1_1); coefs[5] = zapgremlins(y2_1); coefs[2] = zapgremlins(y1_2); coefs[6] = zapgremlins(y2_2); break; case 2: y1_0 = coefs[0]; y2_0 = coefs[4]; b1_0 = coefs[8]; b2_0 = coefs[12]; a0_0 = coefs[16]; y1_1 = coefs[1]; y2_1 = coefs[5]; b1_1 = coefs[9]; b2_1 = coefs[13]; a0_1 = coefs[17]; in = in0; out = unit->m_buf - 1; LooP(unit->mRate->mFilterLoops) { inf = *++in; y0_0 = inf + b1_0 * y1_0 + b2_0 * y2_0; y0_1 = inf + b1_1 * y1_1 + b2_1 * y2_1; *++out = a0_0 * y0_0 + a0_1 * y0_1; inf = *++in; y2_0 = inf + b1_0 * y0_0 + b2_0 * y1_0; y2_1 = inf + b1_1 * y0_1 + b2_1 * y1_1; *++out = a0_0 * y2_0 + a0_1 * y2_1; inf = *++in; y1_0 = inf + b1_0 * y2_0 + b2_0 * y0_0; y1_1 = inf + b1_1 * y2_1 + b2_1 * y0_1; *++out = a0_0 * y1_0 + a0_1 * y1_1; } LooP(unit->mRate->mFilterRemain) { inf = *++in; y0_0 = inf + b1_0 * y1_0 + b2_0 * y2_0; y0_1 = inf + b1_1 * y1_1 + b2_1 * y2_1; *++out = a0_0 * y0_0 + a0_1 * y0_1; y2_0 = y1_0; y1_0 = y0_0; y2_1 = y1_1; y1_1 = y0_1; } coefs[0] = zapgremlins(y1_0); coefs[4] = zapgremlins(y2_0); coefs[1] = zapgremlins(y1_1); coefs[5] = zapgremlins(y2_1); break; case 1: y1_0 = coefs[0]; y2_0 = coefs[4]; b1_0 = coefs[8]; b2_0 = coefs[12]; a0_0 = coefs[16]; in = in0; out = unit->m_buf - 1; LooP(unit->mRate->mFilterLoops) { inf = *++in; y0_0 = inf + b1_0 * y1_0 + b2_0 * y2_0; *++out = a0_0 * y0_0; inf = *++in; y2_0 = inf + b1_0 * y0_0 + b2_0 * y1_0; *++out = a0_0 * y2_0; inf = *++in; y1_0 = inf + b1_0 * y2_0 + b2_0 * y0_0; *++out = a0_0 * y1_0; } LooP(unit->mRate->mFilterRemain) { inf = *++in; y0_0 = inf + b1_0 * y1_0 + b2_0 * y2_0; *++out = a0_0 * y0_0; y2_0 = y1_0; y1_0 = y0_0; } /* coefs[0] = y1_0; coefs[4] = y2_0; */ coefs[0] = zapgremlins(y1_0); coefs[4] = zapgremlins(y2_0); break; case 0: out = unit->m_buf - 1; LooP(inNumSamples) { *++out = 0.f; } break; } coefs = unit->m_coefs; for (int i = 0; i < imax; ++i) { y1_0 = coefs[0]; y2_0 = coefs[4]; b1_0 = coefs[8]; b2_0 = coefs[12]; a0_0 = coefs[16]; y1_1 = coefs[1]; y2_1 = coefs[5]; b1_1 = coefs[9]; b2_1 = coefs[13]; a0_1 = coefs[17]; y1_2 = coefs[2]; y2_2 = coefs[6]; b1_2 = coefs[10]; b2_2 = coefs[14]; a0_2 = coefs[18]; y1_3 = coefs[3]; y2_3 = coefs[7]; b1_3 = coefs[11]; b2_3 = coefs[15]; a0_3 = coefs[19]; in = in0; out = unit->m_buf - 1; LooP(unit->mRate->mFilterLoops) { inf = *++in; y0_0 = inf + b1_0 * y1_0 + b2_0 * y2_0; y0_1 = inf + b1_1 * y1_1 + b2_1 * y2_1; y0_2 = inf + b1_2 * y1_2 + b2_2 * y2_2; y0_3 = inf + b1_3 * y1_3 + b2_3 * y2_3; *++out += a0_0 * y0_0 + a0_1 * y0_1 + a0_2 * y0_2 + a0_3 * y0_3; inf = *++in; y2_0 = inf + b1_0 * y0_0 + b2_0 * y1_0; y2_1 = inf + b1_1 * y0_1 + b2_1 * y1_1; y2_2 = inf + b1_2 * y0_2 + b2_2 * y1_2; y2_3 = inf + b1_3 * y0_3 + b2_3 * y1_3; *++out += a0_0 * y2_0 + a0_1 * y2_1 + a0_2 * y2_2 + a0_3 * y2_3; inf = *++in; y1_0 = inf + b1_0 * y2_0 + b2_0 * y0_0; y1_1 = inf + b1_1 * y2_1 + b2_1 * y0_1; y1_2 = inf + b1_2 * y2_2 + b2_2 * y0_2; y1_3 = inf + b1_3 * y2_3 + b2_3 * y0_3; *++out += a0_0 * y1_0 + a0_1 * y1_1 + a0_2 * y1_2 + a0_3 * y1_3; } LooP(unit->mRate->mFilterRemain) { inf = *++in; y0_0 = inf + b1_0 * y1_0 + b2_0 * y2_0; y0_1 = inf + b1_1 * y1_1 + b2_1 * y2_1; y0_2 = inf + b1_2 * y1_2 + b2_2 * y2_2; y0_3 = inf + b1_3 * y1_3 + b2_3 * y2_3; *++out += a0_0 * y0_0 + a0_1 * y0_1 + a0_2 * y0_2 + a0_3 * y0_3; y2_0 = y1_0; y1_0 = y0_0; y2_1 = y1_1; y1_1 = y0_1; y2_2 = y1_2; y1_2 = y0_2; y2_3 = y1_3; y1_3 = y0_3; } coefs[0] = zapgremlins(y1_0); coefs[4] = zapgremlins(y2_0); coefs[1] = zapgremlins(y1_1); coefs[5] = zapgremlins(y2_1); coefs[2] = zapgremlins(y1_2); coefs[6] = zapgremlins(y2_2); coefs[3] = zapgremlins(y1_3); coefs[7] = zapgremlins(y2_3); coefs += 20; } float x0; float x1 = unit->m_x1; float x2 = unit->m_x2; in = unit->m_buf - 1; out = out0; LooP(unit->mRate->mFilterLoops) { x0 = *++in; *++out = x0 - x2; x2 = *++in; *++out = x2 - x1; x1 = *++in; *++out = x1 - x0; } LooP(unit->mRate->mFilterRemain) { x0 = *++in; *++out = x0 - x2; x2 = x1; x1 = x0; } unit->m_x1 = x1; unit->m_x2 = x2; } //////////////////////////////////////////////////////////////////////////////////////////////////////// static void normalize_samples(int size, float* data, float peak) { float maxamp = 0.f; for (int i = 0; i < size; ++i) { float absamp = std::abs(data[i]); if (absamp > maxamp) maxamp = absamp; } if (maxamp != 0.f && maxamp != peak) { float ampfac = peak / maxamp; for (int i = 0; i < size; ++i) { data[i] *= ampfac; } } } static void normalize_wsamples(int size, float* data, float peak) { float maxamp = 0.f; for (int i = 0; i < size; i += 2) { float absamp = std::abs(data[i] + data[i + 1]); if (absamp > maxamp) maxamp = absamp; } if (maxamp != 0.f && maxamp != peak) { float ampfac = peak / maxamp; for (int i = 0; i < size; ++i) { data[i] *= ampfac; } } } static void add_partial(int size, float* data, double partial, double amp, double phase) { if (amp == 0.0) return; double w = (partial * 2.0 * 3.1415926535897932384626433832795) / (double)size; for (int i = 0; i < size; ++i) { data[i] += amp * sin(phase); phase += w; } } static void add_wpartial(int size, float* data, double partial, double amp, double phase) { if (amp == 0.0) return; int size2 = size >> 1; double w = (partial * 2.0 * 3.1415926535897932384626433832795) / (double)size2; double cur = amp * sin(phase); phase += w; for (int i = 0; i < size; i += 2) { double next = amp * sin(phase); data[i] += 2 * cur - next; data[i + 1] += next - cur; cur = next; phase += w; } } static void add_chebyshev(int size, float* data, double partial, double amp) { if (amp == 0.0) return; double w = 2.0 / (double)size; double phase = -1.0; double offset = -amp * cos(partial * pi2); for (int i = 0; i < size; ++i) { data[i] += amp * cos(partial * acos(phase)) + offset; phase += w; } } static void add_wchebyshev(int size, float* data, double partial, double amp) { if (amp == 0.0) return; int size2 = size >> 1; double w = 2.0 / (double)size2; double phase = -1.0; double offset = -amp * cos(partial * pi2); double cur = amp * cos(partial * acos(phase)) + offset; phase += w; for (int i = 0; i < size; i += 2) { double next = amp * cos(partial * acos(phase)) + offset; data[i] += 2 * cur - next; data[i + 1] += next - cur; cur = next; phase += w; } } static void cantorFill(int size, float* data) // long offset, double amp) { // if (amp == 0.0) return; for (int i = 0; i < (size); ++i) { int j = i; float flag = 1.f; while ((j > 0) && (flag == 1.f)) { if (j % 3 == 1) { flag = 0.f; } j = j / 3; } if (flag) { data[i] += 1.f; } } } enum { flag_Normalize = 1, flag_Wavetable = 2, flag_Clear = 4 }; void ChebyFill(World* world, struct SndBuf* buf, struct sc_msg_iter* msg) { if (buf->channels != 1) return; int flags = msg->geti(); int size = buf->samples; int byteSize = size * sizeof(float); float* data = (float*)malloc(byteSize); if (flags & flag_Clear) Fill(size, data, 0.); else memcpy(data, buf->data, byteSize); for (int partial = 1; msg->remain(); partial++) { double amp = msg->getf(); if (flags & flag_Wavetable) add_wchebyshev(size, data, partial, amp); else add_chebyshev(size, data, partial, amp); } if (flags & flag_Normalize) { if (flags & flag_Wavetable) normalize_wsamples(size, data, 1.); else normalize_samples(size, data, 1.); } memcpy(buf->data, data, byteSize); free(data); } void SineFill1(World* world, struct SndBuf* buf, struct sc_msg_iter* msg) { if (buf->channels != 1) return; int flags = msg->geti(); int size = buf->samples; int byteSize = size * sizeof(float); float* data = (float*)malloc(byteSize); if (flags & flag_Clear) Fill(size, data, 0.); else memcpy(data, buf->data, byteSize); for (int partial = 1; msg->remain(); partial++) { double amp = msg->getf(); if (flags & flag_Wavetable) add_wpartial(size, data, partial, amp, 0.); else add_partial(size, data, partial, amp, 0.); } if (flags & flag_Normalize) { if (flags & flag_Wavetable) normalize_wsamples(size, data, 1.); else normalize_samples(size, data, 1.); } memcpy(buf->data, data, byteSize); free(data); } void SineFill2(World* world, struct SndBuf* buf, struct sc_msg_iter* msg) { if (buf->channels != 1) return; int flags = msg->geti(); int size = buf->samples; int byteSize = size * sizeof(float); float* data = (float*)malloc(byteSize); if (flags & flag_Clear) Fill(size, data, 0.); else memcpy(data, buf->data, byteSize); while (msg->remain()) { double partial = msg->getf(); double amp = msg->getf(); if (flags & flag_Wavetable) add_wpartial(size, data, partial, amp, 0.); else add_partial(size, data, partial, amp, 0.); } if (flags & flag_Normalize) { if (flags & flag_Wavetable) normalize_wsamples(size, data, 1.); else normalize_samples(size, data, 1.); } memcpy(buf->data, data, byteSize); free(data); } void SineFill3(World* world, struct SndBuf* buf, struct sc_msg_iter* msg) { if (buf->channels != 1) return; int flags = msg->geti(); int size = buf->samples; int byteSize = size * sizeof(float); float* data = (float*)malloc(byteSize); if (flags & flag_Clear) Fill(size, data, 0.); else memcpy(data, buf->data, byteSize); while (msg->remain()) { double partial = msg->getf(); double amp = msg->getf(); double phase = msg->getf(); if (flags & flag_Wavetable) add_wpartial(size, data, partial, amp, phase); else add_partial(size, data, partial, amp, phase); } if (flags & flag_Normalize) { if (flags & flag_Wavetable) normalize_wsamples(size, data, 1.); else normalize_samples(size, data, 1.); } memcpy(buf->data, data, byteSize); free(data); } void NormalizeBuf(World* world, struct SndBuf* buf, struct sc_msg_iter* msg) { float newmax; if (msg->remain() != 0) { newmax = msg->getf(); } else { newmax = 1.f; } float* data = buf->data; int size = buf->samples; normalize_samples(size, data, newmax); } void NormalizeWaveBuf(World* world, struct SndBuf* buf, struct sc_msg_iter* msg) { float newmax; if (msg->remain() != 0) { newmax = msg->getf(); } else { newmax = 1.f; } float* data = buf->data; int size = buf->samples; normalize_wsamples(size, data, newmax); } void CopyBuf(World* world, struct SndBuf* buf, struct sc_msg_iter* msg) { int frames1 = buf->frames; int channels1 = buf->channels; int toPos = msg->geti(); uint32 bufnum2 = msg->geti(); int fromPos = msg->geti(); int length = msg->geti(); if (bufnum2 >= world->mNumSndBufs) bufnum2 = 0; SndBuf* buf2 = world->mSndBufs + bufnum2; int frames2 = buf2->frames; int channels2 = buf2->channels; if (channels1 != channels2) return; fromPos = sc_clip(fromPos, 0, frames2 - 1); toPos = sc_clip(toPos, 0, frames1 - 1); int maxLength = sc_min(frames2 - fromPos, frames1 - toPos); if (length < 0) { length = maxLength; } else { length = sc_min(length, maxLength); } if (length <= 0) return; int numbytes = length * sizeof(float) * channels1; float* data1 = buf->data + toPos * channels1; float* data2 = buf2->data + fromPos * channels2; if ((((char*)data1 + numbytes) > (char*)data2) || (((char*)data2 + numbytes) > (char*)data1)) { memmove(data1, data2, numbytes); } else { memcpy(data1, data2, numbytes); } } void CantorFill(World* world, struct SndBuf* buf, struct sc_msg_iter* msg) { float* data = buf->data; int size = buf->samples; // double offset = msg->getf(); // double amp = msg->getf(); // long offs = (long) offset; cantorFill(size, data); } //////////////////////////////////////////////////////////////////////////////////////////////////////// PluginLoad(Osc) { ft = inTable; DefineSimpleUnit(DegreeToKey); DefineSimpleUnit(Select); DefineSimpleUnit(TWindex); DefineSimpleUnit(Index); DefineSimpleUnit(IndexL); DefineSimpleUnit(FoldIndex); DefineSimpleUnit(WrapIndex); DefineSimpleUnit(IndexInBetween); DefineSimpleUnit(DetectIndex); DefineSimpleUnit(Shaper); DefineSimpleUnit(FSinOsc); DefineSimpleUnit(PSinGrain); DefineSimpleUnit(SinOsc); DefineSimpleUnit(SinOscFB); DefineSimpleUnit(VOsc); DefineSimpleUnit(VOsc3); DefineSimpleUnit(Osc); DefineSimpleUnit(OscN); DefineSimpleUnit(COsc); DefineSimpleUnit(Formant); DefineSimpleUnit(Blip); DefineSimpleUnit(Saw); DefineSimpleUnit(Pulse); DefineDtorUnit(Klang); DefineDtorUnit(Klank); DefineBufGen("cheby", ChebyFill); DefineBufGen("sine1", SineFill1); DefineBufGen("sine2", SineFill2); DefineBufGen("sine3", SineFill3); DefineBufGen("normalize", NormalizeBuf); DefineBufGen("wnormalize", NormalizeWaveBuf); DefineBufGen("copy", CopyBuf); DefineBufGen("cantorFill", CantorFill); } //////////////////////////////////////////////////////////////////////////////////////////////////
114,932
C++
.cpp
3,000
30.518
120
0.535776
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,972
ML_SpecStats.cpp
supercollider_supercollider/server/plugins/ML_SpecStats.cpp
/* Spectral statistics UGens for SuperCollider, by Dan Stowell. Copyright (c) Dan Stowell 2006-2007. Now part of SuperCollider 3, (c) James McCartney. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "SC_PlugIn.h" #include "SCComplex.h" #include "FFT_UGens.h" #include "ML.h" ////////////////////////////////////////////////////////////////////////////////////////////////// /* struct FFTAnalyser_Unit : Unit { float outval; // Not always used: multipliers which convert from bin indices to freq vals, and vice versa. // See also the macros for deriving these. float m_bintofreq; // , m_freqtobin; }; struct FFTAnalyser_OutOfPlace : FFTAnalyser_Unit { int m_numbins; float *m_tempbuf; }; struct SpecFlatness : FFTAnalyser_Unit { }; struct SpecPcile : FFTAnalyser_OutOfPlace { bool m_interpolate; }; struct SpecCentroid : FFTAnalyser_Unit { }; */ ////////////////////////////////////////////////////////////////////////////////////////////////// // for operation on one buffer // just like PV_GET_BUF except it outputs unit->outval rather than -1 when FFT not triggered #define FFTAnalyser_GET_BUF \ float fbufnum = ZIN0(0); \ if (fbufnum < 0.f) { \ ZOUT0(0) = unit->outval; \ return; \ } \ ZOUT0(0) = fbufnum; \ uint32 ibufnum = (uint32)fbufnum; \ World* world = unit->mWorld; \ SndBuf* buf; \ if (!(ibufnum < world->mNumSndBufs)) { \ int localBufNum = ibufnum - world->mNumSndBufs; \ Graph* parent = unit->mParent; \ if (!(localBufNum > parent->localBufNum)) { \ buf = parent->mLocalSndBufs + localBufNum; \ } else { \ buf = world->mSndBufs; \ } \ } else { \ buf = world->mSndBufs + ibufnum; \ } \ LOCK_SNDBUF(buf); \ int numbins = (buf->samples - 2) >> 1; // Copied from FFT_UGens.cpp #define GET_BINTOFREQ \ if (unit->m_bintofreq == 0.f) { \ unit->m_bintofreq = world->mFullRate.mSampleRate / buf->samples; \ } \ float bintofreq = unit->m_bintofreq; /* #define GET_FREQTOBIN \ if(unit->m_freqtobin==0.f){ \ unit->m_freqtobin = buf->samples / world->mFullRate.mSampleRate; \ } \ float freqtobin = unit->m_freqtobin; */ ////////////////////////////////////////////////////////////////////////////////////////////////// /* extern "C" { void SpecFlatness_Ctor(SpecFlatness *unit); void SpecFlatness_next(SpecFlatness *unit, int inNumSamples); void SpecPcile_Ctor(SpecPcile *unit); void SpecPcile_next(SpecPcile *unit, int inNumSamples); void SpecPcile_Dtor(SpecPcile *unit); void SpecCentroid_Ctor(SpecCentroid *unit); void SpecCentroid_next(SpecCentroid *unit, int inNumSamples); } */ /* SCPolarBuf* ToPolarApx(SndBuf *buf) { if (buf->coord == coord_Complex) { SCComplexBuf* p = (SCComplexBuf*)buf->data; int numbins = buf->samples - 2 >> 1; for (int i=0; i<numbins; ++i) { p->bin[i].ToPolarApxInPlace(); } buf->coord = coord_Polar; } return (SCPolarBuf*)buf->data; } SCComplexBuf* ToComplexApx(SndBuf *buf) { if (buf->coord == coord_Polar) { SCPolarBuf* p = (SCPolarBuf*)buf->data; int numbins = buf->samples - 2 >> 1; for (int i=0; i<numbins; ++i) { p->bin[i].ToComplexApxInPlace(); } buf->coord = coord_Complex; } return (SCComplexBuf*)buf->data; } InterfaceTable *ft; void init_SCComplex(InterfaceTable *inTable); */ ////////////////////////////////////////////////////////////////////////////////////////////////// void SpecFlatness_Ctor(SpecFlatness* unit) { SETCALC(SpecFlatness_next); ZOUT0(0) = unit->outval = 0.; unit->m_oneovern = 0.; } void SpecFlatness_next(SpecFlatness* unit, int inNumSamples) { FFTAnalyser_GET_BUF if (unit->m_oneovern == 0.) unit->m_oneovern = 1. / (numbins + 2); SCComplexBuf* p = ToComplexApx(buf); // Spectral Flatness Measure is geometric mean divided by arithmetic mean. // // In order to calculate geom mean without hitting the precision limit, // we use the trick of converting to log, taking the average, then converting back from log. double geommean = std::log(sc_abs(p->dc)) + std::log(sc_abs(p->nyq)); double mean = sc_abs(p->dc) + sc_abs(p->nyq); for (int i = 0; i < numbins; ++i) { float rabs = (p->bin[i].real); float iabs = (p->bin[i].imag); float amp = std::sqrt((rabs * rabs) + (iabs * iabs)); if (amp != 0.f) { // zeroes lead to NaNs geommean += std::log(amp); mean += amp; } } double oneovern = unit->m_oneovern; geommean = exp(geommean * oneovern); // Average and then convert back to linear mean *= oneovern; // Store the val for output in future calls unit->outval = (mean == 0.f ? 0.8f : (geommean / mean)); // Note: for silence the value is undefined. // Here, for silence we instead output an empirical value based on very quiet white noise. ZOUT0(0) = unit->outval; } //////////////////////////////////////////////////////////////////////////////////// void SpecPcile_Ctor(SpecPcile* unit) { SETCALC(SpecPcile_next); unit->m_interpolate = ZIN0(2) > 0.f; unit->m_binout = ZIN0(3) > 0.f; ZOUT0(0) = unit->outval = 0.; unit->m_tempbuf = nullptr; } void SpecPcile_next(SpecPcile* unit, int inNumSamples) { FFTAnalyser_GET_BUF // Used to be MAKE_TEMP_BUF but we can handle it more cleanly in this specific case: if (!unit->m_tempbuf) { unit->m_tempbuf = (float*)RTAlloc(unit->mWorld, numbins * sizeof(float)); if (!unit->m_tempbuf) { ClearUnitOutputs(unit, inNumSamples); ClearUnitOnMemFailed; } unit->m_numbins = numbins; unit->m_halfnyq_over_numbinsp2 = ((float)unit->mWorld->mSampleRate) * 0.5f / (float)(numbins + 2); } else if (numbins != unit->m_numbins) return; // Percentile value as a fraction. eg: 0.5 == 50-percentile (median). float fraction = ZIN0(1); bool binout = unit->m_binout; // if true, output the bin number instead of freq bool interpolate = unit->m_interpolate; // The magnitudes in *p will be converted to cumulative sum values and stored in *q temporarily SCComplexBuf* p = ToComplexApx(buf); float* q = (float*)unit->m_tempbuf; float cumul = sc_abs(p->dc); for (int i = 0; i < numbins; ++i) { float real = p->bin[i].real; float imag = p->bin[i].imag; cumul += std::sqrt(real * real + imag * imag); // A convenient place to store the mag values... q[i] = cumul; } cumul += sc_abs(p->nyq); float target = cumul * fraction; // The target cumul value, stored somewhere in q float bestposition = 0; // May be linear-interpolated between bins, but not implemented yet // NB If nothing beats the target (e.g. if fraction is -1) zero Hz is returned float binpos; for (int i = 0; i < numbins; ++i) { // Print("Testing %g, at position %i", q->bin[i].real, i); if (!(q[i] < target)) { // this is a ">=" comparison, done more efficiently as "!(<)" // output the bin number instead of freq if (binout) { if (interpolate && i != 0) { bestposition = ((float)i) + (q[i] - target) / (q[i] - q[i - 1]); } else { bestposition = i; // output bin directly } } else { if (interpolate && i != 0) { binpos = ((float)i) + 1.f - (q[i] - target) / (q[i] - q[i - 1]); } else { binpos = ((float)i) + 1.f; } bestposition = binpos * unit->m_halfnyq_over_numbinsp2; } // Print("Target %g beaten by %g (at position %i), equating to freq %g\n", // target, p->bin[i].real, i, bestposition); break; } } // Store the val for output in future calls unit->outval = bestposition; ZOUT0(0) = unit->outval; } void SpecPcile_Dtor(SpecPcile* unit) { if (unit->m_tempbuf) RTFree(unit->mWorld, unit->m_tempbuf); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void SpecCentroid_Ctor(SpecCentroid* unit) { SETCALC(SpecCentroid_next); ZOUT0(0) = unit->outval = 0.; unit->m_bintofreq = 0.f; } void SpecCentroid_next(SpecCentroid* unit, int inNumSamples) { FFTAnalyser_GET_BUF SCPolarBuf* p = ToPolarApx(buf); GET_BINTOFREQ double num = sc_abs(p->nyq) * (numbins + 1); double denom = sc_abs(p->nyq); for (int i = 0; i < numbins; ++i) { num += sc_abs(p->bin[i].mag) * (i + 1); denom += sc_abs(p->bin[i].mag); } ZOUT0(0) = unit->outval = denom == 0.0 ? 0.f : (float)(bintofreq * num / denom); } ////////////////////////////////////////////////////////////////////////////////////////////////// /* void load(InterfaceTable *inTable) { ft= inTable; //(*ft->fDefineUnit)("SpecFlatness", sizeof(FFTAnalyser_Unit), (UnitCtorFunc)&SpecFlatness_Ctor, 0, 0); //(*ft->fDefineUnit)("SpecPcile", sizeof(SpecPcile_Unit), (UnitCtorFunc)&SpecPcile_Ctor, (UnitDtorFunc)&SpecPcile_Dtor, 0); DefineSimpleUnit(SpecFlatness); DefineDtorUnit(SpecPcile); DefineSimpleUnit(SpecCentroid); } */
12,497
C++
.cpp
261
42.003831
120
0.468655
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,973
ReverbUGens.cpp
supercollider_supercollider/server/plugins/ReverbUGens.cpp
// FreeVerb UGens // faust code generation experiments. blackrain 07/2005 /* Copyright (c) 2005 blackrain <blackrain.sc@gmail.com>. All rights reserved. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "SC_PlugIn.h" // gcc3.3 mathlib doesnt know these yet #if gccversion < 4 # define powf pow # define sqrtf sqrt #endif static InterfaceTable* ft; struct FreeVerb : public Unit { int iota0; int iota1; int iota2; int iota3; int iota4; int iota5; int iota6; int iota7; int iota8; int iota9; int iota10; int iota11; float R0_1; float R1_1; float R2_1; float R3_1; float R0_0; float R1_0; float R2_0; float R3_0; float R4_0; float R5_0; float R6_0; float R7_0; float R8_0; float R9_0; float R10_0; float R11_0; float R12_0; float R13_0; float R14_0; float R15_0; float R16_0; float R17_0; float R18_0; float R19_0; float dline0[225]; float dline1[341]; float dline2[441]; float dline3[556]; float dline4[1617]; float dline5[1557]; float dline6[1491]; float dline7[1422]; float dline8[1277]; float dline9[1116]; float dline10[1188]; float dline11[1356]; }; /* GVerb work */ #define FDNORDER 4 typedef struct { int size; int idx; float* buf; } g_fixeddelay; typedef struct { int size; float coef; int idx; float* buf; } g_diffuser; typedef struct { float damping; float delay; } g_damper; struct GVerb : public Unit { float roomsize, revtime, damping, spread, inputbandwidth, drylevel, earlylevel, taillevel; float maxroomsize; float maxdelay, largestdelay; g_damper* inputdamper; g_fixeddelay* fdndels[FDNORDER]; float fdngains[FDNORDER]; int fdnlens[FDNORDER]; g_damper* fdndamps[FDNORDER]; double alpha; float u[FDNORDER], f[FDNORDER], d[FDNORDER]; g_diffuser* ldifs[FDNORDER]; g_diffuser* rdifs[FDNORDER]; g_fixeddelay* tapdelay; int taps[FDNORDER]; float tapgains[FDNORDER]; float earlylevelslope, taillevelslope, drylevelslope; float fdngainslopes[FDNORDER], tapgainslopes[FDNORDER]; // make the CALCSLOPE values part of the struct // calculate changes first, store them // grab values and use in the sample loop }; extern "C" { void FreeVerb_Ctor(FreeVerb* unit); void FreeVerb_next(FreeVerb* unit, int inNumSamples); void GVerb_Ctor(GVerb* unit); void GVerb_Dtor(GVerb* unit); void GVerb_next(GVerb* unit, int inNumSamples); }; void FreeVerb_Ctor(FreeVerb* unit) { SETCALC(FreeVerb_next); unit->iota0 = 0; unit->iota1 = 0; unit->iota2 = 0; unit->iota3 = 0; unit->iota4 = 0; unit->iota5 = 0; unit->iota6 = 0; unit->iota7 = 0; unit->iota8 = 0; unit->iota9 = 0; unit->iota10 = 0; unit->iota11 = 0; unit->R0_0 = 0.0; unit->R1_0 = 0.0; unit->R2_0 = 0.0; unit->R3_0 = 0.0; unit->R4_0 = 0.0; unit->R5_0 = 0.0; unit->R6_0 = 0.0; unit->R7_0 = 0.0; unit->R8_0 = 0.0; unit->R9_0 = 0.0; unit->R10_0 = 0.0; unit->R11_0 = 0.0; unit->R12_0 = 0.0; unit->R13_0 = 0.0; unit->R14_0 = 0.0; unit->R15_0 = 0.0; unit->R16_0 = 0.0; unit->R17_0 = 0.0; unit->R18_0 = 0.0; unit->R19_0 = 0.0; unit->R0_1 = 0.0; unit->R1_1 = 0.0; unit->R2_1 = 0.0; unit->R3_1 = 0.0; for (int i = 0; i < 225; i++) unit->dline0[i] = 0.0; for (int i = 0; i < 341; i++) unit->dline1[i] = 0.0; for (int i = 0; i < 441; i++) unit->dline2[i] = 0.0; for (int i = 0; i < 556; i++) unit->dline3[i] = 0.0; for (int i = 0; i < 1617; i++) unit->dline4[i] = 0.0; for (int i = 0; i < 1557; i++) unit->dline5[i] = 0.0; for (int i = 0; i < 1491; i++) unit->dline6[i] = 0.0; for (int i = 0; i < 1422; i++) unit->dline7[i] = 0.0; for (int i = 0; i < 1277; i++) unit->dline8[i] = 0.0; for (int i = 0; i < 1116; i++) unit->dline9[i] = 0.0; for (int i = 0; i < 1188; i++) unit->dline10[i] = 0.0; for (int i = 0; i < 1356; i++) unit->dline11[i] = 0.0; FreeVerb_next(unit, 1); } void FreeVerb_next(FreeVerb* unit, int inNumSamples) { float* input0 = IN(0); float* output0 = OUT(0); float ftemp0 = IN0(1); // mix if (ftemp0 > 1.) ftemp0 = 1.; if (ftemp0 < 0.) ftemp0 = 0.; float ftemp1 = (1 - ftemp0); float room = IN0(2); // room if (room > 1.) room = 1.; if (room < 0.) room = 0.; float ftemp5 = (0.700000f + (0.280000f * room)); float damp = IN0(3); // damp if (damp > 1.) damp = 1.; if (damp < 0.) damp = 0.; float ftemp6 = (0.400000f * damp); float ftemp7 = (1 - ftemp6); int iota0 = unit->iota0; int iota1 = unit->iota1; int iota2 = unit->iota2; int iota3 = unit->iota3; int iota4 = unit->iota4; int iota5 = unit->iota5; int iota6 = unit->iota6; int iota7 = unit->iota7; int iota8 = unit->iota8; int iota9 = unit->iota9; int iota10 = unit->iota10; int iota11 = unit->iota11; float R0_1 = unit->R0_1; float R1_1 = unit->R1_1; float R2_1 = unit->R2_1; float R3_1 = unit->R3_1; float R0_0 = unit->R0_0; float R1_0 = unit->R1_0; float R2_0 = unit->R2_0; float R3_0 = unit->R3_0; float R4_0 = unit->R4_0; float R5_0 = unit->R5_0; float R6_0 = unit->R6_0; float R7_0 = unit->R7_0; float R8_0 = unit->R8_0; float R9_0 = unit->R9_0; float R10_0 = unit->R10_0; float R11_0 = unit->R11_0; float R12_0 = unit->R12_0; float R13_0 = unit->R13_0; float R14_0 = unit->R14_0; float R15_0 = unit->R15_0; float R16_0 = unit->R16_0; float R17_0 = unit->R17_0; float R18_0 = unit->R18_0; float R19_0 = unit->R19_0; float* dline0 = unit->dline0; float* dline1 = unit->dline1; float* dline2 = unit->dline2; float* dline3 = unit->dline3; float* dline4 = unit->dline4; float* dline5 = unit->dline5; float* dline6 = unit->dline6; float* dline7 = unit->dline7; float* dline8 = unit->dline8; float* dline9 = unit->dline9; float* dline10 = unit->dline10; float* dline11 = unit->dline11; for (int i = 0; i < inNumSamples; i++) { float ftemp2 = input0[i]; float ftemp4 = (1.500000e-02f * ftemp2); if (++iota0 == 225) iota0 = 0; float T0 = dline0[iota0]; if (++iota1 == 341) iota1 = 0; float T1 = dline1[iota1]; if (++iota2 == 441) iota2 = 0; float T2 = dline2[iota2]; if (++iota3 == 556) iota3 = 0; float T3 = dline3[iota3]; if (++iota4 == 1617) iota4 = 0; float T4 = dline4[iota4]; R5_0 = ((ftemp7 * R4_0) + (ftemp6 * R5_0)); dline4[iota4] = (ftemp4 + (ftemp5 * R5_0)); R4_0 = T4; if (++iota5 == 1557) iota5 = 0; float T5 = dline5[iota5]; R7_0 = ((ftemp7 * R6_0) + (ftemp6 * R7_0)); dline5[iota5] = (ftemp4 + (ftemp5 * R7_0)); R6_0 = T5; if (++iota6 == 1491) iota6 = 0; float T6 = dline6[iota6]; R9_0 = ((ftemp7 * R8_0) + (ftemp6 * R9_0)); dline6[iota6] = (ftemp4 + (ftemp5 * R9_0)); R8_0 = T6; if (++iota7 == 1422) iota7 = 0; float T7 = dline7[iota7]; R11_0 = ((ftemp7 * R10_0) + (ftemp6 * R11_0)); dline7[iota7] = (ftemp4 + (ftemp5 * R11_0)); R10_0 = T7; if (++iota8 == 1277) iota8 = 0; float T8 = dline8[iota8]; R13_0 = ((ftemp7 * R12_0) + (ftemp6 * R13_0)); dline8[iota8] = (ftemp4 + (ftemp5 * R13_0)); R12_0 = T8; if (++iota9 == 1116) iota9 = 0; float T9 = dline9[iota9]; R15_0 = ((ftemp7 * R14_0) + (ftemp6 * R15_0)); dline9[iota9] = (ftemp4 + (ftemp5 * R15_0)); R14_0 = T9; if (++iota10 == 1188) iota10 = 0; float T10 = dline10[iota10]; R17_0 = ((ftemp7 * R16_0) + (ftemp6 * R17_0)); dline10[iota10] = (ftemp4 + (ftemp5 * R17_0)); R16_0 = T10; if (++iota11 == 1356) iota11 = 0; float T11 = dline11[iota11]; R19_0 = ((ftemp7 * R18_0) + (ftemp6 * R19_0)); dline11[iota11] = (ftemp4 + (ftemp5 * R19_0)); R18_0 = T11; float ftemp8 = (R16_0 + R18_0); dline3[iota3] = ((((0.500000f * R3_0) + R4_0) + (R6_0 + R8_0)) + ((R10_0 + R12_0) + (R14_0 + ftemp8))); R3_0 = T3; R3_1 = (R3_0 - (((R4_0 + R6_0) + (R8_0 + R10_0)) + ((R12_0 + R14_0) + ftemp8))); dline2[iota2] = ((0.500000f * R2_0) + R3_1); R2_0 = T2; R2_1 = (R2_0 - R3_1); dline1[iota1] = ((0.500000f * R1_0) + R2_1); R1_0 = T1; R1_1 = (R1_0 - R2_1); dline0[iota0] = ((0.500000f * R0_0) + R1_1); R0_0 = T0; R0_1 = (R0_0 - R1_1); output0[i] = ((ftemp1 * ftemp2) + (ftemp0 * R0_1)); } unit->iota0 = iota0; unit->iota1 = iota1; unit->iota2 = iota2; unit->iota3 = iota3; unit->iota4 = iota4; unit->iota5 = iota5; unit->iota6 = iota6; unit->iota7 = iota7; unit->iota8 = iota8; unit->iota9 = iota9; unit->iota10 = iota10; unit->iota11 = iota11; unit->R0_1 = R0_1; unit->R1_1 = R1_1; unit->R2_1 = R2_1; unit->R3_1 = R3_1; unit->R0_0 = R0_0; unit->R1_0 = R1_0; unit->R2_0 = R2_0; unit->R3_0 = R3_0; unit->R4_0 = R4_0; unit->R5_0 = R5_0; unit->R6_0 = R6_0; unit->R7_0 = R7_0; unit->R8_0 = R8_0; unit->R9_0 = R9_0; unit->R10_0 = R10_0; unit->R11_0 = R11_0; unit->R12_0 = R12_0; unit->R13_0 = R13_0; unit->R14_0 = R14_0; unit->R15_0 = R15_0; unit->R16_0 = R16_0; unit->R17_0 = R17_0; unit->R18_0 = R18_0; unit->R19_0 = R19_0; } // FreeVerb2 struct FreeVerb2 : public Unit { int iota0; int iota1; int iota2; int iota3; int iota4; int iota5; int iota6; int iota7; int iota8; int iota9; int iota10; int iota11; int iota12; int iota13; int iota14; int iota15; int iota16; int iota17; int iota18; int iota19; int iota20; int iota21; int iota22; int iota23; float R0_1; float R1_1; float R2_1; float R3_1; float R0_0; float R1_0; float R2_0; float R3_0; float R4_0; float R5_0; float R6_0; float R7_0; float R8_0; float R9_0; float R10_0; float R11_0; float R12_0; float R13_0; float R14_0; float R15_0; float R16_0; float R17_0; float R18_0; float R19_0; float R20_0; float R21_0; float R22_0; float R23_0; float R24_0; float R25_0; float R26_0; float R27_0; float R28_0; float R29_0; float R30_0; float R31_0; float R32_0; float R33_0; float R34_0; float R35_0; float R36_0; float R37_0; float R38_0; float R39_0; float R20_1; float R21_1; float R22_1; float R23_1; float dline0[225]; float dline1[341]; float dline2[441]; float dline3[556]; float dline4[1617]; float dline5[1557]; float dline6[1491]; float dline7[1422]; float dline8[1277]; float dline9[1116]; float dline10[1188]; float dline11[1356]; float dline12[248]; float dline13[364]; float dline14[464]; float dline15[579]; float dline16[1640]; float dline17[1580]; float dline18[1514]; float dline19[1445]; float dline20[1300]; float dline21[1139]; float dline22[1211]; float dline23[1379]; }; extern "C" { void FreeVerb2_Ctor(FreeVerb2* unit); void FreeVerb2_next(FreeVerb2* unit, int inNumSamples); }; void FreeVerb2_Ctor(FreeVerb2* unit) { SETCALC(FreeVerb2_next); unit->iota0 = 0; unit->iota1 = 0; unit->iota2 = 0; unit->iota3 = 0; unit->iota4 = 0; unit->iota5 = 0; unit->iota6 = 0; unit->iota7 = 0; unit->iota8 = 0; unit->iota9 = 0; unit->iota10 = 0; unit->iota11 = 0; unit->iota12 = 0; unit->iota13 = 0; unit->iota14 = 0; unit->iota15 = 0; unit->iota16 = 0; unit->iota17 = 0; unit->iota18 = 0; unit->iota19 = 0; unit->iota20 = 0; unit->iota21 = 0; unit->iota22 = 0; unit->iota23 = 0; unit->R0_0 = 0.0; unit->R1_0 = 0.0; unit->R2_0 = 0.0; unit->R3_0 = 0.0; unit->R4_0 = 0.0; unit->R5_0 = 0.0; unit->R6_0 = 0.0; unit->R7_0 = 0.0; unit->R8_0 = 0.0; unit->R9_0 = 0.0; unit->R10_0 = 0.0; unit->R11_0 = 0.0; unit->R12_0 = 0.0; unit->R13_0 = 0.0; unit->R14_0 = 0.0; unit->R15_0 = 0.0; unit->R16_0 = 0.0; unit->R17_0 = 0.0; unit->R18_0 = 0.0; unit->R19_0 = 0.0; unit->R20_0 = 0.0; unit->R21_0 = 0.0; unit->R22_0 = 0.0; unit->R23_0 = 0.0; unit->R24_0 = 0.0; unit->R25_0 = 0.0; unit->R26_0 = 0.0; unit->R27_0 = 0.0; unit->R28_0 = 0.0; unit->R29_0 = 0.0; unit->R30_0 = 0.0; unit->R31_0 = 0.0; unit->R32_0 = 0.0; unit->R33_0 = 0.0; unit->R34_0 = 0.0; unit->R35_0 = 0.0; unit->R36_0 = 0.0; unit->R37_0 = 0.0; unit->R38_0 = 0.0; unit->R39_0 = 0.0; unit->R0_1 = 0.0; unit->R1_1 = 0.0; unit->R2_1 = 0.0; unit->R3_1 = 0.0; unit->R23_1 = 0.0; unit->R22_1 = 0.0; unit->R21_1 = 0.0; unit->R20_1 = 0.0; for (int i = 0; i < 225; i++) unit->dline0[i] = 0.0; for (int i = 0; i < 341; i++) unit->dline1[i] = 0.0; for (int i = 0; i < 441; i++) unit->dline2[i] = 0.0; for (int i = 0; i < 556; i++) unit->dline3[i] = 0.0; for (int i = 0; i < 1617; i++) unit->dline4[i] = 0.0; for (int i = 0; i < 1557; i++) unit->dline5[i] = 0.0; for (int i = 0; i < 1491; i++) unit->dline6[i] = 0.0; for (int i = 0; i < 1422; i++) unit->dline7[i] = 0.0; for (int i = 0; i < 1277; i++) unit->dline8[i] = 0.0; for (int i = 0; i < 1116; i++) unit->dline9[i] = 0.0; for (int i = 0; i < 1188; i++) unit->dline10[i] = 0.0; for (int i = 0; i < 1356; i++) unit->dline11[i] = 0.0; for (int i = 0; i < 248; i++) unit->dline12[i] = 0.0; for (int i = 0; i < 364; i++) unit->dline13[i] = 0.0; for (int i = 0; i < 464; i++) unit->dline14[i] = 0.0; for (int i = 0; i < 579; i++) unit->dline15[i] = 0.0; for (int i = 0; i < 1640; i++) unit->dline16[i] = 0.0; for (int i = 0; i < 1580; i++) unit->dline17[i] = 0.0; for (int i = 0; i < 1514; i++) unit->dline18[i] = 0.0; for (int i = 0; i < 1445; i++) unit->dline19[i] = 0.0; for (int i = 0; i < 1300; i++) unit->dline20[i] = 0.0; for (int i = 0; i < 1139; i++) unit->dline21[i] = 0.0; for (int i = 0; i < 1211; i++) unit->dline22[i] = 0.0; for (int i = 0; i < 1379; i++) unit->dline23[i] = 0.0; FreeVerb2_next(unit, 1); } void FreeVerb2_next(FreeVerb2* unit, int inNumSamples) { float* input0 = IN(0); float* input1 = IN(1); float* output0 = OUT(0); float* output1 = OUT(1); float ftemp0 = IN0(2); // mix if (ftemp0 > 1.) ftemp0 = 1.; if (ftemp0 < 0.) ftemp0 = 0.; float ftemp1 = (1 - ftemp0); float room = IN0(3); // room if (room > 1.) room = 1.; if (room < 0.) room = 0.; float ftemp5 = (0.700000f + (0.280000f * room)); float damp = IN0(4); // damp if (damp > 1.) damp = 1.; if (damp < 0.) damp = 0.; float ftemp6 = (0.400000f * damp); float ftemp7 = (1 - ftemp6); float R0_0 = unit->R0_0; float R1_0 = unit->R1_0; float R2_0 = unit->R2_0; float R3_0 = unit->R3_0; float R4_0 = unit->R4_0; float R5_0 = unit->R5_0; float R6_0 = unit->R6_0; float R7_0 = unit->R7_0; float R8_0 = unit->R8_0; float R9_0 = unit->R9_0; float R10_0 = unit->R10_0; float R11_0 = unit->R11_0; float R12_0 = unit->R12_0; float R13_0 = unit->R13_0; float R14_0 = unit->R14_0; float R15_0 = unit->R15_0; float R16_0 = unit->R16_0; float R17_0 = unit->R17_0; float R18_0 = unit->R18_0; float R19_0 = unit->R19_0; float R20_0 = unit->R20_0; float R21_0 = unit->R21_0; float R22_0 = unit->R22_0; float R23_0 = unit->R23_0; float R24_0 = unit->R24_0; float R25_0 = unit->R25_0; float R26_0 = unit->R26_0; float R27_0 = unit->R27_0; float R28_0 = unit->R28_0; float R29_0 = unit->R29_0; float R30_0 = unit->R30_0; float R31_0 = unit->R31_0; float R32_0 = unit->R32_0; float R33_0 = unit->R33_0; float R34_0 = unit->R34_0; float R35_0 = unit->R35_0; float R36_0 = unit->R36_0; float R37_0 = unit->R37_0; float R38_0 = unit->R38_0; float R39_0 = unit->R39_0; float R0_1 = unit->R0_1; float R1_1 = unit->R1_1; float R2_1 = unit->R2_1; float R3_1 = unit->R3_1; float R23_1 = unit->R23_1; float R22_1 = unit->R22_1; float R21_1 = unit->R21_1; float R20_1 = unit->R20_1; int iota0 = unit->iota0; int iota1 = unit->iota1; int iota2 = unit->iota2; int iota3 = unit->iota3; int iota4 = unit->iota4; int iota5 = unit->iota5; int iota6 = unit->iota6; int iota7 = unit->iota7; int iota8 = unit->iota8; int iota9 = unit->iota9; int iota10 = unit->iota10; int iota11 = unit->iota11; int iota12 = unit->iota12; int iota13 = unit->iota13; int iota14 = unit->iota14; int iota15 = unit->iota15; int iota16 = unit->iota16; int iota17 = unit->iota17; int iota18 = unit->iota18; int iota19 = unit->iota19; int iota20 = unit->iota20; int iota21 = unit->iota21; int iota22 = unit->iota22; int iota23 = unit->iota23; float* dline0 = unit->dline0; float* dline1 = unit->dline1; float* dline2 = unit->dline2; float* dline3 = unit->dline3; float* dline4 = unit->dline4; float* dline5 = unit->dline5; float* dline6 = unit->dline6; float* dline7 = unit->dline7; float* dline8 = unit->dline8; float* dline9 = unit->dline9; float* dline10 = unit->dline10; float* dline11 = unit->dline11; float* dline12 = unit->dline12; float* dline13 = unit->dline13; float* dline14 = unit->dline14; float* dline15 = unit->dline15; float* dline16 = unit->dline16; float* dline17 = unit->dline17; float* dline18 = unit->dline18; float* dline19 = unit->dline19; float* dline20 = unit->dline20; float* dline21 = unit->dline21; float* dline22 = unit->dline22; float* dline23 = unit->dline23; for (int i = 0; i < inNumSamples; i++) { float ftemp2 = input0[i]; if (++iota0 == 225) iota0 = 0; float T0 = dline0[iota0]; if (++iota1 == 341) iota1 = 0; float T1 = dline1[iota1]; if (++iota2 == 441) iota2 = 0; float T2 = dline2[iota2]; if (++iota3 == 556) iota3 = 0; float T3 = dline3[iota3]; if (++iota4 == 1617) iota4 = 0; float T4 = dline4[iota4]; float ftemp3 = input1[i]; float ftemp4 = (1.500000e-02f * (ftemp2 + ftemp3)); R5_0 = ((ftemp7 * R4_0) + (ftemp6 * R5_0)); dline4[iota4] = (ftemp4 + (ftemp5 * R5_0)); R4_0 = T4; if (++iota5 == 1557) iota5 = 0; float T5 = dline5[iota5]; R7_0 = ((ftemp7 * R6_0) + (ftemp6 * R7_0)); dline5[iota5] = (ftemp4 + (ftemp5 * R7_0)); R6_0 = T5; if (++iota6 == 1491) iota6 = 0; float T6 = dline6[iota6]; R9_0 = ((ftemp7 * R8_0) + (ftemp6 * R9_0)); dline6[iota6] = (ftemp4 + (ftemp5 * R9_0)); R8_0 = T6; if (++iota7 == 1422) iota7 = 0; float T7 = dline7[iota7]; R11_0 = ((ftemp7 * R10_0) + (ftemp6 * R11_0)); dline7[iota7] = (ftemp4 + (ftemp5 * R11_0)); R10_0 = T7; if (++iota8 == 1277) iota8 = 0; float T8 = dline8[iota8]; R13_0 = ((ftemp7 * R12_0) + (ftemp6 * R13_0)); dline8[iota8] = (ftemp4 + (ftemp5 * R13_0)); R12_0 = T8; if (++iota9 == 1116) iota9 = 0; float T9 = dline9[iota9]; R15_0 = ((ftemp7 * R14_0) + (ftemp6 * R15_0)); dline9[iota9] = (ftemp4 + (ftemp5 * R15_0)); R14_0 = T9; if (++iota10 == 1188) iota10 = 0; float T10 = dline10[iota10]; R17_0 = ((ftemp7 * R16_0) + (ftemp6 * R17_0)); dline10[iota10] = (ftemp4 + (ftemp5 * R17_0)); R16_0 = T10; if (++iota11 == 1356) iota11 = 0; float T11 = dline11[iota11]; R19_0 = ((ftemp7 * R18_0) + (ftemp6 * R19_0)); dline11[iota11] = (ftemp4 + (ftemp5 * R19_0)); R18_0 = T11; float ftemp8 = (R16_0 + R18_0); dline3[iota3] = ((((0.500000f * R3_0) + R4_0) + (R6_0 + R8_0)) + ((R10_0 + R12_0) + (R14_0 + ftemp8))); R3_0 = T3; R3_1 = (R3_0 - (((R4_0 + R6_0) + (R8_0 + R10_0)) + ((R12_0 + R14_0) + ftemp8))); dline2[iota2] = ((0.500000f * R2_0) + R3_1); R2_0 = T2; R2_1 = (R2_0 - R3_1); dline1[iota1] = ((0.500000f * R1_0) + R2_1); R1_0 = T1; R1_1 = (R1_0 - R2_1); dline0[iota0] = ((0.500000f * R0_0) + R1_1); R0_0 = T0; R0_1 = (R0_0 - R1_1); output0[i] = ((ftemp1 * ftemp2) + (ftemp0 * R0_1)); // right chn if (++iota12 == 248) iota12 = 0; float T12 = dline12[iota12]; if (++iota13 == 364) iota13 = 0; float T13 = dline13[iota13]; if (++iota14 == 464) iota14 = 0; float T14 = dline14[iota14]; if (++iota15 == 579) iota15 = 0; float T15 = dline15[iota15]; if (++iota16 == 1640) iota16 = 0; float T16 = dline16[iota16]; R25_0 = ((ftemp7 * R24_0) + (ftemp6 * R25_0)); dline16[iota16] = (ftemp4 + (ftemp5 * R25_0)); R24_0 = T16; if (++iota17 == 1580) iota17 = 0; float T17 = dline17[iota17]; R27_0 = ((ftemp7 * R26_0) + (ftemp6 * R27_0)); dline17[iota17] = (ftemp4 + (ftemp5 * R27_0)); R26_0 = T17; if (++iota18 == 1514) iota18 = 0; float T18 = dline18[iota18]; R29_0 = ((ftemp7 * R28_0) + (ftemp6 * R29_0)); dline18[iota18] = (ftemp4 + (ftemp5 * R29_0)); R28_0 = T18; if (++iota19 == 1445) iota19 = 0; float T19 = dline19[iota19]; R31_0 = ((ftemp7 * R30_0) + (ftemp6 * R31_0)); dline19[iota19] = (ftemp4 + (ftemp5 * R31_0)); R30_0 = T19; if (++iota20 == 1300) iota20 = 0; float T20 = dline20[iota20]; R33_0 = ((ftemp7 * R32_0) + (ftemp6 * R33_0)); dline20[iota20] = (ftemp4 + (ftemp5 * R33_0)); R32_0 = T20; if (++iota21 == 1139) iota21 = 0; float T21 = dline21[iota21]; R35_0 = ((ftemp7 * R34_0) + (ftemp6 * R35_0)); dline21[iota21] = (ftemp4 + (ftemp5 * R35_0)); R34_0 = T21; if (++iota22 == 1211) iota22 = 0; float T22 = dline22[iota22]; R37_0 = ((ftemp7 * R36_0) + (ftemp6 * R37_0)); dline22[iota22] = (ftemp4 + (ftemp5 * R37_0)); R36_0 = T22; if (++iota23 == 1379) iota23 = 0; float T23 = dline23[iota23]; R39_0 = ((ftemp7 * R38_0) + (ftemp6 * R39_0)); dline23[iota23] = (ftemp4 + (ftemp5 * R39_0)); R38_0 = T23; float ftemp9 = (R36_0 + R38_0); dline15[iota15] = ((((0.500000f * R23_0) + R24_0) + (R26_0 + R28_0)) + ((R30_0 + R32_0) + (R34_0 + ftemp9))); R23_0 = T15; R23_1 = (R23_0 - (((R24_0 + R26_0) + (R28_0 + R30_0)) + ((R32_0 + R34_0) + ftemp9))); dline14[iota14] = ((0.500000f * R22_0) + R23_1); R22_0 = T14; R22_1 = (R22_0 - R23_1); dline13[iota13] = ((0.500000f * R21_0) + R22_1); R21_0 = T13; R21_1 = (R21_0 - R22_1); dline12[iota12] = ((0.500000f * R20_0) + R21_1); R20_0 = T12; R20_1 = (R20_0 - R21_1); output1[i] = ((ftemp1 * ftemp3) + (ftemp0 * R20_1)); } unit->iota0 = iota0; unit->iota1 = iota1; unit->iota2 = iota2; unit->iota3 = iota3; unit->iota4 = iota4; unit->iota5 = iota5; unit->iota6 = iota6; unit->iota7 = iota7; unit->iota8 = iota8; unit->iota9 = iota9; unit->iota10 = iota10; unit->iota11 = iota11; unit->iota12 = iota12; unit->iota13 = iota13; unit->iota14 = iota14; unit->iota15 = iota15; unit->iota16 = iota16; unit->iota17 = iota17; unit->iota18 = iota18; unit->iota19 = iota19; unit->iota20 = iota20; unit->iota21 = iota21; unit->iota22 = iota22; unit->iota23 = iota23; unit->R0_1 = R0_1; unit->R1_1 = R1_1; unit->R2_1 = R2_1; unit->R3_1 = R3_1; unit->R20_1 = R20_1; unit->R21_1 = R21_1; unit->R22_1 = R22_1; unit->R23_1 = R23_1; unit->R0_0 = R0_0; unit->R1_0 = R1_0; unit->R2_0 = R2_0; unit->R3_0 = R3_0; unit->R4_0 = R4_0; unit->R5_0 = R5_0; unit->R6_0 = R6_0; unit->R7_0 = R7_0; unit->R8_0 = R8_0; unit->R9_0 = R9_0; unit->R10_0 = R10_0; unit->R11_0 = R11_0; unit->R12_0 = R12_0; unit->R13_0 = R13_0; unit->R14_0 = R14_0; unit->R15_0 = R15_0; unit->R16_0 = R16_0; unit->R17_0 = R17_0; unit->R18_0 = R18_0; unit->R19_0 = R19_0; unit->R20_0 = R20_0; unit->R21_0 = R21_0; unit->R22_0 = R22_0; unit->R23_0 = R23_0; unit->R24_0 = R24_0; unit->R25_0 = R25_0; unit->R26_0 = R26_0; unit->R27_0 = R27_0; unit->R28_0 = R28_0; unit->R29_0 = R29_0; unit->R30_0 = R30_0; unit->R31_0 = R31_0; unit->R32_0 = R32_0; unit->R33_0 = R33_0; unit->R34_0 = R34_0; unit->R35_0 = R35_0; unit->R36_0 = R36_0; unit->R37_0 = R37_0; unit->R38_0 = R38_0; unit->R39_0 = R39_0; } #define TRUE 1 #define FALSE 0 typedef union { float f; #ifdef _WIN32 long int i; #else int32_t i; #endif } ls_pcast32; static inline float flush_to_zero(float f) { ls_pcast32 v; v.f = f; // original: return (v.i & 0x7f800000) == 0 ? 0.0f : f; // version from Tim Blechmann return (v.i & 0x7f800000) < 0x08000000 ? 0.0f : f; } int isprime(int n) { unsigned int i; const unsigned int lim = (int)sqrtf((float)n); if (n == 2) return (TRUE); if ((n & 1) == 0) return (FALSE); for (i = 3; i <= lim; i += 2) if ((n % i) == 0) return (FALSE); return (TRUE); } int nearestprime(int n, float rerror) { int bound, k; if (isprime(n)) return (n); /* assume n is large enough and n*rerror enough smaller than n */ bound = n * static_cast<int>(rerror); for (k = 1; k <= bound; k++) { if (isprime(n + k)) return (n + k); if (isprime(n - k)) return (n - k); } return (-1); } static inline int f_round(float f) { ls_pcast32 p; p.f = f; p.f += (3 << 22); return p.i - 0x4b400000; } g_damper* make_damper(GVerb* unit, float damping) { g_damper* p; p = (g_damper*)RTAlloc(unit->mWorld, sizeof(g_damper)); if (p == nullptr) return nullptr; p->damping = damping; p->delay = 0.f; return (p); } void free_damper(GVerb* unit, g_damper* p) { RTFree(unit->mWorld, p); }; g_diffuser* make_diffuser(GVerb* unit, int size, float coef) { g_diffuser* p; p = (g_diffuser*)RTAlloc(unit->mWorld, sizeof(g_diffuser)); if (p == nullptr) return nullptr; p->size = size; p->coef = coef; p->idx = 0; p->buf = (float*)RTAlloc(unit->mWorld, size * sizeof(float)); if (p->buf == nullptr) { RTFree(unit->mWorld, p); return nullptr; } Clear(size, p->buf); return (p); } void free_diffuser(GVerb* unit, g_diffuser* p) { if (p) RTFree(unit->mWorld, p->buf); RTFree(unit->mWorld, p); } g_fixeddelay* make_fixeddelay(GVerb* unit, int size, int maxsize) { g_fixeddelay* p; p = (g_fixeddelay*)RTAlloc(unit->mWorld, sizeof(g_fixeddelay)); if (p == nullptr) return nullptr; p->size = size; p->idx = 0; p->buf = (float*)RTAlloc(unit->mWorld, maxsize * sizeof(float)); if (p->buf == nullptr) { RTFree(unit->mWorld, p); return nullptr; } Clear(maxsize, p->buf); return (p); } void free_fixeddelay(GVerb* unit, g_fixeddelay* p) { if (p) RTFree(unit->mWorld, p->buf); RTFree(unit->mWorld, p); } static inline float diffuser_do(GVerb* unit, g_diffuser* p, float x) { float y, w; w = x - p->buf[p->idx] * p->coef; w = flush_to_zero(w); y = p->buf[p->idx] + w * p->coef; p->buf[p->idx] = zapgremlins(w); p->idx = (p->idx + 1) % p->size; return (y); } static inline float fixeddelay_read(GVerb* unit, g_fixeddelay* p, int n) { int i; i = (p->idx - n + p->size) % p->size; return (p->buf[i]); } static inline void fixeddelay_write(GVerb* unit, g_fixeddelay* p, float x) { p->buf[p->idx] = zapgremlins(x); p->idx = (p->idx + 1) % p->size; } static inline void damper_set(GVerb* unit, g_damper* p, float damping) { p->damping = damping; } static inline float damper_do(GVerb* unit, g_damper* p, float x) { float y; y = x * (1.0f - p->damping) + p->delay * p->damping; p->delay = zapgremlins(y); return (y); } static inline void gverb_fdnmatrix(float* a, float* b) { const float dl0 = a[0], dl1 = a[1], dl2 = a[2], dl3 = a[3]; b[0] = 0.5f * (+dl0 + dl1 - dl2 - dl3); b[1] = 0.5f * (+dl0 - dl1 - dl2 + dl3); b[2] = 0.5f * (-dl0 + dl1 - dl2 + dl3); b[3] = 0.5f * (+dl0 + dl1 + dl2 + dl3); } static inline void gverb_set_roomsize(GVerb* unit, const float a) { unsigned int i; if (a <= 1.0 || sc_isnan(a)) { unit->roomsize = 1.0; } else { if (a >= unit->maxroomsize) unit->roomsize = unit->maxroomsize - 1.f; else unit->roomsize = a; }; unit->largestdelay = SAMPLERATE * unit->roomsize / 340.0; // * 0.00294f; // the line below causes everything to blow up.... why????? // unit->fdnlens[0] = nearestprime((int)(unit->largestdelay), 0.5); unit->fdnlens[1] = (int)(0.816490 * unit->largestdelay); unit->fdnlens[2] = (int)(0.707100 * unit->largestdelay); unit->fdnlens[3] = (int)(0.632450 * unit->largestdelay); for (i = 0; i < FDNORDER; i++) { float oldfdngain = unit->fdngains[i]; unit->fdngains[i] = static_cast<float>(-std::pow(unit->alpha, static_cast<double>(unit->fdnlens[i]))); unit->fdngainslopes[i] = CALCSLOPE(unit->fdngains[i], oldfdngain); } unit->taps[0] = 5 + (int)(0.410 * unit->largestdelay); unit->taps[1] = 5 + (int)(0.300 * unit->largestdelay); unit->taps[2] = 5 + (int)(0.155 * unit->largestdelay); unit->taps[3] = 5; //+ f_round(0.000 * largestdelay); for (i = 0; i < FDNORDER; i++) { float oldtapgain = unit->tapgains[i]; unit->tapgains[i] = static_cast<float>(std::pow(unit->alpha, static_cast<double>(unit->taps[i]))); unit->tapgainslopes[i] = CALCSLOPE(unit->tapgains[i], oldtapgain); } } static inline void gverb_set_revtime(GVerb* unit, float a) { float ga; double n; unsigned int i; unit->revtime = a; ga = 0.001; n = SAMPLERATE * a; unit->alpha = (double)powf(ga, (float)(1.f / n)); for (i = 0; i < FDNORDER; i++) { float oldfdngain = unit->fdngains[i]; unit->fdngains[i] = static_cast<float>(-std::pow(unit->alpha, static_cast<double>(unit->fdnlens[i]))); unit->fdngainslopes[i] = CALCSLOPE(unit->fdngains[i], oldfdngain); } } static inline void gverb_set_damping(GVerb* unit, float a) { unsigned int i; unit->damping = a; for (i = 0; i < FDNORDER; i++) { damper_set(unit, unit->fdndamps[i], unit->damping); } } static inline void gverb_set_inputbandwidth(GVerb* unit, float a) { unit->inputbandwidth = a; damper_set(unit, unit->inputdamper, 1.0 - unit->inputbandwidth); } static inline float gverb_set_earlylevel(GVerb* unit, float a) { float oldearly = unit->earlylevel; unit->earlylevel = a; unit->earlylevelslope = CALCSLOPE(a, oldearly); return (oldearly); } static inline float gverb_set_taillevel(GVerb* unit, float a) { float oldtail = unit->taillevel; unit->taillevel = a; unit->taillevelslope = CALCSLOPE(a, oldtail); return (oldtail); } static inline float gverb_set_drylevel(GVerb* unit, float a) { float olddry = unit->drylevel; unit->drylevel = a; unit->drylevelslope = CALCSLOPE(a, olddry); return (olddry); } void GVerb_Ctor(GVerb* unit) { SETCALC(GVerb_next); float roomsize = unit->roomsize = IN0(1); float revtime = unit->revtime = IN0(2); float damping = unit->damping = IN0(3); float inputbandwidth = unit->inputbandwidth = 0.; // IN0(4); float spread = unit->spread = IN0(5); unit->drylevel = 0.; // IN0(6); unit->earlylevel = 0.; // IN0(7); unit->taillevel = 0.; // IN0(8); // when roomsize is greater than maxroomsize, it is set to maxroomsize - 1 // when roomsize is less than 0, it is set to 1, therefore maxroomsize must be at least 1. float maxroomsize = unit->maxroomsize = sc_max(1.0001f, IN0(9)); float maxdelay = unit->maxdelay = SAMPLERATE * maxroomsize / 340.f; float largestdelay = unit->largestdelay = SAMPLERATE * roomsize / 340.f; for (int i = 0; i < FDNORDER; ++i) { unit->fdndels[i] = nullptr; unit->fdndamps[i] = nullptr; unit->ldifs[i] = nullptr; unit->rdifs[i] = nullptr; } unit->tapdelay = nullptr; // make the inputdamper unit->inputdamper = make_damper(unit, 1. - inputbandwidth); ClearUnitIfMemFailed(unit->inputdamper); // float ga = powf(10.f, -60.f/20.f); float ga = 0.001f; float n = SAMPLERATE * revtime; double alpha = unit->alpha = pow((double)ga, 1. / (double)n); float gbmul[4] = { 1.000, 0.816490, 0.707100, 0.632450 }; for (int i = 0; i < FDNORDER; ++i) { float gb = gbmul[i] * largestdelay; if (i == 0) { unit->fdnlens[i] = nearestprime((int)gb, 0.5); } else { unit->fdnlens[i] = f_round(gb); } unit->fdngains[i] = static_cast<float>(-std::pow(alpha, static_cast<double>(unit->fdnlens[i]))); } // make the fixeddelay lines and dampers for (int i = 0; i < FDNORDER; i++) { unit->fdndels[i] = make_fixeddelay(unit, (int)unit->fdnlens[i], (int)maxdelay + 1000); unit->fdndamps[i] = make_damper(unit, damping); // damping is the same as fdndamping in source ClearUnitIfMemFailed(unit->fdndels[i] && unit->fdndamps[i]); } // diffuser section float diffscale = static_cast<float>(unit->fdnlens[3] / (210. + 159. + 562. + 410.)); float spread1 = spread; float spread2 = 3.0 * spread; int b = 210; float r = 0.125541; int a = (int)(spread1 * r); int c = 210 + 159 + a; int cc = c - b; r = 0.854046; a = (int)(spread2 * r); int d = 210 + 159 + 562 + a; int dd = d - c; int e = 1341 - d; unit->ldifs[0] = make_diffuser(unit, f_round(diffscale * b), 0.75); unit->ldifs[1] = make_diffuser(unit, f_round(diffscale * cc), 0.75); unit->ldifs[2] = make_diffuser(unit, f_round(diffscale * dd), 0.625); unit->ldifs[3] = make_diffuser(unit, f_round(diffscale * e), 0.625); ClearUnitIfMemFailed(unit->ldifs[0] && unit->ldifs[1] && unit->ldifs[2] && unit->ldifs[3]); b = 210; r = -0.568366; a = (int)(spread1 * r); c = 210 + 159 + a; cc = c - b; r = -0.126815; a = (int)(spread2 * r); d = 210 + 159 + 562 + a; dd = d - c; e = 1341 - d; unit->rdifs[0] = make_diffuser(unit, f_round(diffscale * b), 0.75); unit->rdifs[1] = make_diffuser(unit, f_round(diffscale * cc), 0.75); unit->rdifs[2] = make_diffuser(unit, f_round(diffscale * dd), 0.625); unit->rdifs[3] = make_diffuser(unit, f_round(diffscale * e), 0.625); ClearUnitIfMemFailed(unit->rdifs[0] && unit->rdifs[1] && unit->rdifs[2] && unit->rdifs[3]); unit->taps[0] = 5 + (int)(0.410 * largestdelay); unit->taps[1] = 5 + (int)(0.300 * largestdelay); unit->taps[2] = 5 + (int)(0.155 * largestdelay); unit->taps[3] = 5; //+ f_round(0.000 * largestdelay); for (int i = 0; i < FDNORDER; i++) { unit->tapgains[i] = static_cast<float>(std::pow(alpha, static_cast<double>(unit->taps[i]))); } unit->tapdelay = make_fixeddelay(unit, 44000, 44000); ClearUnitIfMemFailed(unit->tapdelay); // init the slope values unit->earlylevelslope = unit->drylevelslope = unit->taillevelslope = 0.f; ClearUnitOutputs(unit, 1); } void GVerb_Dtor(GVerb* unit) { free_damper(unit, unit->inputdamper); free_fixeddelay(unit, unit->tapdelay); for (int i = 0; i < FDNORDER; i++) { free_fixeddelay(unit, unit->fdndels[i]); free_damper(unit, unit->fdndamps[i]); free_diffuser(unit, unit->ldifs[i]); free_diffuser(unit, unit->rdifs[i]); } } void GVerb_next(GVerb* unit, int inNumSamples) { float* in = IN(0); float* outl = OUT(0); float* outr = OUT(1); float roomsize = IN0(1); float revtime = IN0(2); float damping = IN0(3); float inputbandwidth = IN0(4); // float spread = IN0(5); // spread can only be set at inittime float drylevel = IN0(6); float earlylevel = IN0(7); float taillevel = IN0(8); float earlylevelslope, taillevelslope, drylevelslope; float* fdngainslopes; float* tapgainslopes; g_diffuser** ldifs = unit->ldifs; g_diffuser** rdifs = unit->rdifs; float* u = unit->u; float* f = unit->f; float* d = unit->d; g_damper* inputdamper = unit->inputdamper; float* tapgains = unit->tapgains; g_fixeddelay* tapdelay = unit->tapdelay; int* taps = unit->taps; g_damper** fdndamps = unit->fdndamps; g_fixeddelay** fdndels = unit->fdndels; float* fdngains = unit->fdngains; int* fdnlens = unit->fdnlens; if ((roomsize != unit->roomsize) || (revtime != unit->revtime) || (damping != unit->damping) || (inputbandwidth != unit->inputbandwidth) || (drylevel != unit->drylevel) || (earlylevel != unit->earlylevel) || (taillevel != unit->taillevel)) { // these should calc slopes for k-rate interpolation gverb_set_roomsize(unit, roomsize); gverb_set_revtime(unit, revtime); gverb_set_damping(unit, damping); gverb_set_inputbandwidth(unit, inputbandwidth); drylevel = gverb_set_drylevel(unit, drylevel); earlylevel = gverb_set_earlylevel(unit, earlylevel); taillevel = gverb_set_taillevel(unit, taillevel); } earlylevelslope = unit->earlylevelslope; taillevelslope = unit->taillevelslope; drylevelslope = unit->drylevelslope; fdngainslopes = unit->fdngainslopes; tapgainslopes = unit->tapgainslopes; for (int i = 0; i < inNumSamples; i++) { float sign, sum, lsum, rsum, x; if (sc_isnan(in[i])) x = 0.f; else x = in[i]; sum = 0.f; sign = 1.f; float z = damper_do(unit, inputdamper, x); z = diffuser_do(unit, ldifs[0], z); for (int j = 0; j < FDNORDER; j++) { u[j] = tapgains[j] * fixeddelay_read(unit, tapdelay, taps[j]); } fixeddelay_write(unit, tapdelay, z); for (int j = 0; j < FDNORDER; j++) { d[j] = damper_do(unit, fdndamps[j], fdngains[j] * fixeddelay_read(unit, fdndels[j], fdnlens[j])); } for (int j = 0; j < FDNORDER; j++) { sum += sign * (taillevel * d[j] + earlylevel * u[j]); sign = -sign; } sum += x * earlylevel; lsum = sum; rsum = sum; gverb_fdnmatrix(d, f); for (int j = 0; j < FDNORDER; j++) { fixeddelay_write(unit, fdndels[j], u[j] + f[j]); } lsum = diffuser_do(unit, ldifs[1], lsum); lsum = diffuser_do(unit, ldifs[2], lsum); lsum = diffuser_do(unit, ldifs[3], lsum); rsum = diffuser_do(unit, rdifs[1], rsum); rsum = diffuser_do(unit, rdifs[2], rsum); rsum = diffuser_do(unit, rdifs[3], rsum); x = x * drylevel; outl[i] = lsum + x; outr[i] = rsum + x; drylevel += drylevelslope; taillevel += taillevelslope; earlylevel += earlylevelslope; for (int j = 0; j < FDNORDER; j++) { fdngains[j] += fdngainslopes[j]; tapgains[j] += tapgainslopes[j]; } } // store vals back to the struct for (int i = 0; i < FDNORDER; i++) { unit->ldifs[i] = ldifs[i]; unit->rdifs[i] = rdifs[i]; unit->u[i] = u[i]; unit->f[i] = f[i]; unit->d[i] = d[i]; unit->tapgains[i] = tapgains[i]; unit->taps[i] = taps[i]; unit->fdndamps[i] = fdndamps[i]; unit->fdndels[i] = fdndels[i]; unit->fdngains[i] = fdngains[i]; unit->fdnlens[i] = fdnlens[i]; unit->fdngainslopes[i] = 0.f; unit->tapgainslopes[i] = 0.f; } unit->inputdamper = inputdamper; unit->tapdelay = tapdelay; // clear the slopes unit->earlylevelslope = unit->taillevelslope = unit->drylevelslope = 0.f; } PluginLoad(Reverb) { ft = inTable; DefineSimpleUnit(FreeVerb); DefineSimpleUnit(FreeVerb2); DefineDtorUnit(GVerb); }
42,814
C++
.cpp
1,368
25.21345
119
0.547658
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,974
Onsets.cpp
supercollider_supercollider/server/plugins/Onsets.cpp
/* Onset detector for SuperCollider Copyright (c) 2007 Dan Stowell. All rights reserved. http://onsetsds.sourceforge.net Now part of: SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "SC_PlugIn.h" #include "SCComplex.h" #include "FFT_UGens.h" #include "Onsets.h" ////////////////////////////////////////////////////////////////////////////////////////////////// // for operation on one buffer // almost like PV_GET_BUF except it outputs unit->outval rather than -1 when FFT not triggered #define Onsets_GET_BUF \ float fbufnum = ZIN0(0); \ if (fbufnum < 0.f) { \ ZOUT0(0) = unit->outval; \ return; \ } \ ZOUT0(0) = fbufnum; \ uint32 ibufnum = (uint32)fbufnum; \ World* world = unit->mWorld; \ SndBuf* buf; \ if (ibufnum >= world->mNumSndBufs) { \ int localBufNum = ibufnum - world->mNumSndBufs; \ Graph* parent = unit->mParent; \ if (localBufNum <= parent->localBufNum) { \ buf = parent->mLocalSndBufs + localBufNum; \ } else { \ buf = world->mSndBufs; \ } \ } else { \ buf = world->mSndBufs + ibufnum; \ } \ LOCK_SNDBUF(buf); ////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// void Onsets_Ctor(Onsets* unit) { if (ZIN0(8) > 0) SETCALC(Onsets_next_rawodf); else SETCALC(Onsets_next); unit->m_needsinit = true; unit->m_ods = (OnsetsDS*)RTAlloc(unit->mWorld, sizeof(OnsetsDS)); unit->m_odsdata = nullptr; ClearUnitIfMemFailed(unit->m_ods); ZOUT0(0) = unit->outval = 0.f; } void Onsets_next(Onsets* unit, int inNumSamples) { Onsets_GET_BUF // In practice, making the polar conversion here in SC is more efficient because SC provides a lookup table // method. SCPolarBuf* p = ToPolarApx(buf); OnsetsDS* ods = unit->m_ods; int odftype = (int)ZIN0(2); float relaxtime = ZIN0(3); int medspan = (int)ZIN0(6); if (unit->m_needsinit) { // Init happens here because we need to be sure about FFT size. unit->m_odsdata = (float*)RTAlloc(unit->mWorld, onsetsds_memneeded(odftype, buf->samples, medspan)); ClearUnitIfMemFailed(unit->m_odsdata); onsetsds_init(ods, unit->m_odsdata, ODS_FFT_SC3_POLAR, odftype, buf->samples, medspan, FULLRATE); onsetsds_setrelax(ods, relaxtime, buf->samples >> 1); unit->m_needsinit = false; } // Here is the best place to set parameters - after init is ensured // These are "painless" to set: ods->thresh = ZIN0(1); ods->floor = ZIN0(4); ods->mingap = (int)ZIN0(5); ods->whtype = (int)ZIN0(7); // Now to process unit->outval = onsetsds_process(ods, (float*)p); ZOUT0(0) = unit->outval; } void Onsets_next_rawodf(Onsets* unit, int inNumSamples) { Onsets_GET_BUF // In practice, making the polar conversion here in SC is more efficient because SC provides a lookup table // method. SCPolarBuf* p = ToPolarApx(buf); OnsetsDS* ods = unit->m_ods; int odftype = (int)ZIN0(2); float relaxtime = ZIN0(3); int medspan = (int)ZIN0(6); if (unit->m_needsinit) { // Init happens here because we need to be sure about FFT size. unit->m_odsdata = (float*)RTAlloc(unit->mWorld, onsetsds_memneeded(odftype, buf->samples, medspan)); ClearUnitIfMemFailed(unit->m_odsdata); onsetsds_init(ods, unit->m_odsdata, ODS_FFT_SC3_POLAR, odftype, buf->samples, medspan, FULLRATE); onsetsds_setrelax(ods, relaxtime, buf->samples >> 1); unit->m_needsinit = false; } // Here is the best place to set parameters - after init is ensured // These are "painless" to set: ods->thresh = ZIN0(1); ods->floor = ZIN0(4); ods->mingap = (int)ZIN0(5); ods->whtype = (int)ZIN0(7); // Now to process onsetsds_process(ods, (float*)p); // But we want the ODF, not the triggers, for this special mode... // unit->outval = ods->odfvalpost; unit->outval = ods->odfvals[0]; ZOUT0(0) = unit->outval; } void Onsets_Dtor(Onsets* unit) { if (!unit->m_needsinit) { RTFree(unit->mWorld, unit->m_odsdata); } RTFree(unit->mWorld, unit->m_ods); }
7,109
C++
.cpp
125
51.16
120
0.448683
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,975
BelaUGens.cpp
supercollider_supercollider/server/plugins/BelaUGens.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* * BELA I/O UGens created by nescivi, (c) 2016 * https://www.nescivi.eu */ #include "Bela.h" #include "cobalt/stdio.h" #include "SC_PlugIn.h" class AccessBuffer { protected: AccessBuffer(float* buffer, unsigned int count): m_buffer(buffer), m_count(count), m_last(buffer[count - 1]) {} const float& at(unsigned int n) const { if (n < m_count) return m_buffer[n]; else return m_last; } float& at(unsigned int n) { if (n < m_count) return m_buffer[n]; else return m_last; } void updateBufferWithLast() { m_buffer[m_count - 1] = m_last; } unsigned int count() const { return m_count; } private: float* m_buffer; float m_last; const unsigned int m_count; }; // Two buffer views which on which you can call [] for arbitrarily large numbers, but // if it exceeds count, you will get back the value it had at [count-1] at // initialisation. // Additionally, upon destruction of an AccessBufferWriter object, the // [count-1] element wil be replaced with the cached value, which may have been // overwritten when assigning the returned value. This is done heuristically. // These classes are useful when dealing with Sc buffers transparently without // worrying whether they are at audio or control rate. // It is also safe against overlapping buffers, as long as: // - only one object writes to the buffer // - you write to elements incrementally (starting from 0) // - no one tries to access the buffer if not with one of the Writer or Reader // objects, as long as they are alive // - for each element, you write after reading (note: the way this provides safety is // that you can keep calling [n] with n >= count and you will still access the // valid cached value and not whathever the writer may have written to it // since) class AccessBufferWriter : public AccessBuffer { public: AccessBufferWriter(float* buffer, unsigned int count): AccessBuffer(buffer, count), m_lastTouched(false) {}; ~AccessBufferWriter() { // calling [], you may have been passed a reference to last instead of // a pointer into the buffer itself. Here, we ensure we put it back into the buffer if (m_lastTouched) updateBufferWithLast(); } float& operator[](unsigned int n) { if (n >= count()) m_lastTouched = true; return at(n); } private: bool m_lastTouched; }; class AccessBufferReader : public AccessBuffer { public: AccessBufferReader(float* buffer, unsigned int count): AccessBuffer(buffer, count) {}; const float& operator[](unsigned int n) const { return at(n); } }; static InterfaceTable* ft; static inline void belaUGenInitOutput(Unit* unit) { (unit->mCalcFunc)(unit, 1); } static inline void belaUGenDisable(Unit* unit) { SETCALC(ClearUnitOutputs); belaUGenInitOutput(unit); } struct MultiplexAnalogIn : public Unit {}; struct AnalogIn : public Unit { int mAnalogPin; }; struct AnalogOut : public Unit { int mAnalogPin; }; // static digital pin, static function (in) struct DigitalIn : public Unit { int mDigitalPin; }; // static digital pin, static function (out) - uses DigitalWrite and a check whether value changed struct DigitalOut : public Unit { int mDigitalPin; int mLastOut; }; // flexible digital pin, flexible function (in or out) struct DigitalIO : public Unit { int mDigitalPin; int mLastDigitalIn; int mLastDigitalOut; }; ////////////////////////////////////////////////////////////////////////////////////////////////// void MultiplexAnalogIn_next_aaa(MultiplexAnalogIn* unit, int inNumSamples) { auto* context = unit->mWorld->mBelaContext; float* fin = IN(0); // analog in pin, can be modulated float* fmux = IN(1); // mux channel, can be modulated float* out = OUT(0); float analogValue = 0; // context->audioFrames should be equal to inNumSamples for (unsigned int n = 0; n < inNumSamples; n++) { int analogPin = static_cast<int>(fin[n]); int muxChannel = static_cast<int>(fmux[n]); if ((analogPin < 0) || (analogPin >= context->analogInChannels) || (muxChannel < 0) || (muxChannel >= context->multiplexerChannels)) { rt_fprintf(stderr, "MultiplexAnalogIn warning: analog pin must be between %i and %i, it is %i\n", 0, context->analogInChannels, analogPin); rt_fprintf(stderr, "MultiplexAnalogIn warning: muxChannel must be between %i and %i, it is %i\n", 0, context->multiplexerChannels, muxChannel); } else { // is there something like NI? analogReadNI(context, 0, analogPin); analogValue = multiplexerAnalogRead(context, analogPin, muxChannel); } out[n] = analogValue; } } void MultiplexAnalogIn_next_aak(MultiplexAnalogIn* unit, int inNumSamples) { auto* context = unit->mWorld->mBelaContext; float* fin = IN(0); // analog in pin, can be modulated float* out = OUT(0); float analogValue = 0; int muxChannel = static_cast<int>(IN0(1)); // context->audioFrames should be equal to inNumSamples for (unsigned int n = 0; n < inNumSamples; n++) { int analogPin = static_cast<int>(fin[n]); if ((analogPin < 0) || (analogPin >= context->analogInChannels) || (muxChannel < 0) || (muxChannel >= context->multiplexerChannels)) { rt_fprintf(stderr, "MultiplexAnalogIn warning: analog pin must be between %i and %i, it is %i\n", 0, context->analogInChannels, analogPin); rt_fprintf(stderr, "MultiplexAnalogIn warning: muxChannel must be between %i and %i, it is %i\n", 0, context->multiplexerChannels, muxChannel); } else { // is there something like NI? analogReadNI(context, 0, analogPin); analogValue = multiplexerAnalogRead(context, analogPin, muxChannel); } out[n] = analogValue; } } void MultiplexAnalogIn_next_aka(MultiplexAnalogIn* unit, int inNumSamples) { auto* context = unit->mWorld->mBelaContext; float* fmux = IN(1); // mux channel, can be modulated float* out = OUT(0); int analogPin = static_cast<int>(IN0(0)); float analogValue = 0; // context->audioFrames should be equal to inNumSamples for (unsigned int n = 0; n < inNumSamples; n++) { int muxChannel = static_cast<int>(fmux[n]); if ((analogPin < 0) || (analogPin >= context->analogInChannels) || (muxChannel < 0) || (muxChannel >= context->multiplexerChannels)) { rt_fprintf(stderr, "MultiplexAnalogIn warning: analog pin must be between %i and %i, it is %i\n", 0, context->analogInChannels, analogPin); rt_fprintf(stderr, "MultiplexAnalogIn warning: muxChannel must be between %i and %i, it is %i\n", 0, context->multiplexerChannels, muxChannel); } else { // is there something like NI? analogReadNI(context, 0, analogPin); analogValue = multiplexerAnalogRead(context, analogPin, muxChannel); } out[n] = analogValue; } } void MultiplexAnalogIn_next_akk(MultiplexAnalogIn* unit, int inNumSamples) { auto* context = unit->mWorld->mBelaContext; int analogPin = static_cast<float>(IN0(0)); int muxChannel = static_cast<float>(IN0(1)); float* out = OUT(0); if ((analogPin < 0) || (analogPin >= context->analogInChannels) || (muxChannel < 0) || (muxChannel >= context->multiplexerChannels)) { rt_fprintf(stderr, "MultiplexAnalogIn warning: analog pin must be between %i and %i, it is %i\n", 0, context->analogInChannels, analogPin); rt_fprintf(stderr, "MultiplexAnalogIn warning: muxChannel must be between %i and %i, it is %i\n", 0, context->multiplexerChannels, muxChannel); for (unsigned int n = 0; n < inNumSamples; n++) { out[n] = 0; } } else { for (unsigned int n = 0; n < inNumSamples; n++) { // is there something like NI? analogReadNI(context, 0, analogPin); out[n] = multiplexerAnalogRead(context, analogPin, muxChannel); } } } void MultiplexAnalogIn_next_kkk(MultiplexAnalogIn* unit, int inNumSamples) { auto* context = unit->mWorld->mBelaContext; int analogPin = static_cast<float>(IN0(0)); int muxChannel = static_cast<float>(IN0(1)); if ((analogPin < 0) || (analogPin >= context->analogInChannels)) { rt_fprintf(stderr, "MultiplexAnalogIn warning: analog pin must be between %i and %i, it is %i\n", 0, context->analogInChannels, analogPin); OUT0(0) = 0.0; } else if ((muxChannel < 0) || (muxChannel >= context->multiplexerChannels)) { rt_fprintf(stderr, "MultiplexAnalogIn warning: muxChannel must be between %i and %i, it is %i\n", 0, context->multiplexerChannels, muxChannel); OUT0(0) = 0.0; } else { OUT0(0) = multiplexerAnalogRead(context, analogPin, muxChannel); } } void MultiplexAnalogIn_Ctor(MultiplexAnalogIn* unit) { BelaContext* context = unit->mWorld->mBelaContext; if (!context->multiplexerChannels) { belaUGenDisable(unit); rt_fprintf(stderr, "MultiplexAnalogIn Error: the UGen needs BELA Multiplexer Capelet enabled\n"); return; } // set calculation method if (unit->mCalcRate == calc_FullRate) { if (INRATE(0) == calc_FullRate) { if (INRATE(1) == calc_FullRate) { SETCALC(MultiplexAnalogIn_next_aaa); } else { SETCALC(MultiplexAnalogIn_next_aak); } } else { if (INRATE(1) == calc_FullRate) { SETCALC(MultiplexAnalogIn_next_aka); } else { SETCALC(MultiplexAnalogIn_next_akk); } } } else { if ((INRATE(0) == calc_FullRate) || (INRATE(1) == calc_FullRate)) { rt_fprintf(stderr, "MultiplexAnalogIn warning: output rate is control rate, so cannot change analog pin or " "multiplex channel at audio rate\n"); } SETCALC(MultiplexAnalogIn_next_kkk); } belaUGenInitOutput(unit); } ////////////////////////////////////////////////////////////////////////////////////////////////// static bool updatePin(unsigned int numChannels, unsigned int newPin, int* oldPin, const char* label) { bool isValid = newPin < numChannels; if (newPin != *oldPin) { *oldPin = newPin; if (!isValid) { rt_fprintf(stderr, "%s warning: pin must be 0 <= pin <= %i, it is %i\n", label, numChannels - 1, newPin); } } return isValid; } // returns false if pin is out of range, so that _next functions should avoid using it bool AnalogIn_updatePin(AnalogIn* unit, int newPin) { BelaContext* context = unit->mWorld->mBelaContext; return updatePin(context->analogInChannels, newPin, &unit->mAnalogPin, "AnalogIn"); } void AnalogIn_next_aa(AnalogIn* unit, int inNumSamples) { auto* context = unit->mWorld->mBelaContext; float* fin = IN(0); // analog in pin, can be modulated float* out = OUT(0); float analogValue = 0; for (unsigned int n = 0; n < inNumSamples; n++) { int analogPin = static_cast<int>(fin[n]); if (AnalogIn_updatePin(unit, analogPin)) { analogValue = analogReadNI(context, n, analogPin); } out[n] = analogValue; } } void AnalogIn_next_ak(AnalogIn* unit, int inNumSamples) { auto* context = unit->mWorld->mBelaContext; int analogPin = static_cast<int>(IN0(0)); float* out = OUT(0); if (AnalogIn_updatePin(unit, analogPin)) { for (unsigned int n = 0; n < inNumSamples; n++) { out[n] = analogReadNI(context, n, analogPin); } } else { for (unsigned int n = 0; n < inNumSamples; n++) { out[n] = 0; } } } void AnalogIn_next_kk(AnalogIn* unit, int inNumSamples) { auto* context = unit->mWorld->mBelaContext; int analogPin = static_cast<int>(IN0(0)); if (AnalogIn_updatePin(unit, analogPin)) { OUT0(0) = analogReadNI(context, 0, analogPin); } else { OUT0(0) = 0.0; } } void AnalogIn_Ctor(AnalogIn* unit) { BelaContext* context = unit->mWorld->mBelaContext; if (!context->analogInChannels) { belaUGenDisable(unit); rt_fprintf(stderr, "AnalogIn Error: the UGen needs BELA analog inputs enabled\n"); return; } unit->mAnalogPin = -1; // set calculation method if (unit->mCalcRate == calc_FullRate) { if (INRATE(0) == calc_FullRate) { SETCALC(AnalogIn_next_aa); } else { SETCALC(AnalogIn_next_ak); } } else { if (INRATE(0) == calc_FullRate) { rt_fprintf(stderr, "AnalogIn warning: output rate is control rate, so cannot change analog pin at audio rate\n"); } SETCALC(AnalogIn_next_kk); } belaUGenInitOutput(unit); } ////////////////////////////////////////////////////////////////////////////////////////////////// // returns false if pin is out of range, so that _next functions should avoid using it bool AnalogOut_updatePin(AnalogOut* unit, int newPin) { BelaContext* context = unit->mWorld->mBelaContext; return updatePin(context->analogOutChannels, newPin, &unit->mAnalogPin, "AnalogOut"); } void AnalogOut_next_aaa(AnalogOut* unit, int inNumSamples) { auto* context = unit->mWorld->mBelaContext; float* fin = IN(0); // analog in pin, can be modulated float* in = IN(1); for (unsigned int n = 0; n < inNumSamples; n++) { // read input int analogPin = static_cast<int>(fin[n]); if (AnalogOut_updatePin(unit, analogPin)) { analogWriteOnceNI(context, n, unit->mAnalogPin, in[n]); } } } void AnalogOut_next_aka(AnalogOut* unit, int inNumSamples) { auto* context = unit->mWorld->mBelaContext; int analogPin = static_cast<int>(IN0(0)); // analog in pin, can be modulated float* in = IN(1); if (AnalogOut_updatePin(unit, analogPin)) { for (unsigned int n = 0; n < inNumSamples; n++) { analogWriteOnceNI(context, n, unit->mAnalogPin, in[n]); } } } void AnalogOut_next_aak(AnalogOut* unit, int inNumSamples) { auto* context = unit->mWorld->mBelaContext; float* fin = IN(0); // analog in pin, can be modulated float in = IN0(1); for (unsigned int n = 0; n < inNumSamples; n++) { // read input int analogPin = static_cast<int>(fin[n]); if (AnalogOut_updatePin(unit, analogPin)) { analogWriteOnceNI(context, n, unit->mAnalogPin, in); } } } void AnalogOut_next_kk(AnalogOut* unit, int inNumSamples) { auto* context = unit->mWorld->mBelaContext; int analogPin = static_cast<int>(IN0(0)); // analog in pin, can be modulated float in = IN0(1); if (AnalogOut_updatePin(unit, analogPin)) { analogWriteNI(context, 0, unit->mAnalogPin, in); } } void AnalogOut_Ctor(AnalogOut* unit) { BelaContext* context = unit->mWorld->mBelaContext; if (!context->analogOutChannels) { belaUGenDisable(unit); rt_fprintf(stderr, "AnalogOut Error: the UGen needs BELA analog outputs enabled\n"); return; } unit->mAnalogPin = -1; if (unit->mCalcRate == calc_FullRate) { // ugen running at audio rate; if (INRATE(0) == calc_FullRate) { // pin changed at audio rate if (INRATE(1) == calc_FullRate) { // output changed at audio rate SETCALC(AnalogOut_next_aaa); } else { SETCALC(AnalogOut_next_aak); } } else { // pin changed at control rate if (INRATE(1) == calc_FullRate) { // output changed at audio rate SETCALC(AnalogOut_next_aka); } else { // analog output only changes at control rate anyways rt_fprintf( stderr, "AnalogOut warning: inputs are control rate, so AnalogOut is also running at control rate\n"); SETCALC(AnalogOut_next_kk); } } } else { // ugen at control rate if ((INRATE(0) == calc_FullRate) || (INRATE(1) == calc_FullRate)) { rt_fprintf(stderr, "AnalogOut warning: output rate is control rate, so cannot change inputs at audio rate\n"); } SETCALC(AnalogOut_next_kk); } belaUGenInitOutput(unit); } ////////////////////////////////////////////////////////////////////////////////////////////////// void DigitalIn_next_a(DigitalIn* unit, int inNumSamples) { auto* context = unit->mWorld->mBelaContext; int pinid = unit->mDigitalPin; float* out = OUT(0); for (unsigned int n = 0; n < inNumSamples; n++) { out[n] = static_cast<float>(digitalRead(context, n, pinid)); } } void DigitalIn_next_k(DigitalIn* unit, int inNumSamples) { auto* context = unit->mWorld->mBelaContext; int pinid = unit->mDigitalPin; OUT0(0) = static_cast<float>(digitalRead(context, 0, pinid)); } void DigitalIn_Ctor(DigitalIn* unit) { BelaContext* context = unit->mWorld->mBelaContext; unit->mDigitalPin = static_cast<int>(IN0(0)); // digital in pin -- cannot change after construction if ((unit->mDigitalPin < 0) || (unit->mDigitalPin >= context->digitalChannels)) { rt_fprintf(stderr, "DigitalIn error: digital pin must be between %i and %i, it is %i\n", 0, context->digitalChannels, unit->mDigitalPin); belaUGenDisable(unit); return; } pinMode(context, 0, unit->mDigitalPin, INPUT); // set calculation method if (unit->mCalcRate == calc_FullRate) { // ugen running at audio rate; SETCALC(DigitalIn_next_a); } else { SETCALC(DigitalIn_next_k); } belaUGenInitOutput(unit); } ////////////////////////////////////////////////////////////////////////////////////////////////// void DigitalOut_next_a(DigitalOut* unit, int inNumSamples) { auto* context = unit->mWorld->mBelaContext; int pinid = unit->mDigitalPin; float* in = IN(1); int lastOut = unit->mLastOut; for (unsigned int n = 0; n < inNumSamples; n++) { // read input float newinput = in[n]; if (newinput > 0.5) { if (lastOut == 0) { lastOut = 1; digitalWrite(context, n, pinid, 1); } } else if (lastOut == 1) { lastOut = 0; digitalWrite(context, n, pinid, 0); } } unit->mLastOut = lastOut; } void DigitalOut_next_k(DigitalOut* unit, int inNumSamples) { auto* context = unit->mWorld->mBelaContext; int pinid = unit->mDigitalPin; float in = IN0(1); int lastOut = unit->mLastOut; if (in > 0.5) { if (lastOut == 0) { lastOut = 1; digitalWrite(context, 0, pinid, 1); } } else if (lastOut == 1) { lastOut = 0; digitalWrite(context, 0, pinid, 0); } unit->mLastOut = lastOut; } void DigitalOut_Ctor(DigitalOut* unit) { BelaContext* context = unit->mWorld->mBelaContext; unit->mDigitalPin = static_cast<int>(IN0(0)); // digital in pin -- cannot change after construction unit->mLastOut = 0; if ((unit->mDigitalPin < 0) || (unit->mDigitalPin >= context->digitalChannels)) { rt_fprintf(stderr, "DigitalOut error: digital pin must be between %i and %i, it is %i\n", 0, context->digitalChannels, unit->mDigitalPin); belaUGenDisable(unit); } // initialize first buffer pinMode(context, 0, unit->mDigitalPin, OUTPUT); digitalWrite(context, 0, unit->mDigitalPin, unit->mLastOut); if (unit->mCalcRate == calc_FullRate) { // ugen running at audio rate; if (INRATE(1) == calc_FullRate) { // output changed at audio rate SETCALC(DigitalOut_next_a); } else { // not much reason to actually do audiorate output rt_fprintf(stderr, "DigitalOut warning: inputs are control rate, so DigitalOut will run at control rate\n"); SETCALC(DigitalOut_next_k); } } else { // ugen at control rate if (INRATE(1) == calc_FullRate) { rt_fprintf(stderr, "DigitalOut warning: UGen rate is control rate, so cannot change inputs at audio rate\n"); } SETCALC(DigitalOut_next_k); } belaUGenInitOutput(unit); } ////////////////////////////////////////////////////////////////////////////////////////////////// // returns false if pin is out of range, so that _next functions should avoid using it bool DigitalIO_updatePin(DigitalIO* unit, int newPin) { BelaContext* context = unit->mWorld->mBelaContext; return updatePin(context->digitalChannels, newPin, &unit->mDigitalPin, "DigitalIO"); } static int parseDigitalValue(float value) { return value > 0.5; } static int parseDigitalMode(float mode) { return mode < 0.5 ? INPUT : OUTPUT; } void DigitalIO_next_universal(DigitalIO* unit, int inNumSamples) { auto* context = unit->mWorld->mBelaContext; const bool ugenAudioRate = (calc_FullRate == unit->mCalcRate); const bool pinAudioRate = (calc_FullRate == INRATE(0)); const bool inputAudioRate = (calc_FullRate == INRATE(1)); const bool modeAudioRate = (calc_FullRate == INRATE(2)); unsigned int outsCount = ugenAudioRate ? inNumSamples : 1; unsigned int pinsCount = pinAudioRate ? inNumSamples : 1; unsigned int insCount = inputAudioRate ? inNumSamples : 1; unsigned int modesCount = modeAudioRate ? inNumSamples : 1; AccessBufferWriter outs(OUT(0), outsCount); // may be the same as pins const AccessBufferReader pins(IN(0), pinsCount); const AccessBufferReader ins(IN(1), insCount); const AccessBufferReader modes(IN(2), modesCount); bool lastDigIn = unit->mLastDigitalIn; // with properly initialised AccessBuffers, we can use [n] below regardless // of the K/A rate of each buffer for (unsigned int n = 0; n < inNumSamples; ++n) { unsigned int pin = static_cast<int>(pins[n]); if (DigitalIO_updatePin(unit, pin)) { int mode = parseDigitalMode(modes[n]); if (1 == inNumSamples) { // we are only ever going to go up to 1 (i.e.: processed at // control rate). So fill up the rest of the buffer. pinMode(context, 0, unit->mDigitalPin, mode); } else { pinModeOnce(context, n, unit->mDigitalPin, mode); } if (INPUT == mode) { lastDigIn = digitalRead(context, n, unit->mDigitalPin); } else { bool digOut = parseDigitalValue(ins[n]); if (1 == inNumSamples) { // we are only ever going to go up to 1 (i.e.: processed at // control rate). So fill up the rest of the buffer. digitalWrite(context, 0, unit->mDigitalPin, digOut); } else { digitalWriteOnce(context, n, unit->mDigitalPin, digOut); } } } outs[n] = lastDigIn; } unit->mLastDigitalIn = lastDigIn; } void DigitalIO_Ctor(DigitalIO* unit) { BelaContext* context = unit->mWorld->mBelaContext; unit->mDigitalPin = 0; unit->mLastDigitalIn = 0; unit->mLastDigitalOut = 0; SETCALC(DigitalIO_next_universal); belaUGenInitOutput(unit); } ////////////////////////////////////////////////////////////////////////////////////////////////// struct BelaScopeOut : public Unit { unsigned int numScopeChannels; unsigned int offset; }; void BelaScopeOut_next(BelaScopeOut* unit, unsigned int numSamples) { float* scopeBuffer = unit->mWorld->mBelaScope->buffer; if (!scopeBuffer) return; unsigned int numChannels = unit->numScopeChannels; unsigned int maxChannels = unit->mWorld->mBelaMaxScopeChannels; unsigned int scopeBufferSamples = unit->mWorld->mBelaScope->bufferSamples; float* inputPointers[numChannels]; // input 0: channelOffset // inputs 1 to numInputs-1 : signal inputs for (unsigned int ch = 0; ch < numChannels; ++ch) inputPointers[ch] = IN(ch + 1); // skip IN(0) for (unsigned int frame = unit->offset; frame < scopeBufferSamples; frame += maxChannels) for (unsigned int ch = 0; ch < numChannels; ++ch) scopeBuffer[frame + ch] += *inputPointers[ch]++; unit->mWorld->mBelaScope->touched = true; } void BelaScopeOut_Ctor(BelaScopeOut* unit) { BelaScope* scope = unit->mWorld->mBelaScope; if (!scope || !scope->buffer) { rt_fprintf(stderr, "BelaScopeOut error: Scope not initialized on server\n"); belaUGenDisable(unit); return; }; int offset = static_cast<int>(IN0(0)); unit->offset = static_cast<unsigned int>(offset < 0 ? 0 : offset); uint32 maxScopeChannels = unit->mWorld->mBelaMaxScopeChannels; uint32 numInputSignals = unit->mNumInputs - 1; if (numInputSignals > maxScopeChannels - unit->offset) { rt_fprintf( stderr, "BelaScopeOut warning: can't scope %i channels starting from %i, maxBelaScopeChannels is set to %i\n", numInputSignals, offset, maxScopeChannels); } unit->numScopeChannels = sc_min(numInputSignals, maxScopeChannels - unit->offset); if (unit->numScopeChannels <= 0) { belaUGenDisable(unit); } else { BelaScopeOut_next(unit, 1); SETCALC(BelaScopeOut_next); } } ////////////////////////////////////////////////////////////////////////////////////////////////// PluginLoad(BELA) { ft = inTable; DefineSimpleUnit(MultiplexAnalogIn); DefineSimpleUnit(AnalogIn); DefineSimpleUnit(AnalogOut); DefineSimpleUnit(DigitalIn); DefineSimpleUnit(DigitalOut); DefineSimpleUnit(DigitalIO); DefineSimpleUnit(BelaScopeOut); }
27,087
C++
.cpp
623
36.418941
120
0.623582
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,976
scsynth_test.cpp
supercollider_supercollider/testsuite/server/scsynth/scsynth_test.cpp
#include "scsynth_test.hpp" BOOST_AUTO_TEST_CASE(create_and_destroy_world) { WorldOptions options; options.mRealTime = false; World* world = World_New(&options); World_Cleanup(world, true); }
209
C++
.cpp
7
26.428571
48
0.721393
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,977
audio_frontend_test.cpp
supercollider_supercollider/testsuite/server/supernova/audio_frontend_test.cpp
#include <boost/test/unit_test.hpp> #include <boost/thread.hpp> #define protected public #include "audio_backend/audio_backend.hpp" #include "audio_backend/portaudio.hpp" #include "audio_backend/audio_frontend.hpp" using namespace nova; namespace { void tick(void) {} } BOOST_AUTO_TEST_CASE(frontend_test_1) { audio_frontend<&tick> af; BOOST_REQUIRE(!af.audio_is_opened()); BOOST_REQUIRE(af.audio_is_ready()); BOOST_REQUIRE(af.audio_is_active()); BOOST_REQUIRE(!af.audio_is_opened()); } BOOST_AUTO_TEST_CASE(frontend_test_2) { audio_frontend<&tick> af; BOOST_REQUIRE(!af.audio_is_opened()); BOOST_REQUIRE(af.audio_is_ready()); BOOST_REQUIRE(af.audio_is_active()); af.open_portaudio_backend(); BOOST_REQUIRE(!af.audio_is_ready()); BOOST_REQUIRE(!af.audio_is_active()); device_list devs = af.list_devices(); af.open_audio_stream(devs[0], devs[0].inchannels, devs[0], devs[0].outchannels, devs[0].defaultSampleRate); BOOST_REQUIRE(af.audio_is_ready()); BOOST_REQUIRE(!af.audio_is_active()); af.activate_audio(); BOOST_REQUIRE(af.audio_is_ready()); BOOST_REQUIRE(af.audio_is_active()); boost::xtime xt; boost::xtime_get(&xt, boost::TIME_UTC); xt.sec += 1; boost::thread::sleep(xt); af.deactivate_audio(); BOOST_REQUIRE(af.audio_is_ready()); BOOST_REQUIRE(!af.audio_is_active()); af.close_audio_stream(); BOOST_REQUIRE(!af.audio_is_ready()); BOOST_REQUIRE(!af.audio_is_active()); af.close_audio_backend(); BOOST_REQUIRE(af.audio_is_ready()); BOOST_REQUIRE(af.audio_is_active()); BOOST_REQUIRE(!af.audio_is_opened()); }
1,669
C++
.cpp
47
31.212766
111
0.687305
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,978
sc_plugin_loader_test.cpp
supercollider_supercollider/testsuite/server/supernova/sc_plugin_loader_test.cpp
#include <boost/test/unit_test.hpp> #include <iostream> #include <filesystem> #include "sc/sc_ugen_factory.hpp" #include "server/memory_pool.hpp" #include "server/server_args.hpp" using namespace nova; using namespace std; std::filesystem::path base_path("/home/tim/workspace/nova-server/debug_plugins/"); BOOST_AUTO_TEST_CASE(ugen_factory_test_1) { server_arguments::initialize(0, 0); rt_pool.init(1024 * 1024); sc_factory.initialize(); sc_factory.load_plugin(base_path / "BinaryOpUGens.so"); sc_factory.load_plugin(base_path / "ChaosUGens.so"); sc_factory.load_plugin(base_path / "DelayUGens.so"); sc_factory.load_plugin(base_path / "DemandUGens.so"); sc_factory.load_plugin(base_path / "DiskIO_UGens.so"); sc_factory.load_plugin(base_path / "DynNoiseUGens.so"); sc_factory.load_plugin(base_path / "FFT_UGens.so"); sc_factory.load_plugin(base_path / "FilterUGens.so"); sc_factory.load_plugin(base_path / "GendynUGens.so"); sc_factory.load_plugin(base_path / "GrainUGens.so"); sc_factory.load_plugin(base_path / "IOUGens.so"); sc_factory.load_plugin(base_path / "KeyboardUGens.so"); sc_factory.load_plugin(base_path / "LFUGens.so"); sc_factory.load_plugin(base_path / "ML_UGens.so"); sc_factory.load_plugin(base_path / "MouseUGens.so"); sc_factory.load_plugin(base_path / "MulAddUGens.so"); sc_factory.load_plugin(base_path / "NoiseUGens.so"); sc_factory.load_plugin(base_path / "OscUGens.so"); sc_factory.load_plugin(base_path / "PanUGens.so"); sc_factory.load_plugin(base_path / "PhysicalModelingUGens.so"); sc_factory.load_plugin(base_path / "PV_ThirdParty.so"); sc_factory.load_plugin(base_path / "ReverbUGens.so"); sc_factory.load_plugin(base_path / "TestUGens.so"); sc_factory.load_plugin(base_path / "TriggerUGens.so"); sc_factory.load_plugin(base_path / "UnaryOpUGens.so"); sc_factory.load_plugin(base_path / "UnpackFFTUGens.so"); rt_pool.init(1024 * 1024 * 16, true); } const char* test_synthdefs[] = { "default.scsyndef", "help-In.scsyndef", "help_out.scsyndef", "help_out2.scsyndef", "help_InFeedback.scsyndef", "help_LocalIn.scsyndef", "help_PlayBuf.scsyndef", "help_RecordBuf.scsyndef", "help_RecordBuf_overdub.scsyndef", "help_LocalBuf.scsyndef", "help_Demand.scsyndef", }; #if 0 /* doesn't work anymore because of increased sanity checks */ BOOST_AUTO_TEST_CASE( ugen_construct_test_1 ) { for (int i = 0; i != sizeof(test_synthdefs)/sizeof(const char*); ++i) { const char * synthdef = test_synthdefs[i]; try { std::vector<nova::sc_synthdef> defs = nova::read_synthdef_file(base_path / ".." / "testsuite" / synthdef); sc_synth_prototype_ptr prtype(new sc_synth_prototype(defs[0])); sc_synth * s = new sc_synth(1000, prtype); dsp_context context(44100, 64, 0); for (int i = 0; i != 1000; ++i) s->run(context); delete s; } catch(std::runtime_error const & e) { std::cerr << e.what() << std::endl; } } } #endif
3,166
C++
.cpp
69
40.202899
92
0.660934
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,979
buffer_manager_test.cpp
supercollider_supercollider/testsuite/server/supernova/buffer_manager_test.cpp
#include <iostream> #include <boost/test/unit_test.hpp> #include "server/buffer_manager.cpp" using namespace nova; BOOST_AUTO_TEST_CASE(buffer_manager_test) { buffer_manager bm(1024); bm.allocate_buffer(0, 44100, 2); bm.zero_buffer(0); bm.fill_samples(0, 0, 882000, 0.2); bm.free_buffer(0); }
318
C++
.cpp
11
25.636364
43
0.708609
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,980
static_allocator_test.cpp
supercollider_supercollider/testsuite/server/supernova/static_allocator_test.cpp
#include <boost/test/unit_test.hpp> #include <list> #include <vector> #include <set> #include <iostream> #include "utilities/static_allocator.hpp" using namespace nova; using namespace std; namespace { template <int size, bool b> void test_pool_instatiation(void) { static_allocator<int, size, b> alloc; } struct initialized_struct { initialized_struct(int i): i(i), f(0.2) {} bool operator<(initialized_struct const& rhs) const { return i < rhs.i; } int i; double f; }; template <typename T, bool b> void test_list(void) { list<T, static_allocator<T, 8192, b>> vec; for (int i = 0; i != 8192; ++i) vec.push_back(T(i)); } template <typename T, bool b> void test_vector(void) { vector<T, static_allocator<T, 8192, b>> vec; for (int i = 0; i != 8192; ++i) vec.push_back(T(i)); } template <typename T, bool b> void test_set(void) { set<T, std::less<T>, static_allocator<T, 8192, b>> set; for (int i = 0; i != 8192; ++i) set.insert(T(i)); } } BOOST_AUTO_TEST_CASE(static_alloc_test_1) { test_pool_instatiation<16, false>(); test_pool_instatiation<128, false>(); test_pool_instatiation<1024, false>(); test_pool_instatiation<4096, false>(); test_pool_instatiation<16, true>(); test_pool_instatiation<128, true>(); test_pool_instatiation<1024, true>(); test_pool_instatiation<4096, true>(); } #if 0 BOOST_AUTO_TEST_CASE( static_alloc_test_2 ) { test_list<int, false>(); test_list<initialized_struct, false>(); test_list<int, true>(); test_list<initialized_struct, true>(); } #endif BOOST_AUTO_TEST_CASE(static_alloc_test_3) { test_vector<int, false>(); test_vector<initialized_struct, false>(); test_vector<int, true>(); test_vector<initialized_struct, true>(); } #if 0 BOOST_AUTO_TEST_CASE( static_alloc_test_4 ) { test_set<int, false>(); test_set<initialized_struct, false>(); test_set<int, true>(); test_set<initialized_struct, true>(); } #endif
2,011
C++
.cpp
66
26.924242
103
0.664758
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,981
simple_pool_test.cpp
supercollider_supercollider/testsuite/server/supernova/simple_pool_test.cpp
#include <boost/test/unit_test.hpp> #include <string> #include "utilities/simple_pool.hpp" using namespace nova; using namespace std; namespace { struct foo { foo(void) {} int data[4]; }; void run_simple_test(bool locked) { simple_pool<> pool(16 * 1024, locked); foo* f1 = static_cast<foo*>(pool.malloc(sizeof(foo))); ::new (f1) foo(); f1->~foo(); pool.free(f1); } void run_simple_test_2(bool locked) { simple_pool<> pool; pool.init(16 * 1024, locked); foo* f1 = static_cast<foo*>(pool.malloc(sizeof(foo))); ::new (f1) foo(); f1->~foo(); pool.free(f1); } } BOOST_AUTO_TEST_CASE(simple_pool_tests) { run_simple_test(false); run_simple_test(true); run_simple_test_2(false); run_simple_test_2(true); }
779
C++
.cpp
32
20.84375
58
0.647619
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,982
server_sc_osc_handler_test.cpp
supercollider_supercollider/testsuite/server/supernova/server_sc_osc_handler_test.cpp
#include <boost/test/unit_test.hpp> #include <vector> #include "../../source/server/sc_osc_handler.hpp" using namespace nova; BOOST_AUTO_TEST_CASE(sc_osc_handler_1) { const_cast<server_arguments&>(server_arguments::initialize(0, 0)).udp_port = 54321; sc_osc_handler handler(server_arguments::instance()); } BOOST_AUTO_TEST_CASE(sc_osc_handler_2) { const_cast<server_arguments&>(server_arguments::initialize(0, 0)).tcp_port = 54321; sc_osc_handler handler(server_arguments::instance()); }
509
C++
.cpp
12
39.666667
87
0.735772
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,983
tl_allocator_test.cpp
supercollider_supercollider/testsuite/server/supernova/tl_allocator_test.cpp
#include <boost/test/unit_test.hpp> #include <list> #include <vector> #include <set> #include <iostream> #include "utilities/tl_allocator.hpp" using namespace nova; using namespace std; namespace { struct initialized_struct { initialized_struct(int i): i(i), f(0.2) {} bool operator<(initialized_struct const& rhs) const { return i < rhs.i; } int i; double f; }; template <typename T> void test_list(void) { list<T, tl_allocator<T>> vec; for (int i = 0; i != 8192; ++i) vec.push_back(T(i)); } template <typename T> void test_vector(void) { vector<T, tl_allocator<T>> vec; for (int i = 0; i != 8192; ++i) vec.push_back(T(i)); } template <typename T> void test_set(void) { set<T, std::less<T>, tl_allocator<T>> set; for (int i = 0; i != 8192; ++i) set.insert(T(i)); } } BOOST_AUTO_TEST_CASE(rt_alloc_test_1) { detail::tl_allocator<8 * 1024 * 1024> rt_alloc; } BOOST_AUTO_TEST_CASE(rt_alloc_test_2) { test_list<int>(); test_list<initialized_struct>(); } BOOST_AUTO_TEST_CASE(rt_alloc_test_3) { test_vector<int>(); test_vector<initialized_struct>(); } BOOST_AUTO_TEST_CASE(rt_alloc_test_4) { test_set<int>(); test_set<initialized_struct>(); }
1,246
C++
.cpp
44
24.886364
89
0.650888
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,984
sc_synthdef_test.cpp
supercollider_supercollider/testsuite/server/supernova/sc_synthdef_test.cpp
#include <iostream> #include <boost/test/unit_test.hpp> #include "sc/sc_synthdef.hpp" BOOST_AUTO_TEST_CASE(sc_synthdef_test) { std::vector<nova::sc_synthdef> defs = nova::read_synthdef_file("testsuite/default.scsyndef"); std::cout << defs[0].dump(); }
263
C++
.cpp
7
35
97
0.719368
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,985
sndfile_backend_test.cpp
supercollider_supercollider/testsuite/server/supernova/sndfile_backend_test.cpp
#include <boost/test/unit_test.hpp> #include <chrono> #include <thread> #include "audio_backend/sndfile_backend.hpp" using namespace nova; namespace { aligned_storage_ptr<float> data(nova::calloc_aligned<float>(64)); struct engine_functor; struct engine_functor { void init_tick(void) {} void run_tick(void); }; sndfile_backend<engine_functor> be; void engine_functor::run_tick(void) { float* data_ptr = data.get(); be.output_mapping(&data_ptr, &data_ptr + 1); } } BOOST_AUTO_TEST_CASE(sndfile_backend_test_1) { BOOST_REQUIRE(!be.audio_is_opened()); BOOST_REQUIRE(!be.audio_is_active()); be.open_client("", "./output.wav", 44100, SF_FORMAT_WAV | SF_FORMAT_PCM_16, 1, 64); BOOST_REQUIRE(be.audio_is_opened()); be.activate_audio(); BOOST_REQUIRE(be.audio_is_active()); std::this_thread::sleep_for(std::chrono::seconds(1)); be.deactivate_audio(); BOOST_REQUIRE(!be.audio_is_active()); be.close_client(); BOOST_REQUIRE(!be.audio_is_opened()); }
1,017
C++
.cpp
31
29.354839
87
0.695876
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,986
timetag_test.cpp
supercollider_supercollider/testsuite/server/supernova/timetag_test.cpp
#include <boost/test/unit_test.hpp> #include "utilities/time_tag.hpp" #include "boost/date_time/posix_time/posix_time.hpp" using namespace nova; using namespace boost; BOOST_AUTO_TEST_CASE(time_tag_test_1) { { time_tag tt; BOOST_REQUIRE_EQUAL(tt.get_secs(), 0u); BOOST_REQUIRE_EQUAL(tt.get_fraction(), 0u); } { time_tag tt(100, 200); BOOST_REQUIRE_EQUAL(tt.get_secs(), 100u); BOOST_REQUIRE_EQUAL(tt.get_fraction(), 200u); } { time_tag t1(0, 0); time_tag t2(0, 1); time_tag t3(0, 1); BOOST_REQUIRE(t1 < t2); BOOST_REQUIRE(t1 != t2); BOOST_REQUIRE(t2 == t3); } { time_tag t1(0, 0); time_tag t2(1, 0); time_tag t3 = t1 + t2; BOOST_REQUIRE(t2 == t3); t3 += t2; BOOST_REQUIRE(t3 == time_tag(2, 0)); } } BOOST_AUTO_TEST_CASE(time_tag_test_2) { using namespace boost::posix_time; time_tag first = time_tag::from_ptime(ptime(microsec_clock::universal_time())); time_tag next = time_tag::from_ptime(ptime(microsec_clock::universal_time())); BOOST_REQUIRE(first <= next); }
1,168
C++
.cpp
39
23.717949
83
0.592659
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,987
server_dsp_thread_queue_test.cpp
supercollider_supercollider/testsuite/server/supernova/server_dsp_thread_queue_test.cpp
#include <boost/test/unit_test.hpp> #include "dsp_thread_queue/dsp_thread_queue.hpp" namespace { struct dummy_runnable { dummy_runnable(void): i(0) {} void operator()(unsigned int dummy) { ++i; } int i; }; dummy_runnable dummy; } typedef nova::dsp_queue_interpreter<dummy_runnable> dsp_queue_interpreter; typedef nova::dsp_thread_queue_item<dummy_runnable> dsp_thread_queue_item; typedef nova::dsp_thread_queue<dummy_runnable> dsp_thread_queue; BOOST_AUTO_TEST_CASE(dsp_thread_queue_test_1) { dsp_queue_interpreter interpreter(1); bool runnable = interpreter.init_tick(); BOOST_REQUIRE(!runnable); } BOOST_AUTO_TEST_CASE(dsp_thread_queue_test_2) { dsp_queue_interpreter interpreter(1); bool runnable = interpreter.init_tick(); if (runnable) interpreter.tick(0); } BOOST_AUTO_TEST_CASE(dsp_thread_queue_test_3) { dsp_queue_interpreter interpreter(1); std::unique_ptr<dsp_thread_queue> q(new dsp_thread_queue(1)); dsp_thread_queue_item* item = q->allocate_queue_item(dummy, dsp_thread_queue_item::successor_list(), 0); q->add_initially_runnable(item); interpreter.reset_queue(std::move(q)); bool runnable = interpreter.init_tick(); BOOST_REQUIRE(runnable); interpreter.tick(0); BOOST_REQUIRE_EQUAL(item->get_job().i, 1); } BOOST_AUTO_TEST_CASE(dsp_thread_queue_test_4) { dsp_queue_interpreter interpreter(1); std::unique_ptr<dsp_thread_queue> q(new dsp_thread_queue(2)); dsp_thread_queue_item* item1 = q->allocate_queue_item(dummy, dsp_thread_queue_item::successor_list(), 1); dsp_thread_queue_item::successor_list sl(1); sl[0] = item1; dsp_thread_queue_item* item2 = q->allocate_queue_item(dummy, sl, 0); q->add_initially_runnable(item2); interpreter.reset_queue(std::move(q)); bool runnable = interpreter.init_tick(); BOOST_REQUIRE(runnable); interpreter.tick(0); BOOST_REQUIRE_EQUAL(item1->get_job().i, 1); BOOST_REQUIRE_EQUAL(item2->get_job().i, 1); } BOOST_AUTO_TEST_CASE(dsp_thread_queue_test_5) { dsp_queue_interpreter interpreter(1); { std::unique_ptr<dsp_thread_queue> q(new dsp_thread_queue(2)); dsp_thread_queue_item* item1 = q->allocate_queue_item(dummy, dsp_thread_queue_item::successor_list(), 1); dsp_thread_queue_item::successor_list sl(1); sl[0] = item1; dsp_thread_queue_item* item2 = q->allocate_queue_item(dummy, sl, 0); q->add_initially_runnable(item2); interpreter.reset_queue(std::move(q)); for (int i = 0; i != 2; ++i) { bool runnable = interpreter.init_tick(); BOOST_REQUIRE(runnable); interpreter.tick(0); } BOOST_REQUIRE_EQUAL(item1->get_job().i, 2); BOOST_REQUIRE_EQUAL(item2->get_job().i, 2); } { std::unique_ptr<dsp_thread_queue> q(new dsp_thread_queue(2)); dsp_thread_queue_item* item1 = q->allocate_queue_item(dummy, dsp_thread_queue_item::successor_list(), 1); dsp_thread_queue_item::successor_list sl(1); sl[0] = item1; dsp_thread_queue_item* item2 = q->allocate_queue_item(dummy, sl, 0); q->add_initially_runnable(item2); interpreter.reset_queue(std::move(q)); for (int i = 0; i != 2; ++i) { bool runnable = interpreter.init_tick(); BOOST_REQUIRE(runnable); interpreter.tick(0); } BOOST_REQUIRE_EQUAL(item1->get_job().i, 2); BOOST_REQUIRE_EQUAL(item2->get_job().i, 2); } }
3,548
C++
.cpp
85
35.541176
113
0.66121
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,988
server_node_graph_test.cpp
supercollider_supercollider/testsuite/server/supernova/server_node_graph_test.cpp
#include <boost/test/unit_test.hpp> #include "server/node_graph.hpp" #include "test_synth.hpp" using namespace nova; using namespace std; BOOST_AUTO_TEST_CASE(simple_synth_test_1) { rt_pool.init(1024 * 1024); node_graph n; node_position_constraint to_root = std::make_pair(n.root_group(), insert); { test_synth* s = new test_synth(1000, 0); n.add_node(s, to_root); BOOST_REQUIRE_EQUAL(n.synth_count(), 1u); BOOST_REQUIRE_EQUAL(n.find_synth(1000), s); n.remove_node(s); BOOST_REQUIRE_EQUAL(n.synth_count(), 0u); } BOOST_REQUIRE_EQUAL(n.group_count(), 1u); { test_synth* s = new test_synth(1000, 0); n.add_node(s /* , node_position_constraint() */); BOOST_REQUIRE_EQUAL(n.synth_count(), 1u); n.remove_node(s); BOOST_REQUIRE_EQUAL(n.synth_count(), 0u); } BOOST_REQUIRE_EQUAL(n.group_count(), 1u); } BOOST_AUTO_TEST_CASE(simple_synth_test_2) { node_graph n; group* g = new group(1); n.add_node(g); BOOST_REQUIRE_EQUAL(n.find_group(1), g); n.remove_node(g); } BOOST_AUTO_TEST_CASE(simple_synth_test_3) { node_graph n; group* g = new group(1); n.add_node(g); { node_position_constraint to_group = std::make_pair(g, insert); test_synth* s = new test_synth(1000, 0); n.add_node(s, to_group); n.remove_node(s); } n.remove_node(g); } BOOST_AUTO_TEST_CASE(simple_synth_test_4) { node_graph n; group* g = new group(1); n.add_node(g); test_synth* s = new test_synth(1000, 0); { node_position_constraint to_group = std::make_pair(g, insert); n.add_node(s, to_group); } n.remove_node(g); } BOOST_AUTO_TEST_CASE(simple_synth_test_5) { node_graph n; test_synth* s = new test_synth(1000, 0); test_synth* s2 = new test_synth(1001, 0); n.add_node(s); n.add_node(s2); n.remove_node(s); n.remove_node(s2); } BOOST_AUTO_TEST_CASE(simple_synth_test_6) { node_graph n; test_synth* s1 = new test_synth(1000, 0); n.add_node(s1); test_synth* s2 = new test_synth(1001, 0); { node_position_constraint to_group = std::make_pair(n.root_group(), insert); n.add_node(s2, to_group); } test_synth* s3 = new test_synth(1002, 0); { node_position_constraint position = std::make_pair(s1, after); n.add_node(s3, position); } test_synth* s4 = new test_synth(1003, 0); { node_position_constraint position = std::make_pair(s1, before); n.add_node(s4, position); } // n.dump("test.dot"); n.remove_node(s1); n.remove_node(s2); n.remove_node(s3); n.remove_node(s4); } BOOST_AUTO_TEST_CASE(free_all_test) { node_graph n; group* g = new group(1); n.add_node(g); BOOST_REQUIRE_EQUAL(n.group_count(), 2u); node_position_constraint to_group = std::make_pair(g, insert); test_synth* s = new test_synth(1000, 0); n.add_node(s, to_group); test_synth* s2 = new test_synth(1001, 0); n.add_node(s2, to_group); group* g2 = new group(1002); n.add_node(g2, to_group); BOOST_REQUIRE_EQUAL(n.synth_count(), 2u); BOOST_REQUIRE_EQUAL(n.group_count(), 3u); BOOST_REQUIRE(n.find_node(s->id())); BOOST_REQUIRE(n.find_node(s2->id())); BOOST_REQUIRE(n.find_node(g2->id())); n.group_free_all(g); BOOST_REQUIRE(!n.find_node(s->id())); BOOST_REQUIRE(!n.find_node(s2->id())); BOOST_REQUIRE(!n.find_node(g2->id())); BOOST_REQUIRE_EQUAL(n.synth_count(), 0u); BOOST_REQUIRE_EQUAL(n.group_count(), 2u); BOOST_REQUIRE(n.find_node(g->id())); n.remove_node(g); BOOST_REQUIRE(!n.find_node(g->id())); BOOST_REQUIRE_EQUAL(n.group_count(), 1u); } BOOST_AUTO_TEST_CASE(free_deep_test) { node_graph n; group* g = new group(1); n.add_node(g); BOOST_REQUIRE_EQUAL(n.group_count(), 2u); node_position_constraint to_group = std::make_pair(g, insert); test_synth* s = new test_synth(1000, 0); n.add_node(s, to_group); test_synth* s2 = new test_synth(1001, 0); n.add_node(s2, to_group); group* g2 = new group(1002); n.add_node(g2, to_group); BOOST_REQUIRE_EQUAL(n.synth_count(), 2u); BOOST_REQUIRE_EQUAL(n.group_count(), 3u); BOOST_REQUIRE(n.find_node(s->id())); BOOST_REQUIRE(n.find_node(s2->id())); BOOST_REQUIRE(n.find_node(g2->id())); n.group_free_deep(g); BOOST_REQUIRE(!n.find_node(s->id())); BOOST_REQUIRE(!n.find_node(s2->id())); BOOST_REQUIRE(n.find_node(g2->id())); BOOST_REQUIRE_EQUAL(n.synth_count(), 0u); BOOST_REQUIRE_EQUAL(n.group_count(), 3u); BOOST_REQUIRE(n.find_node(g2->id())); BOOST_REQUIRE(n.find_node(g->id())); n.remove_node(g); BOOST_REQUIRE(!n.find_node(g->id())); BOOST_REQUIRE(!n.find_node(g2->id())); BOOST_REQUIRE_EQUAL(n.group_count(), 1u); } BOOST_AUTO_TEST_CASE(queue_construction_test_1) { node_graph n; test_synth* s = new test_synth(1000, 0); test_synth* s2 = new test_synth(1001, 0); n.add_node(s); n.add_node(s2); unique_ptr<node_graph::dsp_thread_queue> q = n.generate_dsp_queue(); n.remove_node(s); n.remove_node(s2); } BOOST_AUTO_TEST_CASE(queue_construction_test_2) { node_graph n; group* g = new group(1); n.add_node(g); unique_ptr<node_graph::dsp_thread_queue> q = n.generate_dsp_queue(); BOOST_REQUIRE_EQUAL(q->total_node_count(), 0u); n.remove_node(g); } BOOST_AUTO_TEST_CASE(queue_construction_test_3) { node_graph n; test_synth* s = new test_synth(1000, 0); n.add_node(s); unique_ptr<node_graph::dsp_thread_queue> q1 = n.generate_dsp_queue(); BOOST_REQUIRE_EQUAL(q1->total_node_count(), 1u); test_synth* s2 = new test_synth(3, 0); n.add_node(s2); unique_ptr<node_graph::dsp_thread_queue> q2 = n.generate_dsp_queue(); BOOST_REQUIRE_EQUAL(q2->total_node_count(), 1u); n.remove_node(s); n.remove_node(s2); } BOOST_AUTO_TEST_CASE(pgroup_test_1) { node_graph n; parallel_group* g = new parallel_group(1); n.add_node(g); BOOST_REQUIRE_EQUAL(n.find_group(1), g); unique_ptr<node_graph::dsp_thread_queue> q = n.generate_dsp_queue(); BOOST_REQUIRE_EQUAL(q->total_node_count(), 0u); n.remove_node(g); } BOOST_AUTO_TEST_CASE(pgroup_test_2) { node_graph n; parallel_group* g = new parallel_group(1); n.add_node(g); { node_position_constraint to_group = std::make_pair(g, insert); test_synth* s = new test_synth(2, 0); n.add_node(s, to_group); n.remove_node(s); } n.remove_node(g); } BOOST_AUTO_TEST_CASE(pgroup_test_3) { node_graph n; parallel_group* g = new parallel_group(1); n.add_node(g); test_synth* s = new test_synth(2, 0); { node_position_constraint to_group = std::make_pair(g, insert); n.add_node(s, to_group); } n.remove_node(g); } BOOST_AUTO_TEST_CASE(pgroup_test_4) { node_graph n; parallel_group* g = new parallel_group(1); n.add_node(g); { node_position_constraint to_group = std::make_pair(g, insert); test_synth* s = new test_synth(2, 0); n.add_node(s, to_group); unique_ptr<node_graph::dsp_thread_queue> q = n.generate_dsp_queue(); BOOST_REQUIRE_EQUAL(q->total_node_count(), 1u); n.remove_node(s); } n.remove_node(g); } BOOST_AUTO_TEST_CASE(pgroup_test_5) { node_graph n; parallel_group* g = new parallel_group(1); n.add_node(g); { node_position_constraint to_group = std::make_pair(g, insert); test_synth* s1 = new test_synth(2, 0); test_synth* s2 = new test_synth(3, 0); n.add_node(s1, to_group); n.add_node(s2, to_group); unique_ptr<node_graph::dsp_thread_queue> q = n.generate_dsp_queue(); BOOST_REQUIRE_EQUAL(q->total_node_count(), 2u); n.remove_node(s1); n.remove_node(s2); } n.remove_node(g); } BOOST_AUTO_TEST_CASE(pgroup_test_6) { node_graph n; parallel_group* g = new parallel_group(1); n.add_node(g); { node_position_constraint to_group = std::make_pair(g, insert); test_synth* s1 = new test_synth(2, 0); test_synth* s2 = new test_synth(3, 0); test_synth* s3 = new test_synth(4, 0); n.add_node(s1, to_group); n.add_node(s2, to_group); n.add_node(s3, to_group); unique_ptr<node_graph::dsp_thread_queue> q = n.generate_dsp_queue(); BOOST_REQUIRE_EQUAL(q->total_node_count(), 3u); } n.remove_node(g); } BOOST_AUTO_TEST_CASE(pgroup_test_7) { node_graph n; parallel_group* g = new parallel_group(1); n.add_node(g); { node_position_constraint to_group = std::make_pair(g, insert); group* g1 = new group(2); group* g2 = new group(3); group* g3 = new group(4); n.add_node(g1, to_group); n.add_node(g2, to_group); n.add_node(g3, to_group); node_position_constraint to_g1 = std::make_pair(g1, insert); node_position_constraint to_g2 = std::make_pair(g2, insert); test_synth* s1 = new test_synth(1000, 0); test_synth* s2 = new test_synth(1001, 0); n.add_node(s1, to_g1); n.add_node(s2, to_g2); unique_ptr<node_graph::dsp_thread_queue> q = n.generate_dsp_queue(); BOOST_REQUIRE_EQUAL(q->total_node_count(), 2u); } n.remove_node(g); } BOOST_AUTO_TEST_CASE(noid_test) { rt_pool.init(1024 * 1024); node_graph n; node_position_constraint to_root = std::make_pair(n.root_group(), insert); { test_synth* s = new test_synth(1000, 0); n.add_node(s, to_root); BOOST_REQUIRE(s->id() == 1000); n.synth_reassign_id(1000); BOOST_REQUIRE(s->id() != 1000); n.remove_node(s); } { test_synth* s = new test_synth(1000, 0); n.add_node(s /* , node_position_constraint() */); BOOST_REQUIRE(s->id() == 1000); n.synth_reassign_id(1000); BOOST_REQUIRE(s->id() != 1000); n.remove_node(s); } }
10,222
C++
.cpp
304
27.713816
83
0.608949
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,989
sc_synth_prototype_test.cpp
supercollider_supercollider/testsuite/server/supernova/sc_synth_prototype_test.cpp
#include <boost/test/unit_test.hpp> #include "sc/sc_synth_prototype.hpp" #include "server/synth_factory.hpp" using namespace nova; using namespace std; BOOST_AUTO_TEST_CASE(sc_synth_factory) { synth_factory factory; const char* home_ptr = getenv("HOME"); BOOST_REQUIRE(home_ptr != 0); path home(home_ptr); register_synthdefs(factory, sc_read_synthdefs_dir(home / "share/SuperCollider/synthdefs")); }
426
C++
.cpp
12
32.333333
95
0.740196
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,990
server_dsp_thread_test.cpp
supercollider_supercollider/testsuite/server/supernova/server_dsp_thread_test.cpp
#include <boost/test/unit_test.hpp> #include <vector> #include "dsp_thread_queue/dsp_thread.hpp" #include "server/memory_pool.hpp" namespace { volatile int gint; struct dummy_runnable { dummy_runnable(void): i(0) {} void operator()(uint dummy) { ++i; for (int j = 0; j != 1000; ++j) { int l = gint; l += 1; gint = l; } } int i; }; dummy_runnable dummy; } template <typename Alloc> void run_test_1(void) { nova::dsp_thread_pool<dummy_runnable, nova::nop_thread_init, Alloc> t(1); } BOOST_AUTO_TEST_CASE(dsp_thread_test_1) { nova::rt_pool.init(1024 * 1024 * 128); run_test_1<std::allocator<void*>>(); run_test_1<nova::rt_pool_allocator<void*>>(); } template <typename Alloc> void run_test_2(void) { nova::dsp_thread_pool<dummy_runnable, nova::nop_thread_init, Alloc> t(5); t.start_threads(); t.terminate_threads(); } BOOST_AUTO_TEST_CASE(dsp_thread_test_2) { run_test_2<std::allocator<void*>>(); run_test_2<nova::rt_pool_allocator<void*>>(); } template <typename Alloc> void run_test_3(void) { nova::dsp_thread_pool<dummy_runnable, nova::nop_thread_init, Alloc> t(2); t.start_threads(); t.run(); t.terminate_threads(); } BOOST_AUTO_TEST_CASE(dsp_thread_test_3) { run_test_3<std::allocator<void*>>(); run_test_3<nova::rt_pool_allocator<void*>>(); } template <typename Alloc> void run_test_4(void) { typedef typename nova::dsp_thread_queue_item<dummy_runnable, Alloc> dsp_thread_queue_item; typedef typename nova::dsp_thread_queue<dummy_runnable, Alloc> dsp_thread_queue; typedef typename nova::dsp_thread_pool<dummy_runnable, nova::nop_thread_init, Alloc> dsp_thread_pool; typedef std::unique_ptr<dsp_thread_queue> dsp_thread_queue_ptr; dsp_thread_pool t(1); t.start_threads(); dsp_thread_queue_ptr q(new dsp_thread_queue(2)); dsp_thread_queue_item* item1 = q->allocate_queue_item(dummy, typename dsp_thread_queue_item::successor_list(), 1); typename dsp_thread_queue_item::successor_list sl(1); sl[0] = item1; dsp_thread_queue_item* item2 = q->allocate_queue_item(dummy, sl, 0); q->add_initially_runnable(item2); t.reset_queue(std::move(q)); t.run(); t.terminate_threads(); BOOST_REQUIRE_EQUAL(item1->get_job().i, 1); BOOST_REQUIRE_EQUAL(item2->get_job().i, 1); } BOOST_AUTO_TEST_CASE(dsp_thread_test_4) { run_test_4<std::allocator<void*>>(); run_test_4<nova::rt_pool_allocator<void*>>(); } template <typename Alloc> void run_test_5(void) { typedef nova::dsp_thread_queue_item<dummy_runnable, Alloc> dsp_thread_queue_item; typedef nova::dsp_thread_queue<dummy_runnable, Alloc> dsp_thread_queue; typedef nova::dsp_thread_pool<dummy_runnable, nova::nop_thread_init, Alloc> dsp_thread_pool; typedef std::unique_ptr<dsp_thread_queue> dsp_thread_queue_ptr; dsp_thread_pool t(2); t.start_threads(); dsp_thread_queue_ptr q(new dsp_thread_queue(5)); dsp_thread_queue_item* item1 = q->allocate_queue_item(dummy, typename dsp_thread_queue_item::successor_list(), 4); typename dsp_thread_queue_item::successor_list sl(1); sl[0] = item1; dsp_thread_queue_item* item2 = q->allocate_queue_item(dummy, sl, 0); q->add_initially_runnable(item2); dsp_thread_queue_item* item3 = q->allocate_queue_item(dummy, sl, 0); q->add_initially_runnable(item3); dsp_thread_queue_item* item4 = q->allocate_queue_item(dummy, sl, 0); q->add_initially_runnable(item4); dsp_thread_queue_item* item5 = q->allocate_queue_item(dummy, sl, 0); q->add_initially_runnable(item5); t.reset_queue(std::move(q)); t.run(); t.terminate_threads(); BOOST_REQUIRE_EQUAL(item1->get_job().i, 1); BOOST_REQUIRE_EQUAL(item2->get_job().i, 1); BOOST_REQUIRE_EQUAL(item3->get_job().i, 1); BOOST_REQUIRE_EQUAL(item4->get_job().i, 1); BOOST_REQUIRE_EQUAL(item5->get_job().i, 1); } BOOST_AUTO_TEST_CASE(dsp_thread_test_5) { run_test_5<std::allocator<void*>>(); run_test_5<nova::rt_pool_allocator<void*>>(); } template <typename Alloc> void run_test_6(void) { typedef nova::dsp_thread_queue_item<dummy_runnable, Alloc> dsp_thread_queue_item; typedef nova::dsp_thread_queue<dummy_runnable, Alloc> dsp_thread_queue; typedef nova::dsp_thread_pool<dummy_runnable, nova::nop_thread_init, Alloc> dsp_thread_pool; typedef std::unique_ptr<dsp_thread_queue> dsp_thread_queue_ptr; dsp_thread_pool t(2); t.start_threads(); dsp_thread_queue_ptr q(new dsp_thread_queue(20)); std::vector<dsp_thread_queue_item*> items; for (int i = 0; i != 20; ++i) { items.push_back(q->allocate_queue_item(dummy, typename dsp_thread_queue_item::successor_list(), 0)); q->add_initially_runnable(items.back()); } t.reset_queue(std::move(q)); const int iterations = 10000; for (int i = 0; i != iterations; ++i) { for (int item = 0; item != 20; ++item) BOOST_REQUIRE_EQUAL(items[item]->get_job().i, i); t.run(); } t.terminate_threads(); for (int i = 0; i != 20; ++i) BOOST_REQUIRE_EQUAL(items[i]->get_job().i, iterations); } BOOST_AUTO_TEST_CASE(dsp_thread_test_6) { run_test_6<std::allocator<void*>>(); run_test_6<nova::rt_pool_allocator<void*>>(); }
5,359
C++
.cpp
130
36.338462
118
0.66686
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,991
server_synth_factory_test.cpp
supercollider_supercollider/testsuite/server/supernova/server_synth_factory_test.cpp
#include <boost/test/unit_test.hpp> #include "server/synth_factory.hpp" #include "test_synth.hpp" using namespace nova; using namespace std; namespace { struct test_synth_definition : public synth_definition { test_synth_definition(): synth_definition(symbol("foo")) {} abstract_synth* create_instance(int node_id) { return new test_synth(node_id, this); } }; } BOOST_AUTO_TEST_CASE(synth_factory_test_1) { rt_pool.init(1 << 20); synth_factory sf; sf.register_definition(new test_synth_definition); unique_ptr<abstract_synth> s(sf.create_instance("foo", 1)); BOOST_REQUIRE(s.get() != 0); }
628
C++
.cpp
18
31.777778
90
0.723333
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,992
server_scheduler_test.cpp
supercollider_supercollider/testsuite/server/supernova/server_scheduler_test.cpp
#include <boost/test/unit_test.hpp> #include <thread> #include <boost/thread/barrier.hpp> #include "server/server_scheduler.hpp" using namespace nova; using namespace boost; BOOST_AUTO_TEST_CASE(scheduler_test_1) { scheduler<> sched(1); /* sched(); */ } namespace { boost::barrier barr(2); void thread_fn(scheduler<>* sched) { for (int i = 0; i != 1000; ++i) /* (*sched)() */; barr.wait(); } } BOOST_AUTO_TEST_CASE(scheduler_test_2) { scheduler<> sched(1); std::thread thrd(std::bind(thread_fn, &sched)); barr.wait(); thrd.join(); }
585
C++
.cpp
24
21.375
51
0.652803
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,993
callback_interpreter_system.cpp
supercollider_supercollider/testsuite/server/supernova/callback_interpreter_system.cpp
#include <boost/test/unit_test.hpp> #include "utilities/callback_system.hpp" #include "utilities/callback_interpreter.hpp" #include "nova-tt/thread_priority.hpp" using namespace nova; namespace { int i = 0; struct dummy { void run(void) { ++i; } }; } BOOST_AUTO_TEST_CASE(callback_system_test) { callback_system<dummy> cbs; cbs.add_callback(new dummy()); cbs.run_callbacks(); BOOST_REQUIRE_EQUAL(i, 1); } BOOST_AUTO_TEST_CASE(threaded_callback_interpreter_test) { threaded_callback_interpreter<dummy> cbi; cbi.start_thread(); for (int j = 0; j != 20; ++j) cbi.add_callback(new dummy()); cbi.join_thread(); BOOST_REQUIRE_EQUAL(i, 21); } BOOST_AUTO_TEST_CASE(callback_interpreter_threadpool_test) { { callback_interpreter_threadpool<dummy> cbi(4, true, thread_priority_interval().first); for (int j = 0; j != 20; ++j) cbi.add_callback(new dummy()); } BOOST_REQUIRE_EQUAL(i, 41); }
981
C++
.cpp
33
25.636364
94
0.67773
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,994
audio_backend_test.cpp
supercollider_supercollider/testsuite/server/supernova/audio_backend_test.cpp
#define BOOST_TEST_MAIN #include <boost/test/included/unit_test.hpp> #include <boost/thread.hpp> #define protected public #include "audio_backend/audio_backend.hpp" #include "audio_backend/portaudio.hpp" using namespace nova; namespace { void tick(void) {} } template <typename backend> void test_backend(void) { backend be; BOOST_REQUIRE(!be.audiostream_ready()); device_list devs = be.list_devices(); be.open_audio_stream(devs[0], devs[0].inchannels, devs[0], devs[0].outchannels, devs[0].defaultSampleRate); BOOST_REQUIRE(be.audiostream_ready()); BOOST_REQUIRE(!be.is_active()); be.activate(); BOOST_REQUIRE(be.is_active()); boost::xtime xt; boost::xtime_get(&xt, boost::TIME_UTC); xt.sec += 1; boost::thread::sleep(xt); be.deactivate(); BOOST_REQUIRE(!be.is_active()); be.close_audio_stream(); BOOST_REQUIRE(!be.audiostream_ready()); } BOOST_AUTO_TEST_CASE(dummy_test_1) { test_backend<dummy_backend<&tick>>(); } BOOST_AUTO_TEST_CASE(pa_test_1) { test_backend<portaudio_backend<&tick>>(); }
1,074
C++
.cpp
30
32.166667
111
0.705539
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,995
memory-pool_test.cpp
supercollider_supercollider/testsuite/server/supernova/memory-pool_test.cpp
#include <boost/test/unit_test.hpp> #include <vector> #include <set> #include "server/memory_pool.hpp" namespace nova { simple_pool<false> rt_pool; } /* namespace nova */ using namespace nova; BOOST_AUTO_TEST_CASE(init_pool) { rt_pool.init(1024 * 1024); } BOOST_AUTO_TEST_CASE(vector_test) { rt_pool.init(1024 * 1024); int size = 1024; std::vector<int, nova::rt_pool_allocator<int>> vec; for (int i = 0; i != size; ++i) vec.push_back(-i); } BOOST_AUTO_TEST_CASE(set_test) { int size = 1024; std::set<int, std::less<int>, nova::rt_pool_allocator<int>> vec; for (int i = 0; i != size; ++i) vec.insert(-i); }
659
C++
.cpp
22
26.545455
68
0.646497
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,996
static_pool_test.cpp
supercollider_supercollider/testsuite/server/supernova/static_pool_test.cpp
#include <boost/test/unit_test.hpp> #include <string> #include "utilities/static_pool.hpp" using namespace nova; using namespace std; namespace { struct foo { foo(void) {} int data[4]; }; } BOOST_AUTO_TEST_CASE(static_pool_test) { static_pool<16 * 1024> pool; foo* f1 = static_cast<foo*>(pool.malloc(sizeof(foo))); ::new (f1) foo(); f1->~foo(); pool.free(f1); } BOOST_AUTO_TEST_CASE(static_pool_test_locked) { static_pool<16 * 1024> pool(true); foo* f1 = static_cast<foo*>(pool.malloc(sizeof(foo))); ::new (f1) foo(); f1->~foo(); pool.free(f1); }
605
C++
.cpp
25
20.88
58
0.647368
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,997
sized_array_test.cpp
supercollider_supercollider/testsuite/server/supernova/sized_array_test.cpp
#include "utilities/sized_array.hpp" #include "server/memory_pool.hpp" #include <iostream> #include <boost/test/unit_test.hpp> namespace nova { simple_pool<false> rt_pool; } /* namespace nova */ using namespace nova; #ifdef BOOST_HAS_RVALUE_REFS using std::move; #else using boost::move; #endif BOOST_AUTO_TEST_CASE(sized_array_test_1) { sized_array<int> array(5); array[0] = -1; array[1] = 3; array[4] = 44; BOOST_REQUIRE_EQUAL(array.size(), 5u); BOOST_REQUIRE_EQUAL(array[1], 3); BOOST_REQUIRE_EQUAL(array[0], -1); BOOST_REQUIRE_EQUAL(*array.begin(), -1); BOOST_REQUIRE_EQUAL(array.front(), -1); BOOST_REQUIRE_EQUAL(array.back(), 44); BOOST_REQUIRE_EQUAL(*array.rbegin(), 44); BOOST_REQUIRE_EQUAL(*(array.rend() - 1), -1); sized_array<long> long_array(array); BOOST_REQUIRE_EQUAL(long_array.size(), 5u); BOOST_REQUIRE_EQUAL(long_array[1], 3); BOOST_REQUIRE_EQUAL(long_array[0], -1); // move assignment sized_array<int> array3(0); move(&array, &array + 1, &array3); BOOST_REQUIRE_EQUAL(array3.size(), 5u); BOOST_REQUIRE_EQUAL(array3[1], 3); BOOST_REQUIRE_EQUAL(array3[0], -1); BOOST_REQUIRE_EQUAL(array.size(), 0u); // move assignment sized_array<int> array4(move(array3)); BOOST_REQUIRE_EQUAL(array4.size(), 5u); BOOST_REQUIRE_EQUAL(array4[1], 3); BOOST_REQUIRE_EQUAL(array4[0], -1); BOOST_REQUIRE_EQUAL(array3.size(), 0u); } template <typename Alloc1, typename Alloc2> void run_test_2(void) { int size = 1024; std::vector<int, typename Alloc1::template rebind<int>::other> vec; for (int i = 0; i != size; ++i) vec.push_back(-i); sized_array<int, typename Alloc2::template rebind<int>::other> array(vec); for (int i = 0; i != size; ++i) BOOST_REQUIRE_EQUAL(vec[i], array[i]); } BOOST_AUTO_TEST_CASE(sized_array_test_2) { rt_pool.init(1024 * 1024); run_test_2<std::allocator<void*>, std::allocator<void*>>(); run_test_2<rt_pool_allocator<void*>, std::allocator<void*>>(); run_test_2<std::allocator<void*>, rt_pool_allocator<void*>>(); run_test_2<rt_pool_allocator<void*>, rt_pool_allocator<void*>>(); } BOOST_AUTO_TEST_CASE(sized_array_test_3) { sized_array<int> array(5); array[0] = -1; array[1] = 3; array[4] = 44; BOOST_REQUIRE_EQUAL(array.size(), 5u); BOOST_REQUIRE_EQUAL(array[0], -1); BOOST_REQUIRE_EQUAL(array[1], 3); BOOST_REQUIRE_EQUAL(*array.begin(), -1); array.resize(6, 444); BOOST_REQUIRE_EQUAL(array.size(), 6u); BOOST_REQUIRE_EQUAL(array[0], -1); BOOST_REQUIRE_EQUAL(array[1], 3); BOOST_REQUIRE_EQUAL(array[5], 444); array.resize(2); BOOST_REQUIRE_EQUAL(array.size(), 2u); BOOST_REQUIRE_EQUAL(array[0], -1); BOOST_REQUIRE_EQUAL(array[1], 3); } BOOST_AUTO_TEST_CASE(sized_array_test_4) { sized_array<int> array0(int8_t(5)); sized_array<int> array1(uint8_t(5)); sized_array<int> array2(int16_t(5)); sized_array<int> array3(uint16_t(5)); sized_array<int> array4(int32_t(5)); sized_array<int> array5(uint32_t(5)); sized_array<int> array6(int64_t(5)); sized_array<int> array7(uint64_t(5)); sized_array<int> array8(size_t(5)); sized_array<int> array9(short(5)); sized_array<int> array10(int(5)); sized_array<int> array11(long(5)); }
3,352
C++
.cpp
93
31.72043
78
0.655652
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,998
sc_ipc_client.cpp
supercollider_supercollider/editors/sc-ide/primitives/sc_ipc_client.cpp
/* * SuperCollider Qt IDE * Copyright (c) 2012 Jakob Leben & Tim Blechmann * http://www.audiosynth.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <QDataStream> #include <QUuid> #include <QBuffer> #include <QMutex> #include <cstdlib> #include <yaml-cpp/emitter.h> #include <yaml-cpp/node/node.h> #include <yaml-cpp/parser.h> #include "PyrPrimitive.h" #include "SCBase.h" #include "GC.h" #include "PyrKernel.h" #include "PyrSymbol.h" #include "sc_ipc_client.hpp" #include "localsocket_utils.hpp" SCIpcClient::SCIpcClient(const char* ideName): mSocket(NULL) { mSocket = new QLocalSocket(); mSocket->connectToServer(QString(ideName)); connect(mSocket, SIGNAL(readyRead()), this, SLOT(readIDEData())); } void SCIpcClient::send(const char* data, size_t length) { mSocket->write(data, length); } SCIpcClient::~SCIpcClient() { mSocket->disconnectFromServer(); } void SCIpcClient::readIDEData() { mIpcData.append(mSocket->readAll()); // After we have put the data in the buffer, process it int avail = mIpcData.length(); do { if (mReadSize == 0 && avail > 4) { mReadSize = ArrayToInt(mIpcData.left(4)); mIpcData.remove(0, 4); avail -= 4; } if (mReadSize > 0 && avail >= mReadSize) { QByteArray baReceived(mIpcData.left(mReadSize)); mIpcData.remove(0, mReadSize); mReadSize = 0; avail -= mReadSize; QDataStream in(baReceived); in.setVersion(QDataStream::Qt_5_6); QString selector; QVariantList argList; in >> selector; if (in.status() != QDataStream::Ok) return; in >> argList; if (in.status() != QDataStream::Ok) return; onResponse(selector, argList); } } while ((mReadSize == 0 && avail > 4) || (mReadSize > 0 && avail > mReadSize)); } void SCIpcClient::onResponse(const QString& selector, const QVariantList& argList) { static QString upDateDocTextSelector("updateDocText"); static QString upDateDocSelectionSelector("updateDocSelection"); if (selector == upDateDocTextSelector) updateDocText(argList); if (selector == upDateDocSelectionSelector) updateDocSelection(argList); } void SCIpcClient::updateDocText(const QVariantList& argList) { QByteArray quuid = argList[0].toByteArray(); int pos = argList[1].toInt(); int charsRemoved = argList[2].toInt(); QString newChars = argList[3].toString(); #ifdef DEBUG_IPC post("RECEIVED updateDocText with args id: %s, pos: %d, charsR: %d, newC: %s\n", quuid.constData(), pos, charsRemoved, newChars.toLatin1().data()); #endif setTextMirrorForDocument(quuid, newChars, pos, charsRemoved); } void SCIpcClient::updateDocSelection(const QVariantList& argList) { QByteArray quuid = argList[0].toByteArray(); int start = argList[1].toInt(); int range = argList[2].toInt(); #ifdef DEBUG_IPC post("RECEIVED updateDocText with args id: %s, pos: %d, charsR: %d, newC: %s\n", quuid.constData(), pos, charsRemoved, newChars.toLatin1().data()); #endif setSelectionMirrorForDocument(quuid, start, range); } QString SCIpcClient::getTextMirrorForDocument(QByteArray& id, int pos, int range) { QString returnText; if (mDocumentTextMirrors.contains(id)) { if ((pos == 0) && range == -1) { mTextMirrorHashMutex.lock(); returnText = mDocumentTextMirrors[id]; mTextMirrorHashMutex.unlock(); } else { mTextMirrorHashMutex.lock(); QString existingText = mDocumentTextMirrors[id]; if (range == -1) range = existingText.size() - pos; returnText = existingText.mid(pos, range); mTextMirrorHashMutex.unlock(); } } else { post("WARNING: Attempted to access missing Text Mirror for Document %s\n", id.constData()); } return returnText; } void SCIpcClient::setTextMirrorForDocument(QByteArray& id, const QString& text, int pos, int range) { if ((pos == 0) && range == -1) { mTextMirrorHashMutex.lock(); mDocumentTextMirrors[id] = text; mTextMirrorHashMutex.unlock(); } else { if (mDocumentTextMirrors.contains(id)) { mTextMirrorHashMutex.lock(); QString existingText = mDocumentTextMirrors[id]; int size = existingText.size(); if (pos > size) pos = size; if (range == -1) range = existingText.size() - pos; mDocumentTextMirrors[id] = existingText.replace(pos, range, text); mTextMirrorHashMutex.unlock(); } else { post("WARNING: Attempted to modify missing Text Mirror for Document %s\n", id.constData()); } } } QPair<int, int> SCIpcClient::getSelectionMirrorForDocument(QByteArray& id) { QPair<int, int> selection; if (mDocumentSelectionMirrors.contains(id)) { mSelMirrorHashMutex.lock(); selection = mDocumentSelectionMirrors[id]; mSelMirrorHashMutex.unlock(); } else { post("WARNING: Attempted to access missing Selection Mirror for Document %s\n", id.constData()); selection = qMakePair(0, 0); } return selection; } void SCIpcClient::setSelectionMirrorForDocument(QByteArray& id, int start, int range) { mSelMirrorHashMutex.lock(); mDocumentSelectionMirrors[id] = qMakePair(start, range); mSelMirrorHashMutex.unlock(); } static SCIpcClient* gIpcClient = NULL; int ScIDE_Connect(struct VMGlobals* g, int numArgsPushed) { if (gIpcClient) { error("ScIDE already connected\n"); return errFailed; } PyrSlot* ideNameSlot = g->sp; char ideName[1024]; int status = slotStrVal(ideNameSlot, ideName, 1024); if (status != errNone) return errWrongType; gIpcClient = new SCIpcClient(ideName); return errNone; } int ScIDE_Connected(struct VMGlobals* g, int numArgsPushed) { PyrSlot* returnSlot = g->sp - numArgsPushed + 1; SetBool(returnSlot, gIpcClient != 0); return errNone; } struct YAMLSerializer { YAML::Emitter emitter; public: explicit YAMLSerializer(PyrSlot* slot) { serialize(slot); } const char* data() { return emitter.c_str(); } size_t size() { return emitter.size(); } private: void serialize(PyrSlot* slot) { if (IsFloat(slot)) { emitter << slotRawFloat(slot); return; } switch (GetTag(slot)) { case tagNil: emitter << YAML::Null; return; case tagInt: emitter << slotRawInt(slot); return; case tagFalse: emitter << false; return; case tagTrue: emitter << true; return; case tagObj: serialize(slotRawObject(slot)); return; case tagSym: emitter << YAML::DoubleQuoted << slotRawSymbol(slot)->name; return; default: printf("type: %d\n", GetTag(slot)); throw std::runtime_error("YAMLSerializer: not implementation for this type"); } } void serialize(PyrObject* object) { if (isKindOf(object, class_string)) { PyrObjectHdr* hdr = static_cast<PyrObjectHdr*>(object); PyrString* str = static_cast<PyrString*>(hdr); size_t len = str->size; char* cstr = new char[len + 10]; memcpy(cstr, str->s, len); cstr[len] = 0; // zero-terminate emitter << YAML::DoubleQuoted << cstr; delete[] cstr; return; } if (isKindOf(object, class_arrayed_collection)) { emitter << YAML::BeginSeq; for (size_t i = 0; i != object->size; ++i) serialize(object->slots + i); emitter << YAML::EndSeq; return; } throw std::runtime_error("YAMLSerializer: not implementation for this type"); } }; int ScIDE_Send(struct VMGlobals* g, int numArgsPushed) { if (!gIpcClient) { error("ScIDE not connected\n"); return errFailed; } if (!gMainVMGlobals->canCallOS) { error( "You can not use ScIDE:prSend functionality in the current thread.\nTry scheduling on AppClock instead.\n"); return errFailed; } PyrSlot* idSlot = g->sp - 1; char id[255]; if (slotStrVal(idSlot, id, 255)) return errWrongType; PyrSlot* argSlot = g->sp; try { YAMLSerializer serializer(argSlot); sendSelectorAndData(gIpcClient->mSocket, QString(id), QString::fromUtf8(serializer.data())); } catch (std::exception const& e) { postfl("Exception during ScIDE_Send: %s\n", e.what()); return errFailed; } return errNone; } int ScIDE_GetQUuid(struct VMGlobals* g, int numArgsPushed) { PyrSlot* returnSlot = g->sp - numArgsPushed + 1; SetSymbol(returnSlot, getsym(QUuid::createUuid().toString().toLatin1().constData())); return errNone; } int ScIDE_GetDocTextMirror(struct VMGlobals* g, int numArgsPushed) { if (!gIpcClient) { error("ScIDE not connected\n"); return errFailed; } PyrSlot* returnSlot = g->sp - numArgsPushed + 1; PyrSlot* docIDSlot = g->sp - 2; char id[255]; if (slotStrVal(docIDSlot, id, 255)) return errWrongType; int pos, range, err = errNone; PyrSlot* posSlot = g->sp - 1; err = slotIntVal(posSlot, &pos); if (err) return err; PyrSlot* rangeSlot = g->sp; err = slotIntVal(rangeSlot, &range); if (err) return err; QByteArray key = QByteArray(id); QString docText = gIpcClient->getTextMirrorForDocument(key, pos, range); PyrString* pyrString = newPyrString(g->gc, docText.toUtf8().constData(), 0, true); SetObject(returnSlot, pyrString); return errNone; } int ScIDE_SetDocTextMirror(struct VMGlobals* g, int numArgsPushed) { if (!gIpcClient) { error("ScIDE not connected\n"); return errFailed; } PyrSlot* docIDSlot = g->sp - 3; char id[255]; if (slotStrVal(docIDSlot, id, 255)) return errWrongType; PyrSlot* textSlot = g->sp - 2; int length = slotStrLen(textSlot); if (length == -1) return errWrongType; std::vector<char> text(length + 1); if (slotStrVal(textSlot, text.data(), length + 1)) return errWrongType; int pos, range, err = errNone; PyrSlot* posSlot = g->sp - 1; err = slotIntVal(posSlot, &pos); if (err) return err; PyrSlot* rangeSlot = g->sp; err = slotIntVal(rangeSlot, &range); if (err) return err; QByteArray key = QByteArray(id); QString docText = QString(text.data()); gIpcClient->setTextMirrorForDocument(key, docText, pos, range); return errNone; } int ScIDE_GetDocSelectionStart(struct VMGlobals* g, int numArgsPushed) { if (!gIpcClient) { error("ScIDE not connected\n"); return errFailed; } PyrSlot* returnSlot = g->sp - numArgsPushed + 1; PyrSlot* docIDSlot = g->sp; char id[255]; if (slotStrVal(docIDSlot, id, 255)) return errWrongType; QByteArray key = QByteArray(id); QPair<int, int> selection = gIpcClient->getSelectionMirrorForDocument(key); SetInt(returnSlot, selection.first); return errNone; } int ScIDE_GetDocSelectionRange(struct VMGlobals* g, int numArgsPushed) { if (!gIpcClient) { error("ScIDE not connected\n"); return errFailed; } PyrSlot* returnSlot = g->sp - numArgsPushed + 1; PyrSlot* docIDSlot = g->sp; char id[255]; if (slotStrVal(docIDSlot, id, 255)) return errWrongType; QByteArray key = QByteArray(id); QPair<int, int> selection = gIpcClient->getSelectionMirrorForDocument(key); SetInt(returnSlot, selection.second); return errNone; } int ScIDE_SetDocSelectionMirror(struct VMGlobals* g, int numArgsPushed) { if (!gIpcClient) { error("ScIDE not connected\n"); return errFailed; } PyrSlot* docIDSlot = g->sp - 2; char id[255]; if (slotStrVal(docIDSlot, id, 255)) return errWrongType; int start, range, err = errNone; PyrSlot* startSlot = g->sp - 1; err = slotIntVal(startSlot, &start); if (err) return err; PyrSlot* rangeSlot = g->sp; err = slotIntVal(rangeSlot, &range); if (err) return err; QByteArray key = QByteArray(id); gIpcClient->setSelectionMirrorForDocument(key, start, range); return errNone; } void initScIDEPrimitives() { int base = nextPrimitiveIndex(); int index = 0; definePrimitive(base, index++, "_ScIDE_Connect", ScIDE_Connect, 2, 0); definePrimitive(base, index++, "_ScIDE_Connected", ScIDE_Connected, 1, 0); definePrimitive(base, index++, "_ScIDE_Send", ScIDE_Send, 3, 0); definePrimitive(base, index++, "_ScIDE_GetQUuid", ScIDE_GetQUuid, 0, 0); definePrimitive(base, index++, "_ScIDE_GetDocTextMirror", ScIDE_GetDocTextMirror, 4, 0); definePrimitive(base, index++, "_ScIDE_SetDocTextMirror", ScIDE_SetDocTextMirror, 5, 0); definePrimitive(base, index++, "_ScIDE_GetDocSelectionStart", ScIDE_GetDocSelectionStart, 2, 0); definePrimitive(base, index++, "_ScIDE_GetDocSelectionRange", ScIDE_GetDocSelectionRange, 2, 0); definePrimitive(base, index++, "_ScIDE_SetDocSelectionMirror", ScIDE_SetDocSelectionMirror, 4, 0); }
14,330
C++
.cpp
383
30.710183
120
0.646613
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,999
localsocket_utils.cpp
supercollider_supercollider/editors/sc-ide/primitives/localsocket_utils.cpp
#include "localsocket_utils.hpp" qint32 ArrayToInt(QByteArray source) { qint32 temp; QDataStream data(&source, QIODevice::ReadWrite); data >> temp; return temp; } QByteArray IntToArray(qint32 source) { QByteArray temp; QDataStream data(&temp, QIODevice::ReadWrite); data << source; return temp; }
332
C++
.cpp
13
21.846154
52
0.721519
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,000
sc_introspection.cpp
supercollider_supercollider/editors/sc-ide/core/sc_introspection.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "sc_introspection.hpp" #include "util/standard_dirs.hpp" #include "../widgets/main_window.hpp" #include <yaml-cpp/yaml.h> #include <cassert> #include <algorithm> // std::sort #include <QDebug> #include <QHash> #include <QObject> namespace ScIDE { namespace ScLanguage { Introspection::Introspection() { initPaths(); } Introspection::Introspection(QString const& yamlString) { initPaths(); bool parsingSuccessful = parse(yamlString); if (!parsingSuccessful) throw std::runtime_error("Introspection parse error"); } Introspection& Introspection::operator=(Introspection&& rhs) { mClassMap = std::move(rhs.mClassMap); mMethodMap = std::move(rhs.mMethodMap); mClassLibraryPath = std::move(rhs.mClassLibraryPath); mUserExtensionDir = std::move(rhs.mUserExtensionDir); mSystemExtensionDir = std::move(rhs.mSystemExtensionDir); return *this; } void Introspection::initPaths() { mUserExtensionDir = standardDirectory(ScExtensionUserDir) + QStringLiteral("/"); mSystemExtensionDir = standardDirectory(ScExtensionSystemDir) + QStringLiteral("/"); } bool Introspection::parse(const QString& yamlString) { using std::make_pair; clear(); const YAML::Node doc = YAML::Load(yamlString.toStdString()); if (!doc) { MainWindow::instance()->showStatusMessage("no YAML document"); return false; } assert(doc.IsSequence()); for (auto const& element : doc) { assert(element.IsSequence()); QString name = element[0].as<std::string>().c_str(); Class* klass = new Class; klass->name = name; mClassMap.insert(make_pair(klass->name, QSharedPointer<Class>(klass))); } for (YAML::Node const& node : doc) { QString name = node[0].as<std::string>().c_str(); ClassMap::iterator it = mClassMap.find(name); assert(it != mClassMap.end()); Class* klass = it->second.data(); // qDebug() << klass->name; ClassMap::iterator class_it; QString metaClassName = node[1].as<std::string>().c_str(); class_it = mClassMap.find(metaClassName); assert(class_it != mClassMap.end()); klass->metaClass = class_it->second.data(); if (node[2].IsNull()) klass->superClass = 0; else { QString superClassName = node[2].as<std::string>().c_str(); class_it = mClassMap.find(superClassName); assert(class_it != mClassMap.end()); klass->superClass = class_it->second.data(); } klass->definition.path = node[3].as<std::string>().c_str(); klass->definition.position = node[4].as<int>(); const YAML::Node& methodSeq = node[5]; if (methodSeq.Type() != YAML::NodeType::Sequence) continue; // assert(methodSeq.Type() == YAML::NodeType::Sequence); for (const YAML::Node& methodNode : methodSeq) { assert(methodNode.Type() == YAML::NodeType::Sequence); assert(methodNode.size() >= 2); assert(methodNode[0].Type() == YAML::NodeType::Scalar); assert(methodNode[1].Type() == YAML::NodeType::Scalar); Method* method = new Method; method->ownerClass = klass; method->name = methodNode[1].as<std::string>().c_str(); method->definition.path = methodNode[2].as<std::string>().c_str(); method->definition.position = methodNode[3].as<int>(); // qDebug() << "--" << method->name; const YAML::Node& argNode = methodNode[4]; assert(argNode.Type() == YAML::NodeType::Sequence); auto arg = argNode.begin(); while (arg != argNode.end()) { Argument argument; // get arg name assert(arg->Type() == YAML::NodeType::Scalar); argument.name = arg->as<std::string>().c_str(); // qDebug() << "---# " << argument.name; // get arg default value ++arg; if (arg == argNode.end()) break; if (!arg->IsNull()) { assert(arg->Type() == YAML::NodeType::Scalar); argument.defaultValue = arg->as<std::string>().c_str(); } method->arguments.append(argument); // next arg ++arg; } klass->methods.append(method); mMethodMap.insert(make_pair(method->name, QSharedPointer<Method>(method))); } std::sort(klass->methods.begin(), klass->methods.end(), [](Method* lhs, Method* rhs) { return lhs->name.get() < rhs->name.get(); }); } inferClassLibraryPath(); // qDebug("done parsing introspection."); return true; } QString Introspection::compactLibraryPath(QString const& path) const { if (path.startsWith(mClassLibraryPath)) return path.mid(mClassLibraryPath.length()); if (path.startsWith(mUserExtensionDir)) return QStringLiteral("Extensions/") + path.mid(mUserExtensionDir.length()); if (path.startsWith(mSystemExtensionDir)) return QStringLiteral("Extensions/") + path.mid(mSystemExtensionDir.length()); return path; } void Introspection::inferClassLibraryPath() { ClassMap::const_iterator object_class_it = mClassMap.find("Object"); assert(object_class_it != mClassMap.end()); Class* objectClass = object_class_it->second.data(); QString classLibPath = objectClass->definition.path; int len = classLibPath.lastIndexOf("Common"); if (len != -1) classLibPath.truncate(len); else classLibPath.clear(); mClassLibraryPath = classLibPath; } bool Introspection::ensureIntrospectionData() const { if (!introspectionAvailable()) { MainWindow::instance()->showStatusMessage(QObject::tr("Sclang Introspection not available, yet!")); return false; } else return true; } const Class* Introspection::findClass(const QString& className) const { if (!ensureIntrospectionData()) return nullptr; auto classIterator = mClassMap.find(className); if (classIterator == mClassMap.end()) { return nullptr; } return classIterator->second.data(); } const Class* Introspection::findClassOrWarn(const QString& className) const { auto* classInstance = findClass(className); if (classInstance == nullptr) { MainWindow::instance()->showStatusMessage(QObject::tr("Class not defined!")); } return classInstance; } std::vector<const Class*> Introspection::findClassPartial(const QString& partialClassName) const { std::vector<const Class*> matchingClasses; if (!ensureIntrospectionData()) return matchingClasses; typedef ClassMap::const_iterator class_iterator; for (class_iterator it = mClassMap.begin(); it != mClassMap.end(); ++it) { QString const& key = it->first; if (key.contains(partialClassName, Qt::CaseInsensitive)) { if (!key.startsWith("Meta_")) matchingClasses.push_back(it->second.data()); } } return matchingClasses; } std::vector<const Method*> Introspection::findMethodPartial(const QString& partialMethodName) const { std::vector<const Method*> matchingMethods; if (!ensureIntrospectionData()) return matchingMethods; typedef MethodMap::const_iterator class_iterator; for (class_iterator it = mMethodMap.begin(); it != mMethodMap.end(); ++it) { QString const& key = it->first; if (key.contains(partialMethodName, Qt::CaseInsensitive)) matchingMethods.push_back(it->second.data()); } return matchingMethods; } bool Method::matches(const QString& toMatch) const { return toMatch.isEmpty() ? true : name.get().startsWith(toMatch, Qt::CaseInsensitive); } QString Method::signature(SignatureStyle style) const { QString sig = ownerClass->name.get(); if (sig.startsWith("Meta_")) { sig.remove(0, 5); sig.append(": *"); } else sig.append(": "); sig.append(name.get()); if (style == SignatureWithoutArguments) return sig; int argc = arguments.count(); if (argc) { sig.append(" ("); for (int i = 0; i < argc; ++i) { const Argument& arg = arguments[i]; if (i > 0) sig.append(", "); sig.append(arg.name); if (style == SignatureWithArgumentsAndDefaultValues && !arg.defaultValue.get().isEmpty()) { sig.append(" = "); sig.append(arg.defaultValue); } } sig.append(")"); } else if (name.get().endsWith('_')) sig.append(" (value)"); return sig; } } // namespace ScLanguage } // namespace ScIDE
9,699
C++
.cpp
231
34.238095
107
0.634536
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,001
doc_manager.cpp
supercollider_supercollider/editors/sc-ide/core/doc_manager.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "doc_manager.hpp" #include "main.hpp" #include "main_window.hpp" #include "settings/manager.hpp" #include "../widgets/code_editor/highlighter.hpp" #include "../../common/SC_TextUtils.hpp" #include "util/standard_dirs.hpp" #include <QPlainTextDocumentLayout> #include <QDebug> #include <QDir> #include <QFile> #include <QMessageBox> #include <QTextBlock> #include <QApplication> #include <yaml-cpp/yaml.h> using namespace ScIDE; Document::Document(bool isPlainText, const QByteArray& id, const QString& title, const QString& text): mId(id), mDoc(new QTextDocument(text, this)), mTitle(title), mIndentWidth(4), mHighlighter(0), mKeyDownActionEnabled(false), mKeyUpActionEnabled(false), mMouseDownActionEnabled(false), mMouseUpActionEnabled(false), mTextChangedActionEnabled(false), mLastActiveEditor(0), mInitialSelectionStart(0), mInitialSelectionRange(0), mEditable(true), mPromptsToSave(true) { mTmpCoalCount = 0; mTmpCoalTimer.setInterval(RESTORE_COAL_MSECS); mTmpCoalTimer.setSingleShot(true); connect(&mTmpCoalTimer, SIGNAL(timeout()), this, SLOT(onTmpCoalUsecs())); if (mId.isEmpty()) mId = QUuid::createUuid().toString().toLatin1(); if (mTitle.isEmpty()) mTitle = tr("Untitled"); mDoc->setDocumentLayout(new QPlainTextDocumentLayout(mDoc)); if (!isPlainText) mHighlighter = new SyntaxHighlighter(mDoc); connect(Main::instance(), SIGNAL(applySettingsRequest(Settings::Manager*)), this, SLOT(applySettings(Settings::Manager*))); applySettings(Main::settings()); } void Document::setPlainText(bool set_plain_text) { if (isPlainText() == set_plain_text) return; delete mHighlighter; mHighlighter = 0; if (!set_plain_text) mHighlighter = new SyntaxHighlighter(mDoc); } void Document::applySettings(Settings::Manager* settings) { QFont font = settings->codeFont(); int indentWidth = settings->value("IDE/editor/indentWidth").toInt(); setDefaultFont(font); setIndentWidth(indentWidth); } void Document::deleteTrailingSpaces() { QTextCursor cursor(textDocument()); cursor.beginEditBlock(); cursor.movePosition(QTextCursor::EndOfBlock); QTextDocument* doc = textDocument(); while (!cursor.atEnd()) { while ((cursor.block().length() > 1) && doc->characterAt(cursor.position() - 1).isSpace()) cursor.deletePreviousChar(); cursor.movePosition(QTextCursor::NextBlock); cursor.movePosition(QTextCursor::EndOfBlock); } cursor.endEditBlock(); } void Document::setDefaultFont(const QFont& font) { mDoc->setDefaultFont(font); // update tab stop, since it depends on font: setIndentWidth(mIndentWidth); emit defaultFontChanged(); } void Document::resetDefaultFont() { Settings::Manager* settings = Main::settings(); setDefaultFont(settings->codeFont()); } void Document::setIndentWidth(int numSpaces) { mIndentWidth = numSpaces; QFontMetricsF fontMetrics(mDoc->defaultFont()); qreal tabStop = fontMetrics.horizontalAdvance(' ') * numSpaces; QTextOption options = mDoc->defaultTextOption(); options.setTabStopDistance(tabStop); mDoc->setDefaultTextOption(options); } QString Document::textAsSCArrayOfCharCodes(int start = 0, int range = -1) { QTextCursor cursor = QTextCursor(mDoc); cursor.setPosition(start, QTextCursor::MoveAnchor); if (range == -1) { cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor, 1); } else { cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, range); } QByteArray stringBytes = cursor.selectedText().replace(QChar(0x2029), QChar('\n')).toUtf8(); return bytesToSCArrayOfCharCodes(stringBytes); } QString Document::titleAsSCArrayOfCharCodes() { QByteArray stringBytes = mTitle.toUtf8(); return bytesToSCArrayOfCharCodes(stringBytes); } QString Document::pathAsSCArrayOfCharCodes() { QString path; if (mFilePath.isEmpty()) { return QStringLiteral("nil"); } else { path = mFilePath; } QByteArray stringBytes = path.toUtf8(); return bytesToSCArrayOfCharCodes(stringBytes); ; } QString Document::bytesToSCArrayOfCharCodes(QByteArray stringBytes) { QString returnString = QStringLiteral("["); for (int i = 0; i < stringBytes.size(); ++i) { returnString = returnString.append(QString::number(static_cast<int>(stringBytes.at(i)))).append(','); } returnString = returnString.append(QStringLiteral("]")); return returnString; } void Document::setTextInRange(const QString text, int start, int range) { QTextCursor cursor = QTextCursor(mDoc); int size = mDoc->characterCount(); if (start > (size - 1)) { start = size - 1; range = 0; } cursor.setPosition(start, QTextCursor::MoveAnchor); if (range == -1) { cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor, 1); } else { cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, range); } cursor.insertText(text); } void Document::onTmpCoalUsecs() { mTmpCoalCount = RESTORE_COAL; storeTmpFile(); } void Document::storeTmpFile() { QString path, name; QDir tmpFilesDir = standardDirectory(ScConfigUserDir); int i = 0; if (!textDocument()->isModified()) return; if (++mTmpCoalCount < RESTORE_COAL) { mTmpCoalTimer.start(); return; } mTmpCoalCount = 0; if (!mTmpFilePath.isEmpty()) { path = mTmpFilePath; goto store; } if (mFilePath.isEmpty()) name = QStringLiteral("Untitled"); else name = QFileInfo(mFilePath).baseName(); if (!tmpFilesDir.exists("tmp")) tmpFilesDir.mkdir("tmp"); tmpFilesDir.cd("tmp"); path = QStringLiteral("%1/%2.bak").arg(tmpFilesDir.absolutePath()).arg(name); while (QFile(path).exists()) path = QStringLiteral("%1/%2-%3.bak").arg(tmpFilesDir.absolutePath()).arg(name).arg(++i); mTmpFilePath = path; store: QFile file(path); if (!file.open(QIODevice::WriteOnly)) { qWarning() << "DocumentManager: the file" << path << "could not be opened for writing."; return; } QString str = textDocument()->toPlainText(); file.write(str.toUtf8()); file.close(); } void Document::removeTmpFile() { if (mTmpFilePath.isEmpty()) return; if (!QFile(mTmpFilePath).remove()) qWarning() << "DocumentManager: the file" << mTmpFilePath << "could not be removed.'"; mTmpFilePath = ""; } DocumentManager::DocumentManager(Main* main, Settings::Manager* settings): QObject(main), mTextMirrorEnabled(true), mCurrentDocument(NULL), mGlobalKeyDownEnabled(false), mGlobalKeyUpEnabled(false) { mDocumentModel = new QStandardItemModel(this); connect(&mFsWatcher, SIGNAL(fileChanged(QString)), this, SLOT(onFileChanged(QString))); connect(main, SIGNAL(storeSettingsRequest(Settings::Manager*)), this, SLOT(storeSettings(Settings::Manager*))); loadRecentDocuments(settings); } Document* DocumentManager::createDocument(bool isPlainText, const QByteArray& id, const QString& title, const QString& text) { Document* doc = new Document(isPlainText, id, title, text); mDocHash.insert(doc->id(), doc); QStandardItem* item = new QStandardItem(doc->title()); doc->mModelItem = item; item->setData(QVariant::fromValue(doc)); mDocumentModel->appendRow(item); QTextDocument* tdoc = doc->textDocument(); connect(tdoc, SIGNAL(modificationChanged(bool)), doc, SLOT(onModificationChanged(bool))); return doc; } void DocumentManager::create() { Document* doc = createDocument(); connect(doc->textDocument(), SIGNAL(contentsChanged()), doc, SLOT(storeTmpFile())); syncLangDocument(doc); Q_EMIT(opened(doc, 0, 0)); } Document* DocumentManager::open(const QString& path, int initialCursorPosition, int selectionLength, bool toRecent, const QByteArray& id, bool syncLang) { QFileInfo info(path); QString cpath = info.canonicalFilePath(); info.setFile(cpath); if (cpath.isEmpty()) { MainWindow::instance()->showStatusMessage(tr("Cannot open file: %1 (file does not exist)").arg(path)); return 0; } // Check if file already opened for (DocIterator it = mDocHash.begin(); it != mDocHash.end(); ++it) { Document* doc = it.value(); if (doc->mFilePath == cpath) { Q_EMIT(showRequest(doc, initialCursorPosition, selectionLength)); if (toRecent) addToRecent(doc); return doc; } } // Open the file QFile file(cpath); if (!file.open(QIODevice::ReadOnly)) { MainWindow::instance()->showStatusMessage(tr("Cannot open file for reading: %1").arg(cpath)); return 0; } QByteArray bytes(file.readAll()); file.close(); // strip .rtf bool isRTF = false; QString filePath = cpath; if (info.suffix() == QStringLiteral("rtf")) { isRTF = true; filePath += QStringLiteral(".scd"); int result = rtf2txt(bytes.data()); bytes = bytes.left(result); QMessageBox::warning(NULL, QString(tr("Opening RTF File")), QString(tr("Warning: RTF file will be converted to plain-text scd file."))); } closeSingleUntitledIfUnmodified(); const bool fileIsPlainText = !(info.suffix() == QStringLiteral("sc") || (info.suffix() == QStringLiteral("scd")) || (info.suffix() == QStringLiteral("schelp"))); Document* doc = createDocument(fileIsPlainText, id); doc->mDoc->setPlainText(decodeDocument(bytes)); doc->mDoc->setModified(false); doc->mFilePath = filePath; QString fileTitle = info.fileName(); doc->setTitle(fileTitle); doc->mSaveTime = info.lastModified(); doc->setInitialSelection(initialCursorPosition, selectionLength); connect(doc->textDocument(), SIGNAL(contentsChanged()), doc, SLOT(storeTmpFile())); if (!isRTF) mFsWatcher.addPath(cpath); // if this was opened from the lang we don't need to sync if (syncLang) { syncLangDocument(doc); } Q_EMIT(opened(doc, initialCursorPosition, selectionLength)); if (toRecent) this->addToRecent(doc); return doc; } bool DocumentManager::reload(Document* doc) { Q_ASSERT(doc); if (doc->mFilePath.isEmpty()) return false; QFile file(doc->mFilePath); if (!file.open(QIODevice::ReadOnly)) { MainWindow::instance()->showStatusMessage(tr("Cannot open file for reading: %1").arg(doc->mFilePath)); return false; } QByteArray bytes(file.readAll()); file.close(); doc->mDoc->setPlainText(decodeDocument(bytes)); doc->mDoc->setModified(false); QFileInfo info(doc->mFilePath); doc->mSaveTime = info.lastModified(); if (!mFsWatcher.files().contains(doc->mFilePath)) mFsWatcher.addPath(doc->mFilePath); return true; } QStringList DocumentManager::tmpFiles() { QDir tmpFilesDir = standardDirectory(ScConfigUserDir) + "/tmp"; QStringList files = tmpFilesDir.entryList(QStringList("*.bak"), QDir::Files); int i; for (i = 0; i < files.size(); i++) files.replace(i, tmpFilesDir.absolutePath() + "/" + files[i]); return files; } bool DocumentManager::needRestore() { return (!tmpFiles().isEmpty()); } void DocumentManager::restore() { foreach (QString path, tmpFiles()) { QFile file(path); if (!file.open(QIODevice::ReadOnly)) MainWindow::instance()->showStatusMessage(tr("Cannot open file for reading: %1").arg(path)); QByteArray bytes(file.readAll()); file.close(); Document* doc = createDocument(false, QByteArray(), QFileInfo(path).baseName(), decodeDocument(bytes)); doc->mTmpFilePath = path; syncLangDocument(doc); Q_EMIT(opened(doc, 0, 0)); connect(doc->textDocument(), SIGNAL(contentsChanged()), doc, SLOT(storeTmpFile())); } } void DocumentManager::deleteRestore() { foreach (QString file, tmpFiles()) QFile(file).remove(); } Document* DocumentManager::documentForId(const QByteArray docID) { Document* doc = mDocHash.value(docID); if (!doc) MainWindow::instance()->showStatusMessage( QStringLiteral("Lookup failed for Document %1").arg(docID.constData())); return doc; } QString DocumentManager::decodeDocument(const QByteArray& bytes) { QTextStream stream(bytes); #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) stream.setCodec("UTF-8"); #else stream.setEncoding(QStringConverter::Utf8); #endif stream.setAutoDetectUnicode(true); return stream.readAll(); } void DocumentManager::close(Document* doc) { Q_ASSERT(doc); doc->removeTmpFile(); if (mDocHash.remove(doc->id()) == 0) { qWarning("DocumentManager: trying to close an unmanaged document."); return; } mDocumentModel->removeRow(mDocumentModel->indexFromItem(doc->mModelItem).row()); if (!doc->mFilePath.isEmpty()) mFsWatcher.removePath(doc->mFilePath); Q_EMIT(closed(doc)); QString command = QStringLiteral("Document.findByQUuid(\'%1\').closed").arg(doc->id().constData()); Main::evaluateCodeIfCompiled(command, true); doc->deleteLater(); } bool DocumentManager::save(Document* doc) { Q_ASSERT(doc); return doSaveAs(doc, doc->mFilePath); } bool DocumentManager::saveAs(Document* doc, const QString& path) { Q_ASSERT(doc); if (path.isEmpty()) { qWarning() << "DocumentManager: the saving path is empty."; return false; } bool ok = doSaveAs(doc, path); if (ok) addToRecent(doc); return ok; } bool DocumentManager::doSaveAs(Document* doc, const QString& path) { Q_ASSERT(doc); doc->deleteTrailingSpaces(); QFile file(path); if (!file.open(QIODevice::WriteOnly)) { qWarning() << "DocumentManager: the file" << path << "could not be opened for writing."; return false; } QFileInfo info(path); QString cpath = info.canonicalFilePath(); const bool pathChanged = (!(doc->filePath().isEmpty()) && (cpath != doc->filePath())); if (pathChanged) mFsWatcher.removePath(doc->filePath()); QString str = doc->textDocument()->toPlainText(); file.write(str.toUtf8()); file.flush(); file.close(); info.refresh(); const bool fileIsPlainText = !(info.suffix() == QStringLiteral("sc") || (info.suffix() == QStringLiteral("scd")) || (info.suffix() == QStringLiteral("schelp"))); // It's possible the mod time has not been updated - if it looks like that is the case, // just set it one second in the future, so we don't trip the external modification alarm. if (doc->mSaveTime == info.lastModified()) { doc->mSaveTime = QDateTime::currentDateTime().addMSecs(1000); } else { doc->mSaveTime = info.lastModified(); } doc->mFilePath = cpath; QString fileTitle = info.fileName(); doc->setTitle(fileTitle); doc->mDoc->setModified(false); doc->setPlainText(fileIsPlainText); doc->removeTmpFile(); // Always try to start watching, because the file could have been removed: if (!mFsWatcher.files().contains(cpath)) mFsWatcher.addPath(cpath); Q_EMIT(saved(doc)); syncLangDocument(doc); return true; } void DocumentManager::onFileChanged(const QString& path) { DocIterator it; for (it = mDocHash.begin(); it != mDocHash.end(); ++it) { Document* doc = it.value(); if (doc->mFilePath == path) { QFileInfo info(doc->mFilePath); if (doc->mSaveTime < info.lastModified()) { doc->mDoc->setModified(true); doc->mSaveTime = info.lastModified(); emit changedExternally(doc); } } } } void DocumentManager::addToRecent(Document* doc) { const QString& path = doc->mFilePath; int i = mRecent.indexOf(path); if (i != -1) mRecent.move(i, 0); else { mRecent.prepend(path); if (mRecent.count() > mMaxRecent) mRecent.removeLast(); } emit recentsChanged(); } void DocumentManager::clearRecents() { mRecent.clear(); emit recentsChanged(); } void DocumentManager::loadRecentDocuments(Settings::Manager* settings) { QVariantList list = settings->value("IDE/recentDocuments").value<QVariantList>(); mRecent.clear(); foreach (const QVariant& var, list) { QString filePath = var.toString(); if (QFile::exists(filePath)) mRecent << filePath; } } void DocumentManager::storeSettings(Settings::Manager* settings) { QVariantList list; foreach (const QString& path, mRecent) list << QVariant(path); settings->setValue("IDE/recentDocuments", QVariant::fromValue<QVariantList>(list)); } void DocumentManager::closeSingleUntitledIfUnmodified() { QList<Document*> openDocuments = documents(); if (openDocuments.size() == 1) { Document* document = openDocuments.front(); if (document->filePath().isEmpty() && !document->isModified()) close(document); } } void DocumentManager::handleScLangMessage(const QString& selector, const QString& data) { static QString requestDocListSelector("requestDocumentList"); static QString newDocSelector("newDocument"); static QString openFileSelector("openFile"); static QString getDocTextSelector("getDocumentText"); static QString setDocTextSelector("setDocumentText"); static QString setDocSelectionSelector("setDocumentSelection"); static QString setDocEditableSelector("setDocumentEditable"); static QString setDocPromptsToSaveSelector("setDocumentPromptsToSave"); static QString setCurrentDocSelector("setCurrentDocument"); static QString removeDocUndoSelector("removeDocUndo"); static QString closeDocSelector("closeDocument"); static QString saveDocSelector("saveDocument"); static QString setDocTitleSelector("setDocumentTitle"); static QString enableGlobalKeyDownSelector("enableDocumentGlobalKeyDownAction"); static QString enableGlobalKeyUpSelector("enableDocumentGlobalKeyUpAction"); static QString enableKeyDownSelector("enableDocumentKeyDownAction"); static QString enableKeyUpSelector("enableDocumentKeyUpAction"); static QString enableMouseDownSelector("enableDocumentMouseDownAction"); static QString enableMouseUpSelector("enableDocumentMouseUpAction"); static QString enableTextChangedSelector("enableDocumentTextChangedAction"); static QString enableTextMirrorSelector("enableDocumentTextMirror"); if (selector == requestDocListSelector) handleDocListScRequest(); if (selector == newDocSelector) handleNewDocScRequest(data); if (selector == openFileSelector) handleOpenFileScRequest(data); if (selector == getDocTextSelector) handleGetDocTextScRequest(data); if (selector == setDocTextSelector) handleSetDocTextScRequest(data); if (selector == setDocSelectionSelector) handleSetDocSelectionScRequest(data); if (selector == setDocEditableSelector) handleSetDocEditableScRequest(data); if (selector == setDocPromptsToSaveSelector) handleSetDocPromptsToSaveScRequest(data); if (selector == setCurrentDocSelector) handleSetCurrentDocScRequest(data); if (selector == removeDocUndoSelector) handleRemoveDocUndoScRequest(data); if (selector == closeDocSelector) handleCloseDocScRequest(data); if (selector == saveDocSelector) handleSaveDocScRequest(data); if (selector == setDocTitleSelector) handleSetDocTitleScRequest(data); if (selector == enableKeyDownSelector) handleEnableKeyDownScRequest(data); if (selector == enableKeyUpSelector) handleEnableKeyUpScRequest(data); if (selector == enableGlobalKeyDownSelector) handleEnableGlobalKeyDownScRequest(data); if (selector == enableGlobalKeyUpSelector) handleEnableGlobalKeyUpScRequest(data); if (selector == enableMouseDownSelector) handleEnableMouseDownScRequest(data); if (selector == enableMouseUpSelector) handleEnableMouseUpScRequest(data); if (selector == enableTextChangedSelector) handleEnableTextChangedScRequest(data); if (selector == enableTextMirrorSelector) handleEnableTextMirrorScRequest(data); } void DocumentManager::handleDocListScRequest() { QList<Document*> docs = documents(); QList<Document*>::Iterator it; QString command = QStringLiteral("Document.syncDocs(["); for (it = docs.begin(); it != docs.end(); ++it) { Document* doc = *it; int start, range; if (doc->lastActiveEditor()) { // we might have changed selection before sync happened QTextCursor cursor = doc->lastActiveEditor()->textCursor(); start = cursor.selectionStart(); range = cursor.selectionEnd() - start; } else { start = doc->initialSelectionStart(); range = doc->initialSelectionRange(); } QString docData = QStringLiteral("[\'%1\', %2, %3, %4, %5, %6, %7],") .arg(doc->id().constData()) .arg(doc->titleAsSCArrayOfCharCodes()) .arg(doc->textAsSCArrayOfCharCodes(0, -1)) .arg(doc->isModified()) .arg(doc->pathAsSCArrayOfCharCodes()) .arg(start) .arg(range); command = command.append(docData); } command = command.append("]);"); Main::evaluateCode(command, true); } void DocumentManager::handleNewDocScRequest(const QString& data) { try { YAML::Node doc = YAML::Load(data.toStdString()); if (doc) { if (!doc.IsSequence()) return; std::string title = doc[0].as<std::string>(); std::string text = doc[1].as<std::string>(); std::string id = doc[2].as<std::string>(); Document* document = createDocument(false, id.c_str(), QString::fromUtf8(title.c_str()), QString::fromUtf8(text.c_str())); syncLangDocument(document); Q_EMIT(opened(document, 0, 0)); } } catch (std::exception const& e) { qWarning() << "DocumentManager::" << __FUNCTION__ << ": could not handle request:" << e.what(); return; } } void DocumentManager::handleOpenFileScRequest(const QString& data) { try { YAML::Node doc = YAML::Load(data.toStdString()); if (doc) { if (!doc.IsSequence()) return; std::string path = doc[0].as<std::string>(); int position = doc[1].as<int>(); int selectionLength = doc[2].as<int>(); std::string id = doc[3].as<std::string>(); // we don't need to sync with lang in this case open(QString(path.c_str()), position, selectionLength, true, id.c_str(), false); } } catch (std::exception const& e) { qWarning() << "DocumentManager::" << __FUNCTION__ << ": could not handle request:" << e.what() << "\n"; return; } } void DocumentManager::handleGetDocTextScRequest(const QString& data) { try { YAML::Node doc = YAML::Load(data.toStdString()); if (doc) { if (!doc.IsSequence()) return; std::string id = doc[0].as<std::string>(); std::string funcID = doc[1].as<std::string>(); int start = doc[2].as<int>(); int range = doc[3].as<int>(); Document* document = documentForId(id.c_str()); if (document) { QString docText = document->textAsSCArrayOfCharCodes(start, range); QString command = QStringLiteral("Document.executeAsyncResponse(\'%1\', %2.collect({|x| " "{x.asInteger.asAscii}.try ? \"\" }).join)") .arg(funcID.c_str(), docText); Main::evaluateCode(command, true); } } } catch (std::exception const& e) { qWarning() << "DocumentManager::" << __FUNCTION__ << ": could not handle request:" << e.what() << "\n"; return; } } void DocumentManager::handleSetDocTextScRequest(const QString& data) { try { YAML::Node doc = YAML::Load(data.toStdString()); if (doc) { if (!doc.IsSequence()) return; // Parse funcID (doc[1]) later, if it was not null. std::string id = doc[0].as<std::string>(); std::string text = doc[2].as<std::string>(); int start = doc[3].as<int>(); int range = doc[4].as<int>(); Document* document = documentForId(id.c_str()); if (document) { // avoid a loop if (document == mCurrentDocument) { disconnect(document->textDocument(), SIGNAL(contentsChange(int, int, int)), this, SLOT(updateCurrentDocContents(int, int, int))); } document->setTextInRange(QString::fromUtf8(text.c_str()), start, range); if (document == mCurrentDocument) { connect(document->textDocument(), SIGNAL(contentsChange(int, int, int)), this, SLOT(updateCurrentDocContents(int, int, int))); } // Only execute a call if a function name was passed. if (!doc[1].IsNull()) { std::string funcID = doc[1].as<std::string>(""); QString command = QStringLiteral("Document.executeAsyncResponse(\'%1\')").arg(funcID.c_str()); Main::evaluateCode(command, true); } } } } catch (std::exception const& e) { qWarning() << "DocumentManager::" << __FUNCTION__ << ": could not handle request:" << e.what(); return; } } void DocumentManager::handleSetDocSelectionScRequest(const QString& data) { try { YAML::Node doc = YAML::Load(data.toStdString()); if (doc) { if (!doc.IsSequence()) return; std::string id = doc[0].as<std::string>(); int start = doc[1].as<int>(); int range = doc[2].as<int>(); Document* document = documentForId(id.c_str()); if (document) { if (document->lastActiveEditor()) { document->lastActiveEditor()->showPosition(start, range); } } } } catch (std::exception const& e) { qWarning() << "DocumentManager::" << __FUNCTION__ << ": could not handle request:" << e.what(); return; } } void DocumentManager::handleSetDocEditableScRequest(const QString& data) { try { YAML::Node doc = YAML::Load(data.toStdString()); if (doc) { if (!doc.IsSequence()) return; std::string id = doc[0].as<std::string>(); bool editable = doc[1].as<bool>(); Document* document = documentForId(id.c_str()); if (document) { document->setEditable(editable); if (document->lastActiveEditor()) { document->lastActiveEditor()->setReadOnly(!editable); } } } } catch (std::exception const& e) { qWarning() << "DocumentManager::" << __FUNCTION__ << ": could not handle request:" << e.what(); return; } } void DocumentManager::handleSetDocPromptsToSaveScRequest(const QString& data) { try { YAML::Node doc = YAML::Load(data.toStdString()); if (doc) { if (!doc.IsSequence()) return; std::string id = doc[0].as<std::string>(); bool promptsToSave = doc[1].as<bool>(); Document* document = documentForId(id.c_str()); if (document) { document->setPromptsToSave(promptsToSave); } } } catch (std::exception const& e) { qWarning() << "DocumentManager::" << __FUNCTION__ << ": could not handle request:" << e.what(); return; } } void DocumentManager::handleSetCurrentDocScRequest(const QString& data) { try { YAML::Node doc = YAML::Load(data.toStdString()); if (doc) { if (!doc.IsSequence()) return; std::string id = doc[0].as<std::string>(); Document* document = documentForId(id.c_str()); if (document) Q_EMIT(showRequest(document)); } } catch (std::exception const& e) { qWarning() << "DocumentManager::" << __FUNCTION__ << ": could not handle request:" << e.what(); return; } } void DocumentManager::handleRemoveDocUndoScRequest(const QString& data) { try { YAML::Node doc = YAML::Load(data.toStdString()); if (doc) { if (!doc.IsSequence()) return; std::string id = doc[0].as<std::string>(); Document* document = documentForId(id.c_str()); if (document) { QTextDocument* textDoc = document->textDocument(); textDoc->clearUndoRedoStacks(); textDoc->setModified(false); } } } catch (std::exception const& e) { qWarning() << "DocumentManager::" << __FUNCTION__ << ": could not handle request:" << e.what(); return; } } void DocumentManager::handleCloseDocScRequest(const QString& data) { try { YAML::Node doc = YAML::Load(data.toStdString()); if (doc) { if (!doc.IsSequence()) return; std::string id = doc[0].as<std::string>(); Document* document = documentForId(id.c_str()); if (document) { close(document); } } } catch (std::exception const& e) { qWarning() << "DocumentManager::" << __FUNCTION__ << ": could not handle request:" << e.what(); return; } } void DocumentManager::handleSaveDocScRequest(const QString& data) { try { YAML::Node doc = YAML::Load(data.toStdString()); if (doc) { if (!doc.IsSequence()) return; std::string id = doc[0].as<std::string>(); std::string path = doc[1].as<std::string>(); Document* document = documentForId(id.c_str()); if (document) { saveAs(document, QString::fromUtf8(path.c_str())); } } } catch (std::exception const& e) { qWarning() << "DocumentManager::" << __FUNCTION__ << ": could not handle request:" << e.what(); return; } } void DocumentManager::handleSetDocTitleScRequest(const QString& data) { try { YAML::Node doc = YAML::Load(data.toStdString()); if (doc) { if (!doc.IsSequence()) return; std::string id = doc[0].as<std::string>(); std::string title = doc[1].as<std::string>(); Document* document = documentForId(id.c_str()); if (document) { document->mTitle = QString::fromUtf8(title.c_str()); Q_EMIT(titleChanged(document)); } } } catch (std::exception const& e) { qWarning() << "DocumentManager::" << __FUNCTION__ << ": could not handle request:" << e.what(); return; } } bool DocumentManager::parseActionEnabledRequest(const QString& data, std::string* idString, bool* en) { try { YAML::Node doc = YAML::Load(data.toStdString()); if (doc) { if (!doc.IsSequence()) return false; std::string id = doc[0].as<std::string>(); bool enabled = doc[1].as<bool>(); *idString = id; *en = enabled; return true; } } catch (std::exception const& e) { qWarning() << "DocumentManager::" << __FUNCTION__ << ": could not handle request:" << e.what(); } return false; } void DocumentManager::handleEnableKeyDownScRequest(const QString& data) { std::string id; bool enabled; if (parseActionEnabledRequest(data, &id, &enabled)) { Document* document = documentForId(id.c_str()); if (document) { document->setKeyDownActionEnabled(enabled); } } } void DocumentManager::handleEnableKeyUpScRequest(const QString& data) { std::string id; bool enabled; if (parseActionEnabledRequest(data, &id, &enabled)) { Document* document = documentForId(id.c_str()); if (document) { document->setKeyUpActionEnabled(enabled); } } } void DocumentManager::handleEnableGlobalKeyDownScRequest(const QString& data) { try { YAML::Node doc = YAML::Load(data.toStdString()); if (doc) { if (!doc.IsSequence()) return; bool enabled = doc[0].as<bool>(enabled); mGlobalKeyDownEnabled = enabled; } } catch (std::exception const& e) { qWarning() << "DocumentManager::" << __FUNCTION__ << ": could not handle request:" << e.what(); } } void DocumentManager::handleEnableGlobalKeyUpScRequest(const QString& data) { try { YAML::Node doc = YAML::Load(data.toStdString()); if (doc) { if (!doc.IsSequence()) return; bool enabled = doc[0].as<bool>(); mGlobalKeyUpEnabled = enabled; } } catch (std::exception const& e) { qWarning() << "DocumentManager::" << __FUNCTION__ << ": could not handle request:" << e.what(); } } void DocumentManager::handleEnableMouseDownScRequest(const QString& data) { std::string id; bool enabled; if (parseActionEnabledRequest(data, &id, &enabled)) { Document* document = documentForId(id.c_str()); if (document) { document->setMouseDownActionEnabled(enabled); } } } void DocumentManager::handleEnableMouseUpScRequest(const QString& data) { std::string id; bool enabled; if (parseActionEnabledRequest(data, &id, &enabled)) { Document* document = documentForId(id.c_str()); if (document) { document->setMouseUpActionEnabled(enabled); } } } void DocumentManager::handleEnableTextChangedScRequest(const QString& data) { std::string id; bool enabled; if (parseActionEnabledRequest(data, &id, &enabled)) { Document* document = documentForId(id.c_str()); if (document) { document->setTextChangedActionEnabled(enabled); } } } void DocumentManager::handleEnableTextMirrorScRequest(const QString& data) { try { YAML::Node doc = YAML::Load(data.toStdString()); if (doc) { if (!doc.IsSequence()) return; bool enabled = doc[0].as<bool>(); mTextMirrorEnabled = enabled; QList<Document*> docs = documents(); QList<Document*>::Iterator it; if (enabled) { for (it = docs.begin(); it != docs.end(); ++it) { Document* doc = *it; Main::scProcess()->updateTextMirrorForDocument(doc, 0, -1, doc->textDocument()->characterCount()); doc->lastActiveEditor()->updateDocLastSelection(); } } else { // this sets the mirror to empty strings for (it = docs.begin(); it != docs.end(); ++it) { Document* doc = *it; Main::scProcess()->updateTextMirrorForDocument(doc, 0, -1, 0); } QString warning = QStringLiteral("Document Text Mirror Disabled\n"); Main::scProcess()->post(warning); } } } catch (std::exception const& e) { qWarning() << "DocumentManager::" << __FUNCTION__ << ": could not handle request:" << e.what(); } } void DocumentManager::syncLangDocument(Document* doc) { int start, range; if (doc->lastActiveEditor()) { // we might have changed selection before sync happened QTextCursor cursor = doc->lastActiveEditor()->textCursor(); start = cursor.selectionStart(); range = cursor.selectionEnd() - start; } else { start = doc->initialSelectionStart(); range = doc->initialSelectionRange(); } QString command = QStringLiteral("Document.syncFromIDE(\'%1\', %2, %3, %4, %5, %6, %7)") .arg(doc->id().constData()) .arg(doc->titleAsSCArrayOfCharCodes()) .arg(doc->textAsSCArrayOfCharCodes(0, -1)) .arg(doc->isModified()) .arg(doc->pathAsSCArrayOfCharCodes()) .arg(start) .arg(range); Main::evaluateCodeIfCompiled(command, true); } void DocumentManager::setActiveDocument(Document* document) { if (mCurrentDocument) disconnect(mCurrentDocument->textDocument(), SIGNAL(contentsChange(int, int, int)), this, SLOT(updateCurrentDocContents(int, int, int))); if (document) { mCurrentDocumentPath = document->filePath(); connect(document->textDocument(), SIGNAL(contentsChange(int, int, int)), this, SLOT(updateCurrentDocContents(int, int, int))); mCurrentDocument = document; } else { mCurrentDocumentPath.clear(); mCurrentDocument = NULL; } sendActiveDocument(); } void DocumentManager::sendActiveDocument() { if (Main::scProcess()->state() != QProcess::Running) return; if (mCurrentDocument) { QString command = QStringLiteral("Document.setActiveDocByQUuid(\'%1\');").arg(mCurrentDocument->id().constData()); if (mCurrentDocumentPath.isEmpty()) { command = command.append(QStringLiteral("ScIDE.currentPath_(nil);")); } else { command = command.append(QStringLiteral("ScIDE.currentPath_(\"%1\");").arg(mCurrentDocumentPath)); } Main::evaluateCodeIfCompiled(command, true); } else Main::evaluateCodeIfCompiled(QStringLiteral("ScIDE.currentPath_(nil); Document.current = nil;"), true); } void DocumentManager::updateCurrentDocContents(int position, int charsRemoved, int charsAdded) { if (mTextMirrorEnabled) { Main::scProcess()->updateTextMirrorForDocument(mCurrentDocument, position, charsRemoved, charsAdded); } if (mCurrentDocument->textChangedActionEnabled()) { QString addedChars = mCurrentDocument->textAsSCArrayOfCharCodes(position, charsAdded); Main::evaluateCode(QStringLiteral("Document.findByQUuid(\'%1\').textChanged(%2, %3, %4);") .arg(mCurrentDocument->id().constData()) .arg(position) .arg(charsRemoved) .arg(addedChars), true); } }
40,524
C++
.cpp
1,006
32.196819
118
0.625512
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
30,002
session_manager.cpp
supercollider_supercollider/editors/sc-ide/core/session_manager.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "doc_manager.hpp" #include "session_manager.hpp" #include "settings/manager.hpp" #include "util/standard_dirs.hpp" #include "../widgets/main_window.hpp" #include <QFile> #include <QFileInfo> namespace ScIDE { SessionManager::SessionManager(DocumentManager* docMng, QObject* parent): QObject(parent), mDocMng(docMng), mCurrentSession(0) {} QDir SessionManager::sessionsDir() { QDir dir(standardDirectory(ScConfigUserDir)); if (dir.mkpath("sessions")) dir.cd("sessions"); else { qWarning("The path to sessions does not exist and could not be created!"); return QDir(); } dir.setFilter(QDir::Files); dir.setNameFilters(QStringList() << "*.yaml"); return dir; } QStringList SessionManager::availableSessions() { QStringList sessions = sessionsDir().entryList(); QStringList::iterator it; for (it = sessions.begin(); it != sessions.end(); ++it) *it = QFileInfo(*it).baseName(); return sessions; } QString SessionManager::lastSession() { QDir dir = sessionsDir(); if (dir.path().isEmpty()) return QString(); QString path = QFile::symLinkTarget(dir.filePath(".last-session.lnk")); return QFileInfo(path).baseName(); } void SessionManager::newSession() { if (!closeSession()) return; QDir dir = sessionsDir(); if (!dir.path().isEmpty()) saveLastSession(dir, QString()); emit switchSessionRequest(0); } Session* SessionManager::openSession(const QString& name) { // NOTE: This will create a session if it doesn't exists if (!closeSession()) return 0; QDir dir = sessionsDir(); if (dir.path().isEmpty()) return 0; QString sessionFile = dir.filePath(name + ".yaml"); mCurrentSession = new Session(sessionFile, name, Settings::serializationFormat()); saveLastSession(dir, sessionFile); emit switchSessionRequest(mCurrentSession); return mCurrentSession; } void SessionManager::saveSession() { if (mCurrentSession) { emit saveSessionRequest(mCurrentSession); mCurrentSession->sync(); } } Session* SessionManager::saveSessionAs(const QString& name) { // TODO: // Maybe use a different data structure for Session instead of QSettings? // A new class that would allow closing without saving would be nice. if (mCurrentSession) { delete mCurrentSession; mCurrentSession = 0; } QDir dir = sessionsDir(); if (dir.path().isEmpty()) { emit switchSessionRequest(0); return 0; } QString sessionFile = dir.filePath(name + ".yaml"); mCurrentSession = new Session(sessionFile, name, Settings::serializationFormat()); emit saveSessionRequest(mCurrentSession); mCurrentSession->sync(); saveLastSession(dir, sessionFile); emit currentSessionNameChanged(); return mCurrentSession; } bool SessionManager::closeSession() { if (!MainWindow::instance()->promptSaveDocs()) return false; if (mCurrentSession) emit saveSessionRequest(mCurrentSession); delete mCurrentSession; mCurrentSession = 0; return true; } void SessionManager::removeSession(const QString& name) { QDir dir = sessionsDir(); if (dir.path().isEmpty()) return; if (mCurrentSession && mCurrentSession->name() == name) { if (!closeSession()) return; saveLastSession(dir, QString()); emit switchSessionRequest(0); } if (!QFile::remove(dir.filePath(name + ".yaml"))) qWarning("Could not remove a session file!"); } void SessionManager::renameSession(const QString& oldName, const QString& newName) { if (mCurrentSession && mCurrentSession->name() == oldName) { saveSessionAs(newName); removeSession(oldName); } else { QDir dir = sessionsDir(); if (dir.path().isEmpty()) return; if (!dir.rename(oldName + ".yaml", newName + ".yaml")) qWarning("Could not rename session file!"); } } bool SessionManager::saveLastSession(const QDir& dir, const QString& sessionFile) { QString linkFile = dir.filePath(".last-session.lnk"); if (QFile::exists(linkFile)) if (!QFile::remove(linkFile)) { qWarning("Could not remove old link to last session!"); return false; } if (sessionFile.isEmpty() || QFile::link(sessionFile, linkFile)) return true; else qWarning("Could not create link to last session!"); return false; } } // namespace ScIDE
5,416
C++
.cpp
150
30.593333
86
0.686793
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,003
main.cpp
supercollider_supercollider/editors/sc-ide/core/main.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "main.hpp" #include "settings/manager.hpp" #include "session_manager.hpp" #include "util/standard_dirs.hpp" #include "../widgets/main_window.hpp" #include "../widgets/lookup_dialog.hpp" #include "../widgets/code_editor/highlighter.hpp" #include "../widgets/style/style.hpp" #include "../../../QtCollider/hacks/hacks_mac.hpp" #include "../primitives/localsocket_utils.hpp" #include <yaml-cpp/node/node.h> #include <yaml-cpp/parser.h> #include <QAction> #include <QApplication> #include <QBuffer> #include <QDataStream> #include <QDir> #include <QFileOpenEvent> #include <QLibraryInfo> #include <QTranslator> #include <QDebug> #include <QStyleFactory> #include "util/HelpBrowserWebSocketServices.hpp" using namespace ScIDE; bool SingleInstanceGuard::tryConnect(QStringList const& arguments) { const int maxNumberOfInstances = 128; if (!arguments.empty()) { for (int socketID = 0; socketID != maxNumberOfInstances; ++socketID) { QString serverName = QStringLiteral("SuperColliderIDE_Singleton_%1").arg(socketID); QSharedPointer<QLocalSocket> socket(new QLocalSocket(this)); socket->connectToServer(serverName); QStringList canonicalArguments; foreach (QString path, arguments) { QFileInfo info(path); canonicalArguments << info.canonicalFilePath(); } if (socket->waitForConnected(200)) { sendSelectorAndData(socket.data(), QStringLiteral("open"), canonicalArguments); if (!socket->waitForBytesWritten(300)) qWarning("SingleInstanceGuard: writing data to another IDE instance timed out"); return true; } } } mIpcServer = new QLocalServer(this); for (int socketID = 0; socketID != maxNumberOfInstances; ++socketID) { QString serverName = QStringLiteral("SuperColliderIDE_Singleton_%1").arg(socketID); bool listening = mIpcServer->listen(serverName); if (listening) { connect(mIpcServer, SIGNAL(newConnection()), this, SLOT(onNewIpcConnection())); return false; } } return false; } void SingleInstanceGuard::onIpcData() { mIpcData.append(mIpcSocket->readAll()); // After we have put the data in the buffer, process it int avail = mIpcData.length(); do { if (mReadSize == 0 && avail > 4) { mReadSize = ArrayToInt(mIpcData.left(4)); mIpcData.remove(0, 4); avail -= 4; } if (mReadSize > 0 && avail >= mReadSize) { QByteArray baReceived(mIpcData.left(mReadSize)); mIpcData.remove(0, mReadSize); mReadSize = 0; QDataStream in(baReceived); in.setVersion(QDataStream::Qt_4_6); QString selector; in >> selector; if (in.status() != QDataStream::Ok) return; QStringList message; in >> message; if (in.status() != QDataStream::Ok) return; if (selector == QStringLiteral("open")) { foreach (QString path, message) Main::documentManager()->open(path); } } } while ((mReadSize == 0 && avail > 4) || (mReadSize > 0 && avail > mReadSize)); } static inline QString getSettingsFile() { return standardDirectory(ScConfigUserDir) + "/sc_ide_conf.yaml"; } // NOTE: mSettings must be the first to initialize, // because other members use it! Main::Main(void): mSettings(new Settings::Manager(getSettingsFile(), this)), mScProcess(new ScProcess(mSettings, this)), mScServer(new ScServer(mScProcess, mSettings, this)), mDocManager(new DocumentManager(this, mSettings)), mSessionManager(new SessionManager(mDocManager, this)) { new SyntaxHighlighterGlobals(this, mSettings); #ifdef Q_OS_MAC QtCollider::Mac::DisableAutomaticWindowTabbing(); #endif connect(mScProcess, SIGNAL(response(QString, QString)), mDocManager, SLOT(handleScLangMessage(QString, QString))); qApp->installEventFilter(this); qApp->installNativeEventFilter(this); } void Main::quit() { mSessionManager->saveSession(); storeSettings(); mScProcess->stopLanguage(); QApplication::quit(); } bool Main::eventFilter(QObject* object, QEvent* event) { switch (event->type()) { case QEvent::FileOpen: { // open the file dragged onto the application icon on Mac QFileOpenEvent* openEvent = static_cast<QFileOpenEvent*>(event); mDocManager->open(openEvent->file()); return true; } case QEvent::MouseMove: QApplication::restoreOverrideCursor(); break; default: break; } return QObject::eventFilter(object, event); } #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) bool Main::nativeEventFilter(const QByteArray&, void* message, long*) { #else bool Main::nativeEventFilter(const QByteArray&, void* message, qintptr*) { #endif bool result = false; #ifdef Q_OS_MAC if (QtCollider::Mac::IsCmdPeriodKeyDown(reinterpret_cast<void*>(message))) { // QKeyEvent event(QEvent::KeyPress, Qt::Key_Period, Qt::ControlModifier, "."); // QApplication::sendEvent(this, &event); mScProcess->stopMain(); // we completely bypass the shortcut handling result = true; } else if (QtCollider::Mac::IsCmdPeriodKeyUp(reinterpret_cast<void*>(message))) { result = true; } #endif return result; } bool Main::openDocumentation(const QString& string) { #ifdef SC_USE_QTWEBENGINE QString symbol = string.trimmed(); if (symbol.isEmpty()) return false; HelpBrowserDocklet* helpDock = MainWindow::instance()->helpBrowserDocklet(); helpDock->browser()->gotoHelpFor(symbol); helpDock->focus(); return true; #else // SC_USE_QTWEBENGINE return false; #endif // SC_USE_QTWEBENGINE } bool Main::openDocumentationForMethod(const QString& className, const QString& methodName) { #ifdef SC_USE_QTWEBENGINE HelpBrowserDocklet* helpDock = MainWindow::instance()->helpBrowserDocklet(); helpDock->browser()->gotoHelpForMethod(className, methodName); helpDock->focus(); return true; #else // SC_USE_QTWEBENGINE return false; #endif // SC_USE_QTWEBENGINE } void Main::openDefinition(const QString& string, QWidget* parent) { QString definitionString = string.trimmed(); LookupDialog dialog(parent); if (!definitionString.isEmpty()) dialog.query(definitionString); dialog.exec(); } void Main::openCommandLine(const QString& string) { MainWindow::instance()->showCmdLine(string); } void Main::findReferences(const QString& string, QWidget* parent) { QString definitionString = string.trimmed(); ReferencesDialog dialog(parent); if (!definitionString.isEmpty()) dialog.query(definitionString); dialog.exec(); }
7,794
C++
.cpp
197
33.426396
118
0.682245
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
30,004
sc_lexer.cpp
supercollider_supercollider/editors/sc-ide/core/sc_lexer.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "sc_lexer.hpp" #include <QDebug> namespace ScIDE { QVector<ScLexer::LexicalRule> ScLexer::mLexicalRules; void ScLexer::initLexicalRules() { /* NOTE: Order is important: -- floatRegexp is subset of radixFloatRegex -> must come later -- classRegexp and primitiveRegexp are subsets of symbolArgRegexp -> must come later */ mLexicalRules << LexicalRule(Token::WhiteSpace, "\\s+"); initKeywordsRules(); initBuiltinsRules(); mLexicalRules << LexicalRule(Token::RadixFloat, "\\b\\d+r[0-9a-zA-Z]*(\\.[0-9A-Z]*)?"); // Never heard of this one? Check the "Literals" help file :) mLexicalRules << LexicalRule(Token::ScaleDegreeFloat, "\\b\\d+(s+|b+|[sb]\\d+)\\b"); // do not include leading "-" in Float, as left-to-right algorithm does // not know whether it is not rather a binary operator mLexicalRules << LexicalRule(Token::Float, "\\b((\\d+(\\.\\d+)?([eE][-+]?\\d+)?(pi)?)|pi)\\b"); mLexicalRules << LexicalRule(Token::HexInt, "\\b0x(\\d|[a-f]|[A-F])+"); mLexicalRules << LexicalRule(Token::SymbolArg, "\\b[A-Za-z_]\\w*\\:"); mLexicalRules << LexicalRule(Token::Name, "[a-z]\\w*"); mLexicalRules << LexicalRule(Token::Class, "\\b[A-Z]\\w*"); mLexicalRules << LexicalRule(Token::Primitive, "\\b_\\w+"); mLexicalRules << LexicalRule(Token::Symbol, "\\\\\\w*"); mLexicalRules << LexicalRule(Token::Char, "\\$\\\\?."); mLexicalRules << LexicalRule(Token::EnvVar, "~\\w+"); mLexicalRules << LexicalRule(Token::SingleLineComment, "//[^\r\n]*"); mLexicalRules << LexicalRule(Token::MultiLineCommentStart, "/\\*"); mLexicalRules << LexicalRule(Token::Operator, "[+\\-*/&|\\^%<>=]+"); } void ScLexer::initKeywordsRules() { QStringList keywords; keywords << "arg" << "classvar" << "const" << "super" << "this" << "var"; QString keywordPattern = QStringLiteral("\\b(%1)\\b").arg(keywords.join("|")); mLexicalRules << LexicalRule(Token::Keyword, keywordPattern); } void ScLexer::initBuiltinsRules() { QStringList builtins; builtins << "false" << "inf" << "nil" << "true" << "thisFunction" << "thisFunctionDef" << "thisMethod" << "thisProcess" << "thisThread" << "currentEnvironment" << "topEnvironment"; QString builtinsPattern = QStringLiteral("\\b(%1)\\b").arg(builtins.join("|")); mLexicalRules << LexicalRule(Token::Builtin, builtinsPattern); } Token::Type ScLexer::nextToken(int& lengthResult) { Q_ASSERT(mOffset < mText.size()); switch (mState) { case InCode: return nextTokenInCode(lengthResult); case InString: return nextTokenInString(lengthResult); case InSymbol: return nextTokenInSymbol(lengthResult); default: if (mState >= InComment) return nextTokenInComment(lengthResult); } lengthResult = 0; return Token::Unknown; } Token::Type ScLexer::nextTokenInCode(int& lengthResult) { static QString openingBrackets("({["); static QString closingBrackets(")}]"); static QChar stringMark('\"'); static QChar symbolMark('\''); QChar currentChar = mText[mOffset]; Token::Type type = Token::Unknown; int length = 1; if (currentChar == stringMark) { type = Token::StringMark; mState = InString; } else if (currentChar == symbolMark) { type = Token::SymbolMark; if (mOffset + 1 < mText.size()) // line break ends a symbol mState = InSymbol; } else if (openingBrackets.contains(currentChar)) { type = Token::OpeningBracket; } else if (closingBrackets.contains(currentChar)) { type = Token::ClosingBracket; } else { QVector<LexicalRule>::const_iterator it = mLexicalRules.constBegin(); QVector<LexicalRule>::const_iterator end = mLexicalRules.constEnd(); for (; it != end; ++it) { LexicalRule const& rule = *it; QRegularExpressionMatch match = rule.expr.match(mText, mOffset, QRegularExpression::NormalMatch, QRegularExpression::AnchoredMatchOption); if (match.hasMatch()) { // a guard to ensure all regexps match only at the beginning of the string: Q_ASSERT(match.capturedStart() == mOffset); type = rule.type; length = match.capturedLength(); break; } } if (type == Token::MultiLineCommentStart) mState = InComment; } length = qMax(length, 1); // process at least 1 char mOffset += length; lengthResult = length; return type; } Token::Type ScLexer::nextTokenInString(int& length) { // TODO: Provide simple tokenization by word delimiters static QChar stringMark('"'); static QChar escapeChar('\\'); length = 0; Token::Type type = Token::Unknown; int textLength = mText.length(); while (mOffset < textLength) { QChar chr = mText[mOffset]; ++mOffset; if (chr == escapeChar) { ++mOffset; } else if (chr == stringMark) { length = 1; type = Token::StringMark; mState = InCode; break; } } mOffset = qMin(mOffset, textLength); return type; } Token::Type ScLexer::nextTokenInSymbol(int& length) { // TODO: Provide simple tokenization by word delimiters static QChar symbolMark('\''); static QChar escapeChar('\\'); length = 0; Token::Type type = Token::Unknown; int textLength = mText.length(); while (mOffset < textLength) { QChar chr = mText[mOffset]; ++mOffset; if (chr == escapeChar) { ++mOffset; } else if (chr == symbolMark) { length = 1; type = Token::SymbolMark; break; } } mOffset = qMin(mOffset, textLength); mState = InCode; return type; } Token::Type ScLexer::nextTokenInComment(int& lengthResult) { // TODO: Provide tokenization using (some) lexical rules for code int index = mOffset; int maxIndex = mText.size() - 1; static const QString commentStart("/*"); static const QString commentEnd("*/"); int commentStartIndex = -2; int commentEndIndex = -2; while (index < maxIndex) { if ((commentStartIndex == -2) || (commentStartIndex < index)) if (commentStartIndex != -1) commentStartIndex = mText.indexOf(commentStart, index); if ((commentEndIndex == -2) || (commentEndIndex < index)) if (commentEndIndex != -1) commentEndIndex = mText.indexOf(commentEnd, index); if (commentStartIndex == -1) { if (commentEndIndex == -1) { index = maxIndex; } else { index = commentEndIndex + 2; --mState; } } else { if (commentEndIndex == -1) { index = commentStartIndex + 2; ++mState; } else { if (commentStartIndex < commentEndIndex) { index = commentStartIndex + 2; ++mState; } else { index = commentEndIndex + 2; --mState; } } } if (mState < InComment) { mState = InCode; break; } } if (mState == InCode) { mOffset = index; lengthResult = 2; return Token::MultiLineCommentEnd; } mOffset = mText.size(); lengthResult = 0; return Token::Unknown; } }
8,674
C++
.cpp
227
29.894273
108
0.596661
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
30,005
sc_process.cpp
supercollider_supercollider/editors/sc-ide/core/sc_process.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <QBuffer> #include <QCoreApplication> #include <QtCore/QFuture> #include <QtCore/QFutureWatcher> #include <QTextDocumentFragment> #include <QtConcurrent> #include "main.hpp" #include "main_window.hpp" #include "sc_introspection.hpp" #include "sc_process.hpp" #include "sc_server.hpp" #include "settings/manager.hpp" #include "util/standard_dirs.hpp" #include "../primitives/localsocket_utils.hpp" #include <yaml-cpp/node/node.h> #include <yaml-cpp/parser.h> namespace ScIDE { ScProcess::ScProcess(Settings::Manager* settings, QObject* parent): QProcess(parent), mIpcServer(new QLocalServer(this)), mIpcSocket(NULL), mIpcServerName("SCIde_" + QString::number(QCoreApplication::applicationPid())), mTerminationRequested(false), mCompiled(false) { prepareActions(settings); connect(this, SIGNAL(readyRead()), this, SLOT(onReadyRead())); connect(mIpcServer, SIGNAL(newConnection()), this, SLOT(onNewIpcConnection())); connect(this, SIGNAL(stateChanged(QProcess::ProcessState)), this, SLOT(onProcessStateChanged(QProcess::ProcessState))); } void ScProcess::prepareActions(Settings::Manager* settings) { QAction* action; const QString interpreterCategory(tr("Interpreter")); mActions[ToggleRunning] = action = new QAction(tr("Boot or Quit Interpreter"), this); // the default QAction::TextHeuristicRole incorrectly detects a quit role on macOS action->setMenuRole(QAction::NoRole); connect(action, SIGNAL(triggered()), this, SLOT(toggleRunning())); // settings->addAction( action, "interpreter-toggle-running", interpreterCategory); mActions[Start] = action = new QAction(QIcon::fromTheme("system-run"), tr("Boot Interpreter"), this); connect(action, SIGNAL(triggered()), this, SLOT(startLanguage())); settings->addAction(action, "interpreter-start", interpreterCategory); mActions[Stop] = action = new QAction(QIcon::fromTheme("system-shutdown"), tr("Quit Interpreter"), this); connect(action, SIGNAL(triggered()), this, SLOT(stopLanguage())); settings->addAction(action, "interpreter-stop", interpreterCategory); mActions[Restart] = action = new QAction(QIcon::fromTheme("system-reboot"), tr("Reboot Interpreter"), this); connect(action, SIGNAL(triggered()), this, SLOT(restartLanguage())); settings->addAction(action, "interpreter-restart", interpreterCategory); mActions[RecompileClassLibrary] = action = new QAction(QIcon::fromTheme("system-reboot"), tr("Recompile Class Library"), this); action->setShortcut(tr("Ctrl+Shift+l", "Recompile Class Library)")); connect(action, SIGNAL(triggered()), this, SLOT(recompileClassLibrary())); settings->addAction(action, "interpreter-recompile-lib", interpreterCategory); mActions[StopMain] = action = new QAction(QIcon::fromTheme("media-playback-stop"), tr("Stop"), this); action->setShortcut(tr("Ctrl+.", "Stop (a.k.a. cmd-period)")); action->setShortcutContext(Qt::ApplicationShortcut); connect(action, SIGNAL(triggered()), this, SLOT(stopMain())); settings->addAction(action, "interpreter-main-stop", interpreterCategory); mActions[ShowQuarks] = action = new QAction(tr("Quarks"), this); connect(action, SIGNAL(triggered()), this, SLOT(showQuarks())); settings->addAction(action, "interpreter-show-quarks-gui", interpreterCategory); connect(mActions[Start], SIGNAL(changed()), this, SLOT(updateToggleRunningAction())); connect(mActions[Stop], SIGNAL(changed()), this, SLOT(updateToggleRunningAction())); onProcessStateChanged(QProcess::NotRunning); } void ScProcess::updateToggleRunningAction() { QAction* targetAction = state() == QProcess::NotRunning ? mActions[Start] : mActions[Stop]; mActions[ToggleRunning]->setText(targetAction->text()); mActions[ToggleRunning]->setIcon(targetAction->icon()); mActions[ToggleRunning]->setShortcut(targetAction->shortcut()); } void ScProcess::toggleRunning() { switch (state()) { case NotRunning: startLanguage(); break; default: stopLanguage(); } } void ScProcess::startLanguage(void) { if (state() != QProcess::NotRunning) { statusMessage(tr("Interpreter is already running.")); return; } Settings::Manager* settings = Main::settings(); settings->beginGroup("IDE/interpreter"); QString workingDirectory = settings->value("runtimeDir").toString(); QString configFile = settings->value("configFile").toString(); settings->endGroup(); QString sclangCommand; #ifdef Q_OS_MAC sclangCommand = standardDirectory(ScResourceDir) + "/../MacOS/sclang"; #else sclangCommand = "sclang"; #endif QStringList sclangArguments; if (!configFile.isEmpty()) sclangArguments << "-l" << configFile; sclangArguments << "-i" << "scqt"; if (!workingDirectory.isEmpty()) setWorkingDirectory(workingDirectory); QProcess::start(sclangCommand, sclangArguments); bool processStarted = QProcess::waitForStarted(); if (!processStarted) emit statusMessage(tr("Failed to start interpreter!")); } void ScProcess::recompileClassLibrary(void) { if (state() != QProcess::Running) { emit statusMessage(tr("Interpreter is not running!")); return; } mCompiled = false; write("\x18"); } void ScProcess::stopLanguage(void) { if (state() != QProcess::Running) { emit statusMessage(tr("Interpreter is not running!")); return; } evaluateCode("0.exit", true); mCompiled = false; mTerminationRequested = true; mTerminationRequestTime = QDateTime::currentDateTimeUtc(); bool finished = waitForFinished(1000); if (!finished && (state() != QProcess::NotRunning)) { terminate(); bool reallyFinished = waitForFinished(200); if (!reallyFinished) emit statusMessage(tr("Failed to stop interpreter!")); } closeWriteChannel(); mTerminationRequested = false; } void ScProcess::restartLanguage() { mCompiled = false; stopLanguage(); startLanguage(); } void ScProcess::stopMain(void) { evaluateCode("thisProcess.stop", true); } void ScProcess::showQuarks(void) { evaluateCode("Quarks.gui", true); } void ScProcess::onReadyRead(void) { if (mTerminationRequested) { // when stopping the language, we don't want to post for longer than 200 ms to prevent the UI to freeze if (QDateTime::currentDateTimeUtc().toMSecsSinceEpoch() - mTerminationRequestTime.toMSecsSinceEpoch() > 200) return; } QByteArray out = QProcess::readAll(); QString postString = QString::fromUtf8(out); emit scPost(postString); } void ScProcess::evaluateCode(QString const& commandString, bool silent) { if (state() != QProcess::Running) { emit statusMessage(tr("Interpreter is not running!")); return; } QByteArray bytesToWrite = commandString.toUtf8(); size_t writtenBytes = write(bytesToWrite); if (writtenBytes != bytesToWrite.size()) { emit statusMessage(tr("Error when passing data to interpreter!")); return; } char commandChar = silent ? '\x1b' : '\x0c'; write(&commandChar, 1); } void ScProcess::onNewIpcConnection() { if (mIpcSocket) // we can handle only one ipc connection at a time mIpcSocket->disconnect(); mIpcSocket = mIpcServer->nextPendingConnection(); connect(mIpcSocket, SIGNAL(disconnected()), this, SLOT(finalizeConnection())); connect(mIpcSocket, SIGNAL(readyRead()), this, SLOT(onIpcData())); } void ScProcess::finalizeConnection() { mIpcData.clear(); mIpcSocket->deleteLater(); mIpcSocket = NULL; } void ScProcess::onProcessStateChanged(QProcess::ProcessState state) { switch (state) { case QProcess::Starting: mActions[Start]->setEnabled(false); mActions[Stop]->setEnabled(true); mActions[Restart]->setEnabled(true); updateToggleRunningAction(); break; case QProcess::Running: mActions[StopMain]->setEnabled(true); mActions[ShowQuarks]->setEnabled(true); mActions[RecompileClassLibrary]->setEnabled(true); onStart(); break; case QProcess::NotRunning: mActions[Start]->setEnabled(true); mActions[Stop]->setEnabled(false); mActions[Restart]->setEnabled(false); mActions[StopMain]->setEnabled(false); mActions[ShowQuarks]->setEnabled(false); mActions[RecompileClassLibrary]->setEnabled(false); updateToggleRunningAction(); postQuitNotification(); mCompiled = false; break; } } void ScProcess::postQuitNotification() { QString message; switch (exitStatus()) { case QProcess::CrashExit: message = tr("Interpreter has crashed or stopped forcefully. [Exit code: %1]\n").arg(exitCode()); break; default: message = tr("Interpreter has quit. [Exit code: %1]\n").arg(exitCode()); } emit scPost(message); } void ScProcess::onIpcData() { mIpcData.append(mIpcSocket->readAll()); // After we have put the data in the buffer, process it int avail = mIpcData.length(); do { if (mReadSize == 0 && avail > 4) { mReadSize = ArrayToInt(mIpcData.left(4)); mIpcData.remove(0, 4); avail -= 4; } if (mReadSize > 0 && avail >= mReadSize) { QByteArray baReceived(mIpcData.left(mReadSize)); mIpcData.remove(0, mReadSize); avail -= mReadSize; mReadSize = 0; QDataStream in(baReceived); in.setVersion(QDataStream::Qt_4_6); QString selector, message; in >> selector; if (in.status() != QDataStream::Ok) return; in >> message; if (in.status() != QDataStream::Ok) return; onResponse(selector, message); emit response(selector, message); } } while ((mReadSize == 0 && avail > 4) || (mReadSize > 0 && avail > mReadSize)); } void ScProcess::onResponse(const QString& selector, const QString& data) { if (selector == QStringLiteral("introspection")) { using ScLanguage::Introspection; auto watcher = new QFutureWatcher<Introspection>(this); connect(watcher, &QFutureWatcher<Introspection>::finished, [=] { try { Introspection newIntrospection = watcher->result(); mIntrospection = std::move(newIntrospection); emit introspectionChanged(); } catch (std::exception& e) { MainWindow::instance()->showStatusMessage(e.what()); } watcher->deleteLater(); }); // Start the computation. QFuture<Introspection> future = QtConcurrent::run([](QString data) { return ScLanguage::Introspection(data); }, data); watcher->setFuture(future); } else if (selector == QStringLiteral("classLibraryRecompiled")) { mCompiled = true; emit classLibraryRecompiled(); } else if (selector == QStringLiteral("requestCurrentPath")) Main::documentManager()->sendActiveDocument(); } void ScProcess::onStart() { if (!mIpcServer->isListening()) // avoid a warning on stderr mIpcServer->listen(mIpcServerName); QString command = QStringLiteral("ScIDE.connect(\"%1\")").arg(mIpcServerName); evaluateCode(command, true); Main::documentManager()->sendActiveDocument(); } void ScProcess::updateTextMirrorForDocument(Document* doc, int position, int charsRemoved, int charsAdded) { if (!mIpcSocket) return; if (mIpcSocket->state() != QLocalSocket::ConnectedState) return; QVariantList argList; argList.append(QVariant(doc->id())); argList.append(QVariant(position)); argList.append(QVariant(charsRemoved)); QTextCursor cursor = QTextCursor(doc->textDocument()); cursor.setPosition(position, QTextCursor::MoveAnchor); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, charsAdded); argList.append(QVariant(cursor.selection().toPlainText())); try { sendSelectorAndData(mIpcSocket, QStringLiteral("updateDocText"), argList); } catch (std::exception const& e) { scPost(QStringLiteral("Exception during ScIDE_Send: %1\n").arg(e.what())); } } void ScProcess::updateSelectionMirrorForDocument(Document* doc, int start, int range) { if (!mIpcSocket) return; if (mIpcSocket->state() != QLocalSocket::ConnectedState) return; QVariantList argList; argList.append(QVariant(doc->id())); argList.append(QVariant(start)); argList.append(QVariant(range)); try { sendSelectorAndData(mIpcSocket, QStringLiteral("updateDocSelection"), argList); } catch (std::exception const& e) { scPost(QStringLiteral("Exception during ScIDE_Send: %1\n").arg(e.what())); } } } // namespace ScIDE
13,865
C++
.cpp
323
36.804954
116
0.689302
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,006
sc_server.cpp
supercollider_supercollider/editors/sc-ide/core/sc_server.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <QDebug> #include <QWidgetAction> #include "sc_server.hpp" #include "sc_process.hpp" #include "main.hpp" #include "../widgets/util/volume_widget.hpp" #include <yaml-cpp/yaml.h> #include <sstream> #include <iomanip> #include <boost/chrono/chrono_io.hpp> #include <osc/OscReceivedElements.h> #include <osc/OscOutboundPacketStream.h> using namespace std; using namespace boost::chrono; namespace ScIDE { ScServer::ScServer(ScProcess* scLang, Settings::Manager* settings, QObject* parent): QObject(parent), mLang(scLang), mPort(0), mIsRecording(false) { createActions(settings); mUdpSocket = new QUdpSocket(this); startTimer(333); connect(scLang, SIGNAL(stateChanged(QProcess::ProcessState)), this, SLOT(onScLangStateChanged(QProcess::ProcessState))); connect(scLang, SIGNAL(response(QString, QString)), this, SLOT(onScLangReponse(QString, QString))); connect(mUdpSocket, SIGNAL(readyRead()), this, SLOT(onServerDataArrived())); } void ScServer::createActions(Settings::Manager* settings) { const QString synthServerCategory(tr("Sound Synthesis Server")); QAction* action; QWidgetAction* widgetAction; mActions[ToggleRunning] = action = new QAction(tr("Boot or quit default server"), this); // the default QAction::TextHeuristicRole incorrectly detects a quit role on macOS action->setMenuRole(QAction::NoRole); connect(action, SIGNAL(triggered()), this, SLOT(toggleRunning())); // settings->addAction( action, "synth-server-toggle-running", synthServerCategory); mActions[Boot] = action = new QAction(QIcon::fromTheme("system-run"), tr("&Boot Server"), this); action->setShortcut(tr("Ctrl+B", "Boot default server")); connect(action, SIGNAL(triggered()), this, SLOT(boot())); settings->addAction(action, "synth-server-boot", synthServerCategory); mActions[Quit] = action = new QAction(QIcon::fromTheme("system-shutdown"), tr("&Quit Server"), this); connect(action, SIGNAL(triggered()), this, SLOT(quit())); settings->addAction(action, "synth-server-quit", synthServerCategory); mActions[KillAll] = action = new QAction(QIcon::fromTheme("system-killall"), tr("&Kill All Servers"), this); connect(action, SIGNAL(triggered()), this, SLOT(killAll())); settings->addAction(action, "synth-server-killall", synthServerCategory); mActions[Reboot] = action = new QAction(QIcon::fromTheme("system-reboot"), tr("&Reboot Server"), this); connect(action, SIGNAL(triggered()), this, SLOT(reboot())); settings->addAction(action, "synth-server-reboot", synthServerCategory); mActions[ShowMeters] = action = new QAction(tr("Show Server Meter"), this); action->setShortcut(tr("Ctrl+M", "Show server meter")); connect(action, SIGNAL(triggered()), this, SLOT(showMeters())); settings->addAction(action, "synth-server-meter", synthServerCategory); mActions[ShowScope] = action = new QAction(tr("Show Scope"), this); action->setShortcut(tr("Ctrl+Shift+M", "Show scope")); connect(action, SIGNAL(triggered()), this, SLOT(showScope())); settings->addAction(action, "synth-server-scope", synthServerCategory); mActions[ShowFreqScope] = action = new QAction(tr("Show Freqscope"), this); action->setShortcut(tr("Ctrl+Alt+M", "Show freqscope")); connect(action, SIGNAL(triggered()), this, SLOT(showFreqScope())); settings->addAction(action, "synth-server-freqscope", synthServerCategory); mActions[DumpNodeTree] = action = new QAction(tr("Dump Node Tree"), this); action->setShortcut(tr("Ctrl+T", "Dump node tree")); connect(action, SIGNAL(triggered()), this, SLOT(dumpNodeTree())); settings->addAction(action, "synth-server-dump-nodes", synthServerCategory); mActions[DumpNodeTreeWithControls] = action = new QAction(tr("Dump Node Tree with Controls"), this); action->setShortcut(tr("Ctrl+Shift+T", "Dump node tree with controls")); connect(action, SIGNAL(triggered()), this, SLOT(dumpNodeTreeWithControls())); settings->addAction(action, "synth-server-dump-nodes-with-controls", synthServerCategory); mActions[PlotTree] = action = new QAction(tr("Show Node Tree"), this); action->setShortcut(tr("Ctrl+Alt+T", "Show node tree")); connect(action, SIGNAL(triggered()), this, SLOT(plotTree())); settings->addAction(action, "synth-server-plot-tree", synthServerCategory); mActions[DumpOSC] = action = new QAction(tr("Server Dump OSC"), this); action->setCheckable(true); connect(action, SIGNAL(triggered(bool)), this, SLOT(sendDumpingOSC(bool))); settings->addAction(action, "synth-server-dumpOSC", synthServerCategory); mActions[Mute] = action = new QAction(tr("Mute"), this); action->setShortcut(tr("Ctrl+Alt+End", "Mute sound output.")); action->setCheckable(true); connect(action, SIGNAL(triggered(bool)), this, SLOT(sendMuted(bool))); connect(action, SIGNAL(toggled(bool)), this, SIGNAL(mutedChanged(bool))); settings->addAction(action, "synth-server-mute", synthServerCategory); mVolumeWidget = new VolumeWidget; mActions[Volume] = widgetAction = new QWidgetAction(this); widgetAction->setDefaultWidget(mVolumeWidget); connect(mVolumeWidget, &VolumeWidget::volumeChangeRequested, [this](float newValue) { setVolume(newValue); }); connect(this, SIGNAL(volumeChanged(float)), mVolumeWidget, SLOT(setVolume(float))); connect(this, SIGNAL(volumeRangeChanged(float, float)), mVolumeWidget, SLOT(setVolumeRange(float, float))); emit volumeChanged(mVolume); emit volumeRangeChanged(mVolumeMin, mVolumeMax); mActions[VolumeUp] = action = new QAction(tr("Increase Volume"), this); action->setShortcut(tr("Ctrl+Alt+PgUp", "Increase volume")); connect(action, SIGNAL(triggered()), this, SLOT(increaseVolume())); settings->addAction(action, "synth-server-volume-up", synthServerCategory); mActions[VolumeDown] = action = new QAction(tr("Decrease Volume"), this); action->setShortcut(tr("Ctrl+Alt+PgDown", "Decrease volume")); connect(action, SIGNAL(triggered()), this, SLOT(decreaseVolume())); settings->addAction(action, "synth-server-volume-down", synthServerCategory); mActions[VolumeRestore] = action = new QAction(tr("Restore Volume to 0 dB"), this); action->setShortcut(tr("Ctrl+Alt+Home", "Restore volume")); connect(action, SIGNAL(triggered()), this, SLOT(restoreVolume())); settings->addAction(action, "synth-server-volume-restore", synthServerCategory); mActions[Record] = action = new QAction(tr("Recording"), this); action->setCheckable(true); connect(action, SIGNAL(triggered(bool)), this, SLOT(sendRecording(bool))); connect(action, SIGNAL(toggled(bool)), this, SIGNAL(recordingChanged(bool))); settings->addAction(action, "synth-server-record", synthServerCategory); mActions[PauseRecord] = action = new QAction(tr("Pause Recording"), this); action->setCheckable(true); connect(action, SIGNAL(triggered(bool)), this, SLOT(pauseRecording(bool))); connect(action, SIGNAL(toggled(bool)), this, SIGNAL(pauseChanged(bool))); settings->addAction(action, "synth-server-pause-recording", synthServerCategory); connect(mActions[Boot], SIGNAL(changed()), this, SLOT(updateToggleRunningAction())); connect(mActions[Quit], SIGNAL(changed()), this, SLOT(updateToggleRunningAction())); updateToggleRunningAction(); updateRecordingAction(); updateEnabledActions(); } void ScServer::updateToggleRunningAction() { QAction* targetAction = isRunning() ? mActions[Quit] : mActions[Boot]; mActions[ToggleRunning]->setText(targetAction->text()); mActions[ToggleRunning]->setIcon(targetAction->icon()); mActions[ToggleRunning]->setShortcut(targetAction->shortcut()); } void ScServer::boot() { if (isRunning()) return; mLang->evaluateCode("ScIDE.defaultServer.boot", true); } void ScServer::quit() { if (!isRunning()) return; mLang->evaluateCode("ScIDE.defaultServer.quit", true); } void ScServer::killAll() { mLang->evaluateCode("Server.killAll", true); } void ScServer::reboot() { mLang->evaluateCode("ScIDE.defaultServer.reboot", true); } void ScServer::toggleRunning() { if (isRunning()) quit(); else boot(); } void ScServer::showMeters() { mLang->evaluateCode("ScIDE.defaultServer.meter", true); } void ScServer::showScope() { mLang->evaluateCode("ScIDE.defaultServer.scope(ScIDE.defaultServer.options.numOutputBusChannels)", true); } void ScServer::showFreqScope() { mLang->evaluateCode("ScIDE.defaultServer.freqscope", true); } void ScServer::dumpNodeTree() { queryAllNodes(false); } void ScServer::dumpNodeTreeWithControls() { queryAllNodes(true); } void ScServer::queryAllNodes(bool dumpControls) { QString arg = dumpControls ? QStringLiteral("true") : QStringLiteral("false"); mLang->evaluateCode(QStringLiteral("ScIDE.defaultServer.queryAllNodes(%1)").arg(arg), true); } void ScServer::plotTree() { mLang->evaluateCode("ScIDE.defaultServer.plotTree", true); } bool ScServer::isMuted() const { return mActions[Mute]->isChecked(); } void ScServer::setMuted(bool muted) { mActions[Mute]->setChecked(muted); sendMuted(muted); } bool ScServer::isDumpingOSC() const { return mActions[DumpOSC]->isChecked(); } void ScServer::setDumpingOSC(bool dumping) { mActions[DumpOSC]->setChecked(dumping); sendDumpingOSC(dumping); } float ScServer::volume() const { return mVolume; } void ScServer::setVolume(float volume) { volume = qBound(mVolumeMin, volume, mVolumeMax); if (volume != mVolume) { mVolume = volume; sendVolume(volume); emit volumeChanged(volume); } } void ScServer::setVolumeRange(float min, float max) { mVolumeMin = min; mVolumeMax = max; emit volumeRangeChanged(min, max); } void ScServer::increaseVolume() { changeVolume(+1.5); } void ScServer::decreaseVolume() { changeVolume(-1.5); } void ScServer::changeVolume(float difference) { setVolume(volume() + difference); } void ScServer::restoreVolume() { setVolume(0.0f); unmute(); } void ScServer::sendMuted(bool muted) { static const QString muteCommand("ScIDE.defaultServer.mute"); static const QString unmuteCommand("ScIDE.defaultServer.unmute"); mLang->evaluateCode(muted ? muteCommand : unmuteCommand, true); } void ScServer::sendDumpingOSC(bool dumping) { static const QString dumpCommand("ScIDE.defaultServer.dumpOSC(true)"); static const QString stopDumpCommand("ScIDE.defaultServer.dumpOSC(false)"); mLang->evaluateCode(dumping ? dumpCommand : stopDumpCommand, true); } void ScServer::sendVolume(float volume) { mLang->evaluateCode(QStringLiteral("ScIDE.setServerVolume(%1)").arg(volume), true); } bool ScServer::isRecording() const { return mIsRecording; } bool ScServer::isPaused() const { return mIsRecordingPaused; } void ScServer::setRecording(bool doRecord) { if (!isRunning()) return; mIsRecording = doRecord; mIsRecordingPaused = false; updateRecordingAction(); } void ScServer::pauseRecording(bool flag) { if (mIsRecordingPaused != flag) { mIsRecordingPaused = flag; if (flag) { mLang->evaluateCode(QStringLiteral("ScIDE.defaultServer.pauseRecording"), true); } else { if (mIsRecording) { setRecording(true); sendRecording(true); } } updateRecordingAction(); } } void ScServer::sendRecording(bool doRecord) { static const QString startRecordingCommand("ScIDE.defaultServer.record"); static const QString stopRecordingCommand("ScIDE.defaultServer.stopRecording"); setRecording(doRecord); mLang->evaluateCode(doRecord ? startRecordingCommand : stopRecordingCommand); } void ScServer::updateRecordingAction() { if (isRecording()) { int s = mRecordingSeconds % 60; int m = mRecordingSeconds / 60 % 60; int h = mRecordingSeconds / 3600; ostringstream msg; msg << "Recording: "; msg << setw(2) << setfill('0') << h << ':'; msg << setw(2) << setfill('0') << m << ':'; msg << setw(2) << setfill('0') << s; mActions[Record]->setText(msg.str().c_str()); } else { mRecordingSeconds = 0; mActions[Record]->setText("Start Recording"); mIsRecordingPaused = false; } mActions[Record]->setChecked(isRecording()); mActions[PauseRecord]->setChecked(mIsRecordingPaused); } void ScServer::onScLangStateChanged(QProcess::ProcessState) { updateEnabledActions(); } void ScServer::onScLangReponse(const QString& selector, const QString& data) { static QString defaultServerRunningChangedSelector("defaultServerRunningChanged"); static QString mutedSelector("serverMuted"); static QString unmutedSelector("serverUnmuted"); static QString ampSelector("serverAmp"); static QString ampRangeSelector("serverAmpRange"); static QString startDumpOSCSelector("dumpOSCStarted"); static QString stopDumpOSCSelector("dumpOSCStopped"); static QString startRecordingSelector("recordingStarted"); static QString pauseRecordingSelector("recordingPaused"); static QString stopRecordingSelector("recordingStopped"); static QString recordingDurationSelector("recordingDuration"); if (selector == defaultServerRunningChangedSelector) handleRuningStateChangedMsg(data); else if (selector == mutedSelector) { mActions[Mute]->setChecked(true); } else if (selector == unmutedSelector) { mActions[Mute]->setChecked(false); } else if (selector == startDumpOSCSelector) { mActions[DumpOSC]->setChecked(true); } else if (selector == stopDumpOSCSelector) { mActions[DumpOSC]->setChecked(false); } else if (selector == recordingDurationSelector) { bool ok; float duration = data.mid(1, data.size() - 2).toFloat(&ok); if (ok) { mRecordingSeconds = (int)duration; updateRecordingAction(); } } else if (selector == startRecordingSelector) { setRecording(true); } else if (selector == startRecordingSelector) { setRecording(true); } else if (selector == pauseRecordingSelector) { pauseRecording(true); } else if (selector == stopRecordingSelector) { setRecording(false); } else if (selector == ampSelector) { bool ok; float volume = data.mid(1, data.size() - 2).toFloat(&ok); if (ok) { mVolume = volume; emit volumeChanged(volume); } } else if (selector == ampRangeSelector) { bool ok; QStringList dataList = data.mid(1, data.size() - 2).split(','); if (dataList.size() < 2) return; float min = dataList[0].toFloat(&ok); if (!ok) return; float max = dataList[1].toFloat(&ok); if (!ok) return; mVolumeMin = min; mVolumeMax = max; setVolumeRange(min, max); } } void ScServer::handleRuningStateChangedMsg(const QString& data) { bool serverRunningState = false; bool serverUnresponsive = false; std::string hostName; int port = -1; try { const YAML::Node doc = YAML::Load(data.toStdString()); if (doc) { assert(doc.IsSequence()); serverRunningState = doc[0].as<bool>(); hostName = doc[1].as<std::string>(); port = doc[2].as<int>(); serverUnresponsive = doc[3].as<bool>(); } } catch (...) { return; // LATER: report error? } QString qstrHostName(hostName.c_str()); onRunningStateChanged(serverRunningState, qstrHostName, port); emit runningStateChanged(serverRunningState, qstrHostName, port, serverUnresponsive); } void ScServer::timerEvent(QTimerEvent* event) { if (mPort) { char buffer[512]; osc::OutboundPacketStream stream(buffer, 512); stream << osc::BeginMessage("/status"); stream << osc::MessageTerminator(); qint64 sentSize = mUdpSocket->write(stream.Data(), stream.Size()); if (sentSize == -1) qCritical() << "Failed to send server status request:" << mUdpSocket->errorString(); } } void ScServer::onRunningStateChanged(bool running, QString const& hostName, int port) { if (running) { mServerAddress = QHostAddress(hostName); mPort = port; mUdpSocket->connectToHost(mServerAddress, mPort); } else { mServerAddress.clear(); mPort = 0; mIsRecording = false; mUdpSocket->disconnectFromHost(); } updateToggleRunningAction(); updateRecordingAction(); updateEnabledActions(); } void ScServer::onServerDataArrived() { while (mUdpSocket->hasPendingDatagrams()) { size_t datagramSize = mUdpSocket->pendingDatagramSize(); QByteArray array(datagramSize, 0); qint64 readSize = mUdpSocket->readDatagram(array.data(), datagramSize); if (readSize == -1) continue; processOscPacket(osc::ReceivedPacket(array.data(), datagramSize)); } } void ScServer::processOscMessage(const osc::ReceivedMessage& message) { if (strcmp(message.AddressPattern(), "/status.reply") == 0) { processServerStatusMessage(message); } } void ScServer::processServerStatusMessage(const osc::ReceivedMessage& message) { if (!isRunning()) return; osc::int32 unused; osc::int32 ugenCount; osc::int32 synthCount; osc::int32 groupCount; osc::int32 defCount; float avgCPU; float peakCPU; auto args = message.ArgumentStream(); try { args >> unused >> ugenCount >> synthCount >> groupCount >> defCount >> avgCPU >> peakCPU; } catch (osc::MissingArgumentException) { qCritical("Misformatted server status message."); return; } emit updateServerStatus(ugenCount, synthCount, groupCount, defCount, avgCPU, peakCPU); } void ScServer::updateEnabledActions() { bool langRunning = mLang->state() == QProcess::Running; bool langAndServerRunning = langRunning && isRunning(); mActions[ToggleRunning]->setEnabled(langRunning); mActions[KillAll]->setEnabled(langRunning); mActions[Reboot]->setEnabled(langRunning); mActions[ShowMeters]->setEnabled(langRunning); mActions[ShowScope]->setEnabled(langRunning); mActions[ShowFreqScope]->setEnabled(langRunning); mActions[DumpNodeTree]->setEnabled(langAndServerRunning); mActions[DumpNodeTreeWithControls]->setEnabled(langAndServerRunning); mActions[PlotTree]->setEnabled(langAndServerRunning); mActions[Mute]->setEnabled(langAndServerRunning); mActions[VolumeUp]->setEnabled(langAndServerRunning); mActions[VolumeDown]->setEnabled(langAndServerRunning); mActions[Volume]->setEnabled(langAndServerRunning); mActions[VolumeRestore]->setEnabled(langAndServerRunning); mActions[Record]->setEnabled(langAndServerRunning); mActions[PauseRecord]->setEnabled(langAndServerRunning); mActions[DumpOSC]->setEnabled(langAndServerRunning); } }
20,024
C++
.cpp
428
41.252336
114
0.708085
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,007
app_palette.cpp
supercollider_supercollider/editors/sc-ide/core/app_palette.cpp
/* SuperCollider Qt IDE Copyright (c) 2018 SuperCollider Team https://supercollider.github.io/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "main.hpp" #include "util/color.hpp" #include <QBrush> #include <cmath> using namespace ScIDE; void Main::setAppPaletteFromSettings() { const QTextCharFormat* format = &mSettings->getThemeVal("text"); // QPalette::Window = general background color. QColor window = format->background().color(); // QPalette::WindowText = general foreground color. QColor window_text = format->foreground().color(); // QPalette::Button = background color of buttons. QColor button = window; // QPalette::Light = shadow for disabled text. QColor disabled_shadow; // QPalette::Mid = background color for the help and log dock bars as well // as inactive tabs. // QPalette::Dark = background color around the "Auto Scroll" button. // We use the same color for Dark and Mid currently. QColor mid; // QPalette::Highlight = highlight background color, used on menus. QColor highlight; // QPalette::Disabled / QPalette::Text = the foreground color of disabled // text and the selection background color. QColor disabled_text; // QPalette::Shadow = color of dividers between docklets. QColor shadow; int value_difference = window.value() - window_text.value(); if (abs(value_difference) < 32) { // If we are on the darker end of the spectrum we lighten the background. if (window.value() < 127) { window = QColor::fromHsv(window.hue(), window.saturation(), window.value() + 32 - value_difference); } else { // Otherwise we can darken the foreground color. window_text = QColor::fromHsv(window_text.hue(), window_text.saturation(), window_text.value() - (32 - value_difference)); } } int window_value = window.value(); bool dark_on_light = window_text.value() < window_value; if (dark_on_light) { mid = color::darken(window, 23); highlight = color::darken(window, 50); // Disabled text is rendered twice, once in disabled text foreground // color and once with a "shadow" color. We base the disabled text // colors here off the background color, to make them pop less than // regular text. disabled_text = color::darken(window, 20); disabled_shadow = color::darken(window, 20); } else { // mid should pretty much always be darker than window -- subjectively, // it just looks nicer. However, some people set the background really // dark, and mid and window aren't distinguishable. Making mid lighter // than window tends to distractingly highlight mid-colored elements // (such as tabs), so it's not the best idea. // The best results, we decided, were to allow mid and window to be // indistinguishable for those people, and use other ways to // distinguish the selected tab. mid = color::darken(window, 20); highlight = color::lighten(window, 30); disabled_shadow = color::lighten(window, 40); disabled_text = color::lighten(window, 40); } // Shadow (borders between docklets -- see above) is just a hair darker // than mid. shadow = color::darken(mid, 15); // But sometimes window and mid are already both really dark, so we have to // make shadow lighter than window. if (abs(shadow.value() - window.value()) < 20) { shadow = color::lighten(window, 20); } QPalette palette = QPalette(QBrush(window_text), // windowText QBrush(button), // button QBrush(disabled_shadow), // light QBrush(mid), // dark QBrush(mid), // mid QBrush(window_text), // text QBrush(window_text), // bright_text QBrush(window), // base QBrush(window) // window ); palette.setBrush(QPalette::Disabled, QPalette::Text, QBrush(disabled_text)); palette.setBrush(QPalette::Shadow, QBrush(shadow)); palette.setBrush(QPalette::Highlight, QBrush(highlight)); palette.setBrush(QPalette::HighlightedText, QBrush(window_text)); qApp->setPalette(palette); }
5,166
C++
.cpp
103
41.543689
112
0.649276
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,008
main_function.cpp
supercollider_supercollider/editors/sc-ide/core/main_function.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "main.hpp" #include "session_manager.hpp" #include "util/standard_dirs.hpp" #include "../widgets/main_window.hpp" #include <QApplication> #include <QLibraryInfo> #include <QTranslator> #include <QStyleFactory> #include "util/HelpBrowserWebSocketServices.hpp" #include <iostream> #include <string> using namespace ScIDE; static void show_usage(std::string name) { std::cerr << "Usage: " << name << " <option(s)> [file1.scd file2.scd ...]\n" << "Options:\n" << "\t-h, --help\tShow this help message\n" << std::endl; } int main(int argc, char* argv[]) { for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; if ((arg == "-h") || (arg == "--help")) { show_usage(argv[0]); return 0; } } #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif // In order to scale the UI properly on Windows with display scaling like 125% or 150% // we need to disable scale factor rounding QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); QApplication app(argc, argv); QStringList arguments(QApplication::arguments()); arguments.pop_front(); // application path // Pass files to existing instance and quit SingleInstanceGuard guard; if (guard.tryConnect(arguments)) return 0; // Set up translations QTranslator qtTranslator; #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); #else qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::path(QLibraryInfo::TranslationsPath)); #endif app.installTranslator(&qtTranslator); QString ideTranslationPath = standardDirectory(ScResourceDir) + "/translations"; bool translationLoaded; // Load fallback translator that only handles plural forms in English QTranslator fallbackTranslator; translationLoaded = fallbackTranslator.load("scide", ideTranslationPath); app.installTranslator(&fallbackTranslator); if (!translationLoaded) qWarning("scide warning: Failed to load fallback translation file."); // Load translator for locale const QLocale locale; QTranslator scideTranslator; scideTranslator.load(locale, "scide", "_", ideTranslationPath); app.installTranslator(&scideTranslator); // Force Fusion style to appear consistently on all platforms. app.setStyle(QStyleFactory::create("Fusion")); // Palette must be set before style, for consistent application. Main* main = Main::instance(); main->setAppPaletteFromSettings(); // Install style proxy. app.setStyle(new ScIDE::Style(app.style())); // Go... MainWindow* win = new MainWindow(main); // NOTE: load session after GUI is created, so that GUI can respond Settings::Manager* settings = main->settings(); SessionManager* sessions = main->sessionManager(); // NOTE: window has to be shown before restoring its geometry, // or else restoring maximized state will fail, if it has ever before // been saved un-maximized. win->show(); QString startSessionName = settings->value("IDE/startWithSession").toString(); if (startSessionName == "last") { QString lastSession = sessions->lastSession(); if (!lastSession.isEmpty()) { sessions->openSession(lastSession); } } else if (!startSessionName.isEmpty()) { sessions->openSession(startSessionName); } if (!sessions->currentSession()) { win->restoreWindowState(); sessions->newSession(); } foreach (QString argument, arguments) { main->documentManager()->open(argument); } win->restoreDocuments(); bool startInterpreter = settings->value("IDE/interpreter/autoStart").toBool(); if (startInterpreter) main->scProcess()->startLanguage(); #ifdef SC_USE_QTWEBENGINE HelpBrowserWebSocketServices hbServices(win->helpBrowserDocklet()->browser()); #endif return app.exec(); }
5,010
C++
.cpp
117
37.495726
112
0.704176
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
30,009
sig_mux.cpp
supercollider_supercollider/editors/sc-ide/core/sig_mux.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "sig_mux.hpp" #include <cstring> namespace ScIDE { SignalMultiplexer::SignalMultiplexer(QObject* parent): QObject(parent) {} void SignalMultiplexer::connect(QObject* sender, const char* signal, const char* slot, ConnectionMode mode) { Q_ASSERT(strlen(signal) > 0); Q_ASSERT(strlen(slot) > 0); Connection conn; conn.sender = sender; conn.signal = signal; conn.slot = slot; conn.mode = mode; mConnections << conn; connect(conn); } bool SignalMultiplexer::disconnect(QObject* sender) { bool result = false; QList<Connection>::Iterator it; for (it = mConnections.begin(); it != mConnections.end(); ++it) { Connection conn = *it; if ((QObject*)conn.sender == sender) { disconnect(conn); mConnections.erase(it); result = true; } } return result; } bool SignalMultiplexer::disconnect(QObject* sender, const char* signal, const char* slot) { QList<Connection>::Iterator it; for (it = mConnections.begin(); it != mConnections.end(); ++it) { Connection conn = *it; if ((QObject*)conn.sender == sender && qstrcmp(conn.signal, signal) == 0 && qstrcmp(conn.slot, slot) == 0) { disconnect(conn); mConnections.erase(it); return true; } } return false; } void SignalMultiplexer::connect(const char* signal, QObject* receiver, const char* slot, ConnectionMode mode) { Connection conn; conn.receiver = receiver; conn.signal = signal; conn.slot = slot; conn.mode = mode; mConnections << conn; connect(conn); } bool SignalMultiplexer::disconnect(const char* signal, QObject* receiver, const char* slot) { QList<Connection>::Iterator it; for (it = mConnections.begin(); it != mConnections.end(); ++it) { Connection conn = *it; if ((QObject*)conn.receiver == receiver && qstrcmp(conn.signal, signal) == 0 && qstrcmp(conn.slot, slot) == 0) { disconnect(conn); mConnections.erase(it); return true; } } return false; } void SignalMultiplexer::connect(const Connection& conn) { if (!mObject) return; if (!conn.sender && !conn.receiver) return; bool optional = conn.mode == ConnectionOptional; // HACK: for QMetaObject::indexOfSlot/Signal we have to skip first char // that's added by SLOT() and SIGNAL() macros if (conn.sender) { if (optional && (mObject->metaObject()->indexOfSlot(conn.slot + 1) == -1)) return; QObject::connect((QObject*)conn.sender, conn.signal, (QObject*)mObject, conn.slot); } else { if (optional && (mObject->metaObject()->indexOfSignal(conn.signal + 1) == -1)) return; QObject::connect((QObject*)mObject, conn.signal, (QObject*)conn.receiver, conn.slot); } } void SignalMultiplexer::disconnect(const Connection& conn) { if (!mObject) return; if (!conn.sender && !conn.receiver) return; bool optional = conn.mode == ConnectionOptional; // HACK: for QMetaObject::indexOfSlot/Signal we have to skip first char // that's added by SLOT() and SIGNAL() macros if (conn.sender) { if (optional && (mObject->metaObject()->indexOfSlot(conn.slot + 1) == -1)) return; QObject::disconnect((QObject*)conn.sender, conn.signal, (QObject*)mObject, conn.slot); } else { if (optional && (mObject->metaObject()->indexOfSignal(conn.signal + 1) == -1)) return; QObject::disconnect((QObject*)mObject, conn.signal, (QObject*)conn.receiver, conn.slot); } } void SignalMultiplexer::setCurrentObject(QObject* newObject) { if (newObject == mObject) return; QList<Connection>::ConstIterator it; for (it = mConnections.begin(); it != mConnections.end(); ++it) disconnect(*it); mObject = newObject; for (it = mConnections.begin(); it != mConnections.end(); ++it) connect(*it); } } // namespace ScIDE
4,884
C++
.cpp
124
33.298387
120
0.656877
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,010
color.cpp
supercollider_supercollider/editors/sc-ide/core/util/color.cpp
/* SuperCollider Qt IDE Copyright (c) 2018 SuperCollider Team https://supercollider.github.io/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "color.hpp" namespace ScIDE { namespace color { QColor lighten(const QColor& color, int amount) { int value = color.value() + amount; if (value < 0) { value = 0; } else if (value > 255) { value = 255; } return QColor::fromHsv(color.hue(), color.saturation(), value); } QColor darken(const QColor& color, int amount) { return lighten(color, -amount); } QColor interpolate(const QColor& color_1, const QColor& color_2, float amount) { return QColor(color_1.red() * (1 - amount) + color_2.red() * amount, color_1.green() * (1 - amount) + color_2.green() * amount, color_1.blue() * (1 - amount) + color_2.blue() * amount); } QColor setValue(const QColor& color, int value) { return QColor::fromHsv(color.hue(), color.saturation(), value); } } // namespace color } // namespace ScIDE
1,708
C++
.cpp
36
42.444444
115
0.694578
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,011
standard_dirs.cpp
supercollider_supercollider/editors/sc-ide/core/util/standard_dirs.cpp
/* SuperCollider Qt IDE Copyright (c) 2013 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "standard_dirs.hpp" #include "SC_Filesystem.hpp" // getDirectory #include "SC_Codecvt.hpp" // path_to_utf8_str #include <filesystem> namespace ScIDE { QString standardDirectory(StandardDirectory type) { using DirName = SC_Filesystem::DirName; DirName dn; switch (type) { case ScResourceDir: dn = DirName::Resource; break; case ScAppDataSystemDir: dn = DirName::SystemAppSupport; break; case ScAppDataUserDir: dn = DirName::UserAppSupport; break; case ScExtensionSystemDir: dn = DirName::SystemExtension; break; case ScExtensionUserDir: dn = DirName::UserExtension; break; case ScConfigUserDir: dn = DirName::UserConfig; break; default: return QString(); } const std::filesystem::path path = SC_Filesystem::instance().getDirectory(dn); return QString(SC_Codecvt::path_to_utf8_str(path).c_str()); } } // ScIDE
1,823
C++
.cpp
50
30.9
82
0.707456
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
30,012
scdoc_log.cpp
supercollider_supercollider/editors/sc-ide/core/util/scdoc_log.cpp
#include <QDebug> void error(const char* fmt, ...) { qWarning() << fmt; } void post(const char* fmt, ...) { qDebug() << fmt; }
129
C++
.cpp
3
41.333333
55
0.596774
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,013
default_themes.cpp
supercollider_supercollider/editors/sc-ide/core/settings/default_themes.cpp
/* SuperCollider IDE Copyright (c) 2018 SuperCollider Team https://supercollider.github.io/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "theme.hpp" #include <QPalette> #include <QApplication> namespace ScIDE { namespace Settings { /* Kary Pro Colors Copyright (c) 2018 Pouya Kary modified and adaptated for SuperCollider by Nathan Ho This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ void Theme::fillDefault() { QColor background("#f7f7f7"); QColor current_line("#eaeaea"); QColor selection("#d6d6d6"); QColor foreground("#1a1a1a"); QColor line_number("#c7c4c2"); QColor comment("#848484"); QColor red("#cc3626"); QColor orange("#c07f00"); // QColor yellow("#ada526"); // Not used currently. QColor green("#3f831e"); QColor cyan("#3478bc"); QColor blue("#3f39c9"); QColor purple("#af33a6"); add("text", foreground, background); add("currentLine", foreground, current_line); add("searchResult", background, blue); add("matchingBrackets", foreground, current_line, true); add("mismatchedBrackets", background, red); add("evaluatedCode", background, orange); add("whitespace", background); add("keyword", red); add("built-in", purple); add("env-var", orange); add("class", cyan); add("number", purple); add("symbol", green); add("string", blue); add("char", purple); add("comment", comment); add("primitive", orange); add("lineNumbers", line_number); add("selection", foreground, selection); add("postwindowtext", foreground); add("postwindowerror", red); add("postwindowwarning", orange); add("postwindowsuccess", green); add("postwindowemphasis", foreground, Qt::transparent, true); } /* END Kary Pro Colors */ void Theme::fillClassic() { QColor orange("#F8A200"); QColor pale_blue("#3333bf"); QColor green("#007300"); add("text", Qt::black, Qt::white); add("currentLine", Qt::black, QColor("#f4f4f4")); add("searchResult", Qt::black, orange); add("matchingBrackets", QColor("#2bc93d"), QColor("#ffff00"), true); add("mismatchedBrackets", Qt::white, QColor("#960000")); add("evaluatedCode", Qt::black, orange); add("whitespace", QColor("#888888")); add("keyword", QColor("#0000e6"), QColor(Qt::transparent), true); add("built-in", pale_blue); add("env-var", QColor("#8c4614")); add("class", QColor("#0000d2")); add("number", QColor("#980099")); add("symbol", green); add("string", QColor("#5f5f5f")); add("char", green); add("comment", QColor("#bf0000")); add("primitive", pale_blue); add("lineNumbers", Qt::black, QColor("#b8b8b8")); add("selection", Qt::white, QColor("#308cc6")); add("postwindowtext", Qt::black); add("postwindowerror", QColor("#d11c24")); add("postwindowwarning", QColor("#a57706")); add("postwindowsuccess", QColor("#738a05")); add("postwindowemphasis", Qt::black, Qt::transparent, true); } void Theme::fillDark() { add("text", QColor("#ffa4e2"), Qt::black); add("currentLine", QColor("#e4e4e4"), QColor("#393939")); add("searchResult", QColor("#e4e4e4"), QColor("#194c7f")); add("matchingBrackets", QColor("#ff5500"), QColor("#001d49"), true); add("mismatchedBrackets", QColor("#ffaa00"), QColor("#980000")); add("evaluatedCode", QColor("#e4e4e4"), QColor("#636397")); add("whitespace", QColor("#e4e4e4")); add("keyword", QColor("#aaaaff"), Qt::transparent, true); add("built-in", QColor("#ffa4e2")); add("env-var", QColor("#73e7ad")); add("class", QColor("#00abff"), Qt::transparent, true); add("number", QColor("#4aff00")); add("symbol", QColor("#ddde00")); add("string", QColor("#d7d7d7")); add("char", QColor("#ff55ff")); add("comment", QColor("#d4b982")); add("primitive", QColor("#aaff7f")); add("lineNumbers", QColor("#cfcfcf")); add("selection", QColor("#ff5500")); add("postwindowtext", QColor("#e4e4e4")); add("postwindowerror", QColor("#ff1f2a")); add("postwindowwarning", QColor("#de7100")); add("postwindowsuccess", QColor("#b0d206")); add("postwindowemphasis", QColor("#e4e4e4"), Qt::transparent, true); } /* The MIT License (MIT) Copyright (c) 2016 Dracula Theme Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. https://github.com/dracula/dracula-theme/ */ void Theme::fillDracula() { add("text", QColor("#f7fdff"), QColor("#282a36")); add("currentLine", QColor("#909194"), QColor("#282a36")); add("searchResult", QColor("#e4e4e4"), QColor("#194c7f")); add("matchingBrackets", QColor("#ff5500"), QColor("#001d49"), true); add("mismatchedBrackets", QColor("#ffaa00"), QColor("#980000")); add("evaluatedCode", QColor("#e4e4e4"), QColor("#636397")); add("whitespace", QColor("#e4e4e4")); add("keyword", QColor("#ff76c7"), Qt::transparent, true); add("built-in", QColor("#e2e37a")); add("env-var", QColor("#ffb965")); add("class", QColor("#65e5ff"), Qt::transparent, true); add("number", QColor("#be90fc")); add("symbol", QColor("#45fc75")); add("string", QColor("#5df884")); add("char", QColor("#ff55ff")); add("comment", QColor("#6071a6")); add("primitive", QColor("#aaff7f")); add("lineNumbers", QColor("#909194")); add("selection", QColor("#e0eeff")); add("postwindowtext", QColor("#dfe0fc")); add("postwindowerror", QColor("#ff1f2a")); add("postwindowwarning", QColor("#de7100")); add("postwindowsuccess", QColor("#b0d206")); add("postwindowemphasis", QColor("#e4e4e4"), Qt::transparent, true); } /* END MIT LICENSED CODE */ /* The MIT license (MIT) Copyright (c) 2011 Ethan Schoonover Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. https://github.com/altercation/solarized */ void Theme::fillSolarizedLight() { add("text", QColor("#657b83"), QColor("#fdf6e3")); add("currentLine", Qt::transparent, QColor("#eee8d5")); add("searchResult", QColor("#93a1a1"), QColor("#073642")); add("matchingBrackets", QColor("#002b36"), QColor("#eee8d5"), true); add("mismatchedBrackets", QColor("#eee8d5"), QColor("#586e75")); add("evaluatedCode", QColor("#586e75"), QColor("#eee8d5")); add("whitespace", Qt::transparent); add("keyword", QColor("#dc322f"), Qt::transparent, true); add("built-in", QColor("#b58900")); add("env-var", QColor("#d33682")); add("class", QColor("#268bd2")); add("number", QColor("#6c71c4")); add("symbol", QColor("#b58900")); add("string", QColor("#93a1a1")); add("char", QColor("#cb4b16")); add("comment", QColor("#586e75"), Qt::transparent, false, true); add("primitive", QColor("#2aa198")); add("lineNumbers", QColor("#839496"), QColor("#eee8d5")); add("selection", QColor("#fdf6e3"), QColor("#657b83")); add("postwindowtext", QColor("#657b83")); add("postwindowerror", QColor("#dc322f")); add("postwindowwarning", QColor("#cb4b16")); add("postwindowsuccess", QColor("#859900")); add("postwindowemphasis", QColor("#b58900"), Qt::transparent, true); } void Theme::fillSolarizedDark() { add("text", QColor("#839496"), QColor("#002b36")); add("currentLine", Qt::transparent, QColor("#073642")); add("searchResult", QColor("#586e75"), QColor("#eee8d5")); add("matchingBrackets", QColor("#fdf6e3"), QColor("#073642"), true); add("mismatchedBrackets", QColor("#073642"), QColor("#93a1a1")); add("evaluatedCode", QColor("#93a1a1"), QColor("#073642")); add("whitespace", Qt::transparent); add("keyword", QColor("#dc322f"), Qt::transparent, true); add("built-in", QColor("#b58900")); add("env-var", QColor("#d33682")); add("class", QColor("#268bd2")); add("number", QColor("#6c71c4")); add("symbol", QColor("#b58900")); add("string", QColor("#586e75")); add("char", QColor("#cb4b16")); add("comment", QColor("#93a1a1"), Qt::transparent, false, true); add("primitive", QColor("#2aa198")); add("lineNumbers", QColor("#657b83"), QColor("#073642")); add("selection", QColor("#002b36"), QColor("#839496")); add("postwindowtext", QColor("#839496")); add("postwindowerror", QColor("#dc322f")); add("postwindowwarning", QColor("#cb4b16")); add("postwindowsuccess", QColor("#859900")); add("postwindowemphasis", QColor("#b58900"), Qt::transparent, true); } /* END MIT LICENSED CODE */ }} // namespace ScIDE
11,747
C++
.cpp
252
42.511905
81
0.686786
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,014
serialization.cpp
supercollider_supercollider/editors/sc-ide/core/settings/serialization.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "serialization.hpp" #include <yaml-cpp/yaml.h> #include <QDebug> #include <QStringList> #include <QKeySequence> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <iostream> #include <QIODevice> namespace ScIDE { namespace Settings { typedef QSettings::SettingsMap::const_iterator SettingsIterator; struct IODeviceSource : boost::iostreams::source { IODeviceSource(QIODevice* dev): mDev(dev) {} std::streamsize read(char* s, std::streamsize n) { // Read up to n characters from the input // sequence into the buffer s, returning // the number of characters read, or -1 // to indicate end-of-sequence. qint64 ret = mDev->read(s, n); if (ret == 0) ret = -1; return ret; } QIODevice* mDev; }; static QVariant parseTextFormat(const YAML::Node& node) { using namespace YAML; if (node.Type() != NodeType::Map) { qWarning("YAML parsing: a node tagged 'textFormat' has wrong type (not a map)"); return QVariant(); } std::string val; QTextCharFormat fm; const Node ncolor = node["color"]; if (ncolor && ncolor.IsScalar()) { val = ncolor.as<std::string>(); fm.setForeground(QColor(val.c_str())); } const Node nbg = node["background"]; if (nbg && nbg.IsScalar()) { val = nbg.as<std::string>(); QColor color(val.c_str()); if (color.isValid()) fm.setBackground(color); } const Node nbold = node["bold"]; if (nbold && nbold.IsScalar()) { bool bold = nbold.as<bool>(); if (bold) fm.setFontWeight(QFont::Bold); } const Node nitalic = node["italic"]; if (nitalic && nitalic.IsScalar()) { bool italic = nitalic.as<bool>(); fm.setFontItalic(italic); } const Node nunder = node["underline"]; if (nunder && nunder.IsScalar()) { bool underline = nunder.as<bool>(); fm.setFontUnderline(underline); } return QVariant::fromValue<QTextCharFormat>(fm); } static QVariant parseScalar(const YAML::Node& node) { using namespace YAML; switch (node.Type()) { case NodeType::Scalar: { std::string val = node.as<std::string>(); return QVariant(QString::fromUtf8(val.c_str())); } case NodeType::Sequence: { QVariantList list; for (auto const& element : node) list.append(parseScalar(element)); return QVariant::fromValue<QVariantList>(list); } case NodeType::Map: { QVariantMap map; for (auto const& element : node) { std::string key = element.first.as<std::string>(); QVariant value = parseScalar(element.second); map.insert(QString(key.c_str()), value); } return QVariant::fromValue<QVariantMap>(map); } case NodeType::Null: return QVariant(); default: qWarning("YAML parsing: unsupported node type."); return QVariant(); } } static void parseNode(const YAML::Node& node, const QString& parentKey, QSettings::SettingsMap& map) { using namespace YAML; static const std::string textFormatTag("!textFormat"); static const std::string qVariantListTag("!QVariantList"); static const std::string qVariantMapTag("!QVariantMap"); Q_ASSERT(node.Type() == NodeType::Map); for (auto const& element : node) { std::string key = element.first.as<std::string>(); QString childKey(parentKey); if (!childKey.isEmpty()) childKey += "/"; childKey += key.c_str(); const YAML::Node& childNode = element.second; const std::string& childTag = childNode.Tag(); if (childTag == textFormatTag) map.insert(childKey, parseTextFormat(childNode)); else if (childTag == qVariantListTag || childTag == qVariantMapTag || childNode.Type() != NodeType::Map) map.insert(childKey, parseScalar(childNode)); else if (childNode.Type() == NodeType::Map) parseNode(childNode, childKey, map); } } bool readSettings(QIODevice& device, QSettings::SettingsMap& map) { using namespace YAML; try { boost::iostreams::stream<IODeviceSource> in(&device); Node doc = Load(in); if (doc) { if (doc.IsMap()) { QString key; parseNode(doc, key, map); } } return true; } catch (std::exception& e) { qWarning() << "Exception when parsing YAML config file:" << e.what(); return false; } } static void writeTextFormat(const QTextCharFormat& fm, YAML::Emitter& out) { out << YAML::LocalTag("textFormat"); out << YAML::BeginMap; if (fm.hasProperty(QTextFormat::ForegroundBrush)) { out << YAML::Key << "color"; out << YAML::Value << fm.foreground().color().name().toStdString(); } if (fm.hasProperty(QTextFormat::BackgroundBrush)) { out << YAML::Key << "background"; out << YAML::Value << fm.background().color().name().toStdString(); } if (fm.hasProperty(QTextFormat::FontWeight)) { out << YAML::Key << "bold"; out << YAML::Value << (fm.fontWeight() == QFont::Bold); } if (fm.hasProperty(QTextFormat::FontItalic)) { out << YAML::Key << "italic"; out << YAML::Value << fm.fontItalic(); } if (fm.hasProperty(QTextFormat::TextUnderlineStyle)) { qDebug("saving underline"); out << YAML::Key << "underline"; out << YAML::Value << fm.fontUnderline(); } out << YAML::EndMap; } static void writeValue(const QVariant& var, YAML::Emitter& out) { switch (var.type()) { case QVariant::Invalid: { out << YAML::Null; break; } case QVariant::KeySequence: { QKeySequence kseq = var.value<QKeySequence>(); out << kseq.toString(QKeySequence::PortableText).toUtf8().constData(); break; } case QVariant::List: { out << YAML::LocalTag("QVariantList") << YAML::BeginSeq; QVariantList list = var.value<QVariantList>(); foreach (const QVariant& var, list) writeValue(var, out); out << YAML::EndSeq; break; } case QVariant::Map: { out << YAML::LocalTag("QVariantMap") << YAML::BeginMap; QVariantMap map = var.value<QVariantMap>(); QVariantMap::iterator it; for (it = map.begin(); it != map.end(); ++it) { out << YAML::Key << it.key().toStdString(); out << YAML::Value; writeValue(it.value(), out); } out << YAML::EndMap; break; } case QVariant::UserType: { int utype = var.userType(); if (utype == qMetaTypeId<QTextCharFormat>()) { writeTextFormat(var.value<QTextCharFormat>(), out); } else { out << var.toString().toUtf8().constData(); } break; } default: { out << var.toString().toUtf8().constData(); } } } static void writeGroup(const QString& groupKey, YAML::Emitter& out, SettingsIterator& it, const QSettings::SettingsMap& map) { out << YAML::BeginMap; int groupKeyLen = groupKey.size(); while (it != map.end()) { QString key(it.key()); if (!key.startsWith(groupKey)) break; int i_separ = key.indexOf("/", groupKeyLen); if (i_separ != -1) { // There is child nodes key.truncate(i_separ + 1); QString yamlKey(key); yamlKey.remove(0, groupKeyLen); yamlKey.chop(1); out << YAML::Key << yamlKey.toStdString(); out << YAML::Value; writeGroup(key, out, it, map); } else { // There is no child nodes key.remove(0, groupKeyLen); out << YAML::Key << key.toStdString(); out << YAML::Value; writeValue(it.value(), out); ++it; } } out << YAML::EndMap; } bool writeSettings(QIODevice& device, const QSettings::SettingsMap& map) { try { YAML::Emitter out; SettingsIterator it = map.begin(); writeGroup("", out, it, map); device.write(out.c_str()); return true; } catch (std::exception& e) { qWarning() << "Exception when writing YAML config file:" << e.what(); return false; } } QSettings::Format serializationFormat() { static QSettings::Format format = QSettings::registerFormat("yaml", readSettings, writeSettings); if (format == QSettings::InvalidFormat) qWarning("Could not register settings format"); return format; } void printSettings(const QSettings* settings) { using namespace std; cout << "config filename: " << settings->fileName().toStdString() << endl; QStringList keys = settings->allKeys(); cout << "num keys: " << keys.count() << endl; Q_FOREACH (QString key, keys) { QVariant var = settings->value(key); if (var.type() == QVariant::Invalid) cout << key.toStdString() << ": <null>" << endl; else if (var.type() == QVariant::String) cout << key.toStdString() << ": " << var.toString().toStdString() << endl; else cout << key.toStdString() << ": <unknown value type>" << endl; } } }} // namespace ScIDE::Settings
10,312
C++
.cpp
281
29.330961
112
0.606967
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
30,015
theme.cpp
supercollider_supercollider/editors/sc-ide/core/settings/theme.cpp
/* SuperCollider Qt IDE Copyright(c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <QTextCharFormat> #include <QString> #include <QMap> #include <QList> #include <QApplication> #include <QPalette> #include <QDebug> #include "../main.hpp" #include "theme.hpp" #include "manager.hpp" namespace ScIDE { namespace Settings { int legacyTheme(Manager* settings) { QString group = QStringLiteral("IDE/editor/colors/"); QString newGroup = QStringLiteral("IDE/editor/themes/My old theme/"); if (!settings->contains(group + "evaluatedCode")) return 0; /* import default values */ Theme theme("My old theme", "default", settings); theme.save(); QList<QString> keys; keys << "evaluatedCode" << "lineNumbers" << "matchingBrackets" << "searchResult" << "selection" << "text" << "currentLine" << "matchingBrackets" << "postwindowtext"; foreach (QString key, keys) { if (settings->contains(group + key)) { QTextCharFormat fm = settings->value(group + key).value<QTextCharFormat>(); settings->setValue(newGroup + key, QVariant::fromValue<QTextCharFormat>(fm)); } } settings->remove(group); group = QStringLiteral("IDE/editor/highlighting/"); keys.clear(); keys << "keyword" << "built-in" << "env-var" << "class" << "number" << "symbol" << "string" << "char" << "comment" << "primitive" << "postwindowemphasis" << "postwindowerror" << "postwindowsuccess" << "postwindowwarning" << "whitespace"; foreach (QString key, keys) { if (settings->contains(group + key)) { QTextCharFormat fm = theme.format(key); fm.merge(settings->value(group + key).value<QTextCharFormat>()); settings->setValue(newGroup + key, QVariant::fromValue<QTextCharFormat>(fm)); } } settings->remove(group); settings->setValue("IDE/editor/theme", "My old theme"); return 1; } void Theme::add(const char* key, const QColor& fg, const QColor& bg, // = QColor(Qt::transparent) bool bold, // = false bool italic // = false ) { QTextCharFormat* format = new QTextCharFormat(); if (bg != QColor(Qt::transparent)) format->setBackground(bg); if (fg != QColor(Qt::transparent)) format->setForeground(fg); if (bold) format->setFontWeight(QFont::Bold); format->setFontItalic(italic); mFormats.insert(key, format); } void Theme::fillUser(const QString& name, const Manager* settings) { QString group = QStringLiteral("IDE/editor/themes/%1/").arg(name); if (!settings->contains(group + "whitespace")) { qDebug() << "Failed to find theme" << name << settings->group(); fillDefault(); // Fallback to default theme to avoid a broken Theme return; } QList<QString> keys; keys << "text" << "currentLine" << "searchResult" << "matchingBrackets" << "mismatchedBrackets" << "evaluatedCode" << "whitespace" << "keyword" << "built-in" << "env-var" << "class" << "number" << "symbol" << "string" << "char" << "comment" << "primitive" << "lineNumbers" << "selection" << "postwindowtext" << "postwindowerror" << "postwindowwarning" << "postwindowsuccess" << "postwindowemphasis"; foreach (QString key, keys) { QTextCharFormat* format = new QTextCharFormat(settings->value(group + key).value<QTextCharFormat>()); mFormats.insert(key, format); } } Theme::Theme(const QString& _name, Manager* settings) { if (!settings) settings = Main::settings(); mSettings = settings; mName = _name; if (mName == "default") { fillDefault(); mLocked = true; } else if (mName == "classic") { fillClassic(); mLocked = true; } else if (mName == "dark") { fillDark(); mLocked = true; } else if (mName == "dracula") { fillDracula(); mLocked = true; } else if (mName == "solarizedLight") { fillSolarizedLight(); mLocked = true; } else if (mName == "solarizedDark") { fillSolarizedDark(); mLocked = true; } else { fillUser(mName, settings); mLocked = false; } } Theme::Theme(const QString& _name, const QString& _source, Manager* settings): mName(_name) { if (!settings) settings = Main::settings(); mSettings = settings; if (_source == "default") { fillDefault(); } else if (_source == "classic") { fillClassic(); } else if (_source == "dark") { fillDark(); } else if (_source == "dracula") { fillDracula(); } else if (_source == "solarizedLight") { fillSolarizedLight(); } else if (_source == "solarizedDark") { fillSolarizedDark(); } else { fillUser(_source, settings); } mLocked = false; } Theme::~Theme() { qDeleteAll(mFormats); } void Theme::setFormat(const QString& key, const QTextCharFormat& newFormat) { QMap<QString, QTextCharFormat*>::iterator i = mFormats.find(key); bool fontWeight = (newFormat.fontWeight() == QFont::Bold) ? true : false; QColor bg = (newFormat.background() == Qt::NoBrush) ? QColor(Qt::transparent) : newFormat.background().color(); QColor fg = (newFormat.foreground() == Qt::NoBrush) ? QColor(Qt::transparent) : newFormat.foreground().color(); if (i == mFormats.end()) { qDebug() << __FUNCTION__ << "Theme::setFormat" << "Failed to find key " << key; return; } mFormats.remove(key); add(key.toStdString().c_str(), fg, bg, fontWeight, newFormat.fontItalic()); } const QTextCharFormat& Theme::format(const QString& key) { QMap<QString, QTextCharFormat*>::iterator i = mFormats.find(key); if (i == mFormats.end()) qDebug() << "Failed to find key " << key; return (*i.value()); } bool Theme::locked() { return mLocked; } QList<QString> Theme::availableThemes() { QList<QString> themes; themes.append("default"); themes.append("classic"); themes.append("dark"); themes.append("dracula"); themes.append("solarizedLight"); themes.append("solarizedDark"); mSettings->beginGroup("IDE/editor/themes"); themes.append(mSettings->childGroups()); mSettings->endGroup(); return themes; } void Theme::save() { if (mLocked) return; QMap<QString, QTextCharFormat*>::const_iterator i = mFormats.begin(); QString group = QStringLiteral("IDE/editor/themes/").append(mName); mSettings->beginGroup(group); while (i != mFormats.end()) { QTextCharFormat fm = *i.value(); mSettings->setValue(i.key(), QVariant::fromValue<QTextCharFormat>(fm)); ++i; } mSettings->endGroup(); } void Theme::remove() { if (mLocked) return; QString key = QStringLiteral("IDE/editor/themes/").append(mName); mSettings->remove(key); } QString& Theme::name() { return mName; } }} // namespace ScIDE::Settings
8,127
C++
.cpp
236
27.792373
115
0.612549
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,016
manager.cpp
supercollider_supercollider/editors/sc-ide/core/settings/manager.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "manager.hpp" #include "serialization.hpp" #include "theme.hpp" #include <QApplication> #include <QPalette> #include <QTextCharFormat> #include <QDebug> namespace ScIDE { namespace Settings { // manages preferences Manager::Manager(const QString& filename, QObject* parent): QObject(parent), mSettings(new QSettings(filename, serializationFormat(), this)), mDefaultCursorFlashTime(QApplication::cursorFlashTime()) { QString th; initDefaults(); if (legacyTheme(this)) th = "My old theme"; else th = value("IDE/editor/theme").toString(); mTheme = new Theme(th, this); } void Manager::initDefaults() { beginGroup("IDE"); setDefault("startWithSession", "last"); beginGroup("interpreter"); setDefault("autoStart", true); endGroup(); setDefault("postWindow/scrollback", 1000); beginGroup("editor"); setDefault("spaceIndent", false); setDefault("indentWidth", 4); setDefault("stepForwardEvaluation", false); setDefault("lineWrap", true); setDefault("disableBlinkingCursor", false); setDefault("highlightBracketContents", true); setDefault("inactiveEditorFadeAlpha", 64); setDefault("insertMatchingTokens", false); setDefault("showLinenumber", true); setDefault("showAutocompleteHelp", true); setDefault("blinkDuration", 600); // Issue #2389 - register a substitute so that macOS default won't be Helvetica. // But, don't add substitutes for monospace, because this is a global registry. setDefault("font/family", "scide_monospace"); QFont::insertSubstitutions("scide_monospace", { "monospace", "Monaco" }); setDefault("font/antialias", true); setDefault("theme", "default"); endGroup(); // editor endGroup(); // IDE } bool Manager::contains(const QString& key) const { if (mSettings->contains(key)) return true; else return mDefaults.contains(resolvedKey(key)); } QVariant Manager::value(const QString& key) const { if (mSettings->contains(key)) return mSettings->value(key); else return mDefaults.value(resolvedKey(key)); } void Manager::setValue(const QString& key, const QVariant& value) { mSettings->setValue(key, value); } QKeySequence Manager::shortcut(const QString& key) { return QKeySequence(value(key).toString()); } void Manager::addAction(QAction* action, const QString& key, const QString& category) { ActionData actionData; actionData.category = category; actionData.key = key; if (action->data().isValid()) { qWarning("Settings::Manager: action '%s' of class '%s' has data." " It will be overridden for settings purposes!", qPrintable(action->text()), action->parent()->metaObject()->className()); } action->setData(QVariant::fromValue(actionData)); mActions.append(action); beginGroup("IDE/shortcuts"); setDefault(actionData.key, QVariant::fromValue(action->shortcut())); action->setShortcut(value(actionData.key).value<QKeySequence>()); endGroup(); } QString Manager::keyForAction(QAction* action) { ActionData actionData = action->data().value<ActionData>(); return actionData.key; } QFont Manager::codeFont() { QString fontFamily = value("IDE/editor/font/family").toString(); int fontSize = value("IDE/editor/font/size").toInt(); bool fontAntialas = value("IDE/editor/font/antialias").toBool(); QFont font = QApplication::font("QPlainTextEdit"); font.setStyleHint(QFont::TypeWriter); font.setFamily(fontFamily); if (fontSize > 0) font.setPointSize(fontSize); if (!fontAntialas) font.setStyleStrategy(QFont::StyleStrategy(font.styleStrategy() | QFont::NoAntialias)); return font; } void Manager::setThemeVal(QString key, const QTextCharFormat& val) { mTheme->setFormat(key, val); } const QTextCharFormat& Manager::getThemeVal(QString key) { return mTheme->format(key); } void Manager::updateTheme() { QString theme = value("IDE/editor/theme").toString(); delete (mTheme); mTheme = new Theme(theme); } }} // namespace ScIDE::Settings
4,988
C++
.cpp
120
36.758333
102
0.715233
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,017
session_switch_dialog.cpp
supercollider_supercollider/editors/sc-ide/widgets/session_switch_dialog.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <QHBoxLayout> #include "main_window.hpp" #include "session_switch_dialog.hpp" #include "../core/main.hpp" #include "../core/session_manager.hpp" using namespace ScIDE; SessionSwitchDialog::SessionSwitchDialog(QWidget* parent): QDialog(parent) { setWindowTitle(tr("Switch Session")); mSessions = new QListWidget(this); QHBoxLayout* contentBox = new QHBoxLayout; contentBox->addWidget(mSessions); setLayout(contentBox); SessionManager* sessionManager = Main::sessionManager(); QStringList sessions = sessionManager->availableSessions(); mSessions->addItems(sessions); const Session* currentSession = sessionManager->currentSession(); if (!currentSession) return; const int currentSessionIndex = sessions.indexOf(currentSession->name()); if (currentSessionIndex != -1) mSessions->setCurrentRow(currentSessionIndex); connect(mSessions, SIGNAL(itemActivated(QListWidgetItem*)), this, SLOT(onItemActivated(QListWidgetItem*))); } void SessionSwitchDialog::onItemActivated(QListWidgetItem* item) { accept(); }
1,929
C++
.cpp
40
43.725
111
0.75921
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,018
main_window.cpp
supercollider_supercollider/editors/sc-ide/widgets/main_window.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define QT_NO_DEBUG_OUTPUT #include "cmd_line.hpp" #include "doc_list.hpp" #include "documents_dialog.hpp" #include "find_replace_tool.hpp" #include "goto_line_tool.hpp" #include "lookup_dialog.hpp" #include "main_window.hpp" #include "multi_editor.hpp" #include "popup_text_input.hpp" #include "post_window.hpp" #include "session_switch_dialog.hpp" #include "sessions_dialog.hpp" #include "tool_box.hpp" #include "audio_status_box.hpp" #include "lang_status_box.hpp" #include "../core/main.hpp" #include "../core/doc_manager.hpp" #include "../core/session_manager.hpp" #include "../core/sc_server.hpp" #include "../core/util/standard_dirs.hpp" #include "code_editor/sc_editor.hpp" #include "settings/dialog.hpp" #ifdef SC_USE_QTWEBENGINE # include "help_browser.hpp" #endif // SC_USE_QTWEBENGINE #include "QtCollider/hacks/hacks_qt.hpp" #include "SC_Version.hpp" #include <QAction> #include <QApplication> #include <QDesktopServices> #include <QStandardPaths> #include <QFileDialog> #include <QFileInfo> #include <QGridLayout> #include <QInputDialog> #include <QMenu> #include <QMenuBar> #include <QMessageBox> #include <QPointer> #include <QShortcut> #include <QStatusBar> #include <QVBoxLayout> #include <QUrl> #include <QMimeData> #include <QMetaMethod> namespace ScIDE { static QWidget* findFirstResponder(QWidget* widget, const char* methodSignature, int& methodIndex) { methodIndex = -1; while (widget) { methodIndex = widget->metaObject()->indexOfMethod(methodSignature); if (methodIndex != -1) break; if (widget->isWindow()) break; widget = widget->parentWidget(); } return widget; } static void invokeMethodOnFirstResponder(QByteArray const& signature) { int methodIdx = -1; QWidget* widget = findFirstResponder(QApplication::focusWidget(), signature.constData(), methodIdx); if (widget && methodIdx != -1) widget->metaObject()->method(methodIdx).invoke(widget, Qt::DirectConnection); } MainWindow* MainWindow::mInstance = 0; MainWindow::MainWindow(Main* main): mMain(main), mClockLabel(0), mDocDialog(0) { Q_ASSERT(!mInstance); mInstance = this; setAcceptDrops(true); // Construct status bar: mLangStatus = new LangStatusBox(main->scProcess()); mServerStatus = new AudioStatusBox(main->scServer()); mStatusBar = statusBar(); mStatusBar->addPermanentWidget(new QLabel(tr("Interpreter:"))); mStatusBar->addPermanentWidget(mLangStatus); mStatusBar->addPermanentWidget(new QLabel(tr("Server:"))); mStatusBar->addPermanentWidget(mServerStatus); // Code editor mEditors = new MultiEditor(main); // Tools mCmdLine = new CmdLine(tr("Command Line:")); connect(mCmdLine, SIGNAL(invoked(QString, bool)), main->scProcess(), SLOT(evaluateCode(QString, bool))); mFindReplaceTool = new TextFindReplacePanel; mGoToLineTool = new GoToLineTool(); connect(mGoToLineTool, SIGNAL(activated(int)), this, SLOT(hideToolBox())); mToolBox = new ToolBox; mToolBox->addWidget(mCmdLine); mToolBox->addWidget(mFindReplaceTool); mToolBox->addWidget(mGoToLineTool); mToolBox->hide(); // Docks mDocumentsDocklet = new DocumentsDocklet(main->documentManager(), this); mDocumentsDocklet->setObjectName("documents-dock"); addDockWidget(Qt::LeftDockWidgetArea, mDocumentsDocklet->dockWidget()); mDocumentsDocklet->hide(); #ifdef SC_USE_QTWEBENGINE mHelpBrowserDocklet = new HelpBrowserDocklet(this); mHelpBrowserDocklet->setObjectName("help-dock"); addDockWidget(Qt::RightDockWidgetArea, mHelpBrowserDocklet->dockWidget()); // mHelpBrowserDockable->hide(); #endif // SC_USE_QTWEBENGINE mPostDocklet = new PostDocklet(this); mPostDocklet->setObjectName("post-dock"); addDockWidget(Qt::RightDockWidgetArea, mPostDocklet->dockWidget()); // Layout QVBoxLayout* center_box = new QVBoxLayout; center_box->setContentsMargins(0, 0, 0, 0); center_box->setSpacing(0); center_box->addWidget(mEditors); center_box->addWidget(mToolBox); QWidget* central = new QWidget; central->setLayout(center_box); setCentralWidget(central); // Session management connect(main->sessionManager(), SIGNAL(saveSessionRequest(Session*)), this, SLOT(saveSession(Session*))); connect(main->sessionManager(), SIGNAL(switchSessionRequest(Session*)), this, SLOT(switchSession(Session*))); connect(main->sessionManager(), SIGNAL(currentSessionNameChanged()), this, SLOT(updateWindowTitle())); // A system for easy evaluation of pre-defined code: connect(this, SIGNAL(evaluateCode(QString, bool)), main->scProcess(), SLOT(evaluateCode(QString, bool))); // Interpreter: post output connect(main->scProcess(), SIGNAL(scPost(QString)), mPostDocklet->mPostWindow, SLOT(post(QString))); // Interpreter: monitor running state connect(main->scProcess(), SIGNAL(stateChanged(QProcess::ProcessState)), this, SLOT(onInterpreterStateChanged(QProcess::ProcessState))); // Interpreter: forward status messages connect(main->scProcess(), SIGNAL(statusMessage(const QString&)), this, SLOT(showStatusMessage(const QString&))); // Document list interaction connect(mDocumentsDocklet->list(), SIGNAL(clicked(Document*)), mEditors, SLOT(setCurrent(Document*))); connect(mEditors, SIGNAL(currentDocumentChanged(Document*)), mDocumentsDocklet->list(), SLOT(setCurrent(Document*)), Qt::QueuedConnection); connect(mDocumentsDocklet->list(), SIGNAL(updateTabsOrder(QList<Document*>)), mEditors, SLOT(updateTabsOrder(QList<Document*>))); connect(mEditors, SIGNAL(updateDockletOrder(int, int)), mDocumentsDocklet->list(), SLOT(updateDockletOrder(int, int)), Qt::QueuedConnection); // Update actions on document change connect(mEditors, SIGNAL(currentDocumentChanged(Document*)), this, SLOT(onCurrentDocumentChanged(Document*))); // Document management DocumentManager* docMng = main->documentManager(); connect(docMng, SIGNAL(changedExternally(Document*)), this, SLOT(onDocumentChangedExternally(Document*))); connect(docMng, SIGNAL(recentsChanged()), this, SLOT(updateRecentDocsMenu())); connect(docMng, SIGNAL(saved(Document*)), this, SLOT(updateWindowTitle())); connect(docMng, SIGNAL(titleChanged(Document*)), this, SLOT(updateWindowTitle())); connect(main, SIGNAL(applySettingsRequest(Settings::Manager*)), this, SLOT(applySettings(Settings::Manager*))); connect(main, SIGNAL(storeSettingsRequest(Settings::Manager*)), this, SLOT(storeSettings(Settings::Manager*))); // ToolBox connect(mToolBox->closeButton(), SIGNAL(clicked()), this, SLOT(hideToolBox())); createActions(); createMenus(); // Must be called after createAtions(), because it accesses an action: toggleInterpreterActions(false); // Initialize recent documents menu updateRecentDocsMenu(); QIcon icon; // Unfortunately, the SVG icon shows up as a tiny dot on some Linux window // managers (see #3905, #2646). Best we can do here is PNGs. // icon.addFile(":icons/sc-ide-svg"); icon.addFile(":icons/sc-ide-16"); icon.addFile(":icons/sc-ide-24"); icon.addFile(":icons/sc-ide-32"); icon.addFile(":icons/sc-ide-48"); icon.addFile(":icons/sc-ide-64"); icon.addFile(":icons/sc-ide-128"); icon.addFile(":icons/sc-ide-256"); icon.addFile(":icons/sc-ide-512"); icon.addFile(":icons/sc-ide-1024"); QApplication::setWindowIcon(icon); updateWindowTitle(); applyCursorBlinkingSettings(main->settings()); // Custom event handling: qApp->installEventFilter(this); } void MainWindow::createActions() { Settings::Manager* settings = mMain->settings(); QAction* action; const QString ideCategory("IDE"); const QString editorCategory(tr("Text Editor")); const QString helpCategory(tr("Help")); // File mActions[Quit] = action = new QAction(QIcon::fromTheme("application-exit"), tr("&Quit..."), this); action->setShortcut(tr("Ctrl+Q", "Quit application")); action->setStatusTip(tr("Quit SuperCollider IDE")); // explicitly states that this action can be triggered by macOS QUIT events // (such as cmd+q or window closing) action->setMenuRole(QAction::QuitRole); QObject::connect(action, SIGNAL(triggered()), this, SLOT(onQuit())); settings->addAction(action, "ide-quit", ideCategory); mActions[DocNew] = action = new QAction(QIcon::fromTheme("document-new"), tr("&New"), this); action->setShortcut(tr("Ctrl+N", "New document")); action->setStatusTip(tr("Create a new document")); connect(action, SIGNAL(triggered()), this, SLOT(newDocument())); settings->addAction(action, "ide-document-new", ideCategory); mActions[DocOpen] = action = new QAction(QIcon::fromTheme("document-open"), tr("&Open..."), this); action->setShortcut(tr("Ctrl+O", "Open document")); action->setStatusTip(tr("Open an existing file")); connect(action, SIGNAL(triggered()), this, SLOT(openDocument())); settings->addAction(action, "ide-document-open", ideCategory); mActions[DocOpenStartup] = action = new QAction(QIcon::fromTheme("document-open"), tr("Open startup file"), this); action->setStatusTip(tr("Open startup file")); connect(action, SIGNAL(triggered()), this, SLOT(openStartupFile())); settings->addAction(action, "ide-document-open-startup", ideCategory); mActions[DocOpenSupportDir] = action = new QAction(QIcon::fromTheme("document-open"), tr("Open user support directory"), this); action->setStatusTip(tr("Open user support directory")); connect(action, SIGNAL(triggered()), this, SLOT(openUserSupportDirectory())); settings->addAction(action, "ide-document-open-support-directory", ideCategory); mActions[DocSave] = action = new QAction(QIcon::fromTheme("document-save"), tr("&Save"), this); action->setShortcut(tr("Ctrl+S", "Save document")); action->setStatusTip(tr("Save the current document")); connect(action, SIGNAL(triggered()), this, SLOT(saveDocument())); settings->addAction(action, "ide-document-save", ideCategory); mActions[DocSaveAs] = action = new QAction(QIcon::fromTheme("document-save-as"), tr("Save &As..."), this); action->setShortcut(tr("Ctrl+Shift+S", "Save &As...")); action->setStatusTip(tr("Save the current document into a different file")); connect(action, SIGNAL(triggered()), this, SLOT(saveDocumentAs())); settings->addAction(action, "ide-document-save-as", ideCategory); mActions[DocSaveAsExtension] = action = new QAction(QIcon::fromTheme("document-save-as"), tr("Save As Extension..."), this); action->setStatusTip(tr("Save the current document into a different file in the extensions folder")); connect(action, SIGNAL(triggered()), this, SLOT(saveDocumentAsExtension())); settings->addAction(action, "ide-document-save-as-extension", ideCategory); mActions[DocSaveAll] = action = new QAction(QIcon::fromTheme("document-save"), tr("Save All..."), this); action->setShortcut(tr("Ctrl+Alt+S", "Save all documents")); action->setStatusTip(tr("Save all open documents")); connect(action, SIGNAL(triggered()), this, SLOT(saveAllDocuments())); settings->addAction(action, "ide-document-save-all", ideCategory); mActions[DocCloseAll] = action = new QAction(QIcon::fromTheme("window-close"), tr("Close All..."), this); action->setShortcut(tr("Ctrl+Shift+W", "Close all documents")); action->setStatusTip(tr("Close all documents")); connect(action, SIGNAL(triggered()), this, SLOT(closeAllDocuments())); settings->addAction(action, "ide-document-close-all", ideCategory); mActions[DocReload] = action = new QAction(QIcon::fromTheme("view-refresh"), tr("&Reload"), this); action->setShortcut(tr("F5", "Reload document")); action->setStatusTip(tr("Reload the current document")); connect(action, SIGNAL(triggered()), this, SLOT(reloadDocument())); settings->addAction(action, "ide-document-reload", ideCategory); mActions[ClearRecentDocs] = action = new QAction(tr("Clear", "Clear recent documents"), this); action->setStatusTip(tr("Clear list of recent documents")); connect(action, SIGNAL(triggered()), Main::instance()->documentManager(), SLOT(clearRecents())); settings->addAction(action, "ide-clear-recent-documents", ideCategory); // Sessions mActions[NewSession] = action = new QAction(QIcon::fromTheme("document-new"), tr("&New Session"), this); action->setStatusTip(tr("Open a new session")); connect(action, SIGNAL(triggered()), this, SLOT(newSession())); settings->addAction(action, "ide-session-new", ideCategory); mActions[SaveSessionAs] = action = new QAction(QIcon::fromTheme("document-save-as"), tr("Save Session &As..."), this); action->setStatusTip(tr("Save the current session with a different name")); connect(action, SIGNAL(triggered()), this, SLOT(saveCurrentSessionAs())); settings->addAction(action, "ide-session-save-as", ideCategory); mActions[ManageSessions] = action = new QAction(tr("&Manage Sessions..."), this); connect(action, SIGNAL(triggered()), this, SLOT(openSessionsDialog())); settings->addAction(action, "ide-session-manage", ideCategory); mActions[OpenSessionSwitchDialog] = action = new QAction(tr("&Switch Session..."), this); connect(action, SIGNAL(triggered()), this, SLOT(showSwitchSessionDialog())); action->setShortcut(tr("Ctrl+Shift+Q", "Switch Session")); settings->addAction(action, "ide-session-switch", ideCategory); // Edit mActions[Find] = action = new QAction(QIcon::fromTheme("edit-find"), tr("&Find..."), this); action->setShortcut(tr("Ctrl+F", "Find")); action->setStatusTip(tr("Find text in document")); connect(action, SIGNAL(triggered()), this, SLOT(showFindTool())); settings->addAction(action, "editor-find", editorCategory); mActions[Replace] = action = new QAction(QIcon::fromTheme("edit-replace"), tr("&Replace..."), this); action->setShortcut(tr("Ctrl+R", "Replace")); action->setStatusTip(tr("Find and replace text in document")); connect(action, SIGNAL(triggered()), this, SLOT(showReplaceTool())); settings->addAction(action, "editor-replace", editorCategory); // View mActions[ShowCmdLine] = action = new QAction(tr("&Command Line"), this); action->setStatusTip(tr("Command line for quick code evaluation")); action->setShortcut(tr("Ctrl+E", "Show command line")); connect(action, SIGNAL(triggered()), this, SLOT(showCmdLine())); settings->addAction(action, "ide-command-line-show", ideCategory); mActions[CmdLineForCursor] = action = new QAction(tr("&Command Line from selection"), this); action->setShortcut(tr("Ctrl+Shift+E", "Fill command line with current selection")); connect(action, SIGNAL(triggered()), this, SLOT(cmdLineForCursor())); settings->addAction(action, "ide-command-line-fill", ideCategory); mActions[ShowGoToLineTool] = action = new QAction(tr("&Go To Line"), this); action->setStatusTip(tr("Tool to jump to a line by number")); action->setShortcut(tr("Ctrl+L", "Show go-to-line tool")); connect(action, SIGNAL(triggered()), this, SLOT(showGoToLineTool())); settings->addAction(action, "editor-go-to-line", editorCategory); mActions[CloseToolBox] = action = new QAction(QIcon::fromTheme("window-close"), tr("&Close Tool Panel"), this); action->setStatusTip(tr("Close any open tool panel")); action->setShortcut(tr("Esc", "Close tool box")); connect(action, SIGNAL(triggered()), this, SLOT(hideToolBox())); settings->addAction(action, "ide-tool-panel-hide", ideCategory); mActions[ShowFullScreen] = action = new QAction(tr("&Full Screen"), this); action->setCheckable(false); action->setShortcut(tr("Ctrl+Shift+F", "Show ScIDE in Full Screen")); connect(action, SIGNAL(triggered()), this, SLOT(toggleFullScreen())); settings->addAction(action, "ide-show-fullscreen", ideCategory); mActions[FocusPostWindow] = action = new QAction(tr("Focus Post Window"), this); action->setStatusTip(tr("Focus post window")); action->setShortcut(tr("Ctrl+P", "Focus post window")); connect(action, SIGNAL(triggered()), mPostDocklet, SLOT(focus())); settings->addAction(action, "post-focus", ideCategory); // Language mActions[LookupImplementation] = action = new QAction(QIcon::fromTheme("window-lookupdefinition"), tr("Look Up Implementations..."), this); action->setShortcut(tr("Ctrl+Shift+I", "Look Up Implementations")); action->setStatusTip(tr("Open dialog to look up implementations of a class or a method")); connect(action, SIGNAL(triggered()), this, SLOT(lookupImplementation())); settings->addAction(action, "ide-lookup-implementation", ideCategory); mActions[LookupImplementationForCursor] = action = new QAction(tr("Look Up Implementations for Cursor"), this); action->setShortcut(tr("Ctrl+I", "Look Up Implementations for Cursor")); action->setStatusTip(tr("Look up implementations of class or method under cursor")); connect(action, SIGNAL(triggered(bool)), this, SLOT(lookupImplementationForCursor())); settings->addAction(action, "ide-lookup-implementation-for-cursor", ideCategory); mActions[LookupReferences] = action = new QAction(QIcon::fromTheme("window-lookupreferences"), tr("Look Up References..."), this); action->setShortcut(tr("Ctrl+Shift+U", "Look Up References")); action->setStatusTip(tr("Open dialog to look up references to a class or a method")); connect(action, SIGNAL(triggered()), this, SLOT(lookupReferences())); settings->addAction(action, "ide-lookup-references", ideCategory); mActions[LookupReferencesForCursor] = action = new QAction(tr("Look Up References for Cursor"), this); action->setShortcut(tr("Ctrl+U", "Look Up References For Selection")); action->setStatusTip(tr("Look up references to class or method under cursor")); connect(action, SIGNAL(triggered(bool)), this, SLOT(lookupReferencesForCursor())); settings->addAction(action, "ide-lookup-references-for-cursor", ideCategory); // Settings mActions[ShowSettings] = action = new QAction(tr("Preferences"), this); #ifdef Q_OS_MAC action->setShortcut(tr("Ctrl+,", "Show configuration dialog")); #endif action->setStatusTip(tr("Show configuration dialog")); connect(action, SIGNAL(triggered()), this, SLOT(showSettings())); settings->addAction(action, "ide-settings-dialog", ideCategory); // Help mActions[ReportABug] = action = new QAction(QIcon::fromTheme("system-help"), tr("Report a bug..."), this); action->setStatusTip(tr("Report a bug")); connect(action, SIGNAL(triggered()), this, SLOT(doBugReport())); #ifdef SC_USE_QTWEBENGINE mActions[Help] = action = new QAction(tr("Show &Help Browser"), this); action->setStatusTip(tr("Show and focus the Help Browser")); connect(action, SIGNAL(triggered()), this, SLOT(openHelp())); settings->addAction(action, "help-browser", helpCategory); mActions[HelpAboutIDE] = action = new QAction(QIcon::fromTheme("system-help"), tr("How to Use SuperCollider IDE"), this); action->setStatusTip(tr("Open the SuperCollider IDE guide")); connect(action, SIGNAL(triggered()), this, SLOT(openHelpAboutIDE())); mActions[LookupDocumentationForCursor] = action = new QAction(tr("Look Up Documentation for Cursor"), this); action->setShortcut(tr("Ctrl+D", "Look Up Documentation for Cursor")); action->setStatusTip(tr("Look up documentation for text under cursor")); connect(action, SIGNAL(triggered()), this, SLOT(lookupDocumentationForCursor())); settings->addAction(action, "help-lookup-for-cursor", helpCategory); mActions[LookupDocumentation] = action = new QAction(tr("Look Up Documentation..."), this); action->setShortcut(tr("Ctrl+Shift+D", "Look Up Documentation")); action->setStatusTip(tr("Enter text to look up in documentation")); connect(action, SIGNAL(triggered()), this, SLOT(lookupDocumentation())); settings->addAction(action, "help-lookup", helpCategory); #endif // SC_USE_QTWEBENGINE mActions[ShowAbout] = action = new QAction(QIcon::fromTheme("help-about"), tr("&About SuperCollider"), this); connect(action, SIGNAL(triggered()), this, SLOT(showAbout())); settings->addAction(action, "ide-about", ideCategory); mActions[ShowAboutQT] = action = new QAction(QIcon::fromTheme("show-about-qt"), tr("About &Qt"), this); connect(action, SIGNAL(triggered()), this, SLOT(showAboutQT())); settings->addAction(action, "ide-about-qt", ideCategory); // Add external actions to settings: action = mPostDocklet->toggleViewAction(); action->setIcon(QIcon::fromTheme("utilities-terminal")); action->setStatusTip(tr("Show/hide Post docklet")); settings->addAction(mPostDocklet->toggleViewAction(), "ide-docklet-post", ideCategory); action = mDocumentsDocklet->toggleViewAction(); action->setIcon(QIcon::fromTheme("text-x-generic")); action->setStatusTip(tr("Show/hide Documents docklet")); settings->addAction(mDocumentsDocklet->toggleViewAction(), "ide-docklet-documents", ideCategory); #ifdef SC_USE_QTWEBENGINE action = mHelpBrowserDocklet->toggleViewAction(); action->setIcon(QIcon::fromTheme("system-help")); action->setStatusTip(tr("Show/hide Help browser docklet")); settings->addAction(mHelpBrowserDocklet->toggleViewAction(), "ide-docklet-help", ideCategory); #endif // SC_USE_QTWEBENGINE // In Mac OS, all menu item shortcuts need a modifier, so add the action with // the "Escape" default shortcut to the main window widget. // FIXME: This is not perfect, as any other action customized to "Escape" will // still not work. addAction(mActions[CloseToolBox]); // Add actions to docklets, so shortcuts work when docklets detached: #ifdef SC_USE_QTWEBENGINE mPostDocklet->widget()->addAction(mActions[LookupDocumentation]); mPostDocklet->widget()->addAction(mActions[LookupDocumentationForCursor]); #endif // SC_USE_QTWEBENGINE mPostDocklet->widget()->addAction(mActions[LookupImplementation]); mPostDocklet->widget()->addAction(mActions[LookupImplementationForCursor]); mPostDocklet->widget()->addAction(mActions[LookupReferences]); mPostDocklet->widget()->addAction(mActions[LookupReferencesForCursor]); #ifdef SC_USE_QTWEBENGINE mHelpBrowserDocklet->widget()->addAction(mActions[LookupDocumentation]); mHelpBrowserDocklet->widget()->addAction(mActions[LookupDocumentationForCursor]); mHelpBrowserDocklet->widget()->addAction(mActions[LookupImplementation]); mHelpBrowserDocklet->widget()->addAction(mActions[LookupImplementationForCursor]); mHelpBrowserDocklet->widget()->addAction(mActions[LookupReferences]); mHelpBrowserDocklet->widget()->addAction(mActions[LookupReferencesForCursor]); #endif // SC_USE_QTWEBENGINE } void MainWindow::createMenus() { QMenuBar* menuBar; QMenu* menu; QMenu* submenu; // On Mac, create a parent-less menu bar to be shared by all windows: #ifdef Q_OS_MAC menuBar = new QMenuBar(0); #else menuBar = this->menuBar(); #endif menu = new QMenu(tr("&File"), this); menu->addAction(mActions[DocNew]); menu->addAction(mActions[DocOpen]); mRecentDocsMenu = menu->addMenu(tr("Open Recent", "Open a recent document")); connect(mRecentDocsMenu, SIGNAL(triggered(QAction*)), this, SLOT(onOpenRecentDocument(QAction*))); menu->addAction(mActions[DocOpenStartup]); menu->addAction(mActions[DocOpenSupportDir]); menu->addAction(mActions[DocSave]); menu->addAction(mActions[DocSaveAs]); menu->addAction(mActions[DocSaveAsExtension]); menu->addAction(mActions[DocSaveAll]); menu->addSeparator(); menu->addAction(mActions[DocReload]); menu->addSeparator(); menu->addAction(mEditors->action(MultiEditor::DocClose)); menu->addAction(mActions[DocCloseAll]); menu->addSeparator(); menu->addAction(mActions[Quit]); menuBar->addMenu(menu); menu = new QMenu(tr("&Session"), this); menu->addAction(mActions[NewSession]); menu->addAction(mActions[SaveSessionAs]); submenu = menu->addMenu(tr("&Open Session")); connect(submenu, SIGNAL(triggered(QAction*)), this, SLOT(onOpenSessionAction(QAction*))); mSessionsMenu = submenu; updateSessionsMenu(); menu->addSeparator(); menu->addAction(mActions[ManageSessions]); menu->addAction(mActions[OpenSessionSwitchDialog]); menuBar->addMenu(menu); menu = new QMenu(tr("&Edit"), this); menu->addAction(mEditors->action(MultiEditor::Undo)); menu->addAction(mEditors->action(MultiEditor::Redo)); menu->addSeparator(); menu->addAction(mEditors->action(MultiEditor::Cut)); menu->addAction(mEditors->action(MultiEditor::Copy)); menu->addAction(mEditors->action(MultiEditor::Paste)); menu->addSeparator(); menu->addAction(mActions[Find]); menu->addAction(mFindReplaceTool->action(TextFindReplacePanel::FindNext)); menu->addAction(mFindReplaceTool->action(TextFindReplacePanel::FindPrevious)); menu->addAction(mActions[Replace]); menu->addSeparator(); menu->addAction(mEditors->action(MultiEditor::IndentWithSpaces)); menu->addAction(mEditors->action(MultiEditor::IndentLineOrRegion)); menu->addAction(mEditors->action(MultiEditor::ToggleComment)); menu->addAction(mEditors->action(MultiEditor::ToggleOverwriteMode)); menu->addAction(mEditors->action(MultiEditor::SelectRegion)); menu->addAction(mEditors->action(MultiEditor::SelectEnclosingBlock)); menu->addSeparator(); menu->addAction(mActions[ShowSettings]); menuBar->addMenu(menu); menu = new QMenu(tr("&View"), this); submenu = new QMenu(tr("&Docklets"), this); submenu->addAction(mPostDocklet->toggleViewAction()); submenu->addAction(mDocumentsDocklet->toggleViewAction()); #ifdef SC_USE_QTWEBENGINE submenu->addAction(mHelpBrowserDocklet->toggleViewAction()); #endif // SC_USE_QTWEBENGINE menu->addMenu(submenu); menu->addSeparator(); submenu = menu->addMenu(tr("&Tool Panels")); submenu->addAction(mActions[Find]); submenu->addAction(mActions[Replace]); submenu->addAction(mActions[ShowCmdLine]); submenu->addAction(mActions[CmdLineForCursor]); submenu->addAction(mActions[ShowGoToLineTool]); submenu->addSeparator(); submenu->addAction(mActions[CloseToolBox]); menu->addSeparator(); menu->addAction(mEditors->action(MultiEditor::EnlargeFont)); menu->addAction(mEditors->action(MultiEditor::ShrinkFont)); menu->addAction(mEditors->action(MultiEditor::ResetFontSize)); menu->addSeparator(); menu->addAction(mEditors->action(MultiEditor::ShowWhitespace)); menu->addAction(mEditors->action(MultiEditor::ShowLinenumber)); menu->addSeparator(); menu->addAction(mEditors->action(MultiEditor::ShowAutocompleteHelp)); menu->addSeparator(); menu->addAction(mEditors->action(MultiEditor::NextDocument)); menu->addAction(mEditors->action(MultiEditor::PreviousDocument)); menu->addAction(mEditors->action(MultiEditor::SwitchDocument)); menu->addSeparator(); menu->addAction(mEditors->action(MultiEditor::SplitHorizontally)); menu->addAction(mEditors->action(MultiEditor::SplitVertically)); menu->addAction(mEditors->action(MultiEditor::RemoveCurrentSplit)); menu->addAction(mEditors->action(MultiEditor::RemoveAllSplits)); menu->addSeparator(); menu->addAction(mActions[FocusPostWindow]); menuBar->addMenu(menu); menu = new QMenu(tr("&Language"), this); menu->addAction(mMain->scProcess()->action(ScProcess::ToggleRunning)); menu->addAction(mMain->scProcess()->action(ScProcess::Restart)); menu->addAction(mMain->scProcess()->action(ScProcess::RecompileClassLibrary)); menu->addSeparator(); menu->addAction(mMain->scProcess()->action(ScProcess::ShowQuarks)); menu->addSeparator(); menu->addAction(mEditors->action(MultiEditor::EvaluateCurrentDocument)); menu->addAction(mEditors->action(MultiEditor::EvaluateRegion)); menu->addAction(mEditors->action(MultiEditor::EvaluateLine)); menu->addAction(mMain->scProcess()->action(ScIDE::ScProcess::StopMain)); menu->addSeparator(); menu->addAction(mActions[LookupImplementationForCursor]); menu->addAction(mActions[LookupImplementation]); menu->addAction(mActions[LookupReferencesForCursor]); menu->addAction(mActions[LookupReferences]); menuBar->addMenu(menu); menu = new QMenu(tr("Se&rver"), this); menu->addAction(mMain->scServer()->action(ScServer::ToggleRunning)); menu->addAction(mMain->scServer()->action(ScServer::Reboot)); menu->addAction(mMain->scServer()->action(ScServer::KillAll)); menu->addSeparator(); menu->addAction(mMain->scServer()->action(ScServer::ShowMeters)); menu->addAction(mMain->scServer()->action(ScServer::ShowScope)); menu->addAction(mMain->scServer()->action(ScServer::ShowFreqScope)); menu->addAction(mMain->scServer()->action(ScServer::DumpNodeTree)); menu->addAction(mMain->scServer()->action(ScServer::DumpNodeTreeWithControls)); menu->addAction(mMain->scServer()->action(ScServer::PlotTree)); menu->addAction(mMain->scServer()->action(ScServer::DumpOSC)); menu->addAction(mMain->scServer()->action(ScServer::Record)); menu->addAction(mMain->scServer()->action(ScServer::PauseRecord)); menu->addAction(mMain->scServer()->action(ScServer::VolumeUp)); menu->addAction(mMain->scServer()->action(ScServer::VolumeDown)); menu->addAction(mMain->scServer()->action(ScServer::VolumeRestore)); menu->addAction(mMain->scServer()->action(ScServer::Mute)); menuBar->addMenu(menu); menu = new QMenu(tr("&Help"), this); #ifdef SC_USE_QTWEBENGINE menu->addAction(mActions[HelpAboutIDE]); #endif menu->addAction(mActions[ReportABug]); #ifdef SC_USE_QTWEBENGINE menu->addSeparator(); menu->addAction(mActions[Help]); menu->addAction(mActions[LookupDocumentationForCursor]); menu->addAction(mActions[LookupDocumentation]); #endif // SC_USE_QTWEBENGINE menu->addSeparator(); menu->addAction(mActions[ShowAbout]); menu->addAction(mActions[ShowAboutQT]); menuBar->addMenu(menu); } static void saveDetachedState(Docklet* docklet, QVariantMap& data) { data.insert(docklet->objectName(), docklet->saveDetachedState().toBase64()); } template <class T> void MainWindow::saveWindowState(T* settings) { QVariantMap detachedData; saveDetachedState(mPostDocklet, detachedData); saveDetachedState(mDocumentsDocklet, detachedData); #ifdef SC_USE_QTWEBENGINE saveDetachedState(mHelpBrowserDocklet, detachedData); #endif // SC_USE_QTWEBENGINE settings->beginGroup("mainWindow"); settings->setValue("geometry", this->saveGeometry().toBase64()); settings->setValue("state", this->saveState().toBase64()); settings->setValue("detached", QVariant::fromValue(detachedData)); settings->endGroup(); } void MainWindow::saveWindowState() { Settings::Manager* settings = Main::settings(); settings->beginGroup("IDE"); saveWindowState(settings); settings->endGroup(); } static void restoreDetachedState(Docklet* docklet, const QVariantMap& data) { QByteArray base64data = data.value(docklet->objectName()).value<QByteArray>(); docklet->restoreDetachedState(QByteArray::fromBase64(base64data)); } template <class T> void MainWindow::restoreWindowState(T* settings) { qDebug("------------ restore window state ------------"); settings->beginGroup("mainWindow"); QVariant varGeom = settings->value("geometry"); QVariant varState = settings->value("state"); QVariant varDetached = settings->value("detached"); settings->endGroup(); QByteArray geom = QByteArray::fromBase64(varGeom.value<QByteArray>()); QByteArray state = QByteArray::fromBase64(varState.value<QByteArray>()); QVariantMap detachedData = varDetached.value<QVariantMap>(); if (!geom.isEmpty()) { // Workaround for Qt bug 4397: setWindowState(Qt::WindowNoState); restoreGeometry(geom); } else setWindowState(windowState() & ~Qt::WindowFullScreen | Qt::WindowMaximized); restoreDetachedState(mPostDocklet, detachedData); restoreDetachedState(mDocumentsDocklet, detachedData); #ifdef SC_USE_QTWEBENGINE restoreDetachedState(mHelpBrowserDocklet, detachedData); #endif // SC_USE_QTWEBENGINE qDebug("restoring state"); if (!state.isEmpty()) restoreState(state); qDebug("setting dock area corners"); setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea); setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); updateClockWidget(isFullScreen()); qDebug("------------ END restore window state ------------"); } void MainWindow::restoreWindowState() { Settings::Manager* settings = Main::settings(); settings->beginGroup("IDE"); restoreWindowState(settings); settings->endGroup(); } void MainWindow::focusCodeEditor() { if (mEditors->currentEditor()) mEditors->currentEditor()->setFocus(); else mEditors->setFocus(); } void MainWindow::newSession() { mMain->sessionManager()->newSession(); } void MainWindow::saveCurrentSessionAs() { QString name = QInputDialog::getText(this, tr("Save Current Session"), tr("Enter a name for the session:")); if (name.isEmpty()) return; mMain->sessionManager()->saveSessionAs(name); updateSessionsMenu(); } void MainWindow::onOpenSessionAction(QAction* action) { openSession(action->text()); } void MainWindow::switchSession(Session* session) { if (session) restoreWindowState(session); updateWindowTitle(); mEditors->switchSession(session); } void MainWindow::saveSession(Session* session) { saveWindowState(session); mEditors->saveSession(session); } void MainWindow::openSessionsDialog() { QPointer<MainWindow> mainwin(this); SessionsDialog dialog(mMain->sessionManager(), this); dialog.exec(); if (mainwin) mainwin->updateSessionsMenu(); } QAction* MainWindow::action(ActionRole role) { Q_ASSERT(role < ActionCount); return mActions[role]; } bool MainWindow::quit() { if (!promptSaveDocs()) return false; Main::instance()->documentManager()->deleteRestore(); saveWindowState(); mMain->quit(); return true; } void MainWindow::onQuit() { quit(); } void MainWindow::onCurrentDocumentChanged(Document* doc) { updateWindowTitle(); mActions[DocCloseAll]->setEnabled(doc); mActions[DocReload]->setEnabled(doc); mActions[DocSave]->setEnabled(doc); mActions[DocSaveAs]->setEnabled(doc); mActions[DocSaveAsExtension]->setEnabled(doc); GenericCodeEditor* editor = mEditors->currentEditor(); mFindReplaceTool->setEditor(editor); mGoToLineTool->setEditor(editor); } void MainWindow::onDocumentChangedExternally(Document* doc) { if (mDocDialog) return; mDocDialog = new DocumentsDialog(DocumentsDialog::ExternalChange, this); mDocDialog->addDocument(doc); connect(mDocDialog, SIGNAL(finished(int)), this, SLOT(onDocDialogFinished())); mDocDialog->open(); } void MainWindow::onDocDialogFinished() { mDocDialog->deleteLater(); mDocDialog = 0; } void MainWindow::updateRecentDocsMenu() { mRecentDocsMenu->clear(); const QStringList& recent = mMain->documentManager()->recents(); foreach (const QString& path, recent) { QAction* action = mRecentDocsMenu->addAction(path); action->setData(QVariant(path)); } if (!recent.isEmpty()) { mRecentDocsMenu->addSeparator(); mRecentDocsMenu->addAction(mActions[ClearRecentDocs]); } } void MainWindow::onOpenRecentDocument(QAction* action) { mMain->documentManager()->open(action->data().value<QString>()); } void MainWindow::onInterpreterStateChanged(QProcess::ProcessState state) { switch (state) { case QProcess::NotRunning: toggleInterpreterActions(false); case QProcess::Starting: break; case QProcess::Running: toggleInterpreterActions(true); break; } } void MainWindow::closeEvent(QCloseEvent* event) { if (!quit()) event->ignore(); } bool MainWindow::close(Document* doc) { if (doc->textDocument()->isModified() && doc->promptsToSave()) { QMessageBox::StandardButton ret; ret = QMessageBox::warning(mInstance, tr("SuperCollider IDE"), tr("There are unsaved changes in document '%1'.\n\n" "Do you want to save it?") .arg(doc->title()), QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Save // the default ); switch (ret) { case QMessageBox::Cancel: return false; case QMessageBox::Save: if (!MainWindow::save(doc)) return false; break; default:; } } Main::instance()->documentManager()->close(doc); return true; } bool MainWindow::reload(Document* doc) { if (doc->filePath().isEmpty()) return false; if (doc->textDocument()->isModified()) { QMessageBox::StandardButton ret; ret = QMessageBox::warning(mInstance, tr("SuperCollider IDE"), tr("There are unsaved changes in document '%1'.\n\n" "Do you want to reload it?") .arg(doc->title()), QMessageBox::Yes | QMessageBox::No, QMessageBox::No // the default ); if (ret == QMessageBox::No) return false; } return Main::instance()->documentManager()->reload(doc); } QString MainWindow::documentSavePath(Document* document) const { if (!document->filePath().isEmpty()) return document->filePath(); if (!mLastDocumentSavePath.isEmpty()) return QFileInfo(mLastDocumentSavePath).path(); QString interpreterWorkingDir = Main::settings()->value("IDE/interpreter/runtimeDir").toString(); if (!interpreterWorkingDir.isEmpty()) return interpreterWorkingDir; return QStandardPaths::standardLocations(QStandardPaths::HomeLocation)[0]; } bool MainWindow::save(Document* doc, bool forceChoose, bool saveInExtensionFolder) { const bool documentHasPath = !doc->filePath().isEmpty(); if (!forceChoose && !(doc->isModified()) && documentHasPath) return true; DocumentManager* documentManager = Main::instance()->documentManager(); bool fileIsWritable = true; if ((!forceChoose) && documentHasPath) { QFileInfo fileInfo(doc->filePath()); fileIsWritable = fileInfo.isWritable(); if (!fileIsWritable) { QMessageBox::warning(instance(), tr("Saving read-only file"), tr("File is read-only. Please select a new location to save to."), QMessageBox::Ok, QMessageBox::NoButton); } } if (forceChoose || !documentHasPath || !fileIsWritable) { QFileDialog dialog(mInstance); dialog.setAcceptMode(QFileDialog::AcceptSave); dialog.setFileMode(QFileDialog::AnyFile); QStringList filters = QStringList() << tr("All Files (*)") << tr("SuperCollider Document (*.scd)") << tr("SuperCollider Class File (*.sc)") << tr("SuperCollider Help Source (*.schelp)"); dialog.setNameFilters(filters); if (saveInExtensionFolder) { dialog.setDirectory(standardDirectory(ScExtensionUserDir)); } else { QString path = mInstance->documentSavePath(doc); QFileInfo path_info(path); if (path_info.isDir()) // FIXME: // KDE native file dialog shows parent directory instead (KDE bug 229375) dialog.setDirectory(path); else dialog.selectFile(path); // NOTE: do not use QFileDialog::setDefaultSuffix(), because it only adds // the suffix after the dialog is closed, without showing a warning if the // filepath with added suffix already exists! } #ifdef Q_OS_MAC QWidget* last_active_window = QApplication::activeWindow(); #endif int result = dialog.exec(); // FIXME: workaround for Qt bug 25295 // See SC issue #678 #ifdef Q_OS_MAC if (last_active_window) last_active_window->activateWindow(); #endif QString save_path; if (result == QDialog::Accepted) { save_path = dialog.selectedFiles()[0]; if (save_path.indexOf('.') == -1 && !QFile::exists(save_path)) { save_path.append(".scd"); QFileInfo save_path_info(save_path); if (save_path_info.exists()) { QString msg = tr("Extension \".scd\" was automatically added to the " "selected file name, but the file \"%1\" already exists.\n\n" "Do you wish to overwrite it?") .arg(save_path_info.fileName()); QMessageBox::StandardButton result = QMessageBox::warning(mInstance, tr("Overwrite File?"), msg, QMessageBox::Yes | QMessageBox::No); if (result != QMessageBox::Yes) save_path.clear(); } } } if (!save_path.isEmpty()) { if (!saveInExtensionFolder) mInstance->mLastDocumentSavePath = save_path; return documentManager->saveAs(doc, save_path); } else { return false; } } else return documentManager->save(doc); } void MainWindow::newDocument() { mMain->documentManager()->create(); } QString MainWindow::documentOpenPath() const { GenericCodeEditor* currentEditor = mEditors->currentEditor(); if (currentEditor) { QString currentEditorPath = currentEditor->document()->filePath(); if (!currentEditorPath.isEmpty()) return currentEditorPath; } const QStringList& recentDocuments = Main::documentManager()->recents(); if (!recentDocuments.isEmpty()) return recentDocuments[0]; QString interpreterWorkingDir = Main::settings()->value("IDE/interpreter/runtimeDir").toString(); if (!interpreterWorkingDir.isEmpty()) return interpreterWorkingDir; return QStandardPaths::standardLocations(QStandardPaths::HomeLocation)[0]; } void MainWindow::openDocument() { QFileDialog dialog(this, Qt::Dialog); dialog.setModal(true); dialog.setWindowModality(Qt::ApplicationModal); dialog.setFileMode(QFileDialog::ExistingFiles); QString path = documentOpenPath(); QFileInfo path_info(path); if (path_info.isDir()) dialog.setDirectory(path); else dialog.setDirectory(path_info.dir()); QStringList filters; filters << tr("All Files (*)") << tr("SuperCollider (*.scd *.sc)") << tr("SuperCollider Help Source (*.schelp)"); dialog.setNameFilters(filters); #ifdef Q_OS_MAC QWidget* last_active_window = QApplication::activeWindow(); #endif if (dialog.exec()) { QStringList filenames = dialog.selectedFiles(); foreach (QString filename, filenames) mMain->documentManager()->open(filename); } // FIXME: workaround for Qt bug 25295 // See SC issue #678 #ifdef Q_OS_MAC if (last_active_window) last_active_window->activateWindow(); #endif } void MainWindow::restoreDocuments() { DocumentManager* docMng = Main::instance()->documentManager(); if (docMng->needRestore()) { QString msg = tr("Supercollider didn't quit properly last time\n" "Do you want to restore files saved as temporary backups?"); QMessageBox::StandardButton restore = QMessageBox::warning( mInstance, tr("Restore files?"), msg, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); if (restore == QMessageBox::Yes) docMng->restore(); else docMng->deleteRestore(); } } void MainWindow::openStartupFile() { QString configDir = standardDirectory(ScConfigUserDir); QDir dir; // Create the config dir if non existent: dir.mkpath(configDir); if (!dir.cd(configDir)) { qWarning() << "Could not access config dir:" << configDir; return; } QString filePath = dir.filePath("startup.scd"); // Try creating the file if non-existent: if (!QFile::exists(filePath)) { QFile file(filePath); if (!file.open(QIODevice::WriteOnly)) { file.close(); qWarning() << "Could not create startup file:" << filePath; return; } file.close(); } mMain->documentManager()->open(filePath, -1, 0, false); } void MainWindow::openUserSupportDirectory() { QUrl dirUrl = QUrl::fromLocalFile(standardDirectory(ScAppDataUserDir)); QDesktopServices::openUrl(dirUrl); } void MainWindow::saveDocument() { GenericCodeEditor* editor = mEditors->currentEditor(); if (!editor) return; Document* doc = editor->document(); Q_ASSERT(doc); MainWindow::save(doc); } void MainWindow::saveDocumentAs() { GenericCodeEditor* editor = mEditors->currentEditor(); if (!editor) return; Document* doc = editor->document(); Q_ASSERT(doc); MainWindow::save(doc, true); } void MainWindow::saveDocumentAsExtension() { GenericCodeEditor* editor = mEditors->currentEditor(); if (!editor) return; Document* doc = editor->document(); Q_ASSERT(doc); MainWindow::save(doc, true, true); } void MainWindow::saveAllDocuments() { QList<Document*> docs = mMain->documentManager()->documents(); foreach (Document* doc, docs) if (!MainWindow::save(doc)) return; } void MainWindow::reloadDocument() { GenericCodeEditor* editor = mEditors->currentEditor(); if (!editor) return; Q_ASSERT(editor->document()); MainWindow::reload(editor->document()); } void MainWindow::closeDocument() { GenericCodeEditor* editor = mEditors->currentEditor(); if (!editor) return; Q_ASSERT(editor->document()); MainWindow::close(editor->document()); } void MainWindow::closeAllDocuments() { if (promptSaveDocs()) { QList<Document*> docs = mMain->documentManager()->documents(); foreach (Document* doc, docs) mMain->documentManager()->close(doc); } } bool MainWindow::promptSaveDocs() { // LATER: maybe this should go to the DocumentManager class? QList<Document*> docs = mMain->documentManager()->documents(); QList<Document*> unsavedDocs; foreach (Document* doc, docs) if (doc->textDocument()->isModified() && doc->promptsToSave()) unsavedDocs.append(doc); if (!unsavedDocs.isEmpty()) { DocumentsDialog dialog(unsavedDocs, DocumentsDialog::Quit, this); if (!dialog.exec()) return false; } return true; } void MainWindow::updateWindowTitle() { Session* session = mMain->sessionManager()->currentSession(); GenericCodeEditor* editor = mEditors->currentEditor(); Document* doc = editor ? editor->document() : 0; QString title; if (session) { title.append(session->name()); if (doc) title.append(": "); } if (doc) { if (!doc->filePath().isEmpty()) { QFileInfo info = QFileInfo(doc->filePath()); QString pathString = info.dir().path(); QString homePath = QDir::homePath(); if (pathString.startsWith(homePath)) pathString.replace(0, homePath.size(), QStringLiteral("~")); QString titleString = QStringLiteral("%1 (%2)").arg(info.fileName(), pathString); title.append(titleString); setWindowFilePath(doc->filePath()); } else { title.append(tr("Untitled")); setWindowFilePath(""); } } else { setWindowFilePath(""); } if (!title.isEmpty()) title.append(" - "); title.append("SuperCollider IDE"); setWindowTitle(title); } void MainWindow::toggleFullScreen() { if (isFullScreen()) { setWindowState(windowState() & ~Qt::WindowFullScreen); updateClockWidget(false); } else { setWindowState(windowState() | Qt::WindowFullScreen); updateClockWidget(true); } } void MainWindow::updateClockWidget(bool isFullScreen) { if (!isFullScreen) { if (mClockLabel) { delete mClockLabel; mClockLabel = NULL; } } else { if (mClockLabel == NULL) { mClockLabel = new ClockStatusBox(this); statusBar()->insertWidget(0, mClockLabel); } } } void MainWindow::openSession(const QString& sessionName) { mMain->sessionManager()->openSession(sessionName); } void MainWindow::lookupImplementationForCursor() { static const QByteArray signature = QMetaObject::normalizedSignature("openDefinition()"); invokeMethodOnFirstResponder(signature); } void MainWindow::lookupImplementation() { Main::openDefinition(QString(), QApplication::activeWindow()); } void MainWindow::lookupReferencesForCursor() { static const QByteArray signature = QMetaObject::normalizedSignature("findReferences()"); invokeMethodOnFirstResponder(signature); } void MainWindow::lookupReferences() { Main::findReferences(QString(), QApplication::activeWindow()); } void MainWindow::showStatusMessage(QString const& string) { mStatusBar->showMessage(string, 3000); } void MainWindow::applySettings(Settings::Manager* settings) { applyCursorBlinkingSettings(settings); mPostDocklet->mPostWindow->applySettings(settings); #ifdef SC_USE_QTWEBENGINE mHelpBrowserDocklet->browser()->applySettings(settings); #endif // SC_USE_QTWEBENGINE mCmdLine->applySettings(settings); } void MainWindow::applyCursorBlinkingSettings(Settings::Manager* settings) { const bool disableBlinkingCursor = settings->value("IDE/editor/disableBlinkingCursor").toBool(); const int defaultCursorFlashTime = settings->defaultCursorFlashTime(); QApplication::setCursorFlashTime(disableBlinkingCursor ? 0 : defaultCursorFlashTime); } void MainWindow::storeSettings(Settings::Manager* settings) { mPostDocklet->mPostWindow->storeSettings(settings); } void MainWindow::updateSessionsMenu() { mSessionsMenu->clear(); QStringList sessions = mMain->sessionManager()->availableSessions(); foreach (const QString& session, sessions) mSessionsMenu->addAction(session); } void MainWindow::showSwitchSessionDialog() { SessionSwitchDialog* dialog = new SessionSwitchDialog(this); int result = dialog->exec(); if (result == QDialog::Accepted) openSession(dialog->activeElement()); delete dialog; } void MainWindow::showAbout() { QString aboutString = "<h3>SuperCollider %1</h3>" "<p>%2</p>" "&copy; James McCartney and others.<br>" "<h3>SuperCollider IDE</h3>" "&copy; Jakob Leben, Tim Blechmann and others.<br>"; aboutString = aboutString.arg(SC_VersionString().c_str()).arg(SC_BuildString().c_str()); QMessageBox::about(this, tr("About SuperCollider IDE"), aboutString); } void MainWindow::showAboutQT() { QMessageBox::aboutQt(this); } void MainWindow::toggleInterpreterActions(bool enabled) { mEditors->action(MultiEditor::EvaluateCurrentDocument)->setEnabled(enabled); mEditors->action(MultiEditor::EvaluateLine)->setEnabled(enabled); mEditors->action(MultiEditor::EvaluateRegion)->setEnabled(enabled); } void MainWindow::showCmdLine() { mToolBox->setCurrentWidget(mCmdLine); mToolBox->show(); mCmdLine->setFocus(Qt::OtherFocusReason); } void MainWindow::showCmdLine(const QString& cmd) { mCmdLine->setText(cmd); showCmdLine(); } void MainWindow::cmdLineForCursor() { static const QByteArray signature = QMetaObject::normalizedSignature("openCommandLine()"); invokeMethodOnFirstResponder(signature); } void MainWindow::showGoToLineTool() { GenericCodeEditor* editor = mEditors->currentEditor(); mGoToLineTool->setValue(editor ? editor->textCursor().blockNumber() + 1 : 0); mToolBox->setCurrentWidget(mGoToLineTool); mToolBox->show(); mGoToLineTool->setFocus(); } void MainWindow::showFindTool() { mFindReplaceTool->setMode(TextFindReplacePanel::Find); mFindReplaceTool->initiate(); mToolBox->setCurrentWidget(mFindReplaceTool); mToolBox->show(); mFindReplaceTool->setFocus(Qt::OtherFocusReason); } void MainWindow::showReplaceTool() { mFindReplaceTool->setMode(TextFindReplacePanel::Replace); mFindReplaceTool->initiate(); mToolBox->setCurrentWidget(mFindReplaceTool); mToolBox->show(); mFindReplaceTool->setFocus(Qt::OtherFocusReason); } void MainWindow::hideToolBox() { GenericCodeEditor* editor = mEditors->currentEditor(); if (editor) { // This slot is mapped to Escape, so also clear highlighting // whenever invoked: editor->clearSearchHighlighting(); if (!editor->hasFocus()) editor->setFocus(Qt::OtherFocusReason); } mToolBox->hide(); } void MainWindow::showSettings() { static std::atomic<bool> showingSettings { false }; if (showingSettings.load()) return; showingSettings = true; try { Settings::Dialog dialog(mMain->settings()); dialog.resize(700, 400); int result = dialog.exec(); if (result == QDialog::Accepted) mMain->applySettings(); } catch (std::exception const& e) { qWarning() << "Error while executing settings dialog:" << e.what(); } showingSettings = false; } void MainWindow::lookupDocumentation() { PopupTextInput* dialog = new PopupTextInput(tr("Look up Documentation For"), QApplication::activeWindow()); bool success = dialog->exec(); if (success) Main::openDocumentation(dialog->textValue()); delete dialog; } void MainWindow::lookupDocumentationForCursor() { static const QByteArray signature = QMetaObject::normalizedSignature("openDocumentation()"); bool documentationOpened = false; QWidget* widget = QApplication::focusWidget(); int methodIdx = -1; widget = findFirstResponder(widget, signature.constData(), methodIdx); if (widget && methodIdx != -1) { widget->metaObject()->method(methodIdx).invoke(widget, Qt::DirectConnection, Q_RETURN_ARG(bool, documentationOpened)); }; if (!documentationOpened) openHelp(); } void MainWindow::openHelp() { #ifdef SC_USE_QTWEBENGINE if (mHelpBrowserDocklet->browser()->url().isEmpty()) mHelpBrowserDocklet->browser()->goHome(); mHelpBrowserDocklet->focus(); #endif // SC_USE_QTWEBENGINE } void MainWindow::openHelpAboutIDE() { #ifdef SC_USE_QTWEBENGINE mHelpBrowserDocklet->browser()->gotoHelpFor("Guides/SCIde"); mHelpBrowserDocklet->focus(); #endif // SC_USE_QTWEBENGINE } void MainWindow::doBugReport() { Settings::Manager* settings = mMain->settings(); bool useGitHubBugReport = false; if (settings->contains("IDE/useGitHubBugReport")) { useGitHubBugReport = settings->value("IDE/useGitHubBugReport").toBool(); } else { QMessageBox* dialog = new QMessageBox(); dialog->setText("Do you want to submit bugs using <a href=\"https://www.github.com\">GitHub</a>?"); dialog->setInformativeText("This requires a GitHub account."); dialog->addButton("Submit using GitHub", QMessageBox::YesRole); dialog->addButton("Submit anonymously", QMessageBox::NoRole); dialog->addButton("Cancel", QMessageBox::RejectRole); dialog->exec(); QMessageBox::ButtonRole clicked = dialog->buttonRole(dialog->clickedButton()); if (clicked == QMessageBox::YesRole || clicked == QMessageBox::NoRole) { useGitHubBugReport = (clicked == QMessageBox::YesRole); settings->setValue("IDE/useGitHubBugReport", useGitHubBugReport); } else { // Dialog was cancelled, so bail return; } } if (useGitHubBugReport) { QString url("https://github.com/supercollider/supercollider/issues/new"); QString formData("?labels=bug&body=Bug%20description%3A%0A%0ASteps%20to%20reproduce%3A%0A1.%0A2.%0A3.%0A%" "0AActual%20result%3A%0A%0AExpected%20result%3A%0A"); QDesktopServices::openUrl(url + formData); } else { QDesktopServices::openUrl(QStringLiteral("https://gitreports.com/issue/supercollider/supercollider")); } } void MainWindow::dragEnterEvent(QDragEnterEvent* event) { if (event->mimeData()->hasUrls()) { foreach (QUrl url, event->mimeData()->urls()) { if (QURL_IS_LOCAL_FILE(url)) { // LATER: check mime type ? event->acceptProposedAction(); return; } } } } bool MainWindow::checkFileExtension(const QString& fpath) { if (fpath.endsWith(".sc") || fpath.endsWith(".scd") || fpath.endsWith(".txt") || fpath.endsWith(".schelp")) { return true; } int ret = QMessageBox::question(this, tr("Open binary file?"), fpath + tr("\n\nThe file has an unrecognized extension. It may be a binary file. " "Would you still like to open it?"), QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel); if (ret != QMessageBox::Ok) return false; return true; } void MainWindow::dropEvent(QDropEvent* event) { const QMimeData* data = event->mimeData(); if (data->hasUrls()) { foreach (QUrl url, data->urls()) { if (QURL_IS_LOCAL_FILE(url)) { QString fpath = url.toLocalFile(); if (MainWindow::checkFileExtension(fpath)) Main::documentManager()->open(fpath); } } } } bool MainWindow::eventFilter(QObject* object, QEvent* event) { switch (event->type()) { case QEvent::ShortcutOverride: { QKeyEvent* key_event = static_cast<QKeyEvent*>(event); if (key_event->key() == 0) { // FIXME: // On Mac OS, for some global menu items, there is a ShortcutOverride event with // key == 0, which seems like a Qt bug. // Text widgets override all events with key < Qt::Key_Escape, which includes 0. // Instead, prevent overriding such events: event->ignore(); return true; } break; } default: break; } return QMainWindow::eventFilter(object, event); } //////////////////////////// ClockStatusBox //////////////////////////// ClockStatusBox::ClockStatusBox(QWidget* parent): StatusLabel(parent) { setTextColor(Qt::green); mTimerId = startTimer(1000); updateTime(); } ClockStatusBox::~ClockStatusBox() { killTimer(mTimerId); } void ClockStatusBox::timerEvent(QTimerEvent* e) { if (e->timerId() == mTimerId) updateTime(); } void ClockStatusBox::updateTime() { setText(QTime::currentTime().toString()); } } // namespace ScIDE
61,070
C++
.cpp
1,302
40.652074
120
0.691428
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
30,019
find_replace_tool.cpp
supercollider_supercollider/editors/sc-ide/widgets/find_replace_tool.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "find_replace_tool.hpp" #include "main_window.hpp" #include "code_editor/editor.hpp" #include "../core/main.hpp" #include "../core/settings/manager.hpp" #include <QApplication> #include <QTextBlock> #include <QToolButton> #include <QStyle> #include <QHBoxLayout> namespace ScIDE { TextFindReplacePanel::TextFindReplacePanel(QWidget* parent): QWidget(parent), mMode((Mode)0), // a hack so that first setMode() works mEditor(0), mSearchPosition(-1) { mFindField = new QLineEdit; mReplaceField = new QLineEdit; mNextBtn = new QToolButton(); mNextBtn->setIcon(style()->standardIcon(QStyle::SP_ArrowForward)); mNextBtn->setToolTip(tr("Find Next")); mPrevBtn = new QToolButton(); mPrevBtn->setIcon(style()->standardIcon(QStyle::SP_ArrowBack)); mPrevBtn->setToolTip(tr("Find Previous")); mReplaceBtn = new QToolButton(); mReplaceBtn->setText(tr("Replace")); mReplaceAllBtn = new QToolButton(); mReplaceAllBtn->setText(tr("Replace All")); mOptionsBtn = new QToolButton(); mOptionsBtn->setText(tr("Options")); mOptionsBtn->setIcon(QIcon::fromTheme("preferences-other")); mOptionsBtn->setPopupMode(QToolButton::InstantPopup); QMenu* optMenu = new QMenu(this); mMatchCaseAction = optMenu->addAction(tr("Match Case")); mMatchCaseAction->setCheckable(true); mRegExpAction = optMenu->addAction(tr("Regular Expression")); mRegExpAction->setCheckable(true); mWholeWordAction = optMenu->addAction(tr("Whole Words")); mWholeWordAction->setCheckable(true); mOptionsBtn->setMenu(optMenu); mFindLabel = new QLabel(tr("Find:")); mFindLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); mReplaceLabel = new QLabel(tr("Replace:")); mReplaceLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); mGrid = new QGridLayout(); mGrid->setContentsMargins(0, 0, 0, 0); mGrid->setSpacing(2); QHBoxLayout* findBtnLayout = new QHBoxLayout(); findBtnLayout->setContentsMargins(0, 0, 0, 0); findBtnLayout->setSpacing(1); findBtnLayout->addWidget(mPrevBtn); findBtnLayout->addWidget(mNextBtn); findBtnLayout->addStretch(0); findBtnLayout->addWidget(mOptionsBtn); mGrid->addWidget(mFindLabel, 0, 0); mGrid->addWidget(mFindField, 0, 1); mGrid->addLayout(findBtnLayout, 0, 2); QHBoxLayout* replaceBtnLayout = new QHBoxLayout(); replaceBtnLayout->setContentsMargins(0, 0, 0, 0); replaceBtnLayout->setSpacing(1); replaceBtnLayout->addWidget(mReplaceBtn); replaceBtnLayout->addWidget(mReplaceAllBtn); replaceBtnLayout->addStretch(0); mGrid->addWidget(mReplaceLabel, 1, 0); mGrid->addWidget(mReplaceField, 1, 1); mGrid->addLayout(replaceBtnLayout, 1, 2); mGrid->setColumnStretch(1, 1); setLayout(mGrid); setMode(Find); setFocusProxy(mFindField); QWidget::setTabOrder(mFindField, mReplaceField); mFindField->installEventFilter(this); connect(mNextBtn, SIGNAL(clicked()), this, SLOT(findNext())); connect(mPrevBtn, SIGNAL(clicked()), this, SLOT(findPrevious())); connect(mReplaceBtn, SIGNAL(clicked()), this, SLOT(replace())); connect(mReplaceAllBtn, SIGNAL(clicked()), this, SLOT(replaceAll())); connect(mFindField, SIGNAL(returnPressed()), this, SLOT(onFindFieldReturn())); connect(mFindField, SIGNAL(textChanged(QString)), this, SLOT(onFindFieldTextChanged())); connect(mReplaceField, SIGNAL(returnPressed()), this, SLOT(replace())); // Update search results when options change: connect(optMenu, SIGNAL(triggered(QAction*)), this, SLOT(findAll())); Settings::Manager* settings = Main::settings(); QAction* action; action = mActions[FindNext] = new QAction(tr("Find Next"), this); action->setShortcut(tr("Ctrl+G", "Find Next")); connect(action, SIGNAL(triggered()), this, SLOT(findNext())); settings->addAction(action, "editor-find-next", tr("Text Editor")); action = mActions[FindPrevious] = new QAction(tr("Find Previous"), this); action->setShortcut(tr("Ctrl+Shift+G", "Find Previous")); connect(action, SIGNAL(triggered()), this, SLOT(findPrevious())); settings->addAction(action, "editor-find-previous", tr("Text Editor")); } void TextFindReplacePanel::setMode(Mode mode) { if (mode == mMode) return; mMode = mode; bool visible = mMode == Replace; mReplaceLabel->setVisible(visible); mReplaceField->setVisible(visible); mReplaceBtn->setVisible(visible); mReplaceAllBtn->setVisible(visible); } void TextFindReplacePanel::initiate() { mSearchPosition = -1; if (mEditor) { QTextCursor c(mEditor->textCursor()); if (c.hasSelection() && c.document()->findBlock(c.selectionStart()) == c.document()->findBlock(c.selectionEnd())) { mFindField->setText(c.selectedText()); mReplaceField->clear(); } } mFindField->selectAll(); findAll(); } QRegularExpression TextFindReplacePanel::regexp() { QString pattern = findString(); QRegularExpression::PatternOptions opt = QRegularExpression::PatternOption::NoPatternOption; QRegularExpression expr; if (asRegExp()) { expr = QRegularExpression(pattern); } else { expr = QRegularExpression(QRegularExpression::escape(pattern)); opt |= QRegularExpression::PatternOption::DontCaptureOption; } if (!matchCase()) opt |= QRegularExpression::PatternOption::CaseInsensitiveOption; expr.setPatternOptions(opt); return expr; } QTextDocument::FindFlags TextFindReplacePanel::flags() { QTextDocument::FindFlags f; if (wholeWords()) f |= QTextDocument::FindWholeWords; return f; } void TextFindReplacePanel::findNext() { find(false); } void TextFindReplacePanel::findPrevious() { find(true); } void TextFindReplacePanel::onFindFieldReturn() { find(QApplication::keyboardModifiers() & Qt::ShiftModifier); } void TextFindReplacePanel::onFindFieldTextChanged() { // Incremental search if (!mEditor) return; QRegularExpression expr(regexp()); QTextDocument::FindFlags flagz(flags()); if (mSearchPosition == -1) mSearchPosition = mEditor->textCursor().selectionStart(); int count = mEditor->findAll(expr, flagz); if (!expr.pattern().isEmpty()) reportFoundOccurrencies(count); QTextCursor searchCursor(mEditor->textDocument()); searchCursor.setPosition(mSearchPosition); if (expr.pattern().isEmpty()) { mEditor->setTextCursor(searchCursor); } else if (count) { mEditor->setTextCursor(searchCursor); mEditor->find(expr, flagz); } } bool TextFindReplacePanel::eventFilter(QObject* obj, QEvent* ev) { if (obj == mFindField && ev->type() == QEvent::FocusOut) mSearchPosition = -1; return QWidget::eventFilter(obj, ev); } void TextFindReplacePanel::find(bool backwards) { // Non incremental search! if (!mEditor) return; QRegularExpression expr = regexp(); if (expr.pattern().isEmpty()) return; QTextDocument::FindFlags opt = flags(); if (backwards) opt |= QTextDocument::FindBackward; mEditor->find(expr, opt); // This was not incremental search, so reset search position mSearchPosition = -1; } void TextFindReplacePanel::findAll() { if (!mEditor) return; QRegularExpression expr = regexp(); // NOTE: empty expression removes any search highlighting int count = mEditor->findAll(expr, flags()); if (!expr.pattern().isEmpty()) reportFoundOccurrencies(count); } void TextFindReplacePanel::replace() { if (!mEditor) return; QRegularExpression expr = regexp(); if (expr.pattern().isEmpty()) return; mEditor->replace(expr, replaceString(), flags()); mSearchPosition = -1; } void TextFindReplacePanel::replaceAll() { if (!mEditor) return; QRegularExpression expr = regexp(); if (expr.pattern().isEmpty()) return; QTextDocument::FindFlags opt = flags(); int count = mEditor->replaceAll(expr, replaceString(), opt); reportReplacedOccurrencies(count); mSearchPosition = -1; } void TextFindReplacePanel::reportFoundOccurrencies(int count) { QString message = tr("%n matches found.", "Find text in document...", count); MainWindow::instance()->showStatusMessage(message); } void TextFindReplacePanel::reportReplacedOccurrencies(int count) { QString message = tr("%n matches replaced.", "Find/replace text in document...", count); MainWindow::instance()->showStatusMessage(message); } } // namespace ScIDE
9,507
C++
.cpp
232
35.87931
111
0.709365
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
30,020
cmd_line.cpp
supercollider_supercollider/editors/sc-ide/widgets/cmd_line.cpp
/* SuperCollider Qt IDE Copyright (c) 2010-2012 Jakob Leben Copyright (c) 2012 Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cmd_line.hpp" #include "main_window.hpp" #include "util/gui_utilities.hpp" #include "../core/main.hpp" #include "../core/settings/manager.hpp" #include <QHBoxLayout> #include <QLabel> #include <QKeyEvent> namespace ScIDE { QString CmdLineEdit::symbolUnderCursor() { if (hasSelectedText()) return selectedText(); else { int position = cursorPosition(); return tokenInStringAt(position, text()); } } bool CmdLineEdit::openDocumentation() { return Main::openDocumentation(symbolUnderCursor()); } void CmdLineEdit::openDefinition() { return Main::openDefinition(symbolUnderCursor(), MainWindow::instance()); } void CmdLineEdit::openCommandLine() { return Main::openCommandLine(symbolUnderCursor()); } void CmdLineEdit::findReferences() { return Main::findReferences(symbolUnderCursor(), MainWindow::instance()); } CmdLine::CmdLine(const QString& text, int maxHist): curHistory(-1), maxHistory(qMax(1, maxHist)) { QLabel* lbl = new QLabel(text); expr = new CmdLineEdit; QHBoxLayout* l = new QHBoxLayout; l->setContentsMargins(0, 0, 0, 0); l->addWidget(lbl); l->addWidget(expr); setLayout(l); expr->installEventFilter(this); setFocusProxy(expr); applySettings(Main::settings()); } void CmdLine::applySettings(Settings::Manager* settings) { QFont codeFont = settings->codeFont(); expr->setFont(codeFont); } void CmdLine::setText(const QString& text) { expr->setText(text); } bool CmdLine::eventFilter(QObject*, QEvent* e) { int type = e->type(); if (type != QEvent::KeyPress) return false; QKeyEvent* ke = static_cast<QKeyEvent*>(e); switch (ke->key()) { case Qt::Key_Return: case Qt::Key_Enter: if (expr->text().isEmpty()) return true; emit invoked(expr->text(), false); if (history.count() == 0 || history[0] != expr->text()) { if (history.count() >= maxHistory) history.removeAt(history.count() - 1); history.prepend(expr->text()); } curHistory = -1; expr->clear(); return true; case Qt::Key_Up: if (curHistory < history.count() - 1) { expr->blockSignals(true); expr->setText(history[++curHistory]); expr->blockSignals(false); } return true; case Qt::Key_Down: if (curHistory > -1) { --curHistory; expr->blockSignals(true); if (curHistory == -1) expr->clear(); else expr->setText(history[curHistory]); expr->blockSignals(false); } return true; default: return false; } } } // namespace ScIDE
3,610
C++
.cpp
97
30.938144
112
0.65911
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,021
post_window.cpp
supercollider_supercollider/editors/sc-ide/widgets/post_window.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "main_window.hpp" #include "post_window.hpp" #include "util/gui_utilities.hpp" #include "../core/main.hpp" #include "../core/settings/manager.hpp" #include "../core/settings/theme.hpp" #include "../core/util/overriding_action.hpp" #include <QApplication> #include <QScreen> #include <QWindow> #include <QHBoxLayout> #include <QLabel> #include <QPointer> #include <QScrollBar> #include <QShortcut> #include <QKeyEvent> #include <QTextDocumentFragment> #include <QMimeData> namespace ScIDE { PostWindow::PostWindow(QWidget* parent): QPlainTextEdit(parent) { setReadOnly(true); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); setFrameShape(QFrame::NoFrame); previousChar = QChar('\n'); QRect availableScreenRect = this->screen()->availableGeometry(); mSizeHint = QSize(availableScreenRect.width() * 0.4, availableScreenRect.height() * 0.3); createActions(Main::settings()); setContextMenuPolicy(Qt::ActionsContextMenu); connect(this, SIGNAL(scrollToBottomRequest()), this, SLOT(scrollToBottom()), Qt::QueuedConnection); applySettings(Main::settings()); } void PostWindow::createActions(Settings::Manager* settings) { QAction* action; OverridingAction* ovrAction; QString postCategory(tr("Post Window")); mActions[Copy] = action = new QAction(tr("Copy"), this); action->setShortcut(QKeySequence::Copy); action->setShortcutContext(Qt::WidgetShortcut); action->setEnabled(false); connect(action, SIGNAL(triggered()), this, SLOT(copy())); connect(this, SIGNAL(copyAvailable(bool)), action, SLOT(setEnabled(bool))); addAction(action); mActions[Clear] = action = new QAction(tr("Clear"), this); action->setStatusTip(tr("Clear post window")); action->setShortcutContext(Qt::ApplicationShortcut); action->setShortcut(tr("Ctrl+Shift+P", "Clear post window")); settings->addAction(action, "post-clear", postCategory); connect(action, SIGNAL(triggered()), this, SLOT(clear())); addAction(action); action = new QAction(this); action->setSeparator(true); addAction(action); mActions[DocClose] = ovrAction = new OverridingAction(tr("Close"), this); action->setStatusTip(tr("Close the current document")); connect(ovrAction, SIGNAL(triggered()), this, SLOT(closeDocument())); ovrAction->addToWidget(this); mActions[ZoomIn] = ovrAction = new OverridingAction(tr("Enlarge Font"), this); ovrAction->setIconText("+"); ovrAction->setStatusTip(tr("Enlarge post window font")); connect(ovrAction, SIGNAL(triggered()), this, SLOT(zoomIn())); ovrAction->addToWidget(this); mActions[ZoomOut] = ovrAction = new OverridingAction(tr("Shrink Font"), this); ovrAction->setIconText("-"); ovrAction->setStatusTip(tr("Shrink post window font")); connect(ovrAction, SIGNAL(triggered()), this, SLOT(zoomOut())); ovrAction->addToWidget(this); mActions[ResetZoom] = ovrAction = new OverridingAction(tr("Reset Font Size"), this); connect(ovrAction, SIGNAL(triggered()), this, SLOT(resetZoom())); ovrAction->addToWidget(this); action = new QAction(this); action->setSeparator(true); addAction(action); mActions[LineWrap] = action = new QAction(tr("Wrap Text"), this); action->setStatusTip(tr("Wrap lines wider than the post window")); action->setCheckable(true); addAction(action); connect(action, SIGNAL(triggered(bool)), this, SLOT(setLineWrap(bool))); settings->addAction(action, "post-line-wrap", postCategory); mActions[AutoScroll] = action = new QAction(tr("Auto Scroll"), this); action->setStatusTip(tr("Scroll to bottom on new posts")); action->setCheckable(true); action->setChecked(true); connect(action, SIGNAL(triggered(bool)), this, SLOT(onAutoScrollTriggered(bool))); addAction(action); settings->addAction(action, "post-auto-scroll", postCategory); } void PostWindow::updateActionShortcuts(Settings::Manager* settings) { settings->beginGroup("IDE/shortcuts"); mActions[DocClose]->setShortcut(settings->shortcut("ide-document-close")); mActions[ZoomIn]->setShortcut(settings->shortcut("editor-enlarge-font")); mActions[ZoomOut]->setShortcut(settings->shortcut("editor-shrink-font")); mActions[ResetZoom]->setShortcut(settings->shortcut("editor-reset-font-size")); settings->endGroup(); } void PostWindow::closeDocument() { MainWindow::instance()->postDocklet()->close(); } void PostWindow::applySettings(Settings::Manager* settings) { int scrollback = settings->value("IDE/postWindow/scrollback").toInt(); QFont font = settings->codeFont(); QPalette palette; QTextCharFormat format; format.merge(settings->getThemeVal("text")); format.merge(settings->getThemeVal("postwindowtext")); QBrush bg = format.background(); QBrush fg = format.foreground(); if (bg.style() != Qt::NoBrush) palette.setBrush(QPalette::Base, bg); if (fg.style() != Qt::NoBrush) palette.setBrush(QPalette::Text, fg); bool lineWrap = settings->value("IDE/postWindow/lineWrap").toBool(); setMaximumBlockCount(scrollback); setFont(font); setPalette(palette); setLineWrap(lineWrap); QFontMetrics metrics(font); QString stringOfSpaces(settings->value("IDE/editor/indentWidth").toInt(), QChar(' ')); setTabStopDistance(metrics.horizontalAdvance(stringOfSpaces)); updateActionShortcuts(settings); } void PostWindow::storeSettings(Settings::Manager* settings) { settings->setValue("IDE/postWindow/lineWrap", mActions[LineWrap]->isChecked()); } QString PostWindow::symbolUnderCursor() { QTextCursor cursor = textCursor(); if (cursor.hasSelection()) return cursor.selectedText(); else { QString blockString = cursor.block().text(); int position = cursor.positionInBlock(); return tokenInStringAt(position, blockString); } } void PostWindow::post(const QString& text) { bool scroll = mActions[AutoScroll]->isChecked(); QTextCursor cursor(document()); QChar linebreak = QChar('\n'); int startPos = 0, position = 0; foreach (const QChar chr, text) { if (previousChar == linebreak) { cursor.movePosition(QTextCursor::End); cursor.insertText(text.mid(startPos, position - startPos), currentFormat); startPos = position; QString newLine = text.mid(position, text.length() - 1); currentFormat = formatForPostLine(newLine); } previousChar = chr; position++; } // handle remaining chars if not \n terminated if (startPos < text.length()) { cursor.movePosition(QTextCursor::End); cursor.insertText(text.mid(startPos, text.length() - startPos), currentFormat); } if (scroll) emit(scrollToBottomRequest()); } QTextCharFormat PostWindow::formatForPostLine(QString line) { Settings::Manager* settings = Main::settings(); QTextCharFormat postWindowError = settings->getThemeVal("postwindowerror"); QTextCharFormat postWindowWarning = settings->getThemeVal("postwindowwarning"); QTextCharFormat postWindowSuccess = settings->getThemeVal("postwindowsuccess"); QTextCharFormat postWindowEmphasis = settings->getThemeVal("postwindowemphasis"); QTextCharFormat format; if (line.startsWith("ERROR:", Qt::CaseInsensitive) || line.startsWith("!")) format.merge(postWindowError); else if (line.startsWith("WARNING:", Qt::CaseInsensitive) || line.startsWith("?")) format.merge(postWindowWarning); else if (line.startsWith("->")) format.merge(postWindowSuccess); else if (line.startsWith("***")) format.merge(postWindowEmphasis); // else no format return format; } void PostWindow::scrollToBottom() { verticalScrollBar()->triggerAction(QAbstractSlider::SliderToMaximum); } void PostWindow::onAutoScrollTriggered(bool on) { if (on) scrollToBottom(); } void PostWindow::zoomIn(int steps) { zoomFont(steps); } void PostWindow::zoomOut(int steps) { zoomFont(-steps); } void PostWindow::zoomFont(int steps) { QFont currentFont = font(); const int newSize = currentFont.pointSize() + steps; if (newSize <= 0) return; currentFont.setPointSize(newSize); setFont(currentFont); } void PostWindow::resetZoom() { QFont font = this->font(); QFont defaultFont = Main::settings()->codeFont(); font.setPointSize(defaultFont.pointSize()); setFont(font); } bool PostWindow::event(QEvent* event) { switch (event->type()) { case QEvent::ShortcutOverride: { QKeyEvent* kevent = static_cast<QKeyEvent*>(event); if (kevent == QKeySequence::Copy) { event->accept(); return true; } break; } default: break; } return QPlainTextEdit::event(event); } void PostWindow::wheelEvent(QWheelEvent* e) { // FIXME: Disable zooming for now, to avoid nasty effect when Ctrl // is unintentionally pressed while inertial scrolling is going on. // Moreover, Ctrl|Shift + Wheel scrolls by pages, which is also // rather annoying. // So rather just forward the event without modifiers. e->setModifiers(Qt::NoModifier); QPlainTextEdit::wheelEvent(e); return; #if 0 if (e->modifiers() == Qt::ControlModifier) { if (e->delta() > 0) zoomIn(); else zoomOut(); return; } QPlainTextEdit::wheelEvent(e); #endif } void PostWindow::focusOutEvent(QFocusEvent* event) { if (event->reason() == Qt::TabFocusReason) MainWindow::instance()->focusCodeEditor(); else QPlainTextEdit::focusOutEvent(event); } void PostWindow::mouseDoubleClickEvent(QMouseEvent* e) { QTextCursor cursor = textCursor(); cursor.beginEditBlock(); QPlainTextEdit::mouseDoubleClickEvent(e); extendSelectionForEnvVar(this, textCursor()); cursor.endEditBlock(); } QMimeData* PostWindow::createMimeDataFromSelection() const { // Here, we bundle up just the plaintext (not HTML, as is the default) of // the post window's selected contents. QMimeData* data = new QMimeData; data->setText(textCursor().selection().toPlainText()); return data; } bool PostWindow::openDocumentation() { return Main::openDocumentation(symbolUnderCursor()); } void PostWindow::openDefinition() { Main::openDefinition(symbolUnderCursor(), window()); } void PostWindow::openCommandLine() { Main::openCommandLine(symbolUnderCursor()); } void PostWindow::findReferences() { Main::findReferences(symbolUnderCursor(), window()); } void PostWindow::setLineWrap(bool lineWrapOn) { setLineWrapMode(lineWrapOn ? QPlainTextEdit::WidgetWidth : QPlainTextEdit::NoWrap); mActions[LineWrap]->setChecked(lineWrapOn); Main::settings()->setValue("IDE/postWindow/lineWrap", lineWrapOn); } PostDocklet::PostDocklet(QWidget* parent): Docklet(tr("Post window"), parent) { setAllowedAreas(Qt::BottomDockWidgetArea | Qt::RightDockWidgetArea | Qt::LeftDockWidgetArea); mPostWindow = new PostWindow; setWidget(mPostWindow); toolBar()->addAction(mPostWindow->mActions[PostWindow::AutoScroll]); // connect(this, SIGNAL(topLevelChanged(bool)), this, SLOT(onFloatingChanged(bool))); } void PostDocklet::onFloatingChanged(bool floating) { // HACK: After undocking when main window maximized, the dock widget can not be // resized anymore. Apparently it has to do something with the fact that the dock // widget spans from edge to edge of the screen. // The issue is avoided by slightly shrinking the dock widget. if (floating) dockWidget()->resize(dockWidget()->size() - QSize(1, 1)); } } // namespace ScIDE
12,611
C++
.cpp
290
38.52069
107
0.715429
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
30,022
doc_list.cpp
supercollider_supercollider/editors/sc-ide/widgets/doc_list.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "doc_list.hpp" #include "../core/doc_manager.hpp" #include <QApplication> #include <QStyle> namespace ScIDE { DocumentListWidget::DocumentListWidget(DocumentManager* manager, QWidget* parent): QListWidget(parent), mDocModifiedIcon(QApplication::style()->standardIcon(QStyle::SP_DialogSaveButton)) { setFrameShape(QFrame::NoFrame); connect(manager, SIGNAL(opened(Document*, int, int)), this, SLOT(onOpen(Document*, int, int))); connect(manager, SIGNAL(closed(Document*)), this, SLOT(onClose(Document*))); connect(manager, SIGNAL(saved(Document*)), this, SLOT(onSaved(Document*))); connect(this, SIGNAL(itemPressed(QListWidgetItem*)), this, SLOT(onItemClicked(QListWidgetItem*))); setDragDropMode(QAbstractItemView::InternalMove); } void DocumentListWidget::setCurrent(Document* doc) { if (!doc) setCurrentRow(-1); else { Item* itm = itemFor(doc); if (itm) setCurrentItem(itm); } } void DocumentListWidget::dropEvent(QDropEvent* event) { QListWidget::dropEvent(event); QList<Document*> tempDocumentList = listDocuments(); Q_EMIT(updateTabsOrder(tempDocumentList)); } QList<Document*> DocumentListWidget::listDocuments() { QList<Document*> list; for (int row = 0; row < count(); row++) { Item* itm = itemFor(item(row)); if (itm) { Document* doc = itm->mDoc; if (doc) { list << doc; } } } return list; } void DocumentListWidget::updateDockletOrder(int from, int to) { QListWidgetItem* itemToMove = takeItem(to); insertItem(from, itemToMove); setCurrentRow(from); } void DocumentListWidget::onOpen(Document* doc, int, int) { addItemFor(doc); } void DocumentListWidget::onClose(Document* doc) { delete itemFor(doc); } void DocumentListWidget::onSaved(Document* doc) { Item* item = itemFor(doc); if (item) item->setText(doc->title()); } void DocumentListWidget::onModificationChanged(Document* doc) { Item* item = itemFor(doc); if (item) item->setIcon(doc->textDocument()->isModified() ? mDocModifiedIcon : QIcon()); } void DocumentListWidget::onItemClicked(QListWidgetItem* litem) { dockletOrder = listDocuments(); Item* item = itemFor(litem); if (item) Q_EMIT(clicked(item->mDoc)); } DocumentListWidget::Item* DocumentListWidget::addItemFor(Document* doc) { Item* item = new Item(doc, this); QTextDocument* tdoc = doc->textDocument(); if (tdoc->isModified()) item->setIcon(mDocModifiedIcon); connect(tdoc, &QTextDocument::modificationChanged, [this, doc](bool) { onModificationChanged(doc); }); return item; } DocumentListWidget::Item* DocumentListWidget::itemFor(Document* doc) { int c = count(); for (int i = 0; i < c; ++i) { Item* itm = itemFor(item(i)); if (itm && itm->mDoc == doc) return itm; } return 0; } DocumentListWidget::Item* DocumentListWidget::itemFor(QListWidgetItem* litem) { if (litem->type() == QListWidgetItem::UserType) return static_cast<Item*>(litem); else return 0; } DocumentsDocklet::DocumentsDocklet(DocumentManager* manager, QWidget* parent): Docklet(tr("Documents"), parent), mDocList(new DocumentListWidget(manager)) { setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); setWidget(mDocList); } } // namespace ScIDE
4,286
C++
.cpp
111
33.612613
106
0.700265
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,023
editor_box.cpp
supercollider_supercollider/editors/sc-ide/widgets/editor_box.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "editor_box.hpp" #include "code_editor/sc_editor.hpp" #include "../core/main.hpp" #include <QPainter> #include <QScrollBar> #include <QModelIndex> namespace ScIDE { QPointer<CodeEditorBox> CodeEditorBox::gActiveBox; CodeEditorBox::CodeEditorBox(MultiSplitter* splitter, QWidget* parent): QWidget(parent), mSplitter(splitter) { setFocusPolicy(Qt::StrongFocus); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); mTopLayout = new QBoxLayout(QBoxLayout::BottomToTop); mTopLayout->setSpacing(1); mTopLayout->setContentsMargins(0, 0, 0, 0); mLayout = new QStackedLayout(); mTopLayout->addLayout(mLayout); setLayout(mTopLayout); mDocComboBox = new QComboBox(); mDocComboBox->setFocusPolicy(Qt::NoFocus); mTopLayout->addWidget(mDocComboBox); mProxyModel = new QSortFilterProxyModel(); mProxyModel->setSourceModel(Main::documentManager()->docModel()); mProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); mProxyModel->sort(0); mDocComboBox->setModel(mProxyModel); connect(mDocComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboSelectionChanged(int)), Qt::QueuedConnection); connect(Main::documentManager(), SIGNAL(closed(Document*)), this, SLOT(onDocumentClosed(Document*))); connect(Main::documentManager(), SIGNAL(saved(Document*)), this, SLOT(onDocumentSaved(Document*))); connect(Main::instance(), SIGNAL(applySettingsRequest(Settings::Manager*)), this, SLOT(applySettings(Settings::Manager*))); connect(mSplitter->editor(), SIGNAL(splitViewActivated()), this, SLOT(comboBoxWhenSplitting())); connect(mSplitter->editor(), SIGNAL(splitViewDeactivated()), this, SLOT(tabsWhenRemovingSplits())); applySettings(Main::settings()); } void CodeEditorBox::applySettings(Settings::Manager* settings) { bool comboBoxActive = settings->value("IDE/editor/useComboBox").toBool(); showComboBox(comboBoxActive); comboBoxWhenSplitting(); } void CodeEditorBox::comboBoxWhenSplitting() { if (mSplitter->count() > 1) { bool comboBoxInUse = Main::settings()->value("IDE/editor/useComboBox").toBool(); if (!comboBoxInUse) { bool comboBoxIsInUse = Main::settings()->value("IDE/editor/useComboBoxWhenSplitting").toBool(); showComboBox(comboBoxIsInUse); } } } void CodeEditorBox::tabsWhenRemovingSplits() { if (mSplitter->count() < 2) { bool comboBoxInUse = Main::settings()->value("IDE/editor/useComboBox").toBool(); showComboBox(comboBoxInUse); } } void CodeEditorBox::showComboBox(bool condition) { if (condition) mDocComboBox->show(); else mDocComboBox->hide(); } void CodeEditorBox::onComboSelectionChanged(int index) { QModelIndex proxyIndex = mProxyModel->index(index, 0); QModelIndex mRow = mProxyModel->mapToSource(proxyIndex); int mIndex = mRow.row(); if (mIndex >= 0 && index >= 0 && mDocComboBox) { setDocument(Main::documentManager()->docModel()->item(mIndex)->data().value<Document*>(), -1, 0); } } void CodeEditorBox::setDocument(Document* doc, int pos, int selectionLength) { if (!doc) return; GenericCodeEditor* editor = currentEditor(); bool switchEditor = !editor || editor->document() != doc; if (switchEditor) { editor = editorForDocument(doc); if (!editor) { editor = doc->isPlainText() ? new GenericCodeEditor(doc) : new ScCodeEditor(doc); editor->installEventFilter(this); mHistory.prepend(editor); mLayout->addWidget(editor); connect(this, SIGNAL(activeChanged(bool)), editor, SLOT(setActiveAppearance(bool))); } else { mHistory.removeOne(editor); mHistory.prepend(editor); } editor->setActiveAppearance(this->isActive()); editor->setReadOnly(!doc->editable()); mLayout->setCurrentWidget(editor); setFocusProxy(editor); int modelIndex = doc->modelItem()->index().row(); if (mDocComboBox) { mDocComboBox->blockSignals(true); QModelIndex mIndex = Main::documentManager()->docModel()->index(modelIndex, 0, QModelIndex()); QModelIndex proxyRow = mProxyModel->mapFromSource(mIndex); int proxyIndex = proxyRow.row(); mDocComboBox->setCurrentIndex(proxyIndex); mDocComboBox->setCurrentText(doc->title()); mDocComboBox->blockSignals(false); } } if (pos != -1) editor->showPosition(pos, selectionLength); if (switchEditor) emit currentChanged(editor); } void CodeEditorBox::onDocumentClosed(Document* doc) { GenericCodeEditor* editor = editorForDocument(doc); if (editor) { bool wasCurrent = editor == currentEditor(); mHistory.removeAll(editor); editor->deleteLater(); if (wasCurrent) { editor = currentEditor(); if (editor) mLayout->setCurrentWidget(editor); setFocusProxy(editor); emit currentChanged(editor); } } } void CodeEditorBox::onDocumentSaved(Document* doc) { // Check whether the document type still matches the editor type. // If not, replace the editor. int history_idx = historyIndexOf(doc); if (history_idx == -1) return; GenericCodeEditor* editor = mHistory[history_idx]; if (doc->isPlainText() == (qobject_cast<ScCodeEditor*>(editor) == 0)) return; bool was_current = editor == currentEditor(); bool was_focused = editor->window()->focusWidget() == editor; int cursor_position = editor->textCursor().position(); int scroll_position = editor->verticalScrollBar()->value(); mHistory.removeAt(history_idx); delete editor; editor = doc->isPlainText() ? new GenericCodeEditor(doc) : new ScCodeEditor(doc); editor->installEventFilter(this); mHistory.insert(history_idx, editor); mLayout->addWidget(editor); QTextCursor cursor(editor->textDocument()); cursor.setPosition(cursor_position); editor->setTextCursor(cursor); editor->verticalScrollBar()->setValue(scroll_position); if (was_current) { mLayout->setCurrentWidget(editor); setFocusProxy(editor); } if (was_focused) editor->setFocus(Qt::OtherFocusReason); emit currentChanged(editor); } GenericCodeEditor* CodeEditorBox::currentEditor() { if (mHistory.count()) return mHistory.first(); else return 0; } int CodeEditorBox::historyIndexOf(Document* doc) { int count = mHistory.count(); for (int idx = 0; idx < count; ++idx) if (mHistory[idx]->document() == doc) return idx; return -1; } GenericCodeEditor* CodeEditorBox::editorForDocument(Document* doc) { foreach (GenericCodeEditor* editor, mHistory) if (editor->document() == doc) return editor; return 0; } bool CodeEditorBox::eventFilter(QObject* object, QEvent* event) { switch (event->type()) { case QEvent::FocusIn: setActive(); default:; } return QWidget::eventFilter(object, event); } void CodeEditorBox::focusInEvent(QFocusEvent*) { setActive(); } Document* CodeEditorBox::currentDocument() { GenericCodeEditor* editor = currentEditor(); return editor ? editor->document() : 0; } void CodeEditorBox::paintEvent(QPaintEvent*) { if (mLayout->currentWidget() == 0) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing, true); int colorRatio = isActive() ? 160 : 125; painter.setBrush(palette().color(QPalette::Window).darker(colorRatio)); painter.setPen(Qt::NoPen); painter.drawRoundedRect(rect().adjusted(4, 4, -4, -4), 4, 4); } } } // namesapce ScIDE
8,698
C++
.cpp
211
35.004739
110
0.687604
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,024
documents_dialog.cpp
supercollider_supercollider/editors/sc-ide/widgets/documents_dialog.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "documents_dialog.hpp" #include "main_window.hpp" #include "../core/main.hpp" #include <QVBoxLayout> #include <QHBoxLayout> #include <QDialogButtonBox> #include <QPushButton> #include <QHeaderView> #include <QDir> #include <QApplication> namespace ScIDE { DocumentsDialog::DocumentsDialog(Mode mode, QWidget* parent): QDialog(parent) { init(mode); } DocumentsDialog::DocumentsDialog(const QList<Document*>& docs, Mode mode, QWidget* parent): QDialog(parent) { init(mode, docs); } void DocumentsDialog::init(Mode mode, const QList<Document*>& docs) { DocumentManager* mng = Main::documentManager(); connect(mng, SIGNAL(changedExternally(Document*)), this, SLOT(onDocumentChangedExternally(Document*))); mMode = mode; mLabel = new QLabel; mLabel->setWordWrap(true); mDocTree = new QTreeWidget; mDocTree->setRootIsDecorated(false); QStringList headerLabels; headerLabels << tr("Document") << tr("Path", "File path."); if (mode == ExternalChange) headerLabels << tr("Status"); mDocTree->setHeaderLabels(headerLabels); mDocTree->header()->setStretchLastSection(false); mDocTree->header()->setSectionResizeMode(1, QHeaderView::Stretch); if (mode == ExternalChange) mDocTree->header()->setSectionResizeMode(2, QHeaderView::ResizeToContents); switch (mode) { case ExternalChange: setWindowTitle(tr("Externally Changed Documents")); mLabel->setText(tr("The following documents have changed externally.\n\n" "Apply the desired actions to selected documents, until the list is empty.")); break; case Quit: setWindowTitle(tr("Unsaved Documents")); mLabel->setText(tr("The following documents have unsaved changes.\n\n" "Apply desired actions to selected documents, until the list is empty.")); break; } foreach (Document* doc, docs) addDocument(doc); QDialogButtonBox* dialogBtnBox = new QDialogButtonBox(); QPushButton* btn; QPushButton* defaultBtn; if (mode == ExternalChange) { defaultBtn = btn = dialogBtnBox->addButton(tr("&Reload"), QDialogButtonBox::ActionRole); btn->setIcon(QIcon::fromTheme("view-refresh")); connect(btn, SIGNAL(clicked()), this, SLOT(reloadSelected())); btn = dialogBtnBox->addButton(tr("Over&write"), QDialogButtonBox::ActionRole); btn->setIcon(QIcon::fromTheme("document-save")); connect(btn, SIGNAL(clicked()), this, SLOT(saveSelected())); btn = dialogBtnBox->addButton(tr("&Ignore"), QDialogButtonBox::AcceptRole); btn->setIcon(QIcon::fromTheme("window-close")); connect(btn, SIGNAL(clicked()), this, SLOT(ignoreSelected())); btn = dialogBtnBox->addButton(tr("&Close"), QDialogButtonBox::AcceptRole); btn->setIcon(QIcon::fromTheme("window-close")); connect(btn, SIGNAL(clicked()), this, SLOT(closeSelected())); } else { defaultBtn = btn = dialogBtnBox->addButton(tr("&Save"), QDialogButtonBox::ActionRole); btn->setIcon(QIcon::fromTheme("document-save")); connect(btn, SIGNAL(clicked()), this, SLOT(saveSelected())); btn = dialogBtnBox->addButton(tr("&Discard"), QDialogButtonBox::ActionRole); btn->setIcon(QIcon::fromTheme("window-close")); connect(btn, SIGNAL(clicked()), this, SLOT(ignoreSelected())); btn = dialogBtnBox->addButton(tr("&Cancel"), QDialogButtonBox::RejectRole); btn->setIcon(QIcon::fromTheme("window-close")); connect(btn, SIGNAL(clicked()), this, SLOT(reject())); } QPushButton* selectAllBtn = new QPushButton(tr("Select &All")); connect(selectAllBtn, SIGNAL(clicked()), this, SLOT(selectAll())); QPushButton* selectNoneBtn = new QPushButton(tr("Select N&one")); connect(selectNoneBtn, SIGNAL(clicked()), this, SLOT(selectNone())); QLabel* iconLabel = new QLabel; iconLabel->setPixmap(QApplication::style()->standardIcon(QStyle::SP_MessageBoxWarning).pixmap(48, 48)); iconLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); QHBoxLayout* lblBox = new QHBoxLayout(); lblBox->addWidget(iconLabel); lblBox->addWidget(mLabel); QHBoxLayout* selectionBox = new QHBoxLayout(); selectionBox->addWidget(selectAllBtn); selectionBox->addWidget(selectNoneBtn); QVBoxLayout* vbox = new QVBoxLayout(); vbox->addLayout(lblBox); vbox->addWidget(mDocTree); vbox->addLayout(selectionBox); vbox->addWidget(dialogBtnBox); setLayout(vbox); defaultBtn->setDefault(true); defaultBtn->setFocus(Qt::OtherFocusReason); resize(500, 300); } void DocumentsDialog::addDocument(Document* doc) { Item* item = new Item(doc); mDocTree->addTopLevelItem(item); } void DocumentsDialog::selectAll() { int c = count(); for (int i = 0; i < c; ++i) item(i)->setChecked(true); } void DocumentsDialog::selectNone() { int c = count(); for (int i = 0; i < c; ++i) item(i)->setChecked(false); } void DocumentsDialog::saveSelected() { int i = 0; while (i < count()) { Item* itm = item(i); if (itm->isChecked()) { if (!MainWindow::save(itm->document())) return; delete itm; } else ++i; } if (!count()) accept(); } void DocumentsDialog::reloadSelected() { DocumentManager* mng = Main::documentManager(); int i = 0; while (i < count()) { Item* itm = item(i); if (itm->isChecked()) { if (!mng->reload(itm->document())) return; delete itm; } else ++i; } if (!count()) accept(); } void DocumentsDialog::ignoreSelected() { int i = 0; while (i < count()) { Item* itm = item(i); if (itm->isChecked()) delete itm; else ++i; } if (!count()) accept(); } void DocumentsDialog::closeSelected() { DocumentManager* mng = Main::documentManager(); int i = 0; while (i < count()) { Item* itm = item(i); if (itm->isChecked()) { mng->close(itm->document()); delete itm; } else ++i; } if (!count()) accept(); } void DocumentsDialog::onDocumentChangedExternally(Document* doc) { int c = count(); for (int i = 0; i < c; ++i) { Item* itm = item(i); if (itm->document() == doc) { itm->update(); return; } } addDocument(doc); } DocumentsDialog::Item::Item(Document* doc): mDoc(doc) { update(); } void DocumentsDialog::Item::update() { setTitle(mDoc->title()); setPath(mDoc->filePath()); if (!mDoc->filePath().isEmpty() && !QFile::exists(mDoc->filePath())) { setStatus(tr("Removed")); setChecked(false); } else { setStatus(tr("Modified")); setChecked(true); } } }
7,831
C++
.cpp
205
31.8
109
0.649387
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,025
multi_editor.cpp
supercollider_supercollider/editors/sc-ide/widgets/multi_editor.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "multi_editor.hpp" #include "editor_box.hpp" #include "main_window.hpp" #include "lookup_dialog.hpp" #include "code_editor/sc_editor.hpp" #include "util/multi_splitter.hpp" #include "../core/doc_manager.hpp" #include "../core/sig_mux.hpp" #include "../core/main.hpp" #include "../core/sc_process.hpp" #include "../core/session_manager.hpp" #include <yaml-cpp/node/node.h> #include <yaml-cpp/parser.h> #include <QApplication> #include <QDebug> #include <QDialog> #include <QFileInfo> #include <QHBoxLayout> #include <QHeaderView> #include <QListView> #include <QMenu> #include <QPainter> #include <QStandardItemModel> #include <QShortcut> #include <QStyle> #include <QTreeWidget> #include <QVBoxLayout> namespace ScIDE { class DocumentSelectPopUp : public QDialog { public: DocumentSelectPopUp(const CodeEditorBox::History& history, QWidget* parent): #ifndef Q_OS_MAC QDialog(parent, Qt::Popup | Qt::FramelessWindowHint) #else QDialog(parent, Qt::Dialog | Qt::FramelessWindowHint) #endif { mModel = new QStandardItemModel(this); populateModel(history); mListView = new QListView(); mListView->setModel(mModel); mListView->setFrameShape(QFrame::NoFrame); QHBoxLayout* layout = new QHBoxLayout(this); layout->addWidget(mListView); layout->setContentsMargins(1, 1, 1, 1); connect(mListView, SIGNAL(activated(QModelIndex)), this, SLOT(accept())); mListView->setFocus(Qt::OtherFocusReason); QModelIndex nextIndex = mModel->index(1, 0); mListView->setCurrentIndex(nextIndex); mListView->setEditTriggers(QAbstractItemView::NoEditTriggers); } Document* exec(const QPoint& pos) { move(pos); if (QDialog::exec()) return currentDocument(); else return 0; } private: bool event(QEvent* event) { if (event->type() == QEvent::ShortcutOverride) { event->accept(); return true; } return QWidget::event(event); } void keyReleaseEvent(QKeyEvent* ke) { // adapted from qtcreator if (ke->modifiers() == 0 /*HACK this is to overcome some event inconsistencies between platforms*/ || (ke->modifiers() == Qt::AltModifier && (ke->key() == Qt::Key_Alt || ke->key() == -1))) { ke->accept(); accept(); } QDialog::keyReleaseEvent(ke); } void keyPressEvent(QKeyEvent* ke) { switch (ke->key()) { case Qt::Key_Down: case Qt::Key_Tab: cycleDown(); ke->accept(); return; case Qt::Key_Up: case Qt::Key_Backtab: cycleUp(); ke->accept(); return; case Qt::Key_Escape: reject(); return; default:; } QDialog::keyPressEvent(ke); } void paintEvent(QPaintEvent*) { QPainter painter(this); painter.setBrush(Qt::NoBrush); painter.setPen(palette().color(QPalette::Dark)); painter.drawRect(rect().adjusted(0, 0, -1, -1)); } void cycleDown() { int row = mListView->currentIndex().row() + 1; if (!mModel->hasIndex(row, 0)) row = 0; QModelIndex nextIndex = mModel->index(row, 0); mListView->setCurrentIndex(nextIndex); } void cycleUp() { int row = mListView->currentIndex().row() - 1; if (!mModel->hasIndex(row, 0)) row = mModel->rowCount() - 1; QModelIndex nextIndex = mModel->index(row, 0); mListView->setCurrentIndex(nextIndex); } Document* currentDocument() { QStandardItem* currentItem = mModel->itemFromIndex(mListView->currentIndex()); return currentItem ? currentItem->data().value<Document*>() : NULL; } void populateModel(const CodeEditorBox::History& history) { QList<Document*> displayDocuments; foreach (GenericCodeEditor* editor, history) displayDocuments << editor->document(); QList<Document*> managerDocuments = Main::documentManager()->documents(); foreach (Document* document, managerDocuments) if (!displayDocuments.contains(document)) displayDocuments << document; foreach (Document* document, displayDocuments) { QStandardItem* item = new QStandardItem(document->title()); item->setData(QVariant::fromValue(document)); mModel->appendRow(item); } } QListView* mListView; QStandardItemModel* mModel; }; EditorTabBar::EditorTabBar(QWidget* parent): QTabBar(parent) { setDocumentMode(true); setTabsClosable(true); setMovable(true); setUsesScrollButtons(true); setDrawBase(false); setElideMode(Qt::ElideNone); } void EditorTabBar::mousePressEvent(QMouseEvent* event) { if (event->button() == Qt::RightButton) { showContextMenu(event); event->accept(); return; } else if (event->button() == Qt::MiddleButton) { mTabUnderCursor = tabAt(event->pos()); onCloseTab(); event->accept(); return; } QTabBar::mousePressEvent(event); } void EditorTabBar::mouseDoubleClickEvent(QMouseEvent* event) { if (event->button() == Qt::LeftButton) { if (tabAt(event->pos()) == -1) { // no tab under cursor MainWindow::instance()->newDocument(); event->accept(); return; } } QTabBar::mouseDoubleClickEvent(event); } void EditorTabBar::showContextMenu(QMouseEvent* event) { mTabUnderCursor = tabAt(event->pos()); QMenu* menu = new QMenu(this); // Cannot have a close tab action if we are not over a tab if (mTabUnderCursor == -1) { menu->addAction(tr("Close All Tabs"), this, SLOT(onCloseOtherTabs())); } else { menu->addAction(tr("Close"), this, SLOT(onCloseTab())); menu->addAction(tr("Close Other Tabs"), this, SLOT(onCloseOtherTabs())); menu->addAction(tr("Close Tabs to the Right"), this, SLOT(onCloseTabsToTheRight())); } menu->popup(event->screenPos().toPoint()); } void EditorTabBar::onCloseTab() { Document* doc = tabData(mTabUnderCursor).value<Document*>(); assert(doc); MainWindow::close(doc); } void EditorTabBar::onCloseOtherTabs() { QVector<Document*> docsToClose; for (int currentTab = 0; currentTab != count(); ++currentTab) { if (currentTab != mTabUnderCursor) docsToClose.append(tabData(currentTab).value<Document*>()); } for (Document* doc : docsToClose) MainWindow::close(doc); } void EditorTabBar::onCloseTabsToTheRight() { QVector<Document*> docsToClose; for (int currentTab = mTabUnderCursor + 1; currentTab != count(); ++currentTab) docsToClose.append(tabData(currentTab).value<Document*>()); for (Document* doc : docsToClose) MainWindow::close(doc); } MultiEditor::MultiEditor(Main* main, QWidget* parent): QWidget(parent), mEditorSigMux(new SignalMultiplexer(this)), mBoxSigMux(new SignalMultiplexer(this)), #ifdef __APPLE__ mDocModifiedIcon(QApplication::style()->standardIcon(QStyle::SP_DriveHDIcon)) #else mDocModifiedIcon(QIcon::fromTheme("document-save")) #endif { mTabs = new EditorTabBar; mSplitter = new MultiSplitter(this); CodeEditorBox* defaultBox = newBox(mSplitter); mSplitter->addWidget(defaultBox); multiEditorLayout = new QVBoxLayout; multiEditorLayout->setContentsMargins(0, 0, 0, 0); multiEditorLayout->setSpacing(0); multiEditorLayout->addWidget(mTabs); multiEditorLayout->addWidget(mSplitter); setLayout(multiEditorLayout); makeSignalConnections(); connect(main, SIGNAL(applySettingsRequest(Settings::Manager*)), this, SLOT(applySettings(Settings::Manager*))); createActions(); setCurrentBox(defaultBox); // will updateActions(); applySettings(main->settings()); } void MultiEditor::makeSignalConnections() { DocumentManager* docManager = Main::documentManager(); connect(docManager, SIGNAL(opened(Document*, int, int)), this, SLOT(onOpen(Document*, int, int))); connect(docManager, SIGNAL(closed(Document*)), this, SLOT(onClose(Document*))); connect(docManager, SIGNAL(saved(Document*)), this, SLOT(update(Document*))); connect(docManager, SIGNAL(showRequest(Document*, int, int)), this, SLOT(show(Document*, int, int))); connect(docManager, SIGNAL(titleChanged(Document*)), this, SLOT(update(Document*))); connect(mTabs, SIGNAL(currentChanged(int)), this, SLOT(onCurrentTabChanged(int))); connect(mTabs, SIGNAL(tabCloseRequested(int)), this, SLOT(onCloseRequest(int))); connect(mTabs, SIGNAL(tabMoved(int, int)), this, SLOT(updateDocOrder(int, int))); mBoxSigMux->connect(SIGNAL(currentChanged(GenericCodeEditor*)), this, SLOT(onCurrentEditorChanged(GenericCodeEditor*))); } void MultiEditor::updateDocOrder(int from, int to) { Q_EMIT(updateDockletOrder(from, to)); } void MultiEditor::breakSignalConnections() { DocumentManager* docManager = Main::documentManager(); docManager->disconnect(this); mTabs->disconnect(this); mBoxSigMux->disconnect(this); } void MultiEditor::createActions() { Settings::Manager* settings = Main::settings(); QAction* action; const QString editorCategory(tr("Text Editor")); // Edit mActions[Undo] = action = new QAction(QIcon::fromTheme("edit-undo"), tr("&Undo"), this); action->setShortcut(tr("Ctrl+Z", "Undo")); action->setStatusTip(tr("Undo last editing action")); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(undo())); mEditorSigMux->connect(SIGNAL(undoAvailable(bool)), action, SLOT(setEnabled(bool))); settings->addAction(action, "editor-undo", editorCategory); mActions[Redo] = action = new QAction(QIcon::fromTheme("edit-redo"), tr("Re&do"), this); action->setShortcut(tr("Ctrl+Shift+Z", "Redo")); action->setStatusTip(tr("Redo next editing action")); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(redo())); mEditorSigMux->connect(SIGNAL(redoAvailable(bool)), action, SLOT(setEnabled(bool))); settings->addAction(action, "editor-redo", editorCategory); mActions[Cut] = action = new QAction(QIcon::fromTheme("edit-cut"), tr("Cu&t"), this); action->setShortcut(tr("Ctrl+X", "Cut")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); action->setStatusTip(tr("Cut text to clipboard")); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(cut())); mEditorSigMux->connect(SIGNAL(copyAvailable(bool)), action, SLOT(setEnabled(bool))); settings->addAction(action, "editor-cut", editorCategory); mActions[Copy] = action = new QAction(QIcon::fromTheme("edit-copy"), tr("&Copy"), this); action->setShortcut(tr("Ctrl+C", "Copy")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); action->setStatusTip(tr("Copy text to clipboard")); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(copy())); mEditorSigMux->connect(SIGNAL(copyAvailable(bool)), action, SLOT(setEnabled(bool))); settings->addAction(action, "editor-copy", editorCategory); mActions[Paste] = action = new QAction(QIcon::fromTheme("edit-paste"), tr("&Paste"), this); action->setShortcut(tr("Ctrl+V", "Paste")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); action->setStatusTip(tr("Paste text from clipboard")); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(paste())); settings->addAction(action, "editor-paste", editorCategory); mActions[IndentLineOrRegion] = action = new QAction(QIcon::fromTheme("format-indent-line"), tr("Autoindent Line or Region"), this); action->setStatusTip(tr("Autoindent Line or Region")); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(indent()), SignalMultiplexer::ConnectionOptional); settings->addAction(action, "editor-indent-auto", editorCategory); mActions[TriggerAutoCompletion] = action = new QAction(tr("Trigger Autocompletion"), this); action->setStatusTip(tr("Suggest possible completions of text at cursor")); action->setShortcut(tr("Ctrl+Space", "Trigger Autocompletion")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(triggerAutoCompletion()), SignalMultiplexer::ConnectionOptional); settings->addAction(action, "editor-autocompletion", editorCategory); mActions[TriggerMethodCallAid] = action = new QAction(tr("Trigger Method Call Aid"), this); action->setStatusTip(tr("Show arguments for currently typed method call")); action->setShortcut(tr("Ctrl+Shift+Space", "Trigger Method Call Aid")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(triggerMethodCallAid()), SignalMultiplexer::ConnectionOptional); settings->addAction(action, "editor-method-call-assist", editorCategory); mActions[ToggleComment] = action = new QAction(QIcon::fromTheme("edit-comment"), tr("Toggle &Comment"), this); action->setShortcut(tr("Ctrl+/", "Toggle Comment")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); action->setStatusTip(tr("Toggle Comment")); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(toggleComment()), SignalMultiplexer::ConnectionOptional); settings->addAction(action, "editor-toggle-comment", editorCategory); mActions[ToggleOverwriteMode] = action = new QAction(QIcon::fromTheme("edit-overwrite"), tr("Toggle &Overwrite Mode"), this); action->setShortcut(tr("Insert", "Toggle Overwrite Mode")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(toggleOverwriteMode())); settings->addAction(action, "editor-toggle-overwrite", editorCategory); mActions[CopyLineUp] = action = new QAction(QIcon::fromTheme("edit-copylineup"), tr("Copy Line Up"), this); action->setShortcut(tr("Ctrl+Alt+Up", "Copy Line Up")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(copyLineUp())); settings->addAction(action, "editor-copy-line-up", editorCategory); mActions[CopyLineDown] = action = new QAction(QIcon::fromTheme("edit-copylinedown"), tr("Copy Line Down"), this); action->setShortcut(tr("Ctrl+Alt+Down", "Copy Line Up")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(copyLineDown())); settings->addAction(action, "editor-copy-line-down", editorCategory); mActions[MoveLineUp] = action = new QAction(QIcon::fromTheme("edit-movelineup"), tr("Move Line Up"), this); action->setShortcut(tr("Ctrl+Shift+Up", "Move Line Up")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(moveLineUp())); settings->addAction(action, "editor-move-line-up", editorCategory); mActions[MoveLineDown] = action = new QAction(QIcon::fromTheme("edit-movelinedown"), tr("Move Line Down"), this); action->setShortcut(tr("Ctrl+Shift+Down", "Move Line Up")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(moveLineDown())); settings->addAction(action, "editor-move-line-down", editorCategory); mActions[DeleteWord] = action = new QAction(QIcon::fromTheme("edit-deleteword"), tr("Delete Word"), this); #ifdef Q_OS_MAC action->setShortcut(tr("Meta+W", "Delete Word")); #endif action->setShortcutContext(Qt::WidgetWithChildrenShortcut); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(deleteWord())); settings->addAction(action, "delete-word", editorCategory); mActions[GotoPreviousBlock] = action = new QAction(QIcon::fromTheme("edit-gotopreviousblock"), tr("Go to Previous Block"), this); action->setShortcut(tr("Ctrl+[", "Go to Previous Block")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(gotoPreviousBlock()), SignalMultiplexer::ConnectionOptional); settings->addAction(action, "editor-go-to-prev-block", editorCategory); mActions[GotoNextBlock] = action = new QAction(QIcon::fromTheme("edit-gotonextblock"), tr("Go to Next Block"), this); action->setShortcut(tr("Ctrl+]", "Go to Next Block")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(gotoNextBlock()), SignalMultiplexer::ConnectionOptional); settings->addAction(action, "editor-go-to-next-block", editorCategory); mActions[SelectEnclosingBlock] = action = new QAction(tr("Select Enclosing Block"), this); action->setShortcut(tr("Ctrl+Shift+B", "Select Enclosing Block")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); action->setStatusTip(tr("Select everything between brackets that contain cursor")); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(selectBlockAroundCursor()), SignalMultiplexer::ConnectionOptional); settings->addAction(action, "editor-select-enclosing-block", editorCategory); mActions[GotoPreviousRegion] = action = new QAction(QIcon::fromTheme("edit-gotopreviousregion"), tr("Go to Previous Region"), this); action->setShortcut(tr("Ctrl+Alt+[", "Go to Previous Region")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(gotoPreviousRegion()), SignalMultiplexer::ConnectionOptional); settings->addAction(action, "editor-go-to-prev-region", editorCategory); mActions[GotoNextRegion] = action = new QAction(QIcon::fromTheme("edit-gotonextregion"), tr("Go to Next Region"), this); action->setShortcut(tr("Ctrl+Alt+]", "Go to Next Region")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(gotoNextRegion()), SignalMultiplexer::ConnectionOptional); settings->addAction(action, "editor-go-to-next-region", editorCategory); mActions[GotoPreviousEmptyLine] = action = new QAction(tr("Go to Previous Empty Line"), this); action->setShortcut(tr("Ctrl+Up", "Go to Previous Empty Line")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(gotoPreviousEmptyLine())); settings->addAction(action, "editor-go-to-prev-empty-line", editorCategory); mActions[GotoNextEmptyLine] = action = new QAction(tr("Go to Next Empty Line"), this); action->setShortcut(tr("Ctrl+Down", "Go to Next Empty Line")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(gotoNextEmptyLine())); settings->addAction(action, "editor-go-to-next-empty-line", editorCategory); mActions[SelectRegion] = action = new QAction(tr("Select Region"), this); action->setShortcut(tr("Ctrl+Shift+R", "Select Region")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(selectCurrentRegion()), SignalMultiplexer::ConnectionOptional); settings->addAction(action, "editor-select-region", editorCategory); // View mActions[DocClose] = action = new QAction(QIcon::fromTheme("window-close"), tr("&Close"), this); action->setShortcut(tr("Ctrl+W", "Close document")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); action->setStatusTip(tr("Close the current document")); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(closeDocument())); settings->addAction(action, "ide-document-close", editorCategory); mActions[EnlargeFont] = action = new QAction(QIcon::fromTheme("zoom-in"), tr("&Enlarge Font"), this); action->setShortcut(tr("Ctrl++", "Enlarge font")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); action->setStatusTip(tr("Increase displayed font size")); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(zoomIn())); settings->addAction(action, "editor-enlarge-font", editorCategory); mActions[ShrinkFont] = action = new QAction(QIcon::fromTheme("zoom-out"), tr("&Shrink Font"), this); action->setShortcut(tr("Ctrl+-", "Shrink font")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); action->setStatusTip(tr("Decrease displayed font size")); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(zoomOut())); settings->addAction(action, "editor-shrink-font", editorCategory); mActions[ResetFontSize] = action = new QAction(QIcon::fromTheme("zoom-reset"), tr("&Reset Font Size"), this); action->setShortcut(tr("Ctrl+0", "Reset font")); action->setStatusTip(tr("Reset displayed font size")); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(resetFontSize())); settings->addAction(action, "editor-reset-font-size", editorCategory); mActions[ShowWhitespace] = action = new QAction(tr("Show Spaces and Tabs"), this); action->setCheckable(true); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); #ifdef Q_OS_MAC action->setShortcut(QKeySequence(Qt::META | Qt::Key_E, Qt::META | Qt::Key_V)); #else action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_E, Qt::ALT | Qt::Key_V)); #endif connect(action, SIGNAL(triggered(bool)), this, SLOT(setShowWhitespace(bool))); settings->addAction(action, "editor-toggle-show-whitespace", editorCategory); mActions[ShowLinenumber] = action = new QAction(tr("Show Line Number"), this); action->setCheckable(true); action->setShortcut(tr("Ctrl+Alt+#", "Show Line Number")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); connect(action, SIGNAL(triggered(bool)), this, SLOT(setShowLinenumber(bool))); settings->addAction(action, "editor-toggle-show-line-number", editorCategory); mActions[ShowAutocompleteHelp] = action = new QAction(tr("Show Autocomplete Help"), this); action->setCheckable(true); connect(action, SIGNAL(triggered(bool)), this, SLOT(setShowAutocompleteHelp(bool))); settings->addAction(action, "editor-toggle-show-autocomplete-help", editorCategory); mActions[IndentWithSpaces] = action = new QAction(tr("Use Spaces for Indentation"), this); action->setCheckable(true); action->setStatusTip(tr("Indent with spaces instead of tabs")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); mEditorSigMux->connect(action, SIGNAL(triggered(bool)), SLOT(setSpaceIndent(bool)), SignalMultiplexer::ConnectionOptional); settings->addAction(action, "editor-toggle-space-indent", editorCategory); mActions[NextDocument] = action = new QAction(tr("Next Document"), this); #ifndef Q_OS_MAC action->setShortcut(tr("Alt+Right", "Next Document")); #else action->setShortcut(tr("Ctrl+Alt+Right", "Next Document")); #endif connect(action, SIGNAL(triggered()), this, SLOT(showNextDocument())); settings->addAction(action, "editor-document-next", editorCategory); mActions[PreviousDocument] = action = new QAction(tr("Previous Document"), this); #ifndef Q_OS_MAC action->setShortcut(tr("Alt+Left", "Previous Document")); #else action->setShortcut(tr("Ctrl+Alt+Left", "Previous Document")); #endif connect(action, SIGNAL(triggered()), this, SLOT(showPreviousDocument())); settings->addAction(action, "editor-document-previous", editorCategory); mActions[SwitchDocument] = action = new QAction(tr("Switch Document"), this); #ifndef Q_OS_MAC action->setShortcut(tr("Ctrl+Tab", "Switch Document")); #else action->setShortcut(tr("Alt+Tab", "Switch Document")); #endif connect(action, SIGNAL(triggered()), this, SLOT(switchDocument())); settings->addAction(action, "editor-document-switch", editorCategory); mActions[SplitHorizontally] = action = new QAction(tr("Split To Right"), this); // action->setShortcut( tr("Ctrl+P, 3", "Split To Right")); connect(action, SIGNAL(triggered()), this, SLOT(splitHorizontally())); settings->addAction(action, "editor-split-right", editorCategory); mActions[SplitVertically] = action = new QAction(tr("Split To Bottom"), this); // action->setShortcut( tr("Ctrl+P, 2", "Split To Bottom")); connect(action, SIGNAL(triggered()), this, SLOT(splitVertically())); settings->addAction(action, "editor-split-bottom", editorCategory); mActions[RemoveCurrentSplit] = action = new QAction(tr("Remove Current Split"), this); // action->setShortcut( tr("Ctrl+P, 1", "Remove Current Split")); connect(action, SIGNAL(triggered()), this, SLOT(removeCurrentSplit())); settings->addAction(action, "editor-split-remove", editorCategory); mActions[RemoveAllSplits] = action = new QAction(tr("Remove All Splits"), this); // action->setShortcut( tr("Ctrl+P, 0", "Remove All Splits")); connect(action, SIGNAL(triggered()), this, SLOT(removeAllSplits())); settings->addAction(action, "editor-split-remove-all", editorCategory); // Language mActions[EvaluateCurrentDocument] = action = new QAction(QIcon::fromTheme("media-playback-start"), tr("Evaluate &File"), this); action->setStatusTip(tr("Evaluate current File")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(evaluateDocument()), SignalMultiplexer::ConnectionOptional); settings->addAction(action, "editor-eval-file", editorCategory); mActions[EvaluateRegion] = action = new QAction(QIcon::fromTheme("media-playback-start"), tr("&Evaluate Selection, Line or Region"), this); action->setShortcut(tr("Ctrl+Return", "Evaluate region")); action->setStatusTip(tr("Evaluate current region")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(evaluateRegion()), SignalMultiplexer::ConnectionOptional); settings->addAction(action, "editor-eval-smart", editorCategory); mActions[EvaluateLine] = action = new QAction(QIcon::fromTheme("media-playback-start"), tr("&Evaluate Selection or Line"), this); action->setShortcut(tr("Shift+Return", "Evaluate selection/line")); action->setStatusTip(tr("Evaluate current selection/line")); action->setShortcutContext(Qt::WidgetWithChildrenShortcut); mEditorSigMux->connect(action, SIGNAL(triggered()), SLOT(evaluateLine()), SignalMultiplexer::ConnectionOptional); settings->addAction(action, "editor-eval-line", editorCategory); // These actions are not added to any menu, so they have to be added // at least to this widget, in order for the shortcuts to always respond: addAction(mActions[TriggerAutoCompletion]); addAction(mActions[TriggerMethodCallAid]); addAction(mActions[SwitchDocument]); // These actions have to be added because to the widget because they have // Qt::WidgetWithChildrenShortcut context: addAction(mActions[Cut]); addAction(mActions[Copy]); addAction(mActions[Paste]); addAction(mActions[DocClose]); addAction(mActions[EnlargeFont]); addAction(mActions[ShrinkFont]); addAction(mActions[ShowWhitespace]); addAction(mActions[ShowLinenumber]); addAction(mActions[IndentWithSpaces]); addAction(mActions[EvaluateCurrentDocument]); addAction(mActions[EvaluateRegion]); addAction(mActions[EvaluateLine]); addAction(mActions[ToggleComment]); addAction(mActions[ToggleOverwriteMode]); addAction(mActions[CopyLineUp]); addAction(mActions[CopyLineDown]); addAction(mActions[MoveLineUp]); addAction(mActions[MoveLineDown]); addAction(mActions[DeleteWord]); addAction(mActions[GotoPreviousBlock]); addAction(mActions[GotoNextBlock]); addAction(mActions[SelectEnclosingBlock]); addAction(mActions[GotoPreviousRegion]); addAction(mActions[GotoNextRegion]); addAction(mActions[GotoPreviousEmptyLine]); addAction(mActions[GotoNextEmptyLine]); addAction(mActions[SelectRegion]); } void MultiEditor::updateActions() { GenericCodeEditor* editor = currentEditor(); ScCodeEditor* scEditor = qobject_cast<ScCodeEditor*>(editor); QTextDocument* doc = editor ? editor->textDocument() : 0; mActions[Undo]->setEnabled(doc && doc->isUndoAvailable()); mActions[Redo]->setEnabled(doc && doc->isRedoAvailable()); mActions[Copy]->setEnabled(editor && editor->textCursor().hasSelection()); mActions[Cut]->setEnabled(mActions[Copy]->isEnabled()); mActions[Paste]->setEnabled(editor); mActions[ToggleOverwriteMode]->setEnabled(editor); mActions[CopyLineUp]->setEnabled(editor); mActions[CopyLineDown]->setEnabled(editor); mActions[MoveLineUp]->setEnabled(editor); mActions[MoveLineDown]->setEnabled(editor); mActions[DeleteWord]->setEnabled(editor); mActions[GotoPreviousEmptyLine]->setEnabled(editor); mActions[GotoNextEmptyLine]->setEnabled(editor); mActions[DocClose]->setEnabled(editor); mActions[EnlargeFont]->setEnabled(editor); mActions[ShrinkFont]->setEnabled(editor); mActions[ResetFontSize]->setEnabled(editor); mActions[IndentWithSpaces]->setEnabled(scEditor); mActions[IndentWithSpaces]->setChecked(scEditor && scEditor->spaceIndent()); // ScLang-specific actions bool editorIsScCodeEditor = qobject_cast<ScCodeEditor*>(editor); // NOOP at the moment, but mActions[ToggleComment]->setEnabled(editor && editorIsScCodeEditor); mActions[GotoPreviousBlock]->setEnabled(editor && editorIsScCodeEditor); mActions[GotoNextBlock]->setEnabled(editor && editorIsScCodeEditor); mActions[SelectEnclosingBlock]->setEnabled(editor && editorIsScCodeEditor); mActions[GotoPreviousRegion]->setEnabled(editor && editorIsScCodeEditor); mActions[GotoNextRegion]->setEnabled(editor && editorIsScCodeEditor); mActions[SelectRegion]->setEnabled(editor && editorIsScCodeEditor); mActions[IndentLineOrRegion]->setEnabled(editor && editorIsScCodeEditor); mActions[EvaluateCurrentDocument]->setEnabled(editor && editorIsScCodeEditor); mActions[EvaluateRegion]->setEnabled(editor && editorIsScCodeEditor); mActions[EvaluateLine]->setEnabled(editor && editorIsScCodeEditor); } void MultiEditor::applySettings(Settings::Manager* settings) { bool show_whitespace = settings->value("IDE/editor/showWhitespace").toBool(); bool show_linenumber = settings->value("IDE/editor/showLinenumber").toBool(); bool show_autocompletehelp = settings->value("IDE/editor/showAutocompleteHelp").toBool(); mActions[ShowWhitespace]->setChecked(show_whitespace); mActions[ShowLinenumber]->setChecked(show_linenumber); mActions[ShowAutocompleteHelp]->setChecked(show_autocompletehelp); setMainComboBoxOption(); int boxCount = mSplitter->findChildren<CodeEditorBox*>().count(); if (boxCount > 1) { activateComboBoxWhenSplitting(); } } void MultiEditor::activateComboBoxWhenSplitting() { emit splitViewActivated(); bool comboBoxInUse = Main::settings()->value("IDE/editor/useComboBox").toBool(); if (!comboBoxInUse) { bool comboBoxWhenSplitting = Main::settings()->value("IDE/editor/useComboBoxWhenSplitting").toBool(); showEditorTabs(comboBoxWhenSplitting); } } void MultiEditor::setMainComboBoxOption() { bool comboBoxInUse = Main::settings()->value("IDE/editor/useComboBox").toBool(); showEditorTabs(comboBoxInUse); } void MultiEditor::showEditorTabs(bool condition) { if (condition) mTabs->hide(); else mTabs->show(); } static QVariantList saveBoxState(CodeEditorBox* box, const QList<Document*>& documentList) { // save editors in reverse order - first one is last shown. QVariantList boxData; int idx = box->history().count(); while (idx--) { GenericCodeEditor* editor = box->history()[idx]; if (!editor->document()->filePath().isEmpty()) { int documentIndex = documentList.indexOf(editor->document()); Q_ASSERT(documentIndex >= 0); QVariantMap editorData; editorData.insert("documentIndex", documentIndex); editorData.insert("position", editor->textCursor().position()); boxData.append(editorData); } } return boxData; } static QVariantMap saveSplitterState(QSplitter* splitter, const QList<Document*>& documentList) { QVariantMap splitterData; splitterData.insert("state", splitter->saveState().toBase64()); QVariantList childrenData; int childCount = splitter->count(); for (int idx = 0; idx < childCount; idx++) { QWidget* child = splitter->widget(idx); CodeEditorBox* box = qobject_cast<CodeEditorBox*>(child); if (box) { QVariantList boxData = saveBoxState(box, documentList); childrenData.append(QVariant(boxData)); continue; } QSplitter* childSplitter = qobject_cast<QSplitter*>(child); if (childSplitter) { QVariantMap childSplitterData = saveSplitterState(childSplitter, documentList); childrenData.append(QVariant(childSplitterData)); } } splitterData.insert("elements", childrenData); return splitterData; } void MultiEditor::saveSession(Session* session) { QList<Document*> documentList; QVariantList tabsData; int tabCount = mTabs->count(); for (int tabIdx = 0; tabIdx < tabCount; ++tabIdx) { Document* doc = documentForTab(tabIdx); if (doc) { documentList << doc; tabsData << doc->filePath(); } } session->setValue("documents", QVariant::fromValue(tabsData)); session->remove("editors"); session->setValue("editors", saveSplitterState(mSplitter, documentList)); } void MultiEditor::loadBoxState(CodeEditorBox* box, const QVariantList& data, const QList<Document*>& documentList) { int docCount = documentList.count(); foreach (QVariant docVar, data) { QVariantMap docData = docVar.value<QVariantMap>(); int docIndex = docData.value("documentIndex").toInt(); int docPos = docData.value("position").toInt(); if (docIndex >= 0 && docIndex < docCount) box->setDocument(documentList[docIndex], docPos); } } void MultiEditor::loadSplitterState(MultiSplitter* splitter, const QVariantMap& data, const QList<Document*>& documentList) { QByteArray state = QByteArray::fromBase64(data.value("state").value<QByteArray>()); QVariantList childrenData = data.value("elements").value<QVariantList>(); foreach (const QVariant& childVar, childrenData) { if (childVar.type() == QVariant::List) { CodeEditorBox* childBox = newBox(splitter); splitter->addWidget(childBox); QVariantList childBoxData = childVar.value<QVariantList>(); loadBoxState(childBox, childBoxData, documentList); } else if (childVar.type() == QVariant::Map) { MultiSplitter* childSplitter = new MultiSplitter(this); splitter->addWidget(childSplitter); QVariantMap childSplitterData = childVar.value<QVariantMap>(); loadSplitterState(childSplitter, childSplitterData, documentList); } } if (!splitter->restoreState(state)) qWarning("MultiEditor: could not restore splitter state!"); } void MultiEditor::switchSession(Session* session) { ///// Going offline... breakSignalConnections(); DocumentManager* docManager = Main::documentManager(); QList<Document*> documentList = docManager->documents(); // close all docs foreach (Document* doc, documentList) docManager->close(doc); // remove all tabs while (mTabs->count()) mTabs->removeTab(0); // remove all editors delete mSplitter; documentList.clear(); mSplitter = new MultiSplitter(this); CodeEditorBox* firstBox = 0; if (session) { // open documents saved in the session QVariantList docDataList = session->value("documents").value<QVariantList>(); foreach (const QVariant& docData, docDataList) { QString filePath = docData.toString(); Document* doc = docManager->open(filePath, -1, 0, true); documentList << doc; } // restore tabs for (int i = 0; i < documentList.size(); ++i) insertTab(documentList[i], i); // restore editors if (session->contains("editors")) { QVariantMap splitterData = session->value("editors").value<QVariantMap>(); loadSplitterState(mSplitter, splitterData, documentList); if (mSplitter->count()) { firstBox = mSplitter->findChild<CodeEditorBox>(); if (!firstBox) { qWarning("Session seems to contain invalid editor split data!"); delete mSplitter; mSplitter = new MultiSplitter(this); } } } } if (!firstBox) { // Restoring the session didn't result in any editor box, so create one: firstBox = newBox(mSplitter); mSplitter->addWidget(firstBox); } layout()->addWidget(mSplitter); makeSignalConnections(); ///// Back online. mCurrentEditorBox = 0; // ensure complete update setCurrentBox(firstBox); if (!session) // create a document on new session docManager->create(); firstBox->setFocus(Qt::OtherFocusReason); // ensure focus setMainComboBoxOption(); if (mSplitter->count() > 1) activateComboBoxWhenSplitting(); else emit splitViewDeactivated(); } int MultiEditor::insertTab(Document* doc, int insertIndex) { if (!doc) return -1; int tabIdx = tabForDocument(doc); if (tabIdx != -1) return tabIdx; QTextDocument* tdoc = doc->textDocument(); QIcon icon; if (tdoc->isModified()) icon = mDocModifiedIcon; insertIndex = insertIndex < 0 ? mTabs->currentIndex() + 1 : insertIndex; tabIdx = mTabs->insertTab(insertIndex, icon, doc->title()); mTabs->setTabData(tabIdx, QVariant::fromValue<Document*>(doc)); connect(tdoc, &QTextDocument::modificationChanged, [this, doc](bool) { onDocModified(doc); }); return tabIdx; } void MultiEditor::setCurrent(Document* doc) { int tabIdx = tabForDocument(doc); if (tabIdx != -1) mTabs->setCurrentIndex(tabIdx); } void MultiEditor::updateTabsOrder(QList<Document*> docOrder) { mTabs->blockSignals(true); for (int idx = 0; idx < docOrder.count(); idx++) { if (docOrder.at(idx) != documentForTab(idx)) { Document* doc = docOrder.at(idx); int tabIdx = tabForDocument(doc); mTabs->moveTab(tabIdx, idx); } } mTabs->blockSignals(false); } void MultiEditor::showNextDocument() { int currentIndex = mTabs->currentIndex(); mTabs->setCurrentIndex(qMin(currentIndex + 1, mTabs->count() - 1)); } void MultiEditor::showPreviousDocument() { int currentIndex = mTabs->currentIndex(); mTabs->setCurrentIndex(qMax(0, currentIndex - 1)); } void MultiEditor::switchDocument() { CodeEditorBox* box = currentBox(); DocumentSelectPopUp* popup = new DocumentSelectPopUp(box->history(), this); QRect popupRect(0, 0, 300, 200); popupRect.moveCenter(rect().center()); popup->resize(popupRect.size()); QPoint globalPosition = mapToGlobal(popupRect.topLeft()); Document* selectedDocument = popup->exec(globalPosition); if (selectedDocument) box->setDocument(selectedDocument); } void MultiEditor::onOpen(Document* doc, int initialCursorPosition, int selectionLength) { insertTab(doc); currentBox()->setDocument(doc, initialCursorPosition, selectionLength); currentBox()->setFocus(Qt::OtherFocusReason); } void MultiEditor::onClose(Document* doc) { int tabIdx = tabForDocument(doc); if (tabIdx != -1) mTabs->removeTab(tabIdx); // TODO: each box should switch document according to their own history } void MultiEditor::onDocModified(Document* doc) { if (!doc) return; int tabIdx = tabForDocument(doc); if (tabIdx == -1) return; bool isModified = doc->textDocument()->isModified(); QIcon icon; if (isModified) icon = mDocModifiedIcon; Main::evaluateCodeIfCompiled( QStringLiteral("Document.findByQUuid(\'%1\').prSetEdited(%2)").arg(doc->id().constData()).arg(isModified), true); mTabs->setTabIcon(tabIdx, icon); } void MultiEditor::show(Document* doc, int pos, int selectionLength) { currentBox()->setDocument(doc, pos, selectionLength); currentBox()->setFocus(Qt::OtherFocusReason); } void MultiEditor::update(Document* doc) { int tabIdx = tabForDocument(doc); if (tabIdx != -1) mTabs->setTabText(tabIdx, doc->title()); // update thisProcess.nowExecutingPath GenericCodeEditor* editor = currentEditor(); if (editor->document() == doc) Main::documentManager()->setActiveDocument(doc); } void MultiEditor::onCloseRequest(int index) { Document* doc = documentForTab(index); if (doc) MainWindow::close(doc); } void MultiEditor::onCurrentTabChanged(int index) { if (index == -1) return; Document* doc = documentForTab(index); if (!doc) return; CodeEditorBox* curBox = currentBox(); curBox->setDocument(doc); curBox->setFocus(Qt::OtherFocusReason); } void MultiEditor::onCurrentEditorChanged(GenericCodeEditor* editor) { setCurrentEditor(editor); } void MultiEditor::onBoxActivated(CodeEditorBox* box) { setCurrentBox(box); } Document* MultiEditor::documentForTab(int index) { QVariant doc = mTabs->tabData(index); if (doc.isValid() && !doc.isNull()) return doc.value<Document*>(); else return NULL; } int MultiEditor::tabForDocument(Document* doc) { int tabCount = mTabs->count(); for (int idx = 0; idx < tabCount; ++idx) { Document* tabDoc = documentForTab(idx); if (tabDoc && tabDoc == doc) return idx; } return -1; } CodeEditorBox* MultiEditor::newBox(MultiSplitter* currSplitter) { CodeEditorBox* box = new CodeEditorBox(currSplitter); connect(box, SIGNAL(activated(CodeEditorBox*)), this, SLOT(onBoxActivated(CodeEditorBox*))); return box; } void MultiEditor::setCurrentBox(CodeEditorBox* box) { if (mCurrentEditorBox == box) return; mCurrentEditorBox = box; mBoxSigMux->setCurrentObject(box); setCurrentEditor(box->currentEditor()); mCurrentEditorBox->setActive(); } void MultiEditor::setCurrentEditor(GenericCodeEditor* editor) { if (editor) { int tabIndex = tabForDocument(editor->document()); if (tabIndex != -1) mTabs->setCurrentIndex(tabIndex); } mEditorSigMux->setCurrentObject(editor); updateActions(); Document* currentDocument = editor ? editor->document() : 0; Main::documentManager()->setActiveDocument(currentDocument); emit currentDocumentChanged(currentDocument); } GenericCodeEditor* MultiEditor::currentEditor() { return currentBox()->currentEditor(); } void MultiEditor::split(Qt::Orientation splitDirection) { CodeEditorBox* box = newBox(mSplitter); CodeEditorBox* curBox = currentBox(); GenericCodeEditor* curEditor = curBox->currentEditor(); if (curEditor) box->setDocument(curEditor->document(), curEditor->textCursor().position()); mSplitter->insertWidget(box, curBox, splitDirection); box->setFocus(Qt::OtherFocusReason); activateComboBoxWhenSplitting(); } void MultiEditor::removeCurrentSplit() { int boxCount = mSplitter->findChildren<CodeEditorBox*>().count(); if (boxCount < 2) { // Do not allow removing the one and only box. return; } CodeEditorBox* box = currentBox(); mSplitter->removeWidget(box); // switch current box to first box found: box = mSplitter->findChild<CodeEditorBox>(); Q_ASSERT(box); setCurrentBox(box); box->setFocus(Qt::OtherFocusReason); if (boxCount == 2) { emit splitViewDeactivated(); setMainComboBoxOption(); } else if (boxCount > 2) { activateComboBoxWhenSplitting(); } } void MultiEditor::removeAllSplits() { CodeEditorBox* box = currentBox(); Q_ASSERT(box); Q_ASSERT(mSplitter->count()); if (mSplitter->count() == 1 && mSplitter->widget(0) == box) // Nothing to do. return; breakSignalConnections(); MultiSplitter* newSplitter = new MultiSplitter(this); CodeEditorBox* nBox = newBox(newSplitter); newSplitter->addWidget(nBox); GenericCodeEditor* curEditor = box->currentEditor(); if (curEditor) nBox->setDocument(curEditor->document(), curEditor->textCursor().position()); delete mSplitter; mSplitter = newSplitter; layout()->addWidget(mSplitter); emit splitViewDeactivated(); setMainComboBoxOption(); mCurrentEditorBox = 0; // ensure complete update setCurrentBox(nBox); makeSignalConnections(); // ensure signal connections nBox->setFocus(Qt::OtherFocusReason); } void MultiEditor::setShowWhitespace(bool showWhitespace) { Main::settings()->setValue("IDE/editor/showWhitespace", showWhitespace); Main::instance()->applySettings(); } void MultiEditor::setShowLinenumber(bool showLinenumber) { Main::settings()->setValue("IDE/editor/showLinenumber", showLinenumber); Main::instance()->applySettings(); } void MultiEditor::setShowAutocompleteHelp(bool showAutocompleteHelp) { Main::settings()->setValue("IDE/editor/showAutocompleteHelp", showAutocompleteHelp); } } // namespace ScIDE
47,211
C++
.cpp
983
41.926755
119
0.701748
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,026
lookup_dialog.cpp
supercollider_supercollider/editors/sc-ide/widgets/lookup_dialog.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "lookup_dialog.hpp" #include "main_window.hpp" #include "../core/sc_introspection.hpp" #include "../core/main.hpp" #include <QVBoxLayout> #include <QHeaderView> #include <QKeyEvent> #include <QApplication> #include <QScreen> #include <QWindow> #include <QApplication> #include <QPainter> #include <QFileInfo> #include <yaml-cpp/yaml.h> namespace ScIDE { GenericLookupDialog::GenericLookupDialog(QWidget* parent): QDialog(parent) { #ifdef SC_USE_QTWEBENGINE addAction(MainWindow::instance()->action(MainWindow::LookupDocumentationForCursor)); #endif // SC_USE_WEBENGINE mQueryEdit = new QLineEdit(this); mResult = new QTreeView(this); mResult->setRootIsDecorated(false); mResult->setAllColumnsShowFocus(true); mResult->setHeaderHidden(true); mResult->header()->setStretchLastSection(false); mPreviewDocument = new Document(false); mPreviewEditor = new ScCodeEditor(mPreviewDocument); mPreviewEditor->setReadOnly(true); mPreviewEditor->setVisible(false); mPreviewEditor->setTabChangesFocus(true); QVBoxLayout* layout = new QVBoxLayout; layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(1); layout->addWidget(mQueryEdit, 0); layout->addWidget(mResult, 2); layout->addWidget(mPreviewEditor, 1); setLayout(layout); connect(mQueryEdit, SIGNAL(returnPressed()), this, SLOT(performQuery())); connect(mResult, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(onAccepted(QModelIndex))); connect(mResult, SIGNAL(activated(QModelIndex)), this, SLOT(onAccepted(QModelIndex))); mResult->installEventFilter(this); QRect bounds(0, 0, 600, 300); if (parent) { QRect parentRect = parent->rect(); bounds.moveCenter(parent->mapToGlobal(parentRect.center())); } else { QRect availableBounds = this->screen()->availableGeometry(); bounds.moveCenter(availableBounds.center()); } setGeometry(bounds); mQueryEdit->setFocus(Qt::OtherFocusReason); } void GenericLookupDialog::setModel(QStandardItemModel* model) { if (mResult->selectionModel()) { disconnect(mResult->selectionModel(), SIGNAL(currentChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(currentChanged(const QModelIndex&, const QModelIndex&))); } mResult->setModel(model); if (mResult->selectionModel()) { mPreviewEditor->setActiveAppearance(true); connect(mResult->selectionModel(), SIGNAL(currentChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(currentChanged(const QModelIndex&, const QModelIndex&))); } else { mPreviewEditor->setActiveAppearance(false); } } void GenericLookupDialog::currentChanged(const QModelIndex& item, const QModelIndex& oldItem) { QString path = item.data(PathRole).toString(); int pos = item.data(CharPosRole).toInt(); QFileInfo info(path); QString cpath = info.canonicalFilePath(); info.setFile(cpath); if (cpath.isEmpty()) { MainWindow::instance()->showStatusMessage(tr("Cannot open file: %1 (file does not exist)").arg(path)); return; } // Open the file QFile file(cpath); if (!file.open(QIODevice::ReadOnly)) { MainWindow::instance()->showStatusMessage(tr("Cannot open file for reading: %1").arg(cpath)); return; } QByteArray bytes(file.readAll()); file.close(); QTextStream stream(bytes); #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) stream.setCodec("UTF-8"); #else stream.setEncoding(QStringConverter::Utf8); #endif stream.setAutoDetectUnicode(true); mPreviewDocument->setTextInRange(stream.readAll(), 0, -1); mPreviewEditor->showPosition(pos, 0); mPreviewEditor->selectCurrentRegion(); } bool GenericLookupDialog::openDocumentation() { QModelIndex currentIndex = mResult->currentIndex(); QStandardItemModel* model = qobject_cast<QStandardItemModel*>(mResult->model()); if (!model) return true; currentIndex = currentIndex.sibling(currentIndex.row(), 0); QStandardItem* currentItem = model->itemFromIndex(currentIndex); if (!currentItem) return true; bool isClass = currentItem->data(IsClassRole).toBool(); if (isClass) { Main::openDocumentation(currentItem->text()); } else { QString className = currentItem->data(ClassNameRole).toString(); QString methodName = currentItem->data(MethodNameRole).toString(); Main::openDocumentationForMethod(className, methodName); } accept(); return true; } void GenericLookupDialog::onAccepted(QModelIndex currentIndex) { QStandardItem* currentItem = firstItemInLine(currentIndex); if (!currentItem) { reject(); return; } QString path = currentItem->data(PathRole).toString(); int pos = currentItem->data(CharPosRole).toInt(); Main::documentManager()->open(path, pos, 0, false); accept(); } QStandardItem* GenericLookupDialog::firstItemInLine(QModelIndex index) { QStandardItemModel* model = qobject_cast<QStandardItemModel*>(mResult->model()); if (!model) return NULL; index = index.sibling(index.row(), 0); return model->itemFromIndex(index); } bool GenericLookupDialog::event(QEvent* event) { switch (event->type()) { case QEvent::ShortcutOverride: { QKeyEvent* kevent = static_cast<QKeyEvent*>(event); if (kevent->key() == Qt::Key_Escape) { accept(); return true; } } default:; } return QDialog::event(event); } bool GenericLookupDialog::eventFilter(QObject* object, QEvent* event) { if (object == mResult && event->type() == QEvent::KeyPress) { QKeyEvent* ke = static_cast<QKeyEvent*>(event); switch (ke->key()) { case Qt::Key_Enter: case Qt::Key_Return: onAccepted(mResult->currentIndex()); return true; default:; } } return QDialog::eventFilter(object, event); } void GenericLookupDialog::focusResults() { mResult->header()->resizeSections(QHeaderView::ResizeToContents); mResult->setFocus(Qt::OtherFocusReason); QStandardItemModel* model = qobject_cast<QStandardItemModel*>(mResult->model()); QStandardItem* firstItem = model->item(0, 0); if (firstItem) { QModelIndex firstIndex = model->indexFromItem(firstItem); mResult->setCurrentIndex(firstIndex); } } using namespace ScLanguage; using std::pair; using std::vector; LookupDialog::LookupDialog(QWidget* parent): GenericLookupDialog(parent), mIsPartialQuery(false) { setWindowTitle(tr("Look Up Implementations")); mQueryEdit->setText(tr("Enter class or method name...")); mQueryEdit->selectAll(); } void LookupDialog::performQuery() { QString queryString = mQueryEdit->text(); if (queryString.isEmpty()) { setModel(NULL); return; } const Introspection& introspection = Main::scProcess()->introspection(); if (!introspection.introspectionAvailable()) { MainWindow::instance()->showStatusMessage(tr("Introspection data not yet available")); return; } mIsPartialQuery = false; if (queryString[0].isUpper()) { bool success = performClassQuery(queryString); mPreviewEditor->setVisible(success); if (success) { focusResults(); return; } } else { bool success = performMethodQuery(queryString); mPreviewEditor->setVisible(success); if (success) { focusResults(); return; } } bool success = performPartialQuery(queryString); mPreviewEditor->setVisible(success); if (success) focusResults(); } void LookupDialog::onAccepted(QModelIndex currentIndex) { if (!mIsPartialQuery) { GenericLookupDialog::onAccepted(currentIndex); return; } QStandardItemModel* model = qobject_cast<QStandardItemModel*>(mResult->model()); currentIndex = currentIndex.sibling(currentIndex.row(), 0); QStandardItem* currentItem = model->itemFromIndex(currentIndex); if (!currentItem) { reject(); return; } bool isClass = currentItem->data(IsClassRole).toBool(); if (!isClass) { GenericLookupDialog::onAccepted(currentIndex); return; } QString className = currentItem->text(); mQueryEdit->setText(className); performQuery(); } QList<QStandardItem*> GenericLookupDialog::makeDialogItem(QString const& displayString, QString const& displayPath, QString const& path, int position, QString const& className, QString const& methodName, bool isClassItem) { // LATER: shall we just store a shared pointer to the class or method? QStandardItem* item = new QStandardItem(displayString); item->setData(path, PathRole); item->setData(position, CharPosRole); item->setData(isClassItem, IsClassRole); item->setData(className, ClassNameRole); item->setData(methodName, MethodNameRole); QStandardItem* pathItem = new QStandardItem(displayPath); QList<QStandardItem*> ret; ret << item << pathItem; return ret; } QStandardItemModel* LookupDialog::modelForClass(const QString& className, const QString& methodName) { const Introspection& introspection = Main::scProcess()->introspection(); const Class* klass = introspection.findClassOrWarn(className); if (!klass) return NULL; QStandardItemModel* model = new QStandardItemModel(this); QStandardItem* parentItem = model->invisibleRootItem(); while (klass) { Class* metaClass = klass->metaClass; QString displayPath = introspection.compactLibraryPath(klass->definition.path); if (methodName.isEmpty()) { parentItem->appendRow(makeDialogItem(klass->name.get(), displayPath, klass->definition.path.get(), klass->definition.position, klass->name.get(), QStringLiteral(""), true)); } foreach (const Method* method, metaClass->methods) { QString signature = method->signature(Method::SignatureWithoutArguments); QString displayPath = introspection.compactLibraryPath(method->definition.path); if (method->matches(methodName)) { parentItem->appendRow(makeDialogItem(signature, displayPath, method->definition.path.get(), method->definition.position, metaClass->name.get(), method->name.get(), false)); } } foreach (const Method* method, klass->methods) { QString signature = method->signature(Method::SignatureWithoutArguments); QString displayPath = introspection.compactLibraryPath(method->definition.path); if (method->matches(methodName)) { parentItem->appendRow(makeDialogItem(signature, displayPath, method->definition.path.get(), method->definition.position, klass->name.get(), method->name.get(), false)); } } klass = klass->superClass; } return model; } QStandardItemModel* LookupDialog::modelForMethod(const QString& methodName) { const Introspection& introspection = Main::scProcess()->introspection(); const MethodMap& methods = introspection.methodMap(); pair<MethodMap::const_iterator, MethodMap::const_iterator> matchingMethods = methods.equal_range(methodName); if (matchingMethods.first == matchingMethods.second) return NULL; QStandardItemModel* model = new QStandardItemModel(this); QStandardItem* parentItem = model->invisibleRootItem(); for (MethodMap::const_iterator it = matchingMethods.first; it != matchingMethods.second; ++it) { Method* method = it->second.data(); QString signature = method->signature(Method::SignatureWithoutArguments); const QString& path = method->definition.path; QString displayPath = introspection.compactLibraryPath(path); parentItem->appendRow(makeDialogItem(signature, displayPath, method->definition.path.get(), method->definition.position, method->ownerClass->name.get(), method->name.get(), false)); } model->sort(0); return model; } QStandardItemModel* LookupDialog::modelForPartialQuery(const QString& queryString) { const Introspection& introspection = Main::scProcess()->introspection(); vector<const Class*> classes = introspection.findClassPartial(queryString); vector<const Method*> methods = introspection.findMethodPartial(queryString); typedef vector<const Method*>::const_iterator MethodIterator; typedef vector<const Class*>::const_iterator ClassIterator; if (classes.empty() && methods.empty()) { MainWindow::instance()->showStatusMessage(tr("No result for query")); return NULL; } mIsPartialQuery = true; QStandardItemModel* model = new QStandardItemModel(this); QStandardItem* parentItem = model->invisibleRootItem(); for (MethodIterator it = methods.begin(); it != methods.end(); ++it) { const Method* method = *it; QString signature = method->signature(Method::SignatureWithoutArguments); const QString& path = method->definition.path; QString displayPath = introspection.compactLibraryPath(path); parentItem->appendRow(makeDialogItem(signature, displayPath, method->definition.path.get(), method->definition.position, method->ownerClass->name.get(), method->name.get(), false)); } for (ClassIterator it = classes.begin(); it != classes.end(); ++it) { const Class* klass = *it; QString displayPath = introspection.compactLibraryPath(klass->definition.path); parentItem->appendRow(makeDialogItem(klass->name.get(), displayPath, klass->definition.path.get(), klass->definition.position, klass->name.get(), "", true)); } model->sort(0); return model; } bool LookupDialog::performClassQuery(const QString& className) { QStandardItemModel* model; if (className.contains(QChar(':'))) { QStringList split = className.split(":"); model = modelForClass(split[0].trimmed(), split[1].trimmed()); } else { model = modelForClass(className); } setModel(model); return model; } bool LookupDialog::performMethodQuery(const QString& methodName) { QStandardItemModel* model = modelForMethod(methodName); setModel(model); return model; } bool LookupDialog::performPartialQuery(const QString& queryString) { QStandardItemModel* model = modelForPartialQuery(queryString); setModel(model); return model; } ReferencesDialog::ReferencesDialog(QWidget* parent): LookupDialog(parent) { mRequest = new SymbolReferenceRequest(Main::scProcess(), this); connect(mRequest, SIGNAL(response(QString, QString)), this, SLOT(onResposeFromLanguage(QString, QString))); connect(mRequest, SIGNAL(cancelled()), this, SLOT(requestCancelled())); setWindowTitle(tr("Look Up References")); mQueryEdit->setText(tr("Enter class or method name...")); mQueryEdit->selectAll(); } void ReferencesDialog::performQuery() { QString queryString = mQueryEdit->text(); if (queryString.isEmpty()) { setModel(NULL); } else { queryString.replace('\"', "\\\""); mRequest->sendRequest(queryString); } } void ReferencesDialog::requestCancelled() { setModel(NULL); } void ReferencesDialog::onResposeFromLanguage(const QString&, const QString& responseData) { QStandardItemModel* model = parse(responseData); setModel(model); if (model) focusResults(); } QStandardItemModel* ReferencesDialog::parse(const QString& responseData) { using namespace ScLanguage; const Introspection& introspection = Main::scProcess()->introspection(); if (!introspection.introspectionAvailable()) { // just required for short path name MainWindow::instance()->showStatusMessage(tr("Introspection data not yet available")); return NULL; } YAML::Node doc = YAML::Load(responseData.toStdString()); if (!doc) { qWarning("no YAML document"); return NULL; } assert(doc.Type() == YAML::NodeType::Sequence); QString symbol = doc[0].as<std::string>().c_str(); QStandardItemModel* model = new QStandardItemModel(this); QStandardItem* parentItem = model->invisibleRootItem(); YAML::Node const& references = doc[1]; for (YAML::Node const& reference : references) { QString className = reference[0].as<std::string>().c_str(); QString methodName = reference[1].as<std::string>().c_str(); QString path = reference[2].as<std::string>().c_str(); int charPos = reference[3].as<int>(); QString displayPath = introspection.compactLibraryPath(path); QString fullName = ScLanguage::makeFullMethodName(className, methodName); parentItem->appendRow(makeDialogItem(fullName, displayPath, path, charPos, className, methodName, false)); } return model; } } // namespace ScIDE
18,488
C++
.cpp
423
36.368794
120
0.679666
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
30,027
audio_status_box.cpp
supercollider_supercollider/editors/sc-ide/widgets/audio_status_box.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 - 2013 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "audio_status_box.hpp" #include "../core/sc_server.hpp" #include <QHBoxLayout> #include <QWheelEvent> namespace ScIDE { AudioStatusBox::AudioStatusBox(ScServer* server, QWidget* parent): StatusBox(parent) { mStatisticsLabel = new StatusLabel; mVolumeLabel = new StatusLabel; mMuteLabel = new StatusLabel; mMuteLabel->setText("M"); mRecordLabel = new StatusLabel; mRecordLabel->setText("R"); QHBoxLayout* layout = new QHBoxLayout; layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(1); layout->addWidget(mStatisticsLabel); layout->addWidget(mVolumeLabel); layout->addWidget(mMuteLabel); layout->addWidget(mRecordLabel); setLayout(layout); server->action(ScServer::Record)->setProperty("keep_menu_open", true); server->action(ScServer::PauseRecord)->setProperty("keep_menu_open", true); server->action(ScServer::VolumeRestore)->setProperty("keep_menu_open", true); server->action(ScServer::Mute)->setProperty("keep_menu_open", true); server->action(ScServer::DumpOSC)->setProperty("keep_menu_open", true); addAction(server->action(ScServer::ToggleRunning)); addAction(server->action(ScServer::Reboot)); addAction(server->action(ScServer::KillAll)); addActionSeparator(); addAction(server->action(ScServer::ShowMeters)); addAction(server->action(ScServer::ShowScope)); addAction(server->action(ScServer::ShowFreqScope)); addAction(server->action(ScServer::DumpNodeTree)); addAction(server->action(ScServer::DumpNodeTreeWithControls)); addAction(server->action(ScServer::PlotTree)); addAction(server->action(ScServer::DumpOSC)); addActionSeparator(); addAction(server->action(ScServer::Record)); addAction(server->action(ScServer::PauseRecord)); addActionSeparator(); addAction(server->action(ScServer::VolumeRestore)); addAction(server->action(ScServer::Mute)); addAction(server->action(ScServer::Volume)); // server -> box connect(server, SIGNAL(runningStateChanged(bool, QString, int, bool)), this, SLOT(onServerRunningChanged(bool, QString, int, bool))); connect(server, SIGNAL(updateServerStatus(int, int, int, int, float, float)), this, SLOT(updateStatistics(int, int, int, int, float, float))); connect(server, SIGNAL(volumeChanged(float)), this, SLOT(updateVolumeLabel(float))); connect(server, SIGNAL(mutedChanged(bool)), this, SLOT(updateMuteLabel(bool))); connect(server, SIGNAL(recordingChanged(bool)), this, SLOT(updateRecordLabel(bool))); onServerRunningChanged(false, "", 0, false); updateVolumeLabel(server->volume()); updateMuteLabel(server->isMuted()); updateRecordLabel(server->isRecording()); // box to server connect(this, &AudioStatusBox::decreaseVolume, [=]() { server->changeVolume(-0.5); }); connect(this, &AudioStatusBox::increaseVolume, [=]() { server->changeVolume(+0.5); }); } void AudioStatusBox::onServerRunningChanged(bool running, const QString&, int, bool unresponsive) { if (unresponsive) { mStatisticsLabel->setTextColor(Qt::yellow); mVolumeLabel->setTextColor(Qt::yellow); } else if (running) { mStatisticsLabel->setTextColor(Qt::green); mVolumeLabel->setTextColor(Qt::green); } else { mStatisticsLabel->setTextColor(Qt::white); mVolumeLabel->setTextColor(Qt::white); }; if (!running) { updateStatistics(0, 0, 0, 0, 0, 0); } } void AudioStatusBox::wheelEvent(QWheelEvent* event) { if (!event->angleDelta().isNull()) { if (event->angleDelta().x() > 0) emit increaseVolume(); else emit decreaseVolume(); } StatusBox::wheelEvent(event); } void AudioStatusBox::updateStatistics(int ugens, int synths, int groups, int synthDefs, float avgCPU, float peakCPU) { QString statusString = QStringLiteral("%1% %2% %3u %4s %5g %6d ") .arg(avgCPU, 5, 'f', 2) .arg(peakCPU, 5, 'f', 2) .arg(ugens, 4) .arg(synths, 4) .arg(groups, 4) .arg(synthDefs, 4); mStatisticsLabel->setText(statusString); } void AudioStatusBox::updateVolumeLabel(float volume) { mVolumeLabel->setText(QStringLiteral("%1dB ").arg(volume, 5, 'f', 1)); } void AudioStatusBox::updateMuteLabel(bool muted) { mMuteLabel->setTextColor(muted ? Qt::red : QColor(30, 30, 30)); } void AudioStatusBox::updateRecordLabel(bool recording) { mRecordLabel->setTextColor(recording ? Qt::red : QColor(30, 30, 30)); } } // namespace ScIDE
5,549
C++
.cpp
117
40.965812
118
0.691696
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
30,028
help_browser.cpp
supercollider_supercollider/editors/sc-ide/widgets/help_browser.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef SC_USE_QTWEBENGINE # define QT_NO_DEBUG_OUTPUT # include "help_browser.hpp" # include "main_window.hpp" # include "../core/sc_process.hpp" # include "../core/main.hpp" # include "../core/util/overriding_action.hpp" # include "QtCollider/widgets/web_page.hpp" # include "QtCollider/hacks/hacks_qt.hpp" # include <QVBoxLayout> # include <QToolBar> # include <QAction> # include <QMenu> # include <QStyle> # include <QShortcut> # include <QApplication> # include <QScreen> # include <QWindow> # include <QDebug> # include <QKeyEvent> # include <QWebEngineSettings> # if (QT_VERSION < QT_VERSION_CHECK(6, 2, 0)) # include <QWebEngineContextMenuData> # else # include <QWebEngineContextMenuRequest> # endif # ifdef Q_OS_MAC # include <QStyleFactory> // QStyleFactory::create, see below # endif namespace ScIDE { HelpBrowser::HelpBrowser(QWidget* parent): QWidget(parent) { QRect availableScreenRect = qApp->primaryScreen()->availableGeometry(); mSizeHint = QSize(availableScreenRect.width() * 0.4, availableScreenRect.height() * 0.7); // setPage does not take ownership of webPage; it must be deleted manually later (see below) mWebView = new QtCollider::WebView(this); mWebView->settings()->setAttribute(QWebEngineSettings::LocalStorageEnabled, true); mWebView->setContextMenuPolicy(Qt::CustomContextMenu); // Set the style's standard palette to avoid system's palette incoherencies // get in the way of rendering web pages mWebView->setPalette(style()->standardPalette()); # ifdef Q_OS_MAC // On macOS, checkboxes unwantedly appear in the top left-hand corner. // See QTBUG-43366, 43070, and 42948. The workaround is to set style to fusion. mWebView->setStyle(QStyleFactory::create("Fusion")); # endif mWebView->installEventFilter(this); mLoadProgressIndicator = new LoadProgressIndicator; mLoadProgressIndicator->setIndent(10); QVBoxLayout* layout = new QVBoxLayout; layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); layout->addWidget(mWebView); setLayout(layout); connect(mWebView, SIGNAL(loadStarted()), mLoadProgressIndicator, SLOT(start())); connect(mWebView, SIGNAL(loadFinished(bool)), this, SLOT(onPageLoad())); connect(mWebView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(onContextMenuRequest(QPoint))); mWebView->setOverrideNavigation(true); connect(mWebView->page(), SIGNAL(navigationRequested(const QUrl&, QWebEnginePage::NavigationType, bool)), this, SLOT(onLinkClicked(const QUrl&, QWebEnginePage::NavigationType, bool))); mWebView->setDelegateReload(true); connect(mWebView->page()->action(QWebEnginePage::Reload), SIGNAL(triggered(bool)), this, SLOT(onReload())); connect(mWebView, SIGNAL(jsConsoleMsg(QString, int, QString)), this, SLOT(onJsConsoleMsg(QString, int, QString))); ScProcess* scProcess = Main::scProcess(); connect(scProcess, SIGNAL(response(QString, QString)), this, SLOT(onScResponse(QString, QString))); connect(scProcess, SIGNAL(finished(int)), mLoadProgressIndicator, SLOT(stop())); // FIXME: should actually respond to class library shutdown, but we don't have that signal connect(scProcess, SIGNAL(classLibraryRecompiled()), mLoadProgressIndicator, SLOT(stop())); // Legacy mac build support -- with Qt 5.9.3 this causes a segfault on application exit. # if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) // Delete the help browser's page to avoid an assert/crash during shutdown. See QTBUG-56441, QTBUG-50160. // Note that putting this in the destructor doesn't work. connect(QApplication::instance(), &QApplication::aboutToQuit, [this]() { delete mWebView->page(); }); # endif createActions(); applySettings(Main::settings()); setFocusProxy(mWebView); } void HelpBrowser::onPageLoad() { mLoadProgressIndicator->stop(); // add these actions to weview's renderer, to capture shift+enter and possibly other swallowed shortcuts static_cast<OverridingAction*>(mActions[EvaluateRegion])->addToWidget(mWebView->focusProxy()); static_cast<OverridingAction*>(mActions[Evaluate])->addToWidget(mWebView->focusProxy()); } void HelpBrowser::createActions() { QAction* action; OverridingAction* ovrAction; mActions[GoHome] = action = new QAction(tr("Home"), this); connect(action, SIGNAL(triggered()), this, SLOT(goHome())); mActions[DocClose] = ovrAction = new OverridingAction(tr("Close"), this); connect(ovrAction, SIGNAL(triggered()), this, SLOT(closeDocument())); ovrAction->addToWidget(this); mActions[ZoomIn] = ovrAction = new OverridingAction(tr("Zoom In"), this); connect(ovrAction, SIGNAL(triggered()), this, SLOT(zoomIn())); ovrAction->addToWidget(this); mActions[ZoomOut] = ovrAction = new OverridingAction(tr("Zoom Out"), this); connect(ovrAction, SIGNAL(triggered()), this, SLOT(zoomOut())); ovrAction->addToWidget(this); mActions[ResetZoom] = ovrAction = new OverridingAction(tr("Reset Zoom"), this); connect(ovrAction, SIGNAL(triggered()), this, SLOT(resetZoom())); ovrAction->addToWidget(this); // eval actions are added to mWebView->focusProxy() in onPageLoad() mActions[Evaluate] = ovrAction = new OverridingAction(tr("Evaluate as Code"), this); connect(ovrAction, SIGNAL(triggered()), this, SLOT(evaluateSelection())); mActions[EvaluateRegion] = new OverridingAction(tr("Evaluate as Code Region"), this); connect(mActions[EvaluateRegion], &OverridingAction::triggered, this, [=]() { this->evaluateSelection(true); }); // For the sake of display: mWebView->pageAction(QWebEnginePage::Copy)->setShortcut(QKeySequence::Copy); mWebView->pageAction(QWebEnginePage::Paste)->setShortcut(QKeySequence::Paste); } void HelpBrowser::applySettings(Settings::Manager* settings) { settings->beginGroup("IDE/shortcuts"); mWebView->pageAction(QWebEnginePage::Back)->setShortcut(QKeySequence::Back); mWebView->pageAction(QWebEnginePage::Forward)->setShortcut(QKeySequence::Forward); mActions[DocClose]->setShortcut(settings->shortcut("ide-document-close")); mActions[ZoomIn]->setShortcut(settings->shortcut("editor-enlarge-font")); mActions[ZoomOut]->setShortcut(settings->shortcut("editor-shrink-font")); mActions[ResetZoom]->setShortcut(settings->shortcut("editor-reset-font-size")); QList<QKeySequence> evalShortcuts; evalShortcuts.append(settings->shortcut("editor-eval-line")); evalShortcuts.append(QKeySequence(Qt::Key_Enter)); mActions[Evaluate]->setShortcuts(evalShortcuts); mActions[EvaluateRegion]->setShortcut(settings->shortcut("editor-eval-smart")); settings->endGroup(); QString codeFontFamily = settings->codeFont().family(); mWebView->settings()->setFontFamily(QWebEngineSettings::FixedFont, codeFontFamily); } void HelpBrowser::goHome() { static QString code("HelpBrowser.goHome"); sendRequest(code); } void HelpBrowser::closeDocument() { MainWindow::instance()->helpBrowserDocklet()->close(); } /// Escapes double quotes; used for strings sent to interpreter. static inline QString escapeDoubleQuotes(const QString& s) { return QString { s }.replace('\"', "\\\""); } void HelpBrowser::gotoHelpFor(const QString& symbol) { QString escaped = escapeDoubleQuotes(symbol); QString code = QStringLiteral("HelpBrowser.openHelpFor(\"%1\")").arg(escaped); sendRequest(code); } void HelpBrowser::gotoHelpForMethod(const QString& className, const QString& methodName) { QString escapedClass = escapeDoubleQuotes(className); QString escapedMethod = escapeDoubleQuotes(methodName); QString code = QStringLiteral("HelpBrowser.openHelpForMethod( %1.findMethod(\\%2) )").arg(escapedClass, escapedMethod); sendRequest(code); } void HelpBrowser::onLinkClicked(const QUrl& url, QWebEnginePage::NavigationType type, bool isMainFrame) { qDebug() << "link clicked:" << url; static const QStringList nonHelpFileExtensions = QStringList() << ".sc" << ".scd" << ".schelp" << ".txt" << ".rtf"; static const QString fileScheme("file"); QString urlString = escapeDoubleQuotes(url.toString()); foreach (const QString& extension, nonHelpFileExtensions) { if (urlString.endsWith(extension)) { if (QURL_IS_LOCAL_FILE(url)) { Main::documentManager()->open(url.toLocalFile(), -1, 0, false); return; } break; } } sendRequest(QStringLiteral("HelpBrowser.goTo(\"%1\")").arg(urlString)); } void HelpBrowser::onReload() { onLinkClicked(mWebView->url(), QWebEnginePage::NavigationTypeReload, true); } void HelpBrowser::zoomIn() { qreal zoomFactor = mWebView->zoomFactor(); zoomFactor = qMin(zoomFactor + 0.1, 2.0); mWebView->setZoomFactor(zoomFactor); } void HelpBrowser::zoomOut() { qreal zoomFactor = mWebView->zoomFactor(); zoomFactor = qMax(zoomFactor - 0.1, 0.1); mWebView->setZoomFactor(zoomFactor); } void HelpBrowser::resetZoom() { mWebView->setZoomFactor(1.0); } void HelpBrowser::findText(const QString& text, bool backwards) { QWebEnginePage::FindFlags flags; if (backwards) flags |= QWebEnginePage::FindBackward; mWebView->findText(text, backwards); } bool HelpBrowser::helpBrowserHasFocus() const { QWidget* focused = QApplication::focusWidget(); while (focused) { if (focused == mWebView) { return true; } focused = qobject_cast<QWidget*>(focused->parent()); } return false; } bool HelpBrowser::eventFilter(QObject* object, QEvent* event) { if (object == mWebView) { switch (event->type()) { case QEvent::MouseButtonPress: { QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event); switch (mouseEvent->button()) { case Qt::XButton1: mWebView->triggerPageAction(QWebEnginePage::Back); return true; case Qt::XButton2: mWebView->triggerPageAction(QWebEnginePage::Forward); return true; default: break; } break; } case QEvent::ShortcutOverride: { event->accept(); return true; } default: break; } } return false; } void HelpBrowser::sendRequest(const QString& code) { ScProcess* scProcess = Main::scProcess(); if (scProcess->state() == QProcess::NotRunning) { qDebug() << "HelpBrowser: aborting request - sclang not running."; MainWindow::instance()->showStatusMessage(tr("Can not use help - interpreter not running!")); return; } qDebug() << "sending request..."; mLoadProgressIndicator->start(tr("Sending request")); Main::scProcess()->evaluateCode(code, true); } void HelpBrowser::onScResponse(const QString& command, const QString& data) { const QString openHelpUrlString = "openHelpUrl"; if (command != openHelpUrlString) return; qDebug() << "HelpBrowser: got response:" << data; mLoadProgressIndicator->stop(); QString urlString = data; // undress YAML string: urlString.remove(0, 1).chop(1); mWebView->load(urlString); HelpBrowserDocklet* helpDock = MainWindow::instance()->helpBrowserDocklet(); if (helpDock) helpDock->focus(); emit urlChanged(); } void HelpBrowser::evaluateSelection(bool evaluateRegion) { static const QString jsSelectLine("selectLine()"); static const QString jsSelectRegion("selectRegion()"); QString selected = mWebView->selectedText(); if (!selected.isEmpty()) { Main::scProcess()->evaluateCode(selected); } else { mWebView->page()->runJavaScript(evaluateRegion ? jsSelectRegion : jsSelectLine, [this](QVariant res) { QString selectionResult = res.toString(); if (!selectionResult.isEmpty()) { Main::scProcess()->evaluateCode(selectionResult); } }); } } void HelpBrowser::onJsConsoleMsg(const QString& arg1, int arg2, const QString& arg3) { qWarning() << "*** JavaScript Message:" << arg1; qWarning() << "* line:" << arg2; qWarning() << "* source ID:" << arg3; } void HelpBrowser::onContextMenuRequest(const QPoint& pos) { QMenu menu; # if (QT_VERSION < QT_VERSION_CHECK(6, 2, 0)) const auto& contextData = mWebView->page()->contextMenuData(); if (!contextData.linkUrl().isEmpty()) { # else const auto& contextData = mWebView->lastContextMenuRequest(); if (!contextData->linkUrl().isEmpty()) { # endif menu.addAction(mWebView->pageAction(QWebEnginePage::CopyLinkToClipboard)); menu.addSeparator(); } # if (QT_VERSION < QT_VERSION_CHECK(6, 2, 0)) if (contextData.isContentEditable() || !contextData.selectedText().isEmpty()) { # else if (contextData->isContentEditable() || !contextData->selectedText().isEmpty()) { # endif menu.addAction(mWebView->pageAction(QWebEnginePage::Copy)); # if (QT_VERSION < QT_VERSION_CHECK(6, 2, 0)) if (contextData.isContentEditable()) # else if (contextData->isContentEditable()) # endif menu.addAction(mWebView->pageAction(QWebEnginePage::Paste)); menu.addSeparator(); } menu.addAction(mWebView->pageAction(QWebEnginePage::Back)); menu.addAction(mWebView->pageAction(QWebEnginePage::Forward)); menu.addAction(mWebView->pageAction(QWebEnginePage::Reload)); # if (QT_VERSION < QT_VERSION_CHECK(6, 2, 0)) if (contextData.selectedText().isEmpty()) # else if (contextData->selectedText().isEmpty()) # endif menu.addAction(mActions[EvaluateRegion]); else menu.addAction(mActions[Evaluate]); menu.addSeparator(); menu.addAction(mWebView->pageAction(QWebEnginePage::Back)); menu.addAction(mWebView->pageAction(QWebEnginePage::Forward)); menu.addAction(mWebView->pageAction(QWebEnginePage::Reload)); menu.addSeparator(); menu.addAction(mActions[ZoomIn]); menu.addAction(mActions[ZoomOut]); menu.addAction(mActions[ResetZoom]); menu.addAction(mActions[DocClose]); menu.exec(mWebView->mapToGlobal(pos)); } QString HelpBrowser::symbolUnderCursor() { return mWebView->selectedText(); // FIXME: should parse out word under cursor if no selection } bool HelpBrowser::openDocumentation() { return Main::openDocumentation(symbolUnderCursor()); } void HelpBrowser::openDefinition() { return Main::openDefinition(symbolUnderCursor(), window()); } void HelpBrowser::openCommandLine() { return Main::openCommandLine(symbolUnderCursor()); } void HelpBrowser::findReferences() { return Main::findReferences(symbolUnderCursor(), window()); } HelpBrowserFindBox::HelpBrowserFindBox(QWidget* parent): QLineEdit(parent) { setPlaceholderText(tr("Find in page...")); connect(this, SIGNAL(textChanged(QString)), this, SIGNAL(query(QString))); } bool HelpBrowserFindBox::event(QEvent* event) { switch (event->type()) { case QEvent::ShortcutOverride: { QKeyEvent* kevent = static_cast<QKeyEvent*>(event); if (kevent->key() == Qt::Key_Escape) { event->accept(); return true; } if (kevent->key() == Qt::Key_W && (kevent->modifiers() & Qt::CTRL)) { MainWindow::instance()->helpBrowserDocklet()->close(); event->accept(); return true; } break; } case QEvent::KeyPress: { QKeyEvent* kevent = static_cast<QKeyEvent*>(event); switch (kevent->key()) { case Qt::Key_Return: case Qt::Key_Enter: { bool backwards = kevent->modifiers() & Qt::ShiftModifier; emit query(text(), backwards); return true; } case Qt::Key_Escape: clear(); default: break; } } default: break; } return QLineEdit::event(event); } HelpBrowserDocklet::HelpBrowserDocklet(QWidget* parent): Docklet(tr("Help browser"), parent) { mHelpBrowser = new HelpBrowser; setAllowedAreas(Qt::AllDockWidgetAreas); setWidget(mHelpBrowser); mFindBox = new HelpBrowserFindBox(); toolBar()->addWidget(mHelpBrowser->loadProgressIndicator(), 1); toolBar()->addAction(mHelpBrowser->mActions[HelpBrowser::GoHome]); toolBar()->addAction(mHelpBrowser->mWebView->pageAction(QWebEnginePage::Back)); toolBar()->addAction(mHelpBrowser->mWebView->pageAction(QWebEnginePage::Forward)); toolBar()->addAction(mHelpBrowser->mWebView->pageAction(QWebEnginePage::Reload)); toolBar()->addWidget(mFindBox); connect(mFindBox, SIGNAL(query(QString, bool)), mHelpBrowser, SLOT(findText(QString, bool))); connect(Main::scProcess(), SIGNAL(started()), this, SLOT(onInterpreterStart())); OverridingAction* action; action = new OverridingAction(this); action->setShortcut(QKeySequence::Find); action->addToWidget(mHelpBrowser); action->addToWidget(toolBar()); connect(action, SIGNAL(triggered(bool)), mFindBox, SLOT(setFocus())); connect(action, SIGNAL(triggered(bool)), mFindBox, SLOT(selectAll())); } } // namespace ScIDE #endif // SC_USE_QTWEBENGINE
18,519
C++
.cpp
400
40.1625
118
0.687892
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
30,029
lang_status_box.cpp
supercollider_supercollider/editors/sc-ide/widgets/lang_status_box.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 - 2013 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "lang_status_box.hpp" #include "../core/sc_process.hpp" #include <QHBoxLayout> namespace ScIDE { LangStatusBox::LangStatusBox(ScProcess* lang, QWidget* parent): StatusBox(parent) { mLabel = new StatusLabel; QHBoxLayout* layout = new QHBoxLayout; layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(mLabel); setLayout(layout); addAction(lang->action(ScProcess::ToggleRunning)); addAction(lang->action(ScProcess::Restart)); addAction(lang->action(ScProcess::RecompileClassLibrary)); connect(lang, SIGNAL(stateChanged(QProcess::ProcessState)), this, SLOT(onInterpreterStateChanged(QProcess::ProcessState))); onInterpreterStateChanged(lang->state()); } void LangStatusBox::onInterpreterStateChanged(QProcess::ProcessState state) { QString text; QColor color; switch (state) { case QProcess::NotRunning: text = tr("Inactive"); color = Qt::white; break; case QProcess::Starting: text = tr("Booting"); color = QColor(255, 255, 0); break; case QProcess::Running: text = tr("Active"); color = Qt::green; break; } mLabel->setText(text); mLabel->setTextColor(color); } } // namespace ScIDE
2,111
C++
.cpp
54
33.796296
83
0.711906
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,030
status_box.cpp
supercollider_supercollider/editors/sc-ide/widgets/util/status_box.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 - 2013 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "status_box.hpp" #include <QtGui/qfontdatabase.h> namespace ScIDE { StatusLabel::StatusLabel(QWidget* parent): QLabel(parent) { setAutoFillBackground(true); setMargin(3); setAlignment(Qt::AlignCenter); setBackground(Qt::black); setTextColor(Qt::white); QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont); font.setPointSize(font.pointSize()); font.setStyleHint(QFont::Monospace); font.setBold(true); setFont(font); } void StatusLabel::setBackground(const QBrush& brush) { QPalette plt(palette()); plt.setBrush(QPalette::Window, brush); setPalette(plt); } void StatusLabel::setTextColor(const QColor& color) { QPalette plt(palette()); plt.setColor(QPalette::WindowText, color); setPalette(plt); } StatusBox::StatusBox(QWidget* parent): QWidget(parent), mMenu(0) {} void StatusBox::showContextMenu() { if (!mMenu) { QList<QAction*> actions = this->actions(); if (actions.count()) { StatusBoxMenu* menu = new StatusBoxMenu; menu->addActions(actions); mMenu = menu; } } if (!mMenu->isVisible()) mMenu->popup(mapToGlobal(QPoint(0, -mMenu->sizeHint().height() - 2))); } void StatusBox::mousePressEvent(QMouseEvent*) { showContextMenu(); } void StatusBox::addActionSeparator() { QAction* separator = new QAction(this); separator->setSeparator(true); addAction(separator); } } // namespace ScIDE
2,323
C++
.cpp
61
33.344262
81
0.715049
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
30,031
docklet.cpp
supercollider_supercollider/editors/sc-ide/widgets/util/docklet.cpp
/* SuperCollider Qt IDE Copyright (c) 2012-2013 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define QT_NO_DEBUG_OUTPUT #include "docklet.hpp" #include "gui_utilities.hpp" #include <QWidget> #include <QToolButton> #include <QLabel> #include <QHBoxLayout> #include <QVBoxLayout> #include <QIcon> #include <QAction> #include <QMenu> #include <QPainter> #include <QStyle> #include <QFontMetrics> #include <QEvent> #include <QDebug> namespace ScIDE { DockletToolButton::DockletToolButton(QWidget* parent): QToolButton(parent) {} void DockletToolButton::mouseDoubleClickEvent(QMouseEvent* event) { event->accept(); } void DockletToolButton::mousePressEvent(QMouseEvent* event) { if (event->button() == Qt::RightButton) event->accept(); else QToolButton::mousePressEvent(event); } DockletToolBar::DockletToolBar(const QString& title) { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); mOptionsMenu = new QMenu(this); QToolButton* optionsBtn = new DockletToolButton; optionsBtn->setIcon(optionsBtn->style()->standardIcon(QStyle::SP_TitleBarNormalButton)); optionsBtn->setIconSize(QSize(16, 16)); optionsBtn->setMenu(mOptionsMenu); optionsBtn->setPopupMode(QToolButton::InstantPopup); optionsBtn->setToolButtonStyle(Qt::ToolButtonIconOnly); optionsBtn->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); QLabel* titleLabel = new QLabel(title); titleLabel->setMargin(5); titleLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); QHBoxLayout* l = new QHBoxLayout(); l->setContentsMargins(0, 0, 0, 0); l->setSpacing(0); l->addWidget(optionsBtn); l->addWidget(titleLabel); setLayout(l); } void DockletToolBar::addAction(QAction* action) { QToolButton* btn = new DockletToolButton; btn->setIconSize(QSize(16, 16)); btn->setDefaultAction(action); if (!btn->icon().isNull()) btn->setToolButtonStyle(Qt::ToolButtonIconOnly); btn->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); if (layout()) layout()->addWidget(btn); } void DockletToolBar::addWidget(QWidget* widget, int stretch) { static_cast<QHBoxLayout*>(layout())->addWidget(widget, stretch); } void DockletToolBar::paintEvent(QPaintEvent* event) { QPainter painter(this); QRect r = rect(); painter.setBrush(palette().color(QPalette::Mid)); painter.setPen(Qt::NoPen); painter.drawRect(r); painter.setPen(palette().color(QPalette::Shadow)); painter.drawLine(r.bottomLeft(), r.bottomRight()); // painter.setPen( palette().color(QPalette::Mid).lighter(120) ); // painter.drawLine( r.topLeft(), r.topRight() ); } static void updateWindowState(QWidget* window, QDockWidget::DockWidgetFeatures features) { Qt::WindowFlags flags = window->windowFlags(); if (features & QDockWidget::DockWidgetClosable) flags |= Qt::WindowCloseButtonHint; else flags &= ~Qt::WindowCloseButtonHint; window->setWindowFlags(flags); } Docklet::Docklet(const QString& title, QWidget* parent): QObject(parent), mWindow(0), mWidget(0) { mDockWidget = new QDockWidget(title, parent); mDockWidget->installEventFilter(this); mToolBar = new DockletToolBar(title); mDockWidget->setTitleBarWidget(mToolBar); QMenu* optionsMenu = mToolBar->optionsMenu(); QAction* action; QDockWidget::DockWidgetFeatures features = mDockWidget->features(); mDockAction = action = optionsMenu->addAction(tr("Undock")); action->setEnabled(features & QDockWidget::DockWidgetFloatable); connect(action, SIGNAL(triggered(bool)), this, SLOT(toggleFloating())); mDetachAction = action = optionsMenu->addAction(tr("Detach")); action->setEnabled(features & QDockWidget::DockWidgetFloatable); connect(action, SIGNAL(triggered(bool)), this, SLOT(toggleDetached())); action = optionsMenu->addAction(tr("Close")); action->setEnabled(features & QDockWidget::DockWidgetClosable); connect(action, SIGNAL(triggered(bool)), this, SLOT(close())); mVisibilityAction = action = new QAction(title, this); action->setCheckable(true); connect(action, SIGNAL(triggered(bool)), this, SLOT(setVisible(bool))); connect(mDockWidget, SIGNAL(topLevelChanged(bool)), this, SLOT(updateDockAction())); connect(mDockWidget, SIGNAL(featuresChanged(QDockWidget::DockWidgetFeatures)), this, SLOT(onFeaturesChanged(QDockWidget::DockWidgetFeatures))); } void Docklet::toggleFloating() { bool undock = !(isDetached() || mDockWidget->isFloating()); // WARNING: QDockWidget is broken: it internally caches undocked geometry, // but only when resized, not when moved. // Thus QDockWidget::setFloating may potentially restore wrong geometry, // in turn corrupting also our own mUndockedGeom via event filtering! // So take measures to remedy that: QRect undockedGeom = mUndockedGeom; QWidget* container = currentContainer(); if (container != mDockWidget) { container->hide(); setCurrentContainer(DockableContainer); } mDockWidget->setFloating(undock); mDockWidget->show(); if (undock) { qDebug() << "dock: set geom (toggleFloating):" << undockedGeom << this; if (undockedGeom.isNull()) { // Looks like resize or move event does not always occur, // so store the undocked geometry here. mUndockedGeom = mDockWidget->geometry(); } else { mDockWidget->setGeometry(undockedGeom); } } updateDockAction(); } void Docklet::toggleDetached() { setDetachedAndVisible(!isDetached(), this->isVisible()); } void Docklet::setDetachedAndVisible(bool detach, bool visible) { if (isDetached() == detach) return; Q_ASSERT(!isDetached() || mWindow != NULL); QRect undockedGeom = mUndockedGeom; currentContainer()->hide(); setCurrentContainer(detach ? WindowContainer : DockableContainer); if (!detach) mDockWidget->setFloating(true); QWidget* container = currentContainer(); // NOTE: Only call show() if the docklet is set to visible otherwise we might // get into some timing issue where show() can be called after setVisible(false) // https://github.com/supercollider/supercollider/issues/3287 if (visible) container->show(); // NOTE: set geometry after show() or else some geometry modifying events // are postponed! qDebug() << (detach ? "win:" : "dock:") << "set geom (setDetachedAndVisible):" << undockedGeom << this; if (!undockedGeom.isNull()) container->setGeometry(undockedGeom); updateDockAction(); } void Docklet::setCurrentContainer(ContainerType containerType) { switch (containerType) { case DockableContainer: mDockWidget->setTitleBarWidget(mToolBar); mDockWidget->setWidget(mWidget); break; case WindowContainer: mDockWidget->setWidget(0); mDockWidget->setTitleBarWidget(0); QVBoxLayout* layout; if (!mWindow) { mWindow = new QWidget(); layout = new QVBoxLayout(); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); mWindow->setLayout(layout); mWindow->setWindowTitle(mDockWidget->windowTitle()); mWindow->installEventFilter(this); updateWindowState(mWindow, mDockWidget->features()); } else layout = qobject_cast<QVBoxLayout*>(mWindow->layout()); layout->addWidget(mToolBar); layout->addWidget(mWidget); mWidget->show(); mToolBar->show(); break; } mDetachAction->setText(containerType == WindowContainer ? tr("Attach") : tr("Detach")); } QByteArray Docklet::saveDetachedState() const { QByteArray data; if (isDetached()) { data.append((char)mWindow->isVisible()); data.append(mWindow->saveGeometry()); } return data; } void Docklet::restoreDetachedState(const QByteArray& data) { if (!data.isEmpty()) { bool visible = data.at(0) == 1; setDetachedAndVisible(true, visible); mWindow->restoreGeometry(data.mid(1)); } else setDetachedAndVisible(false, this->isVisible()); } void Docklet::updateDockAction() { bool docked = currentContainer() == mDockWidget && !mDockWidget->isFloating(); mDockAction->setText(docked ? tr("Undock") : tr("Dock")); } void Docklet::onFeaturesChanged(QDockWidget::DockWidgetFeatures features) { if (mWindow) updateWindowState(mWindow, features); } bool Docklet::eventFilter(QObject* object, QEvent* event) { switch (event->type()) { case QEvent::Show: // qDebug() << "shown:" << object; mVisibilityAction->setChecked(true); #ifdef Q_OS_MAC if (object == mDockWidget && mDockWidget->isFloating()) { // qDebug("fitting geometry"); mDockWidget->setGeometry(fittedToScreen(mDockWidget->geometry(), mDockWidget)); } #endif break; case QEvent::Hide: // qDebug() << "hidden:" << object; mVisibilityAction->setChecked(false); break; case QEvent::Resize: case QEvent::Move: { if (object == currentContainer()) { if (object == mWindow) { mUndockedGeom = mWindow->geometry(); qDebug() << "cache window geom" << mUndockedGeom << this; } else if (object == mDockWidget && mDockWidget->isFloating()) { mUndockedGeom = mDockWidget->geometry(); qDebug() << "cache dock geom" << mUndockedGeom << this; } } break; } default: break; } return QObject::eventFilter(object, event); } } // namespace ScIDE
10,554
C++
.cpp
255
35.443137
107
0.6913
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,033
popup_widget.cpp
supercollider_supercollider/editors/sc-ide/widgets/util/popup_widget.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "popup_widget.hpp" #include <QKeyEvent> #include <QApplication> #include <QScreen> #include <QWindow> #include <QDebug> namespace ScIDE { PopUpWidget::PopUpWidget(QWidget* parent): QWidget(parent, Qt::ToolTip), mEventLoop(0), mResult(0) {} PopUpWidget::~PopUpWidget() { quit(); } int PopUpWidget::exec(const QRect& targetRect) { if (mEventLoop) { qWarning("ScIDE::PopUpWidget: recursive exec() - suppressed!"); return Rejected; } mResult = Rejected; mTargetRect = targetRect; QEventLoop eventLoop; mEventLoop = &eventLoop; show(); QPointer<QObject> self(this); mEventLoop->exec(); if (self.isNull()) return Rejected; return mResult; } void PopUpWidget::popup(const QRect& targetRect) { mResult = Rejected; mTargetRect = targetRect; show(); } void PopUpWidget::keyPressEvent(QKeyEvent* ke) { switch (ke->key()) { case Qt::Key_Escape: reject(); break; default:; } } void PopUpWidget::showEvent(QShowEvent*) { QRect rect = geometry(); rect.moveTopLeft(mTargetRect.bottomLeft()); QWidget* parentWid = parentWidget(); QWidget* referenceWidget = parentWid ? parentWid : this; QRect screen = referenceWidget->screen()->availableGeometry(); if (!screen.contains(rect)) { if (rect.right() > screen.right()) rect.moveRight(screen.right()); if (rect.left() < screen.left()) rect.moveLeft(screen.left()); if (rect.bottom() > screen.bottom()) rect.moveBottom(qMin(mTargetRect.top(), screen.bottom())); if (rect.top() < screen.top()) rect.moveTop(screen.top()); } move(rect.topLeft()); } } // namespace ScIDE
2,583
C++
.cpp
73
30.260274
101
0.686621
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
30,034
gui_utilities.cpp
supercollider_supercollider/editors/sc-ide/widgets/util/gui_utilities.cpp
/* SuperCollider Qt IDE Copyright (c) 2012-2013 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "gui_utilities.hpp" #include <QWidget> #include <QApplication> #include <QApplication> #include <QScreen> #include <QWindow> namespace ScIDE { QRect fittedToScreen(const QRect& rect, QWidget* referenceWidget) { QRect fittedRect = rect; QRect screen = referenceWidget->screen()->availableGeometry(); if (!screen.contains(fittedRect)) { if (fittedRect.right() > screen.right()) fittedRect.moveRight(screen.right()); if (fittedRect.left() < screen.left()) fittedRect.moveLeft(screen.left()); if (fittedRect.bottom() > screen.bottom()) fittedRect.moveBottom(screen.bottom()); if (fittedRect.top() < screen.top()) fittedRect.moveTop(screen.top()); } return fittedRect; } }
1,624
C++
.cpp
39
36.435897
81
0.714014
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
30,035
text_format_list_widget.cpp
supercollider_supercollider/editors/sc-ide/widgets/util/text_format_list_widget.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "text_format_list_widget.hpp" #include <QPainter> #include <QApplication> #include <QHeaderView> #include <QStandardItemModel> #include <QColorDialog> namespace ScIDE { TextFormatListWidget::ItemDelegate::ItemDelegate(QObject* parent): QStyledItemDelegate(parent) {} QSize TextFormatListWidget::ItemDelegate::sizeHint(const QStyleOptionViewItem& opt, const QModelIndex& index) const { switch (index.column()) { case 1: return QSize(30, 20); default: return QStyledItemDelegate::sizeHint(opt, index); } } void TextFormatListWidget::ItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& opt, const QModelIndex& index) const { int col = index.column(); if (col < 1 || col > 2) { QStyledItemDelegate::paint(painter, opt, index); return; } QApplication::style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter); QBrush brush = index.data(Qt::DisplayRole).value<QBrush>(); if (brush.style() == Qt::NoBrush) { brush.setColor(opt.palette.color(QPalette::Text)); brush.setStyle(Qt::BDiagPattern); } QSize sz(30, 14); QRect r; r.setSize(sz); r.moveCenter(opt.rect.center()); painter->save(); painter->setBrush(brush); painter->setPen(opt.palette.color(QPalette::Text)); painter->drawRect(r.adjusted(0, 0, -1, -1)); painter->restore(); } TextFormatListWidget::TextFormatListWidget(QWidget* parent): QTreeView(parent) { QStandardItemModel* m = new QStandardItemModel(this); m->setHorizontalHeaderLabels(QStringList() << tr("Role") << tr("Color") << tr("Background") << "B" << "I" << "U"); QItemSelectionModel* old_sm = selectionModel(); QAbstractItemModel* old_m = model(); setModel(m); delete old_m; delete old_sm; QAbstractItemDelegate* old_d = itemDelegate(); setItemDelegate(new ItemDelegate(this)); delete old_d; header()->setSectionResizeMode(QHeaderView::ResizeToContents); setContextMenuPolicy(Qt::CustomContextMenu); connect(this, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(onDoubleClicked(const QModelIndex&))); } void TextFormatListWidget::addFormat(const QString& name, const QTextCharFormat& format) { QList<QStandardItem*> items; QStandardItem* nameItem = new QStandardItem(name); nameItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); items << nameItem; items << makeBrushItem(format.foreground()); items << makeBrushItem(format.background()); items << makeBoolItem(format.fontWeight() == QFont::Bold); items << makeBoolItem(format.fontItalic()); items << makeBoolItem(format.fontUnderline()); standardModel()->appendRow(items); } void TextFormatListWidget::setFormat(int index, const QTextCharFormat& format) { QStandardItemModel* m = standardModel(); if (index < 0 || index >= m->rowCount()) return; m->item(index, 1)->setData(format.foreground(), Qt::DisplayRole); m->item(index, 2)->setData(format.background(), Qt::DisplayRole); m->item(index, 3)->setCheckState(format.fontWeight() == QFont::Bold ? Qt::Checked : Qt::Unchecked); m->item(index, 4)->setCheckState(format.fontItalic() ? Qt::Checked : Qt::Unchecked); m->item(index, 5)->setCheckState(format.fontUnderline() ? Qt::Checked : Qt::Unchecked); } QString TextFormatListWidget::name(int index) { QStandardItemModel* m = standardModel(); QString str; if (index < 0 || index >= m->rowCount()) return str; str = m->item(index, 0)->text(); return str; } QTextCharFormat TextFormatListWidget::format(int index) { QStandardItemModel* m = standardModel(); QTextCharFormat fm; if (index < 0 || index >= m->rowCount()) return fm; QBrush br = m->item(index, 1)->data(Qt::DisplayRole).value<QBrush>(); if (br.style() != Qt::NoBrush) fm.setForeground(br); br = m->item(index, 2)->data(Qt::DisplayRole).value<QBrush>(); if (br.style() != Qt::NoBrush) fm.setBackground(br); bool b = m->item(index, 3)->checkState() == Qt::Checked; if (b) fm.setFontWeight(QFont::Bold); b = m->item(index, 4)->checkState() == Qt::Checked; if (b) fm.setFontItalic(true); b = m->item(index, 5)->checkState() == Qt::Checked; if (b) fm.setFontUnderline(true); return fm; } void TextFormatListWidget::onDoubleClicked(const QModelIndex& index) { int column = index.column(); if (column < 1 || column > 2) return; QStandardItem* item = standardModel()->item(index.row(), column); QBrush br = item->data(Qt::DisplayRole).value<QBrush>(); QColor color = QColorDialog::getColor(br.color(), this); if (color.isValid()) { item->setData(QBrush(color), Qt::DisplayRole); } } QStandardItem* TextFormatListWidget::makeBrushItem(const QBrush& brush) { QStandardItem* item = new QStandardItem(); item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); item->setData(brush, Qt::DisplayRole); return item; } QStandardItem* TextFormatListWidget::makeBoolItem(bool b) { QStandardItem* item = new QStandardItem(); item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); item->setCheckable(true); if (b) item->setCheckState(Qt::Checked); return item; } } // namespace ScIDE
6,339
C++
.cpp
150
36.433333
117
0.681167
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,036
volume_widget.cpp
supercollider_supercollider/editors/sc-ide/widgets/util/volume_widget.cpp
/* SuperCollider Qt IDE Copyright (c) 2013 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "volume_widget.hpp" #include "SC_BoundsMacros.h" #include "SC_InlineUnaryOp.h" #include <QtGlobal> #include <QHBoxLayout> #include <QSlider> #include <QLabel> #include <QKeyEvent> namespace ScIDE { VolumeWidget::VolumeWidget(QWidget* parent): QWidget(parent) { mVolumeLabel = new QLabel; mVolumeSlider = new QSlider; mVolumeSlider->setOrientation(Qt::Horizontal); mVolumeSlider->setMinimum(0); mVolumeSlider->setMaximum(1000); mVolumeSlider->setMinimumWidth(120); mVolumeSlider->installEventFilter(this); QHBoxLayout* layout = new QHBoxLayout; layout->addWidget(new QLabel("Volume:")); layout->addWidget(mVolumeLabel); layout->addWidget(mVolumeSlider); setLayout(layout); connect(mVolumeSlider, &QSlider::actionTriggered, [=] { onVolumeSliderAction(); }); } void VolumeWidget::setVolume(float volume) { mVolumeSlider->setValue(volumeToSlider(volume)); mVolumeLabel->setText(QString::number(volume, 'f', 1) + " dB"); } void VolumeWidget::setVolumeRange(float min, float max) { mVolumeMin = min; mVolumeMax = max; } void VolumeWidget::onVolumeSliderAction() { emit volumeChangeRequested(volumeFromSlider(mVolumeSlider->sliderPosition())); } int VolumeWidget::volumeToSlider(float volume) { float ampMax = sc_dbamp(mVolumeMax); float ampMin = sc_dbamp(mVolumeMin); float ampRange = ampMax - ampMin; float slider = (ampRange >= 0) ? std::sqrt((sc_dbamp(volume) - ampMin) / ampRange) : 1 - std::sqrt(1 - ((sc_dbamp(volume) - ampMin) / ampRange)); return slider * 1000.f; } float VolumeWidget::volumeFromSlider(int sliderValue) { float slider = sliderValue / 1000.f; float ampMax = sc_dbamp(mVolumeMax); float ampMin = sc_dbamp(mVolumeMin); float ampRange = ampMax - ampMin; if (ampRange >= 0) return sc_ampdb(slider * slider * ampRange + ampMin); else { return sc_ampdb((1.f - (1.f - slider) * (1.f - slider)) * ampRange + ampMin); } } bool VolumeWidget::eventFilter(QObject* object, QEvent* event) { if (object != mVolumeSlider) return false; switch (event->type()) { case QEvent::KeyPress: { QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event); switch (keyEvent->key()) { case Qt::Key_Home: emit volumeChangeRequested(0.f); event->accept(); return true; case Qt::Key_End: emit volumeChangeRequested(-9999); event->accept(); return true; default: break; } } default: break; } return QWidget::eventFilter(object, event); } } // namespace ScIDE
3,551
C++
.cpp
95
31.915789
97
0.68821
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,037
completion_menu.cpp
supercollider_supercollider/editors/sc-ide/widgets/code_editor/completion_menu.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "completion_menu.hpp" #include <QDebug> #include <QKeyEvent> #include <QApplication> namespace ScIDE { CompletionMenu::CompletionMenu(QWidget* parent): PopUpWidget(parent), mCompletionRole(Qt::DisplayRole) { mModel = new QStandardItemModel(this); mFilterModel = new QSortFilterProxyModel(this); mFilterModel->setSourceModel(mModel); mListView = new QListView(); mListView->setModel(mFilterModel); mListView->setFrameShape(QFrame::NoFrame); mListView->setFixedHeight(200); mTextBrowser = new CompletionTextBrowser(); mTextBrowser->setFrameShape(QFrame::NoFrame); mTextBrowser->setReadOnly(true); mTextBrowser->setFixedSize(500, 400); mTextBrowser->hide(); mTextBrowser->setOpenLinks(false); mLayout = new QHBoxLayout(this); mLayout->addWidget(mListView); mLayout->addWidget(mTextBrowser); mLayout->setContentsMargins(1, 1, 1, 1); connect(mListView, SIGNAL(clicked(QModelIndex)), this, SLOT(accept())); connect(mTextBrowser, SIGNAL(anchorClicked(const QUrl)), this, SLOT(onAnchorClicked(const QUrl))); mListView->setFocus(Qt::OtherFocusReason); parent->installEventFilter(this); } void CompletionMenu::addItem(QStandardItem* item) { mModel->appendRow(item); } void CompletionMenu::adapt() { mListView->setFixedWidth(mListView->sizeHintForColumn(0)); resize(0, 0); } void CompletionMenu::addInfo(QString info) { mTextBrowser->setText(info); mListView->setFixedHeight(400); mTextBrowser->show(); } void CompletionMenu::setCompletionRole(int role) { mFilterModel->setFilterRole(role); mFilterModel->setSortRole(role); mCompletionRole = role; } QString CompletionMenu::currentText() { QStandardItem* item = mModel->itemFromIndex(mFilterModel->mapToSource(mListView->currentIndex())); if (item) return item->data(mCompletionRole).toString(); return QString(); } const ScLanguage::Method* CompletionMenu::currentMethod() { QStandardItem* item = mModel->itemFromIndex(mFilterModel->mapToSource(mListView->currentIndex())); return item ? item->data(MethodRole).value<const ScLanguage::Method*>() : 0; } QString CompletionMenu::exec(const QRect& rect) { QString result; QPointer<CompletionMenu> self = this; if (PopUpWidget::exec(rect)) { if (!self.isNull()) result = currentText(); } return result; } QSortFilterProxyModel* CompletionMenu::model() { return mFilterModel; } QListView* CompletionMenu::view() { return mListView; } bool CompletionMenu::eventFilter(QObject* obj, QEvent* ev) { if (isVisible() && obj == parentWidget() && ev->type() == QEvent::KeyPress) { static int oldIndex = 0; QKeyEvent* kev = static_cast<QKeyEvent*>(ev); switch (kev->key()) { case Qt::Key_Up: case Qt::Key_Down: case Qt::Key_PageUp: case Qt::Key_PageDown: QApplication::sendEvent(mListView, ev); if (oldIndex != mListView->currentIndex().row()) { emit itemChanged(mListView->currentIndex().row()); oldIndex = mListView->currentIndex().row(); } return true; case Qt::Key_Return: case Qt::Key_Enter: accept(); return true; } } return PopUpWidget::eventFilter(obj, ev); } void CompletionMenu::onAnchorClicked(QUrl url) { emit infoClicked(QString(url.path())); } } // namespace ScIDE
4,309
C++
.cpp
105
35.590476
104
0.708363
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,038
highlighter.cpp
supercollider_supercollider/editors/sc-ide/widgets/code_editor/highlighter.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cassert> #include <algorithm> #include "highlighter.hpp" #include "../../core/main.hpp" #include "../../core/settings/manager.hpp" #include "../../core/settings/theme.hpp" #include <QApplication> namespace ScIDE { SyntaxHighlighterGlobals* SyntaxHighlighterGlobals::mInstance = 0; SyntaxHighlighterGlobals::SyntaxHighlighterGlobals(Main* main, Settings::Manager* settings): QObject(main) { Q_ASSERT(mInstance == 0); mInstance = this; ScLexer::initLexicalRules(); // initialize formats from settings: applySettings(settings); connect(main, SIGNAL(applySettingsRequest(Settings::Manager*)), this, SLOT(applySettings(Settings::Manager*))); } void SyntaxHighlighterGlobals::applySettings(Settings::Manager* s) { applySettings(s, "whitespace", WhitespaceFormat); applySettings(s, "keyword", KeywordFormat); applySettings(s, "built-in", BuiltinFormat); applySettings(s, "primitive", PrimitiveFormat); applySettings(s, "class", ClassFormat); applySettings(s, "number", NumberFormat); applySettings(s, "symbol", SymbolFormat); applySettings(s, "env-var", EnvVarFormat); applySettings(s, "string", StringFormat); applySettings(s, "char", CharFormat); applySettings(s, "comment", CommentFormat); Q_EMIT(syntaxFormatsChanged()); } void SyntaxHighlighterGlobals::applySettings(Settings::Manager* s, const QString& key, SyntaxFormat type) { mFormats[type] = s->getThemeVal(key); } SyntaxHighlighter::SyntaxHighlighter(QTextDocument* parent): QSyntaxHighlighter(parent) { mGlobals = SyntaxHighlighterGlobals::instance(); connect(mGlobals, SIGNAL(syntaxFormatsChanged()), this, SLOT(rehighlight())); connect(Main::scProcess(), &ScProcess::introspectionChanged, this, &SyntaxHighlighter::rehighlight); } void SyntaxHighlighter::highlightBlockInCode(ScLexer& lexer) { TextBlockData* blockData = static_cast<TextBlockData*>(currentBlockUserData()); Q_ASSERT(blockData); const QTextCharFormat* formats = mGlobals->formats(); do { int tokenPosition = lexer.offset(); int tokenLength; Token::Type tokenType = lexer.nextToken(tokenLength); switch (tokenType) { case Token::WhiteSpace: setFormat(tokenPosition, tokenLength, formats[WhitespaceFormat]); break; case Token::Class: { auto className = QString(lexer.text().begin() + tokenPosition, tokenLength); auto* classInstance = Main::scProcess()->introspection().findClass(className); if (classInstance != nullptr) setFormat(tokenPosition, tokenLength, formats[ClassFormat]); break; } case Token::Builtin: setFormat(tokenPosition, tokenLength, formats[BuiltinFormat]); break; case Token::Primitive: setFormat(tokenPosition, tokenLength, formats[PrimitiveFormat]); break; case Token::Keyword: setFormat(tokenPosition, tokenLength, formats[KeywordFormat]); break; case Token::Symbol: setFormat(tokenPosition, tokenLength, formats[SymbolFormat]); break; case Token::SymbolArg: // Don't highlight the trailing ':' setFormat(tokenPosition, tokenLength - 1, formats[SymbolFormat]); break; case Token::EnvVar: setFormat(tokenPosition, tokenLength, formats[EnvVarFormat]); break; case Token::Char: setFormat(tokenPosition, tokenLength, formats[CharFormat]); break; case Token::Float: case Token::HexInt: case Token::ScaleDegreeFloat: case Token::RadixFloat: setFormat(tokenPosition, tokenLength, formats[NumberFormat]); break; case Token::SingleLineComment: setFormat(tokenPosition, tokenLength, formats[CommentFormat]); break; case Token::MultiLineCommentStart: setFormat(tokenPosition, tokenLength, formats[CommentFormat]); break; case Token::StringMark: setFormat(tokenPosition, tokenLength, formats[StringFormat]); break; case Token::SymbolMark: setFormat(tokenPosition, tokenLength, formats[SymbolFormat]); break; default:; } if ((tokenType != Token::WhiteSpace) && (tokenType != Token::SingleLineComment) && (tokenType != Token::MultiLineCommentStart)) { Token token(tokenType, tokenPosition, tokenLength); if (token.length == 1) token.character = lexer.text()[tokenPosition].toLatin1(); blockData->tokens.push_back(token); } } while (lexer.state() == ScLexer::InCode && lexer.offset() < lexer.text().size()); } void SyntaxHighlighter::highlightBlockInString(ScLexer& lexer) { int originalOffset = lexer.offset(); int tokenLength; Token::Type tokenType = lexer.nextToken(tokenLength); int range = lexer.offset() - originalOffset; setFormat(originalOffset, range, mGlobals->format(StringFormat)); if (tokenType == Token::Unknown) return; Q_ASSERT(tokenType == Token::StringMark); Token token(tokenType, lexer.offset() - 1, 1); token.character = '"'; TextBlockData* blockData = static_cast<TextBlockData*>(currentBlockUserData()); Q_ASSERT(blockData); blockData->tokens.push_back(token); } void SyntaxHighlighter::highlightBlockInSymbol(ScLexer& lexer) { int originalOffset = lexer.offset(); int tokenLength; Token::Type tokenType = lexer.nextToken(tokenLength); int range = lexer.offset() - originalOffset; setFormat(originalOffset, range, mGlobals->format(SymbolFormat)); if (tokenType == Token::Unknown) return; Q_ASSERT(tokenType == Token::SymbolMark); Token token(tokenType, lexer.offset() - 1, 1); token.character = '\''; TextBlockData* blockData = static_cast<TextBlockData*>(currentBlockUserData()); Q_ASSERT(blockData); blockData->tokens.push_back(token); } void SyntaxHighlighter::highlightBlockInComment(ScLexer& lexer) { int originalOffset = lexer.offset(); int tokenLength; lexer.nextToken(tokenLength); int range = lexer.offset() - originalOffset; setFormat(originalOffset, range, mGlobals->format(CommentFormat)); } void SyntaxHighlighter::highlightBlock(const QString& text) { // if we don't have introspection yet don't format anything if (!Main::scProcess()->introspection().introspectionAvailable()) return; TextBlockData* blockData = static_cast<TextBlockData*>(currentBlockUserData()); if (!blockData) { blockData = new TextBlockData; blockData->tokens.reserve(8); setCurrentBlockUserData(blockData); } else { blockData->tokens.clear(); } int previousState = previousBlockState(); if (previousState == -1) previousState = ScLexer::InCode; ScLexer lexer(text, 0, previousState); while (lexer.offset() < text.size()) { switch (lexer.state()) { case ScLexer::InCode: highlightBlockInCode(lexer); break; case ScLexer::InString: highlightBlockInString(lexer); break; case ScLexer::InSymbol: highlightBlockInSymbol(lexer); break; default: if (lexer.state() >= ScLexer::InComment) highlightBlockInComment(lexer); } } setCurrentBlockState(lexer.state()); } }
8,443
C++
.cpp
197
35.467005
115
0.682912
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,039
autocompleter.cpp
supercollider_supercollider/editors/sc-ide/widgets/code_editor/autocompleter.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define QT_NO_DEBUG_OUTPUT #include "autocompleter.hpp" #include "sc_editor.hpp" #include "tokens.hpp" #include "../../core/sc_introspection.hpp" #include "../../core/sc_process.hpp" #include "../../core/main.hpp" #include "../../core/util/standard_dirs.hpp" #include "../main_window.hpp" #ifdef SC_USE_QTWEBENGINE # include "../help_browser.hpp" #endif // SC_USE_QTWEBENGINE #include <yaml-cpp/node/node.h> #include <yaml-cpp/parser.h> #include <QDebug> #include <QLabel> #include <QScrollBar> #include <QApplication> #include <QScreen> #include <QWindow> #include <QProxyStyle> #include <QFile> namespace ScIDE { static bool tokenMaybeName(Token::Type type) { return (type == Token::Name || type == Token::Keyword || type == Token::Builtin); } static QString incrementedString(const QString& other) { if (other.isEmpty()) return QString(); QString str = other; int pos = str.length() - 1; str[pos] = QChar(str[pos].unicode() + 1); return str; } class MethodCallWidget : public QWidget { public: MethodCallWidget(QWidget* parent = 0): QWidget(parent, Qt::ToolTip) { mLabel = new QLabel(this); mLabel->setTextFormat(Qt::RichText); mLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); // Qt 4 had a class called "QGtkStyle" which allowed Qt to access the // native style of the window manager in Linux and other *nix systems. // It was removed in Qt 5, so we don't have that option anymore. We have // to hardcode the colors now. In the future, this should be configurable // by the user. // This #if used to be "#if defined(Q_WS_X11)", and then NetBSD was // excluded (commit c3017f5) because QGtkStyle was not defined on that // system. Qt 5 got rid of the Q_WS_ macros, so we changed Q_WS_X11 to // Q_OS_UNIX && !Q_OS_MAC as a best guess. The NetBSD check is probably // vestigial, but we REALLY needed to get this fix through since Linux // users have had unreadable autocomplete widgets for almost 18 months // now. We figured it was best to leave it alone. // See: https://github.com/supercollider/supercollider/pull/2762 #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) && !defined(__NetBSD__) QPalette p; p.setColor(QPalette::Window, QColor(255, 255, 220)); p.setColor(QPalette::WindowText, Qt::black); setPalette(p); #else QPalette p(palette()); p.setColor(QPalette::Window, p.color(QPalette::ToolTipBase)); setPalette(p); mLabel->setForegroundRole(QPalette::ToolTipText); #endif } void showMethod(const AutoCompleter::MethodCall& methodCall, int argNum, const QRect& cursorRect) { const ScLanguage::Method* method = methodCall.method; int argc = method->arguments.count(); QString text; if (methodCall.functionalNotation) { addArgument(text, "receiver", QString(), argNum == 0); --argNum; if (argc) text += ", &nbsp;&nbsp;"; } for (int i = 0; i < argc; ++i) { const ScLanguage::Argument& arg = method->arguments[i]; addArgument(text, arg.name, arg.defaultValue, argNum == i); if (i != argc - 1) text += ", &nbsp;&nbsp;"; } mLabel->setText(text); mTargetRect = cursorRect; updateGeometry(); show(); } private: void static addArgument(QString& text, const QString& argText, const QString& valText, bool highlight) { if (highlight) { text += QString("<span style=\"" //"text-decoration: underline;" "font-weight: bold;" "\">"); } text += argText; if (!valText.isEmpty()) text += " = " + valText; if (highlight) text += "</span>"; } void updateGeometry() { static const QSize margins = QSize(5, 2); QSize labelSize = mLabel->sizeHint(); mLabel->move(margins.width(), margins.height()); mLabel->resize(labelSize); QRect rect; rect.setSize(labelSize + (margins * 2)); rect.moveBottomLeft(mTargetRect.topLeft()); QWidget* parentWid = parentWidget(); QWidget* referenceWidget = parentWid ? parentWid : this; QRect screen = referenceWidget->screen()->availableGeometry(); if (!screen.contains(rect)) { if (rect.right() > screen.right()) rect.moveRight(screen.right()); if (rect.left() < screen.left()) rect.moveLeft(screen.left()); if (rect.top() < screen.top()) rect.moveTop(qMax(mTargetRect.bottom(), screen.top())); if (rect.bottom() > screen.bottom()) rect.moveBottom(screen.bottom()); } setGeometry(rect); } QLabel* mLabel; QRect mTargetRect; }; AutoCompleter::AutoCompleter(ScCodeEditor* editor): QObject(editor), mEditor(editor) { mCompletion.on = false; mEditor->installEventFilter(this); connect(editor, SIGNAL(cursorPositionChanged()), this, SLOT(onCursorChanged())); connect(editor->horizontalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(hideWidgets())); connect(editor->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(hideWidgets())); connect(Main::scProcess(), SIGNAL(introspectionChanged()), this, SLOT(clearMethodCallStack())); } void AutoCompleter::documentChanged(QTextDocument* doc) { connect(doc, SIGNAL(contentsChange(int, int, int)), this, SLOT(onContentsChange(int, int, int))); } inline QTextDocument* AutoCompleter::document() { return static_cast<QPlainTextEdit*>(mEditor)->document(); } void AutoCompleter::keyPress(QKeyEvent* e) { switch (e->key()) { case Qt::Key_ParenLeft: case Qt::Key_Comma: triggerMethodCallAid(false); break; case Qt::Key_Backspace: case Qt::Key_Delete: return; default: qDebug(">>> key"); // Only trigger completion if event produces at least 1 printable character: if (!mCompletion.on && !e->text().isEmpty() && e->text()[0].isPrint()) triggerCompletion(); } } bool AutoCompleter::eventFilter(QObject* object, QEvent* event) { if (object != mEditor) return false; switch (event->type()) { case QEvent::FocusOut: hideWidgets(); break; case QEvent::ShortcutOverride: { QKeyEvent* kevent = static_cast<QKeyEvent*>(event); switch (kevent->key()) { case Qt::Key_Left: case Qt::Key_Right: if (mCompletion.menu && mCompletion.menu->isVisible()) mCompletion.menu->reject(); break; case Qt::Key_Escape: if (mCompletion.menu && mCompletion.menu->isVisible()) mCompletion.menu->reject(); else if (mMethodCall.menu && mMethodCall.menu->isVisible()) mMethodCall.menu->reject(); else if (mMethodCall.widget && mMethodCall.widget->isVisible()) { // disable method call aid for current call: Q_ASSERT(!mMethodCall.stack.isEmpty()); mMethodCall.stack.top().suppressed = true; hideMethodCall(); } else break; return true; } break; } case QEvent::KeyPress: { QKeyEvent* kevent = static_cast<QKeyEvent*>(event); switch (kevent->key()) { case Qt::Key_Tab: case Qt::Key_Backtab: if (trySwitchMethodCallArgument(kevent->key() == Qt::Key_Backtab)) { event->accept(); return true; } break; } break; } default:; } return QObject::eventFilter(object, event); } void AutoCompleter::onContentsChange(int pos, int removed, int added) { qDebug() << ">>> contentsChange:" << pos << "-" << removed << "+" << added; int callIdx = 0; while (callIdx < mMethodCall.stack.count()) { MethodCall& call = mMethodCall.stack[callIdx]; if (pos > call.position) { break; } else if (pos + removed > call.position) { qDebug("Method call: opening bracket deleted. popping."); mMethodCall.stack.remove(callIdx); } else { // Adjust method call positions. // FIXME: We are disregarding changes in context that defines the method call. // This is for reason of simplicity, and with the benefit that (irrelevant) // indentation changes don't destroy the method call stack qDebug("Method call: adjusting position: %i", call.position); call.position -= removed; call.position += added; qDebug("Method call: adjusted position: %i", call.position); ++callIdx; } } if (mCompletion.on) { if (pos < mCompletion.contextPos) { quitCompletion("context changed"); } else if (pos <= mCompletion.pos + mCompletion.len) { QTextBlock block(document()->findBlock(mCompletion.pos)); TokenIterator it(block, mCompletion.pos - block.position()); Token::Type type = it.type(); if (type == Token::Class || tokenMaybeName(type)) { mCompletion.len = it->length; mCompletion.text = tokenText(it); } else { mCompletion.len = 0; mCompletion.text.clear(); } if (!mCompletion.menu.isNull()) updateCompletionMenu(false); } } } void AutoCompleter::onCursorChanged() { int cursorPos = mEditor->textCursor().position(); qDebug(">>> cursorChanged: %i", cursorPos); // completion if (mCompletion.on) { if (cursorPos < mCompletion.pos || cursorPos > mCompletion.pos + mCompletion.len) { quitCompletion("out of bounds"); } } if (!mMethodCall.menu.isNull()) { qDebug("Method call: quitting menu"); delete mMethodCall.menu; } updateMethodCall(cursorPos); } void AutoCompleter::triggerCompletion(bool forceShow) { if (mCompletion.on) { qDebug("AutoCompleter::triggerCompletion(): completion already started."); updateCompletionMenu(forceShow); return; } QTextCursor cursor(mEditor->textCursor()); const int cursorPos = cursor.positionInBlock(); QTextBlock block(cursor.block()); TokenIterator it(block, cursorPos - 1); if (!it.isValid()) return; const Token& triggeringToken = *it; if (triggeringToken.type == Token::Class) { if (triggeringToken.length < 3) return; mCompletion.type = ClassCompletion; mCompletion.pos = it.position(); mCompletion.len = it->length; mCompletion.text = tokenText(it); mCompletion.contextPos = mCompletion.pos + 3; mCompletion.base = mCompletion.text; mCompletion.base.truncate(3); } else { TokenIterator objectIt, dotIt, nameIt; Token::Type objectTokenType = Token::Unknown; if (tokenMaybeName(it.type())) { nameIt = it; --it; } if (it.isValid() && it.character() == '.') { dotIt = it; --it; } else // don't trigger on method names without preceding dot (for now) return; if (dotIt.isValid()) { objectTokenType = it.type(); switch (objectTokenType) { case Token::Class: case Token::Char: case Token::StringMark: case Token::Builtin: case Token::Symbol: case Token::SymbolMark: case Token::Float: case Token::RadixFloat: case Token::HexInt: objectIt = it; break; default:; } } if (!objectIt.isValid() && (!nameIt.isValid() || nameIt->length < 3)) return; if (nameIt.isValid()) { mCompletion.pos = nameIt.position(); mCompletion.len = nameIt->length; mCompletion.text = tokenText(nameIt); } else { mCompletion.pos = dotIt.position() + 1; mCompletion.len = 0; mCompletion.text.clear(); } if (objectIt.isValid()) { mCompletion.contextPos = mCompletion.pos; mCompletion.base = tokenText(objectIt); mCompletion.tokenType = objectTokenType; mCompletion.type = ClassMethodCompletion; } else { mCompletion.contextPos = mCompletion.pos + 3; mCompletion.base = tokenText(nameIt); mCompletion.type = MethodCompletion; } } mCompletion.on = true; qDebug() << QStringLiteral("Completion: ON <%1>").arg(mCompletion.base); showCompletionMenu(forceShow); if (mCompletion.menu.isNull()) mCompletion.on = false; } void AutoCompleter::quitCompletion(const QString& reason) { Q_ASSERT(mCompletion.on); qDebug() << QStringLiteral("Completion: OFF (%1)").arg(reason); if (mCompletion.menu) { mCompletion.menu->hide(); mCompletion.menu->deleteLater(); mCompletion.menu = 0; } mCompletion.on = false; } void AutoCompleter::showCompletionMenu(bool forceShow) { qDebug(">>> showCompletionMenu"); using namespace ScLanguage; using ScLanguage::Method; Q_ASSERT(mCompletion.on); Q_ASSERT(mCompletion.menu.isNull()); QPointer<CompletionMenu> menu; switch (mCompletion.type) { case ClassCompletion: menu = menuForClassCompletion(mCompletion, mEditor); break; case ClassMethodCompletion: menu = menuForClassMethodCompletion(mCompletion, mEditor); break; case MethodCompletion: menu = menuForMethodCompletion(mCompletion, mEditor); break; default: break; } if (menu == NULL) return; mCompletion.menu = menu; connect(menu, SIGNAL(finished(int)), this, SLOT(onCompletionMenuFinished(int))); QRect popupTargetRect = globalCursorRect(mCompletion.pos).adjusted(0, -5, 0, 5); menu->popup(popupTargetRect); updateCompletionMenu(forceShow); if (mCompletion.type == ClassCompletion && Main::settings()->value("IDE/editor/showAutocompleteHelp").toBool()) { connect(menu, SIGNAL(itemChanged(int)), this, SLOT(updateCompletionMenuInfo())); connect(menu, SIGNAL(infoClicked(QString)), this, SLOT(gotoHelp(QString))); updateCompletionMenuInfo(); } } CompletionMenu* AutoCompleter::menuForClassCompletion(CompletionDescription const& completion, ScCodeEditor* editor) { using namespace ScLanguage; const Introspection& introspection = Main::scProcess()->introspection(); const ClassMap& classes = introspection.classMap(); QString min = completion.base; QString max = incrementedString(min); ClassMap::const_iterator matchStart, matchEnd; matchStart = classes.lower_bound(min); matchEnd = classes.lower_bound(max); if (matchStart == matchEnd) { qDebug() << "Completion: no class matches:" << completion.base; return NULL; } CompletionMenu* menu = new CompletionMenu(editor); for (ClassMap::const_iterator it = matchStart; it != matchEnd; ++it) { Class* klass = it->second.data(); menu->addItem(new QStandardItem(klass->name)); } menu->adapt(); return menu; } CompletionMenu* AutoCompleter::menuForClassMethodCompletion(CompletionDescription const& completion, ScCodeEditor* editor) { using namespace ScLanguage; const Class* klass = NULL; switch (completion.tokenType) { case Token::Float: case Token::RadixFloat: case Token::HexInt: // Only show completion if at least 1 character after dot if (!completion.base.contains(".") && completion.text.isEmpty()) return NULL; default:; } klass = classForToken(completion.tokenType, completion.base); if (klass == NULL) { qDebug() << "Autocompletion not implemented for" << completion.base; return NULL; } QMap<QString, const Method*> methodMap; // for quick lookup QList<const Method*> methodList; // to keep order by class hierarchy do { foreach (const Method* method, klass->methods) { QString methodName = method->name.get(); // Operators are also methods, but are not valid in // a method call syntax, so filter them out. Q_ASSERT(!methodName.isEmpty()); if (!methodName[0].isLetter()) continue; if (methodMap.value(methodName) != 0) continue; methodMap.insert(methodName, method); methodList.append(method); } klass = klass->superClass; } while (klass); CompletionMenu* menu = new CompletionMenu(editor); menu->setCompletionRole(CompletionMenu::CompletionRole); foreach (const Method* method, methodList) { QString methodName = method->name.get(); QString detail(" [ %1 ]"); QStandardItem* item = new QStandardItem(); item->setText(methodName + detail.arg(method->ownerClass->name)); item->setData(QVariant::fromValue(method), CompletionMenu::MethodRole); item->setData(methodName, CompletionMenu::CompletionRole); menu->addItem(item); } menu->adapt(); return menu; } CompletionMenu* AutoCompleter::menuForMethodCompletion(CompletionDescription const& completion, ScCodeEditor* editor) { using namespace ScLanguage; const Introspection& introspection = Main::scProcess()->introspection(); const MethodMap& methods = introspection.methodMap(); QString min = completion.base; QString max = incrementedString(min); MethodMap::const_iterator matchStart, matchEnd; matchStart = methods.lower_bound(min); matchEnd = methods.lower_bound(max); if (matchStart == matchEnd) { qDebug() << "Completion: no method matches:" << completion.base; return NULL; } CompletionMenu* menu = new CompletionMenu(editor); menu->setCompletionRole(CompletionMenu::CompletionRole); for (MethodMap::const_iterator it = matchStart; it != matchEnd;) { const Method* method = it->second.data(); std::pair<MethodMap::const_iterator, MethodMap::const_iterator> range = methods.equal_range(it->first); int count = std::distance(range.first, range.second); QStandardItem* item = new QStandardItem(); QString methodName = method->name.get(); QString detail(" [ %1 ]"); if (count == 1) { item->setText(methodName + detail.arg(method->ownerClass->name)); item->setData(QVariant::fromValue(method), CompletionMenu::MethodRole); } else item->setText(methodName + detail.arg(count)); item->setData(methodName, CompletionMenu::CompletionRole); menu->addItem(item); it = range.second; } menu->adapt(); return menu; } const ScLanguage::Class* AutoCompleter::classForToken(Token::Type tokenType, const QString& tokenString) { using namespace ScLanguage; const Introspection& introspection = Main::scProcess()->introspection(); switch (tokenType) { case Token::Class: { const Class* klass = introspection.findClassOrWarn(tokenString); if (klass) klass = klass->metaClass; return klass; } case Token::Float: case Token::RadixFloat: case Token::HexInt: if (tokenString.contains(".")) // else it is an int return introspection.findClass("Float"); else return introspection.findClass("Integer"); case Token::Char: return introspection.findClass("Char"); case Token::StringMark: return introspection.findClass("String"); case Token::Symbol: case Token::SymbolMark: return introspection.findClass("Symbol"); default:; } if (tokenString == QStringLiteral("true")) return introspection.findClass("True"); if (tokenString == QStringLiteral("false")) return introspection.findClass("False"); if (tokenString == QStringLiteral("nil")) return introspection.findClass("Nil"); if (tokenString == QStringLiteral("thisProcess")) return introspection.findClass("Main"); if (tokenString == QStringLiteral("thisFunction")) return introspection.findClass("Function"); if (tokenString == QStringLiteral("thisMethod")) return introspection.findClass("Method"); if (tokenString == QStringLiteral("thisFunctionDef")) return introspection.findClass("FunctionDef"); if (tokenString == QStringLiteral("thisThread")) return introspection.findClass("Thread"); if (tokenString == QStringLiteral("currentEnvironment")) return introspection.findClass("Environment"); if (tokenString == QStringLiteral("topEnvironment")) return introspection.findClass("Environment"); if (tokenString == QStringLiteral("inf")) return introspection.findClass("Float"); return NULL; } void AutoCompleter::updateCompletionMenu(bool forceShow) { Q_ASSERT(mCompletion.on && !mCompletion.menu.isNull()); CompletionMenu* menu = mCompletion.menu; if (!mCompletion.text.isEmpty()) { QString pattern = mCompletion.text; pattern.prepend("^"); menu->model()->setFilterRegularExpression(pattern); } else menu->model()->setFilterRegularExpression(QString()); if (menu->model()->hasChildren()) { menu->view()->setCurrentIndex(menu->model()->index(0, 0)); if (forceShow || menu->currentText() != mCompletion.text) { if (!menu->isVisible()) menu->setTargetRect(globalCursorRect(mCompletion.pos).adjusted(0, -5, 0, 5)); // The Show event will adjust position. menu->show(); } else menu->hide(); } else menu->hide(); if (mCompletion.type == ClassCompletion && Main::settings()->value("IDE/editor/showAutocompleteHelp").toBool()) updateCompletionMenuInfo(); } void AutoCompleter::onCompletionMenuFinished(int result) { qDebug("Completion: menu finished"); if (!mCompletion.on) return; if (result) { QString text = mCompletion.menu->currentText(); if (!text.isEmpty()) { quitCompletion("done"); QTextCursor cursor(mEditor->textCursor()); cursor.setPosition(mCompletion.pos); cursor.setPosition(mCompletion.pos + mCompletion.len, QTextCursor::KeepAnchor); cursor.insertText(text); return; } } // Do not cancel completion whenever menu hidden. // It could be hidden because of current filter yielding 0 results. // quitCompletion("cancelled"); } void AutoCompleter::updateCompletionMenuInfo() { DocNode* node = parseHelpClass(findHelpClass(mCompletion.menu->currentText())); if (!node) { mCompletion.menu->addInfo(QString()); return; } QString examples = parseClassElement(node, "EXAMPLES"); if (!examples.isEmpty()) examples.prepend("<h4>Examples</h4>"); // MSVStudio 2013 does not concatenate multiple QStringliterals ("""") properly // see http://blog.qt.io/blog/2014/06/13/qt-weekly-13-qstringliteral/ QString infos = QStringLiteral("<h4>%1</h4>%2%3<p><a href=\"%4\">go to help</a>") .arg(parseClassElement(node, "SUMMARY")) .arg(parseClassElement(node, "DESCRIPTION")) .arg(examples) .arg(mCompletion.menu->currentText()); mCompletion.menu->addInfo(infos); doc_node_free_tree(node); } void AutoCompleter::triggerMethodCallAid(bool explicitTrigger) { using namespace ScLanguage; if (!mMethodCall.menu.isNull()) { qDebug("Method call: disambiguation menu already shown. Aborting."); return; } QTextCursor cursor(mEditor->textCursor()); // Find the first bracket that defines a method call TokenIterator tokenIt; TokenIterator bracketIt = TokenIterator::leftOf(cursor.block(), cursor.positionInBlock()); while (true) { bracketIt = ScCodeEditor::previousOpeningBracket(bracketIt); if (!bracketIt.isValid()) return; if (bracketIt->character == '(') { tokenIt = bracketIt.previous(); Token::Type tokenType = tokenIt.type(); if (tokenIt.block() == bracketIt.block() && (tokenType == Token::Name || tokenType == Token::Class)) break; } if (!explicitTrigger) return; --bracketIt; } int bracketPos = bracketIt.position(); // Compare against stack if (!mMethodCall.stack.isEmpty() && mMethodCall.stack.top().position == bracketPos) { // A matching call is already on stack qDebug("Method call: trigger -> call already on stack"); // If triggered explicitly, then either retrigger disambiguation (if needed), // or unsuppress it. if (explicitTrigger && !mMethodCall.stack.top().method) { qDebug("Method call: forced re-trigger, popping current call."); mMethodCall.stack.pop(); hideMethodCall(); } else { if (explicitTrigger) { mMethodCall.stack.top().suppressed = false; updateMethodCall(cursor.position()); } // Else, method call popup has been updated by updateMethodCall() // called on cursor change, before this function. return; } } QString methodName; bool functionalNotation = false; const Class* receiverClass = NULL; Token::Type tokenType = tokenIt.type(); Q_ASSERT(tokenType == Token::Name || tokenType == Token::Class); if (tokenType == Token::Name) { methodName = tokenText(tokenIt); --tokenIt; if (tokenIt.isValid() && tokenIt.character() == '.') --tokenIt; else functionalNotation = true; } else methodName = "new"; if (!functionalNotation && tokenIt.isValid()) receiverClass = classForToken(tokenIt->type, tokenText(tokenIt)); // Ok, this is a valid method call, push on stack qDebug("Method call: found call: %s:%s", receiverClass ? qPrintable(receiverClass->name.get()) : "", methodName.toStdString().c_str()); qDebug("Method call: new call"); MethodCall call; call.position = bracketPos; call.functionalNotation = functionalNotation; pushMethodCall(call); // Obtain method data, either by inferrence or by user-disambiguation via a menu const Method* method = 0; if (receiverClass) { const Class* klass = receiverClass; do { foreach (const Method* m, klass->methods) { if (m->name == methodName) { method = m; break; } } if (method) break; klass = klass->superClass; } while (klass); } else { method = disambiguateMethod(methodName, bracketPos); } // Finally, show the aid for the method if (method) { Q_ASSERT(!mMethodCall.stack.isEmpty()); mMethodCall.stack.top().method = method; updateMethodCall(mEditor->textCursor().position()); } } const ScLanguage::Method* AutoCompleter::disambiguateMethod(const QString& methodName, int cursorPos) { Q_ASSERT(mMethodCall.menu.isNull()); using namespace ScLanguage; using std::pair; const Introspection& introspection = Main::scProcess()->introspection(); const MethodMap& methods = introspection.methodMap(); pair<MethodMap::const_iterator, MethodMap::const_iterator> match = methods.equal_range(methodName); const Method* method = 0; if (match.first == match.second) { qDebug() << "MethodCall: no method matches:" << methodName; method = 0; } else if (std::distance(match.first, match.second) == 1) method = match.first->second.data(); else { QPointer<CompletionMenu> menu = new CompletionMenu(mEditor); mMethodCall.menu = menu; for (MethodMap::const_iterator it = match.first; it != match.second; ++it) { const Method* method = it->second.data(); QStandardItem* item = new QStandardItem(); item->setText(method->name + " (" + method->ownerClass->name + ')'); item->setData(QVariant::fromValue(method), CompletionMenu::MethodRole); menu->addItem(item); } menu->adapt(); QRect popupTargetRect = globalCursorRect(cursorPos).adjusted(0, -5, 0, 5); if (static_cast<PopUpWidget*>(menu)->exec(popupTargetRect)) method = menu->currentMethod(); delete menu; } return method; } void AutoCompleter::updateMethodCall(int cursorPos) { int i = mMethodCall.stack.count(); while (i--) { MethodCall& call = mMethodCall.stack[i]; int argNum = -1; TokenIterator argNameToken; if (!testMethodCall(call, cursorPos, argNum, argNameToken)) { qDebug("Method call: popping."); Q_ASSERT(i == mMethodCall.stack.count() - 1); mMethodCall.stack.pop(); continue; } if (call.suppressed) { qDebug("Method call: suppressed, not showing anything"); break; } if (!call.method || !call.method->arguments.count()) { qDebug("Method call: no info to show. skipping."); continue; } if (argNameToken.isValid()) { QString argName = tokenText(argNameToken); argName.chop(1); for (int idx = 0; idx < call.method->arguments.count(); ++idx) { if (call.method->arguments[idx].name == argName) { argNum = idx; if (call.functionalNotation) ++argNum; break; } } } qDebug("Method call: found current call: %s(%i)", call.method->name.get().toStdString().c_str(), argNum); showMethodCall(call, argNum); return; } hideMethodCall(); } void AutoCompleter::pushMethodCall(const MethodCall& call) { qDebug("Method Call: pushing on stack."); Q_ASSERT(mMethodCall.stack.isEmpty() || mMethodCall.stack.last().position < call.position); mMethodCall.stack.push(call); } void AutoCompleter::showMethodCall(const MethodCall& call, int arg) { if (mMethodCall.widget.isNull()) mMethodCall.widget = new MethodCallWidget(mEditor); MethodCallWidget* w = mMethodCall.widget; w->showMethod(call, arg, globalCursorRect(call.position).adjusted(0, -7, 0, 5)); } void AutoCompleter::hideMethodCall() { delete mMethodCall.widget; } bool AutoCompleter::trySwitchMethodCallArgument(bool backwards) { // FIXME: Only cycle through argument names that have not been entered already using namespace ScLanguage; QTextCursor cursor(mEditor->textCursor()); if (cursor.hasSelection()) return false; if (mMethodCall.stack.isEmpty()) { qDebug("Insert arg name: empty stack"); return false; } MethodCall& call = mMethodCall.stack.top(); if (!call.method || !call.method->arguments.count()) { qDebug("Insert arg name: no method, or method has no args"); return false; } int cursorPos = cursor.position(); int argNum = -1; TokenIterator argNameToken; static const bool strict = true; bool callValid = testMethodCall(call, cursorPos, argNum, argNameToken, strict); if (!callValid) { qDebug("Insert arg name: call invalid"); return false; } bool cursorAtArgName = argNum == -1; if (argNameToken.isValid()) { qDebug("Insert arg name: have a reference arg name"); QString argName = tokenText(argNameToken); argName.chop(1); for (int idx = 0; idx < call.method->arguments.count(); ++idx) { if (call.method->arguments[idx].name == argName) { argNum = idx; break; } } // only increment/decrement if a reference name exists if (backwards) --argNum; else ++argNum; } // limit / wrap if (argNum < 0) argNum = call.method->arguments.count() - 1; else if (argNum >= call.method->arguments.count()) argNum = 0; QString text = call.method->arguments[argNum].name; text.append(": "); // insert argument name if (argNameToken.isValid() && cursorAtArgName) { int pos = argNameToken.position(); cursor.setPosition(pos); cursor.setPosition(pos + argNameToken->length + 1, QTextCursor::KeepAnchor); } cursor.insertText(text); return true; } bool AutoCompleter::testMethodCall(const MethodCall& call, int cursorPos, int& outArgNum, TokenIterator& outArgNameToken, bool strict) { // The 'strict' argument denotes whether the test passes if token before cursor is // not a comma or an argument name - i.e. the user is typing the value of an argument if (call.position >= cursorPos) { qDebug("Method call: call right of cursor."); return false; } QTextBlock block(document()->findBlock(call.position)); TokenIterator token = TokenIterator::rightOf(block, call.position - block.position()); if (!token.isValid()) qWarning("Method call: call stack out of sync!"); Q_ASSERT(token.isValid()); int argNum = 0; int level = 1; TokenIterator argNameToken; bool strictlyValid = true; ++token; while (level > 0 && token.isValid() && token.position() < cursorPos) { strictlyValid = false; char chr = token.character(); Token::Type type = token->type; if (level == 1) { if (type == Token::SymbolArg) { argNameToken = token; argNum = -1; // denote argument name strictlyValid = true; } else if (chr == ',') { if (argNum >= 0) ++argNum; else argNum = -2; // denote comma after argument name strictlyValid = true; } } if (type == Token::OpeningBracket) ++level; else if (type == Token::ClosingBracket) --level; ++token; } if (level <= 0) { qDebug("Method call: call left of cursor."); return false; } outArgNameToken = argNameToken; outArgNum = argNum; return (strictlyValid || !strict); } void AutoCompleter::clearMethodCallStack() { mMethodCall.stack.clear(); hideMethodCall(); } void AutoCompleter::hideWidgets() { if (mCompletion.menu) mCompletion.menu->reject(); if (mMethodCall.menu) mMethodCall.menu->reject(); if (mMethodCall.widget) mMethodCall.widget->hide(); } QString AutoCompleter::tokenText(TokenIterator& it) { if (!it.isValid()) return QString(); int pos = it.position(); QTextCursor cursor(document()); cursor.setPosition(pos); cursor.setPosition(pos + it->length, QTextCursor::KeepAnchor); return cursor.selectedText(); } QRect AutoCompleter::globalCursorRect(int cursorPosition) { QTextCursor cursor(document()); cursor.setPosition(cursorPosition); QRect r = mEditor->cursorRect(cursor); r.moveTopLeft(mEditor->viewport()->mapToGlobal(r.topLeft())); return r; } QString AutoCompleter::findHelpClass(QString klass) { QString file = standardDirectory(ScResourceDir).append("/HelpSource/Classes/").append(klass).append(".schelp"); if (QFile::exists(file)) return file; return QString(); } DocNode* AutoCompleter::parseHelpClass(QString file) { if (file.isEmpty()) return NULL; // note, toStdString() converts to UTF-8 return scdoc_parse_file(file.toStdString(), 0); } QString AutoCompleter::parseClassElement(DocNode* node, QString element) { if (QString(node->id) == element) { QString str; parseClassNode(node, &str); return str; } for (int i = 0; i < node->n_childs; i++) { QString ret = parseClassElement(node->children[i], element); if (!ret.isEmpty()) return ret; } return QString(); } void AutoCompleter::parseClassNode(DocNode* node, QString* str) { QString id = node->id; if (id == "NOTE") str->append("<br><br>Note:<br>"); if (node->text) { if (id == "LINK") { QStringList locations = QString(node->text).split('/').last().split('#'); /* if empty, the link is on the same page. No HTML link */ if (locations.first().isEmpty()) str->append(QStringLiteral(" %1 ").arg(locations.first())); else str->append(QStringLiteral("<a href=\"%1\">%2</a>").arg(locations.first()).arg(locations.last())); } else if (id == "CODE") { str->append(QStringLiteral("<code>%1</code>").arg(node->text)); } else if (id == "CODEBLOCK") { str->append(QStringLiteral("<pre><code>%1</code></pre>").arg(node->text)); } else { str->append(node->text); } } for (int i = 0; i < node->n_childs; i++) parseClassNode(node->children[i], str); } void AutoCompleter::gotoHelp(QString symbol) { #ifdef SC_USE_QTWEBENGINE HelpBrowserDocklet* helpDock = MainWindow::instance()->helpBrowserDocklet(); helpDock->browser()->gotoHelpFor(symbol); helpDock->focus(); #endif // SC_USE_QTWEBENGINE } } // namespace ScIDE #undef QT_NO_DEBUG_OUTPUT
39,241
C++
.cpp
979
31.813075
119
0.623925
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
30,040
line_indicator.cpp
supercollider_supercollider/editors/sc-ide/widgets/code_editor/line_indicator.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "editor.hpp" #include "line_indicator.hpp" using namespace ScIDE; LineIndicator::LineIndicator(GenericCodeEditor* editor): QWidget(editor), mEditor(editor) { setLineCount(1); } void LineIndicator::setLineCount(int count) { mLineCount = count; setFixedWidth(widthForLineCount(count)); Q_EMIT(widthChanged()); } void LineIndicator::changeEvent(QEvent* e) { if (e->type() == QEvent::FontChange) { setFixedWidth(widthForLineCount(mLineCount)); Q_EMIT(widthChanged()); } else QWidget::changeEvent(e); } void LineIndicator::paintEvent(QPaintEvent* e) { mEditor->paintLineIndicator(e); } void LineIndicator::mousePressEvent(QMouseEvent* e) { QTextCursor cursor = mEditor->cursorForPosition(QPoint(0, e->pos().y())); if (cursor.isNull()) { mLastCursorPos = -1; return; } mEditor->setTextCursor(cursor); mLastCursorPos = cursor.position(); } void LineIndicator::mouseMoveEvent(QMouseEvent* e) { QTextCursor cursor = mEditor->cursorForPosition(QPoint(0, e->pos().y())); if (cursor.isNull() || cursor.position() == mLastCursorPos) return; QTextCursor origCursor = mEditor->textCursor(); origCursor.setPosition(cursor.position(), QTextCursor::KeepAnchor); mEditor->setTextCursor(origCursor); mLastCursorPos = cursor.position(); // The selectionChanged() signal of the editor does not always fire here! // Qt bug? update(); } void LineIndicator::mouseDoubleClickEvent(QMouseEvent* e) { QTextCursor cursor = mEditor->cursorForPosition(QPoint(0, e->pos().y())); cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); mEditor->setTextCursor(cursor); } int LineIndicator::widthForLineCount(int lineCount) { int digits = 2; if (hideLineIndicator) return 0; while (lineCount >= 100) { lineCount /= 10; ++digits; } #if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)) return 6 + fontMetrics().horizontalAdvance('9') * digits; #else return 6 + fontMetrics().width('9') * digits; #endif } void LineIndicator::setHideLineIndicator(bool hide) { hideLineIndicator = hide; }
3,003
C++
.cpp
74
36.108108
110
0.721154
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,041
editor.cpp
supercollider_supercollider/editors/sc-ide/widgets/code_editor/editor.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "editor.hpp" #include "line_indicator.hpp" #include "overlay.hpp" #include "../util/gui_utilities.hpp" #include "../../core/main.hpp" #include "../../core/doc_manager.hpp" #include "../../core/settings/manager.hpp" #include "../../core/settings/theme.hpp" #include "../main_window.hpp" #include <QApplication> #include <QDebug> #include <QGraphicsView> #include <QKeyEvent> #include <QPainter> #include <QPaintEvent> #include <QTextBlock> #include <QTextDocumentFragment> #include <QUrl> #include <QMimeData> #include <QScrollBar> #ifdef Q_WS_X11 # include <QX11Info> # include <X11/Xlib.h> // X11 defines the following, clashing with QEvent::Type enum # undef KeyPress # undef KeyRelease #endif namespace ScIDE { GenericCodeEditor::GenericCodeEditor(Document* doc, QWidget* parent): QPlainTextEdit(parent), mDoc(doc), mEditorBoxIsActive(false), mLastCursorBlock(-1) { Q_ASSERT(mDoc != 0); setFrameShape(QFrame::NoFrame); mLineIndicator = new LineIndicator(this); mLineIndicator->move(contentsRect().topLeft()); mOverlay = new QGraphicsScene(this); QPalette overlayPalette; overlayPalette.setBrush(QPalette::Base, Qt::NoBrush); QGraphicsView* overlayView = new QGraphicsView(mOverlay, this); overlayView->setFrameShape(QFrame::NoFrame); overlayView->setPalette(overlayPalette); overlayView->setFocusPolicy(Qt::NoFocus); overlayView->setAttribute(Qt::WA_TransparentForMouseEvents, true); overlayView->setSceneRect(QRectF(0, 0, 1, 1)); overlayView->setAlignment(Qt::AlignLeft | Qt::AlignTop); mOverlayWidget = overlayView; mOverlayAnimator = new OverlayAnimator(this, mOverlay); connect(mDoc, SIGNAL(defaultFontChanged()), this, SLOT(onDocumentFontChanged())); connect(this, SIGNAL(blockCountChanged(int)), mLineIndicator, SLOT(setLineCount(int))); connect(mLineIndicator, SIGNAL(widthChanged()), this, SLOT(updateLayout())); connect(this, SIGNAL(updateRequest(QRect, int)), this, SLOT(updateLineIndicator(QRect, int))); connect(this, SIGNAL(selectionChanged()), mLineIndicator, SLOT(update())); connect(this, SIGNAL(selectionChanged()), this, SLOT(updateDocLastSelection())); connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(onCursorPositionChanged())); connect(Main::instance(), SIGNAL(applySettingsRequest(Settings::Manager*)), this, SLOT(applySettings(Settings::Manager*))); QTextDocument* tdoc = doc->textDocument(); QPlainTextEdit::setDocument(tdoc); onDocumentFontChanged(); doc->setLastActiveEditor(this); applySettings(Main::settings()); } GenericCodeEditor::~GenericCodeEditor() { // Prevent a dangling pointer. if (mDoc->lastActiveEditor() == this) { mDoc->setLastActiveEditor(nullptr); } } void GenericCodeEditor::applySettings(Settings::Manager* settings) { settings->beginGroup("IDE/editor"); bool lineWrap = settings->value("lineWrap").toBool(); bool showWhitespace = settings->value("showWhitespace").toBool(); bool showLinenumber = settings->value("showLinenumber").toBool(); mInactiveFadeAlpha = settings->value("inactiveEditorFadeAlpha").toInt(); QPalette palette; const QTextCharFormat* format = &settings->getThemeVal("text"); QBrush bg = format->background(); QBrush fg = format->foreground(); if (bg.style() != Qt::NoBrush) palette.setBrush(QPalette::Base, bg); if (fg.style() != Qt::NoBrush) palette.setBrush(QPalette::Text, fg); // NOTE: the line number widget will inherit the palette from the editor format = &settings->getThemeVal("lineNumbers"); mLineIndicator->setFont(format->font()); bg = format->background(); fg = format->foreground(); palette.setBrush(QPalette::Mid, bg.style() != Qt::NoBrush ? bg : palette.base()); palette.setBrush(QPalette::ButtonText, fg.style() != Qt::NoBrush ? fg : palette.base()); format = &settings->getThemeVal("selection"); bg = format->background(); fg = format->foreground(); if (bg.style() != Qt::NoBrush) palette.setBrush(QPalette::Highlight, bg); if (fg.style() != Qt::NoBrush) palette.setBrush(QPalette::HighlightedText, fg); mCurrentLineTextFormat = settings->getThemeVal("currentLine"); mSearchResultTextFormat = settings->getThemeVal("searchResult"); mHighlightCurrentLine = settings->value("highlightCurrentLine").toBool(); updateCurrentLineHighlighting(); settings->endGroup(); // IDE/editor setLineWrapMode(lineWrap ? QPlainTextEdit::WidgetWidth : QPlainTextEdit::NoWrap); setShowWhitespace(showWhitespace); setShowLinenumber(showLinenumber); mLineIndicator->setLineCount(blockCount()); setPalette(palette); setActiveAppearance(hasFocus()); } bool GenericCodeEditor::showWhitespace() { QTextOption options(textDocument()->defaultTextOption()); return options.flags().testFlag(QTextOption::ShowTabsAndSpaces); } void GenericCodeEditor::setShowWhitespace(bool show) { QTextDocument* doc = textDocument(); QTextOption opt(doc->defaultTextOption()); if (show) opt.setFlags(opt.flags() | QTextOption::ShowTabsAndSpaces); else opt.setFlags(opt.flags() & ~QTextOption::ShowTabsAndSpaces); doc->setDefaultTextOption(opt); } void GenericCodeEditor::setShowLinenumber(bool show) { mLineIndicator->setHideLineIndicator(!show); } static bool findInBlock(QTextDocument* doc, const QTextBlock& block, const QRegularExpression& expr, int offset, QTextDocument::FindFlags options, QTextCursor& cursor, QRegularExpressionMatch* match) { QString text = block.text(); if (options & QTextDocument::FindBackward) text.truncate(offset); text.replace(QChar::Nbsp, QLatin1Char(' ')); qsizetype idx = -1; while (offset >= 0 && offset <= text.length()) { idx = (options & QTextDocument::FindBackward) ? text.lastIndexOf(expr, offset, match) : text.indexOf(expr, offset, match); if (idx == -1) return false; if (options & QTextDocument::FindWholeWords) { const qsizetype start = idx; const qsizetype end = start + match->capturedLength(0); if ((start != 0 && text.at(start - 1).isLetterOrNumber()) || (end != text.length() && text.at(end).isLetterOrNumber())) { // if this is not a whole word, continue the search in the string offset = (options & QTextDocument::FindBackward) ? idx - 1 : end + 1; idx = -1; continue; } } // we have a hit, return the cursor for that. break; } if (idx == -1) return false; cursor = QTextCursor(doc); cursor.setPosition(block.position() + idx); cursor.setPosition(cursor.position() + match->capturedLength(0), QTextCursor::KeepAnchor); return true; } static bool findInBlock(QTextDocument* doc, const QTextBlock& block, const QRegularExpression& expr, int offset, QTextDocument::FindFlags options, QTextCursor& cursor) { QRegularExpressionMatch match; return findInBlock(doc, block, expr, offset, options, cursor, &match); } bool GenericCodeEditor::find(const QRegularExpression& expr, QTextDocument::FindFlags options) { // Although QTextDocument provides a find() method, we implement // our own, because the former one is not adequate. if (expr.pattern().isEmpty()) return true; bool backwards = options & QTextDocument::FindBackward; QTextCursor c(textCursor()); int pos; if (c.hasSelection()) { bool matching = expr.match(c.selectedText()).hasMatch(); if (backwards == matching) pos = c.selectionStart(); else pos = c.selectionEnd(); } else pos = c.position(); QTextDocument* doc = QPlainTextEdit::document(); QTextBlock startBlock = doc->findBlock(pos); int startBlockOffset = pos - startBlock.position(); QTextCursor cursor; if (!backwards) { int blockOffset = startBlockOffset; QTextBlock block = startBlock; while (block.isValid()) { if (findInBlock(doc, block, expr, blockOffset, options, cursor)) break; blockOffset = 0; block = block.next(); } if (cursor.isNull()) { blockOffset = 0; block = doc->begin(); while (true) { if (findInBlock(doc, block, expr, blockOffset, options, cursor) || block == startBlock) break; block = block.next(); } } } else { int blockOffset = startBlockOffset; QTextBlock block = startBlock; while (block.isValid()) { if (findInBlock(doc, block, expr, blockOffset, options, cursor)) break; block = block.previous(); blockOffset = block.length() - 1; } if (cursor.isNull()) { block = doc->end(); while (true) { blockOffset = block.length() - 1; if (findInBlock(doc, block, expr, blockOffset, options, cursor) || block == startBlock) break; block = block.previous(); } } } if (!cursor.isNull()) { setTextCursor(cursor); return true; } else return false; } int GenericCodeEditor::findAll(const QRegularExpression& expr, QTextDocument::FindFlags options) { mSearchSelections.clear(); if (expr.pattern().isEmpty()) { this->updateExtraSelections(); return 0; } QTextEdit::ExtraSelection selection; selection.format = mSearchResultTextFormat; QTextDocument* doc = QPlainTextEdit::document(); QTextBlock block = doc->begin(); QTextCursor cursor; while (block.isValid()) { int blockPos = block.position(); int offset = 0; while (findInBlock(doc, block, expr, offset, options, cursor)) { offset = cursor.selectionEnd() - blockPos; if (cursor.hasSelection()) { selection.cursor = cursor; mSearchSelections.append(selection); } else offset += 1; } block = block.next(); } this->updateExtraSelections(); return mSearchSelections.count(); } // #define CSTR(QSTR) QSTR.toStdString().c_str() static QString replace_backreferences_with_capturing_groups(const QString& replacement, const QRegularExpressionMatch& match) { // qDebug("START"); static const QRegularExpression rexpr("(\\\\\\\\)|(\\\\[0-9]+)"); QString str(replacement); qsizetype i = 0; while (i < str.size()) { QRegularExpressionMatch backref_match = rexpr.match(str, i); if (!backref_match.hasMatch()) break; i = backref_match.capturedStart(0); qsizetype len = backref_match.capturedLength(0); if (backref_match.capturedStart(1) != -1) { // qDebug("%lli (%s): escape", i, CSTR(backref_match.captured(1))); str.replace(i, len, "\\"); i += 1; } else if (backref_match.capturedStart(2) != -1) { QString num_str = backref_match.captured(2); num_str.remove(0, 1); int num = num_str.toInt(); // qDebug("%lli (%s): backref = %i", i, CSTR(backref_match.captured(2)), num); if (num <= match.lastCapturedIndex()) { QString cap = match.captured(num); // qDebug("resolving ref to: %s", CSTR(cap)); str.replace(i, len, cap); i += cap.size(); } else { // qDebug("%lli ref out of range: backref = %i", i, num); str.remove(i, len); } } else { // qDebug("%lli (%s): unknown match", i, CSTR(backref_match.captured(0))); str.remove(i, len); } // qDebug(">> [%s] %lli", CSTR(str), i); } // qDebug("END"); return str; } bool GenericCodeEditor::replace(const QRegularExpression& expr, const QString& replacement, QTextDocument::FindFlags options) { if (expr.pattern().isEmpty()) return true; QTextCursor cursor = textCursor(); bool captures = (expr.patternOptions() & QRegularExpression::PatternOption::DontCaptureOption) == 0; if (cursor.hasSelection()) { QRegularExpressionMatch match = expr.match(cursor.selectedText()); if (match.hasMatch()) { QString rstr = replacement; if (captures) { rstr = replace_backreferences_with_capturing_groups(rstr, match); } cursor.insertText(rstr); } } return find(expr, options); } int GenericCodeEditor::replaceAll(const QRegularExpression& expr, const QString& replacement, QTextDocument::FindFlags options) { mSearchSelections.clear(); updateExtraSelections(); if (expr.pattern().isEmpty()) return 0; int replacements = 0; bool captures = (expr.patternOptions() & QRegularExpression::PatternOption::DontCaptureOption) == 0; QTextDocument* doc = QPlainTextEdit::document(); QTextBlock block = doc->begin(); QTextCursor cursor; QRegularExpressionMatch match; QTextCursor(doc).beginEditBlock(); while (block.isValid()) { int blockPos = block.position(); int offset = 0; while (findInBlock(doc, block, expr, offset, options, cursor, &match)) { QString rstr = replacement; if (captures) rstr = replace_backreferences_with_capturing_groups(rstr, match); cursor.insertText(rstr); ++replacements; offset = cursor.selectionEnd() - blockPos; } block = block.next(); } QTextCursor(doc).endEditBlock(); return replacements; } void GenericCodeEditor::showPosition(int pos, int selectionLength) { if (pos < 0) return; QTextDocument* doc = QPlainTextEdit::document(); if (!doc) return; int lineNumber = doc->findBlock(pos).firstLineNumber(); verticalScrollBar()->setValue(lineNumber); QTextCursor cursor(doc); cursor.setPosition(pos); if (selectionLength) cursor.setPosition(pos + selectionLength, QTextCursor::KeepAnchor); setTextCursor(cursor); } QString GenericCodeEditor::symbolUnderCursor() { const QTextCursor cursor = textCursor(); if (cursor.hasSelection()) return cursor.selectedText(); const QString blockString = cursor.block().text(); const int position = cursor.positionInBlock(); return tokenInStringAt(position, blockString); } bool GenericCodeEditor::event(QEvent* event) { switch (event->type()) { case QEvent::ShortcutOverride: { // Prevent overriding certain shortcuts, // as they are useful in our application. QKeyEvent* kevent = static_cast<QKeyEvent*>(event); switch (kevent->key()) { case Qt::Key_Return: case Qt::Key_Enter: event->ignore(); return true; } break; } default: break; } return QPlainTextEdit::event(event); } void GenericCodeEditor::keyPressEvent(QKeyEvent* event) { hideMouseCursor(event); QTextCursor cursor(textCursor()); bool updateCursor = false; if (event == QKeySequence::InsertLineSeparator) { // override to avoid entering a "soft" new line cursor.insertBlock(); updateCursor = true; } else { switch (event->key()) { case Qt::Key_BraceRight: case Qt::Key_BracketRight: case Qt::Key_ParenRight: handleKeyRightParentheses(event, cursor); break; case Qt::Key_Delete: handleKeyDelete(event, cursor); break; case Qt::Key_Backspace: handleKeyBackspace(event, cursor, updateCursor); break; case Qt::Key_Down: handleKeyDown(event, cursor); break; case Qt::Key_Up: handleKeyUp(event, cursor); break; default: QPlainTextEdit::keyPressEvent(event); } } if (updateCursor) { cursor.setVerticalMovementX(-1); setTextCursor(cursor); ensureCursorVisible(); } if (mDoc->keyDownActionEnabled() || Main::documentManager()->globalKeyDownActionEnabled()) doKeyAction(event); } void GenericCodeEditor::handleKeyDown(QKeyEvent* event, QTextCursor& textCursor) { if (textCursor.block() == textDocument()->lastBlock()) { QTextCursor::MoveMode moveMode = event->modifiers() & Qt::SHIFT ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor; textCursor.movePosition(QTextCursor::EndOfBlock, moveMode); setTextCursor(textCursor); } else QPlainTextEdit::keyPressEvent(event); } void GenericCodeEditor::handleKeyUp(QKeyEvent* event, QTextCursor& textCursor) { if (textCursor.block() == textDocument()->firstBlock()) { QTextCursor::MoveMode moveMode = event->modifiers() & Qt::SHIFT ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor; textCursor.movePosition(QTextCursor::StartOfBlock, moveMode); setTextCursor(textCursor); } else QPlainTextEdit::keyPressEvent(event); } void GenericCodeEditor::handleKeyDelete(QKeyEvent* event, QTextCursor& textCursor) { if (event->modifiers() & Qt::META) { textCursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); textCursor.removeSelectedText(); } else QPlainTextEdit::keyPressEvent(event); } void GenericCodeEditor::handleKeyBackspace(QKeyEvent* event, QTextCursor& textCursor, bool& updateCursor) { if (event->modifiers() & Qt::META) { textCursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor); textCursor.removeSelectedText(); } else { if (!overwriteMode() || (textCursor.positionInBlock() == 0) || textCursor.hasSelection()) { QPlainTextEdit::keyPressEvent(event); } else { // in overwrite mode, backspace should insert a space textCursor.beginEditBlock(); textCursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor); QString selectedText = textCursor.selectedText(); if (selectedText == QStringLiteral(" ") || selectedText == QStringLiteral("\t")) { textCursor.clearSelection(); } else { textCursor.insertText(QString(QChar(' '))); textCursor.movePosition(QTextCursor::PreviousCharacter); } textCursor.endEditBlock(); } updateCursor = true; } } void GenericCodeEditor::handleKeyRightParentheses(QKeyEvent* event, QTextCursor& textCursor) { if (!textCursor.atBlockEnd()) { QTextCursor nextCharCursor(textCursor); nextCharCursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); if (nextCharCursor.selectedText() == event->text()) { // don't insert, just move moveCursor(QTextCursor::NextCharacter); return; } } QPlainTextEdit::keyPressEvent(event); } void GenericCodeEditor::keyReleaseEvent(QKeyEvent* e) { if (mDoc->keyUpActionEnabled() || Main::documentManager()->globalKeyUpActionEnabled()) doKeyAction(e); } void GenericCodeEditor::doKeyAction(QKeyEvent* ke) { int key = ke->key(); int mods = ke->modifiers(); QChar character; #ifdef Q_OS_MAC bool isLetter = key >= Qt::Key_A && key <= Qt::Key_Z; if (mods & Qt::MetaModifier && isLetter) { character = QChar(key - Qt::Key_A + 1); } else if (mods & Qt::AltModifier && isLetter) { character = (mods & Qt::ShiftModifier) ? QChar(key) : QChar(key - Qt::Key_A + 97); } else #endif { QString text(ke->text()); if (text.count()) { character = text[0]; } else { character = QChar(QChar::ReplacementCharacter); } } int unicode = character.unicode(); #ifdef Q_WS_X11 KeySym sym = ke->nativeVirtualKey(); int keycode = XKeysymToKeycode(QX11Info::display(), sym); #else // FIXME: On Mac OS X, this does not work for modifier keys int keycode = ke->nativeVirtualKey(); #endif QString type; if (ke->type() == QEvent::KeyPress) { type = QStringLiteral("keyDown"); } else { type = QStringLiteral("keyUp"); } Main::evaluateCodeIfCompiled(QStringLiteral("Document.findByQUuid(\'%1\').%2(%3, %4, %5, %6)") .arg(mDoc->id().constData()) .arg(type) .arg(mods) .arg(unicode) .arg(keycode) .arg(key), true); } void GenericCodeEditor::mousePressEvent(QMouseEvent* e) { if (mDoc->mouseDownActionEnabled()) { int button; switch (e->button()) { case Qt::LeftButton: button = 0; break; case Qt::RightButton: button = 1; break; case Qt::MiddleButton: button = 2; break; default: button = -1; } Main::evaluateCodeIfCompiled(QStringLiteral("Document.findByQUuid(\'%1\').mouseDown(%2, %3, %4, %5, 1)") .arg(mDoc->id().constData()) #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) .arg(e->x()) .arg(e->y()) #else .arg(e->position().x()) .arg(e->position().y()) #endif .arg(e->modifiers()) .arg(button), true); } QPlainTextEdit::mousePressEvent(e); } void GenericCodeEditor::mouseDoubleClickEvent(QMouseEvent* e) { if (mDoc->mouseDownActionEnabled()) { int button; switch (e->button()) { case Qt::LeftButton: button = 0; break; case Qt::RightButton: button = 1; break; case Qt::MiddleButton: button = 2; break; default: button = -1; } Main::evaluateCodeIfCompiled(QStringLiteral("Document.findByQUuid(\'%1\').mouseDown(%2, %3, %4, %5, 2)") .arg(mDoc->id().constData()) #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) .arg(e->x()) .arg(e->y()) #else .arg(e->position().x()) .arg(e->position().y()) #endif .arg(e->modifiers()) .arg(button), true); } QPlainTextEdit::mouseDoubleClickEvent(e); } void GenericCodeEditor::mouseReleaseEvent(QMouseEvent* e) { if (mDoc->mouseUpActionEnabled()) { int button; switch (e->button()) { case Qt::LeftButton: button = 0; break; case Qt::RightButton: button = 1; break; case Qt::MiddleButton: button = 2; break; default: button = -1; } Main::evaluateCodeIfCompiled(QStringLiteral("Document.findByQUuid(\'%1\').mouseUp(%2, %3, %4, %5)") .arg(mDoc->id().constData()) #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) .arg(e->x()) .arg(e->y()) #else .arg(e->position().x()) .arg(e->position().y()) #endif .arg(e->modifiers()) .arg(button), true); } QPlainTextEdit::mouseReleaseEvent(e); } void GenericCodeEditor::wheelEvent(QWheelEvent* e) { // FIXME: Disable zooming for now, to avoid nasty effect when Ctrl // is unintentionally pressed while inertial scrolling is going on. // Moreover, Ctrl|Shift + Wheel scrolls by pages, which is also // rather annoying. // So rather just forward the event without modifiers. e->setModifiers(Qt::NoModifier); QPlainTextEdit::wheelEvent(e); return; #if 0 if (e->modifiers() == Qt::ControlModifier) { if (e->delta() > 0) zoomIn(); else zoomOut(); return; } QPlainTextEdit::wheelEvent(e); #endif } void GenericCodeEditor::updateFocusRect() { if (mFocusRect) { QRect viewportRect = viewport()->rect(); QRect focusRect = QRect(viewportRect.bottomLeft() + QPoint(0, -2), viewportRect.bottomRight()); mFocusRect->setRect(focusRect); } } void GenericCodeEditor::focusInEvent(QFocusEvent* e) { if (mFocusRect) { updateFocusRect(); mFocusRect->setVisible(true); } else { QColor rectColor = palette().color(QPalette::Text); rectColor.setAlpha(40); mFocusRect = mOverlay->addRect(QRect(0, 0, 0, 0), Qt::NoPen, rectColor); updateFocusRect(); } QPlainTextEdit::focusInEvent(e); } void GenericCodeEditor::focusOutEvent(QFocusEvent* e) { if (mFocusRect) { mFocusRect->setVisible(false); } QPlainTextEdit::focusOutEvent(e); } void GenericCodeEditor::dragEnterEvent(QDragEnterEvent* event) { const QMimeData* data = event->mimeData(); if (data->hasUrls()) { // Propagate event to parent. // URL drops are ultimately handled by MainWindow. event->ignore(); return; } QPlainTextEdit::dragEnterEvent(event); } void GenericCodeEditor::hideMouseCursor(QKeyEvent* event) { switch (event->key()) { case Qt::Key_Shift: case Qt::Key_Control: case Qt::Key_Meta: case Qt::Key_Alt: case Qt::Key_Super_L: case Qt::Key_Super_R: case Qt::Key_Hyper_L: case Qt::Key_Hyper_R: case Qt::Key_Menu: return; default: hideMouseCursor(); } } void GenericCodeEditor::closeDocument() { MainWindow::instance()->closeDocument(); } void GenericCodeEditor::clearSearchHighlighting() { mSearchSelections.clear(); this->updateExtraSelections(); } void GenericCodeEditor::zoomIn(int steps) { zoomFont(steps); } void GenericCodeEditor::zoomOut(int steps) { zoomFont(-steps); } void GenericCodeEditor::resetFontSize() { mDoc->resetDefaultFont(); } void GenericCodeEditor::zoomFont(int steps) { QFont currentFont = mDoc->defaultFont(); const int newSize = currentFont.pointSize() + steps; if (newSize <= 0) return; currentFont.setPointSize(newSize); mDoc->setDefaultFont(currentFont); } void GenericCodeEditor::onDocumentFontChanged() { QFont font = mDoc->defaultFont(); setFont(font); } void GenericCodeEditor::updateLayout() { setViewportMargins(mLineIndicator->width(), 0, 0, 0); mOverlayWidget->setGeometry(viewport()->geometry()); } void GenericCodeEditor::updateLineIndicator(QRect r, int dy) { if (dy) mLineIndicator->scroll(0, dy); else mLineIndicator->update(0, r.y(), mLineIndicator->width(), r.height()); } void GenericCodeEditor::onCursorPositionChanged() { if (mHighlightCurrentLine) updateCurrentLineHighlighting(); mLastCursorBlock = textCursor().blockNumber(); updateDocLastSelection(); } void GenericCodeEditor::updateDocLastSelection() { QTextCursor cursor = textCursor(); int start = cursor.selectionStart(); int range = cursor.selectionEnd() - start; Main::scProcess()->updateSelectionMirrorForDocument(mDoc, start, range); } void GenericCodeEditor::updateCurrentLineHighlighting() { int currentCursorBlock = textCursor().blockNumber(); int first_block_num = qMin(mLastCursorBlock, currentCursorBlock); int second_block_num = qMax(mLastCursorBlock, currentCursorBlock); QRegion region(0, 0, 0, 0); QTextBlock block = firstVisibleBlock(); int block_num = block.blockNumber(); qreal top = blockBoundingGeometry(block).translated(contentOffset()).top(); qreal max_top = viewport()->rect().bottom(); while (block.isValid() && block_num <= second_block_num && top <= max_top) { QRectF block_rect = blockBoundingRect(block); if (block_num == first_block_num || block_num == second_block_num) { region += block_rect.translated(0, top).toRect(); } top += block_rect.height(); block = block.next(); ++block_num; } viewport()->update(region); } void GenericCodeEditor::updateExtraSelections() { QList<QTextEdit::ExtraSelection> selections; selections.append(mSearchSelections); setExtraSelections(selections); } void GenericCodeEditor::resizeEvent(QResizeEvent* e) { QPlainTextEdit::resizeEvent(e); if (hasFocus()) { updateFocusRect(); } QRect cr = contentsRect(); mLineIndicator->resize(mLineIndicator->width(), cr.height()); mOverlayWidget->setGeometry(viewport()->geometry()); } void GenericCodeEditor::paintLineIndicator(QPaintEvent* e) { QPalette plt(mLineIndicator->palette()); QRect r(e->rect()); QPainter p(mLineIndicator); p.fillRect(r, plt.color(QPalette::Mid)); QTextDocument* doc = QPlainTextEdit::document(); QTextCursor cursor(textCursor()); int selStartBlock, selEndBlock; if (cursor.hasSelection()) { selStartBlock = doc->findBlock(cursor.selectionStart()).blockNumber(); selEndBlock = doc->findBlock(cursor.selectionEnd()).blockNumber(); } else selStartBlock = selEndBlock = -1; QTextBlock block = firstVisibleBlock(); int blockNumber = block.blockNumber(); qreal top = blockBoundingGeometry(block).translated(contentOffset()).top(); qreal bottom = top + blockBoundingRect(block).height(); while (block.isValid() && top <= e->rect().bottom()) { if (block.isVisible() && bottom >= e->rect().top()) { p.save(); QRectF numRect(0, top, mLineIndicator->width() - 1, bottom - top); int num = blockNumber; if (num >= selStartBlock && num <= selEndBlock) { num -= selStartBlock; p.setPen(Qt::NoPen); p.setBrush(plt.color(QPalette::Highlight)); p.drawRect(numRect); p.setPen(plt.color(QPalette::HighlightedText)); } QString number = QString::number(num + 1); p.setPen(plt.color(QPalette::ButtonText)); p.drawText(0, top, mLineIndicator->width() - 4, bottom - top, Qt::AlignRight, number); p.restore(); } block = block.next(); top = bottom; bottom = top + blockBoundingRect(block).height(); ++blockNumber; } if (!mEditorBoxIsActive) { QColor color = plt.color(QPalette::Mid); if (color.lightness() >= 128) color = color.darker(60); else color = color.lighter(50); color.setAlpha(inactiveFadeAlpha()); p.fillRect(r, color); } } void GenericCodeEditor::paintEvent(QPaintEvent* event) { if (mHighlightCurrentLine) { int cursor_block_num = textCursor().blockNumber(); QTextBlock block = firstVisibleBlock(); int block_num = block.blockNumber(); qreal top = blockBoundingGeometry(block).translated(contentOffset()).top(); qreal max_top = event->rect().bottom(); while (block.isValid() && block_num <= cursor_block_num && top <= max_top) { QRectF block_rect = blockBoundingRect(block); if (block_num == cursor_block_num) { QPainter painter(viewport()); painter.fillRect(block_rect.translated(0, top), mCurrentLineTextFormat.background().color()); painter.end(); break; } top += block_rect.height(); block = block.next(); ++block_num; } } QPlainTextEdit::paintEvent(event); } void GenericCodeEditor::copyUpDown(bool up) { // directly taken from qtcreator // Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). // GNU Lesser General Public License QTextCursor cursor = textCursor(); QTextCursor move = cursor; move.beginEditBlock(); bool hasSelection = cursor.hasSelection(); if (hasSelection) { move.setPosition(cursor.selectionStart()); move.movePosition(QTextCursor::StartOfBlock); move.setPosition(cursor.selectionEnd(), QTextCursor::KeepAnchor); move.movePosition(move.atBlockStart() ? QTextCursor::Left : QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); } else { move.movePosition(QTextCursor::StartOfBlock); move.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); } QString text = move.selectedText(); if (up) { move.setPosition(cursor.selectionStart()); move.movePosition(QTextCursor::StartOfBlock); move.insertBlock(); move.movePosition(QTextCursor::Left); } else { move.movePosition(QTextCursor::EndOfBlock); if (move.atBlockStart()) { move.movePosition(QTextCursor::NextBlock); move.insertBlock(); move.movePosition(QTextCursor::Left); } else { move.insertBlock(); } } int start = move.position(); move.clearSelection(); move.insertText(text); int end = move.position(); move.setPosition(start); move.setPosition(end, QTextCursor::KeepAnchor); move.endEditBlock(); setTextCursor(move); } void GenericCodeEditor::toggleOverwriteMode() { setOverwriteMode(!overwriteMode()); // FIXME: reset cursor to the same position in to force a repaint // there might be a nicer solution for this issue, though setTextCursor(textCursor()); } void GenericCodeEditor::copyLineDown() { copyUpDown(false); } void GenericCodeEditor::copyLineUp() { copyUpDown(true); } void GenericCodeEditor::moveLineUpDown(bool up) { // directly taken from qtcreator // Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). // GNU Lesser General Public License QTextCursor cursor = textCursor(); QTextCursor move = cursor; move.setVisualNavigation(false); // this opens folded items instead of destroying them move.beginEditBlock(); bool hasSelection = cursor.hasSelection(); if (cursor.hasSelection()) { move.setPosition(cursor.selectionStart()); move.movePosition(QTextCursor::StartOfBlock); move.setPosition(cursor.selectionEnd(), QTextCursor::KeepAnchor); move.movePosition(move.atBlockStart() ? QTextCursor::Left : QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); } else { move.movePosition(QTextCursor::StartOfBlock); move.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); } QString text = move.selectedText(); move.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor); move.removeSelectedText(); if (up) { move.movePosition(QTextCursor::PreviousBlock); move.insertBlock(); move.movePosition(QTextCursor::Left); } else { move.movePosition(QTextCursor::EndOfBlock); if (move.atBlockStart()) { // empty block move.movePosition(QTextCursor::NextBlock); move.insertBlock(); move.movePosition(QTextCursor::Left); } else { move.insertBlock(); } } int start = move.position(); move.clearSelection(); move.insertText(text); int end = move.position(); if (hasSelection) { move.setPosition(start); move.setPosition(end, QTextCursor::KeepAnchor); } move.endEditBlock(); setTextCursor(move); } void GenericCodeEditor::moveLineUp() { moveLineUpDown(true); } void GenericCodeEditor::moveLineDown() { moveLineUpDown(false); } void GenericCodeEditor::deleteWord() { QTextCursor cur = textCursor(); cur.beginEditBlock(); cur.movePosition(QTextCursor::StartOfWord, QTextCursor::KeepAnchor); cur.deletePreviousChar(); cur.endEditBlock(); } void GenericCodeEditor::gotoPreviousEmptyLine() { gotoEmptyLineUpDown(true); } void GenericCodeEditor::gotoNextEmptyLine() { gotoEmptyLineUpDown(false); } void GenericCodeEditor::gotoEmptyLineUpDown(bool up) { static const QRegularExpression whiteSpaceLine("^\\s*$"); const QTextCursor::MoveOperation direction = up ? QTextCursor::PreviousBlock : QTextCursor::NextBlock; QTextCursor cursor = textCursor(); cursor.beginEditBlock(); bool cursorMoved = false; // find first non-whitespace line while (cursor.movePosition(direction)) { if (!whiteSpaceLine.match(cursor.block().text()).hasMatch()) break; } // find first whitespace line while (cursor.movePosition(direction)) { if (whiteSpaceLine.match(cursor.block().text()).hasMatch()) { setTextCursor(cursor); cursorMoved = true; break; } } if (!cursorMoved) { const QTextCursor::MoveOperation startOrEnd = up ? QTextCursor::Start : QTextCursor::End; cursor.movePosition(startOrEnd); setTextCursor(cursor); } cursor.endEditBlock(); } void GenericCodeEditor::hideMouseCursor() { #ifdef Q_OS_MAC return; // LATER: for some reason this crashes on osx. we should try to figure out why #endif QCursor* overrideCursor = QApplication::overrideCursor(); if (!overrideCursor || overrideCursor->shape() != Qt::BlankCursor) QApplication::setOverrideCursor(Qt::BlankCursor); } void GenericCodeEditor::setActiveAppearance(bool active) { if (active) mDoc->setLastActiveEditor(this); mOverlayAnimator->setActiveAppearance(active); mEditorBoxIsActive = active; } QMimeData* GenericCodeEditor::createMimeDataFromSelection() const { // Here, we bundle up just the plaintext (not HTML, as is the default) of // the editor's selected contents. QMimeData* data = new QMimeData; data->setText(textCursor().selection().toPlainText()); return data; } } // namespace ScIDE
39,906
C++
.cpp
1,008
31.345238
118
0.630587
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
30,042
overlay.cpp
supercollider_supercollider/editors/sc-ide/widgets/code_editor/overlay.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "overlay.hpp" #include "editor.hpp" #include "sc_editor.hpp" #include "../../core/main.hpp" #include "../../core/settings/theme.hpp" #include <QTextDocument> #include <QTextLayout> #include <QTextBlock> #include <QPainter> #include <QPropertyAnimation> #include <QtCore/qmath.h> #include <QDebug> namespace ScIDE { OverlayAnimator::OverlayAnimator(GenericCodeEditor* editor, QObject* parent): QObject(parent), mEditor(editor), mBackgroundAnimation(this, "backgroundColor") {} QColor OverlayAnimator::backgroundColor() const { return mEditor->mOverlay->backgroundBrush().color(); } void OverlayAnimator::setBackgroundColor(const QColor& color) { mEditor->mOverlay->setBackgroundBrush(color); } void OverlayAnimator::setActiveAppearance(bool active) { QColor color = mEditor->palette().color(QPalette::Base); if (color.lightness() >= 128) color = color.darker(60); else color = color.lighter(50); if (active) color.setAlpha(0); else color.setAlpha(mEditor->inactiveFadeAlpha()); mBackgroundAnimation.stop(); if (mEditor->isVisible()) { mBackgroundAnimation.setDuration(500); mBackgroundAnimation.setEasingCurve(QEasingCurve::OutCubic); mBackgroundAnimation.setStartValue(backgroundColor()); mBackgroundAnimation.setEndValue(color); mBackgroundAnimation.start(); } else { setBackgroundColor(color); } } void ScCodeEditor::blinkCode(const QTextCursor& c) { if (!c.document() || !c.hasSelection()) return; Settings::Manager* settings = Main::settings(); QTextCharFormat evalCodeTextFormat = settings->getThemeVal("evaluatedCode"); QTextDocument* doc = c.document(); int startPos = c.selectionStart(); int endPos = c.selectionEnd(); QTextBlock startBlock = doc->findBlock(startPos); QTextBlock endBlock = doc->findBlock(endPos); startPos -= startBlock.position(); endPos -= endBlock.position(); // Get the bounds of visible blocks within the cursor's selection: QTextBlock block = firstVisibleBlock(); int idx = block.blockNumber(); int sidx = startBlock.blockNumber(); QTextBlock firstBlock, lastBlock; firstBlock = lastBlock = block; QRectF geom = blockBoundingGeometry(block).translated(contentOffset()); qreal top = geom.top(); qreal bottom = top; qreal width = 0; while (block.isValid() && bottom < viewport()->rect().height()) { if (block.isVisible()) { QTextLayout* l = block.layout(); QRectF r = l->boundingRect(); bottom += r.height(); if (idx < sidx) { // Block not within the selection. Will skip it. top = bottom; } else { // Block within the selection. width = qMax(width, l->maximumWidth() + r.left()); } } if (block == endBlock) break; block = block.next(); ++idx; if (top == bottom) firstBlock = block; } lastBlock = block; if (bottom == top) { // qDebug("no visible block."); return; } // Construct a pixmap to render the code on: QPixmap pix(QSize(qCeil(width), qCeil(bottom - top))); pix.fill(QColor(0, 0, 0, 0)); // Render the visible blocks: QPainter painter(&pix); QVector<QTextLayout::FormatRange> selections; block = firstBlock; int y = 0; while (block.isValid()) { if (block.isVisible()) { QRectF blockRect = block.layout()->boundingRect(); // Use extra char formatting to hide code outside of selection // and modify the appearance of selected code: QTextLayout::FormatRange range; selections.clear(); int start = 0; if (block == startBlock) { range.start = 0; range.length = startPos; range.format.setForeground(QColor(0, 0, 0, 0)); range.format.setBackground(Qt::NoBrush); selections.append(range); start = startPos; } range.start = start; range.length = (block == endBlock ? endPos : block.length() - 1) - range.start; range.format = evalCodeTextFormat; selections.append(range); if (block == endBlock) { range.start = range.start + range.length; range.length = block.length() - 1 - range.start; range.format.setForeground(QColor(0, 0, 0, 0)); range.format.setBackground(Qt::NoBrush); selections.append(range); } block.layout()->draw(&painter, QPointF(0, y), selections); y += blockRect.height(); } if (block == lastBlock) break; block = block.next(); } // Create an overlay item to display the pixmap, and animate it: CodeFragmentOverlay* item = new CodeFragmentOverlay(); item->setPixmap(pix); item->setPos(geom.left(), top); mOverlay->addItem(item); QPropertyAnimation* anim = new QPropertyAnimation(item, "opacity", item); anim->setDuration(mBlinkDuration); anim->setStartValue(1.0); anim->setEndValue(0.0); anim->setEasingCurve(QEasingCurve::InCubic); anim->start(); connect(anim, SIGNAL(finished()), item, SLOT(deleteLater())); } } // namespace ScIDE
6,328
C++
.cpp
159
32.125786
111
0.641574
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,043
sc_editor.cpp
supercollider_supercollider/editors/sc-ide/widgets/code_editor/sc_editor.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "sc_editor.hpp" #include "autocompleter.hpp" #include "line_indicator.hpp" #include "main_window.hpp" #include "../util/gui_utilities.hpp" #include "../../core/main.hpp" #include "../../core/doc_manager.hpp" #include "../../core/settings/manager.hpp" #include "../../core/settings/theme.hpp" #ifdef SC_USE_QTWEBENGINE # include "help_browser.hpp" #endif // SC_USE_QTWEBENGINE #include "QtCollider/hacks/hacks_qt.hpp" #include <QKeyEvent> #include <QStack> #include <QMimeData> #include <QUrl> namespace ScIDE { ScCodeEditor::ScCodeEditor(Document* doc, QWidget* parent): GenericCodeEditor(doc, parent), mSpaceIndent(true), mBlinkDuration(600), mMouseBracketMatch(false), mAutoCompleter(new AutoCompleter(this)) { Q_ASSERT(mDoc != 0); connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(matchBrackets())); connect(Main::instance(), SIGNAL(applySettingsRequest(Settings::Manager*)), this, SLOT(applySettings(Settings::Manager*))); mAutoCompleter->documentChanged(textDocument()); applySettings(Main::settings()); } void ScCodeEditor::applySettings(Settings::Manager* settings) { settings->beginGroup("IDE/editor"); mSpaceIndent = settings->value("spaceIndent").toBool(); mBlinkDuration = settings->value("blinkDuration").toInt(); mBracketHighlight = settings->getThemeVal("matchingBrackets"); mBracketMismatchFormat = settings->getThemeVal("mismatchedBrackets"); mStepForwardEvaluation = settings->value("stepForwardEvaluation").toBool(); mInsertMatchingTokens = settings->value("insertMatchingTokens").toBool(); mHighlightBracketContents = settings->value("highlightBracketContents").toBool(); settings->endGroup(); // update bracket match highlighting: matchBrackets(); } bool ScCodeEditor::event(QEvent* e) { switch (e->type()) { case QEvent::KeyPress: { QKeyEvent* ke = static_cast<QKeyEvent*>(e); switch (ke->key()) { case Qt::Key_Tab: if (!tabChangesFocus()) { indent(); e->accept(); return true; } default: break; } break; } default: break; } return GenericCodeEditor::event(e); } void ScCodeEditor::keyPressEvent(QKeyEvent* e) { hideMouseCursor(e); bool actionInSuper = false; QTextCursor cursor(textCursor()); bool cursorMoved = true; if (e == QKeySequence::MoveToNextWord) moveToNextToken(cursor, QTextCursor::MoveAnchor); else if (e == QKeySequence::MoveToPreviousWord) moveToPreviousToken(cursor, QTextCursor::MoveAnchor); else if (e == QKeySequence::SelectNextWord) moveToNextToken(cursor, QTextCursor::KeepAnchor); else if (e == QKeySequence::SelectPreviousWord) moveToPreviousToken(cursor, QTextCursor::KeepAnchor); else cursorMoved = false; if (cursorMoved) { setTextCursor(cursor); doKeyAction(e); return; } switch (e->key()) { case Qt::Key_Home: { Qt::KeyboardModifiers mods(e->modifiers()); if (mods && mods != Qt::ShiftModifier) { GenericCodeEditor::keyPressEvent(e); return; } QTextCursor::MoveMode mode = mods & Qt::ShiftModifier ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor; QTextCursor c(textCursor()); QTextBlock b(c.block()); int pos = indentedStartOfLine(b); pos += b.position(); if (c.position() == pos) c.movePosition(QTextCursor::StartOfLine, mode); else c.setPosition(pos, mode); setTextCursor(c); doKeyAction(e); return; } case Qt::Key_Backtab: { QTextCursor cursor = textCursor(); insertSpaceToNextTabStop(cursor); ensureCursorVisible(); doKeyAction(e); return; } case Qt::Key_Backspace: if (mInsertMatchingTokens && !overwriteMode() && e->modifiers() == 0) if (removeMatchingTokens()) break; GenericCodeEditor::keyPressEvent(e); actionInSuper = true; break; case Qt::Key_Enter: case Qt::Key_Return: { QTextBlock cursorBlock = cursor.block(); int cursorPosInBlock = cursor.position() - cursorBlock.position(); TokenIterator prevToken = TokenIterator::leftOf(cursorBlock, cursorPosInBlock); TokenIterator nextToken = TokenIterator::rightOf(cursorBlock, cursorPosInBlock); if (nextToken.block() == cursorBlock && nextToken.type() == Token::ClosingBracket && prevToken.type() != Token::ClosingBracket // no double-newline if cursor is between closing brackets, i.e. ]) && !(prevToken.block().firstLineNumber() < nextToken.block().firstLineNumber()) // no double-nl if only whitespace to the left ) { cursor.beginEditBlock(); cursor.insertBlock(); cursor.insertBlock(); cursor.endEditBlock(); cursor.movePosition(QTextCursor::PreviousBlock, QTextCursor::KeepAnchor); indent(cursor, JoinEditBlock); cursor.movePosition(QTextCursor::EndOfBlock); } else { cursor.beginEditBlock(); cursor.insertBlock(); cursor.endEditBlock(); indent(cursor, JoinEditBlock); } cursor.setVerticalMovementX(-1); setTextCursor(cursor); break; } default: if (!overwriteMode() && insertMatchingTokens(e->text())) break; GenericCodeEditor::keyPressEvent(e); actionInSuper = true; } mAutoCompleter->keyPress(e); if (!actionInSuper) doKeyAction(e); } void ScCodeEditor::mouseReleaseEvent(QMouseEvent* e) { // Prevent deselection of bracket match: if (!mMouseBracketMatch) GenericCodeEditor::mouseReleaseEvent(e); mMouseBracketMatch = false; } void ScCodeEditor::mouseDoubleClickEvent(QMouseEvent* e) { // Always pass to superclass so as to handle line selection on triple click GenericCodeEditor::mouseDoubleClickEvent(e); if (e->button() == Qt::LeftButton) { QTextCursor cursor = cursorForPosition(e->pos()); QTextCursor selection = selectionForPosition(cursor.position()); if (!selection.isNull()) { mMouseBracketMatch = true; setTextCursor(selection); return; } } } void ScCodeEditor::mouseMoveEvent(QMouseEvent* e) { // Prevent initiating a text drag: if (!mMouseBracketMatch) GenericCodeEditor::mouseMoveEvent(e); } void ScCodeEditor::dragEnterEvent(QDragEnterEvent* event) { // The purpose is only to bypass GenericCodeEditor::dragEnterEvent: QPlainTextEdit::dragEnterEvent(event); } bool ScCodeEditor::canInsertFromMimeData(const QMimeData* data) const { if (data->hasUrls()) return true; return QPlainTextEdit::canInsertFromMimeData(data); } void ScCodeEditor::insertFromMimeData(const QMimeData* data) { if (data->hasUrls()) { QTextCursor cursor = textCursor(); QList<QUrl> urls = data->urls(); bool multiple = urls.size() > 1; if (multiple) { cursor.insertText("["); cursor.insertBlock(); } for (int i = 0; i < urls.size(); ++i) { QUrl url = urls[i]; cursor.insertText("\""); if (QURL_IS_LOCAL_FILE(url)) cursor.insertText(url.toLocalFile()); else cursor.insertText(url.toString()); cursor.insertText("\""); if (i < urls.size() - 1) { cursor.insertText(","); cursor.insertBlock(); } } if (multiple) { cursor.insertBlock(); cursor.insertText("]"); } } else QPlainTextEdit::insertFromMimeData(data); } void ScCodeEditor::moveToNextToken(QTextCursor& cursor, QTextCursor::MoveMode mode) { if (cursor.atBlockEnd()) { cursor.movePosition(QTextCursor::NextCharacter, mode); return; } QTextBlock block(cursor.block()); QString blockText = block.text(); int positionInBlock = cursor.position() - block.position(); // go to end of token or end of word TokenIterator tokenIt(block, positionInBlock); if (tokenIt.isValid()) positionInBlock = tokenIt->positionInBlock + tokenIt->length; else { int pos = positionInBlock; if (blockText[pos].isLetterOrNumber()) { ++pos; while (pos < blockText.size() && blockText[pos].isLetterOrNumber()) ++pos; } else { ++pos; } positionInBlock = pos; } // skip whitespace while (positionInBlock < blockText.size() && blockText[positionInBlock].isSpace()) ++positionInBlock; cursor.setPosition(positionInBlock + block.position(), mode); } void ScCodeEditor::moveToPreviousToken(QTextCursor& cursor, QTextCursor::MoveMode mode) { if (cursor.atBlockStart()) { cursor.movePosition(QTextCursor::PreviousCharacter, mode); return; } QTextBlock block(cursor.block()); QString blockText = block.text(); int positionInBlock = cursor.position() - block.position() - 1; // skip whitespace while (positionInBlock > 0 && blockText[positionInBlock].isSpace()) --positionInBlock; cursor.setPosition(positionInBlock + block.position(), mode); if (positionInBlock == 0) return; // go to beginning of token or beginning of word TokenIterator tokenIt(block, positionInBlock); if (tokenIt.isValid()) { cursor.setPosition(tokenIt.position(), mode); } else { int pos = positionInBlock; if (blockText[pos].isLetterOrNumber()) { while (pos > 0 && blockText[pos - 1].isLetterOrNumber()) --pos; } cursor.setPosition(pos + block.position(), mode); } } bool ScCodeEditor::insertMatchingTokens(const QString& text) { if (text.isEmpty()) return false; QTextCursor cursor = textCursor(); QTextDocument* document = cursor.document(); int cursorPosition = cursor.position(); QChar token = text[0]; QChar matchingToken; static QString openingTokens("([{'\""); static QString closingTokens(")]}'\""); bool isOpeningToken, isClosingToken; int idx; if ((idx = openingTokens.indexOf(token)) != -1) { matchingToken = closingTokens[idx]; isOpeningToken = true; isClosingToken = token == matchingToken; } else if ((idx = closingTokens.indexOf(token)) != -1) { matchingToken = openingTokens[idx]; isClosingToken = true; isOpeningToken = token == matchingToken; } else return false; cursor.beginEditBlock(); if (mInsertMatchingTokens) { if (cursor.hasSelection()) { if (isOpeningToken) { int start = cursor.selectionStart(); int end = cursor.selectionEnd(); cursor.setPosition(start); cursor.insertText(token); cursor.setPosition(end + 1); cursor.insertText(matchingToken); } else cursor.insertText(token); } else { if (isClosingToken && document->characterAt(cursorPosition) == token) { cursor.movePosition(QTextCursor::NextCharacter); } else if (isOpeningToken) { cursor.insertText(token); cursor.insertText(matchingToken); cursor.movePosition(QTextCursor::PreviousCharacter); } else cursor.insertText(token); } } else cursor.insertText(token); cursor.endEditBlock(); cursor.setVerticalMovementX(-1); setTextCursor(cursor); if (isClosingToken) indent(cursor, JoinEditBlock); ensureCursorVisible(); return true; } bool ScCodeEditor::removeMatchingTokens() { QTextCursor cursor = textCursor(); QTextDocument* document = cursor.document(); int cursorPosition = cursor.position(); if (cursorPosition == 0) return false; QChar previousChar = document->characterAt(cursorPosition - 1); QChar nextChar; if (previousChar == '{') nextChar = '}'; else if (previousChar == '[') nextChar = ']'; else if (previousChar == '(') nextChar = ')'; else if (previousChar == '\'' || previousChar == '"') nextChar = previousChar; else return false; if (document->characterAt(cursorPosition) != nextChar) return false; cursor.beginEditBlock(); cursor.deletePreviousChar(); cursor.deleteChar(); cursor.endEditBlock(); setTextCursor(cursor); return true; } QTextCursor ScCodeEditor::selectionForPosition(int position) { QTextBlock block(textDocument()->findBlock(position)); if (!block.isValid()) return QTextCursor(); int positionInBlock = position - block.position(); TokenIterator it = TokenIterator(block, positionInBlock); if (it.type() == Token::Unknown) { // Token is invalid, or Token::Unknown (i.e. punctuations). // Prefer token at previous position. TokenIterator alternativeIt = TokenIterator(block, positionInBlock - 1); if (alternativeIt.isValid()) it = alternativeIt; } if (it.isValid()) { switch (it->type) { case Token::OpeningBracket: case Token::ClosingBracket: { BracketPair match; matchBracket(it, match); if (match.first.isValid() && match.second.isValid()) { int start = match.first.position(); int end = match.second.position() + 1; QTextCursor selection(textDocument()); if (it == match.second) { selection.setPosition(start); selection.setPosition(end, QTextCursor::KeepAnchor); } else { selection.setPosition(end); selection.setPosition(start, QTextCursor::KeepAnchor); } return selection; } break; } default: QTextCursor selection(textDocument()); selection.setPosition(it.position()); selection.setPosition(selection.position() + it->length, QTextCursor::KeepAnchor); return selection; } } return QTextCursor(); } void ScCodeEditor::matchBrackets() { mBracketSelections.clear(); QTextCursor cursor(textCursor()); QTextBlock block(cursor.block()); int posInBlock = cursor.positionInBlock(); TokenIterator it(block); while (it.isValid() && it.block() == block) { const Token& token = *it; if (token.positionInBlock > posInBlock) { it = TokenIterator(); break; } else if ((token.positionInBlock == posInBlock && token.type == Token::OpeningBracket) || (token.positionInBlock == posInBlock - 1 && token.type == Token::ClosingBracket)) break; ++it; } if (!it.isValid() || it.block() != block) { updateExtraSelections(); return; } BracketPair match; matchBracket(it, match); if (match.first.isValid() && match.second.isValid()) { const Token& tok1 = *match.first; const Token& tok2 = *match.second; if ((tok1.character == '(' && tok2.character == ')') || (tok1.character == '[' && tok2.character == ']') || (tok1.character == '{' && tok2.character == '}')) { QTextEdit::ExtraSelection selection; selection.format = mBracketHighlight; cursor.setPosition(match.first.position()); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); selection.cursor = cursor; mBracketSelections.append(selection); cursor.setPosition(match.second.position()); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); selection.cursor = cursor; mBracketSelections.append(selection); if (mHighlightBracketContents) { QTextCharFormat format; format.setBackground(mBracketHighlight.background()); selection.format = format; cursor.setPosition(match.first.position() + 1); cursor.setPosition(match.second.position(), QTextCursor::KeepAnchor); selection.cursor = cursor; mBracketSelections.append(selection); } } else { QTextEdit::ExtraSelection selection; selection.format = mBracketMismatchFormat; cursor.setPosition(match.first.position()); cursor.setPosition(match.second.position() + 1, QTextCursor::KeepAnchor); selection.cursor = cursor; mBracketSelections.append(selection); } } else { if (it.type() == Token::OpeningBracket) { cursor.setPosition(it.position()); cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor); } else { cursor.setPosition(it.position() + 1); cursor.movePosition(QTextCursor::Start, QTextCursor::KeepAnchor); } QTextEdit::ExtraSelection selection; selection.format = mBracketMismatchFormat; selection.cursor = cursor; mBracketSelections.append(selection); } updateExtraSelections(); } int ScCodeEditor::indentedStartOfLine(const QTextBlock& b) { QString t(b.text()); int n = t.size(); int i = 0; while (i < n) { QChar c(t[i]); if (c != ' ' && c != '\t') break; ++i; } return i; } void ScCodeEditor::updateExtraSelections() { QList<QTextEdit::ExtraSelection> selections; selections.append(mBracketSelections); selections.append(mSearchSelections); setExtraSelections(selections); } void ScCodeEditor::indentCurrentRegion() { indent(currentRegion()); } void ScCodeEditor::indent(EditBlockMode editBlockMode) { indent(textCursor(), editBlockMode); } void ScCodeEditor::indent(const QTextCursor& selection, EditBlockMode editBlockMode) { if (selection.isNull()) return; QTextCursor cursor(selection); if (editBlockMode == NewEditBlock) cursor.beginEditBlock(); else cursor.joinPreviousEditBlock(); QTextDocument* doc = QPlainTextEdit::document(); int startBlockNum = doc->findBlock(cursor.selectionStart()).blockNumber(); int endBlockNum = cursor.hasSelection() ? doc->findBlock(cursor.selectionEnd()).blockNumber() : startBlockNum; QStack<int> stack; int global_level = 0; int blockNum = 0; bool in_string = false; QTextBlock block = QPlainTextEdit::document()->begin(); while (block.isValid()) { int initialStackSize = stack.size(); int level = 0; bool block_start_in_string = in_string; TextBlockData* data = static_cast<TextBlockData*>(block.userData()); if (data) { int count = data->tokens.size(); for (int idx = 0; idx < count; ++idx) { const Token& token = data->tokens[idx]; switch (token.type) { case Token::OpeningBracket: if (token.character != '(' || stack.size() || token.positionInBlock) ++level; break; case Token::ClosingBracket: if (level) --level; else if (global_level) { --global_level; if (!stack.isEmpty() && global_level < stack.top()) stack.pop(); } break; case Token::StringMark: in_string = !in_string; break; default: break; } } } if (blockNum >= startBlockNum) { int indentLevel; if (data && data->tokens.size() && data->tokens[0].type == Token::ClosingBracket) indentLevel = stack.size(); else if (!block_start_in_string) indentLevel = initialStackSize; else indentLevel = 0; block = indent(block, indentLevel); } if (blockNum == endBlockNum) break; block = block.next(); ++blockNum; if (level) { global_level += level; stack.push(global_level); } } cursor.endEditBlock(); } QString ScCodeEditor::makeIndentationString(int level) { if (level <= 0) return QString(); if (mSpaceIndent) { const int spaces = mDoc->indentWidth() * level; QString indentationString(spaces, QChar(' ')); return indentationString; } else { const int tabs = level; QString indentationString(tabs, QChar('\t')); return indentationString; } } QTextBlock ScCodeEditor::indent(const QTextBlock& block, int level) { QTextCursor cursor(block); cursor.movePosition(QTextCursor::StartOfBlock); cursor.setPosition(cursor.position() + indentedStartOfLine(block), QTextCursor::KeepAnchor); cursor.insertText(makeIndentationString(level)); // modification has invalidated the block, so return a new one return cursor.block(); } int ScCodeEditor::indentationLevel(const QTextCursor& cursor) { QTextDocument* doc = QPlainTextEdit::document(); int startBlockNum = doc->findBlock(cursor.selectionStart()).blockNumber(); QStack<int> stack; int level = 0; int blockNum = 0; QTextBlock block = QPlainTextEdit::document()->begin(); while (block.isValid()) { if (level > 0) { stack.push(level); level = 0; } TextBlockData* data = static_cast<TextBlockData*>(block.userData()); if (data) { int count = data->tokens.size(); for (int idx = 0; idx < count; ++idx) { const Token& token = data->tokens[idx]; switch (token.type) { case Token::OpeningBracket: if (token.character != '(' || stack.size() || token.positionInBlock) level += 1; break; case Token::ClosingBracket: if (level) level -= 1; else if (!stack.isEmpty()) { stack.top() -= 1; if (stack.top() <= 0) stack.pop(); } break; default:; } } } if (blockNum == startBlockNum) return stack.size(); block = block.next(); ++blockNum; } return -1; } void ScCodeEditor::insertSpaceToNextTabStop(QTextCursor& cursor) { if (mSpaceIndent) { const int indentWidth = mDoc->indentWidth(); if (indentWidth < 1) return; const int spaces = indentWidth - (cursor.positionInBlock() % indentWidth); QString spaceString(spaces, QChar(' ')); cursor.insertText(spaceString); } else { cursor.insertText("\t"); } } void ScCodeEditor::triggerAutoCompletion() { mAutoCompleter->triggerCompletion(); } void ScCodeEditor::triggerMethodCallAid() { mAutoCompleter->triggerMethodCallAid(); } static bool isSingleLineComment(QTextBlock const& block) { static QRegularExpression commentRegex("^\\s*//.*"); return commentRegex.match(block.text()).hasMatch(); } static bool isSingleLineComment(QTextCursor const& selection) { QTextCursor cursor(selection); cursor.setPosition(selection.selectionStart()); QTextBlock startBlock = cursor.block(); cursor.setPosition(selection.selectionEnd() - 1); QTextBlock endBlock = cursor.block(); for (QTextBlock block = startBlock; block != endBlock.next(); block = block.next()) { if (!isSingleLineComment(block)) return false; } return true; } static bool isSelectionComment(QString const& text) { QString trimmed = text.trimmed(); if (trimmed.startsWith(QStringLiteral("/*")) && trimmed.endsWith(QStringLiteral("*/"))) return true; else return false; } void ScCodeEditor::toggleComment() { QTextCursor cursor = textCursor(); if (cursor.hasSelection()) toggleCommentSelection(); else toggleCommentSingleLine(); } void ScCodeEditor::toggleCommentSingleLine() { QTextCursor cursor = textCursor(); cursor.beginEditBlock(); toggleCommentSingleLine(cursor); cursor.endEditBlock(); } void ScCodeEditor::addSingleLineComment(QTextCursor cursor, int indentation) { QTextBlock currentBlock(cursor.block()); int blockIndentationLevel = indentationLevel(cursor); cursor.movePosition(QTextCursor::StartOfBlock); cursor.setPosition(cursor.position() + indentedStartOfLine(currentBlock), QTextCursor::KeepAnchor); QString commentString = makeIndentationString(indentation) + QStringLiteral("// ") + makeIndentationString(blockIndentationLevel - indentation); cursor.insertText(commentString); cursor.movePosition(QTextCursor::StartOfBlock); } void ScCodeEditor::removeSingleLineComment(QTextCursor cursor) { QTextBlock currentBlock(cursor.block()); cursor.movePosition(QTextCursor::StartOfBlock); const int startPosition = cursor.position(); const int indentPosition = indentedStartOfLine(currentBlock); const int commentStartPosition = startPosition + indentPosition; cursor.setPosition(commentStartPosition); cursor.setPosition(commentStartPosition + 3, QTextCursor::KeepAnchor); if (!cursor.selectedText().endsWith(QStringLiteral("// "))) { cursor.setPosition(commentStartPosition + 2, QTextCursor::KeepAnchor); if (!cursor.selectedText().endsWith(QStringLiteral("//"))) return; } cursor.insertText(""); } void ScCodeEditor::toggleCommentSingleLine(QTextCursor cursor) { QTextBlock currentBlock(cursor.block()); cursor.beginEditBlock(); if (!isSingleLineComment(currentBlock)) { int blockIndentation = indentationLevel(cursor); addSingleLineComment(cursor, blockIndentation); } else removeSingleLineComment(cursor); cursor.endEditBlock(); indent(cursor); } static bool isBlockOnlySelection(QTextCursor cursor) { Q_ASSERT(cursor.hasSelection()); QTextCursor begin(cursor); begin.setPosition(begin.anchor()); if (begin.atBlockStart() && (cursor.atBlockStart() || cursor.atBlockEnd())) return true; else return false; } void ScCodeEditor::toggleCommentSelection() { QTextCursor cursor = textCursor(); cursor.beginEditBlock(); if (isBlockOnlySelection(cursor)) { const bool isComment = isSingleLineComment(cursor); QTextCursor selectionCursor(cursor); selectionCursor.setPosition(cursor.selectionStart()); QTextBlock currentBlock = selectionCursor.block(); int firstBlockIndentation = isComment ? 0 : indentationLevel(selectionCursor); do { QTextCursor blockCursor(currentBlock); if (!isComment) addSingleLineComment(blockCursor, firstBlockIndentation); else removeSingleLineComment(blockCursor); currentBlock = currentBlock.next(); } while (currentBlock.isValid() && currentBlock.position() < cursor.selectionEnd()); if (!isComment) { // fix up selection QTextCursor newSelection(cursor); if (cursor.anchor() < cursor.position()) { newSelection.setPosition(newSelection.selectionStart()); newSelection.movePosition(QTextCursor::StartOfBlock); newSelection.setPosition(cursor.selectionEnd(), QTextCursor::KeepAnchor); } else { newSelection.setPosition(newSelection.selectionEnd()); newSelection.setPosition(cursor.selectionStart(), QTextCursor::KeepAnchor); newSelection.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor); } setTextCursor(newSelection); } } else { QString selectionText = cursor.selectedText(); QTextCursor selectionCursor(cursor); if (isSelectionComment(selectionText)) { selectionText = selectionText.trimmed().remove(0, 2); selectionText.chop(2); selectionCursor.insertText(selectionText); } else { selectionText = QStringLiteral("/*") + selectionText + QStringLiteral("*/"); selectionCursor.insertText(selectionText); } // fix up selection const int position = selectionCursor.position(); const int anchor = selectionCursor.anchor(); if (position > anchor) { cursor.setPosition(position - selectionText.size()); cursor.setPosition(position, QTextCursor::KeepAnchor); } else { cursor.setPosition(position); cursor.setPosition(position - selectionText.size(), QTextCursor::KeepAnchor); } setTextCursor(cursor); } cursor.endEditBlock(); } // taking nested brackets into account TokenIterator ScCodeEditor::previousOpeningBracket(TokenIterator it) { int level = 0; while (it.isValid()) { switch (it->type) { case Token::OpeningBracket: if (level == 0) return it; --level; break; case Token::ClosingBracket: ++level; default: break; } --it; } return it; } // taking nested brackets into account TokenIterator ScCodeEditor::nextClosingBracket(TokenIterator it) { int level = 0; while (it.isValid()) { switch (it->type) { case Token::ClosingBracket: if (level == 0) return it; --level; break; case Token::OpeningBracket: ++level; default: break; } ++it; } return it; } void ScCodeEditor::matchBracket(const TokenIterator& bracket, BracketPair& match) { Q_ASSERT(bracket.isValid()); switch (bracket->type) { case Token::OpeningBracket: match.first = bracket; match.second = nextClosingBracket(bracket.next()); break; case Token::ClosingBracket: match.second = bracket; match.first = previousOpeningBracket(bracket.previous()); break; default: match.first = TokenIterator(); match.second = TokenIterator(); } } void ScCodeEditor::nextBracketPair(const TokenIterator& startIt, BracketPair& bracketPair) { TokenIterator it(startIt); while (it.isValid()) { if (it->type == Token::OpeningBracket) { matchBracket(it, bracketPair); return; } ++it; } bracketPair = BracketPair(); } void ScCodeEditor::gotoNextBlock() { QTextCursor cursor = textCursor(); TokenIterator tokenIt = TokenIterator::rightOf(cursor.block(), cursor.positionInBlock()); if (tokenIt.type() == Token::OpeningBracket && tokenIt.block() == cursor.block() && tokenIt->positionInBlock == cursor.positionInBlock()) ++tokenIt; tokenIt = nextClosingBracket(tokenIt); if (tokenIt.isValid()) setTextCursor(cursorAt(tokenIt, 1)); else { cursor.movePosition(QTextCursor::End); setTextCursor(cursor); } } void ScCodeEditor::gotoPreviousBlock() { QTextCursor cursor = textCursor(); TokenIterator tokenIt = TokenIterator::leftOf(cursor.block(), cursor.positionInBlock()); if (tokenIt.type() == Token::ClosingBracket && tokenIt.block() == cursor.block() && tokenIt->positionInBlock == cursor.positionInBlock() - 1) --tokenIt; tokenIt = previousOpeningBracket(tokenIt); if (tokenIt.isValid()) setTextCursor(cursorAt(tokenIt)); else { cursor.movePosition(QTextCursor::Start); setTextCursor(cursor); } } QTextCursor ScCodeEditor::blockAroundCursor(const QTextCursor& cursor) { TokenIterator left_bracket = previousOpeningBracket(TokenIterator::leftOf(cursor.block(), cursor.positionInBlock())); if (!left_bracket.isValid()) return QTextCursor(); TokenIterator right_bracket = nextClosingBracket(TokenIterator::rightOf(cursor.block(), cursor.positionInBlock())); if (!right_bracket.isValid()) return QTextCursor(); QTextCursor block_cursor = cursor; block_cursor.setPosition(left_bracket.position()); block_cursor.setPosition(right_bracket.position() + 1, QTextCursor::KeepAnchor); return block_cursor; } void ScCodeEditor::selectBlockAroundCursor() { QTextCursor block_cursor = blockAroundCursor(textCursor()); if (!block_cursor.isNull()) setTextCursor(block_cursor); } inline static bool tokenMaybeRegionStart(const TokenIterator& it) { Q_ASSERT(it.isValid()); return (it->character == '(' && it->positionInBlock == 0); } inline static bool tokenMaybeRegionEnd(const TokenIterator& it) { Q_ASSERT(it.isValid()); if (it->character != ')') return false; TokenIterator next_it = it.next(); return (!next_it.isValid() || next_it.block() != it.block() || next_it->character == ';'); } static bool bracketPairDefinesRegion(const BracketPair& bracketPair) { Q_ASSERT(bracketPair.first.isValid()); Q_ASSERT(bracketPair.second.isValid()); if (!tokenMaybeRegionStart(bracketPair.first) || !tokenMaybeRegionEnd(bracketPair.second)) return false; return true; } QTextCursor ScCodeEditor::regionAroundCursor(const QTextCursor& cursor) { int cursorPosition = cursor.position(); BracketPair bracketPair; TokenIterator it = TokenIterator::rightOf(textDocument()->begin(), 0); while (it.isValid()) { nextBracketPair(it, bracketPair); if (bracketPair.first.isValid() && bracketPair.first.position() < cursorPosition) { if (bracketPair.second.isValid() && bracketPair.second.position() >= cursorPosition && bracketPairDefinesRegion(bracketPair)) { QTextCursor regionCursor(QPlainTextEdit::document()); regionCursor.setPosition(bracketPair.first.position()); regionCursor.setPosition(bracketPair.second.position() + 1, QTextCursor::KeepAnchor); return regionCursor; } } else { break; } it = bracketPair.second; } return QTextCursor(); } QTextCursor ScCodeEditor::currentRegion() { QTextCursor cursor = textCursor(); QTextBlock block = cursor.block(); int positionInBlock = cursor.positionInBlock(); if (TokenIterator(block, positionInBlock - 1).type() == Token::ClosingBracket) cursor.movePosition(QTextCursor::PreviousCharacter); else if (TokenIterator(block, positionInBlock).type() == Token::OpeningBracket) cursor.movePosition(QTextCursor::NextCharacter); return regionAroundCursor(cursor); } void ScCodeEditor::selectCurrentRegion() { QTextCursor selectedRegionCursor = currentRegion(); if (!selectedRegionCursor.isNull() && selectedRegionCursor.hasSelection()) setTextCursor(selectedRegionCursor); } void ScCodeEditor::gotoNextRegion() { QTextCursor cursor = textCursor(); int cursorPosition = cursor.position(); BracketPair bracketPair; TokenIterator it = TokenIterator::rightOf(textDocument()->begin(), 0); while (it.isValid()) { nextBracketPair(it, bracketPair); if (bracketPair.first.isValid() && bracketPair.second.isValid() && bracketPair.first.position() > cursorPosition && bracketPairDefinesRegion(bracketPair)) { setTextCursor(cursorAt(bracketPair.first)); return; } it = bracketPair.second; } cursor.movePosition(QTextCursor::End); setTextCursor(cursor); } void ScCodeEditor::gotoPreviousRegion() { QTextCursor cursor = textCursor(); int cursorPosition = cursor.position(); BracketPair prevBracketPair; BracketPair bracketPair; TokenIterator it = TokenIterator::rightOf(textDocument()->begin(), 0); while (it.isValid()) { nextBracketPair(it, bracketPair); if (!bracketPair.second.isValid() || bracketPair.second.position() >= cursorPosition - 1) { break; } if (bracketPairDefinesRegion(bracketPair)) { prevBracketPair = bracketPair; } it = bracketPair.second; } if (prevBracketPair.first.isValid() && prevBracketPair.second.isValid()) { setTextCursor(cursorAt(prevBracketPair.second, 1)); return; } cursor.movePosition(QTextCursor::Start); setTextCursor(cursor); } bool ScCodeEditor::openDocumentation() { return Main::openDocumentation(symbolUnderCursor()); } void ScCodeEditor::openDefinition() { Main::openDefinition(symbolUnderCursor(), this); } void ScCodeEditor::openCommandLine() { Main::openCommandLine(symbolUnderCursor()); } void ScCodeEditor::findReferences() { Main::findReferences(symbolUnderCursor(), this); } void ScCodeEditor::evaluateLine() { QString text; #ifdef SC_USE_QTWEBENGINE HelpBrowserDocklet* help = MainWindow::instance()->helpBrowserDocklet(); if (help && help->browser()->helpBrowserHasFocus()) { help->browser()->evaluateSelection(false); return; // early return } #endif // SC_USE_QTWEBENGINE // Try current selection QTextCursor cursor = textCursor(); if (cursor.hasSelection()) text = cursor.selectedText(); else { text = cursor.block().text(); if (mStepForwardEvaluation) { QTextCursor newCursor = cursor; newCursor.movePosition(QTextCursor::NextBlock); newCursor.setVerticalMovementX(cursor.verticalMovementX()); setTextCursor(newCursor); } // Adjust cursor for code blinking: cursor.movePosition(QTextCursor::StartOfBlock); cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); } if (text.isEmpty()) return; text.replace(QChar(0x2029), QChar('\n')); Main::evaluateCode(text); blinkCode(cursor); } void ScCodeEditor::evaluateRegion() { QString text; #ifdef SC_USE_QTWEBENGINE HelpBrowserDocklet* help = MainWindow::instance()->helpBrowserDocklet(); if (help && help->browser()->helpBrowserHasFocus()) { help->browser()->evaluateSelection(true); return; // early return } #endif // SC_USE_QTWEBENGINE // Try current selection QTextCursor cursor = textCursor(); if (cursor.hasSelection()) text = cursor.selectedText(); else { // If no selection, try current region cursor = currentRegion(); if (!cursor.isNull()) { text = cursor.selectedText(); } else { // If no current region, try current line cursor = textCursor(); text = cursor.block().text(); if (mStepForwardEvaluation) { QTextCursor newCursor = cursor; newCursor.movePosition(QTextCursor::NextBlock); newCursor.setVerticalMovementX(cursor.verticalMovementX()); setTextCursor(newCursor); } // Adjust cursor for code blinking: cursor.movePosition(QTextCursor::StartOfBlock); cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); } } if (text.isEmpty()) return; text.replace(QChar(0x2029), QChar('\n')); Main::evaluateCode(text); blinkCode(cursor); } void ScCodeEditor::evaluateDocument() { QString documentText = textDocument()->toPlainText(); Main::evaluateCode(documentText); } QTextCursor ScCodeEditor::cursorAt(const TokenIterator it, int offset) { Q_ASSERT(it.isValid()); QTextCursor textCursor(textDocument()); textCursor.setPosition(it.position() + offset); return textCursor; } } // namespace ScIDE
41,526
C++
.cpp
1,076
30.3829
120
0.639033
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
30,044
general_page.cpp
supercollider_supercollider/editors/sc-ide/widgets/settings/general_page.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "general_page.hpp" #include "ui_settings_general.h" #include "../../core/settings/manager.hpp" Q_DECLARE_METATYPE(QAction*) Q_DECLARE_METATYPE(QKeySequence) namespace ScIDE { namespace Settings { GeneralPage::GeneralPage(QWidget* parent): QWidget(parent), ui(new Ui::GeneralConfigPage) { ui->setupUi(this); connect(ui->startSessionName, SIGNAL(textChanged(QString)), this, SLOT(onStartSessionNameChanged(QString))); } GeneralPage::~GeneralPage() { delete ui; } void GeneralPage::load(Manager* settings) { QString startSessionName = settings->value("IDE/startWithSession").toString(); if (startSessionName.isEmpty()) ui->startNewSessionOption->setChecked(true); else if (startSessionName == "last") ui->startLastSessionOption->setChecked(true); else { ui->startNamedSessionOption->setChecked(true); ui->startSessionName->setText(startSessionName); } } void GeneralPage::store(Manager* settings) { settings->beginGroup("IDE"); QWidget* checkedOption = ui->startSessionOptions->checkedButton(); if (checkedOption == ui->startLastSessionOption) { settings->setValue("startWithSession", "last"); } else if (checkedOption == ui->startNamedSessionOption && !ui->startSessionName->text().isEmpty()) { settings->setValue("startWithSession", ui->startSessionName->text()); } else { settings->setValue("startWithSession", ""); } settings->endGroup(); } void GeneralPage::onStartSessionNameChanged(const QString& text) { if (!text.isEmpty()) ui->startNamedSessionOption->setChecked(true); } }} // namespace ScIDE::Settings
2,494
C++
.cpp
55
40.781818
112
0.734214
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,045
shortcuts_page.cpp
supercollider_supercollider/editors/sc-ide/widgets/settings/shortcuts_page.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "shortcuts_page.hpp" #include "ui_settings_shortcuts.h" #include "../../core/settings/manager.hpp" #include "../../core/main.hpp" #include <QHeaderView> #include <QTreeWidget> #include <QTreeWidgetItem> #include <QKeyEvent> #include <QMessageBox> Q_DECLARE_METATYPE(QAction*) Q_DECLARE_METATYPE(QKeySequence) namespace ScIDE { namespace Settings { ShortcutsPage::ShortcutsPage(QWidget* parent): QWidget(parent), ui(new Ui::ShortcutConfigPage) { ui->setupUi(this); ui->clearSeq->setIcon(style()->standardIcon(QStyle::SP_DockWidgetCloseButton)); connect(ui->filter, SIGNAL(textChanged(QString)), this, SLOT(filterBy(QString))); connect(ui->actionTree, SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)), this, SLOT(showItem(QTreeWidgetItem*, QTreeWidgetItem*))); // automation connect(ui->defaultOpt, SIGNAL(clicked()), ui->customSeq, SLOT(reset())); connect(ui->customOpt, SIGNAL(clicked()), ui->customSeq, SLOT(setFocus())); connect(ui->customSeq, SIGNAL(editingStarted()), ui->customOpt, SLOT(toggle())); connect(ui->clearSeq, SIGNAL(clicked()), ui->customSeq, SLOT(reset())); connect(ui->clearSeq, SIGNAL(clicked()), ui->customOpt, SLOT(click())); // value application connect(ui->defaultOpt, SIGNAL(clicked()), this, SLOT(apply())); connect(ui->customOpt, SIGNAL(clicked()), this, SLOT(apply())); connect(ui->customSeq, SIGNAL(editingFinished()), this, SLOT(apply())); } ShortcutsPage::~ShortcutsPage() { delete ui; } void ShortcutsPage::load(Manager* s) { ui->actionTree->clear(); s->beginGroup("IDE/shortcuts"); const QList<QAction*>& actions = s->actions(); foreach (QAction* action, actions) addAction(action, s); s->endGroup(); ui->actionTree->sortByColumn(0, Qt::AscendingOrder); ui->actionTree->header()->resizeSections(QHeaderView::ResizeToContents); } void ShortcutsPage::store(Manager* s) { s->beginGroup("IDE/shortcuts"); s->remove(""); int c = ui->actionTree->topLevelItemCount(); for (int i = 0; i < c; ++i) { QTreeWidgetItem* item = ui->actionTree->topLevelItem(i); QAction* action = item->data(0, ActionRole).value<QAction*>(); Q_ASSERT(action); QVariant var = item->data(0, CustomSequenceRole); if (var.isValid()) { s->setValue(s->keyForAction(action), var); } else { var = s->defaultValue(s->keyForAction(action)); } action->setShortcut(var.value<QKeySequence>()); } s->endGroup(); } void ShortcutsPage::addAction(QAction* a, Manager* s) { QString description = a->statusTip(); if (description.isEmpty()) description = a->toolTip(); QTreeWidgetItem* item = new QTreeWidgetItem; item->setIcon(0, a->icon()); item->setText(0, a->text().remove('&')); item->setText(2, description); QString key = s->keyForAction(a); item->setData(0, ActionRole, QVariant::fromValue<QAction*>(a)); item->setData(0, DefaultSequenceRole, s->defaultValue(key)); if (s->isOverridden(key)) { // For reason of performance, ensure the variant holds a QKeySequence QKeySequence seq = s->value(key).value<QKeySequence>(); item->setData(0, CustomSequenceRole, QVariant::fromValue<QKeySequence>(seq)); } updateItem(item); ui->actionTree->addTopLevelItem(item); } void ShortcutsPage::filterBy(const QString& str) { int c = ui->actionTree->topLevelItemCount(); if (str.isEmpty()) { for (int i = 0; i < c; ++i) ui->actionTree->topLevelItem(i)->setHidden(false); } else { for (int i = 0; i < c; ++i) { QTreeWidgetItem* item = ui->actionTree->topLevelItem(i); bool visible = item->text(0).contains(str, Qt::CaseInsensitive) || item->text(2).contains(str, Qt::CaseInsensitive); item->setHidden(!visible); } } } void ShortcutsPage::showItem(QTreeWidgetItem* item, QTreeWidgetItem* prev) { QVariant defaultSeqVar = item ? item->data(0, DefaultSequenceRole) : QVariant(); QString defaultSeq = defaultSeqVar.value<QKeySequence>().toString(QKeySequence::NativeText); ui->defaultSeq->setText(defaultSeq); QVariant customSeqVar = item ? item->data(0, CustomSequenceRole) : QVariant(); ui->customSeq->setSequence(customSeqVar.value<QKeySequence>()); if (customSeqVar.isValid()) ui->customOpt->setChecked(true); else ui->defaultOpt->setChecked(true); } void ShortcutsPage::apply() { applyTo(ui->actionTree->currentItem()); } void ShortcutsPage::applyTo(QTreeWidgetItem* targetItem) { if (!targetItem) return; bool seqIsCustom = ui->customOpt->isChecked(); QKeySequence currentSeq = seqIsCustom ? ui->customSeq->sequence() : targetItem->data(0, DefaultSequenceRole).value<QKeySequence>(); // Check for duplicates if (!currentSeq.isEmpty()) { int itemCount = ui->actionTree->topLevelItemCount(); for (int itemIdx = 0; itemIdx < itemCount; ++itemIdx) { QTreeWidgetItem* item = ui->actionTree->topLevelItem(itemIdx); if (item == targetItem) continue; QKeySequence itemSeq = activeItemSequence(item); if (currentSeq == itemSeq) { // Got a duplicate sequence if (confirmOverride(currentSeq, item)) { item->setData(0, CustomSequenceRole, QVariant::fromValue(QKeySequence())); updateItem(item); } else { seqIsCustom = true; currentSeq = QKeySequence(); ui->customOpt->setChecked(true); ui->customSeq->clear(); } break; } } } if (seqIsCustom) { targetItem->setData(0, CustomSequenceRole, QVariant::fromValue(currentSeq)); } else { targetItem->setData(0, CustomSequenceRole, QVariant()); } updateItem(targetItem); } bool ShortcutsPage::confirmOverride(const QKeySequence& duplicateSequence, QTreeWidgetItem* duplicateItem) { QString warningString = tr("Shortcut '%1' has already been assigned to '%2'.\n\n" "Would you like to override it?"); warningString = warningString.arg(duplicateSequence.toString(), duplicateItem->text(0)); QMessageBox::StandardButton result = QMessageBox::warning( this, tr("Duplicate Shortcut"), warningString, QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel); return result == QMessageBox::Ok; } void ShortcutsPage::updateItem(QTreeWidgetItem* item) { QVariant seqData = item->data(0, CustomSequenceRole); if (!seqData.isValid()) seqData = item->data(0, DefaultSequenceRole); QKeySequence seq = seqData.value<QKeySequence>(); item->setText(1, seq.toString(QKeySequence::NativeText)); } QKeySequence ShortcutsPage::activeItemSequence(QTreeWidgetItem* item) { QVariant seqVar = item->data(0, CustomSequenceRole); if (!seqVar.isValid()) seqVar = item->data(0, DefaultSequenceRole); return seqVar.value<QKeySequence>(); } }} // namespace ScIDE::Settings
8,076
C++
.cpp
177
38.830508
117
0.671381
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,046
dialog.cpp
supercollider_supercollider/editors/sc-ide/widgets/settings/dialog.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "dialog.hpp" #include "ui_settings_dialog.h" #include "general_page.hpp" #include "sclang_page.hpp" #include "editor_page.hpp" #include "shortcuts_page.hpp" #include "../../core/settings/manager.hpp" #include "../../core/main.hpp" #include <QVBoxLayout> #include <QHBoxLayout> #include <QDialogButtonBox> #include <QStackedWidget> #include <QListWidget> #include <QFile> #include <QLineEdit> #include <QPushButton> namespace ScIDE { namespace Settings { Dialog::Dialog(Manager* settings, QWidget* parent): QDialog(parent), mManager(settings), ui(new Ui::ConfigDialog) { ui->setupUi(this); QWidget* w; w = new GeneralPage; ui->configPageStack->addWidget(w); ui->configPageList->addItem(new QListWidgetItem(QIcon::fromTheme("preferences-system"), tr("General"))); connect(this, SIGNAL(storeRequest(Manager*)), w, SLOT(store(Manager*))); connect(this, SIGNAL(loadRequest(Manager*)), w, SLOT(load(Manager*))); w = new SclangPage; ui->configPageStack->addWidget(w); ui->configPageList->addItem(new QListWidgetItem(QIcon::fromTheme("applications-system"), tr("Interpreter"))); connect(this, SIGNAL(storeRequest(Manager*)), w, SLOT(store(Manager*))); connect(this, SIGNAL(loadRequest(Manager*)), w, SLOT(load(Manager*))); w = new EditorPage; ui->configPageStack->addWidget(w); ui->configPageList->addItem(new QListWidgetItem(QIcon::fromTheme("accessories-text-editor"), tr("Editor"))); connect(this, SIGNAL(storeRequest(Manager*)), w, SLOT(store(Manager*))); connect(this, SIGNAL(loadRequest(Manager*)), w, SLOT(load(Manager*))); w = new ShortcutsPage; ui->configPageStack->addWidget(w); ui->configPageList->addItem(new QListWidgetItem(QIcon::fromTheme("input-keyboard"), tr("Shortcuts"))); connect(this, SIGNAL(storeRequest(Manager*)), w, SLOT(store(Manager*))); connect(this, SIGNAL(loadRequest(Manager*)), w, SLOT(load(Manager*))); connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(ui->buttonBox, SIGNAL(rejected()), this, SLOT(reject())); connect(ui->buttonBox->button(QDialogButtonBox::Apply), SIGNAL(clicked()), this, SLOT(apply())); connect(ui->buttonBox->button(QDialogButtonBox::Reset), SIGNAL(clicked()), this, SLOT(reset())); ui->configPageList->setMinimumWidth(ui->configPageList->sizeHintForColumn(0)); reset(); } Dialog::~Dialog() { delete ui; } void Dialog::accept() { Q_EMIT(storeRequest(mManager)); QDialog::accept(); } void Dialog::reject() { QDialog::reject(); } void Dialog::apply() { Q_EMIT(storeRequest(mManager)); Main::instance()->applySettings(); } void Dialog::reset() { Q_EMIT(loadRequest(mManager)); } }} // namespace ScIDE::Settings
3,573
C++
.cpp
75
43.88
115
0.724892
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,047
editor_page.cpp
supercollider_supercollider/editors/sc-ide/widgets/settings/editor_page.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "editor_page.hpp" #include "ui_settings_editor.h" #include "../code_editor/highlighter.hpp" #include "../../core/settings/manager.hpp" #include "../../core/settings/theme.hpp" #include "../../core/main.hpp" #include <QMenu> #include <QDebug> #include <QListWidgetItem> #include <QFontDatabase> #include <QApplication> #include <QInputDialog> #include <QMessageBox> namespace ScIDE { namespace Settings { EditorPage::EditorPage(QWidget* parent): QWidget(parent), #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) fontDatabase(new QFontDatabase), #endif() ui(new Ui::EditorConfigPage) { ui->setupUi(this); connect(ui->tabs, SIGNAL(currentChanged(int)), this, SLOT(onCurrentTabChanged(int))); connect(ui->onlyMonoFonts, SIGNAL(toggled(bool)), this, SLOT(onMonospaceToggle(bool))); connect(ui->fontCombo, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateFontPreview())); connect(ui->fontSize, SIGNAL(valueChanged(int)), this, SLOT(updateFontPreview())); connect(ui->fontAntialias, SIGNAL(stateChanged(int)), this, SLOT(updateFontPreview())); connect(ui->themeCombo, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateTheme(QString))); connect(ui->themeCopyBtn, SIGNAL(clicked()), this, SLOT(dialogCopyTheme())); connect(ui->themeDeleteBtn, SIGNAL(clicked()), this, SLOT(deleteTheme())); connect(ui->textFormats, SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)), this, SLOT(updateTextFormatEdit())); connect(ui->fgPicker, SIGNAL(colorPicked(QColor)), this, SLOT(updateTextFormatDisplay())); connect(ui->bgPicker, SIGNAL(colorPicked(QColor)), this, SLOT(updateTextFormatDisplay())); connect(ui->italicOption, SIGNAL(clicked()), this, SLOT(updateTextFormatDisplay())); connect(ui->boldOption, SIGNAL(clicked()), this, SLOT(updateTextFormatDisplay())); connect(ui->fgClearBtn, SIGNAL(clicked()), ui->fgPicker, SLOT(clear())); connect(ui->fgClearBtn, SIGNAL(clicked()), this, SLOT(updateTextFormatDisplay())); connect(ui->bgClearBtn, SIGNAL(clicked()), ui->bgPicker, SLOT(clear())); connect(ui->bgClearBtn, SIGNAL(clicked()), this, SLOT(updateTextFormatDisplay())); updateTextFormatEdit(); } EditorPage::~EditorPage() { delete ui; #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) delete fontDatabase; #endif qDeleteAll(mThemes); } void EditorPage::load(Manager* s) { s->beginGroup("IDE/editor"); ui->spaceIndent->setChecked(s->value("spaceIndent").toBool()); ui->indentWidth->setValue(s->value("indentWidth").toInt()); ui->stepForwardEvaluation->setChecked(s->value("stepForwardEvaluation").toBool()); ui->editorLineWrap->setChecked(s->value("lineWrap").toBool()); ui->disableBlinkingCursor->setChecked(s->value("disableBlinkingCursor").toBool()); ui->insertMatchingTokens->setChecked(s->value("insertMatchingTokens").toBool()); ui->blinkDuration->setValue(s->value("blinkDuration").toInt()); ui->highlightCurrentLine->setChecked(s->value("highlightCurrentLine").toBool()); ui->highlightBracketContents->setChecked(s->value("highlightBracketContents").toBool()); ui->inactiveEditorFadeAlpha->setValue(s->value("inactiveEditorFadeAlpha").toInt()); ui->useComboBox->setChecked(s->value("useComboBox").toBool()); ui->useComboBoxWhenSplitting->setChecked(s->value("useComboBoxWhenSplitting").toBool()); s->beginGroup("font"); QString fontFamily = s->value("family").toString(); int fontSize = s->value("size").toInt(); ui->fontAntialias->setChecked(s->value("antialias").toBool()); s->endGroup(); // Display info about the font that would actually be used: QFont defaultFont = QApplication::font("QPlainTextEdit"); defaultFont.setFamily(fontFamily); if (fontSize > 0) defaultFont.setPointSize(fontSize); defaultFont.setStyleHint(QFont::TypeWriter); QFontInfo fontInfo(defaultFont); fontFamily = fontInfo.family(); fontSize = fontInfo.pointSize(); populateFontList(ui->onlyMonoFonts->isChecked()); int fontFamilyIndex = ui->fontCombo->findText(fontFamily, Qt::MatchFixedString); ui->fontCombo->setCurrentIndex(fontFamilyIndex); ui->fontSize->setValue(fontSize); ui->textFormats->clear(); s->endGroup(); // IDE/editor QString themeName = s->value("IDE/editor/theme").toString(); updateTheme(themeName); populateThemeList(themeName); s->beginGroup("IDE/postWindow"); ui->postWindowScrollback->setValue(s->value("scrollback").toInt()); ui->postWindowLineWrap->setChecked(s->value("lineWrap").toBool()); s->endGroup(); updateFontPreview(); updateTextFormatDisplayCommons(); ui->textFormats->expandAll(); } void EditorPage::updateTheme(QString name) { Theme* theme; QMap<QString, Theme*>::const_iterator i = mThemes.find(name); if (i == mThemes.end()) { theme = new Theme(name); mThemes.insert(name, theme); } else { theme = i.value(); } loadThemeFormats(*theme); ui->bgPicker->setDisabled(theme->locked()); ui->fgPicker->setDisabled(theme->locked()); ui->bgClearBtn->setDisabled(theme->locked()); ui->fgClearBtn->setDisabled(theme->locked()); ui->themeDeleteBtn->setDisabled(theme->locked()); ui->italicOption->setDisabled(theme->locked()); ui->boldOption->setDisabled(theme->locked()); } void EditorPage::loadThemeFormats(Theme& theme) { ui->textFormats->clear(); // common text format item is special - don't set foreground and background on the item! mCommonTextFormatItem = new QTreeWidgetItem(ui->textFormats); mCommonTextFormatItem->setText(0, tr("Text")); mCommonTextFormatItem->setData(0, TextFormatConfigKeyRole, "text"); mCommonTextFormatItem->setData(0, TextFormatRole, QVariant::fromValue(theme.format("text"))); updateTextFormatDisplayCommons(); static char const* const keys[] = { "currentLine", "searchResult", "matchingBrackets", "mismatchedBrackets", "evaluatedCode", "lineNumbers", "selection", "postwindowtext", "whitespace", "keyword", "built-in", "env-var", "class", "number", "symbol", "string", "char", "comment", "primitive", "postwindowerror", "postwindowwarning", "postwindowsuccess", "postwindowemphasis" }; static QStringList strings = QStringList() << tr("Current Line") << tr("Search Result") << tr("Matching Brackets") << tr("Mismatched Brackets") << tr("Evaluated Code") << tr("Line Numbers") << tr("Selected Text") << tr("Post Window Text") << tr("Whitespace") << tr("Keyword") << tr("Built-in Value") << tr("Environment Variable") << tr("Class") << tr("Number") << tr("Symbol") << tr("String") << tr("Char") << tr("Comment") << tr("Primitive") << tr("Post Window Error") << tr("Post Window Warning") << tr("Post Window Success") << tr("Post Window Emphasis"); static int count = strings.count(); for (int idx = 0; idx < count; ++idx) { QTextCharFormat format = theme.format(keys[idx]); addTextFormat(strings[idx], keys[idx], format); } } void EditorPage::populateFontList(bool onlyMonospaced) { ui->fontCombo->clear(); #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) QStringList fontFamilies = fontDatabase->families(); #else QStringList fontFamilies = QFontDatabase::families(); #endif foreach (QString family, fontFamilies) { #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) if (onlyMonospaced && !fontDatabase->isFixedPitch(family)) #else if (onlyMonospaced && !QFontDatabase::isFixedPitch(family)) #endif continue; ui->fontCombo->addItem(family); } } void EditorPage::populateThemeList(const QString& sel) { /* managing the combo box send parasite signals */ disconnect(ui->themeCombo, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateTheme(QString))); QMap<QString, Theme*>::const_iterator itr = mThemes.begin(); QList<QString> list = itr.value()->availableThemes(); int i = 0; foreach (QString th, mThemes.keys()) { if (list.indexOf(th) < 0) list.append(th); } ui->themeCombo->clear(); foreach (QString themeName, list) { ui->themeCombo->addItem(themeName); if (sel == themeName) ui->themeCombo->setCurrentIndex(i); else i++; } connect(ui->themeCombo, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateTheme(QString))); } void EditorPage::store(Manager* s) { s->beginGroup("IDE/editor"); s->setValue("spaceIndent", ui->spaceIndent->isChecked()); s->setValue("indentWidth", ui->indentWidth->value()); s->setValue("stepForwardEvaluation", ui->stepForwardEvaluation->isChecked()); s->setValue("lineWrap", ui->editorLineWrap->isChecked()); s->setValue("disableBlinkingCursor", ui->disableBlinkingCursor->isChecked()); s->setValue("insertMatchingTokens", ui->insertMatchingTokens->isChecked()); s->setValue("highlightCurrentLine", ui->highlightCurrentLine->isChecked()); s->setValue("highlightBracketContents", ui->highlightBracketContents->isChecked()); s->setValue("inactiveEditorFadeAlpha", ui->inactiveEditorFadeAlpha->value()); s->setValue("useComboBox", ui->useComboBox->isChecked()); s->setValue("useComboBoxWhenSplitting", ui->useComboBoxWhenSplitting->isChecked()); s->setValue("blinkDuration", ui->blinkDuration->value()); s->beginGroup("font"); QString fontFamily = ui->fontCombo->currentText(); if (!fontFamily.isEmpty()) s->setValue("family", fontFamily); s->setValue("size", ui->fontSize->value()); s->setValue("antialias", ui->fontAntialias->checkState()); s->endGroup(); s->setValue("theme", ui->themeCombo->currentText()); s->endGroup(); s->beginGroup("IDE/postWindow"); s->setValue("scrollback", ui->postWindowScrollback->value()); s->setValue("lineWrap", ui->postWindowLineWrap->isChecked()); s->endGroup(); foreach (Theme* theme, mThemes) { if (ui->themeCombo->findText(theme->name()) > 0) theme->save(); else theme->remove(); } ui->themeCopyBtn->setDisabled(false); s->updateTheme(); } void EditorPage::onCurrentTabChanged(int) { if (ui->tabs->currentWidget() == ui->colorsTab) updateFontPreview(); } void EditorPage::onMonospaceToggle(bool onlyMonospaced) { QString fontFamily = ui->fontCombo->currentText(); bool signals_blocked = ui->fontCombo->blockSignals(true); populateFontList(onlyMonospaced); if (!fontFamily.isEmpty()) { int fontFamilyIndex = ui->fontCombo->findText(fontFamily, Qt::MatchFixedString); if (fontFamilyIndex == -1) fontFamilyIndex = 0; ui->fontCombo->setCurrentIndex(fontFamilyIndex); } ui->fontCombo->blockSignals(signals_blocked); updateFontPreview(); } void EditorPage::updateFontPreview() { if (ui->tabs->currentWidget() == ui->colorsTab) ui->textFormats->setFont(constructFont()); } QFont EditorPage::constructFont() { QString family = ui->fontCombo->currentText(); int size = ui->fontSize->value(); bool antialias = (ui->fontAntialias->checkState() == Qt::Checked); QFont font(family, size); font.setStyleHint(QFont::TypeWriter); if (!antialias) font.setStyleStrategy(QFont::StyleStrategy(font.styleStrategy() | QFont::NoAntialias)); return font; } QTreeWidgetItem* EditorPage::addTextFormat(const QString& name, const QString& key, const QTextCharFormat& format, const QTextCharFormat& defaultFormat) { QTreeWidgetItem* item = new QTreeWidgetItem(ui->textFormats); item->setText(0, name); item->setData(0, TextFormatConfigKeyRole, key); item->setData(0, TextFormatRole, QVariant::fromValue(format)); item->setData(0, DefaultTextFormatRole, QVariant::fromValue(defaultFormat)); updateTextFormatDisplay(item); return item; } void EditorPage::updateTextFormatDisplay(QTreeWidgetItem* item) { QTextCharFormat format = item->data(0, DefaultTextFormatRole).value<QTextCharFormat>(); format.merge(item->data(0, TextFormatRole).value<QTextCharFormat>()); QBrush fg = format.foreground(); if (fg != Qt::NoBrush) item->setForeground(0, fg); else item->setData(0, Qt::ForegroundRole, QVariant()); QBrush bg = format.background(); if (bg != Qt::NoBrush) item->setBackground(0, bg); else item->setData(0, Qt::BackgroundRole, QVariant()); QFont f; if (format.hasProperty(QTextFormat::FontItalic)) f.setItalic(format.fontItalic()); if (format.hasProperty(QTextFormat::FontWeight)) f.setWeight(static_cast<QFont::Weight>(format.fontWeight())); item->setFont(0, f); } QTextCharFormat EditorPage::constructTextFormat() { QTextCharFormat format; QBrush fg = ui->fgPicker->brush(); if (ui->fgPicker->isEnabled() && fg.style() != Qt::NoBrush) format.setForeground(fg); QBrush bg = ui->bgPicker->brush(); if (ui->bgPicker->isEnabled() && bg.style() != Qt::NoBrush) format.setBackground(bg); if (ui->italicOption->isEnabled() && ui->italicOption->isChecked()) format.setFontItalic(true); if (ui->boldOption->isEnabled() && ui->boldOption->isChecked()) format.setFontWeight(QFont::Bold); return format; } void EditorPage::updateTextFormatEdit() { QTreeWidgetItem* item = ui->textFormats->currentItem(); bool canEdit = item && item->data(0, TextFormatConfigKeyRole).isValid(); ui->textFormatEdit->setEnabled(canEdit); if (!canEdit) { ui->fgPicker->setBrush(QBrush()); ui->bgPicker->setBrush(QBrush()); ui->italicOption->setChecked(false); ui->italicOption->setChecked(false); } else { QTextCharFormat format = item->data(0, TextFormatRole).value<QTextCharFormat>(); int enable = true; ui->fgPicker->setBrush(format.foreground()); ui->bgPicker->setBrush(format.background()); ui->italicOption->setChecked(format.fontItalic()); ui->boldOption->setChecked(format.fontWeight() == QFont::Bold); if (item->data(0, TextFormatConfigKeyRole).toString() == "currentLine") enable = false; ui->fgPicker->setEnabled(enable); ui->italicOption->setEnabled(enable); ui->boldOption->setEnabled(enable); ui->fgClearBtn->setEnabled(enable); } } void EditorPage::updateTextFormatDisplay() { QTreeWidgetItem* item = ui->textFormats->currentItem(); bool canEdit = item && item->data(0, TextFormatConfigKeyRole).isValid(); if (!canEdit) return; QTextCharFormat format = constructTextFormat(); item->setData(0, TextFormatRole, QVariant::fromValue(format)); if (item != mCommonTextFormatItem) updateTextFormatDisplay(item); else updateTextFormatDisplayCommons(); Theme* theme = mThemes.value(ui->themeCombo->currentText()); theme->setFormat(item->data(0, TextFormatConfigKeyRole).toString(), format); } void EditorPage::updateTextFormatDisplayCommons() { QTextCharFormat commonFormat = mCommonTextFormatItem->data(0, TextFormatRole).value<QTextCharFormat>(); QPalette palette; QBrush fg = commonFormat.foreground(); if (fg != Qt::NoBrush) palette.setBrush(QPalette::Text, fg); QBrush bg = commonFormat.background(); if (bg != Qt::NoBrush) palette.setBrush(QPalette::Base, bg); ui->textFormats->setPalette(palette); } void EditorPage::dialogCopyTheme() { bool ok; QString themeName = ui->themeCombo->currentText(); QString newThemeName = QInputDialog::getText(this, tr("Copy theme"), tr("copy the selected theme:"), QLineEdit::Normal, themeName, &ok); if (ok && !newThemeName.isEmpty()) { QMap<QString, Theme*>::const_iterator i = mThemes.begin(); QList<QString> themes = i.value()->availableThemes(); if (themes.indexOf(newThemeName) >= 0) { QMessageBox::information(this, tr("Theme Already Existing"), tr("This theme already exists, pick another one\n")); } else { Theme* theme = new Theme(newThemeName, themeName); mThemes.insert(newThemeName, theme); ui->themeCombo->addItem(newThemeName); ui->themeCombo->setCurrentIndex(ui->themeCombo->findText(newThemeName)); ui->themeCopyBtn->setDisabled(true); updateTheme(newThemeName); } } } void EditorPage::deleteTheme() { ui->themeCombo->removeItem(ui->themeCombo->currentIndex()); } }} // namespace ScIDE::Settings
18,473
C++
.cpp
391
39.378517
114
0.657789
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
30,048
sclang_page.cpp
supercollider_supercollider/editors/sc-ide/widgets/settings/sclang_page.cpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <QDebug> #include <QMessageBox> #include <QInputDialog> #include <QFile> #include <fstream> #include "sclang_page.hpp" #include "ui_settings_sclang.h" #include "../../core/settings/manager.hpp" #include "../../core/util/standard_dirs.hpp" #include <yaml-cpp/yaml.h> namespace ScIDE { namespace Settings { SclangPage::SclangPage(QWidget* parent): QWidget(parent), ui(new Ui::SclangConfigPage) { ui->setupUi(this); ui->sclang_add_configfile->setIcon(QIcon::fromTheme("list-add")); ui->sclang_remove_configfile->setIcon(QIcon::fromTheme("list-remove")); ui->sclang_add_include->setIcon(QIcon::fromTheme("list-add")); ui->sclang_remove_include->setIcon(QIcon::fromTheme("list-remove")); ui->sclang_add_exclude->setIcon(QIcon::fromTheme("list-add")); ui->sclang_remove_exclude->setIcon(QIcon::fromTheme("list-remove")); ui->runtimeDir->setFileMode(QFileDialog::Directory); connect(ui->activeConfigFileComboBox, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(changeSelectedLanguageConfig(const QString&))); connect(ui->sclang_add_configfile, SIGNAL(clicked()), this, SLOT(dialogCreateNewConfigFile())); connect(ui->sclang_remove_configfile, SIGNAL(clicked()), this, SLOT(dialogDeleteCurrentConfigFile())); connect(ui->sclang_add_include, SIGNAL(clicked()), this, SLOT(addIncludePath())); connect(ui->sclang_add_exclude, SIGNAL(clicked()), this, SLOT(addExcludePath())); connect(ui->sclang_remove_include, SIGNAL(clicked()), this, SLOT(removeIncludePath())); connect(ui->sclang_remove_exclude, SIGNAL(clicked()), this, SLOT(removeExcludePath())); connect(ui->sclang_post_inline_warnings, SIGNAL(stateChanged(int)), this, SLOT(markSclangConfigDirty())); connect(ui->sclang_exclude_default_paths, SIGNAL(stateChanged(int)), this, SLOT(markSclangConfigDirty())); } SclangPage::~SclangPage() { delete ui; } void SclangPage::load(Manager* s) { s->beginGroup("IDE/interpreter"); ui->autoStart->setChecked(s->value("autoStart").toBool()); ui->runtimeDir->setText(s->value("runtimeDir").toString()); QStringList availConfigFiles = availableLanguageConfigFiles(); QString configSelectedLanguageConfigFile = s->value("configFile").toString(); ui->activeConfigFileComboBox->clear(); ui->activeConfigFileComboBox->addItems(availConfigFiles); int index = availConfigFiles.indexOf(configSelectedLanguageConfigFile); if (index != -1) ui->activeConfigFileComboBox->setCurrentIndex(index); selectedLanguageConfigFile = configSelectedLanguageConfigFile; // Happens after setting the combobox entries, since // the code triggers stateChanged event. s->endGroup(); readLanguageConfig(); } void SclangPage::store(Manager* s) { s->beginGroup("IDE/interpreter"); s->setValue("autoStart", ui->autoStart->isChecked()); s->setValue("runtimeDir", ui->runtimeDir->text()); s->setValue("configFile", ui->activeConfigFileComboBox->currentText()); s->endGroup(); writeLanguageConfig(); } void SclangPage::addIncludePath() { QString path = QFileDialog::getExistingDirectory(this, tr("ScLang include directories")); if (path.size()) ui->sclang_include_directories->addItem(path); sclangConfigDirty = true; } void SclangPage::removeIncludePath() { foreach (QListWidgetItem* item, ui->sclang_include_directories->selectedItems()) { ui->sclang_include_directories->removeItemWidget(item); delete item; } sclangConfigDirty = true; } void SclangPage::addExcludePath() { QString path = QFileDialog::getExistingDirectory(this, tr("ScLang exclude directories")); if (path.size()) ui->sclang_exclude_directories->addItem(path); sclangConfigDirty = true; } void SclangPage::removeExcludePath() { foreach (QListWidgetItem* item, ui->sclang_exclude_directories->selectedItems()) { ui->sclang_exclude_directories->removeItemWidget(item); delete item; } sclangConfigDirty = true; } void SclangPage::changeSelectedLanguageConfig(const QString& configPath) { selectedLanguageConfigFile = configPath; readLanguageConfig(); } void SclangPage::readLanguageConfig() { // LATER: watch for changes QString configFile = languageConfigFile(); QFileInfo configFileInfo(configFile); const bool configFileExists = configFileInfo.exists(); if (!configFileExists) return; using namespace YAML; try { std::ifstream fin(configFile.toStdString()); Node doc = YAML::Load(fin); if (doc) { const Node& includePaths = doc["includePaths"]; if (includePaths && includePaths.IsSequence()) { ui->sclang_include_directories->clear(); for (Node const& pathNode : includePaths) { if (!pathNode.IsScalar()) continue; std::string path = pathNode.as<std::string>(); if (!path.empty()) ui->sclang_include_directories->addItem(QString(path.c_str())); } } const Node& excludePaths = doc["excludePaths"]; if (excludePaths && excludePaths.IsSequence()) { ui->sclang_exclude_directories->clear(); for (Node const& pathNode : excludePaths) { if (!pathNode.IsScalar()) continue; std::string path = pathNode.as<std::string>(); if (!path.empty()) ui->sclang_exclude_directories->addItem(QString(path.c_str())); } } const Node& inlineWarnings = doc["postInlineWarnings"]; if (inlineWarnings) { try { bool postInlineWarnings = inlineWarnings.as<bool>(); ui->sclang_post_inline_warnings->setChecked(postInlineWarnings); } catch (...) { qDebug() << "Warning: Cannot parse config file entry \"postInlineWarnings\""; } } const Node& excludeDefaultPaths = doc["excludeDefaultPaths"]; if (excludeDefaultPaths) { try { bool excludeDefaultPathsBool = excludeDefaultPaths.as<bool>(); ui->sclang_exclude_default_paths->setChecked(excludeDefaultPathsBool); } catch (...) { qDebug() << "Warning: Cannot parse config file entry \"excludeDefaultPaths\""; } } } } catch (std::exception&) {} sclangConfigDirty = false; } void SclangPage::writeLanguageConfig() { if (!sclangConfigDirty) return; using namespace YAML; using std::ofstream; Emitter out; out.SetIndent(4); out.SetMapFormat(Block); out.SetSeqFormat(Block); out.SetBoolFormat(TrueFalseBool); out << BeginMap; out << Key << "includePaths"; out << Value << BeginSeq; for (int i = 0; i != ui->sclang_include_directories->count(); ++i) out << ui->sclang_include_directories->item(i)->text().toStdString(); out << EndSeq; out << Key << "excludePaths"; out << Value << BeginSeq; for (int i = 0; i != ui->sclang_exclude_directories->count(); ++i) out << ui->sclang_exclude_directories->item(i)->text().toStdString(); out << EndSeq; out << Key << "postInlineWarnings"; out << Value << (ui->sclang_post_inline_warnings->checkState() == Qt::Checked); out << Key << "excludeDefaultPaths"; out << Value << (ui->sclang_exclude_default_paths->checkState() == Qt::Checked); out << EndMap; ofstream fout(languageConfigFile().toStdString().c_str()); fout << out.c_str(); QMessageBox::information(this, tr("Sclang configuration file updated"), tr("The SuperCollider language configuration has been updated. " "Reboot the interpreter to apply the changes.")); sclangConfigDirty = false; } QString SclangPage::languageConfigFile() { if (selectedLanguageConfigFile.isEmpty()) { selectedLanguageConfigFile = standardDirectory(ScConfigUserDir) + "/" + QStringLiteral("sclang_conf.yaml"); } return selectedLanguageConfigFile; } QStringList SclangPage::availableLanguageConfigFiles() { QDir qdir = QDir(standardDirectory(ScConfigUserDir)); QStringList fileFilters; fileFilters << "sclang_conf*.yaml"; QFileInfoList configFileList = qdir.entryInfoList(fileFilters); QStringList canonicalPaths; foreach (QFileInfo aFile, configFileList) { canonicalPaths.append(aFile.canonicalFilePath()); } return canonicalPaths; } void SclangPage::dialogCreateNewConfigFile() { bool ok; QString text = QInputDialog::getText(this, tr("New Configuration File"), tr("Create configuration file 'sclang_conf_*.yaml' with '*' replaced by:"), QLineEdit::Normal, QDir::home().dirName(), &ok); if (ok && !text.isEmpty()) { QString proposedLanguageConfigFile = standardDirectory(ScConfigUserDir) + "/sclang_conf_" + text + ".yaml"; if (QFile(proposedLanguageConfigFile).exists()) { QMessageBox::information(this, tr("File Already Exists"), tr("Configuration file already exists:\n%1").arg(proposedLanguageConfigFile)); } else { selectedLanguageConfigFile = proposedLanguageConfigFile; sclangConfigDirty = true; writeLanguageConfig(); int index = ui->activeConfigFileComboBox->count(); ui->activeConfigFileComboBox->addItem(selectedLanguageConfigFile); ui->activeConfigFileComboBox->setCurrentIndex(index); } } } void SclangPage::dialogDeleteCurrentConfigFile() { int ret = QMessageBox::warning(this, tr("Delete Configuration File"), tr("Are you sure you want to delete the following configuration file?\nThis action " "is immediate and cannot be undone.\n") + selectedLanguageConfigFile, QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel); if (ret == QMessageBox::Ok) { QString pathBeingRemoved = selectedLanguageConfigFile; QFile::remove(pathBeingRemoved); ui->activeConfigFileComboBox->removeItem(ui->activeConfigFileComboBox->findText(pathBeingRemoved)); if (ui->activeConfigFileComboBox->count() != 0) { ui->activeConfigFileComboBox->setCurrentIndex(0); } } } }} // namespace ScIDE::Settings
11,628
C++
.cpp
240
39.8125
119
0.658752
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,049
style.cpp
supercollider_supercollider/editors/sc-ide/widgets/style/style.cpp
/* SuperCollider Qt IDE Copyright (c) 2010-2012 Jakob Leben Copyright (c) 2012 Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "style.hpp" #include "../../core/util/color.hpp" #include <cmath> #include <QPainter> #include <QStyleOption> #include <QDockWidget> #include <QStyleOptionTab> #include <QTabBar> #include <QToolButton> #include <QLayout> #include <QDebug> #ifdef SC_USE_QTWEBENGINE # include <QWebEngineView> #endif // SC_USE_QTWEBENGINE namespace ScIDE { inline bool Style::shouldNotHandle(const QWidget* widget) const { return widget ? widget->window()->windowType() == Qt::Dialog : false; } void Style::polish(QWidget* widget) { if (shouldNotHandle(widget)) { QProxyStyle::polish(widget); widget->update(); widget->updateGeometry(); if (widget->layout()) widget->layout()->invalidate(); return; } if (qobject_cast<QDockWidget*>(widget)) { return; } if ((qobject_cast<QTabBar*>(widget)) || (qobject_cast<QToolButton*>(widget))) { widget->setAttribute(Qt::WA_Hover, true); } else QProxyStyle::polish(widget); } void Style::unpolish(QWidget* widget) { QProxyStyle::unpolish(widget); } void Style::drawComplexControl(ComplexControl control, const QStyleOptionComplex* option, QPainter* painter, const QWidget* widget) const { if (shouldNotHandle(widget)) { QProxyStyle::drawComplexControl(control, option, painter, widget); return; } switch (control) { #ifdef SC_USE_QTWEBENGINE // FIXME: this is a workaround for the WebKit bug #104116 (or a variation on it). case QStyle::CC_ScrollBar: { if (qobject_cast<const QWebEngineView*>(widget) != 0 && option->type == QStyleOption::SO_Slider) { // WebKit tries to hide scrollbars, but mistakenly hides QWebView - NULL-ify styleObject to prevent. const QStyleOptionSlider* optSlider = static_cast<const QStyleOptionSlider*>(option); QStyleOptionSlider opt2(*optSlider); opt2.styleObject = NULL; QProxyStyle::drawComplexControl(control, &opt2, painter, widget); return; } } #endif // SC_USE_QTWEBENGINE case QStyle::CC_ToolButton: { // TODO: We only draw either text, or icon, or arrow const QToolButton* toolBtn = qobject_cast<const QToolButton*>(widget); if (!toolBtn) break; Q_ASSERT(toolBtn); const QStyleOptionToolButton* toolOption = static_cast<const QStyleOptionToolButton*>(option); painter->save(); QRect r = option->rect; if (option->state & QStyle::State_On) { painter->setBrush(option->palette.color(QPalette::Dark)); painter->setPen(option->palette.color(QPalette::Shadow)); painter->drawRect(r.adjusted(0, 0, -1, -1)); } else { bool highlight = option->state & QStyle::State_MouseOver; if (highlight) { QColor fill = option->palette.color(QPalette::Button); painter->setBrush(fill); painter->setPen(Qt::NoPen); painter->drawRect(r.adjusted(0, 0, 0, -1)); } if (qobject_cast<QTabBar*>(toolBtn->parent())) { if (!highlight) { QColor fill = option->palette.color(QPalette::Mid); painter->setBrush(fill); painter->setPen(Qt::NoPen); painter->drawRect(r.adjusted(0, 0, 0, -1)); } if (toolBtn->arrowType() == Qt::LeftArrow) { painter->setPen(option->palette.color(QPalette::Shadow)); painter->drawLine(option->rect.topLeft(), option->rect.bottomLeft()); } } } painter->restore(); QIcon icon = toolOption->icon; if (!icon.isNull()) { QIcon::Mode iconMode = option->state & QStyle::State_Enabled ? (option->state & QStyle::State_MouseOver ? QIcon::Active : QIcon::Normal) : QIcon::Disabled; QIcon::State iconState = option->state & QStyle::State_Selected ? QIcon::On : QIcon::Off; QPixmap pixmap = icon.pixmap(toolOption->iconSize, iconMode, iconState); QRect pixRect; pixRect.setSize(QSize(16, 16)); pixRect.moveCenter(option->rect.center()); painter->drawPixmap(pixRect, pixmap); } else { QStyle::PrimitiveElement elem = Style::PE_CustomBase; switch (toolBtn->arrowType()) { case Qt::LeftArrow: elem = PE_IndicatorArrowLeft; break; case Qt::RightArrow: elem = PE_IndicatorArrowRight; break; case Qt::DownArrow: elem = PE_IndicatorArrowDown; break; case Qt::UpArrow: elem = PE_IndicatorArrowUp; break; default: break; } if (elem != Style::PE_CustomBase) { drawPrimitive(elem, option, painter, widget); } else if (!toolOption->text.isEmpty()) { painter->drawText(toolOption->rect, Qt::AlignCenter | Qt::TextShowMnemonic, toolOption->text); } } return; } default: break; } QProxyStyle::drawComplexControl(control, option, painter, widget); } void Style::drawControl(ControlElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const { if (shouldNotHandle(widget)) { QProxyStyle::drawControl(element, option, painter, widget); return; } switch (element) { case QStyle::CE_TabBarTab: { const QStyleOptionTab* tabOption = static_cast<const QStyleOptionTab*>(option); painter->save(); bool selected = tabOption->state & QStyle::State_Selected; bool mouseOver = tabOption->state & QStyle::State_MouseOver; QColor background_color; if (selected) { background_color = option->palette.color(QPalette::Window); } else { background_color = option->palette.color(QPalette::Mid); if (mouseOver) { background_color = color::lighten(background_color, 10); } } QColor text_color = option->palette.color(QPalette::WindowText); if (!selected) { text_color = color::interpolate(text_color, background_color, kDeselectedTabBlend); } // Draw tab rectangle. QRect rect = tabOption->rect; painter->setBrush(background_color); painter->setPen(Qt::NoPen); painter->drawRect(rect); // For inactive tabs, add a thin dark line to the right side for visual // separation. if (!selected && !(tabOption->selectedPosition == QStyleOptionTab::NextIsSelected) && !(tabOption->position == QStyleOptionTab::End) && !(tabOption->position == QStyleOptionTab::OnlyOneTab)) { QPen pen(option->palette.color(QPalette::Shadow), 1); painter->setPen(pen); painter->drawLine(rect.topRight(), rect.bottomRight()); } // If the contrast between active and inactive tabs is stupidly low, // then use an overline to distinguish them. This happens when the user // sets a really dark background color. int window_mid_value_difference = abs(option->palette.color(QPalette::Window).value() - option->palette.color(QPalette::Mid).value()); if (selected && window_mid_value_difference < 20) { painter->setBrush(text_color); painter->drawRect(rect.left(), rect.top(), rect.width(), 2); } painter->restore(); // Draw icon. if (!tabOption->icon.isNull()) { QPixmap pixmap = tabOption->icon.pixmap(tabOption->iconSize); QRect iconRect; iconRect.setSize(QSize(14, 14)); iconRect.moveCenter(tabOption->rect.center()); int lmargin = 5; if (tabOption->leftButtonSize.width() > 0) lmargin += tabOption->leftButtonSize.width() + 4; iconRect.moveLeft(tabOption->rect.left() + lmargin); painter->drawPixmap(iconRect, pixmap); } // Draw text. QRect textRect = subElementRect(QStyle::SE_TabBarTabText, option, widget); painter->save(); if (selected) { QFont font; font.setBold(true); painter->setFont(font); } painter->setPen(text_color); painter->drawText(textRect, Qt::AlignCenter | Qt::TextShowMnemonic, tabOption->text); painter->restore(); return; } case CE_Splitter: painter->save(); painter->setPen(Qt::NoPen); painter->setBrush(option->palette.color(QPalette::Shadow)); painter->drawRect(option->rect); painter->restore(); return; default: break; } QProxyStyle::drawControl(element, option, painter, widget); } void Style::drawPrimitive(PrimitiveElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const { if (shouldNotHandle(widget)) { QProxyStyle::drawPrimitive(element, option, painter, widget); return; } switch (element) { case QStyle::PE_IndicatorTabTear: return; case QStyle::PE_FrameTabBarBase: { const QTabBar* tabBar = qobject_cast<const QTabBar*>(widget); painter->save(); painter->setPen(Qt::NoPen); if (tabBar) { painter->setBrush(option->palette.color(QPalette::Mid)); painter->drawRect(tabBar->rect()); } painter->setBrush(option->palette.color(QPalette::Shadow)); painter->drawRect(option->rect); painter->restore(); return; } case PE_IndicatorDockWidgetResizeHandle: painter->save(); painter->setPen(Qt::NoPen); painter->setBrush(option->palette.color(QPalette::Shadow)); painter->drawRect(option->rect); painter->restore(); return; case PE_IndicatorTabClose: { QPoint center = option->rect.center(); int rect_width = option->rect.width(); // a = half of the width of the X. int a = rect_width * 0.5f * 0.4f; float cx = center.x() + 0.5f; float cy = center.y() + 0.5f; QColor x_color = option->palette.color(QPalette::WindowText); if (!(option->state & QStyle::State_Selected)) { QColor background = option->palette.color(QPalette::Mid); x_color = color::interpolate(x_color, background, kDeselectedTabBlend); } if ((option->state & State_Enabled) && (option->state & State_MouseOver)) { x_color = color::lighten(x_color, 40); } float thickness = 1.5f; // Sometimes this needs adjusting for symmetrical results on different // line thicknesses. float extend = 0.0f; QPen pen(x_color, thickness); painter->save(); painter->setRenderHint(QPainter::Antialiasing, true); painter->setPen(pen); painter->drawLine(QLineF(cx - a, cy - a, cx + a + extend, cy + a + extend)); painter->drawLine(QLineF(cx - a, cy + a, cx + a + extend, cy - a - extend)); painter->restore(); return; } default: QProxyStyle::drawPrimitive(element, option, painter, widget); } } QRect Style::subElementRect(SubElement element, const QStyleOption* option, const QWidget* widget) const { if (shouldNotHandle(widget)) { return QProxyStyle::subElementRect(element, option, widget); } switch (element) { // NOTE: Assuming horizontal tab bar direction case QStyle::SE_TabBarTabRightButton: { QRect r; r.setSize(QSize(16, 16)); r.moveCenter(option->rect.center()); r.moveRight(option->rect.right() + 1 - 5); return r; } case QStyle::SE_TabBarTabLeftButton: { QRect r; r.setSize(QSize(16, 16)); r.moveCenter(option->rect.center()); r.moveLeft(option->rect.left() + 5); return r; } case QStyle::SE_TabBarTabText: { const auto* tabOption = static_cast<const QStyleOptionTab*>(option); int lMargin = 5; if (tabOption->leftButtonSize.width() > 0) lMargin += tabOption->leftButtonSize.width() + 4; if (!tabOption->icon.isNull()) lMargin += tabOption->iconSize.width() + 4; int rMargin = 5; if (tabOption->rightButtonSize.width() > 0) rMargin += tabOption->rightButtonSize.width() + 4; QRect r = option->rect; r.adjust(lMargin, 0, -rMargin, 0); return r; } default: return QProxyStyle::subElementRect(element, option, widget); } } QSize Style::sizeFromContents(ContentsType type, const QStyleOption* option, const QSize& contentsSize, const QWidget* widget) const { if (shouldNotHandle(widget)) { return QProxyStyle::sizeFromContents(type, option, contentsSize, widget); } switch (type) { case QStyle::CT_TabBarTab: return contentsSize; //+ QSize(10, 10); case QStyle::CT_ToolButton: return contentsSize + QSize(10, 10); default: return QProxyStyle::sizeFromContents(type, option, contentsSize, widget); } } int Style::pixelMetric(PixelMetric metric, const QStyleOption* option, const QWidget* widget) const { if (shouldNotHandle(widget)) { return QProxyStyle::pixelMetric(metric, option, widget); } switch (metric) { case QStyle::PM_DockWidgetFrameWidth: return 2; case QStyle::PM_DockWidgetSeparatorExtent: case QStyle::PM_SplitterWidth: return 1; case QStyle::PM_TabBarBaseHeight: return 0; case QStyle::PM_TabBarBaseOverlap: return 1; case QStyle::PM_TabBarTabShiftHorizontal: case QStyle::PM_TabBarTabShiftVertical: return 0; case QStyle::PM_TabBarTabHSpace: case QStyle::PM_TabBarTabVSpace: return 10; case QStyle::PM_TabBarTabOverlap: return 0; case QStyle::PM_TabBarIconSize: return 16; case PM_TabCloseIndicatorHeight: case PM_TabCloseIndicatorWidth: return 16; case PM_TabBarScrollButtonWidth: return 24; case PM_TabBar_ScrollButtonOverlap: return 1; case PM_MenuButtonIndicator: return 0; default: break; } return QProxyStyle::pixelMetric(metric, option, widget); } int Style::styleHint(StyleHint hint, const QStyleOption* option, const QWidget* widget, QStyleHintReturn* returnData) const { if (shouldNotHandle(widget)) { return QProxyStyle::styleHint(hint, option, widget, returnData); } switch (hint) { case SH_TabBar_PreferNoArrows: return 0; case SH_TabBar_ElideMode: return Qt::ElideNone; default: break; } return QProxyStyle::styleHint(hint, option, widget, returnData); } } // namespace ScIDE
16,116
C++
.cpp
403
31.094293
112
0.617754
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
30,050
SCDocPrim.cpp
supercollider_supercollider/SCDoc/SCDocPrim.cpp
/************************************************************************ * * Copyright 2012 Jonatan Liljedahl <lijon@kymatica.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "GC.h" #include "PyrKernel.h" #include "PyrPrimitive.h" #include "PyrSymbol.h" #include "SCBase.h" #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <cerrno> // extern "C" { #include "SCDoc.h" //} PyrSymbol* s_scdoc_node; static void _doc_traverse(struct VMGlobals* g, DocNode* n, PyrObject* parent, PyrSlot* slot) { PyrObject* result = instantiateObject(g->gc, s_scdoc_node->u.classobj, 0, false, true); SetObject(slot, result); if (parent) { assert(isKindOf(parent, class_array)); g->gc->GCWriteNew(parent, result); // we know result is white so we can use GCWriteNew parent->size++; } // initialise the instance vars PyrSymbol* id = getsym(n->id); SetSymbol(result->slots, id); // id // text if (n->text) { PyrObject* str = (PyrObject*)newPyrString(g->gc, n->text, 0, true); SetObject(result->slots + 1, str); g->gc->GCWriteNew(result, str); // we know str is white so we can use GCWriteNew } // children if (n->n_childs) { PyrObject* array = newPyrArray(g->gc, n->n_childs, 0, true); SetObject(result->slots + 2, array); g->gc->GCWriteNew(result, array); // we know array is white so we can use GCWriteNew for (int i = 0; i < n->n_childs; i++) { _doc_traverse(g, n->children[i], array, array->slots + i); } } // makeDiv, notPrivOnly, sort remain nil for now } int prSCDoc_ParseFile(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; char filename[PATH_MAX]; int mode, err; a = g->sp - 2; b = g->sp - 1; c = g->sp; err = slotStrVal(b, filename, PATH_MAX); if (err) return err; err = slotIntVal(c, &mode); if (err) return err; DocNode* n = scdoc_parse_file(filename, mode); if (n) { // doc_node_dump(n); _doc_traverse(g, n, NULL, a); doc_node_free_tree(n); } else { SetNil(a); } return errNone; } void initSCDocPrimitives() { int base, index = 0; s_scdoc_node = getsym("SCDocNode"); base = nextPrimitiveIndex(); definePrimitive(base, index++, "_SCDoc_ParseFile", prSCDoc_ParseFile, 3, 0); }
3,098
C++
.cpp
88
30.625
94
0.615642
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,051
lex.scdoc.cpp
supercollider_supercollider/SCDoc/lex.scdoc.cpp
#line 2 "lex.scdoc.cpp" #line 4 "lex.scdoc.cpp" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define yy_create_buffer scdoc_create_buffer #define yy_delete_buffer scdoc_delete_buffer #define yy_scan_buffer scdoc_scan_buffer #define yy_scan_string scdoc_scan_string #define yy_scan_bytes scdoc_scan_bytes #define yy_init_buffer scdoc_init_buffer #define yy_flush_buffer scdoc_flush_buffer #define yy_load_buffer_state scdoc_load_buffer_state #define yy_switch_to_buffer scdoc_switch_to_buffer #define yypush_buffer_state scdocpush_buffer_state #define yypop_buffer_state scdocpop_buffer_state #define yyensure_buffer_stack scdocensure_buffer_stack #define yy_flex_debug scdoc_flex_debug #define yyin scdocin #define yyleng scdocleng #define yylex scdoclex #define yylineno scdoclineno #define yyout scdocout #define yyrestart scdocrestart #define yytext scdoctext #define yywrap scdocwrap #define yyalloc scdocalloc #define yyrealloc scdocrealloc #define yyfree scdocfree #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 6 #define YY_FLEX_SUBMINOR_VERSION 4 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif #ifdef yy_create_buffer #define scdoc_create_buffer_ALREADY_DEFINED #else #define yy_create_buffer scdoc_create_buffer #endif #ifdef yy_delete_buffer #define scdoc_delete_buffer_ALREADY_DEFINED #else #define yy_delete_buffer scdoc_delete_buffer #endif #ifdef yy_scan_buffer #define scdoc_scan_buffer_ALREADY_DEFINED #else #define yy_scan_buffer scdoc_scan_buffer #endif #ifdef yy_scan_string #define scdoc_scan_string_ALREADY_DEFINED #else #define yy_scan_string scdoc_scan_string #endif #ifdef yy_scan_bytes #define scdoc_scan_bytes_ALREADY_DEFINED #else #define yy_scan_bytes scdoc_scan_bytes #endif #ifdef yy_init_buffer #define scdoc_init_buffer_ALREADY_DEFINED #else #define yy_init_buffer scdoc_init_buffer #endif #ifdef yy_flush_buffer #define scdoc_flush_buffer_ALREADY_DEFINED #else #define yy_flush_buffer scdoc_flush_buffer #endif #ifdef yy_load_buffer_state #define scdoc_load_buffer_state_ALREADY_DEFINED #else #define yy_load_buffer_state scdoc_load_buffer_state #endif #ifdef yy_switch_to_buffer #define scdoc_switch_to_buffer_ALREADY_DEFINED #else #define yy_switch_to_buffer scdoc_switch_to_buffer #endif #ifdef yypush_buffer_state #define scdocpush_buffer_state_ALREADY_DEFINED #else #define yypush_buffer_state scdocpush_buffer_state #endif #ifdef yypop_buffer_state #define scdocpop_buffer_state_ALREADY_DEFINED #else #define yypop_buffer_state scdocpop_buffer_state #endif #ifdef yyensure_buffer_stack #define scdocensure_buffer_stack_ALREADY_DEFINED #else #define yyensure_buffer_stack scdocensure_buffer_stack #endif #ifdef yylex #define scdoclex_ALREADY_DEFINED #else #define yylex scdoclex #endif #ifdef yyrestart #define scdocrestart_ALREADY_DEFINED #else #define yyrestart scdocrestart #endif #ifdef yylex_init #define scdoclex_init_ALREADY_DEFINED #else #define yylex_init scdoclex_init #endif #ifdef yylex_init_extra #define scdoclex_init_extra_ALREADY_DEFINED #else #define yylex_init_extra scdoclex_init_extra #endif #ifdef yylex_destroy #define scdoclex_destroy_ALREADY_DEFINED #else #define yylex_destroy scdoclex_destroy #endif #ifdef yyget_debug #define scdocget_debug_ALREADY_DEFINED #else #define yyget_debug scdocget_debug #endif #ifdef yyset_debug #define scdocset_debug_ALREADY_DEFINED #else #define yyset_debug scdocset_debug #endif #ifdef yyget_extra #define scdocget_extra_ALREADY_DEFINED #else #define yyget_extra scdocget_extra #endif #ifdef yyset_extra #define scdocset_extra_ALREADY_DEFINED #else #define yyset_extra scdocset_extra #endif #ifdef yyget_in #define scdocget_in_ALREADY_DEFINED #else #define yyget_in scdocget_in #endif #ifdef yyset_in #define scdocset_in_ALREADY_DEFINED #else #define yyset_in scdocset_in #endif #ifdef yyget_out #define scdocget_out_ALREADY_DEFINED #else #define yyget_out scdocget_out #endif #ifdef yyset_out #define scdocset_out_ALREADY_DEFINED #else #define yyset_out scdocset_out #endif #ifdef yyget_leng #define scdocget_leng_ALREADY_DEFINED #else #define yyget_leng scdocget_leng #endif #ifdef yyget_text #define scdocget_text_ALREADY_DEFINED #else #define yyget_text scdocget_text #endif #ifdef yyget_lineno #define scdocget_lineno_ALREADY_DEFINED #else #define yyget_lineno scdocget_lineno #endif #ifdef yyset_lineno #define scdocset_lineno_ALREADY_DEFINED #else #define yyset_lineno scdocset_lineno #endif #ifdef yywrap #define scdocwrap_ALREADY_DEFINED #else #define yywrap scdocwrap #endif #ifdef yyalloc #define scdocalloc_ALREADY_DEFINED #else #define yyalloc scdocalloc #endif #ifdef yyrealloc #define scdocrealloc_ALREADY_DEFINED #else #define yyrealloc scdocrealloc #endif #ifdef yyfree #define scdocfree_ALREADY_DEFINED #else #define yyfree scdocfree #endif #ifdef yytext #define scdoctext_ALREADY_DEFINED #else #define yytext scdoctext #endif #ifdef yyleng #define scdocleng_ALREADY_DEFINED #else #define yyleng scdocleng #endif #ifdef yyin #define scdocin_ALREADY_DEFINED #else #define yyin scdocin #endif #ifdef yyout #define scdocout_ALREADY_DEFINED #else #define yyout scdocout #endif #ifdef yy_flex_debug #define scdoc_flex_debug_ALREADY_DEFINED #else #define yy_flex_debug scdoc_flex_debug #endif #ifdef yylineno #define scdoclineno_ALREADY_DEFINED #else #define yylineno scdoclineno #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #ifndef SIZE_MAX #define SIZE_MAX (~(size_t)0) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ /* begin standard C++ headers. */ /* TODO: this is always defined, so inline it */ #define yyconst const #if defined(__GNUC__) && __GNUC__ >= 3 #define yynoreturn __attribute__((__noreturn__)) #else #define yynoreturn #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an * integer in range [0..255] for use as an array index. */ #define YY_SC_TO_UI(c) ((YY_CHAR) (c)) /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN (yy_start) = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START (((yy_start) - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE yyrestart( yyin ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif extern int yyleng; extern FILE *yyin, *yyout; #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do { \ int yyl;\ for ( yyl = n; yyl < yyleng; ++yyl )\ if ( yytext[yyl] == '\n' )\ --yylineno;\ }while(0) #define YY_LINENO_REWIND_TO(dst) \ do {\ const char *p;\ for ( p = yy_cp-1; p >= (dst); --p)\ if ( *p == '\n' )\ --yylineno;\ }while(0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = (yy_hold_char); \ YY_RESTORE_YY_MORE_OFFSET \ (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, (yytext_ptr) ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ int yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ int yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* Stack of input buffers. */ static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */ static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */ static YY_BUFFER_STATE * yy_buffer_stack = NULL; /**< Stack as an array. */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( (yy_buffer_stack) \ ? (yy_buffer_stack)[(yy_buffer_stack_top)] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)] /* yy_hold_char holds the character lost when yytext is formed. */ static char yy_hold_char; static int yy_n_chars; /* number of characters read into yy_ch_buf */ int yyleng; /* Points to current character in buffer. */ static char *yy_c_buf_p = NULL; static int yy_init = 0; /* whether we need to initialize */ static int yy_start = 0; /* start state number */ /* Flag which is used to allow yywrap()'s to do buffer switches * instead of setting up a fresh yyin. A bit of a hack ... */ static int yy_did_buffer_switch_on_eof; void yyrestart ( FILE *input_file ); void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer ); YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size ); void yy_delete_buffer ( YY_BUFFER_STATE b ); void yy_flush_buffer ( YY_BUFFER_STATE b ); void yypush_buffer_state ( YY_BUFFER_STATE new_buffer ); void yypop_buffer_state ( void ); static void yyensure_buffer_stack ( void ); static void yy_load_buffer_state ( void ); static void yy_init_buffer ( YY_BUFFER_STATE b, FILE *file ); #define YY_FLUSH_BUFFER yy_flush_buffer( YY_CURRENT_BUFFER ) YY_BUFFER_STATE yy_scan_buffer ( char *base, yy_size_t size ); YY_BUFFER_STATE yy_scan_string ( const char *yy_str ); YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len ); void *yyalloc ( yy_size_t ); void *yyrealloc ( void *, yy_size_t ); void yyfree ( void * ); #define yy_new_buffer yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer( yyin, YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer( yyin, YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define scdocwrap() (/*CONSTCOND*/1) #define YY_SKIP_YYWRAP typedef flex_uint8_t YY_CHAR; FILE *yyin = NULL, *yyout = NULL; typedef int yy_state_type; extern int yylineno; int yylineno = 1; extern char *yytext; #ifdef yytext_ptr #undef yytext_ptr #endif #define yytext_ptr yytext static yy_state_type yy_get_previous_state ( void ); static yy_state_type yy_try_NUL_trans ( yy_state_type current_state ); static int yy_get_next_buffer ( void ); static void yynoreturn yy_fatal_error ( const char* msg ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ (yytext_ptr) = yy_bp; \ yyleng = (int) (yy_cp - yy_bp); \ (yy_hold_char) = *yy_cp; \ *yy_cp = '\0'; \ (yy_c_buf_p) = yy_cp; #define YY_NUM_RULES 109 #define YY_END_OF_BUFFER 110 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static const flex_int16_t yy_accept[1313] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 110, 67, 56, 49, 57, 65, 67, 51, 68, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 68, 67, 66, 55, 48, 68, 65, 68, 55, 47, 57, 68, 91, 91, 87, 57, 88, 90, 92, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 92, 108, 108, 57, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 57, 108, 108, 63, 61, 62, 57, 59, 63, 51, 59, 56, 0, 0, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 65, 46, 51, 42, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 45, 66, 48, 65, 0, 0, 0, 0, 91, 91, 88, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 88, 90, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 106, 0, 0, 61, 61, 59, 0, 59, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 46, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 53, 54, 52, 45, 43, 0, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 107, 60, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 44, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 58, 64, 64, 64, 64, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 64, 0, 64, 64, 64, 64, 64, 64, 0, 64, 64, 64, 64, 64, 64, 64, 0, 64, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 64, 64, 0, 64, 64, 36, 64, 64, 64, 64, 64, 64, 64, 0, 64, 64, 30, 22, 38, 64, 29, 64, 64, 64, 64, 64, 64, 33, 64, 64, 64, 64, 0, 64, 0, 23, 64, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 89, 0, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 94, 102, 0, 0, 0, 0, 0, 97, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 64, 1, 64, 64, 36, 39, 64, 64, 64, 64, 64, 64, 64, 32, 64, 64, 30, 22, 38, 41, 0, 29, 64, 64, 64, 64, 64, 64, 33, 0, 64, 64, 64, 26, 64, 2, 23, 64, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 89, 69, 89, 89, 89, 89, 89, 89, 89, 0, 89, 89, 89, 89, 89, 89, 89, 70, 0, 0, 0, 0, 0, 0, 0, 100, 103, 0, 0, 0, 0, 96, 0, 0, 94, 102, 105, 0, 0, 0, 0, 97, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31, 64, 64, 1, 64, 64, 64, 64, 64, 64, 64, 64, 64, 32, 64, 0, 14, 64, 0, 64, 0, 0, 0, 34, 64, 64, 0, 26, 64, 2, 0, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 89, 69, 89, 89, 89, 89, 89, 89, 0, 82, 0, 89, 0, 0, 89, 89, 0, 70, 0, 0, 0, 95, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 98, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31, 0, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 64, 8, 14, 64, 9, 0, 4, 20, 10, 34, 64, 64, 3, 0, 28, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 89, 89, 89, 89, 89, 0, 89, 76, 82, 77, 0, 72, 78, 89, 89, 71, 0, 95, 0, 0, 0, 0, 0, 0, 0, 98, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 64, 64, 0, 64, 64, 64, 64, 35, 19, 27, 64, 8, 64, 9, 6, 4, 20, 10, 64, 64, 3, 37, 28, 91, 91, 91, 91, 91, 91, 91, 91, 89, 89, 0, 89, 89, 86, 89, 76, 77, 74, 72, 78, 89, 89, 71, 0, 0, 0, 0, 0, 99, 0, 0, 0, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 0, 64, 7, 0, 64, 64, 0, 35, 19, 27, 64, 64, 6, 0, 64, 37, 40, 91, 91, 91, 91, 91, 91, 91, 0, 89, 75, 0, 89, 86, 89, 74, 0, 89, 0, 0, 0, 99, 0, 0, 101, 104, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 64, 7, 13, 64, 0, 21, 64, 64, 11, 64, 91, 91, 91, 91, 73, 89, 75, 81, 0, 89, 79, 89, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 13, 64, 16, 21, 64, 0, 11, 64, 91, 91, 91, 73, 0, 81, 83, 89, 79, 89, 0, 0, 0, 0, 0, 0, 0, 17, 64, 16, 64, 24, 0, 91, 91, 84, 83, 89, 0, 0, 0, 0, 0, 17, 0, 64, 24, 12, 91, 84, 89, 80, 0, 0, 0, 25, 0, 12, 91, 0, 80, 0, 25, 18, 85, 18, 85, 0 } ; static const YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 6, 7, 8, 1, 9, 9, 7, 10, 11, 9, 9, 12, 9, 7, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 1, 9, 9, 9, 6, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 25, 32, 33, 34, 35, 36, 37, 38, 39, 25, 7, 40, 7, 1, 41, 1, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 51, 58, 59, 60, 61, 62, 63, 64, 65, 51, 7, 66, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static const YY_CHAR yy_meta[67] = { 0, 1, 2, 3, 3, 2, 1, 1, 1, 1, 4, 4, 5, 1, 6, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 1 } ; static const flex_int16_t yy_base[1321] = { 0, 0, 0, 65, 104, 143, 182, 222, 0, 288, 0, 353, 0, 79, 83, 413, 0, 4128, 4129, 478, 87, 118, 89, 4119, 72, 4111, 97, 4110, 109, 117, 102, 86, 144, 58, 119, 159, 146, 145, 175, 519, 346, 348, 476, 4058, 0, 514, 543, 557, 202, 4108, 4129, 566, 4129, 4129, 0, 605, 4129, 4129, 126, 4108, 4129, 665, 731, 536, 558, 605, 574, 661, 666, 667, 782, 727, 4106, 4129, 842, 4129, 109, 164, 158, 337, 354, 347, 350, 557, 344, 467, 665, 563, 638, 760, 4105, 786, 4129, 593, 4129, 166, 639, 0, 209, 0, 0, 790, 4111, 213, 4103, 456, 674, 728, 457, 470, 472, 530, 543, 739, 654, 554, 582, 776, 783, 602, 4051, 816, 848, 871, 852, 487, 4129, 4103, 4100, 735, 734, 789, 798, 827, 850, 653, 703, 864, 874, 875, 878, 761, 883, 880, 888, 890, 892, 895, 917, 903, 908, 911, 924, 791, 900, 920, 913, 934, 4106, 4098, 4046, 969, 0, 979, 950, 983, 997, 4096, 4095, 0, 0, 538, 963, 634, 664, 781, 888, 943, 933, 975, 976, 979, 765, 4093, 988, 990, 998, 1018, 1026, 1031, 1036, 1061, 1056, 1077, 1078, 1095, 1136, 1094, 4090, 0, 1102, 987, 971, 981, 993, 1060, 999, 1018, 1035, 1121, 1117, 1108, 1127, 1141, 1116, 1125, 1141, 1143, 1129, 1126, 1141, 1139, 1140, 1152, 1168, 1159, 1159, 1149, 1176, 1157, 1160, 1212, 4088, 4129, 1220, 4087, 1224, 1207, 1225, 4088, 0, 1196, 1198, 1217, 1218, 1218, 1207, 1225, 1212, 1210, 1206, 1213, 1213, 1214, 1216, 1224, 1229, 1261, 1237, 1265, 1240, 1233, 1227, 1244, 1238, 1295, 4079, 1269, 1270, 1274, 1289, 1287, 1286, 1288, 1295, 1308, 1294, 1296, 1300, 1313, 1312, 1317, 1314, 1315, 1321, 1322, 1327, 1338, 1326, 1341, 1342, 1344, 1348, 1349, 1359, 1352, 1362, 1371, 1372, 1379, 1380, 1378, 4129, 4129, 4129, 1399, 4129, 4072, 1362, 1381, 1368, 1377, 1396, 1380, 1375, 1383, 1395, 1401, 1403, 1413, 1393, 1428, 1433, 1434, 1441, 1475, 1466, 1479, 1488, 1497, 1522, 1518, 1524, 1540, 1560, 1565, 4129, 1560, 1417, 1425, 1439, 1452, 1477, 1523, 1518, 1545, 1545, 1557, 1564, 1563, 1561, 1574, 1578, 1580, 1568, 1582, 1592, 1575, 1576, 1585, 1586, 1592, 1602, 1598, 4129, 4129, 1593, 1611, 1600, 1617, 1599, 1615, 1622, 1624, 1615, 1610, 1613, 1612, 1616, 1629, 1630, 1635, 1639, 1622, 1636, 1645, 1627, 1633, 1638, 1644, 1647, 1657, 1653, 1663, 1656, 0, 1674, 1677, 1679, 1675, 4070, 1684, 1681, 1687, 1680, 1698, 1676, 1703, 1701, 1707, 1705, 4068, 4064, 4062, 1709, 4060, 1722, 1710, 1714, 1728, 1735, 1729, 4056, 1740, 1736, 1744, 1755, 1739, 1761, 4052, 1733, 4129, 1743, 1731, 1727, 1756, 1749, 1744, 1743, 1761, 1749, 1763, 1775, 1760, 1763, 1770, 1775, 1796, 1800, 1809, 1813, 1830, 1848, 1852, 1854, 1858, 1886, 1890, 1899, 1940, 1906, 1931, 1785, 1785, 1789, 1785, 1799, 1799, 4051, 1822, 1822, 1851, 1842, 1857, 1879, 1879, 4029, 4028, 1882, 1903, 1895, 1897, 1913, 4026, 1911, 1934, 1948, 1931, 1948, 1943, 1950, 1941, 4025, 1948, 1949, 1947, 1946, 1952, 1956, 1972, 1959, 4015, 4009, 1962, 3993, 1979, 1987, 1974, 1974, 1978, 1988, 1993, 2000, 1997, 1985, 2000, 3992, 1997, 0, 2008, 2007, 2011, 2016, 542, 2015, 2009, 2033, 2022, 2036, 2037, 2041, 3975, 2034, 2043, 753, 817, 854, 2053, 1052, 2045, 2050, 2058, 2059, 2065, 2070, 1125, 2071, 2073, 2091, 2067, 3963, 2072, 3947, 1241, 2087, 2070, 2063, 2079, 2077, 2081, 2097, 2084, 2085, 2105, 2091, 2090, 2103, 2108, 2113, 2110, 2130, 2172, 2148, 2155, 2154, 2193, 2197, 2214, 2224, 2241, 2249, 2248, 2280, 2276, 2284, 2293, 3936, 3869, 2098, 2104, 2118, 2161, 3832, 2131, 2141, 2133, 2140, 3739, 2183, 2184, 3727, 3687, 2198, 2185, 2214, 2216, 2207, 3686, 2225, 2268, 2272, 2267, 2274, 3682, 2297, 2291, 2316, 3604, 2307, 2304, 2306, 2301, 2311, 2311, 2316, 2316, 3603, 3593, 2332, 3587, 2320, 2321, 2337, 2338, 2330, 2331, 2344, 2346, 2333, 3572, 2327, 3516, 3503, 2339, 3456, 2357, 2358, 1363, 2360, 2364, 1432, 2367, 2380, 2378, 2382, 2383, 2384, 2385, 1416, 2387, 2398, 843, 2421, 2434, 3442, 2444, 2388, 2435, 2414, 2423, 2395, 2436, 2457, 3424, 2429, 2437, 2438, 1499, 2441, 1510, 2471, 2442, 2436, 2452, 2449, 2447, 2451, 2450, 2450, 2464, 2450, 2465, 2467, 2458, 2475, 2477, 2467, 3392, 2491, 3385, 2508, 2499, 2500, 2532, 2549, 2550, 2551, 2556, 2581, 2598, 2594, 2602, 2619, 2629, 2647, 3339, 3332, 3326, 2478, 3302, 2500, 2553, 2568, 2534, 2581, 2586, 2598, 2618, 3294, 2634, 2646, 1203, 2664, 3283, 2648, 2652, 2654, 2647, 2702, 3242, 2649, 2651, 2648, 2659, 2663, 2661, 3199, 2675, 2665, 2712, 2664, 2667, 2677, 2678, 2700, 2688, 2707, 2707, 2726, 3189, 2710, 2712, 2715, 2716, 2703, 2709, 2705, 2707, 2702, 3172, 2711, 3171, 2721, 1876, 2729, 2730, 1560, 2738, 2735, 2768, 3171, 2734, 2760, 2745, 2761, 2759, 2762, 2767, 2280, 2771, 3105, 2416, 2797, 2791, 3107, 2146, 2804, 2797, 3068, 2763, 3007, 2963, 2955, 2822, 2259, 2804, 2800, 2947, 2827, 2818, 2582, 2832, 2934, 2756, 2802, 2807, 2806, 2810, 2823, 2826, 2826, 2880, 2827, 2831, 2831, 2822, 2818, 2820, 2816, 2856, 2628, 2858, 2874, 2866, 2883, 2905, 2921, 2929, 2876, 2938, 2939, 2960, 2973, 2977, 2990, 2981, 2854, 2855, 2900, 2830, 2869, 2873, 2873, 2904, 2926, 2865, 2903, 2900, 2913, 2924, 3007, 2959, 2848, 3016, 3036, 2859, 2789, 2964, 2788, 2775, 3045, 2732, 2990, 3005, 2666, 3008, 2997, 3011, 3008, 3024, 3050, 3022, 3032, 3024, 3035, 3027, 3042, 3043, 2665, 3062, 2645, 3047, 2605, 3035, 2604, 2575, 2567, 3048, 3053, 2560, 3054, 2536, 3073, 2531, 3061, 3075, 3064, 3076, 3075, 3078, 3079, 3082, 2530, 2525, 2507, 3099, 3087, 2487, 3104, 3096, 2927, 2486, 2971, 3101, 3104, 3122, 3103, 3117, 3115, 3140, 2405, 3134, 3133, 3097, 3103, 3120, 3127, 3117, 3119, 3133, 2396, 2354, 3120, 2273, 2266, 3131, 3136, 2237, 3142, 3155, 3167, 3169, 3175, 3176, 3197, 3214, 2216, 3162, 2203, 3218, 2188, 2183, 3219, 3236, 2165, 3163, 3168, 3205, 3155, 3235, 3173, 3198, 3216, 3208, 3219, 2158, 2148, 3253, 3223, 2137, 3279, 3229, 3247, 2130, 2129, 3253, 3253, 3259, 3256, 3257, 3264, 3260, 2116, 2047, 3265, 1919, 3267, 1915, 1910, 1883, 1882, 1877, 3265, 3278, 1833, 1804, 1799, 3295, 3288, 3291, 3293, 1713, 3292, 3289, 3295, 3300, 3313, 3317, 3318, 3319, 3333, 3338, 3312, 3340, 3333, 3351, 3355, 3359, 3364, 3348, 3337, 3368, 3359, 3376, 3355, 3353, 3362, 3353, 3360, 1702, 3357, 1546, 3356, 3369, 3388, 3389, 3407, 3398, 3408, 1540, 3432, 3386, 3387, 3388, 1532, 3393, 3394, 3439, 3449, 3424, 1505, 3431, 3361, 3376, 1492, 3408, 3416, 1486, 3436, 3494, 3429, 3433, 1465, 1464, 3442, 3447, 1454, 3461, 3457, 3457, 3460, 1450, 1427, 3470, 3476, 1354, 3475, 3473, 1353, 3468, 1301, 3495, 3504, 1247, 3493, 3496, 1186, 3519, 3532, 3539, 3513, 3527, 3512, 3547, 3548, 3552, 3556, 3560, 1182, 3524, 3561, 3565, 3573, 3505, 3525, 1131, 3537, 3539, 3552, 3550, 3546, 3569, 3567, 1100, 3573, 3601, 3588, 3605, 3599, 3605, 3611, 3622, 3631, 3622, 3618, 3639, 1084, 1047, 3595, 1012, 3617, 3677, 3616, 1011, 3627, 3664, 993, 3640, 982, 961, 3635, 3634, 960, 3636, 3640, 953, 3659, 3688, 3682, 3640, 3671, 3690, 3685, 3679, 943, 3692, 3708, 3712, 3716, 3708, 3691, 3722, 3713, 3707, 3730, 928, 910, 3689, 898, 3707, 3704, 849, 3715, 844, 3725, 3738, 824, 3729, 3744, 3745, 3748, 812, 3750, 3771, 3727, 801, 3786, 3746, 3740, 3797, 783, 756, 3746, 731, 3759, 720, 714, 3770, 3763, 677, 3774, 3805, 3809, 654, 3810, 3811, 3802, 3805, 3822, 3806, 641, 3826, 3814, 3789, 631, 3809, 3803, 3832, 3823, 3839, 3840, 611, 3824, 3844, 3841, 3870, 604, 3822, 3826, 600, 3823, 593, 3830, 576, 3834, 3862, 3872, 3886, 3859, 3896, 3900, 3891, 3877, 3906, 569, 549, 3865, 3878, 3907, 536, 3911, 3920, 3899, 3912, 3912, 3901, 493, 488, 3896, 3912, 470, 379, 3945, 374, 3956, 3920, 3967, 3919, 3918, 345, 3971, 3978, 3961, 344, 3905, 204, 3907, 195, 3982, 3930, 185, 3993, 3987, 3934, 3997, 3989, 4004, 167, 120, 112, 4008, 4008, 4013, 98, 82, 4020, 78, 4024, 4030, 4034, 4044, 4048, 4129, 4053, 4056, 4064, 4072, 4080, 4088, 4092, 4100 } ; static const flex_int16_t yy_def[1321] = { 0, 1312, 1, 1313, 1313, 1313, 1313, 1312, 7, 1312, 9, 9, 11, 11, 11, 1312, 15, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1312, 1312, 1315, 1312, 1312, 1312, 1315, 1312, 1312, 1312, 1312, 1312, 1316, 1316, 1312, 1312, 1312, 1316, 1312, 1317, 1317, 62, 62, 62, 62, 62, 62, 62, 62, 62, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1318, 1312, 1319, 19, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1312, 1312, 1312, 1312, 1315, 1312, 1315, 1312, 1312, 1312, 1312, 1316, 55, 1312, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1312, 1316, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 1312, 74, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1318, 1319, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1312, 1312, 1312, 1312, 1312, 1312, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1320, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1312, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1320, 1314, 1314, 1314, 1314, 1312, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1312, 1312, 1312, 1314, 1312, 1314, 1314, 1314, 1314, 1314, 1314, 1312, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1312, 1314, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1314, 1314, 1314, 1312, 1314, 1314, 1312, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1312, 1314, 1314, 1312, 1312, 1312, 1314, 1312, 1314, 1314, 1314, 1314, 1314, 1314, 1312, 1314, 1314, 1314, 1314, 1312, 1314, 1312, 1312, 1314, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 62, 1312, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1314, 1314, 1312, 1314, 1314, 1312, 1312, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1312, 1314, 1314, 1312, 1312, 1312, 1312, 1312, 1312, 1314, 1314, 1314, 1314, 1314, 1314, 1312, 1312, 1314, 1314, 1314, 1312, 1314, 1312, 1312, 1314, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 62, 1312, 62, 62, 62, 62, 62, 62, 62, 1312, 62, 62, 62, 62, 62, 62, 62, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1314, 1314, 1312, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1312, 1314, 1312, 1312, 1314, 1312, 1314, 1312, 1312, 1312, 1312, 1314, 1314, 1312, 1312, 1314, 1312, 1312, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 62, 1312, 62, 62, 62, 62, 62, 62, 1312, 1312, 1312, 62, 1312, 1312, 62, 62, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1314, 1314, 1314, 1314, 1314, 1314, 1314, 1312, 1312, 1312, 1314, 1312, 1312, 1314, 1312, 1312, 1312, 1312, 1312, 1312, 1314, 1314, 1312, 1312, 1312, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 62, 62, 62, 62, 62, 1312, 62, 1312, 1312, 1312, 1312, 1312, 1312, 62, 62, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1314, 1314, 1312, 1314, 1314, 1314, 1314, 1312, 1312, 1312, 1314, 1312, 1314, 1312, 1312, 1312, 1312, 1312, 1314, 1314, 1312, 1312, 1312, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 62, 62, 1312, 62, 62, 1312, 62, 1312, 1312, 1312, 1312, 1312, 62, 62, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1314, 1312, 1312, 1314, 1314, 1312, 1312, 1312, 1312, 1314, 1314, 1312, 1312, 1314, 1312, 1312, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1312, 62, 1312, 1312, 62, 1312, 62, 1312, 1312, 62, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1314, 1312, 1312, 1314, 1312, 1312, 1314, 1314, 1312, 1314, 1316, 1316, 1316, 1316, 1312, 62, 1312, 1312, 1312, 62, 1312, 62, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1314, 1312, 1312, 1314, 1312, 1312, 1314, 1316, 1316, 1316, 1312, 1312, 1312, 1312, 62, 1312, 62, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1314, 1312, 1314, 1312, 1312, 1316, 1316, 1312, 1312, 62, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1314, 1312, 1312, 1316, 1312, 62, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1316, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 0, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312 } ; static const flex_int16_t yy_nxt[4196] = { 0, 18, 19, 20, 21, 19, 22, 22, 23, 18, 22, 22, 24, 18, 22, 25, 26, 27, 28, 29, 30, 31, 27, 27, 32, 27, 33, 34, 35, 36, 27, 37, 38, 39, 40, 27, 27, 41, 27, 27, 42, 18, 26, 27, 28, 29, 30, 31, 27, 27, 32, 27, 33, 34, 35, 36, 27, 37, 38, 39, 40, 27, 27, 41, 27, 27, 43, 45, 46, 21, 47, 48, 48, 127, 125, 48, 48, 125, 141, 48, 25, 73, 91, 75, 73, 73, 91, 75, 73, 121, 122, 121, 121, 1308, 73, 123, 123, 1309, 73, 123, 123, 127, 104, 123, 141, 49, 45, 46, 21, 47, 48, 48, 127, 1304, 48, 48, 138, 127, 48, 25, 101, 101, 101, 101, 127, 131, 129, 1306, 182, 130, 136, 182, 127, 104, 127, 1300, 132, 134, 210, 133, 137, 135, 138, 142, 49, 50, 51, 52, 53, 48, 48, 131, 129, 48, 48, 130, 136, 48, 53, 127, 127, 127, 132, 134, 210, 133, 137, 135, 237, 142, 237, 237, 139, 140, 127, 143, 145, 147, 214, 144, 211, 146, 1304, 53, 50, 51, 52, 53, 48, 48, 127, 212, 48, 48, 213, 148, 48, 53, 139, 140, 1301, 143, 145, 147, 214, 144, 211, 146, 164, 164, 1292, 125, 164, 164, 125, 125, 164, 212, 125, 1298, 213, 148, 53, 54, 55, 56, 57, 55, 54, 54, 54, 54, 54, 54, 58, 54, 59, 60, 61, 61, 62, 63, 64, 61, 61, 61, 65, 61, 66, 61, 67, 61, 61, 68, 69, 70, 71, 61, 61, 61, 61, 61, 72, 54, 61, 61, 62, 63, 64, 61, 61, 61, 65, 61, 66, 61, 67, 61, 61, 68, 69, 70, 71, 61, 61, 61, 61, 61, 54, 73, 74, 73, 75, 74, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 76, 73, 77, 78, 79, 73, 73, 73, 80, 73, 81, 82, 83, 73, 73, 84, 85, 86, 87, 73, 73, 73, 73, 73, 73, 73, 76, 73, 77, 78, 79, 73, 73, 73, 80, 73, 81, 82, 83, 73, 73, 84, 85, 86, 87, 73, 73, 73, 73, 73, 73, 88, 88, 89, 88, 1296, 1283, 127, 153, 127, 157, 215, 154, 219, 90, 73, 155, 73, 73, 73, 220, 216, 223, 73, 156, 73, 73, 73, 217, 218, 73, 73, 73, 73, 153, 1289, 157, 215, 154, 219, 1287, 73, 155, 73, 73, 73, 220, 216, 223, 73, 156, 73, 73, 73, 217, 218, 73, 73, 73, 73, 92, 93, 94, 95, 93, 96, 92, 92, 96, 97, 92, 98, 96, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 96, 100, 101, 101, 100, 158, 1276, 102, 224, 241, 125, 103, 159, 125, 104, 105, 247, 106, 107, 108, 109, 248, 249, 110, 1272, 111, 112, 113, 114, 1283, 115, 116, 117, 118, 224, 241, 119, 101, 101, 101, 101, 105, 247, 106, 107, 108, 109, 248, 249, 110, 104, 111, 112, 113, 114, 127, 115, 116, 117, 118, 149, 182, 119, 160, 182, 120, 101, 163, 101, 101, 150, 250, 1280, 184, 151, 152, 266, 188, 650, 104, 101, 101, 101, 101, 184, 1259, 149, 184, 251, 165, 166, 166, 165, 104, 221, 184, 150, 250, 222, 184, 151, 152, 167, 188, 229, 1277, 184, 256, 230, 184, 184, 184, 1270, 184, 251, 191, 236, 189, 237, 236, 221, 184, 184, 257, 222, 184, 103, 168, 170, 1249, 229, 170, 184, 256, 230, 184, 1267, 184, 171, 264, 1259, 191, 184, 189, 172, 173, 174, 1261, 184, 257, 175, 184, 176, 184, 177, 190, 184, 178, 179, 180, 181, 231, 231, 231, 231, 264, 238, 1231, 184, 238, 172, 173, 174, 238, 232, 311, 175, 1252, 176, 184, 177, 190, 184, 178, 179, 180, 181, 169, 169, 127, 1246, 169, 169, 169, 169, 169, 169, 169, 184, 169, 169, 311, 192, 184, 184, 254, 225, 275, 194, 184, 255, 242, 184, 1221, 184, 184, 226, 184, 184, 193, 227, 228, 243, 312, 184, 244, 238, 169, 192, 184, 184, 254, 225, 275, 194, 184, 255, 242, 184, 127, 184, 184, 226, 184, 184, 193, 227, 228, 243, 312, 1218, 244, 169, 169, 169, 276, 1241, 169, 169, 169, 169, 169, 169, 169, 184, 169, 169, 1215, 185, 245, 127, 127, 197, 246, 267, 184, 252, 268, 184, 186, 253, 276, 187, 231, 231, 231, 231, 266, 182, 661, 184, 182, 1212, 169, 185, 245, 232, 127, 197, 246, 267, 184, 252, 268, 184, 186, 253, 1200, 187, 234, 234, 234, 234, 101, 101, 101, 101, 258, 169, 184, 260, 281, 235, 195, 261, 127, 104, 127, 262, 297, 184, 313, 259, 184, 127, 270, 263, 1231, 196, 121, 122, 121, 121, 258, 269, 184, 260, 281, 1233, 195, 261, 266, 104, 662, 262, 297, 184, 313, 259, 184, 1230, 270, 263, 127, 196, 199, 791, 271, 199, 791, 269, 121, 122, 121, 121, 265, 265, 265, 265, 272, 1227, 200, 201, 202, 104, 1191, 127, 203, 266, 204, 663, 205, 273, 271, 206, 207, 208, 209, 123, 123, 127, 277, 123, 123, 274, 272, 123, 200, 201, 202, 127, 127, 279, 203, 127, 204, 127, 205, 273, 127, 206, 207, 208, 209, 127, 278, 127, 277, 127, 314, 274, 127, 280, 282, 1186, 284, 127, 283, 279, 127, 288, 287, 292, 285, 127, 286, 1183, 127, 298, 127, 293, 278, 1175, 127, 300, 314, 127, 289, 280, 282, 127, 284, 295, 283, 294, 290, 288, 287, 292, 285, 127, 286, 291, 296, 298, 299, 293, 164, 164, 1217, 300, 164, 164, 289, 315, 164, 316, 301, 295, 1209, 294, 290, 305, 305, 305, 305, 1206, 1203, 291, 296, 308, 299, 101, 163, 101, 101, 165, 166, 166, 165, 315, 309, 316, 301, 310, 104, 317, 318, 1161, 167, 166, 166, 166, 166, 320, 184, 308, 184, 214, 1201, 216, 218, 319, 167, 219, 322, 184, 309, 184, 184, 310, 184, 317, 318, 168, 321, 184, 1191, 1186, 184, 320, 184, 223, 184, 214, 184, 216, 218, 319, 224, 219, 322, 184, 184, 184, 184, 184, 184, 325, 184, 323, 321, 184, 184, 184, 184, 225, 184, 223, 184, 324, 184, 184, 1183, 184, 224, 266, 184, 665, 184, 326, 228, 184, 184, 325, 184, 323, 338, 184, 184, 184, 222, 225, 184, 184, 184, 324, 184, 184, 184, 184, 328, 184, 184, 184, 184, 326, 228, 330, 184, 1193, 327, 329, 338, 184, 184, 331, 222, 184, 184, 184, 184, 184, 184, 332, 184, 1185, 328, 184, 211, 184, 184, 184, 184, 330, 184, 184, 327, 329, 335, 212, 184, 331, 337, 184, 184, 340, 184, 184, 266, 332, 672, 339, 341, 342, 211, 230, 1123, 184, 184, 345, 184, 184, 184, 333, 335, 212, 346, 347, 337, 348, 343, 340, 349, 184, 334, 350, 184, 339, 341, 342, 351, 230, 344, 352, 353, 345, 354, 357, 184, 333, 358, 359, 346, 347, 362, 348, 343, 355, 349, 184, 334, 350, 184, 360, 363, 356, 351, 1172, 344, 352, 353, 1165, 354, 357, 361, 863, 358, 359, 863, 237, 362, 237, 237, 355, 231, 231, 231, 231, 366, 360, 363, 356, 234, 234, 234, 234, 236, 232, 237, 236, 361, 238, 367, 368, 238, 235, 103, 369, 238, 371, 373, 374, 375, 376, 366, 377, 378, 379, 380, 370, 381, 372, 382, 383, 266, 387, 680, 390, 367, 368, 391, 392, 1162, 369, 393, 371, 373, 374, 375, 376, 394, 377, 378, 379, 380, 370, 381, 372, 382, 383, 384, 387, 388, 390, 127, 127, 391, 392, 385, 127, 393, 238, 396, 389, 398, 386, 394, 265, 265, 265, 265, 127, 127, 127, 127, 397, 384, 400, 388, 127, 127, 127, 402, 403, 385, 127, 1159, 405, 396, 389, 398, 386, 399, 127, 406, 401, 404, 127, 127, 127, 127, 397, 127, 400, 407, 408, 127, 127, 402, 403, 411, 127, 127, 405, 413, 414, 409, 415, 399, 412, 406, 401, 404, 127, 410, 416, 127, 127, 419, 127, 407, 408, 417, 127, 127, 418, 411, 127, 1157, 1104, 413, 414, 409, 415, 127, 412, 266, 127, 776, 420, 410, 416, 421, 422, 419, 424, 127, 127, 417, 423, 425, 418, 427, 127, 127, 127, 432, 433, 426, 434, 429, 305, 305, 305, 305, 420, 428, 430, 421, 422, 435, 424, 436, 437, 438, 423, 425, 439, 427, 440, 441, 443, 432, 433, 426, 434, 429, 446, 442, 266, 444, 788, 428, 430, 779, 780, 435, 779, 436, 437, 438, 445, 1099, 439, 184, 440, 441, 443, 447, 184, 184, 463, 464, 446, 442, 184, 444, 184, 184, 450, 184, 184, 465, 184, 184, 1098, 448, 445, 184, 1148, 184, 184, 466, 449, 447, 184, 184, 463, 464, 1089, 1145, 184, 184, 184, 184, 450, 184, 184, 465, 184, 184, 184, 448, 184, 184, 184, 184, 184, 466, 449, 452, 1141, 184, 451, 184, 184, 184, 1123, 184, 184, 467, 454, 266, 184, 808, 184, 453, 184, 184, 184, 1136, 184, 184, 266, 184, 810, 452, 184, 184, 451, 184, 184, 184, 455, 457, 184, 467, 454, 184, 184, 184, 184, 453, 468, 184, 184, 456, 1130, 184, 184, 184, 184, 184, 184, 184, 1126, 184, 469, 458, 455, 457, 1054, 905, 470, 184, 905, 184, 184, 471, 468, 184, 184, 456, 459, 184, 184, 184, 184, 184, 462, 184, 184, 184, 469, 458, 472, 473, 184, 460, 470, 184, 344, 461, 184, 471, 184, 184, 474, 475, 459, 476, 477, 184, 478, 479, 462, 480, 184, 481, 482, 483, 472, 473, 184, 460, 484, 184, 344, 461, 485, 486, 184, 487, 474, 475, 488, 476, 477, 489, 478, 479, 490, 480, 491, 481, 482, 483, 492, 493, 494, 495, 484, 496, 497, 498, 485, 486, 499, 487, 500, 501, 488, 502, 503, 489, 504, 505, 490, 506, 491, 507, 508, 509, 492, 493, 494, 495, 510, 496, 497, 498, 511, 512, 499, 513, 500, 501, 514, 502, 503, 515, 504, 505, 516, 506, 517, 507, 508, 509, 127, 127, 127, 127, 510, 127, 127, 127, 511, 512, 127, 513, 521, 127, 514, 519, 520, 515, 529, 522, 516, 525, 517, 524, 127, 528, 527, 127, 1049, 127, 526, 127, 531, 127, 532, 127, 127, 540, 521, 1092, 127, 519, 520, 530, 529, 522, 533, 525, 127, 524, 537, 528, 527, 539, 127, 127, 526, 541, 531, 127, 532, 127, 127, 540, 544, 127, 127, 547, 554, 530, 127, 549, 533, 542, 555, 556, 537, 557, 543, 539, 546, 127, 548, 541, 551, 558, 550, 127, 559, 560, 544, 561, 552, 547, 554, 562, 563, 549, 564, 542, 555, 556, 565, 557, 543, 566, 546, 567, 548, 568, 551, 558, 550, 569, 559, 560, 586, 561, 552, 587, 588, 562, 563, 184, 564, 1033, 589, 184, 565, 570, 1088, 566, 590, 567, 184, 568, 184, 184, 184, 569, 184, 184, 586, 591, 571, 587, 588, 184, 572, 184, 184, 184, 589, 184, 184, 570, 573, 184, 590, 1031, 184, 593, 184, 184, 184, 594, 184, 184, 184, 591, 571, 184, 574, 184, 572, 575, 184, 184, 595, 184, 184, 184, 573, 184, 596, 578, 184, 593, 597, 184, 184, 594, 184, 576, 184, 577, 184, 184, 574, 184, 266, 575, 902, 1027, 595, 184, 598, 184, 1026, 1025, 596, 578, 184, 184, 597, 184, 184, 184, 184, 576, 599, 577, 184, 602, 184, 184, 184, 184, 184, 579, 603, 184, 598, 584, 581, 580, 1085, 184, 604, 184, 184, 1023, 605, 184, 184, 1020, 599, 184, 606, 602, 184, 608, 184, 184, 184, 579, 603, 184, 184, 584, 581, 580, 585, 184, 604, 609, 184, 184, 605, 184, 184, 582, 184, 184, 606, 611, 612, 608, 184, 613, 610, 184, 614, 615, 184, 616, 583, 618, 585, 619, 620, 609, 621, 184, 622, 184, 623, 582, 184, 624, 625, 611, 612, 628, 184, 613, 610, 184, 614, 615, 630, 616, 583, 618, 631, 619, 620, 632, 621, 633, 622, 634, 623, 635, 636, 624, 625, 638, 639, 628, 640, 641, 643, 127, 127, 127, 630, 127, 645, 637, 631, 127, 647, 632, 652, 633, 651, 634, 127, 635, 636, 644, 646, 638, 639, 648, 640, 641, 643, 127, 127, 649, 127, 127, 645, 637, 654, 127, 653, 127, 652, 127, 651, 1082, 659, 656, 127, 644, 646, 127, 655, 648, 657, 664, 127, 127, 660, 649, 666, 668, 669, 127, 654, 127, 653, 667, 127, 127, 127, 127, 659, 656, 674, 682, 673, 670, 655, 683, 657, 664, 676, 671, 660, 127, 666, 668, 669, 127, 684, 675, 685, 667, 678, 686, 687, 688, 689, 681, 674, 682, 673, 670, 690, 683, 691, 692, 676, 671, 693, 694, 696, 697, 1081, 718, 684, 675, 685, 719, 678, 686, 687, 688, 689, 681, 695, 1073, 1072, 184, 690, 720, 691, 692, 724, 1054, 693, 694, 696, 697, 184, 718, 266, 698, 918, 719, 1049, 184, 725, 726, 727, 702, 695, 184, 184, 184, 1067, 720, 184, 699, 724, 184, 703, 1059, 704, 184, 184, 184, 184, 698, 699, 184, 721, 184, 725, 726, 727, 702, 722, 184, 184, 1056, 184, 700, 184, 184, 1055, 184, 703, 701, 704, 184, 184, 184, 184, 729, 184, 184, 721, 730, 733, 1053, 734, 184, 722, 705, 184, 184, 184, 700, 184, 184, 706, 184, 1051, 701, 707, 735, 184, 736, 737, 729, 184, 184, 184, 730, 733, 184, 734, 184, 739, 705, 184, 184, 184, 964, 184, 184, 706, 184, 184, 708, 707, 735, 709, 736, 737, 184, 184, 184, 184, 184, 710, 184, 184, 266, 739, 925, 184, 184, 184, 711, 184, 184, 961, 915, 184, 708, 915, 740, 709, 960, 741, 184, 184, 184, 713, 184, 710, 184, 184, 712, 742, 184, 184, 184, 184, 711, 184, 184, 184, 715, 184, 184, 184, 740, 743, 184, 741, 714, 744, 184, 713, 184, 745, 184, 184, 712, 742, 184, 750, 751, 184, 752, 746, 184, 184, 753, 184, 184, 184, 754, 743, 184, 755, 714, 744, 747, 756, 184, 745, 757, 184, 748, 759, 760, 750, 751, 761, 752, 762, 763, 764, 753, 765, 766, 767, 754, 768, 770, 755, 772, 958, 747, 756, 127, 127, 757, 127, 748, 759, 760, 127, 777, 761, 127, 762, 763, 764, 774, 765, 766, 767, 775, 768, 770, 127, 772, 127, 778, 127, 127, 127, 127, 781, 127, 127, 786, 789, 777, 785, 797, 783, 127, 956, 774, 127, 782, 784, 775, 790, 791, 787, 1032, 791, 778, 792, 792, 792, 792, 781, 801, 127, 786, 789, 799, 785, 797, 783, 793, 794, 127, 793, 782, 784, 800, 790, 127, 787, 796, 796, 796, 796, 127, 127, 127, 127, 801, 798, 127, 127, 799, 803, 803, 803, 803, 805, 812, 802, 813, 699, 800, 816, 806, 817, 809, 811, 811, 811, 811, 807, 818, 819, 814, 798, 820, 821, 822, 823, 815, 824, 825, 805, 812, 802, 813, 826, 827, 816, 806, 817, 809, 828, 266, 1024, 1020, 807, 818, 819, 814, 184, 820, 821, 822, 823, 815, 824, 825, 184, 184, 849, 184, 826, 827, 184, 1018, 829, 184, 828, 184, 184, 831, 184, 184, 832, 851, 184, 833, 184, 854, 855, 184, 854, 1017, 184, 184, 849, 184, 1016, 1008, 184, 184, 829, 184, 1006, 184, 184, 831, 184, 184, 832, 851, 184, 833, 184, 184, 834, 184, 184, 184, 184, 836, 835, 837, 838, 184, 852, 184, 1004, 184, 184, 184, 184, 184, 184, 1001, 184, 931, 184, 184, 931, 184, 834, 1000, 184, 184, 184, 836, 835, 837, 184, 184, 852, 853, 839, 184, 184, 184, 184, 184, 184, 184, 184, 184, 184, 184, 841, 184, 856, 840, 857, 184, 999, 997, 184, 858, 184, 184, 184, 853, 839, 184, 184, 949, 842, 184, 949, 184, 184, 184, 184, 859, 841, 184, 856, 840, 857, 184, 184, 184, 184, 858, 184, 184, 184, 861, 843, 184, 184, 184, 842, 184, 184, 918, 184, 844, 184, 859, 862, 864, 865, 866, 864, 867, 184, 184, 868, 184, 184, 869, 184, 861, 843, 995, 964, 184, 872, 873, 184, 845, 874, 844, 184, 875, 862, 876, 877, 866, 878, 867, 879, 881, 868, 184, 882, 869, 184, 870, 870, 870, 870, 883, 872, 873, 884, 845, 874, 880, 780, 875, 880, 876, 877, 885, 878, 886, 879, 881, 887, 888, 882, 889, 794, 891, 889, 892, 893, 883, 894, 895, 884, 896, 897, 898, 899, 900, 901, 127, 127, 885, 980, 886, 127, 127, 887, 888, 127, 904, 907, 891, 908, 892, 893, 127, 894, 895, 903, 896, 897, 898, 899, 900, 901, 779, 780, 906, 779, 127, 127, 127, 127, 127, 910, 904, 907, 127, 908, 909, 911, 127, 914, 933, 903, 961, 916, 912, 793, 794, 913, 793, 921, 906, 792, 792, 792, 792, 960, 958, 910, 796, 796, 796, 796, 909, 911, 127, 914, 933, 127, 919, 916, 912, 127, 927, 913, 934, 921, 803, 803, 803, 803, 926, 929, 929, 929, 929, 127, 811, 811, 811, 811, 930, 935, 936, 937, 919, 938, 939, 940, 927, 941, 934, 942, 943, 944, 945, 946, 926, 947, 965, 966, 855, 965, 966, 968, 865, 956, 930, 935, 936, 937, 855, 938, 939, 940, 184, 941, 184, 942, 943, 944, 945, 946, 948, 947, 184, 184, 969, 184, 184, 968, 184, 952, 184, 957, 950, 184, 951, 838, 184, 970, 184, 184, 184, 184, 967, 865, 184, 967, 948, 971, 184, 184, 184, 184, 184, 184, 184, 952, 184, 953, 950, 184, 951, 184, 184, 970, 972, 184, 973, 184, 854, 855, 184, 854, 184, 971, 974, 184, 184, 184, 954, 184, 266, 955, 1023, 953, 956, 184, 975, 184, 184, 932, 972, 184, 973, 958, 184, 184, 184, 976, 184, 184, 974, 184, 928, 184, 954, 184, 184, 955, 184, 184, 924, 184, 975, 959, 184, 960, 184, 184, 923, 978, 184, 184, 184, 976, 266, 184, 1025, 184, 961, 184, 184, 184, 184, 184, 184, 184, 964, 184, 979, 959, 184, 962, 184, 184, 184, 978, 184, 184, 184, 977, 963, 184, 977, 184, 981, 184, 184, 184, 863, 184, 184, 863, 922, 184, 979, 982, 184, 962, 983, 184, 184, 984, 184, 184, 184, 985, 963, 184, 864, 865, 981, 864, 986, 184, 987, 988, 184, 870, 870, 870, 870, 982, 880, 780, 983, 880, 989, 984, 990, 991, 992, 985, 993, 994, 889, 794, 996, 889, 986, 998, 987, 988, 1002, 1003, 1005, 1007, 127, 905, 1007, 127, 905, 1009, 989, 920, 990, 991, 992, 1010, 993, 994, 127, 127, 996, 127, 127, 998, 1011, 127, 1002, 1003, 1005, 915, 127, 1014, 915, 1012, 1021, 1009, 1013, 1021, 794, 127, 1015, 1010, 266, 1019, 1026, 266, 127, 1027, 917, 1034, 1011, 1022, 1028, 1028, 1028, 1028, 266, 1014, 1031, 1012, 127, 1029, 1013, 1030, 931, 1035, 1015, 931, 1036, 1019, 929, 929, 929, 929, 266, 1034, 1033, 1022, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 949, 184, 1029, 949, 1030, 1044, 1035, 1052, 965, 1036, 1052, 965, 184, 966, 855, 184, 966, 780, 1060, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 184, 184, 184, 810, 808, 1044, 1046, 1045, 184, 184, 1062, 184, 184, 184, 184, 184, 184, 1048, 1060, 184, 184, 890, 1047, 184, 967, 865, 184, 967, 184, 1049, 184, 776, 1046, 1045, 184, 184, 1062, 184, 1063, 184, 184, 184, 184, 1048, 184, 184, 184, 184, 1047, 184, 1054, 184, 184, 1064, 1061, 1065, 184, 1061, 184, 1050, 1066, 184, 184, 184, 1063, 184, 1057, 184, 1068, 184, 184, 1058, 977, 184, 871, 977, 1070, 184, 184, 1064, 184, 1065, 1071, 184, 184, 1050, 1066, 184, 184, 184, 1074, 184, 1057, 1075, 1068, 184, 1076, 1058, 1069, 1069, 1069, 1069, 1070, 1077, 1078, 1079, 184, 1080, 1071, 184, 1083, 1084, 1086, 1087, 1007, 838, 1074, 1007, 266, 1075, 1089, 127, 1076, 127, 127, 127, 860, 127, 1093, 1077, 1078, 1079, 127, 1080, 850, 1094, 1083, 1084, 1086, 1087, 1091, 1090, 1095, 266, 127, 1097, 1096, 266, 266, 1098, 1099, 127, 1101, 1102, 1093, 1101, 1100, 1021, 848, 1103, 1021, 1094, 1103, 266, 847, 1104, 1091, 1090, 1095, 127, 1105, 846, 1096, 1105, 1106, 1106, 1106, 1106, 1107, 1102, 127, 1107, 1100, 1028, 1028, 1028, 1028, 1110, 1109, 266, 1110, 1111, 1113, 1114, 1108, 1112, 1112, 1112, 1112, 1115, 1116, 1117, 1118, 1119, 1120, 1128, 1052, 1129, 1128, 1052, 1129, 1137, 1131, 1132, 1109, 1131, 1132, 830, 1113, 1114, 1108, 184, 184, 1138, 715, 1115, 1116, 1117, 1118, 1119, 1120, 184, 184, 184, 1124, 184, 1122, 1137, 1121, 1123, 184, 184, 184, 1135, 1139, 184, 1135, 184, 184, 1138, 1061, 184, 184, 1061, 184, 1125, 804, 184, 184, 184, 1124, 184, 1122, 1140, 1121, 184, 184, 184, 184, 1127, 1139, 184, 184, 1142, 795, 1143, 184, 184, 184, 184, 184, 1125, 184, 184, 1144, 1133, 184, 1158, 773, 1140, 1158, 184, 1146, 184, 1147, 1127, 184, 1149, 184, 1142, 1134, 1143, 184, 1150, 1151, 184, 1152, 1153, 184, 184, 1144, 1133, 184, 1069, 1069, 1069, 1069, 1154, 1146, 184, 1147, 1155, 184, 1149, 1156, 127, 1134, 127, 127, 1150, 1151, 1160, 1152, 1153, 266, 680, 1161, 1163, 1166, 1166, 1166, 1166, 1164, 1154, 127, 127, 1101, 1155, 771, 1101, 1156, 1167, 1167, 1167, 1167, 1176, 127, 1160, 1168, 1168, 1168, 1168, 1170, 1163, 1169, 1173, 1103, 1171, 1164, 1103, 1171, 1105, 1177, 1178, 1105, 1106, 1106, 1106, 1106, 1107, 1110, 1176, 1107, 1110, 1174, 1175, 1179, 1174, 1170, 1180, 1169, 1173, 1112, 1112, 1112, 1112, 1181, 1182, 1177, 1178, 184, 1183, 184, 1184, 769, 1186, 184, 1188, 1188, 1188, 1188, 184, 1179, 184, 184, 1180, 184, 184, 1128, 665, 184, 1128, 1181, 1182, 1129, 758, 184, 1129, 184, 1184, 1190, 1194, 184, 1190, 184, 662, 749, 184, 184, 184, 184, 1131, 184, 184, 1131, 184, 184, 1187, 184, 184, 1132, 184, 184, 1132, 1191, 184, 1189, 1194, 1135, 1192, 184, 1135, 184, 1195, 184, 184, 184, 1197, 1198, 184, 266, 184, 1212, 1187, 184, 184, 1202, 184, 184, 1204, 1205, 184, 1189, 1199, 1200, 1192, 1199, 1207, 184, 1195, 1208, 184, 184, 1197, 1198, 184, 1196, 1196, 1196, 1196, 1210, 1158, 1202, 127, 1158, 1204, 1205, 1211, 1175, 1214, 1211, 127, 1214, 1207, 715, 266, 1208, 1215, 738, 732, 1216, 1213, 266, 127, 1218, 1223, 1210, 1166, 1166, 1166, 1166, 1167, 1167, 1167, 1167, 1168, 1168, 1168, 1168, 127, 127, 1171, 1220, 266, 1171, 1221, 1216, 1213, 1219, 1174, 1175, 1223, 1174, 1224, 1222, 1225, 1226, 1229, 184, 731, 1229, 1231, 184, 1188, 1188, 1188, 1188, 1190, 1220, 184, 1190, 728, 184, 184, 1219, 1228, 184, 1236, 184, 1224, 1222, 1225, 1226, 184, 184, 1232, 1237, 1238, 184, 184, 1235, 1200, 184, 1235, 184, 184, 1239, 1234, 184, 184, 1240, 1228, 184, 1236, 184, 1196, 1196, 1196, 1196, 184, 1242, 1232, 1237, 1238, 1243, 184, 1199, 1200, 184, 1199, 184, 1244, 1239, 1234, 1211, 1175, 1240, 1211, 1245, 1214, 1247, 1245, 1214, 1247, 127, 266, 1242, 1249, 127, 1255, 1243, 1250, 1250, 1250, 1250, 1253, 127, 1244, 1253, 1256, 1257, 1258, 1248, 1251, 1258, 1259, 184, 184, 1229, 1260, 1254, 1229, 1260, 1263, 723, 1255, 1263, 184, 184, 1265, 184, 1262, 1266, 1268, 184, 1256, 1257, 1269, 1248, 1251, 1271, 1245, 184, 184, 1245, 184, 1254, 1264, 184, 1235, 1200, 127, 1235, 184, 184, 1265, 184, 1262, 1266, 1268, 184, 717, 266, 1269, 1272, 1247, 1271, 266, 1247, 1276, 1273, 184, 1278, 1264, 184, 1274, 1274, 1274, 1274, 1250, 1250, 1250, 1250, 127, 1279, 1253, 1258, 1275, 1253, 1258, 1260, 1263, 184, 1260, 1263, 1282, 1273, 1284, 1278, 1281, 1281, 1281, 1281, 184, 1283, 184, 184, 1285, 1286, 266, 1279, 1292, 127, 1275, 1293, 1297, 184, 1299, 184, 184, 266, 1282, 1300, 1284, 1288, 1288, 1288, 1288, 716, 184, 1290, 184, 184, 1285, 1286, 1274, 1274, 1274, 1274, 679, 1293, 1297, 184, 1299, 1303, 184, 1291, 1291, 1291, 1291, 1294, 1294, 1294, 1294, 184, 677, 1290, 1281, 1281, 1281, 1281, 1288, 1288, 1288, 1288, 184, 1302, 658, 184, 1302, 1303, 1295, 1291, 1291, 1291, 1291, 1294, 1294, 1294, 1294, 184, 1304, 184, 1305, 642, 629, 1305, 1307, 1307, 1307, 1307, 184, 1302, 184, 184, 1302, 184, 1295, 266, 1305, 1308, 627, 1305, 1307, 1307, 1307, 1307, 626, 184, 1310, 1310, 1310, 1310, 1311, 1311, 1311, 1311, 617, 607, 184, 601, 600, 184, 1310, 1310, 1310, 1310, 1311, 1311, 1311, 1311, 44, 44, 44, 44, 44, 44, 44, 44, 44, 128, 128, 162, 592, 553, 162, 162, 162, 545, 162, 169, 169, 538, 169, 536, 169, 535, 169, 184, 184, 534, 184, 523, 184, 431, 184, 239, 239, 239, 395, 239, 239, 239, 239, 239, 240, 365, 240, 518, 364, 233, 518, 336, 518, 183, 518, 518, 307, 306, 304, 303, 302, 127, 266, 161, 126, 124, 233, 198, 183, 159, 161, 127, 126, 124, 1312, 17, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312 } ; static const flex_int16_t yy_chk[4196] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 33, 24, 3, 3, 24, 33, 3, 3, 13, 13, 13, 13, 14, 14, 14, 14, 20, 20, 20, 20, 1306, 13, 22, 22, 1304, 14, 22, 22, 31, 20, 22, 33, 3, 4, 4, 4, 4, 4, 4, 26, 1303, 4, 4, 31, 30, 4, 4, 21, 21, 21, 21, 28, 28, 26, 1299, 58, 26, 30, 58, 29, 21, 34, 1298, 28, 29, 76, 28, 30, 29, 31, 34, 4, 5, 5, 5, 5, 5, 5, 28, 26, 5, 5, 26, 30, 5, 5, 32, 37, 36, 28, 29, 76, 28, 30, 29, 95, 34, 95, 95, 32, 32, 35, 35, 36, 37, 78, 35, 77, 36, 1297, 5, 6, 6, 6, 6, 6, 6, 38, 77, 6, 6, 77, 38, 6, 6, 32, 32, 1290, 35, 36, 37, 78, 35, 77, 36, 48, 48, 1287, 98, 48, 48, 98, 103, 48, 77, 103, 1285, 77, 38, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 1283, 1279, 40, 40, 41, 41, 79, 40, 81, 11, 11, 40, 11, 11, 11, 82, 79, 84, 11, 40, 11, 11, 11, 80, 80, 11, 11, 11, 11, 40, 1273, 41, 79, 40, 81, 1271, 11, 40, 11, 11, 11, 82, 79, 84, 11, 40, 11, 11, 11, 80, 80, 11, 11, 11, 11, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 19, 19, 19, 19, 42, 1270, 19, 85, 105, 125, 19, 42, 125, 19, 19, 108, 19, 19, 19, 19, 109, 110, 19, 1267, 19, 19, 19, 19, 1266, 19, 19, 19, 19, 85, 105, 19, 45, 45, 45, 45, 19, 108, 19, 19, 19, 19, 109, 110, 19, 45, 19, 19, 19, 19, 39, 19, 19, 19, 19, 39, 171, 19, 42, 171, 19, 46, 46, 46, 46, 39, 111, 1259, 63, 39, 39, 523, 63, 523, 46, 47, 47, 47, 47, 63, 1255, 39, 63, 112, 51, 51, 51, 51, 47, 83, 64, 39, 111, 83, 63, 39, 39, 51, 63, 87, 1254, 64, 115, 87, 64, 63, 66, 1243, 63, 112, 66, 93, 64, 93, 93, 83, 64, 66, 116, 83, 66, 93, 51, 55, 1241, 87, 55, 64, 115, 87, 64, 1239, 66, 55, 119, 1236, 66, 65, 64, 55, 55, 55, 1231, 66, 116, 55, 66, 55, 65, 55, 65, 65, 55, 55, 55, 55, 88, 88, 88, 88, 119, 96, 1224, 65, 96, 55, 55, 55, 96, 88, 173, 55, 1220, 55, 65, 55, 65, 65, 55, 55, 55, 55, 61, 61, 135, 1213, 61, 61, 61, 61, 61, 61, 61, 67, 61, 61, 173, 67, 68, 69, 114, 86, 135, 69, 67, 114, 106, 67, 1209, 68, 69, 86, 68, 69, 68, 86, 86, 106, 174, 67, 106, 96, 61, 67, 68, 69, 114, 86, 135, 69, 67, 114, 106, 67, 136, 68, 69, 86, 68, 69, 68, 86, 86, 106, 174, 1206, 106, 61, 62, 62, 136, 1205, 62, 62, 62, 62, 62, 62, 62, 71, 62, 62, 1203, 62, 107, 130, 129, 71, 107, 129, 71, 113, 130, 71, 62, 113, 136, 62, 89, 89, 89, 89, 534, 182, 534, 71, 182, 1201, 62, 62, 107, 89, 141, 71, 107, 129, 71, 113, 130, 71, 62, 113, 1200, 62, 91, 91, 91, 91, 101, 101, 101, 101, 117, 62, 70, 118, 141, 91, 70, 118, 131, 101, 153, 118, 153, 70, 175, 117, 70, 132, 132, 118, 1195, 70, 121, 121, 121, 121, 117, 131, 70, 118, 141, 1191, 70, 118, 535, 121, 535, 118, 153, 70, 175, 117, 70, 1186, 132, 118, 133, 70, 74, 661, 133, 74, 661, 131, 122, 122, 122, 122, 124, 124, 124, 124, 133, 1183, 74, 74, 74, 122, 1181, 134, 74, 536, 74, 536, 74, 134, 133, 74, 74, 74, 74, 123, 123, 137, 137, 123, 123, 134, 133, 123, 74, 74, 74, 138, 139, 139, 74, 140, 74, 143, 74, 134, 142, 74, 74, 74, 74, 144, 138, 145, 137, 146, 176, 134, 147, 140, 142, 1178, 143, 154, 142, 139, 149, 147, 146, 149, 144, 150, 145, 1176, 151, 154, 156, 150, 138, 1175, 148, 156, 176, 155, 148, 140, 142, 152, 143, 152, 142, 151, 148, 147, 146, 149, 144, 157, 145, 148, 152, 154, 155, 150, 164, 164, 1164, 156, 164, 164, 148, 177, 164, 178, 157, 152, 1155, 151, 148, 161, 161, 161, 161, 1152, 1149, 148, 152, 172, 155, 163, 163, 163, 163, 165, 165, 165, 165, 177, 172, 178, 157, 172, 163, 179, 180, 1148, 165, 166, 166, 166, 166, 181, 184, 172, 185, 201, 1146, 202, 203, 180, 166, 204, 186, 184, 172, 185, 184, 172, 185, 179, 180, 165, 185, 186, 1143, 1139, 186, 181, 184, 206, 185, 201, 187, 202, 203, 180, 207, 204, 186, 184, 188, 185, 184, 187, 185, 189, 187, 187, 185, 186, 190, 188, 186, 208, 188, 206, 189, 188, 187, 189, 1137, 190, 207, 538, 190, 538, 188, 190, 208, 187, 192, 189, 187, 187, 205, 191, 190, 188, 205, 208, 188, 192, 189, 188, 192, 189, 191, 190, 192, 191, 190, 193, 194, 190, 208, 194, 192, 1136, 191, 193, 205, 191, 193, 194, 205, 193, 194, 192, 197, 195, 192, 195, 191, 1123, 192, 191, 200, 193, 194, 197, 195, 194, 197, 195, 191, 193, 197, 200, 193, 194, 200, 193, 194, 210, 197, 195, 545, 195, 545, 209, 211, 212, 200, 209, 1115, 197, 195, 214, 197, 195, 196, 196, 197, 200, 215, 216, 200, 217, 213, 210, 218, 196, 196, 219, 196, 209, 211, 212, 220, 209, 213, 221, 222, 214, 223, 225, 196, 196, 226, 227, 215, 216, 229, 217, 213, 224, 218, 196, 196, 219, 196, 228, 230, 224, 220, 1108, 213, 221, 222, 1096, 223, 225, 228, 731, 226, 227, 731, 237, 229, 237, 237, 224, 231, 231, 231, 231, 241, 228, 230, 224, 234, 234, 234, 234, 236, 231, 236, 236, 228, 238, 242, 243, 238, 234, 236, 244, 238, 245, 246, 247, 248, 249, 241, 250, 251, 252, 253, 244, 254, 245, 255, 256, 553, 258, 553, 260, 242, 243, 261, 262, 1093, 244, 263, 245, 246, 247, 248, 249, 264, 250, 251, 252, 253, 244, 254, 245, 255, 256, 257, 258, 259, 260, 267, 268, 261, 262, 257, 269, 263, 238, 267, 259, 269, 257, 264, 265, 265, 265, 265, 272, 271, 273, 270, 268, 257, 271, 259, 276, 274, 277, 273, 274, 257, 278, 1090, 276, 267, 259, 269, 257, 270, 275, 277, 272, 275, 280, 279, 282, 283, 268, 281, 271, 278, 279, 284, 285, 273, 274, 282, 288, 286, 276, 284, 285, 280, 286, 270, 283, 277, 272, 275, 287, 281, 287, 289, 290, 290, 291, 278, 279, 288, 292, 293, 289, 282, 295, 1088, 1085, 284, 285, 280, 286, 294, 283, 647, 296, 647, 291, 281, 287, 292, 293, 290, 295, 297, 298, 288, 294, 296, 289, 298, 301, 299, 300, 308, 309, 297, 310, 300, 305, 305, 305, 305, 291, 299, 301, 292, 293, 311, 295, 312, 313, 314, 294, 296, 315, 298, 316, 317, 318, 308, 309, 297, 310, 300, 320, 317, 658, 319, 658, 299, 301, 650, 650, 311, 650, 312, 313, 314, 319, 1082, 315, 321, 316, 317, 318, 321, 322, 323, 338, 339, 320, 317, 321, 319, 324, 321, 324, 322, 323, 340, 322, 323, 1081, 322, 319, 324, 1076, 321, 324, 341, 323, 321, 322, 323, 338, 339, 1073, 1072, 321, 326, 324, 321, 324, 322, 323, 340, 322, 323, 325, 322, 326, 324, 327, 326, 324, 341, 323, 326, 1067, 325, 325, 328, 325, 327, 1064, 326, 327, 342, 328, 677, 329, 677, 328, 327, 325, 328, 326, 1060, 327, 326, 679, 329, 679, 326, 329, 325, 325, 328, 325, 327, 329, 331, 327, 342, 328, 330, 329, 332, 328, 327, 343, 328, 331, 330, 1054, 331, 330, 329, 332, 330, 329, 332, 1049, 333, 344, 332, 329, 331, 1041, 776, 345, 330, 776, 332, 333, 346, 343, 333, 331, 330, 333, 331, 330, 334, 332, 330, 337, 332, 335, 333, 344, 332, 347, 348, 334, 334, 345, 334, 337, 335, 333, 346, 335, 333, 349, 350, 333, 351, 352, 334, 353, 354, 337, 355, 335, 356, 357, 358, 347, 348, 334, 334, 359, 334, 337, 335, 360, 361, 335, 362, 349, 350, 363, 351, 352, 366, 353, 354, 367, 355, 368, 356, 357, 358, 369, 370, 371, 372, 359, 373, 374, 375, 360, 361, 376, 362, 377, 378, 363, 379, 380, 366, 381, 382, 367, 383, 368, 384, 385, 386, 369, 370, 371, 372, 387, 373, 374, 375, 388, 389, 376, 390, 377, 378, 391, 379, 380, 392, 381, 382, 393, 383, 394, 384, 385, 386, 396, 399, 406, 397, 387, 398, 404, 402, 388, 389, 401, 390, 398, 403, 391, 396, 397, 392, 406, 399, 393, 402, 394, 401, 405, 405, 404, 408, 1039, 407, 403, 410, 408, 409, 409, 414, 417, 417, 398, 1011, 418, 396, 397, 407, 406, 399, 410, 402, 416, 401, 414, 405, 404, 416, 419, 421, 403, 418, 408, 430, 409, 420, 424, 417, 421, 427, 423, 424, 430, 407, 425, 425, 410, 419, 432, 433, 414, 434, 420, 416, 423, 426, 424, 418, 427, 435, 426, 428, 436, 437, 421, 438, 428, 424, 430, 439, 440, 425, 441, 419, 432, 433, 442, 434, 420, 443, 423, 444, 424, 445, 427, 435, 426, 446, 436, 437, 462, 438, 428, 463, 464, 439, 440, 447, 441, 1006, 465, 448, 442, 447, 1005, 443, 466, 444, 447, 445, 449, 447, 448, 446, 450, 448, 462, 467, 448, 463, 464, 449, 449, 447, 449, 450, 465, 448, 450, 447, 450, 451, 466, 1004, 447, 469, 449, 447, 448, 470, 450, 448, 451, 467, 448, 451, 451, 449, 449, 452, 449, 450, 471, 453, 450, 454, 450, 451, 472, 455, 452, 469, 473, 452, 453, 470, 454, 453, 451, 454, 455, 451, 451, 455, 773, 452, 773, 1001, 471, 453, 474, 454, 1000, 999, 472, 455, 452, 456, 473, 452, 453, 457, 454, 453, 475, 454, 455, 478, 456, 455, 458, 456, 457, 456, 479, 457, 474, 460, 458, 457, 998, 458, 480, 456, 458, 997, 481, 457, 460, 995, 475, 460, 482, 478, 456, 484, 458, 456, 457, 456, 479, 457, 461, 460, 458, 457, 461, 458, 480, 485, 458, 459, 481, 461, 460, 459, 461, 460, 482, 486, 487, 484, 459, 488, 485, 459, 489, 490, 461, 491, 459, 493, 461, 494, 495, 485, 496, 459, 497, 461, 498, 459, 461, 499, 500, 486, 487, 503, 459, 488, 485, 459, 489, 490, 505, 491, 459, 493, 506, 494, 495, 507, 496, 508, 497, 509, 498, 510, 511, 499, 500, 512, 513, 503, 514, 515, 517, 520, 519, 525, 505, 521, 520, 511, 506, 524, 522, 507, 525, 508, 524, 509, 527, 510, 511, 519, 521, 512, 513, 522, 514, 515, 517, 526, 532, 522, 528, 529, 520, 511, 527, 530, 526, 533, 525, 539, 524, 993, 532, 529, 540, 519, 521, 537, 528, 522, 530, 537, 541, 542, 533, 522, 539, 541, 542, 543, 527, 549, 526, 540, 544, 546, 551, 547, 532, 529, 547, 555, 546, 543, 528, 556, 530, 537, 549, 544, 533, 554, 539, 541, 542, 548, 557, 548, 558, 540, 551, 559, 560, 561, 562, 554, 547, 555, 546, 543, 563, 556, 564, 565, 549, 544, 566, 567, 568, 569, 992, 588, 557, 548, 558, 589, 551, 559, 560, 561, 562, 554, 567, 984, 983, 570, 563, 590, 564, 565, 593, 979, 566, 567, 568, 569, 570, 588, 795, 570, 795, 589, 976, 572, 594, 595, 596, 572, 567, 574, 573, 570, 975, 590, 572, 591, 593, 572, 573, 964, 574, 573, 570, 574, 573, 570, 571, 571, 591, 572, 594, 595, 596, 572, 591, 574, 573, 961, 571, 571, 572, 571, 960, 572, 573, 571, 574, 573, 575, 574, 573, 598, 576, 571, 591, 599, 602, 958, 603, 575, 591, 575, 575, 576, 571, 571, 576, 571, 576, 577, 956, 571, 577, 604, 575, 605, 606, 598, 576, 578, 577, 599, 602, 577, 603, 575, 608, 575, 575, 576, 578, 947, 576, 578, 576, 577, 579, 578, 577, 604, 579, 605, 606, 581, 580, 578, 577, 579, 580, 577, 579, 804, 608, 804, 581, 580, 578, 581, 580, 578, 944, 788, 579, 578, 788, 609, 579, 943, 610, 581, 580, 583, 583, 579, 580, 582, 579, 582, 611, 584, 581, 580, 583, 581, 580, 583, 582, 585, 585, 582, 584, 609, 612, 584, 610, 584, 614, 583, 583, 585, 615, 582, 585, 582, 611, 584, 618, 619, 583, 620, 616, 583, 582, 621, 585, 582, 584, 622, 612, 584, 623, 584, 614, 616, 624, 585, 615, 625, 585, 616, 628, 630, 618, 619, 631, 620, 632, 633, 634, 621, 635, 636, 637, 622, 638, 640, 623, 643, 941, 616, 624, 645, 646, 625, 648, 616, 628, 630, 649, 648, 631, 651, 632, 633, 634, 645, 635, 636, 637, 646, 638, 640, 653, 643, 652, 649, 654, 655, 656, 657, 651, 659, 666, 656, 659, 648, 655, 666, 653, 670, 940, 645, 660, 652, 654, 646, 660, 791, 657, 930, 791, 649, 662, 662, 662, 662, 651, 670, 668, 656, 659, 668, 655, 666, 653, 663, 663, 669, 663, 652, 654, 669, 660, 674, 657, 665, 665, 665, 665, 667, 671, 675, 676, 670, 667, 678, 681, 668, 672, 672, 672, 672, 674, 681, 671, 682, 683, 669, 684, 675, 685, 678, 680, 680, 680, 680, 676, 686, 687, 683, 667, 688, 689, 690, 691, 683, 692, 693, 674, 681, 671, 682, 694, 695, 684, 675, 685, 678, 696, 917, 921, 917, 676, 686, 687, 683, 698, 688, 689, 690, 691, 683, 692, 693, 701, 702, 718, 698, 694, 695, 698, 914, 698, 700, 696, 701, 702, 700, 701, 702, 701, 720, 698, 702, 700, 723, 723, 700, 723, 913, 701, 702, 718, 698, 912, 903, 698, 703, 698, 700, 901, 701, 702, 700, 701, 702, 701, 720, 703, 702, 700, 703, 703, 700, 704, 705, 706, 705, 704, 706, 707, 707, 721, 703, 899, 704, 705, 706, 704, 705, 706, 896, 707, 810, 703, 707, 810, 703, 703, 895, 704, 705, 706, 705, 704, 706, 708, 707, 721, 722, 708, 704, 705, 706, 704, 705, 706, 708, 707, 710, 708, 707, 710, 709, 724, 709, 725, 711, 894, 892, 710, 726, 708, 710, 709, 722, 708, 709, 711, 830, 711, 711, 830, 708, 712, 710, 708, 727, 710, 709, 724, 709, 725, 711, 713, 712, 710, 726, 712, 710, 709, 729, 712, 709, 711, 713, 711, 711, 713, 890, 712, 713, 714, 727, 730, 732, 732, 734, 732, 735, 713, 712, 736, 714, 712, 737, 714, 729, 712, 888, 874, 713, 740, 741, 713, 714, 742, 713, 714, 743, 730, 744, 745, 734, 747, 735, 748, 750, 736, 714, 751, 737, 714, 738, 738, 738, 738, 752, 740, 741, 753, 714, 742, 749, 749, 743, 749, 744, 745, 754, 747, 755, 748, 750, 756, 757, 751, 758, 758, 760, 758, 761, 762, 752, 763, 764, 753, 765, 766, 767, 768, 770, 772, 774, 775, 754, 871, 755, 781, 778, 756, 757, 777, 775, 778, 760, 781, 761, 762, 783, 763, 764, 774, 765, 766, 767, 768, 770, 772, 779, 779, 777, 779, 785, 782, 784, 786, 799, 783, 775, 778, 787, 781, 782, 784, 789, 787, 813, 774, 869, 789, 785, 793, 793, 786, 793, 799, 777, 792, 792, 792, 792, 868, 866, 783, 796, 796, 796, 796, 782, 784, 797, 787, 813, 806, 797, 789, 785, 805, 806, 786, 814, 799, 803, 803, 803, 803, 805, 808, 808, 808, 808, 809, 811, 811, 811, 811, 809, 815, 816, 817, 797, 818, 819, 820, 806, 822, 814, 823, 824, 825, 826, 827, 805, 828, 846, 847, 847, 846, 847, 849, 865, 862, 809, 815, 816, 817, 855, 818, 819, 820, 829, 822, 831, 823, 824, 825, 826, 827, 829, 828, 833, 829, 850, 831, 829, 849, 831, 833, 832, 838, 831, 833, 832, 821, 833, 851, 829, 834, 831, 832, 848, 848, 832, 848, 829, 852, 833, 829, 834, 831, 829, 834, 831, 833, 832, 834, 831, 833, 832, 835, 833, 851, 853, 834, 856, 832, 854, 854, 832, 854, 835, 852, 857, 835, 834, 836, 835, 834, 920, 836, 920, 834, 837, 837, 858, 835, 836, 812, 853, 836, 856, 839, 839, 840, 837, 859, 835, 837, 857, 835, 807, 836, 835, 839, 840, 836, 839, 840, 802, 837, 858, 840, 836, 841, 841, 836, 801, 861, 839, 840, 837, 859, 922, 837, 922, 841, 842, 842, 841, 839, 840, 843, 839, 840, 845, 845, 867, 840, 842, 843, 841, 842, 843, 861, 844, 843, 845, 860, 844, 845, 860, 841, 872, 842, 841, 844, 863, 843, 844, 863, 800, 845, 867, 873, 842, 843, 875, 842, 843, 876, 844, 843, 845, 877, 844, 845, 864, 864, 872, 864, 878, 844, 879, 881, 844, 870, 870, 870, 870, 873, 880, 880, 875, 880, 882, 876, 883, 884, 885, 877, 886, 887, 889, 889, 891, 889, 878, 893, 879, 881, 897, 898, 900, 902, 904, 905, 902, 906, 905, 904, 882, 798, 883, 884, 885, 906, 886, 887, 908, 907, 891, 909, 910, 893, 907, 911, 897, 898, 900, 915, 916, 910, 915, 908, 918, 904, 909, 918, 794, 919, 911, 906, 923, 916, 923, 924, 926, 924, 790, 933, 907, 919, 925, 925, 925, 925, 928, 910, 928, 908, 927, 926, 909, 927, 931, 934, 911, 931, 935, 916, 929, 929, 929, 929, 932, 933, 932, 919, 936, 937, 938, 939, 942, 945, 946, 949, 948, 926, 949, 927, 948, 934, 957, 965, 935, 957, 965, 948, 966, 966, 948, 966, 780, 968, 936, 937, 938, 939, 942, 945, 946, 950, 948, 951, 771, 769, 948, 951, 950, 952, 953, 970, 950, 948, 951, 950, 948, 951, 953, 968, 952, 953, 759, 952, 953, 967, 967, 950, 967, 951, 954, 954, 746, 951, 950, 952, 953, 970, 950, 971, 951, 950, 954, 951, 953, 954, 952, 953, 955, 952, 953, 959, 959, 962, 972, 969, 973, 954, 969, 955, 955, 974, 955, 959, 962, 971, 959, 962, 954, 978, 963, 954, 963, 977, 955, 739, 977, 981, 959, 962, 972, 963, 973, 982, 963, 955, 955, 974, 955, 959, 962, 985, 959, 962, 986, 978, 963, 987, 963, 980, 980, 980, 980, 981, 988, 989, 990, 963, 991, 982, 963, 994, 996, 1002, 1003, 1007, 733, 985, 1007, 1008, 986, 1008, 1013, 987, 1009, 1012, 1010, 728, 1014, 1012, 988, 989, 990, 1015, 991, 719, 1013, 994, 996, 1002, 1003, 1010, 1009, 1014, 1016, 1022, 1016, 1015, 1017, 1018, 1017, 1018, 1019, 1020, 1022, 1012, 1020, 1019, 1021, 717, 1023, 1021, 1013, 1023, 1024, 716, 1024, 1010, 1009, 1014, 1030, 1025, 715, 1015, 1025, 1026, 1026, 1026, 1026, 1027, 1022, 1029, 1027, 1019, 1028, 1028, 1028, 1028, 1031, 1030, 1032, 1031, 1032, 1034, 1035, 1029, 1033, 1033, 1033, 1033, 1036, 1037, 1038, 1040, 1042, 1043, 1051, 1052, 1053, 1051, 1052, 1053, 1062, 1055, 1056, 1030, 1055, 1056, 699, 1034, 1035, 1029, 1044, 1045, 1063, 697, 1036, 1037, 1038, 1040, 1042, 1043, 1047, 1044, 1045, 1047, 1044, 1045, 1062, 1044, 1046, 1046, 1048, 1047, 1059, 1065, 1047, 1059, 1044, 1045, 1063, 1061, 1046, 1048, 1061, 1046, 1048, 673, 1047, 1044, 1045, 1047, 1044, 1045, 1066, 1044, 1050, 1046, 1048, 1047, 1050, 1065, 1047, 1057, 1068, 664, 1070, 1050, 1046, 1048, 1050, 1046, 1048, 1058, 1057, 1071, 1057, 1057, 1089, 644, 1066, 1089, 1050, 1074, 1058, 1075, 1050, 1058, 1077, 1057, 1068, 1058, 1070, 1050, 1078, 1079, 1050, 1080, 1083, 1058, 1057, 1071, 1057, 1057, 1069, 1069, 1069, 1069, 1084, 1074, 1058, 1075, 1086, 1058, 1077, 1087, 1094, 1058, 1091, 1095, 1078, 1079, 1091, 1080, 1083, 1092, 642, 1092, 1094, 1097, 1097, 1097, 1097, 1095, 1084, 1102, 1100, 1101, 1086, 641, 1101, 1087, 1098, 1098, 1098, 1098, 1113, 1109, 1091, 1099, 1099, 1099, 1099, 1102, 1094, 1100, 1109, 1103, 1104, 1095, 1103, 1104, 1105, 1114, 1116, 1105, 1106, 1106, 1106, 1106, 1107, 1110, 1113, 1107, 1110, 1111, 1111, 1117, 1111, 1102, 1118, 1100, 1109, 1112, 1112, 1112, 1112, 1119, 1120, 1114, 1116, 1122, 1121, 1121, 1122, 639, 1124, 1124, 1126, 1126, 1126, 1126, 1122, 1117, 1121, 1122, 1118, 1121, 1124, 1128, 629, 1124, 1128, 1119, 1120, 1129, 627, 1122, 1129, 1121, 1122, 1130, 1138, 1124, 1130, 1125, 626, 617, 1122, 1127, 1121, 1122, 1131, 1121, 1124, 1131, 1125, 1124, 1125, 1125, 1127, 1132, 1134, 1127, 1132, 1133, 1133, 1127, 1138, 1135, 1134, 1125, 1135, 1134, 1140, 1127, 1134, 1133, 1142, 1144, 1133, 1159, 1125, 1159, 1125, 1125, 1127, 1147, 1134, 1127, 1150, 1151, 1133, 1127, 1145, 1145, 1134, 1145, 1153, 1134, 1140, 1154, 1134, 1133, 1142, 1144, 1133, 1141, 1141, 1141, 1141, 1156, 1158, 1147, 1160, 1158, 1150, 1151, 1157, 1157, 1161, 1157, 1163, 1161, 1153, 613, 1162, 1154, 1162, 607, 601, 1163, 1160, 1165, 1170, 1165, 1177, 1156, 1166, 1166, 1166, 1166, 1167, 1167, 1167, 1167, 1168, 1168, 1168, 1168, 1173, 1169, 1171, 1170, 1172, 1171, 1172, 1163, 1160, 1169, 1174, 1174, 1177, 1174, 1179, 1173, 1180, 1182, 1185, 1184, 600, 1185, 1187, 1187, 1188, 1188, 1188, 1188, 1190, 1170, 1184, 1190, 597, 1184, 1187, 1169, 1184, 1187, 1194, 1189, 1179, 1173, 1180, 1182, 1192, 1184, 1189, 1197, 1198, 1187, 1189, 1193, 1193, 1189, 1193, 1192, 1184, 1202, 1192, 1184, 1187, 1204, 1184, 1187, 1194, 1189, 1196, 1196, 1196, 1196, 1192, 1207, 1189, 1197, 1198, 1208, 1189, 1199, 1199, 1189, 1199, 1192, 1210, 1202, 1192, 1211, 1211, 1204, 1211, 1212, 1214, 1215, 1212, 1214, 1215, 1216, 1217, 1207, 1217, 1219, 1223, 1208, 1218, 1218, 1218, 1218, 1221, 1222, 1210, 1221, 1225, 1226, 1227, 1216, 1219, 1227, 1228, 1228, 1232, 1229, 1230, 1222, 1229, 1230, 1233, 592, 1223, 1233, 1228, 1232, 1237, 1228, 1232, 1238, 1240, 1234, 1225, 1226, 1242, 1216, 1219, 1244, 1245, 1228, 1232, 1245, 1234, 1222, 1234, 1234, 1235, 1235, 1248, 1235, 1228, 1232, 1237, 1228, 1232, 1238, 1240, 1234, 587, 1246, 1242, 1246, 1247, 1244, 1252, 1247, 1252, 1248, 1234, 1256, 1234, 1234, 1249, 1249, 1249, 1249, 1250, 1250, 1250, 1250, 1251, 1257, 1253, 1258, 1251, 1253, 1258, 1260, 1263, 1262, 1260, 1263, 1262, 1248, 1265, 1256, 1261, 1261, 1261, 1261, 1262, 1264, 1264, 1262, 1268, 1269, 1277, 1257, 1277, 1275, 1251, 1278, 1284, 1264, 1286, 1262, 1264, 1289, 1262, 1289, 1265, 1272, 1272, 1272, 1272, 586, 1262, 1275, 1264, 1262, 1268, 1269, 1274, 1274, 1274, 1274, 552, 1278, 1284, 1264, 1286, 1293, 1264, 1276, 1276, 1276, 1276, 1280, 1280, 1280, 1280, 1282, 550, 1275, 1281, 1281, 1281, 1281, 1288, 1288, 1288, 1288, 1282, 1292, 531, 1282, 1292, 1293, 1282, 1291, 1291, 1291, 1291, 1294, 1294, 1294, 1294, 1282, 1295, 1295, 1296, 516, 504, 1296, 1300, 1300, 1300, 1300, 1282, 1302, 1295, 1282, 1302, 1295, 1282, 1301, 1305, 1301, 502, 1305, 1307, 1307, 1307, 1307, 501, 1295, 1308, 1308, 1308, 1308, 1309, 1309, 1309, 1309, 492, 483, 1295, 477, 476, 1295, 1310, 1310, 1310, 1310, 1311, 1311, 1311, 1311, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1314, 1314, 1315, 468, 429, 1315, 1315, 1315, 422, 1315, 1316, 1316, 415, 1316, 413, 1316, 412, 1316, 1317, 1317, 411, 1317, 400, 1317, 307, 1317, 1318, 1318, 1318, 266, 1318, 1318, 1318, 1318, 1318, 1319, 239, 1319, 1320, 235, 232, 1320, 198, 1320, 183, 1320, 1320, 168, 167, 160, 159, 158, 128, 127, 120, 104, 102, 90, 72, 59, 49, 43, 27, 25, 23, 17, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312, 1312 } ; /* Table of booleans, true if rule could match eol. */ static const flex_int32_t yy_rule_can_match_eol[110] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, }; static yy_state_type yy_last_accepting_state; static char *yy_last_accepting_cpos; extern int yy_flex_debug; int yy_flex_debug = 0; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET char *yytext; #line 1 "SCDoc.l" #line 2 "SCDoc.l" /************************************************************************ * * Copyright 2012 Jonatan Liljedahl <lijon@kymatica.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include <string.h> #include "SCDoc.h" #include "SCDoc.tab.hpp" int scdoc_start_token = 0; //int colnum; //#define YY_USER_ACTION { scdoclloc.first_column = colnum; colnum=colnum+yyleng; scdoclloc.last_column=colnum; if(scdoclloc.first_line!=yylineno) colnum=1; scdoclloc.first_line = scdoclloc.last_line = yylineno;} static int method_caller; #line 2123 "lex.scdoc.cpp" #define YY_NO_UNISTD_H 1 #line 2126 "lex.scdoc.cpp" #define INITIAL 0 #define verbatim 1 #define verbatim2 2 #define metadata 3 #define eat 4 #define eat2 5 #define eat3 6 #define method 7 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif static int yy_init_globals ( void ); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int yylex_destroy ( void ); int yyget_debug ( void ); void yyset_debug ( int debug_flag ); YY_EXTRA_TYPE yyget_extra ( void ); void yyset_extra ( YY_EXTRA_TYPE user_defined ); FILE *yyget_in ( void ); void yyset_in ( FILE * _in_str ); FILE *yyget_out ( void ); void yyset_out ( FILE * _out_str ); int yyget_leng ( void ); char *yyget_text ( void ); int yyget_lineno ( void ); void yyset_lineno ( int _line_number ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int yywrap ( void ); #else extern int yywrap ( void ); #endif #endif #ifndef YY_NO_UNPUT static void yyunput ( int c, char *buf_ptr ); #endif #ifndef yytext_ptr static void yy_flex_strncpy ( char *, const char *, int ); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen ( const char * ); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput ( void ); #else static int input ( void ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, (size_t) yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ int n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = (int) fread(buf, 1, (yy_size_t) max_size, yyin)) == 0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int yylex (void); #define YY_DECL int yylex (void) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; if ( !(yy_init) ) { (yy_init) = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! (yy_start) ) (yy_start) = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer( yyin, YY_BUF_SIZE ); } yy_load_buffer_state( ); } { #line 45 "SCDoc.l" #line 50 "SCDoc.l" if (scdoc_start_token) { int t = scdoc_start_token; scdoc_start_token = 0; // colnum = 1; if(t==START_METADATA) BEGIN(eat); return t; } #line 2366 "lex.scdoc.cpp" while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = (yy_c_buf_p); /* Support of yytext. */ *yy_cp = (yy_hold_char); /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = (yy_start); yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 1313 ) yy_c = yy_meta[yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; ++yy_cp; } while ( yy_current_state != 1312 ); yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { int yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) yylineno++; ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = (yy_hold_char); yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); goto yy_find_action; case 1: YY_RULE_SETUP #line 60 "SCDoc.l" return CLASS; YY_BREAK case 2: YY_RULE_SETUP #line 61 "SCDoc.l" return TITLE; YY_BREAK case 3: YY_RULE_SETUP #line 62 "SCDoc.l" return SUMMARY; YY_BREAK case 4: YY_RULE_SETUP #line 63 "SCDoc.l" return RELATED; YY_BREAK case 5: YY_RULE_SETUP #line 64 "SCDoc.l" return CATEGORIES; YY_BREAK case 6: YY_RULE_SETUP #line 65 "SCDoc.l" return REDIRECT; YY_BREAK case 7: YY_RULE_SETUP #line 67 "SCDoc.l" return CLASSTREE; YY_BREAK case 8: YY_RULE_SETUP #line 68 "SCDoc.l" return KEYWORD; YY_BREAK case 9: YY_RULE_SETUP #line 70 "SCDoc.l" return PRIVATE; YY_BREAK case 10: YY_RULE_SETUP #line 71 "SCDoc.l" return SECTION; YY_BREAK case 11: YY_RULE_SETUP #line 72 "SCDoc.l" return SUBSECTION; YY_BREAK case 12: YY_RULE_SETUP #line 73 "SCDoc.l" return SUBSUBSECTION; YY_BREAK case 13: YY_RULE_SETUP #line 74 "SCDoc.l" return COPYMETHOD; YY_BREAK case 14: YY_RULE_SETUP #line 75 "SCDoc.l" method_caller = YY_START; BEGIN(method); return METHOD; YY_BREAK case 15: YY_RULE_SETUP #line 76 "SCDoc.l" return ARGUMENT; YY_BREAK case 16: /* rule 16 can match eol */ YY_RULE_SETUP #line 78 "SCDoc.l" return DESCRIPTION; YY_BREAK case 17: /* rule 17 can match eol */ YY_RULE_SETUP #line 79 "SCDoc.l" return CLASSMETHODS; YY_BREAK case 18: /* rule 18 can match eol */ YY_RULE_SETUP #line 80 "SCDoc.l" return INSTANCEMETHODS; YY_BREAK case 19: /* rule 19 can match eol */ YY_RULE_SETUP #line 81 "SCDoc.l" return EXAMPLES; YY_BREAK case 20: /* rule 20 can match eol */ YY_RULE_SETUP #line 83 "SCDoc.l" return RETURNS; YY_BREAK case 21: /* rule 21 can match eol */ YY_RULE_SETUP #line 84 "SCDoc.l" return DISCUSSION; YY_BREAK case 22: /* rule 22 can match eol */ YY_RULE_SETUP #line 86 "SCDoc.l" return LIST; YY_BREAK case 23: /* rule 23 can match eol */ YY_RULE_SETUP #line 87 "SCDoc.l" return TREE; YY_BREAK case 24: /* rule 24 can match eol */ YY_RULE_SETUP #line 88 "SCDoc.l" return NUMBEREDLIST; YY_BREAK case 25: /* rule 25 can match eol */ YY_RULE_SETUP #line 89 "SCDoc.l" return DEFINITIONLIST; YY_BREAK case 26: /* rule 26 can match eol */ YY_RULE_SETUP #line 90 "SCDoc.l" return TABLE; YY_BREAK case 27: /* rule 27 can match eol */ YY_RULE_SETUP #line 91 "SCDoc.l" return FOOTNOTE; YY_BREAK case 28: /* rule 28 can match eol */ YY_RULE_SETUP #line 92 "SCDoc.l" return WARNING; YY_BREAK case 29: /* rule 29 can match eol */ YY_RULE_SETUP #line 93 "SCDoc.l" return NOTE; YY_BREAK case 30: YY_RULE_SETUP #line 95 "SCDoc.l" BEGIN(verbatim); return LINK; YY_BREAK case 31: YY_RULE_SETUP #line 96 "SCDoc.l" BEGIN(verbatim); return ANCHOR; YY_BREAK case 32: YY_RULE_SETUP #line 97 "SCDoc.l" BEGIN(verbatim); return IMAGE; YY_BREAK case 33: /* rule 33 can match eol */ YY_RULE_SETUP #line 98 "SCDoc.l" BEGIN(verbatim); return SOFT; YY_BREAK case 34: /* rule 34 can match eol */ YY_RULE_SETUP #line 99 "SCDoc.l" BEGIN(verbatim); return STRONG; YY_BREAK case 35: /* rule 35 can match eol */ YY_RULE_SETUP #line 100 "SCDoc.l" BEGIN(verbatim); return EMPHASIS; YY_BREAK case 36: YY_RULE_SETUP #line 101 "SCDoc.l" BEGIN(verbatim); return CODE; YY_BREAK case 37: YY_RULE_SETUP #line 102 "SCDoc.l" BEGIN(verbatim); return TELETYPE; YY_BREAK case 38: YY_RULE_SETUP #line 103 "SCDoc.l" BEGIN(verbatim); return MATH; YY_BREAK case 39: /* rule 39 can match eol */ YY_RULE_SETUP #line 105 "SCDoc.l" BEGIN(verbatim2); return CODEBLOCK; YY_BREAK case 40: /* rule 40 can match eol */ YY_RULE_SETUP #line 106 "SCDoc.l" BEGIN(verbatim2); return TELETYPEBLOCK; YY_BREAK case 41: /* rule 41 can match eol */ YY_RULE_SETUP #line 107 "SCDoc.l" BEGIN(verbatim2); return MATHBLOCK; YY_BREAK case 42: /* rule 42 can match eol */ YY_RULE_SETUP #line 109 "SCDoc.l" BEGIN(0); return TAGSYM; YY_BREAK case 43: /* rule 43 can match eol */ YY_RULE_SETUP #line 110 "SCDoc.l" BEGIN(0); return TAGSYM; YY_BREAK case 44: /* rule 44 can match eol */ YY_RULE_SETUP #line 111 "SCDoc.l" scdoclval.str = strdup("\n::"); return TEXT; YY_BREAK case 45: /* rule 45 can match eol */ YY_RULE_SETUP #line 112 "SCDoc.l" return BARS; YY_BREAK case 46: /* rule 46 can match eol */ YY_RULE_SETUP #line 113 "SCDoc.l" return HASHES; YY_BREAK case 47: /* rule 47 can match eol */ YY_RULE_SETUP #line 115 "SCDoc.l" scdoclval.str = strdup("\n"); return TEXT; YY_BREAK case 48: /* rule 48 can match eol */ YY_RULE_SETUP #line 116 "SCDoc.l" scdoclval.str = strdup(" "); return TEXT; YY_BREAK case 49: /* rule 49 can match eol */ YY_RULE_SETUP #line 117 "SCDoc.l" return NEWLINE; YY_BREAK case 50: /* rule 50 can match eol */ YY_RULE_SETUP #line 118 "SCDoc.l" return EMPTYLINES; YY_BREAK case 51: YY_RULE_SETUP #line 120 "SCDoc.l" scdoclval.str = strdup(scdoctext); return COMMA; YY_BREAK case 52: YY_RULE_SETUP #line 122 "SCDoc.l" scdoclval.str = strdup("||"); return TEXT; YY_BREAK case 53: YY_RULE_SETUP #line 123 "SCDoc.l" scdoclval.str = strdup("##"); return TEXT; YY_BREAK case 54: YY_RULE_SETUP #line 124 "SCDoc.l" scdoclval.str = strdup("::"); return TEXT; YY_BREAK case 55: YY_RULE_SETUP #line 125 "SCDoc.l" scdoclval.str = strdup(" "); return TEXT; YY_BREAK case 56: YY_RULE_SETUP #line 126 "SCDoc.l" scdoclval.str = strdup(" "); return TEXT; YY_BREAK case 57: YY_RULE_SETUP #line 128 "SCDoc.l" /* eat this */ YY_BREAK case 58: YY_RULE_SETUP #line 130 "SCDoc.l" scdoclval.str = strdup(scdoctext); return URL; YY_BREAK case 59: YY_RULE_SETUP #line 131 "SCDoc.l" scdoclval.str = strdup(scdoctext); return METHODNAME; YY_BREAK case 60: /* rule 60 can match eol */ YY_RULE_SETUP #line 132 "SCDoc.l" scdoclval.str = strdup(scdoctext); return METHODARGS; YY_BREAK case 61: YY_RULE_SETUP #line 133 "SCDoc.l" /* eat this */ YY_BREAK case 62: /* rule 62 can match eol */ YY_RULE_SETUP #line 134 "SCDoc.l" BEGIN(method_caller); return NEWLINE; YY_BREAK case 63: YY_RULE_SETUP #line 135 "SCDoc.l" return BAD_METHODNAME; YY_BREAK case 64: #line 138 "SCDoc.l" case 65: #line 139 "SCDoc.l" case 66: #line 140 "SCDoc.l" case 67: #line 141 "SCDoc.l" case 68: YY_RULE_SETUP #line 141 "SCDoc.l" scdoclval.str = strdup(scdoctext); return TEXT; YY_BREAK case 69: YY_RULE_SETUP #line 143 "SCDoc.l" BEGIN(metadata); return CLASS; YY_BREAK case 70: YY_RULE_SETUP #line 144 "SCDoc.l" BEGIN(metadata); return TITLE; YY_BREAK case 71: YY_RULE_SETUP #line 145 "SCDoc.l" BEGIN(metadata); return SUMMARY; YY_BREAK case 72: YY_RULE_SETUP #line 146 "SCDoc.l" BEGIN(metadata); return RELATED; YY_BREAK case 73: YY_RULE_SETUP #line 147 "SCDoc.l" BEGIN(metadata); return CATEGORIES; YY_BREAK case 74: YY_RULE_SETUP #line 148 "SCDoc.l" BEGIN(metadata); return REDIRECT; YY_BREAK case 75: YY_RULE_SETUP #line 149 "SCDoc.l" BEGIN(metadata); return CLASSTREE; YY_BREAK case 76: YY_RULE_SETUP #line 150 "SCDoc.l" BEGIN(metadata); return KEYWORD; YY_BREAK case 77: YY_RULE_SETUP #line 151 "SCDoc.l" BEGIN(metadata); return PRIVATE; YY_BREAK case 78: YY_RULE_SETUP #line 152 "SCDoc.l" BEGIN(metadata); return SECTION; YY_BREAK case 79: YY_RULE_SETUP #line 153 "SCDoc.l" BEGIN(metadata); return SUBSECTION; YY_BREAK case 80: YY_RULE_SETUP #line 154 "SCDoc.l" BEGIN(metadata); return SUBSUBSECTION; YY_BREAK case 81: YY_RULE_SETUP #line 155 "SCDoc.l" BEGIN(metadata); return COPYMETHOD; YY_BREAK case 82: YY_RULE_SETUP #line 156 "SCDoc.l" method_caller = YY_START; BEGIN(method); return METHOD; YY_BREAK case 83: /* rule 83 can match eol */ YY_RULE_SETUP #line 157 "SCDoc.l" BEGIN(eat); return DESCRIPTION; YY_BREAK case 84: /* rule 84 can match eol */ YY_RULE_SETUP #line 158 "SCDoc.l" BEGIN(eat); return CLASSMETHODS; YY_BREAK case 85: /* rule 85 can match eol */ YY_RULE_SETUP #line 159 "SCDoc.l" BEGIN(eat); return INSTANCEMETHODS; YY_BREAK case 86: /* rule 86 can match eol */ YY_RULE_SETUP #line 160 "SCDoc.l" BEGIN(eat); return EXAMPLES; YY_BREAK case 87: /* rule 87 can match eol */ YY_RULE_SETUP #line 161 "SCDoc.l" BEGIN(eat); return NEWLINE; YY_BREAK case 88: YY_RULE_SETUP #line 162 "SCDoc.l" scdoclval.str = strdup(scdoctext); return COMMA; YY_BREAK case 89: #line 164 "SCDoc.l" case 90: #line 165 "SCDoc.l" case 91: #line 166 "SCDoc.l" case 92: YY_RULE_SETUP #line 166 "SCDoc.l" scdoclval.str = strdup(scdoctext); return TEXT; YY_BREAK case 93: YY_RULE_SETUP #line 167 "SCDoc.l" scdoclval.str = strdup("::"); return TEXT; YY_BREAK case 94: YY_RULE_SETUP #line 168 "SCDoc.l" BEGIN(eat2); YY_BREAK case 95: YY_RULE_SETUP #line 169 "SCDoc.l" BEGIN(eat2); YY_BREAK case 96: YY_RULE_SETUP #line 170 "SCDoc.l" BEGIN(eat2); YY_BREAK case 97: /* rule 97 can match eol */ YY_RULE_SETUP #line 171 "SCDoc.l" BEGIN(eat2); YY_BREAK case 98: /* rule 98 can match eol */ YY_RULE_SETUP #line 172 "SCDoc.l" BEGIN(eat2); YY_BREAK case 99: /* rule 99 can match eol */ YY_RULE_SETUP #line 173 "SCDoc.l" BEGIN(eat2); YY_BREAK case 100: YY_RULE_SETUP #line 174 "SCDoc.l" BEGIN(eat2); YY_BREAK case 101: YY_RULE_SETUP #line 175 "SCDoc.l" BEGIN(eat2); YY_BREAK case 102: YY_RULE_SETUP #line 176 "SCDoc.l" BEGIN(eat2); YY_BREAK case 103: /* rule 103 can match eol */ YY_RULE_SETUP #line 177 "SCDoc.l" BEGIN(eat3); YY_BREAK case 104: /* rule 104 can match eol */ YY_RULE_SETUP #line 178 "SCDoc.l" BEGIN(eat3); YY_BREAK case 105: /* rule 105 can match eol */ YY_RULE_SETUP #line 179 "SCDoc.l" BEGIN(eat3); YY_BREAK case 106: /* rule 106 can match eol */ YY_RULE_SETUP #line 180 "SCDoc.l" BEGIN(eat); YY_BREAK case 107: /* rule 107 can match eol */ YY_RULE_SETUP #line 181 "SCDoc.l" BEGIN(eat); YY_BREAK case 108: /* rule 108 can match eol */ YY_RULE_SETUP #line 182 "SCDoc.l" /* empty */ YY_BREAK case 109: YY_RULE_SETUP #line 183 "SCDoc.l" ECHO; YY_BREAK #line 2998 "lex.scdoc.cpp" case YY_STATE_EOF(INITIAL): case YY_STATE_EOF(verbatim): case YY_STATE_EOF(verbatim2): case YY_STATE_EOF(metadata): case YY_STATE_EOF(eat): case YY_STATE_EOF(eat2): case YY_STATE_EOF(eat3): case YY_STATE_EOF(method): yyterminate(); case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = (yy_hold_char); YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) { /* This was really a NUL. */ yy_state_type yy_next_state; (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state ); yy_bp = (yytext_ptr) + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++(yy_c_buf_p); yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); goto yy_find_action; } } else switch ( yy_get_next_buffer( ) ) { case EOB_ACT_END_OF_FILE: { (yy_did_buffer_switch_on_eof) = 0; if ( yywrap( ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: (yy_c_buf_p) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (void) { char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = (yytext_ptr); int number_to_move, i; int ret_val; if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr) - 1); for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0; else { int num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int) ((yy_c_buf_p) - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { int new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ yyrealloc( (void *) b->yy_ch_buf, (yy_size_t) (b->yy_buf_size + 2) ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = NULL; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), (yy_n_chars), num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } if ( (yy_n_chars) == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; yyrestart( yyin ); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if (((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ int new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc( (void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, (yy_size_t) new_size ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); /* "- 2" to take care of EOB's */ YY_CURRENT_BUFFER_LVALUE->yy_buf_size = (int) (new_size - 2); } (yy_n_chars) += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR; (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (void) { yy_state_type yy_current_state; char *yy_cp; yy_current_state = (yy_start); for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 1313 ) yy_c = yy_meta[yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state ) { int yy_is_jam; char *yy_cp = (yy_c_buf_p); YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 1313 ) yy_c = yy_meta[yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; yy_is_jam = (yy_current_state == 1312); return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT static void yyunput (int c, char * yy_bp ) { char *yy_cp; yy_cp = (yy_c_buf_p); /* undo effects of setting up yytext */ *yy_cp = (yy_hold_char); if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) { /* need to shift things up to make room */ /* +2 for EOB chars. */ int number_to_move = (yy_n_chars) + 2; char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[ YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2]; char *source = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]; while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) *--dest = *--source; yy_cp += (int) (dest - source); yy_bp += (int) (dest - source); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = (int) YY_CURRENT_BUFFER_LVALUE->yy_buf_size; if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) YY_FATAL_ERROR( "flex scanner push-back overflow" ); } *--yy_cp = (char) c; if ( c == '\n' ){ --yylineno; } (yytext_ptr) = yy_bp; (yy_hold_char) = *yy_cp; (yy_c_buf_p) = yy_cp; } #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void) #else static int input (void) #endif { int c; *(yy_c_buf_p) = (yy_hold_char); if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) /* This was really a NUL. */ *(yy_c_buf_p) = '\0'; else { /* need more input */ int offset = (int) ((yy_c_buf_p) - (yytext_ptr)); ++(yy_c_buf_p); switch ( yy_get_next_buffer( ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ yyrestart( yyin ); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( yywrap( ) ) return 0; if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(); #else return input(); #endif } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + offset; break; } } } c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */ *(yy_c_buf_p) = '\0'; /* preserve yytext */ (yy_hold_char) = *++(yy_c_buf_p); if ( c == '\n' ) yylineno++; ; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * * @note This function does not reset the start condition to @c INITIAL . */ void yyrestart (FILE * input_file ) { if ( ! YY_CURRENT_BUFFER ){ yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer( yyin, YY_BUF_SIZE ); } yy_init_buffer( YY_CURRENT_BUFFER, input_file ); yy_load_buffer_state( ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * */ void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ) { /* TODO. We should be able to replace this entire function body * with * yypop_buffer_state(); * yypush_buffer_state(new_buffer); */ yyensure_buffer_stack (); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } YY_CURRENT_BUFFER_LVALUE = new_buffer; yy_load_buffer_state( ); /* We don't actually know whether we did this switch during * EOF (yywrap()) processing, but the only time this flag * is looked at is after yywrap() is called, so it's safe * to go ahead and always set it. */ (yy_did_buffer_switch_on_eof) = 1; } static void yy_load_buffer_state (void) { (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; (yy_hold_char) = *(yy_c_buf_p); } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * * @return the allocated buffer state. */ YY_BUFFER_STATE yy_create_buffer (FILE * file, int size ) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) yyalloc( (yy_size_t) (b->yy_buf_size + 2) ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_is_our_buffer = 1; yy_init_buffer( b, file ); return b; } /** Destroy the buffer. * @param b a buffer created with yy_create_buffer() * */ void yy_delete_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) yyfree( (void *) b->yy_ch_buf ); yyfree( (void *) b ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a yyrestart() or at EOF. */ static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file ) { int oerrno = errno; yy_flush_buffer( b ); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then yy_init_buffer was _probably_ * called from yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * */ void yy_flush_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) yy_load_buffer_state( ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * */ void yypush_buffer_state (YY_BUFFER_STATE new_buffer ) { if (new_buffer == NULL) return; yyensure_buffer_stack(); /* This block is copied from yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) (yy_buffer_stack_top)++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from yy_switch_to_buffer. */ yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * */ void yypop_buffer_state (void) { if (!YY_CURRENT_BUFFER) return; yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; if ((yy_buffer_stack_top) > 0) --(yy_buffer_stack_top); if (YY_CURRENT_BUFFER) { yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void yyensure_buffer_stack (void) { yy_size_t num_to_alloc; if (!(yy_buffer_stack)) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */ (yy_buffer_stack) = (struct yy_buffer_state**)yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; (yy_buffer_stack_top) = 0; return; } if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = (yy_buffer_stack_max) + grow_size; (yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc ((yy_buffer_stack), num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size ) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return NULL; b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); b->yy_buf_size = (int) (size - 2); /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = NULL; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; yy_switch_to_buffer( b ); return b; } /** Setup the input buffer state to scan a string. The next call to yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * yy_scan_bytes() instead. */ YY_BUFFER_STATE yy_scan_string (const char * yystr ) { return yy_scan_bytes( yystr, (int) strlen(yystr) ); } /** Setup the input buffer state to scan the given bytes. The next call to yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_bytes (const char * yybytes, int _yybytes_len ) { YY_BUFFER_STATE b; char *buf; yy_size_t n; int i; /* Get memory for full buffer, including space for trailing EOB's. */ n = (yy_size_t) (_yybytes_len + 2); buf = (char *) yyalloc( n ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = yy_scan_buffer( buf, n ); if ( ! b ) YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yynoreturn yy_fatal_error (const char* msg ) { fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = (yy_hold_char); \ (yy_c_buf_p) = yytext + yyless_macro_arg; \ (yy_hold_char) = *(yy_c_buf_p); \ *(yy_c_buf_p) = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the current line number. * */ int yyget_lineno (void) { return yylineno; } /** Get the input stream. * */ FILE *yyget_in (void) { return yyin; } /** Get the output stream. * */ FILE *yyget_out (void) { return yyout; } /** Get the length of the current token. * */ int yyget_leng (void) { return yyleng; } /** Get the current token. * */ char *yyget_text (void) { return yytext; } /** Set the current line number. * @param _line_number line number * */ void yyset_lineno (int _line_number ) { yylineno = _line_number; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. * * @see yy_switch_to_buffer */ void yyset_in (FILE * _in_str ) { yyin = _in_str ; } void yyset_out (FILE * _out_str ) { yyout = _out_str ; } int yyget_debug (void) { return yy_flex_debug; } void yyset_debug (int _bdebug ) { yy_flex_debug = _bdebug ; } static int yy_init_globals (void) { /* Initialization is the same as for the non-reentrant scanner. * This function is called from yylex_destroy(), so don't allocate here. */ /* We do not touch yylineno unless the option is enabled. */ yylineno = 1; (yy_buffer_stack) = NULL; (yy_buffer_stack_top) = 0; (yy_buffer_stack_max) = 0; (yy_c_buf_p) = NULL; (yy_init) = 0; (yy_start) = 0; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = NULL; yyout = NULL; #endif /* For future reference: Set errno on error, since we are called by * yylex_init() */ return 0; } /* yylex_destroy is for both reentrant and non-reentrant scanners. */ int yylex_destroy (void) { /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ yy_delete_buffer( YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; yypop_buffer_state(); } /* Destroy the stack itself. */ yyfree((yy_buffer_stack) ); (yy_buffer_stack) = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * yylex() is called, initialization will occur. */ yy_init_globals( ); return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, const char * s2, int n ) { int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (const char * s ) { int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *yyalloc (yy_size_t size ) { return malloc(size); } void *yyrealloc (void * ptr, yy_size_t size ) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return realloc(ptr, size); } void yyfree (void * ptr ) { free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 183 "SCDoc.l"
142,595
C++
.cpp
3,521
36.372053
212
0.55774
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
30,052
main.cpp
supercollider_supercollider/SCDoc/main.cpp
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include "SCDoc.h" void error(const char* fmt, ...) { fprintf(stderr, "ERROR: "); va_list vargs; va_start(vargs, fmt); vfprintf(stderr, fmt, vargs); fflush(stderr); va_end(vargs); } void post(const char* fmt, ...) { va_list vargs; va_start(vargs, fmt); vfprintf(stderr, fmt, vargs); fflush(stderr); va_end(vargs); } int main(int argc, char** argv) { if (argc > 1) { DocNode* n; if (argc > 2 && strcmp(argv[1], "--partial") == 0) n = scdoc_parse_file(argv[2], SCDOC_PARSE_PARTIAL); else if (argc > 2 && strcmp(argv[1], "--metadata") == 0) n = scdoc_parse_file(argv[2], SCDOC_PARSE_METADATA); else n = scdoc_parse_file(argv[1], SCDOC_PARSE_FULL); if (n) { doc_node_dump(n); doc_node_free_tree(n); } else return 1; } else { fprintf(stderr, "Usage: %s inputfile.schelp\n", argv[0]); } return 0; }
1,064
C++
.cpp
39
21.358974
65
0.555338
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
30,053
SCDoc.cpp
supercollider_supercollider/SCDoc/SCDoc.cpp
/************************************************************************ * * Copyright 2012 Jonatan Liljedahl <lijon@kymatica.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "SCDoc.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <vector> #ifdef _WIN32 # include "SC_Codecvt.hpp" // utf8_cstr_to_utf16_wstring #endif // _WIN32 extern void error(const char* fmt, ...); // for scdoc_parse_file DocNode* scdoc_parse_run(int partial); void scdocrestart(FILE* input_file); int scdoclex_destroy(void); const char* scdoc_current_file = NULL; const char* NODE_TEXT = "TEXT"; const char* NODE_NL = "NL"; // merge a+b and free b char* strmerge(char* a, char* b) { if (a == NULL) return b; if (b == NULL) return a; char* s = (char*)realloc(a, strlen(a) + strlen(b) + 1); strcat(s, b); free(b); return s; } static char* striptrailingws(char* s) { char* s2 = strchr(s, 0); // don't use isspace -- triggers assert with VS while (--s2 > s && (*s2 == ' ' || *s2 == '\t' || *s2 == '\n' || *s2 == '\v' || *s2 == '\f' || *s2 == '\r')) { *s2 = 0; } return s; } DocNode* doc_node_create(const char* id) { DocNode* n = (DocNode*)malloc(sizeof(DocNode)); n->id = id; n->text = NULL; n->n_childs = 0; n->children = NULL; return n; } // takes ownership of child DocNode* doc_node_add_child(DocNode* n, DocNode* child) { if (child) { n->children = (DocNode**)realloc(n->children, (n->n_childs + 1) * sizeof(DocNode*)); n->children[n->n_childs] = child; n->n_childs++; } return n; } // moves the childs from src doc_node to n void doc_node_move_children(DocNode* n, DocNode* src) { if (src) { free(n->children); n->children = src->children; n->n_childs = src->n_childs; // src->children = NULL; // src->n_childs = 0; free(src->text); free(src); } } DocNode* doc_node_make(const char* id, char* text, DocNode* child) { DocNode* n = doc_node_create(id); n->text = text; doc_node_add_child(n, child); return n; } DocNode* doc_node_make_take_children(const char* id, char* text, DocNode* src) { DocNode* n = doc_node_make(id, text, NULL); doc_node_move_children(n, src); return n; } void doc_node_free_tree(DocNode* n) { int i; if (!n) return; free(n->text); for (i = 0; i < n->n_childs; i++) { doc_node_free_tree(n->children[i]); } free(n->children); free(n); } void doc_node_fixup_tree(DocNode* n) { int i; if (n->id != NODE_TEXT && n->text) { n->text = striptrailingws(n->text); } if (n->n_childs) { DocNode* last = n->children[n->n_childs - 1]; if (last->id == NODE_NL) { free(last); // NL has no text or children n->n_childs--; } last = NULL; for (i = 0; i < n->n_childs; i++) { DocNode* child = n->children[i]; if ((child->id == NODE_TEXT || child->id == NODE_NL) && last && last->id == NODE_TEXT) { if (child->id == NODE_NL) { last->text = (char*)realloc(last->text, strlen(last->text) + 2); strcat(last->text, " "); } else { last->text = strmerge(last->text, child->text); } free(child); // we took childs text and it has no children n->children[i] = NULL; } else { doc_node_fixup_tree(child); last = child; } } int j = 0; for (i = 0; i < n->n_childs; i++) { if (n->children[i]) { n->children[j++] = n->children[i]; } } n->n_childs = j; } } /** * Recursive tree printing. * * \param n node to print * \param levelStatuses vector whose size indicates the current recursion depth and whose elements indicate * for each level, whether or not it is the last child. `True` means it is. */ static void doc_node_dump_recursive(DocNode* n, std::vector<bool>& levelStatuses) { if (!levelStatuses.empty()) { for (size_t i = 0; i < levelStatuses.size() - 1; ++i) { printf(levelStatuses[i] ? " " : "| "); } printf(levelStatuses.back() ? "`-- " : "|-- "); } printf("%s", n->id); if (n->text) printf(" \"%s\"", n->text); printf("\n"); for (int i = 0; i < n->n_childs; i++) { levelStatuses.push_back(i == n->n_childs - 1); doc_node_dump_recursive(n->children[i], levelStatuses); levelStatuses.pop_back(); } } void doc_node_dump(DocNode* n) { std::vector<bool> statuses; doc_node_dump_recursive(n, statuses); } DocNode* scdoc_parse_file(const std::string& fn, int mode) { FILE* fp; DocNode* n; // incoming fn is from QString.toStdString(), so it's UTF-8. #ifdef _WIN32 const std::wstring fn_w = SC_Codecvt::utf8_cstr_to_utf16_wstring(fn.c_str()); fp = _wfopen(fn_w.c_str(), L"r"); #else fp = fopen(fn.c_str(), "r"); #endif // _WIN32 if (!fp) { error("scdoc_parse_file: could not open '%s'\n", fn.c_str()); return nullptr; } scdoc_current_file = fn.c_str(); scdocrestart(fp); n = scdoc_parse_run(mode); if (n) { doc_node_fixup_tree(n); } fclose(fp); scdoclex_destroy(); scdoc_current_file = NULL; return n; }
6,193
C++
.cpp
193
26.440415
113
0.556039
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false