id
int64
0
877k
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
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 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
1,535,844
ksvd_dct2D.h
codearxiv_PCReconstruct/dictionarylearning/ksvd_dct2D.h
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef KSVD_DCT2D_H #define KSVD_DCT2D_H #include "alignment.h" #include <Eigen/Dense> #include <vector> #include <functional> class MessageLogger; void ksvd_dct2D( bool useOpenMP, const std::vector<Eigen::VectorXf>& Y, const std::vector<Eigen::VectorXf>& U, const std::vector<Eigen::VectorXf>& V, Eigen::Index nfreq, Eigen::Index latm, int maxIters, float maxError, const std::function<void( const Eigen::VectorXf&, const Eigen::MatrixXf&, Eigen::Index, Eigen::VectorXf&, Eigen::VectorXf& )> sparseFunct, Eigen::MatrixXf& D, Eigen::MatrixXf& X, MessageLogger* msgLogger = nullptr ); void print_error_dct2D( bool useOpenMP, const std::vector<Eigen::VectorXf>& Y, const std::vector<Eigen::VectorXf>& U, const std::vector<Eigen::VectorXf>& V, const Eigen::MatrixXf& D, const Eigen::MatrixXf& X, Eigen::Index nfreq, Eigen::Index iter, MessageLogger* msgLogger ); void column_normalize(Eigen::Ref<Eigen::MatrixXf, ALIGNEDX> M, Eigen::Ref<Eigen::VectorXf, ALIGNEDX> NrmInv); #endif // KSVD_DCT2D_H
1,304
C++
.h
44
25.522727
63
0.663974
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,845
ksvd.h
codearxiv_PCReconstruct/dictionarylearning/ksvd.h
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef KSVD_H #define KSVD_H #include <Eigen/Dense> #include <functional> void ksvd( bool useOpenMP, const Eigen::MatrixXf& Y, Eigen::Index latm, int maxIters, float maxError, int svPowIters, const std::function<void( const Eigen::VectorXf&, const Eigen::MatrixXf&, Eigen::Index, Eigen::VectorXf&, Eigen::VectorXf&)> sparseFunct, Eigen::MatrixXf& D, Eigen::MatrixXf& X ); #endif // KSVD_H
636
C++
.h
24
22.458333
62
0.617057
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,846
OrthogonalPursuit.h
codearxiv_PCReconstruct/dictionarylearning/OrthogonalPursuit.h
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef ORTHOGONALPURSUIT_H #define ORTHOGONALPURSUIT_H #include "alignment.h" #include <Eigen/Dense> #include <vector> class OrthogonalPursuit { using Index = Eigen::Index; using MatrixXf = Eigen::MatrixXf; using VectorXf = Eigen::VectorXf; using MapVectf = Eigen::Map<VectorXf, ALIGNEDX>; using MapMtrxf = Eigen::Map<MatrixXf, ALIGNEDX>; template<typename T> using Map = Eigen::Map<T, ALIGNEDX>; template<typename T> using vector = std::vector<T, Eigen::aligned_allocator<T>>; public: OrthogonalPursuit() : ndim(0), natm(0), lmax(0), dworkOffset(0), U(nullptr,0), V(nullptr,0), W(nullptr,0), XI(nullptr,0), I(nullptr,0), E(nullptr,0,0), F(nullptr,0,0), ETblk(nullptr,0,0), Fblk(nullptr,0,0), ldlt(nullptr), ldltSize(0) {} OrthogonalPursuit(const OrthogonalPursuit &op) : OrthogonalPursuit(){} //{ ensure(sa.ndim, sa.natm, sa.lmax); } ~OrthogonalPursuit(){ delete ldlt; } void ensure(Index nd, Index na, Index lm); void operator() ( const VectorXf& Y, const MatrixXf& D, Index l, VectorXf& X, VectorXf& R); private: void ensureWorkspace(); Index ndim; // Size of signal vector. Index natm; // No. of 'atoms' in dictionary. Index lmax; // maximum sparsity constraint <= natm. vector<float> dwork; size_t dworkOffset; vector<Index> iwork; // Work-space mapped onto work buffer. MapVectf U, V, W, XI; Map< Eigen::Matrix<Index,Eigen::Dynamic,1> > I; MapMtrxf E, F, ETblk, Fblk; Eigen::LDLT<MatrixXf> *ldlt; Index ldltSize; }; #endif // ORTHOGONALPURSUIT_H
1,763
C++
.h
50
31.52
82
0.677227
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,847
MatchingPursuit.h
codearxiv_PCReconstruct/dictionarylearning/MatchingPursuit.h
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef MATCHINGPURSUIT_H #define MATCHINGPURSUIT_H #include "alignment.h" #include <Eigen/Core> class MatchingPursuit { using Index = Eigen::Index; using MatrixXf = Eigen::MatrixXf; using VectorXf = Eigen::VectorXf; public: MatchingPursuit() : ndim(0), natm(0), lmax(0) {} MatchingPursuit(const MatchingPursuit &mp) : MatchingPursuit() {} //{ ensure(sa.ndim, sa.natm, sa.lmax); } ~MatchingPursuit(){} void ensure(Index nd, Index na, Index lm); void operator() ( const VectorXf& Y, const MatrixXf& D, Index l, VectorXf& X, VectorXf& R); private: Index ndim; // Size of signal vector. Index natm; // No. of 'atoms' in dictionary. Index lmax; // maximum sparsity constraint <= natm. }; #endif // MATCHINGPURSUIT_H
961
C++
.h
28
30.607143
67
0.657459
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,848
cosine_transform.h
codearxiv_PCReconstruct/dictionarylearning/cosine_transform.h
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef COSINETRANSFORM_H #define COSINETRANSFORM_H #include "alignment.h" #include <Eigen/Core> #include <vector> void cosine_transform( const Eigen::VectorXf& U, const Eigen::VectorXf& V, Eigen::Index nfreq, std::vector<float, Eigen::aligned_allocator<float>>& dwork, Eigen::Ref<Eigen::MatrixXf, ALIGNEDX> T ); #endif // COSINETRANSFORM_H
556
C++
.h
16
31.125
62
0.644487
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,849
main.cpp
GrowtopiaNoobs_GrowtopiaServer2/src/main.cpp
/********************************************************************************** New Growtopia Private Server Copyright (C) 2019 Growtopia Noobs This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **********************************************************************************/ #include <csignal> #include <chrono> #include <thread> #include <iostream> #include "ENetWrapper/ENetServer.hpp" #include "Server.hpp" void sigint(int) { std::cout << "Caught SIGINT signal! Stopping server..." << std::endl; enet_deinitialize(); exit(0); } void sigterm(int) { std::cout << "Caught SIGTERM signal! Stopping server..." << std::endl; enet_deinitialize(); exit(0); } // TODO: catch other signals too and execute stop event, before server is terminated int main () { std::cout << "GrowServer v0.0.1 starting..." << std::endl; try { ENet_Init(); } catch (...) { std::cout << "An error occurred while initializing ENet." << std::endl; return EXIT_FAILURE; } registerEventPools(); modulesLoader.execute(); registerServerEvents(); std::vector<Server*> servers; for(int i=0; i<4; i++) { Server* s = new Server(); servers.push_back(s); } int serverOffset = 0; const int serverBeginPort = 17091; for(Server* server: servers) { try { server->init(serverBeginPort + serverOffset, 128, "127.0.0.1"); serverOffset++; } catch(...) { std::cout << "Error while initializing server " << serverOffset << ", port " << serverBeginPort + serverOffset << " is busy..." << std::endl; return 1; } } for(Server* server: servers) { server->execute(); } signal(SIGINT, sigint); signal(SIGTERM, sigterm); while (true) { std::this_thread::sleep_for(std::chrono::seconds(10)); } }
2,305
C++
.cpp
67
32.253731
144
0.666965
GrowtopiaNoobs/GrowtopiaServer2
37
21
11
AGPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,850
Server.cpp
GrowtopiaNoobs_GrowtopiaServer2/src/Server.cpp
/********************************************************************************** New Growtopia Private Server Copyright (C) 2019 Growtopia Noobs This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **********************************************************************************/ #include "Server.hpp" EVENT(SendLoginRequestPacket) { try { LoginRequestPacket p; auto peer = pack["peer"]; if(peer.getType() == EventPackDataType::STRING_T) { p.send(server.getPeer(peer)); } else { std::vector<std::string> peers = peer; for(auto x: peers) { p.send(server.getPeer(x)); } } } catch(...) { std::cout << "Missing peer for LoginReuqestPacket" << std::endl; } } EVENT(SendTankPacket) { std::string data; try { TankPacket p; try { p.packetType = (int)pack["packetType"]; } catch(...) {} try { p.netID = (int)pack["netID"]; } catch(...) {} try { p.padding1 = pack["padding1"]; } catch(...) {} try { p.characterState = (int)pack["characterState"]; } catch(...) {} try { p.padding2 = pack["padding2"]; } catch(...) {} try { p.plantingTree = (int)pack["plantingTree"]; } catch(...) {} try { p.x = (float)pack["x"]; } catch(...) {} try { p.y = (float)pack["y"]; } catch(...) {} try { p.XSpeed = (float)pack["XSpeed"]; } catch(...) {} try { p.YSpeed = (float)pack["YSpeed"]; } catch(...) {} try { p.padding3 = pack["padding3"]; } catch(...) {} try { p.punchX = (int)pack["punchX"]; } catch(...) {} try { p.punchY = (int)pack["punchY"]; } catch(...) {} try { std::string data_tmp = pack["data"]; data = std::move(data_tmp); p.setAdditionalData((uint8_t*)data.c_str(), data.length()); } catch(...) {} auto peer = pack["peer"]; if(peer.getType() == EventPackDataType::STRING_T) { p.send(server.getPeer(peer)); } else { std::vector<std::string> peers = peer; for(auto x: peers) { p.send(server.getPeer(x)); } } } catch(...) { std::cout << "Missing peer for TankPacket" << std::endl; } } EVENT(SendVariantPacket) { try { VariantPacket p; std::string packetName = pack["name"]; p.appendString(packetName); try { for(int i=1; ; i++) { EventUnpackRequest item = pack[std::to_string(i)]; switch(item.getType()) { case INTEGER_T: { p.appendIntx(item); break; } case FLOAT_T: { p.appendFloat(item); break; } case VECTOR_FLOAT_T: { std::vector<float> val = item; switch(val.size()) { case 1: { p.appendFloat(val[0]); break; } case 2: { p.appendFloat(val[0], val[1]); break; } case 3: { p.appendFloat(val[0], val[1], val[2]); break; } default: { std::cout << "Unsupported float vector size for VariantList " << packetName << "!" << std::endl; } } break; } case STRING_T: { p.appendString(item); break; } default: { std::cout << "Unsupported VarianList type for " << packetName << "!" << std::endl; break; } } } } catch(...) { } auto peer = pack["peer"]; if(peer.getType() == EventPackDataType::STRING_T) { p.send(server.getPeer(pack["peer"])); } else { std::vector<std::string> peers = peer; for(auto x: peers) { p.send(server.getPeer(x)); } } } catch(...) { std::cout << "Missing peer or packet name for VariantPacket" << std::endl; } } EVENT(SendDisconnect) { try { auto peer = pack["peer"]; if(peer.getType() == EventPackDataType::STRING_T) { server.getPeer(peer).requestDisconnect(); } else { std::vector<std::string> peers = peer; for(auto x: peers) { server.getPeer(x).requestDisconnect(); } } } catch(...) { std::cout << "Missing peer for SendDisconnect" << std::endl; } } void registerServerEvents() { eventRegistrator.register_function("SendLoginRequestPacket", SendLoginRequestPacket); eventRegistrator.register_function("SendTankPacket", SendTankPacket); eventRegistrator.register_function("SendVariantPacket", SendVariantPacket); eventRegistrator.register_function("SendDisconnect", SendDisconnect); } void Server::OnConnect(Peer peer) { uint8_t* tmp = *events.currentDataPtr; std::string id = peer.getUID(); { EventPack pack(_X_); pack["peer"] = peer.getUID(); events.create_event_self("__MallocPeer", pack); } { EventPack pack(_X_); pack["peer"] = peer.getUID(); events.create_event_self("OnPlayerConnect", pack); } *events.currentDataPtr = tmp; } void Server::OnPlayerActionPacket(Peer peer, std::string data) { EventPack pack(_X_); pack["peer"] = peer.getUID(); pack["data"] = data; events.create_event_self("OnPlayerActionPacket", pack); } void Server::OnServerActionPacket(Peer peer, std::string data) { EventPack pack(_X_); pack["peer"] = peer.getUID(); pack["data"] = data; events.create_event_self("OnServerActionPacket", pack); } void Server::OnTankPacket(Peer peer, TankPacketStruct data, uint8_t* additionalData, uint32_t additionalDataSize) { { EventPack pack(_X_); pack["peer"] = peer.getUID(); pack["packetType"] = (int)data.packetType; pack["netID"] = (int)data.netID; pack["plantingTree"] = (int)data.plantingTree; pack["characterState"] = (int)data.characterState; pack["x"] = (float)data.x; pack["y"] = (float)data.y; pack["xSpeed"] = (float)data.XSpeed; pack["ySpeed"] = (float)data.YSpeed; pack["punchX"] = (int)data.punchX; pack["punchY"] = (int)data.punchY; std::string data; data.resize(additionalDataSize); memcpy((void*)data.c_str(), (void*)additionalData, additionalDataSize); pack["data"] = data; events.create_event_self("OnTankPacket", pack); } } void Server::OnUnknownPacket(Peer peer, int type) { EventPack pack(_X_); pack["text"] = "Please implement packet type: " + std::to_string(type); events.create_event_self("ConsoleLog", pack); } void Server::OnRecievedPacket(Peer peer, uint8_t* data, uint32_t dataLen) { uint8_t* tmp = *events.currentDataPtr; decode(peer, data, dataLen); *events.currentDataPtr = tmp; } void Server::OnDisconnect(Peer peer) { uint8_t* tmp = *events.currentDataPtr; EventPack pack(_X_); pack["peer"] = peer.getUID(); events.create_event_self("OnPlayerDisconnect", pack); *events.currentDataPtr = tmp; } void Server::OnPeriodicEvent() { events.execute(*this); }
6,983
C++
.cpp
244
25.17623
115
0.636918
GrowtopiaNoobs/GrowtopiaServer2
37
21
11
AGPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,851
VariantList.cpp
GrowtopiaNoobs_GrowtopiaServer2/src/Packets/PacketsEncoder/VariantList/VariantList.cpp
/********************************************************************************** New Growtopia Private Server Copyright (C) 2019 Growtopia Noobs This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **********************************************************************************/ #include "VariantList.hpp" template <typename t, int exceptedSize> void VariantList::appendValue(t val) { static_assert(sizeof(val) == exceptedSize, "Invalid VariantList data size (probably compiler issue)"); this->data.insert(this->data.end(), sizeof(val), 0); memcpy(this->data.data() + this->data.size() - sizeof(val), &val, sizeof(val)); } VariantList& VariantList::appendFloat(float val) { this->data.push_back(this->indexes); this->data.push_back(1); this->appendValue<float, 4>(val); this->indexes++; return *this; } VariantList& VariantList::appendFloat(float val, float val2) { this->data.push_back(this->indexes); this->data.push_back(3); this->appendValue<float, 4>(val); this->appendValue<float, 4>(val2); this->indexes++; return *this; } VariantList& VariantList::appendFloat(float val, float val2, float val3) { this->data.push_back(this->indexes); this->data.push_back(4); this->appendValue<float, 4>(val); this->appendValue<float, 4>(val2); this->appendValue<float, 4>(val3); this->indexes++; return *this; } VariantList& VariantList::appendInt(int val) { this->data.push_back(this->indexes); this->data.push_back(9); this->appendValue<int, 4>(val); this->indexes++; return *this; } VariantList& VariantList::appendIntx(int val) { this->data.push_back(this->indexes); this->data.push_back(5); this->appendValue<int, 4>(val); this->indexes++; return *this; } VariantList& VariantList::appendString(std::string str) { this->data.push_back(this->indexes); this->data.push_back(2); int sLen = str.length(); this->appendValue<int, 4>(sLen); for (int i = 0; i < sLen; i++) { this->data.push_back(str[i]); } this->indexes++; return *this; } std::vector<uint8_t> VariantList::getData() { std::vector<uint8_t> Tdata = this->data; Tdata.insert(Tdata.begin(), this->indexes); return Tdata; } VariantList::VariantList() { indexes = 0; } VariantList::VariantList(std::string packetName) { VariantList(); this->appendString(packetName); } VariantList::~VariantList() { }
2,910
C++
.cpp
89
30.876404
103
0.700036
GrowtopiaNoobs/GrowtopiaServer2
37
21
11
AGPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,852
EventsHandler.cpp
GrowtopiaNoobs_GrowtopiaServer2/src/Events/EventsHandler.cpp
/********************************************************************************** New Growtopia Private Server Copyright (C) 2019 Growtopia Noobs This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **********************************************************************************/ #include "EventsHandler.h" EventRegistrator eventRegistrator; FuncitonRegistrator functionRegistrator; std::list<EventsHandlerPool> pools; std::list<std::vector<EventsHandler>> othersHandlerSyncer; void registerEventPools() { pools = std::list<EventsHandlerPool>(); othersHandlerSyncer = std::list<std::vector<EventsHandler>>(); } bool ModulesLoaderUtils::hasEnding(std::string const &fullString, std::string const &ending) { if (fullString.length() >= ending.length()) { return (0 == fullString.compare(fullString.length() - ending.length(), ending.length(), ending)); } else { return false; } } void moduleRegisterEvent(char* name, void* event) { std::string nameS = name; eventRegistrator.register_function(name, (EventHandler)event); } void moduleRegisterEventGuard(char* name, void* event) { std::string nameS = name; eventRegistrator.register_guard(name, (GuardHandler)event); } void moduleRegisterFunction(char* name, void* event) { std::string nameS = name; functionRegistrator.register_function(name, (FucntionHandler)event); } void module_create_event_self(void* ptr, char* name, uint8_t* data, long long int msTime) { EventsGlobalPool* pool = (EventsGlobalPool*)ptr; pool->create_event_self(name, data, msTime); } void module_create_event_global(void* ptr, char* name, uint8_t* data, long long int msTime) { EventsGlobalPool* pool = (EventsGlobalPool*)ptr; pool->create_event_global(name, data, msTime); } void module_create_event_self_and_global(void* ptr, char* name, uint8_t* data, long long int msTime) { EventsGlobalPool* pool = (EventsGlobalPool*)ptr; pool->create_event_self_and_global(name, data, msTime); } uint8_t* module_call_function(void* eventGeneratorPtr, char* name, uint8_t* data, char* serverName, void* serverPtr, uint8_t** memPtr) { return functionRegistrator.execute(name, data, serverName, serverPtr, eventGeneratorPtr, memPtr).getData(); } ModulesLoader modulesLoader;
2,814
C++
.cpp
58
46.706897
136
0.734233
GrowtopiaNoobs/GrowtopiaServer2
37
21
11
AGPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,853
Event.cpp
GrowtopiaNoobs_GrowtopiaServer2/src/Events/Event.cpp
/********************************************************************************** New Growtopia Private Server Copyright (C) 2019 Growtopia Noobs This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **********************************************************************************/ #include "Event.h" void EventPackData::operator=(int arg) { int sizePos = push_header(EventPackDataType::INTEGER_T); this->push_back(arg); add_data_size(sizePos, sizeof(int)); } void EventPackData::operator=(std::vector<int> arg) { int sizePos = push_header(EventPackDataType::VECTOR_INTEGER_T); for(int val: arg) { this->push_back(val); } add_data_size(sizePos, sizeof(int)*arg.size()); } void EventPackData::operator=(long long int arg) { int sizePos = push_header(EventPackDataType::LONG_INTEGER_T); this->push_back(arg); add_data_size(sizePos, sizeof(long long int)); } void EventPackData::operator=(std::vector<long long int> arg) { int sizePos = push_header(EventPackDataType::VECTOR_LONG_INTEGER_T); for(long long int val: arg) { this->push_back(val); } add_data_size(sizePos, sizeof(long long int)*arg.size()); } void EventPackData::operator=(float arg) { int sizePos = push_header(EventPackDataType::FLOAT_T); this->push_back(arg); add_data_size(sizePos, sizeof(int)); } void EventPackData::operator=(std::vector<float> arg) { int sizePos = push_header(EventPackDataType::VECTOR_FLOAT_T); for(int val: arg) { this->push_back(val); } add_data_size(sizePos, sizeof(int)*arg.size()); } void EventPackData::operator=(std::string arg) { int sizePos = push_header(EventPackDataType::STRING_T); this->push_back(arg.c_str(), arg.length()); add_data_size(sizePos, arg.length()); } void EventPackData::operator=(std::vector<std::string> arg) { int sizePos = push_header(EventPackDataType::VECTOR_STRING_T); int length_final = 0; for(std::string val: arg) { int len = val.length(); this->push_back(len); this->push_back(val.c_str(), len); length_final += len + sizeof(int); } add_data_size(sizePos, length_final); } void EventPackData::operator=(EventPack arg) { int sizePos = push_header(EventPackDataType::EVENT_PACK_T); int dataSize; uint8_t *data = arg.serialize(&dataSize); this->push_back(data, dataSize); add_data_size(sizePos, dataSize); } void EventPackData::operator=(std::vector<EventPack> arg) { int sizePos = push_header(EventPackDataType::VECTOR_EVENT_PACK_T); int length_final = 0; for(EventPack& pack: arg) { int dataSize; uint8_t *data = pack.serialize(&dataSize); this->push_back(dataSize); this->push_back(data, dataSize); length_final += dataSize + sizeof(int); } add_data_size(sizePos, length_final); } void EventPackData::operator=(EventUnpack arg) { int sizePos = push_header(EventPackDataType::EVENT_PACK_T); int dataSize; if(arg.getData() == NULL) { dataSize = 0; } else { dataSize = *(int*)arg.getData(); } uint8_t *data = arg.getData(); this->push_back(data, dataSize+sizeof(int)); add_data_size(sizePos, dataSize+sizeof(int)); } void EventUnpackRequest::resolve_value(uint8_t* ptr, EventUnpack& ret) { if(*(short*)ptr!=EventPackDataType::EVENT_PACK_T) throw; ptr+=sizeof(short); if(*(int*)ptr == 0) { ret = EventUnpack(NULL); } else { ptr+=sizeof(int); ret = EventUnpack(ptr); } } void EventUnpackRequest::resolve_value(uint8_t* ptr, std::vector<EventUnpack>& ret) { if(*(short*)ptr!=EventPackDataType::VECTOR_EVENT_PACK_T) throw; ptr+=sizeof(short); int size=*(int*)ptr; ptr+=sizeof(int); for(int i=0; i<size; ) { int pack_size = *(int*)ptr; ptr+=sizeof(int); i+=sizeof(int); ret.push_back(EventUnpack(ptr)); ptr+=pack_size; i+=pack_size; } }
4,268
C++
.cpp
122
32.893443
85
0.703802
GrowtopiaNoobs/GrowtopiaServer2
37
21
11
AGPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
1,535,854
PeersIterator.cpp
GrowtopiaNoobs_GrowtopiaServer2/src/ENetWrapper/PeersIterator.cpp
/********************************************************************************** New Growtopia Private Server Copyright (C) 2019 Growtopia Noobs This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **********************************************************************************/ #include "PeersIterator.hpp"
907
C++
.cpp
15
58.533333
83
0.651685
GrowtopiaNoobs/GrowtopiaServer2
37
21
11
AGPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
1,535,857
ENetServer.cpp
GrowtopiaNoobs_GrowtopiaServer2/src/ENetWrapper/ENetServer.cpp
/********************************************************************************** New Growtopia Private Server Copyright (C) 2019 Growtopia Noobs This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **********************************************************************************/ #include "ENetServer.hpp" short ENetServer::id_generator = 0; void ENet_Init() { if (enet_initialize() != 0) { throw; } atexit(enet_deinitialize); } std::thread& ENetServer::getThread() { return this->t; } void ENetServer::run() { ENetEvent event; /* Wait up to 1000 milliseconds for an event. */ while (true) { while (enet_host_service(server, &event, 10) > 0) { Peer peer(event.peer, id); switch (event.type) { case ENET_EVENT_TYPE_CONNECT: event.peer->data = NULL; /* Store any relevant client information here. */ OnConnect(peer); break; case ENET_EVENT_TYPE_RECEIVE: OnRecievedPacket(peer, event.packet->data, event.packet->dataLength); /* Clean up the packet now that we're done using it. */ enet_packet_destroy(event.packet); break; case ENET_EVENT_TYPE_DISCONNECT: OnDisconnect(peer); /* Reset the peer's client information. */ if((char *)event.peer->data != NULL) { delete (char *)event.peer->data; event.peer->data = NULL; } } } OnPeriodicEvent(); } } void ENetServer::init(int port, int maxPeers) { if (this->server != NULL) throw; ENetAddress address; address.host = ENET_HOST_ANY; address.port = port; server = enet_host_create(&address /* the address to bind the server host to */, maxPeers /* allow up to maxPeers clients and/or outgoing connections */, 2 /* allow up to 2 channels to be used, 0 and 1 */, 0 /* assume any amount of incoming bandwidth */, 0 /* assume any amount of outgoing bandwidth */); if (server == NULL) { throw; } server->checksum = enet_crc32; enet_host_compress_with_range_coder(server); } void ENetServer::execute() { std::thread t(&ENetServer::run, this); this->t = move(t); } ENetServer::ENetServer() { this->server = NULL; auto id_tpm = id_generator++; int str_len = sizeof(id_generator)*2; id.resize(str_len); static const char* digits = "0123456789ABCDEF"; for (unsigned int i=0; i<str_len; ++i) id[i] = digits[(id_tpm>>(i<<2)) & 0x0f]; } ENetServer::ENetServer(int port, int maxPeers) : ENetServer() { init(port, maxPeers); } ENetServer::~ENetServer() { enet_host_destroy(server); } void ENetServer::OnConnect(Peer peer) { std::cout << "OnConnect is not set! forgot to override?" << std::endl; } void ENetServer::OnRecievedPacket(Peer peer, uint8_t* data, uint32_t dataLen) { std::cout << "OnRecievedPacket is not set! forgot to override?" << std::endl; } void ENetServer::OnDisconnect(Peer peer) { std::cout << "OnDisconnect is not set! forgot to override?" << std::endl; } void ENetServer::OnPeriodicEvent() { std::cout << "OnPeriodicEvent is not set! forgot to override?" << std::endl; } PeersIterator ENetServer::getPeers() { PeersIterator it(this->server->peers, this->server->peerCount, id); return it; } Peer ENetServer::getPeer(std::string peerID) { for(int i=0; i<this->server->peerCount; i++) { if(this->server->peers[i].state == ENET_PEER_STATE_CONNECTED) { if(peerID == Peer(&this->server->peers[i], id).getUID()) { return Peer(&this->server->peers[i], id); } } } return Peer(NULL, ""); } void* ENetServer::getServerPtr() { return (void*)server; } std::string ENetServer::getServerID() { return id; } void ENetServer::setServerData(uint8_t* data) { server->data = (void*) data; } uint8_t* ENetServer::getServerData() { return (uint8_t*)server->data; }
4,285
C++
.cpp
132
29.916667
83
0.679419
GrowtopiaNoobs/GrowtopiaServer2
37
21
11
AGPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,859
Server.hpp
GrowtopiaNoobs_GrowtopiaServer2/src/Server.hpp
/********************************************************************************** New Growtopia Private Server Copyright (C) 2019 Growtopia Noobs This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **********************************************************************************/ #pragma once #define _X_ (this->events.currentDataPtr) #include <map> #include <vector> #include <string> #include "ENetWrapper/ENetServer.hpp" #include "Packets/PacketsDecoder/PacketsDecoder.hpp" #include "Packets/PacketsEncoder/PacketsEncoder.hpp" #include "Events/EventsHandler.h" void registerServerEvents(); struct ServerData { // add variables under existing ones, so compatibility isn't broken char* serverUrl; int serverPort; }; class Server : public ENetServer, private PacketDecoder { private: EventsGlobalPool events; void OnConnect(Peer peer) override; void OnRecievedPacket(Peer peer, uint8_t* data, uint32_t dataLen) override; void OnDisconnect(Peer peer) override; void OnPeriodicEvent() override; void OnPlayerActionPacket(Peer peer, std::string data) override; void OnServerActionPacket(Peer peer, std::string data) override; void OnTankPacket(Peer peer, TankPacketStruct data, uint8_t* additionalData, uint32_t additionalDataSize) override; void OnUnknownPacket(Peer peer, int type) override; public: Server() {}; void init(int port, int peerCount, std::string url) { uint8_t* tmp = *events.currentDataPtr; ENetServer::init(port, peerCount); ServerData* data = new ServerData; char* name = new char[url.length()+1]; memcpy(name, url.c_str(), url.length()+1); data->serverUrl = name; data->serverPort = port; setServerData((uint8_t*)data); EventPack pack(_X_); events.create_event_self("__MallocServer", pack); OnPeriodicEvent(); *events.currentDataPtr = tmp; } void execute() { ENetServer::execute(); } };
2,453
C++
.h
59
39.474576
116
0.726815
GrowtopiaNoobs/GrowtopiaServer2
37
21
11
AGPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,860
PacketsCommon.hpp
GrowtopiaNoobs_GrowtopiaServer2/src/Packets/PacketsCommon/PacketsCommon.hpp
/********************************************************************************** New Growtopia Private Server Copyright (C) 2019 Growtopia Noobs This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **********************************************************************************/ #pragma once struct TankPacketStruct { uint32_t packetType = 0; int32_t netID = 0; uint32_t padding1 = 0; uint32_t characterState = 0; uint32_t padding2 = 0; uint32_t plantingTree = 0; float x = 0; float y = 0; float XSpeed = 0; float YSpeed = 0; uint32_t padding3 = 0; uint32_t punchX = 0; uint32_t punchY = 0; uint32_t packetLenght = 0; }; static_assert(sizeof(TankPacketStruct) == 56, "Ivalid size of TankPacketStruct, maybe your compiler isnt supported");
1,354
C++
.h
32
40.375
117
0.674507
GrowtopiaNoobs/GrowtopiaServer2
37
21
11
AGPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,861
PacketsDecoder.hpp
GrowtopiaNoobs_GrowtopiaServer2/src/Packets/PacketsDecoder/PacketsDecoder.hpp
/********************************************************************************** New Growtopia Private Server Copyright (C) 2019 Growtopia Noobs This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **********************************************************************************/ #pragma once #include <iostream> #include "../PacketsCommon/PacketsCommon.hpp" #include "../../ENetWrapper/Peer.hpp" class PacketDecoder { private: std::string dataToString(uint8_t* data, uint32_t dataLen) { std::string ret; ret.resize(dataLen-1); std::memcpy((void*)ret.data(), data, dataLen - 1); return ret; } uint8_t* dataToTankData(uint8_t* data, uint32_t len) { uint8_t* ret = NULL; if (len >= 56) { TankPacketStruct* tankData = (TankPacketStruct*)data; if (tankData->characterState & 8) { if (len < tankData->packetLenght + 56) { ret = 0; } } else { tankData->packetLenght = 0; } } return ret; } protected: virtual void OnPlayerActionPacket(Peer peer, std::string data); virtual void OnServerActionPacket(Peer peer, std::string data); virtual void OnTankPacket(Peer peer, TankPacketStruct data, uint8_t* additionalData, uint32_t additionalDataSize); virtual void OnUnknownPacket(Peer peer, int type); public: void decode(Peer peer, uint8_t* data, uint32_t length) { if (length < 5) throw; int packetType = *(int*)data; data += 4; length -= 4; switch (packetType) { case 2: { OnPlayerActionPacket(peer, dataToString(data, length)); break; } case 3: { OnServerActionPacket(peer, dataToString(data, length)); break; } case 4: { if (length < 56) throw; uint8_t* tankUpdatePacket = dataToTankData(data, length); TankPacketStruct tankData = *(TankPacketStruct*)data; if (tankUpdatePacket) { uint8_t* dataPtr; if (length > sizeof(TankPacketStruct)) { dataPtr = tankUpdatePacket + sizeof(TankPacketStruct); } else { dataPtr = NULL; } OnTankPacket(peer, tankData, dataPtr, length - sizeof(TankPacketStruct)); } else { OnTankPacket(peer, tankData, 0, 0); } break; } /*case 5: { break; } case 6: { std::cout << "Got packet type 6 with content: " << PacketHandler::GetTextPointerFromPacket(packet)) << std::endl; break; }*/ default: { OnUnknownPacket(peer, packetType); break; } } } }; inline void PacketDecoder::OnPlayerActionPacket(Peer peer, std::string data) { std::cout << "OnPlayerActionPacket is not set! forgot to override?" << std::endl; } inline void PacketDecoder::OnServerActionPacket(Peer peer, std::string data) { std::cout << "OnServerActionPacket is not set! forgot to override?" << std::endl; } inline void PacketDecoder::OnTankPacket(Peer peer, TankPacketStruct data, uint8_t* additionalData, uint32_t additionalDataSize) { std::cout << "OnTankPacket is not set! forgot to override?" << std::endl; } inline void PacketDecoder::OnUnknownPacket(Peer peer, int type) { std::cout << "OnUnknownPacket is not set! forgot to override?" << std::endl; }
3,653
C++
.h
118
28
116
0.689028
GrowtopiaNoobs/GrowtopiaServer2
37
21
11
AGPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,862
PacketsEncoder.hpp
GrowtopiaNoobs_GrowtopiaServer2/src/Packets/PacketsEncoder/PacketsEncoder.hpp
/********************************************************************************** New Growtopia Private Server Copyright (C) 2019 Growtopia Noobs This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **********************************************************************************/ #pragma once #include "../PacketsCommon/PacketsCommon.hpp" #include "VariantList/VariantList.hpp" #include "../../ENetWrapper/ENetServer.hpp" class Packet { public: virtual void send(Peer peer) { std::cout << "Please implement send method for Packet" << std::endl; } }; class TankPacket : public TankPacketStruct, public Packet { private: uint8_t* data = NULL; int dataLenght = 0; public: void setAdditionalData(uint8_t* data, int dataLenght) { this->data = data; this->dataLenght = dataLenght; } void send(Peer peer) override { if (data == NULL || dataLenght == 0) { TankPacketStruct data = *this; this->packetLenght = 0; peer.sendPacket(4, (char*)&data, sizeof(TankPacketStruct)); } else { int sizeOfDataToSend = sizeof(TankPacketStruct) + dataLenght; this->packetLenght = dataLenght; uint8_t* dataToSend = new uint8_t[sizeOfDataToSend]; TankPacketStruct dataStruct = *this; memcpy(dataToSend, &dataStruct, sizeof(TankPacketStruct)); memcpy(dataToSend + sizeof(TankPacketStruct), this->data, dataLenght); peer.sendPacket(4, (char*)dataToSend, sizeOfDataToSend); delete dataToSend; } } }; class VariantPacket : public VariantList, public TankPacket { private: void setAdditionalData(uint8_t* data, int dataLenght); public: VariantPacket() : VariantList() { packetType = 1; netID = -1; characterState = 8; } VariantPacket(std::string name, int netID = -1) : VariantList(name) { VariantPacket(); this->netID = netID; packetType = 1; characterState = 8; } void send(Peer peer) override { std::vector<uint8_t> tempData = getData(); TankPacket::setAdditionalData(tempData.data(), tempData.size()); TankPacket::send(peer); } }; class TextPacket : public Packet { private: std::string data; public: TextPacket(std::string text = "") { this->data = text; } void setText(std::string text) { this->data = text; } void send(Peer peer) override { peer.sendPacket(3, (char*)data.c_str(), data.length()); } }; class LoginRequestPacket : public Packet { public: void send(Peer peer) override { peer.sendPacket(1, 0, 0); } };
3,000
C++
.h
91
30.593407
83
0.701348
GrowtopiaNoobs/GrowtopiaServer2
37
21
11
AGPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,863
VariantList.hpp
GrowtopiaNoobs_GrowtopiaServer2/src/Packets/PacketsEncoder/VariantList/VariantList.hpp
/********************************************************************************** New Growtopia Private Server Copyright (C) 2019 Growtopia Noobs This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **********************************************************************************/ #pragma once #include <string> #include <cstring> #include <enet/enet.h> #include <vector> class VariantList { private: std::vector<uint8_t> data; int indexes = 0; template <typename t, int e> void appendValue(t val); public: VariantList& appendFloat(float val); VariantList& appendFloat(float val1, float val2); VariantList& appendFloat(float val1, float val2, float val3); VariantList& appendInt(int val); VariantList& appendIntx(int val); VariantList& appendString(std::string str); std::vector<uint8_t> getData(); VariantList(); VariantList(std::string packetName); ~VariantList(); };
1,485
C++
.h
38
37.236842
83
0.696044
GrowtopiaNoobs/GrowtopiaServer2
37
21
11
AGPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,865
EventsHandler.h
GrowtopiaNoobs_GrowtopiaServer2/src/Events/EventsHandler.h
/********************************************************************************** New Growtopia Private Server Copyright (C) 2019 Growtopia Noobs This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **********************************************************************************/ #ifndef __EVENTS_HANDLER_H__ #define __EVENTS_HANDLER_H__ #include "Event.h" #include <list> #include <unordered_map> #include <chrono> #include "../ENetWrapper/ENetServer.hpp" struct EventRunnableStuff { std::vector<EventHandler> events; std::vector<GuardHandler> guards; }; class EventRegistrator { private: std::unordered_map<std::string, EventRunnableStuff> map; public: void register_function(const std::string& key, EventHandler handler) { if(map.find(key) == map.end()) { // key not found EventRunnableStuff x; x.events.push_back(handler); map.insert({key, x}); } else { // key found map.find(key)->second.events.push_back(handler); } } void register_guard(const std::string& key, GuardHandler handler) { auto item = map.find(key); if(item == map.end()) { // key not found EventRunnableStuff x; x.guards.push_back(handler); map.insert({key, x}); } else { // key found item->second.guards.push_back(handler); } } inline int serverIDtoInt(const char* name) { int ret = 0; uint32_t inc = 0; while(*name) { uint8_t retTmp = *(name++); if(retTmp>'9') { ret += ((uint32_t)(retTmp-'A'))<<inc; } else { ret += ((uint32_t)(retTmp-'0'))<<inc; } inc+=4; } return ret; } void execute(const std::string& key, EventUnpack& pack, ENetServer& server, void* pool_ptr, uint8_t** currentDataPtr) { auto handlers = map.find(key); auto handlersAny = map.find("*"); if(handlers == map.end() && handlersAny == map.end()) return; bool canBeLaunched = true; auto serverPtr = server.getServerPtr(); uint8_t* tmp = *currentDataPtr; if(handlers != map.end()) for(GuardHandler handler: handlers->second.guards) { try { bool x = (*handler)(pack.getData(), (char*)server.getServerID().c_str(), serverPtr, pool_ptr, currentDataPtr); if(!x) { canBeLaunched = false; } } catch(...) { std::cout << "Uncought exception in event-guard " << handlers->first << std::endl; } } if(handlersAny != map.end() && !handlersAny->second.guards.empty()) { EventPack anyPack(currentDataPtr); anyPack["name"] = key; anyPack["data"] = (EventUnpack)pack; EventUnpack anyUnpack(anyPack.serialize()); for(GuardHandler handler: handlersAny->second.guards) { try { bool x = (*handler)(anyUnpack.getData(), (char*)server.getServerID().c_str(), serverPtr, pool_ptr, currentDataPtr); if(!x) { canBeLaunched = false; } } catch(...) { std::cout << "Uncought exception in event-guard " << handlersAny->first << std::endl; } } } *currentDataPtr = tmp; if(canBeLaunched) { if(handlers != map.end()) for (EventHandler handler: handlers->second.events) { try { (*handler)(pack.getData(), (char*)server.getServerID().c_str(), serverPtr, pool_ptr, currentDataPtr); } catch (...) { std::cout << "Uncought exception in event " << handlers->first << std::endl; } } if(handlersAny != map.end() && !handlersAny->second.events.empty()) { EventPack anyPack(currentDataPtr); anyPack["name"] = key; anyPack["data"] = (EventUnpack)pack; EventUnpack anyUnpack(anyPack.serialize()); for (EventHandler handler: handlersAny->second.events) { try { (*handler)(anyUnpack.getData(), (char*)server.getServerID().c_str(), serverPtr, pool_ptr, currentDataPtr); } catch (...) { std::cout << "Uncought exception in event " << handlersAny->first << std::endl; } } } } *currentDataPtr = tmp; } }; class FuncitonRegistrator { private: std::unordered_map<std::string, std::vector<FucntionHandler>> map; public: void register_function(std::string key, FucntionHandler handler) { if(map.find(key) == map.end()) { // key not found std::vector<FucntionHandler> vec; vec.push_back(handler); map.insert({key, vec}); } else { // key found map.find(key)->second.push_back(handler); } } EventUnpack execute(const std::string& key, uint8_t* pack, char* serverName, void* serverPtr, void* pool_ptr, uint8_t** currentDataPtr) { uint8_t* ret; auto mapFuncs = map.find(key); auto anyFuncs = map.find("*"); if(mapFuncs == map.end() && anyFuncs == map.end()) return EventUnpack(NULL); if(mapFuncs != map.end()) for(FucntionHandler handler: mapFuncs->second) { ret = (*handler)(pack, serverName, serverPtr, pool_ptr, currentDataPtr); if(!EventUnpack(ret).isEmpty()) return EventUnpack(ret); } if(anyFuncs != map.end()) { EventPack anyPack(currentDataPtr); anyPack["name"] = key; anyPack["data"] = (EventUnpack) pack; EventUnpack anyUnpack(anyPack.serialize()); for (FucntionHandler handler: anyFuncs->second) { ret = (*handler)(anyUnpack.getData(), serverName, serverPtr, pool_ptr, currentDataPtr); if (!EventUnpack(ret).isEmpty()) return EventUnpack(ret); } } return EventUnpack(ret); } EventUnpack execute(const std::string& key, EventUnpack pack, ENetServer& server, void* pool_ptr, uint8_t** currentDataPtr) { uint8_t* ret; auto mapFuncs = map.find(key); if(mapFuncs == map.end()) return EventUnpack(NULL); for(FucntionHandler handler: mapFuncs->second) { ret = (*handler)(pack.getData(), (char *) server.getServerID().c_str(), server.getServerPtr(), pool_ptr, currentDataPtr); if(!EventUnpack(ret).isEmpty()) return EventUnpack(ret); } return EventUnpack(ret); } }; extern EventRegistrator eventRegistrator; extern FuncitonRegistrator functionRegistrator; struct Event { std::string name; EventUnpack data; long long int time = 0; public: Event(std::string name, EventUnpack data) : name(std::move(name)), data(data) {}; }; class EventsHandler { std::list<Event>& events; public: void create_event(std::string name, EventUnpack data, long long int msTime=0) { void* data_copy; if(data.isEmpty()) { data_copy = malloc(4); *(int*)data_copy = 0; } else { int size = (*(int*)data.getData()) + 4; data_copy = malloc(size); memcpy(data_copy, data.getData(), size); } Event event(std::move(name), (uint8_t*)data_copy); if(msTime!=0) { event.time = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now().time_since_epoch()).count() + msTime; } else { event.time = 0; } events.push_back(event); } bool operator==(std::list<Event>& x) { return addressof(x) == addressof(events); } explicit EventsHandler(std::list<Event> &events) : events(events) {} }; class EventsHandlerPool { std::list<std::list<Event>> pool; public: void execute(ENetServer& server, void* pool_ptr, uint8_t** currentDataPtr) { for(std::list<Event>& events: pool) { long long int time = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now().time_since_epoch()).count(); auto i = events.begin(); while (i != events.end()) { if (i->time == 0 || i->time <= time) { eventRegistrator.execute(i->name, i->data, server, pool_ptr, currentDataPtr); free(i->data.getData()); events.erase(i++); } else { ++i; } } } } EventsHandler requestHandler() { std::list<Event> v; pool.push_back(v); EventsHandler e(pool.back()); return e; } bool isChild(EventsHandler x) { for(std::list<Event>& y: pool) { if (x==y) return true; } return false; } }; extern std::list<EventsHandlerPool> pools; extern std::list<std::vector<EventsHandler>> othersHandlerSyncer; void registerEventPools(); class EventsGlobalPool { private: EventsHandlerPool& pool; EventsHandler selfHandler; std::vector<EventsHandler>& othersHandler; uint8_t* temporaryData; static EventsHandlerPool& generateSelfHandler() { pools.emplace_back(EventsHandlerPool()); return pools.back(); } static std::vector<EventsHandler>& generateOthersHandlerSyncer() { othersHandlerSyncer.emplace_back(std::vector<EventsHandler>()); return othersHandlerSyncer.back(); } public: uint8_t** currentDataPtr; void create_event_self(const std::string& name, EventUnpack data, long long int msTime=0) { selfHandler.create_event(std::move(name), data, msTime); } void create_event_global(const std::string& name, const EventUnpack& data, long long int msTime=0) { for(EventsHandler handler: othersHandler) { handler.create_event(name, data, msTime); } } void create_event_self_and_global(const std::string& name, const EventUnpack& data, long long int msTime=0) { create_event_self(name, data, msTime); create_event_global(name, data, msTime); } EventUnpack call_function(const std::string& key, EventUnpack pack, ENetServer& server) { return functionRegistrator.execute(key, pack, server, (void*)this, currentDataPtr); } void execute(ENetServer& server) { pool.execute(server, (void*)this, currentDataPtr); } EventsGlobalPool() : pool(generateSelfHandler()), selfHandler(pool.requestHandler()), othersHandler(generateOthersHandlerSyncer()) { for(EventsHandlerPool& p: pools) { if(!p.isChild(selfHandler)) { othersHandler.emplace_back(p.requestHandler()); } } for(std::vector<EventsHandler>& x: othersHandlerSyncer) { if(addressof(x)!=addressof(othersHandler)) { x.emplace_back(pool.requestHandler()); } } temporaryData = new uint8_t[16000000]; currentDataPtr = new uint8_t*; *currentDataPtr = temporaryData; } }; #include <iostream> namespace ModulesLoaderUtils { bool hasEnding(std::string const &fullString, std::string const &ending); } #define MODULE_API_VERSION 1 void moduleRegisterEvent(char* name, void* event); void moduleRegisterEventGuard(char* name, void* event); void moduleRegisterFunction(char* name, void* event); void module_create_event_self(void* ptr, char* name, uint8_t* data, long long int msTime); void module_create_event_global(void* ptr, char* name, uint8_t* data, long long int msTime); void module_create_event_self_and_global(void* ptr, char* name, uint8_t* data, long long int msTime); uint8_t* module_call_function(void* eventGeneratorPtr, char* name, uint8_t* data, char* serverName, void* serverPtr, uint8_t** memPtr); #ifdef _WIN32 #include <windows.h> #else #include <dirent.h> #include <dlfcn.h> #endif class ModulesLoader { public: void execute() { #ifdef _WIN32 HANDLE hFind; WIN32_FIND_DATA data; hFind = FindFirstFile("./modules/*", &data); if (hFind != INVALID_HANDLE_VALUE) { do { if (ModulesLoaderUtils::hasEnding(data.cFileName, ".dll")) { std::string totalPath = "./modules/"; totalPath += data.cFileName; HINSTANCE handle = LoadLibrary(totalPath.c_str()); if(handle == NULL) { std::cout << "DLL open error: " << GetLastError() << std::endl; continue; } int (*moduleVerFunction)() = (int (*)()) GetProcAddress(handle, "ModuleGetVersion"); if (moduleVerFunction == NULL) { std::cout << "Dynamic library " << data.cFileName << " isn't valid server module!" << std::endl; continue; } int moduleVer = moduleVerFunction(); if (moduleVer == MODULE_API_VERSION) { std::cout << "Loading module " << data.cFileName << "..." << std::endl; ((void (*)(void *, void *, void *, void *, void *, void*, void*)) GetProcAddress(handle, "ModuleExecuteSetup"))((void*)moduleRegisterEvent, (void*)moduleRegisterEventGuard, (void*)moduleRegisterFunction, (void*)module_create_event_self, (void*)module_create_event_global, (void*)module_create_event_self_and_global, (void*)module_call_function); } else { std::cout << "Module " << data.cFileName << " (" << moduleVer <<") have different API version than server (" << MODULE_API_VERSION << ")." << std::endl; } } } while (FindNextFile(hFind, &data)); FindClose(hFind); std::cout << "All modules were loaded!" << std::endl; } else { std::cout << "Error opening ./modules/ directory" << std::endl; } #else DIR *dir; struct dirent *ent; if ((dir = opendir("./modules/")) != NULL) { /* print all the files and directories within directory */ while ((ent = readdir(dir)) != NULL) { if (ModulesLoaderUtils::hasEnding(ent->d_name, ".so")) { std::string totalPath = "./modules/"; totalPath += ent->d_name; void *handle = dlopen(totalPath.c_str(), RTLD_LAZY); if(handle == NULL) { std::cout << dlerror() << std::endl; continue; } int (*moduleVerFunction)() = (int (*)()) dlsym(handle, "ModuleGetVersion"); if (moduleVerFunction == NULL) { std::cout << "Dynamic library " << ent->d_name << " isn't valid server module!" << std::endl; continue; } int moduleVer = moduleVerFunction(); if (moduleVer == MODULE_API_VERSION) { std::cout << "Loading module " << ent->d_name << "..." << std::endl; ((void (*)(void *, void *, void *, void *, void *, void*, void*)) dlsym(handle, "ModuleExecuteSetup"))((void*)moduleRegisterEvent, (void*)moduleRegisterEventGuard, (void*)moduleRegisterFunction, (void*)module_create_event_self, (void*)module_create_event_global, (void*)module_create_event_self_and_global, (void*)module_call_function); } else { std::cout << "Module " << ent->d_name << " (" << moduleVer <<") have different API version than server (" << MODULE_API_VERSION << ")." << std::endl; } } } closedir(dir); std::cout << "All modules were loaded!" << std::endl; } else { std::cout << "Error opening ./modules/ directory" << std::endl; } #endif } }; extern ModulesLoader modulesLoader; #endif
14,298
C++
.h
382
33.997382
351
0.677454
GrowtopiaNoobs/GrowtopiaServer2
37
21
11
AGPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,866
ENetServer.hpp
GrowtopiaNoobs_GrowtopiaServer2/src/ENetWrapper/ENetServer.hpp
/********************************************************************************** New Growtopia Private Server Copyright (C) 2019 Growtopia Noobs This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **********************************************************************************/ #pragma once #include <enet/enet.h> #include <thread> #include <string> #include <iostream> #include "Peer.hpp" #include "PeersIterator.hpp" void ENet_Init(); class ENetServer { protected: std::thread& getThread(); void init(int port, int maxPeers); void execute(); ENetServer(); ENetServer(int port, int maxPeers = 256); ~ENetServer(); private: static short id_generator; std::thread t; ENetHost * server; std::string id; virtual void OnConnect(Peer peer); virtual void OnRecievedPacket(Peer peer, uint8_t* data, uint32_t dataLen); virtual void OnDisconnect(Peer peer); virtual void OnPeriodicEvent(); void run(); public: PeersIterator getPeers(); Peer getPeer(std::string id); void* getServerPtr(); std::string getServerID(); void setServerData(uint8_t* data); uint8_t* getServerData(); };
1,697
C++
.h
48
33.5
83
0.700183
GrowtopiaNoobs/GrowtopiaServer2
37
21
11
AGPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,868
ENetWrapper.hpp
GrowtopiaNoobs_GrowtopiaServer2/src/ENetWrapper/ENetWrapper.hpp
/********************************************************************************** New Growtopia Private Server Copyright (C) 2019 Growtopia Noobs This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **********************************************************************************/ #pragma once #include <enet/enet.h> #include <thread> #include <string> #include "Peer.hpp" #include "ENetServer.hpp"
998
C++
.h
20
48.1
83
0.660164
GrowtopiaNoobs/GrowtopiaServer2
37
21
11
AGPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,869
PeersIterator.hpp
GrowtopiaNoobs_GrowtopiaServer2/src/ENetWrapper/PeersIterator.hpp
/********************************************************************************** New Growtopia Private Server Copyright (C) 2019 Growtopia Noobs This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **********************************************************************************/ #pragma once #include "Peer.hpp" class PeersIterator { // https://gist.github.com/jeetsukumaran/307264 ENetPeer* peersBegin = NULL; int size = 0; std::string serverID = ""; class iterator { public: typedef iterator self_type; typedef ENetPeer* value_type; typedef ENetPeer& reference; typedef ENetPeer* pointer; typedef std::forward_iterator_tag iterator_category; typedef int difference_type; iterator(pointer ptr, pointer begin, int size, std::string serverID) : ptr_(ptr), serverID(std::move(serverID)) { begin_ = begin; size_ = size; } self_type operator++() { self_type i = *this; ptr_++; while (ptr_ < &begin_[size_] && ptr_->state != ENET_PEER_STATE_CONNECTED) ptr_++; return i; } self_type operator++(int junk) { ptr_++; while (ptr_ < &begin_[size_] && ptr_->state != ENET_PEER_STATE_CONNECTED) ptr_++; return *this; } Peer operator*() { Peer p(ptr_, serverID); return p; } Peer operator->() { Peer p(ptr_, serverID); return p; } bool operator==(const self_type& rhs) { return ptr_ == rhs.ptr_; } bool operator!=(const self_type& rhs) { return ptr_ != rhs.ptr_; } private: pointer ptr_; pointer begin_; int size_; std::string serverID = ""; }; public: iterator begin() const { int i = 0; while (true) { if (peersBegin[i].state != ENET_PEER_STATE_CONNECTED && i<size) { i++; } else { break; } } return iterator(&peersBegin[i], peersBegin, size, serverID); } iterator end() const { return iterator(&peersBegin[size], peersBegin, 0, serverID); } PeersIterator(ENetPeer* peers, int size, std::string serverID) : serverID(std::move(serverID)) { this->peersBegin = peers; this->size = size; } PeersIterator() { this->peersBegin = 0; this->size = 0; } };
2,671
C++
.h
82
29.731707
147
0.656323
GrowtopiaNoobs/GrowtopiaServer2
37
21
11
AGPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
1,535,889
main.cpp
g1n0st_AyaRay/src/main.cpp
#include "Core/integrator.h" #include "Core/Medium.h" #include <array> #include "Media/Homogeneous.h" #include "Core\BSDF.h" #include "BSDFs\LambertianDiffuse.h" #include "BSDFs\Glass.h" #include "Core/Memory.h" #include "BSDFs\Mirror.h" #include "BSDFs\Disney.h" #include "Accelerators\BVH.h" #include "Core\Scene.h" #include "Core\Camera.h" #include "Lights\AreaLight.h" #include "Lights\EnvironmentLight.h" #include "Lights\PointLight.h" #include "Lights\SpotLight.h" #include "Lights\DirectionalLight.h" #include "Integrators\DirectLighting.h" #include "Integrators\PathTracing.h" #include "Integrators\BidirectionalPathTracing.h" #include "Samplers\RandomSampler.h" #include "Samplers\SobolSampler.h" #include "Filters\BoxFilter.h" #include "Filters\GaussianFilter.h" #include "Filters\MitchellNetravaliFilter.h" #include "Filters\TriangleFilter.h" #include "Integrators\VertexCM.h" #include "Math\Matrix4x4.h" using namespace Aya; using namespace std; void ayaInit() { //Aya::SampledSpectrum::init(); } std::unique_ptr<BSDF> scene_parser_lambertian(const ObjMaterial &mtl) { std::unique_ptr<BSDF> bsdf; if (mtl.Tf != Spectrum(0.f)) { bsdf = std::make_unique<Glass>(mtl.Tf, 1.f, mtl.Ni); } else if (mtl.Ks[0] > 0.4f) { bsdf = std::make_unique<Glass>(Spectrum(1.f, 1.f, 1.f), 1.f, 1.5f); } else { /*std::unique_ptr<Texture2D<float>> specular; if (mtl.map_Ks[0]) specular = std::make_unique<ImageTexture2D<float, float>>(mtl.map_Ks); else specular = std::make_unique<ConstantTexture2D<float>>((mtl.Ks[0] + mtl.Ks[1] + mtl.Ks[2]) / 3.f); std::unique_ptr<Texture2D<float>> roughness = std::make_unique<ConstantTexture2D<float>>((512.f - mtl.Ns) / 512.f); float metallic = mtl.Ns / 512.f; */ if (mtl.map_Kd[0]) bsdf = std::make_unique<LambertianDiffuse>(mtl.map_Kd); else bsdf = std::make_unique<LambertianDiffuse>(Spectrum(mtl.Kd)); } //if (mtl.map_Bump[0]) // bsdf->setNormalMap(mtl.map_Bump); return bsdf; } RNG rr; std::unique_ptr<BSDF> hahaha(const ObjMaterial &mtl) { return std::make_unique<Disney>(Spectrum::fromRGB(rr.drand48(), rr.drand48(), rr.drand48()), std::make_unique<ConstantTexture2D<float>>(0.1f), std::make_unique<ConstantTexture2D<float>>(0.9f)); } int main(void) { ayaInit(); int testnumx = 600; int testnumy = 600; RNG rng; RandomSampler *random_sampler = new RandomSampler(); SobolSampler *sobol_sampler = new SobolSampler(testnumx, testnumy); GaussianFilter *filter = new GaussianFilter(); MitchellNetravaliFilter *mfilter = new MitchellNetravaliFilter(); //Camera *cam = new Camera(Point3(-5, 0, 0), Vector3(0, 0, 0), Vector3(0, -1, 0), testnumx, testnumy, 40.f, 0.1f, 1000.f, 0.1f, 5, 2.f); Camera *cam = new Camera(Point3(6, 1.5, 0), Vector3(0, 1.5, 0), Vector3(0, -1, 0), testnumx, testnumy, 40.f); //Camera *cam = new Camera(Point3(-7.73, 1.47, 7.50), Point3(-8.49, 0.94, 7.12), Vector3(0.47f, -0.85, 0.24), testnumx, testnumy, 75); //Camera *cam = new Camera(Point3(-12.38, 2.03, -0.39), Point3(-13.23, 1.67, -0.76), Vector3(0.34, -0.93, 0.15), testnumx, testnumy, 40); //Camera *cam = new Camera(Point3(-24.79, 7.58, -1.87), Point3(-23.80, 7.43, -1.88), Vector3(-0.15, -0.99, -0.00), testnumx, testnumy, 40); //Camera *cam = new Camera(Point3(-15.12f, 3.73f, 9.96f), Point3(-14.58f, 3.06f, 9.45f), Vector3(-0.48f, -0.75f, 0.46f), testnumx, testnumy, 30); Film *film = new Film(testnumx, testnumy, mfilter); // Tomoko Tracker //for (int i = 82; i <= 85; i++) // for (int j = 531; j <= 534; j++) //film->splat(i, 900 - j, Spectrum(10.f, 10.f, 10.f)); //film->addSampleCount(); //film->updateDisplay(); //Bitmap::save("test.bmp", (float*)film->getPixelBuffer(), testnumx, testnumy, RGBA_32); Transform murb = Transform().setScale(0.04f, 0.04f, 0.04f) * Transform().setEulerZYX(0, 15, 0); AffineTransform cb = AffineTransform().setScale(2, 2, 2) * AffineTransform().setEulerZYX(0, 90, 0); AffineTransform cbb = AffineTransform().setScale(1.3f, 1.3f, 1.3f); Transform bunnyc = Transform().setScale(0.4f, 0.4f, 0.4f) * Transform().setTranslate(-0.2f, 0, -1.5f) * AffineTransform().setEulerZYX(0, 75, 0); Transform bunnyb = Transform().setScale(0.5f, 0.5f, 0.5f) * Transform().setTranslate(0.6f, 2.1f, 1.4f) * AffineTransform().setEulerZYX(0, 130, 0); Transform idt = Transform() * Transform().setScale(0.004f, 0.004f, 0.004f) * Transform().setTranslate(60, -420, 0); Transform o2w = Transform().setTranslate(-2.04f, 1.56f, 0) * Transform().setScale(3, 3.25f, 4) * Transform().setEulerZYX(0, 0, -90); Transform o2w1 = Transform().setTranslate(3, 1.4f, 0); int st = clock(); Primitive * primitive = new Primitive(); Primitive * light_p = new Primitive(); Primitive *bunny = new Primitive(); Primitive *bunny0 = new Primitive(); Primitive *mur = new Primitive(); Primitive *teapot = new Primitive(); Primitive *plane = new Primitive(); //primitive->loadMesh(o2w, "teapot.obj", true); //primitive->loadPlane(o2w, 3, std::make_unique<LambertianDiffuse>(Spectrum(1.f, 1.f, 1.f))); //light_p->loadMesh(cb, "./cornell-box/light.obj"); //mur->loadMesh(murb, "mur.obj", true); RNG dr; dr.srand(time(0)); printf("Reading models...\n"); bunny0->loadMesh(bunnyb, "bunny.obj", [](const ObjMaterial &mtl) { return std::make_unique<Glass>(Spectrum::fromRGB(1.f, 1.f, 1.f), 1.f, 2.f); } , true, true); bunny->loadMesh(bunnyc, "bunny.obj", [](const ObjMaterial &mtl) { return std::make_unique<LambertianDiffuse>(Spectrum::fromRGB(100.f / 255.f, 149.f / 255.f, 225.0f / 255.0f)); } , true, true); //bunny->loadMesh(bunnyc, "bunny.obj", true, true, std::make_unique<Disney>(Spectrum::fromRGB(100.f / 255.f, 149.f / 255.f, 225.0f / 255.0f), 0.1f, 0.9f)); //plane->loadPlane(o2w, 1, std::make_unique<Disney>("background.jpg", 0.0f, 1.0f)); //plane->loadPlane(o2w, 1, std::make_unique<LambertianDiffuse>(Spectrum(0.5, 0.5, 0.5))); //primitive->loadPlane(o2w, 2, std::make_unique<Glass>(Spectrum::fromRGB(1.f, 1.f, 1.f))); //primitive->loadMesh(o2w, "teapot.obj", true, std::make_unique<Glass>(Spectrum::fromRGB(1.f, 0.7529f, 0.796f), 1.f, 1.5f)); //teapot->loadMesh(bunnyc, "teapot.obj", false, true, std::make_unique<Glass>(Spectrum::fromRGB(1.f, 1.f, 1.f), 1.f, 1.5f)); //primitive->loadMesh(idt, "Alucy.obj", true, std::make_unique<Mirror>(Spectrum::fromRGB(1.f, 1.f, 1.f))); //primitive->loadMesh(idt, "Alucy.obj", true, std::make_unique<LambertianDiffuse>(Spectrum::fromRGB(1.f, 1.f, 1.f))); //primitive->loadMesh(cb, "./cornell-box/CornellBox-Water.obj"); primitive->loadMesh(cb, "./cornell-box/CornellBox-Empty-Squashed.obj", &scene_parser_lambertian); //primitive->loadMesh(Transform(), "san-miguel.obj", &scene_parser_lambertian, true, true); //primitive->loadMesh(o2w, "teapot.obj", true, std::make_unique<Glass>(Spectrum::fromRGB(1.f, 1.f, 1.f))); //primitive->loadMesh(o2w, "teapot.obj", true, true, std::make_unique<Disney>(Spectrum::fromRGB(65.f / 255.f, 105.f / 255.f, 225.f / 255.f), 0.0f, 1.0f, 0.0f, 0, 0, 0.5f, 0.f)); //primitive->loadMesh(cb, "shaderball.obj", true, true); //primitive->loadSphere(cbb, 1, std::make_unique<Disney>(Spectrum::fromRGB(0.05f, 0.05f, 0.05f), // std::make_unique<ImageTexture2D<float, float>> ("piso_rustico_Spec.png"), std::make_unique<ImageTexture2D<float, float>> ("piso_rustico_Spec.png"))); Scene *scene = new Scene(); //scene->addPrimitive(plane); scene->addPrimitive(primitive); //scene->addPrimitive(teapot); scene->addPrimitive(bunny0); scene->addPrimitive(bunny); //scene->addPrimitive(light_p); //scene->addLight(new EnvironmentLight("uffizi-large.hdr", scene)); //scene->addLight(new EnvironmentLight("forest.jpg", scene)); //scene->addLight(new PointLight(Point3(3, 1, 0), Spectrum(2.f, 2.f, 2.f))); //scene->addLight(new SpotLight(Point3(3, 1, 0), Spectrum(1.f, 1.f, 1.f), Vector3(0, -1, 0), 20, 0)); ////scene->addLight(new DirectionalLight(Vector3(1.3, -1, 0), Spectrum(2.f, 2.f, 2.f), scene, 30)); Primitive * l1 = new Primitive(); //Primitive * l2 = new Primitive(); //l1->loadSphere(Transform().setTranslate(3, 1, 0), 0.5, std::make_unique<LambertianDiffuse>(Spectrum::fromRGB(1.f, 1.f, 1.f))); //l2->loadSphere(Transform().setTranslate(-0.6, 2.7, 1.3), 0.2, std::make_unique<LambertianDiffuse>(Spectrum::fromRGB(1.f, 1.f, 1.f))); //scene->addLight(new AreaLight(l1, Spectrum(10.f, 10.f, 10.f))); //scene->addLight(new AreaLight(l2, Spectrum(0.f, 0, 1.f))); //scene->addLight(new PointLight(Point3(0.6, 3.0, 1.2), Spectrum(1.f, 55.0 / 255.0 * 1, 0.f))); scene->addLight(new PointLight(Point3(0, 3.10f, 0), Spectrum(8.f, 8.f, 8.f))); //scene->addLight(new AreaLight(light_p, Spectrum::fromRGB(10.f, 10.f, 10.f))); //scene->addLight(new EnvironmentLight("uffizi-large.hdr", scene, 1.f)); //scene->addLight(new EnvironmentLight(Spectrum::fromRGB(8.f, 8.f, 8.f), scene)); //scene->addLight(new DirectionalLight(Vector3(0.21, -0.7, -0.67), Spectrum(50000, 50000, 50000), scene, 1.f)); //scene->addLight(new DirectionalLight(Vector3(0.38f, -0.9f, 0.24f), Spectrum(25000, 25000, 25000), scene, 1.f)); printf("Constructing accelerator...\n"); scene->initAccelerator(); TaskSynchronizer task(testnumx, testnumy); int spp = 200; DirectLightingIntegrator *dl = new DirectLightingIntegrator(task, spp, 5); PathTracingIntegrator *pt = new PathTracingIntegrator(task, spp, 16); BidirectionalPathTracingIntegrator *bdpt = new BidirectionalPathTracingIntegrator(task, spp, 32, cam, film); VertexCMIntegrator *vcm = new VertexCMIntegrator(task, spp, 0, 16, cam, film, VertexCMIntegrator::AlgorithmType::kBpt, 0.003f, 0.75f); MemoryPool memory; bdpt->render(scene, cam, random_sampler, film); //vcm->render(scene, cam, random_sampler, film); //pt->render(scene, cam, sobol_sampler , film); //dl->render(scene, cam, sobol_sampler, film); cout << clock() - st << endl; Bitmap::save("test.bmp", (float*)film->getPixelBuffer(), testnumx, testnumy, RGBA_32); return 0; }
9,898
C++
.cpp
177
53.903955
178
0.695518
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,891
EmbreeAccelerator.cpp
g1n0st_AyaRay/src/Accelerators/EmbreeAccelerator.cpp
#include <Accelerators/EmbreeAccelerator.h> namespace Aya { #if defined AYA_USE_EMBREE void EmbreeAccel::construct(const std::vector<Primitive*> &prims) { #if (AYA_USE_EMBREE == 3) if (!m_device) { m_device = rtcNewDevice(nullptr); } if (!m_rtcScene) { m_rtcScene = rtcNewScene(m_device); rtcSetSceneBuildQuality(m_rtcScene, RTC_BUILD_QUALITY_HIGH); rtcSetSceneFlags(m_rtcScene, RTC_SCENE_FLAG_ROBUST); } for (int i = 0; i < prims.size(); i++) { auto mesh = prims[i]->getMesh(); auto geom = rtcNewGeometry(m_device, RTC_GEOMETRY_TYPE_TRIANGLE); rtcSetSharedGeometryBuffer(geom, RTC_BUFFER_TYPE_VERTEX, 0, RTC_FORMAT_FLOAT3, mesh->getVertexBuffer(), 0, sizeof(MeshVertex), mesh->getVertexCount()); rtcSetSharedGeometryBuffer(geom, RTC_BUFFER_TYPE_INDEX, 0, RTC_FORMAT_UINT3, mesh->getIndexBuffer(), 0, sizeof(uint32_t) * 3, mesh->getTriangleCount()); rtcCommitGeometry(geom); rtcAttachGeometryByID(m_rtcScene, geom, i); rtcSetGeometryIntersectFilterFunction(geom, &alphaTest); rtcSetGeometryOccludedFilterFunction(geom, &alphaTest); rtcSetGeometryUserData(geom, prims[i]); rtcReleaseGeometry(geom); } rtcCommitScene(m_rtcScene); #elif (AYA_USE_EMBREE == 2) m_device = rtcNewDevice(nullptr); m_rtcScene = rtcDeviceNewScene(m_device, RTC_SCENE_STATIC | RTC_SCENE_INCOHERENT | RTC_SCENE_HIGH_QUALITY, RTC_INTERSECT1); for (auto &prim : prims) { uint32_t geomID = rtcNewTriangleMesh( m_rtcScene, RTC_GEOMETRY_STATIC, prim->getMesh()->getTriangleCount(), prim->getMesh()->getVertexCount()); rtcSetBuffer(m_rtcScene, geomID, RTC_VERTEX_BUFFER, prim->getMesh()->getVertexBuffer(), 0, sizeof(MeshVertex)); rtcSetBuffer(m_rtcScene, geomID, RTC_INDEX_BUFFER, prim->getMesh()->getIndexBuffer(), 0, 3 * sizeof(uint32_t)); rtcSetIntersectionFilterFunction(m_rtcScene, geomID, (RTCFilterFunc)&alphaTest); rtcSetOcclusionFilterFunction(m_rtcScene, geomID, (RTCFilterFunc)&alphaTest); rtcSetUserData(m_rtcScene, geomID, prim); } rtcCommit(m_rtcScene); #endif } BBox EmbreeAccel::worldBound() const { RTCBounds rtc_bound; #if (AYA_USE_EMBREE == 3) rtcGetSceneBounds(m_rtcScene, &rtc_bound); #elif (AYA_USE_EMBREE == 2) rtcGetBounds(m_rtcScene, rtc_bound); #endif return BBox( Point3(rtc_bound.lower_x, rtc_bound.lower_y, rtc_bound.lower_z), Point3(rtc_bound.upper_x, rtc_bound.upper_y, rtc_bound.upper_z) ); } bool EmbreeAccel::intersect(const Ray &ray, Intersection *si) const { #if (AYA_USE_EMBREE == 3) RTCRayHit ray_hit; ray_hit.ray = toRTCRay(ray); ray_hit.hit.geomID = RTC_INVALID_GEOMETRY_ID; ray_hit.hit.primID = RTC_INVALID_GEOMETRY_ID; ray_hit.hit.instID[0] = RTC_INVALID_GEOMETRY_ID; RTCIntersectContext context; rtcInitIntersectContext(&context); rtcIntersect1(m_rtcScene, &context, &ray_hit); if (ray_hit.hit.geomID == RTC_INVALID_GEOMETRY_ID || ray_hit.hit.primID == RTC_INVALID_GEOMETRY_ID) return false; si->prim_id = ray_hit.hit.geomID; si->tri_id = ray_hit.hit.primID; si->dist = ray_hit.ray.tfar; si->u = ray_hit.hit.u; si->v = ray_hit.hit.v; ray.m_maxt = si->dist; return true; #elif (AYA_USE_EMBREE == 2) RTCRay rtc_ray = toRTCRay(ray); rtc_ray.mask = -1; rtcIntersect(m_rtcScene, rtc_ray); if (rtc_ray.geomID == RTC_INVALID_GEOMETRY_ID) return false; si->prim_id = rtc_ray.geomID; si->tri_id = rtc_ray.primID; si->dist = rtc_ray.tfar; si->u = rtc_ray.u; si->v = rtc_ray.v; ray.m_maxt = si->dist; return true; #endif } bool EmbreeAccel::occluded(const Ray &ray) const { RTCRay rtc_ray = toRTCRay(ray); #if (AYA_USE_EMBREE == 3) RTCIntersectContext context; rtcInitIntersectContext(&context); rtcOccluded1(m_rtcScene, &context, &rtc_ray); return rtc_ray.tfar < 0; #elif (AYA_USE_EMBREE == 2) rtcOccluded(m_rtcScene, rtc_ray); return rtc_ray.geomID != RTC_INVALID_GEOMETRY_ID; #endif } EmbreeAccel::~EmbreeAccel() { #if (AYA_USE_EMBREE == 3) if (m_rtcScene) { rtcReleaseScene(m_rtcScene); } if (m_device) { rtcReleaseDevice(m_device); } #endif } #endif }
4,114
C++
.cpp
117
31.957265
114
0.718214
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,893
RandomSampler.cpp
g1n0st_AyaRay/src/Samplers/RandomSampler.cpp
#include <Samplers/RandomSampler.h> namespace Aya { void RandomSampler::generateSamples( const int pixel_x, const int pixel_y, CameraSample *samples, RNG &rng) { assert(samples); samples->image_x = rng.drand48(); samples->image_y = rng.drand48(); samples->lens_u = rng.drand48(); samples->lens_v = rng.drand48(); samples->time = rng.drand48(); } void RandomSampler::startPixel(const int pixel_x, const int pixel_y) {} float RandomSampler::get1D() { return rng.drand48(); } Vector2f RandomSampler::get2D() { return Vector2f(rng.drand48(), rng.drand48()); } Sample RandomSampler::getSample() { return Sample(rng); } std::unique_ptr<Sampler> RandomSampler::clone(const int seed) const { return std::make_unique<RandomSampler>(seed); } std::unique_ptr<Sampler> RandomSampler::deepClone() const { RandomSampler *copy = new RandomSampler(); memcpy_s(copy, sizeof(RandomSampler), this, sizeof(RandomSampler)); return std::unique_ptr<RandomSampler>(copy); } }
1,001
C++
.cpp
33
27.848485
72
0.728778
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,895
SobolSampler.cpp
g1n0st_AyaRay/src/Samplers/SobolSampler.cpp
#include <Samplers/SobolSampler.h> namespace Aya { void SobolSampler::generateSamples( const int pixel_x, const int pixel_y, CameraSample *samples, RNG &rng) { assert(samples); samples->image_x = sobolSample(m_dim++) * m_res - pixel_x; samples->image_y = sobolSample(m_dim++) * m_res - pixel_y; samples->lens_u = sobolSample(m_dim++); samples->lens_v = sobolSample(m_dim++); samples->time = sobolSample(m_dim++); } void SobolSampler::advanceSampleIndex() { m_sampleIdx++; } void SobolSampler::startPixel(const int px, const int py) { m_sobolIdx = enumerateSampleIndex(px, py); m_dim = 0; } float SobolSampler::get1D() { return sobolSample(m_dim++); } Vector2f SobolSampler::get2D() { int dim = m_dim; Vector2f ret = Vector2f( sobolSample(m_dim), sobolSample(m_dim + 1) ); m_dim += 2; return ret; } Sample SobolSampler::getSample() { int dim = m_dim; Sample ret; ret.u = sobolSample(m_dim); ret.v = sobolSample(m_dim + 1); ret.w = sobolSample(m_dim + 2); m_dim += 3; return ret; } std::unique_ptr<Sampler> SobolSampler::clone(const int seed) const { return std::make_unique<SobolSampler>(m_res, m_log2Res, m_scramble, m_sampleIdx); } std::unique_ptr<Sampler> SobolSampler::deepClone() const { SobolSampler *copy = new SobolSampler(); memcpy_s(copy, sizeof(SobolSampler), this, sizeof(SobolSampler)); return std::unique_ptr<SobolSampler>(copy); } uint64_t SobolSampler::enumerateSampleIndex(const uint32_t px, const uint32_t py) const { if (m_log2Res == 0) { return 0; } const uint32_t m2 = m_log2Res << 1; uint64_t idx = m_sampleIdx; uint64_t idx2 = idx << m2; uint64_t delta = 0; for (int c = 0; idx; idx >>= 1, c++) { if (idx & 1) // Add flipped column m + c + 1. delta ^= VdC_sobol_matrices[m_log2Res - 1][c]; } // Flipped b uint64_t b = (((uint64_t)px << m_log2Res) | py) ^ delta; for (int c = 0; b; b >>= 1, c++) { if (b & 1) // Add column 2 * m - c. idx2 ^= VdC_sobol_matrices_inv[m_log2Res - 1][c]; } return idx2; } float SobolSampler::sobolSample(const int dimension) const { if (dimension < num_sobol_dimensions) { uint64_t v = m_scramble; uint64_t idx = m_sobolIdx; for (int i = dimension * sobol_matrix_size + sobol_matrix_size - 1; idx != 0; idx >>= 1, i--) { if (idx & 1) v ^= sobol_matrices32[i]; } return v * 2.3283064365386963e-10f; /* 1 / 2^32 */ } else { return rng.drand48(); } } }
2,480
C++
.cpp
85
26.082353
98
0.650567
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,898
GuidedPathTracer.cpp
g1n0st_AyaRay/src/Integrators/GuidedPathTracer.cpp
#include <Integrators/GuidedPathTracer.h> #include <Filters/GaussianFilter.h> namespace Aya { void GuidedPathTracerIntegrator::resetSDTree() { m_sdTree->refine((size_t)(std::sqrtf(std::powf(2, m_iter) * m_sppPerPass / 4) * m_sTreeThreshold), m_sdTreeMaxMemory); m_sdTree->forEachDTreeWrapperParallel([this](DTreeWrapper *dTree) { dTree->reset(20, m_dTreeThreshold); }); } void GuidedPathTracerIntegrator::buildSDTree() { // Build distributions m_sdTree->forEachDTreeWrapperParallel([](DTreeWrapper* dTree) { dTree->build(); }); // Gather statistics // no info system, ignored temporarily m_isBuilt = true; } bool GuidedPathTracerIntegrator::doNeeWithSpp(int spp) { switch (m_nee) { case Never: return false; case Kickstart: return spp < 128; default: return true; } } void GuidedPathTracerIntegrator::render(const Scene *scene, const Camera *camera, Sampler *sampler, Film *film) { m_sdTree = std::unique_ptr<STree>(new STree(scene->worldBound())); m_iter = 0; m_isFinalIter = false; m_varianceBuffer = std::shared_ptr<Film>(new Film(m_task.getX(), m_task.getY(), new GaussianFilter())); m_image = std::shared_ptr<Film>(new Film(m_task.getX(), m_task.getY(), new GaussianFilter())); m_squaredImage = std::shared_ptr<Film>(new Film(m_task.getX(), m_task.getY(), new GaussianFilter())); m_images.clear(); m_variances.clear(); { m_passesRendered = 0; size_t sample_count = static_cast<size_t>(m_spp); int n_passes = (int)std::ceilf(sample_count / (float)m_sppPerPass); sample_count = n_passes * m_sppPerPass; float currentVarAtEnd = std::numeric_limits<float>::infinity(); while (!m_task.aborted() && m_passesRendered < n_passes) { const int spp_rendered = m_passesRendered * m_sppPerPass; m_doNee = doNeeWithSpp(spp_rendered); int remaining_passes = n_passes - m_passesRendered; int current_passes = Min(remaining_passes, 1 << m_iter); // If the next iteration does not manage to double the number of passes once more // then it would be unwise to throw away the current iteration. Instead, extend // the current iteration to the end. // This condition can also be interpreted as: the last iteration must always use // at _least_ half the total sample budget. if (remaining_passes - current_passes < 2 * current_passes) { current_passes = remaining_passes; } m_isFinalIter = current_passes >= remaining_passes; film->clear(); resetSDTree(); float variance; if (!renderPasses(variance, current_passes, scene, camera, sampler, film)) { break; } const float lastVarAtEnd = currentVarAtEnd; currentVarAtEnd = current_passes * variance / remaining_passes; remaining_passes -= current_passes; if (m_sampleCombination == SampleCombination::DiscardWithAutomaticBudget && remaining_passes > 0 && ( // if there is any time remaining we want to keep going if // either will have less time next iter remaining_passes < current_passes || // or, according to the convergence behavior, we're better off if we keep going // (we only trust the variance if we drew enough samples for it to be a reliable estimate, // captured by an arbitraty threshold). (spp_rendered > 256 && currentVarAtEnd > lastVarAtEnd) )) { m_isFinalIter = true; if (!renderPasses(variance, remaining_passes, scene, camera, sampler, film)) { break; } } buildSDTree(); ++m_iter; m_passesRenderedThisIter = 0; } } if (m_task.aborted()) { return; } if (m_sampleCombination == SampleCombination::InverseVariance) { // Combine the last 4 images according to their inverse variance film->clear(); size_t begin = m_images.size() - Min(m_images.size(), (size_t)4); float total_weight = 0.f; for (size_t i = begin; i < m_variances.size(); ++i) { total_weight += 1.f / m_variances[i]; } for (size_t i = begin; i < m_variances.size(); ++i) { film->addFilm(&(*m_images[i]), 1.f / m_variances[i] / total_weight); } film->updateDisplay(); } } bool GuidedPathTracerIntegrator::renderPasses(float &variance, int num_passes, const Scene *scene, const Camera *camera, Sampler *sampler, Film *film) { m_image->clear(); m_squaredImage->clear(); int passesRenderedLocal = { 0 }; int tiles_count = m_task.getTilesCount(); for (int pass = 0; pass < num_passes; ++pass) { ++m_passesRendered; ++m_passesRenderedThisIter; ++passesRenderedLocal; if (m_task.aborted()) { return false; } for (int spp = 0; spp < m_sppPerPass; ++spp) { concurrency::parallel_for(0, tiles_count, [&](int i) { //for (int i = 0; i < tiles_count; i++) { const RenderTile& tile = m_task.getTile(i); std::unique_ptr<Sampler> tile_sampler(sampler->clone(((m_passesRendered - 1) * m_sppPerPass + spp) * tiles_count + i)); RNG rng; MemoryPool memory; for (int y = tile.min_y; y < tile.max_y; ++y) { for (int x = tile.min_x; x < tile.max_x; ++x) { if (m_task.aborted()) return; tile_sampler->startPixel(x, y); CameraSample cam_sample; tile_sampler->generateSamples(x, y, &cam_sample, rng); cam_sample.image_x += x; cam_sample.image_y += y; RayDifferential ray; Spectrum L(0.f); if (camera->generateRayDifferential(cam_sample, &ray)) { L = li(ray, scene, tile_sampler.get(), rng, memory); } film->addSample(cam_sample.image_x, cam_sample.image_y, L); m_image->addSample(cam_sample.image_x, cam_sample.image_y, L); m_squaredImage->addSample(cam_sample.image_x, cam_sample.image_y, L * L); memory.freeAll(); } } //} }); if (m_task.aborted()) { return false; } film->addSampleCount(); film->updateDisplay(); } } variance = 0.f; std::shared_ptr<Film> image(new Film(m_task.getX(), m_task.getY(), nullptr)); image->addFilm(&(*m_image)); if (m_sampleCombination == SampleCombination::InverseVariance) { // Record all previously rendered iterations such that later on all iterations can be // combined by weighting them by their estimated inverse pixel variance. m_images.push_back(image); } m_varianceBuffer->clear(); int N = passesRenderedLocal * m_sppPerPass; Vector2i size = m_squaredImage->getSize(); for (int x = 0; x < size.x; ++x) for (int y = 0; y < size.y; ++y) { Spectrum pixel = m_image->getPixel(x, y); Spectrum local_var = m_squaredImage->getPixel(x, y) - pixel * pixel / (float)N; m_varianceBuffer->setPixel(x, y, local_var); // The local variance is clamped such that fireflies don't cause crazily unstable estimates. variance += Min(local_var.luminance(), 10000.0f); } variance /= (float)size.x * size.y * (N - 1); if (m_sampleCombination == SampleCombination::InverseVariance) { // Record estimated mean pixel variance for later use in weighting of all images. m_variances.push_back(variance); } return true; } Spectrum GuidedPathTracerIntegrator::li(const RayDifferential &ray, const Scene *scene, Sampler *sampler, RNG &rng, MemoryPool &memory) const { return Spectrum(1.f); struct Vertex { DTreeWrapper *dTree; Vector3 voxel_size; Ray ray; Spectrum throughput; Spectrum bsdf_val; Spectrum radiance; float wo_pdf, bsdf_pdf, dTree_pdf; bool is_delta; void record(const Spectrum &r) { radiance += r; } void commit(STree &sdTree, float statistical_weight, SpatialFilter spatial_filter, DirectionalFilter directional_filter, BsdfSamplingFractionLoss sampling_loss, Sampler *sampler) { if (!(wo_pdf > 0.f) || !radiance.isValid() || !bsdf_val.isValid()) { return; } Spectrum local_radiance(0.f); for (int i = 0; i < Spectrum::nSamples; ++i) { if (throughput[i] * wo_pdf > 1e-4f) { local_radiance[i] = radiance[i] / throughput[i]; } } Spectrum product = local_radiance * bsdf_val; float radiance_average = 0.f, product_average = 0.f; for (int i = 0; i < Spectrum::nSamples; ++i) { radiance_average += local_radiance[i]; product_average += product[i]; } radiance_average /= (float)Spectrum::nSamples; product_average /= (float)Spectrum::nSamples; DTreeRecord rec{ ray.m_dir, radiance_average, product_average, wo_pdf, bsdf_pdf, dTree_pdf, statistical_weight, is_delta }; switch (spatial_filter) { case SpatialFilter::Nearest: dTree->record(rec, directional_filter, sampling_loss); break; case SpatialFilter::StochasticBox: { DTreeWrapper *splat_dTree = dTree; // Jitter the actual position within the // filter box to perform stochastic filtering. Vector3 offset = voxel_size; offset.x *= sampler->get1D() - .5f; offset.y *= sampler->get1D() - .5f; offset.z *= sampler->get1D() - .5f; Point3 origin = sdTree.aabb().clip(ray.m_ori + offset); splat_dTree = sdTree.dTreeWrapper(origin); if (splat_dTree) { splat_dTree->record(rec, directional_filter, sampling_loss); } break; } case SpatialFilter::Box: sdTree.record(ray.m_ori, voxel_size, rec, directional_filter, sampling_loss); break; } } }; static const int MAX_NUM_VERTICES = 32; std::array<Vertex, MAX_NUM_VERTICES> vertices; Spectrum Li(0.f); float eta = 1.f; Spectrum throughput(1.f); bool scattered = false; bool spec_bounce = true; int nVertices = 0; auto recordRadiance = [&](Spectrum radiance) { Li += radiance; for (int i = 0; i < nVertices; ++i) { vertices[i].record(radiance); } }; int depth = 0; RayDifferential path_ray = ray; while (depth <= m_maxDepth || m_maxDepth < 0) { // ignored medium sampling ... SurfaceIntersection intersection; bool intersected = scene->intersect(path_ray, &intersection); MediumIntersection medium; if (path_ray.mp_medium) { throughput *= path_ray.mp_medium->sample(path_ray, sampler, &medium); } if (!medium.isValid()) { if (intersected) scene->postIntersect(path_ray, &intersection); if (spec_bounce) { if (intersected) recordRadiance(throughput * intersection.emit(-path_ray.m_dir)); else if (scene->getEnviromentLight()) recordRadiance(throughput * scene->getEnviromentLight()->emit(-path_ray.m_dir)); } if (!intersected || (depth >= m_maxDepth && m_maxDepth != -1)) break; const BSDF *bsdf = intersection.bsdf; Vector3 voxel_size; DTreeWrapper *dTree = nullptr; // We only guide smooth BRDFs for now. Analytic product sampling // would be conceivable for discrete decisions such as refraction vs // reflection. if (bsdf->getScatterType() & !bsdf->isSpecular()) { dTree = m_sdTree->dTreeWrapper(intersection.p, voxel_size); } float sampling_fraction = m_bsdfSamplingFraction; if (dTree && m_bsdfSamplingFractionLoss != BsdfSamplingFractionLoss::None) { sampling_fraction = dTree->bsdfSamplingFraction(); } // BSDF sampling float wo_pdf, bsdf_pdf, dTree_pdf; Vector3 out = -path_ray.m_dir; Vector3 in; Spectrum bsdf_weight; ScatterType sample_types; Sample sample = sampler->getSample(); do { if (!m_isBuilt || !dTree || bsdf->isSpecular()) { bsdf_weight = bsdf->sample_f(out, sample, intersection, &in, &bsdf_pdf, ScatterType::BSDF_ALL, &sample_types); wo_pdf = bsdf_pdf; dTree_pdf = 0.f; break; } if (sample.u < sampling_fraction) { sample.u /= sampling_fraction; bsdf_weight = bsdf->sample_f(out, sample, intersection, &in, &bsdf_pdf, ScatterType::BSDF_ALL, &sample_types); if (bsdf_weight.isBlack()) { wo_pdf = bsdf_pdf = dTree_pdf = 0.f; break; } // If we sampled a delta component, then we have a 0 probability // of sampling that direction via guiding, thus we can return early. else if (bsdf->isSpecular()) { dTree_pdf = 0.f; wo_pdf = bsdf_pdf * sampling_fraction; bsdf_weight /= sampling_fraction; break; } bsdf_weight *= bsdf_pdf; } else { sample.u = (sample.u - sampling_fraction) / (1.f - sampling_fraction); in = dTree->sample(sampler); bsdf_weight = bsdf->f(out, in, intersection); } { bsdf_pdf = bsdf->pdf(out, in, intersection); if (!std::isfinite(bsdf_pdf)) { dTree_pdf = 0.f; wo_pdf = 0.f; } else { dTree_pdf = dTree->pdf(out); wo_pdf = sampling_fraction * bsdf_pdf + (1.f - sampling_fraction) * dTree_pdf; } } if (wo_pdf == 0.f) { bsdf_weight = Spectrum(0.f); } bsdf_weight /= wo_pdf; } while (0); // Luminaire sampling // Estimate the direct illumination if this is requested if (m_doNee && !!bsdf->isSpecular()) { float sample1d = sampler->get1D(); int light_idx = Min(int(sample1d * scene->getLightCount()), int(scene->getLightCount() - 1)); Spectrum value = estimateDirectLighting(intersection, -path_ray.m_dir, scene->getLight(light_idx), scene, sampler) * float(scene->getLightCount()); if (!value.isBlack()) { float woDotGN = intersection.gn.dot(in); //const Spectrum bsdf_val = bsdf->f() // ... } } // BSDF handling if (bsdf_weight.isBlack()) break; // Trace a ray in this direction path_ray = Ray(intersection.p, in, intersection.m_mediumInterface.getMedium(in, intersection.n)); // Keep track of the throughput, medium, and relative // refractive index along the path throughput *= bsdf_weight; recordRadiance(throughput); // eta update ... Spectrum value(0.f); } else { // ... } } return Li; } }
13,880
C++
.cpp
365
32.761644
153
0.657499
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,899
VertexCM.cpp
g1n0st_AyaRay/src/Integrators/VertexCM.cpp
#include <Integrators/VertexCM.h> namespace Aya { VertexCMIntegrator::VertexCMIntegrator(const TaskSynchronizer &task, const uint32_t &spp, uint32_t min_depth, uint32_t max_depth, const Camera *camera, Film *film, AlgorithmType algorithm_type, const float radius_factor, const float radius_alpha) : Integrator(task, spp), m_minDepth(min_depth), m_maxDepth(max_depth), mp_cam(camera), mp_film(film), m_useVC(false), m_useVM(false), m_PPM(false) { switch (algorithm_type) { case kPpm: m_PPM = true; m_useVM = true; break; case kBpm: m_useVM = true; break; case kBpt: m_useVC = true; break; case kVcm: m_useVC = true; m_useVM = true; break; default: assert((printf("Unknown algorithm requested\n"), 0)); break; } m_baseRadius = radius_factor; m_radiusAlpha = radius_alpha; // While we have the same number of pixels (camera paths) // and light paths, we do keep them separate for clarity reasons m_lightPathCount = float(film->getPixelCount()); m_screenPixelCount = float(film->getPixelCount()); } void VertexCMIntegrator::render(const Scene *scene, const Camera *camera, Sampler *sampler, Film *film) { Point3 scene_center; float scene_radius; scene->worldBound().boundingSphere(&scene_center, &scene_radius); // global Lock std::mutex mutex; std::vector<PathVertex> light_vertices; // Stored light vertices // For light path belonging to pixel index [x] it stores // where it's light vertices end (begin is at [x-1]) BlockedArray<Vector2i> ranges; BlockedArray<std::unique_ptr<Sampler>> pixel_samplers; HashGrid grid; ranges.init(m_task.getX(), m_task.getY()); pixel_samplers.init(m_task.getX(), m_task.getY()); for (uint32_t spp = 0; spp < m_spp; spp++) { int tiles_count = m_task.getTilesCount(); int height = m_task.getX(); int width = m_task.getY(); // Setup our radius, 1st iteration has aIteration == 0, thus offset float radius = m_baseRadius * scene_radius; radius /= std::powf(float(spp + 1), .5f * (1.f - m_radiusAlpha)); // Purely for numeric stability radius = Max(radius, 1e-7f); const float radius_sqr = radius * radius; // Factor used to normalise vertex merging contribution. // We divide the summed up energy by disk radius and number of light paths m_VM_normalization = 1.f / (radius_sqr * float(M_PI) * m_lightPathCount); // MIS weight constant [tech. rep. (20)], with n_VC = 1 and n_VM = mLightPathCount const float etaVCM = (radius_sqr * float(M_PI)) * m_lightPathCount; m_MIS_VM_weight = m_useVM ? MIS(etaVCM) : 0.f; m_MIS_VC_weight = m_useVC ? MIS(1.f / etaVCM) : 0.f; // Remove all light vertices and reserve space for some light_vertices.reserve(m_task.getX() * m_task.getY()); light_vertices.clear(); concurrency::parallel_for(0, tiles_count, [&](int i) { //for (int i = 0; i < tiles_count; i++) { const RenderTile& tile = m_task.getTile(i); std::unique_ptr<Sampler> tile_sampler = sampler->clone(spp * tiles_count + i); RNG rng; MemoryPool memory; for (int y = tile.min_y; y < tile.max_y; ++y) { for (int x = tile.min_x; x < tile.max_x; ++x) { if (m_task.aborted()) return; Sampler *sampler = tile_sampler.get(); sampler->startPixel(x, y); // Randomly select a light source, and generate the light path PathVertex *light_path = memory.alloc<PathVertex>(m_maxDepth); int light_vertex_cnt; int light_path_len = generateLightPath(scene, sampler, rng, mp_cam, mp_film, m_maxDepth + 1, light_path, &light_vertex_cnt); { std::lock_guard<std::mutex> lck(mutex); int vertex_start = int(light_vertices.size()); for (int i = 0; i < light_vertex_cnt; i++) { const PathVertex &vert = light_path[i]; light_vertices.push_back(vert); } int vertex_end = int(light_vertices.size()); ranges(x, y) = Vector2i(vertex_start, vertex_end); pixel_samplers(x, y) = sampler->deepClone(); } } } //} }); // Only build grid when merging (VCM, BPM, and PPM) if (m_useVM) { grid.reserve(m_task.getX() * m_task.getY()); grid.build(light_vertices, radius); } concurrency::parallel_for(0, tiles_count, [&](int i) { //for (int i = 0; i < tiles_count; i++) { const RenderTile& tile = m_task.getTile(i); RNG rng; MemoryPool memory; for (int y = tile.min_y; y < tile.max_y; ++y) { for (int x = tile.min_x; x < tile.max_x; ++x) { if (m_task.aborted()) return; Sampler *sampler = pixel_samplers(x, y).get(); CameraSample cam_sample; sampler->generateSamples(x, y, &cam_sample, rng); cam_sample.image_x += x; cam_sample.image_y += y; RayDifferential ray; Spectrum L(0.f); if (camera->generateRayDifferential(cam_sample, &ray)) { // Initialize camera path with eye ray PathState cam_path; sampleCamera(scene, mp_cam, mp_film, ray, cam_path); // Iterate camera path with Path Tracing, and connect it with the light path while (true) { RayDifferential path_ray(cam_path.ori, cam_path.dir); SurfaceIntersection local_isect; if (!scene->intersect(path_ray, &local_isect)) { // miss intersecting, but directly hitting IBL if (scene->getEnviromentLight()) { if (cam_path.path_len >= m_minDepth) L += cam_path.throughput * hittingLightSource(scene, rng, path_ray, local_isect, scene->getEnviromentLight(), cam_path); } break; } scene->postIntersect(ray, &local_isect); // Update the MIS quantities, following the initialization in // GenerateLightSample() or SampleScattering(). Implement equations // [tech. rep. (31)-(33)] or [tech. rep. (34)-(36)], respectively. { float cos_in = Abs(local_isect.n.dot(-path_ray.m_dir)); cam_path.dvcm *= MIS(local_isect.dist * local_isect.dist); cam_path.dvcm /= MIS(cos_in); cam_path.dvc /= MIS(cos_in); cam_path.dvm /= MIS(cos_in); } // Add contribution when directly hitting a light source if (local_isect.arealight != nullptr) { if (cam_path.path_len >= m_minDepth) L += cam_path.throughput * hittingLightSource(scene, rng, path_ray, local_isect, (Light*)local_isect.arealight, cam_path); break; } if (++cam_path.path_len >= m_maxDepth + 1) break; const BSDF *bsdf = local_isect.bsdf; // Vertex connection if (!bsdf->isSpecular() && m_useVC) { // Connect to light source if (cam_path.path_len >= m_minDepth) L += cam_path.throughput * connectToLight(scene, sampler, rng, path_ray, local_isect, cam_path); // Connect to light vertices Vector2i range = ranges(x, y); for (auto i = range.x; i < range.y; ++i) { const PathVertex &light_vertex = light_vertices[i]; if (light_vertex.path_len + cam_path.path_len < m_minDepth) continue; // Light vertices are stored in increasing path length // order; once we go above the max path length, we can // skip the rest if (light_vertex.path_len + cam_path.path_len > m_maxDepth) break; L += cam_path.throughput * light_vertex.throughput * connectVertex(scene, rng, local_isect, light_vertex, cam_path); } } // Vertex merging if (!bsdf->isSpecular() && m_useVM) { RangeQuery query(*this, local_isect, bsdf, cam_path); grid.process(light_vertices, query); L += cam_path.throughput * m_VM_normalization * query.getContrib(); // PPM merges only at the first non-specular surface from camera if (m_PPM) break; } // Extend camera path with importance sampling on BSDF if (!sampleScattering(scene, rng, path_ray, local_isect, sampler->getSample(), cam_path)) break; } } film->addSample(cam_sample.image_x, cam_sample.image_y, L); memory.freeAll(); } } //} }); sampler->advanceSampleIndex(); film->addSampleCount(); film->updateDisplay(); if (m_task.aborted()) break; } } VertexCMIntegrator::PathState VertexCMIntegrator::sampleLightSource(const Scene *scene, Sampler *sampler, RNG &rng) const { float light_sample = sampler->get1D(); float light_pick_pdf; const Light *light = scene->chooseLightSource(light_sample, &light_pick_pdf); Ray light_ray; Normal3 emit_dir; float emit_pdf, direct_pdf; PathState path; path.throughput = light->sample(sampler->getSample(), sampler->getSample(), &light_ray, &emit_dir, &emit_pdf, &direct_pdf); if (emit_pdf == 0.f) return path; direct_pdf *= light_pick_pdf; emit_pdf *= light_pick_pdf; path.throughput /= emit_pdf; path.is_finite_light = light->isFinite(); path.specular_path = true; path.path_len = 1; path.dir = light_ray.m_dir; path.ori = light_ray.m_ori; float emit_cos = emit_dir.dot(light_ray.m_dir); // Light sub-path MIS quantities. Implements [tech. rep. (31)-(33)] partially. // The evaluation is completed after tracing the emission ray in the light sub-path loop. // Delta lights are handled as well [tech. rep. (48)-(50)]. path.dvcm = MIS(direct_pdf / emit_pdf); if (light->isDelta()) path.dvc = 0.f; else if (light->isFinite()) path.dvc = MIS(emit_cos / emit_pdf); else path.dvc = MIS(1.f / emit_pdf); path.dvm = path.dvc * m_MIS_VC_weight; return path; } int VertexCMIntegrator::generateLightPath(const Scene *scene, Sampler *sampler, RNG &rng, const Camera *camera, Film *film, const uint32_t max_depth, PathVertex *path, int *vertex_count, const bool connect_to_cam, const int RR_depth) const { if (max_depth == 0) { *vertex_count = 0; return 0; } // Select a light source, and generate the light path PathState light_path = sampleLightSource(scene, sampler, rng); if (light_path.throughput.isBlack()) return 0; if (light_path.path_len >= max_depth) { *vertex_count = 0; return light_path.path_len; } // Light Tracing *vertex_count = 0; while (true) { Ray path_ray(light_path.ori, light_path.dir); SurfaceIntersection intersection; if (!scene->intersect(path_ray, &intersection)) break; scene->postIntersect(path_ray, &intersection); // Update the MIS quantities before storing them at the vertex. // These updates follow the initialization in GenerateLightSample() or // SampleScattering(), and together implement equations [tech. rep. (31)-(33)] // or [tech. rep. (34)-(36)], respectively. float cos_in = Abs(intersection.n.dot(-path_ray.m_dir)); // Special Case at Infinite Light Source (5.1) if (light_path.is_finite_light || light_path.path_len > 1) light_path.dvcm *= MIS(intersection.dist * intersection.dist); light_path.dvcm /= MIS(cos_in); light_path.dvc /= MIS(cos_in); light_path.dvm /= MIS(cos_in); // Store vertex, unless BSDF is purely specular, which prevents // vertex connections and merging const BSDF *bsdf = intersection.bsdf; if (!bsdf->isSpecular() && (m_useVC || m_useVM)) { // Store the light vertex PathVertex &light_vertex = path[(*vertex_count)++]; light_vertex.throughput = light_path.throughput; light_vertex.path_len = light_path.path_len; light_vertex.isect = intersection; light_vertex.v_in = -light_path.dir; light_vertex.dvc = light_path.dvc; light_vertex.dvm = light_path.dvm; light_vertex.dvcm = light_path.dvcm; // Connect to camera if (m_useVC) { if (connect_to_cam && light_path.path_len + 1 >= m_minDepth) { Point3 raster; Spectrum L = connectToCamera(scene, sampler, rng, camera, film, intersection, light_vertex, &raster); film->splat(raster.x, raster.y, L); } } } // Terminate with hard limitation if (++light_path.path_len >= max_depth) break; // Extend light path with importance sampling on BSDF if (!sampleScattering(scene, rng, path_ray, intersection, sampler->getSample(), light_path, RR_depth)) break; } return light_path.path_len; } Spectrum VertexCMIntegrator::connectToCamera(const Scene *scene, Sampler *sampler, RNG &rng, const Camera *camera, Film *film, const SurfaceIntersection &intersection, const PathVertex &path_vertex, Point3 *raster_pos) const { Point3 cam_pos = camera->m_pos; Vector3 cam_dir = camera->m_dir; // Check if the point lies within the raster range Vector3 dir2cam; if (camera->getCircleOfConfusionRadius() == 0.f) { // Pin Hole Model *raster_pos = camera->worldToRaster(intersection.p); dir2cam = cam_pos - intersection.p; } else { // Thin Lens Model *raster_pos = camera->worldToRaster(intersection.p); Vector2f scr_coord(2.f * float(raster_pos->x) / float(camera->getResolusionX()) - 1.f, 2.f * float(raster_pos->y) / float(camera->getResolusionY()) - 1.f); scr_coord.x *= camera->m_ratio; scr_coord.y *= -1.f; // Sampling on disk lens float U, V; ConcentricSampleDisk(sampler->get1D(), sampler->get1D(), &U, &V); if (Vector2f(scr_coord.x + U, scr_coord.v + V).length() > camera->m_vignetteFactor) return Spectrum(0.f); U *= camera->getCircleOfConfusionRadius(); V *= camera->getCircleOfConfusionRadius(); Ray eye_ray; eye_ray.m_ori = Point3(U, V, 0.f); eye_ray.m_dir = (camera->view(intersection.p) - eye_ray.m_ori).normalize(); Point3 focal = eye_ray(camera->getFocusDistance() / eye_ray.m_dir.z); *raster_pos = camera->cameraToRaster(focal); dir2cam = camera->viewInv(eye_ray.m_ori) - intersection.p; } // Check whether the ray is in front of camera if (cam_dir.dot(-dir2cam) <= 0.f || !camera->checkRaster(*raster_pos)) return Spectrum(0.f); float dist2cam = dir2cam.length(); dir2cam.normalized(); const BSDF *bsdf = intersection.bsdf; Spectrum bsdf_fac = bsdf->f(dir2cam, path_vertex.v_in, intersection, ScatterType(BSDF_ALL & ~BSDF_SPECULAR)) * Abs(path_vertex.v_in.dot(intersection.n)) / Abs(path_vertex.v_in.dot(intersection.gn)); if (bsdf_fac.isBlack()) return Spectrum(0.f); // Forward and reverse solid angle pdfs for sub-path vertex float pdf = bsdf->pdf(path_vertex.v_in, dir2cam, intersection, ScatterType(BSDF_ALL & ~BSDF_SPECULAR)); float rev_pdf = bsdf->pdf(dir2cam, path_vertex.v_in, intersection, ScatterType(BSDF_ALL & ~BSDF_SPECULAR)); if (pdf == 0.f || rev_pdf == 0.f) return Spectrum(0.f); // Compute pdf conversion factor from image plane area to surface area float cos_cam2gn = intersection.gn.dot(dir2cam); float cos_cam2dir = cam_dir.dot(-dir2cam); float raster2cam_dist = camera->getImagePlaneDistance() / cos_cam2dir; float raster2SA_fac = raster2cam_dist * raster2cam_dist / cos_cam2dir; // We put the virtual image plane at such a distance from the camera origin // that the pixel area is one and thus the image plane sampling pdf is 1. // The area pdf of aHitpoint as sampled from the camera is then equal to // the conversion factor from image plane area density to surface area density float cam_pdfA = raster2SA_fac * Abs(cos_cam2gn) / (dist2cam * dist2cam); // nlight is the total number of light sub-paths float n_lights = float(film->getPixelCount()); // Partial light sub-path weight [tech. rep. (46)]. Note the division by // mLightPathCount, which is the number of samples this technique uses. // This division also appears a few lines below in the framebuffer accumulation. float weight_light = MIS(cam_pdfA / n_lights) * (m_MIS_VM_weight + path_vertex.dvcm + MIS(rev_pdf) * path_vertex.dvc); // Partial eye sub-path weight is 0 [tech. rep. (47)] // Full path MIS weight [tech. rep. (37)]. float MIS_weight = 1.f / (weight_light + 1.f); // We divide the contribution by surfaceToImageFactor to convert the (already // divided) pdf from surface area to image plane area, w.r.t. which the // pixel integral is actually defined. We also divide by the number of samples // this technique makes, which is equal to the number of light sub-paths Spectrum L = MIS_weight * path_vertex.throughput * bsdf_fac * cam_pdfA / n_lights; Ray ray2cam(intersection.p, dir2cam, intersection.m_mediumInterface.getMedium(dir2cam, intersection.n), 0.f, dist2cam); if (L.isBlack() || scene->occluded(ray2cam)) return Spectrum(0.f); return L; } void VertexCMIntegrator::sampleCamera(const Scene *scene, const Camera *camera, Film *film, const RayDifferential &ray, PathState &init_path) const { // Compute pdf conversion factor from area on image plane to solid angle on ray float cos_cam2dir = camera->m_dir.dot(ray.m_dir); float raster2cam_dist = camera->getImagePlaneDistance() / cos_cam2dir; // We put the virtual image plane at such a distance from the camera origin // that the pixel area is one and thus the image plane sampling pdf is 1. // The solid angle ray pdf is then equal to the conversion factor from // image plane area density to ray solid angle density// We put the virtual image plane at such a distance from the camera origin // that the pixel area is one and thus the image plane sampling pdf is 1. // The solid angle ray pdf is then equal to the conversion factor from // image plane area density to ray solid angle density float camera_pdfW = raster2cam_dist * raster2cam_dist / cos_cam2dir; float n_lights = float(film->getPixelCount()); init_path.ori = ray.m_ori; init_path.dir = ray.m_dir; init_path.throughput = Spectrum(1.f); init_path.path_len = 1; init_path.specular_path = true; // Eye sub-path MIS quantities. Implements [tech. rep. (31)-(33)] partially. // The evaluation is completed after tracing the camera ray in the eye sub-path loop. init_path.dvcm = MIS(n_lights / camera_pdfW); init_path.dvc = 0.f; init_path.dvm = 0.f; } Spectrum VertexCMIntegrator::connectToLight(const Scene *scene, Sampler *sampler, RNG &rng, const RayDifferential &ray, const SurfaceIntersection &intersection, PathState &cam_path) const { // Sample light source and get radiance float light_sample = sampler->get1D(); float light_pick_pdf; const Light *light = scene->chooseLightSource(light_sample, &light_pick_pdf); const Point3 &pos = intersection.p; Vector3 v_in; VisibilityTester tester; float light_pdfW, emit_pdfW, cos_at_light; Spectrum radiance = light->illuminate(intersection, sampler->getSample(), &v_in, &tester, &light_pdfW, &cos_at_light, &emit_pdfW); if (radiance.isBlack() || light_pdfW == 0.f) return Spectrum(0.f); const BSDF *bsdf = intersection.bsdf; Vector3 v_out = -ray.m_dir; Spectrum bsdf_fac = bsdf->f(v_out, v_in, intersection); if (bsdf_fac.isBlack()) return Spectrum(0.f); float bsdf_pdfW = bsdf->pdf(v_out, v_in, intersection); if (bsdf_pdfW == 0.f) return Spectrum(0.f); // If the light is delta light, we can never hit it // by BSDF sampling, so the probability of this path is 0 if (light->isDelta()) bsdf_pdfW = 0.f; float rev_bsdf_pdfW = bsdf->pdf(v_in, v_out, intersection); // Partial light sub-path MIS weight [tech. rep. (44)]. // Note that wLight is a ratio of area pdfs. But since both are on the // light source, their distance^2 and cosine terms cancel out. // Therefore we can write wLight as a ratio of solid angle pdfs, // both expressed w.r.t. the same shading point. float weight_light = MIS(bsdf_pdfW / (light_pdfW * light_pick_pdf)); float cos2light = Abs(intersection.n.dot(v_in)); // Partial eye sub-path MIS weight [tech. rep. (45)]. // // In front of the sum in the parenthesis we have Mis(ratio), where // ratio = emissionPdfA / directPdfA, // with emissionPdfA being the product of the pdfs for choosing the // point on the light source and sampling the outgoing direction. // What we are given by the light source instead are emissionPdfW // and directPdfW. Converting to area pdfs and plugging into ratio: // emissionPdfA = emissionPdfW * cosToLight / dist^2 // directPdfA = directPdfW * cosAtLight / dist^2 // ratio = (emissionPdfW * cosToLight / dist^2) / (directPdfW * cosAtLight / dist^2) // ratio = (emissionPdfW * cosToLight) / (directPdfW * cosAtLight) // // Also note that both emissionPdfW and directPdfW should be // multiplied by lightPickProb, so it cancels out. float weight_camera = MIS(emit_pdfW * cos2light / (light_pdfW * cos_at_light)) * (m_MIS_VM_weight + cam_path.dvcm + cam_path.dvc * MIS(rev_bsdf_pdfW)); // Full path MIS weight [tech. rep. (37)] float MIS_weight = 1.f / (weight_light + 1.f + weight_camera); Spectrum L = (MIS_weight * cos2light / (light_pdfW * light_pick_pdf)) * bsdf_fac * radiance; if (L.isBlack() || !tester.unoccluded(scene)) return Spectrum(0.f); return L; } Spectrum VertexCMIntegrator::hittingLightSource(const Scene *scene, RNG &rng, const RayDifferential &ray, const SurfaceIntersection &intersection, const Light *light, PathState &cam_path) const { float light_pick_pdf = scene->lightPdf(light); Vector3 v_out = -ray.m_dir; float direct_pdfA; float emit_pdfW; Spectrum radiance = light->emit(v_out, intersection.gn, &emit_pdfW, &direct_pdfA); if (radiance.isBlack()) return Spectrum(0.f); // If we see light source directly from camera, no weighting is required if (cam_path.path_len == 1) return radiance; // When using only vertex merging, we want purely specular paths // to give radiance (cannot get it otherwise). Rest is handled // by merging and we should return 0. if (m_useVM && !m_useVC) return cam_path.specular_path ? radiance : Spectrum(0.f); direct_pdfA *= light_pick_pdf; emit_pdfW *= light_pick_pdf; // Partial eye sub-path MIS weight [tech. rep. (43)]. // If the last hit was specular, then dVCM == 0. float weight_camera = MIS(direct_pdfA) * cam_path.dvcm + MIS(emit_pdfW) * cam_path.dvc; // Partial light sub-path weight is 0 [tech. rep. (42)]. // Full path MIS weight [tech. rep. (37)]. float MIS_weight = 1.f / (1.f + weight_camera); return MIS_weight * radiance; } Spectrum VertexCMIntegrator::connectVertex(const Scene *scene, RNG &rng, const SurfaceIntersection &intersection, const PathVertex &light_vertex, const PathState &cam_path) const { const Point3 &cam_pos = intersection.p; // Get the connection Vector3 dir2light = light_vertex.isect.p - cam_pos; float dist2light2 = dir2light.length2(); float dist2light = Sqrt(dist2light2); dir2light.normalized(); // Evaluate BSDF at camera vertex const BSDF *cam_bsdf = intersection.bsdf; const Normal3 &cam_n = intersection.n; Vector3 v_out_cam = -cam_path.dir; Spectrum cam_bsdf_fac = cam_bsdf->f(v_out_cam, dir2light, intersection); float cos_at_cam = cam_n.dot(dir2light); float cam_dir_pdfW = cam_bsdf->pdf(v_out_cam, dir2light, intersection); float rev_cam_dir_pdfW = cam_bsdf->pdf(dir2light, v_out_cam, intersection); if (cam_bsdf_fac.isBlack() || cam_dir_pdfW == 0.f || rev_cam_dir_pdfW == 0.f) return Spectrum(0.f); // Evaluate BSDF at light vertex const BSDF *light_bsdf = light_vertex.isect.bsdf; Vector3 dir2cam = -dir2light; Spectrum light_bsdf_fac = light_bsdf->f(light_vertex.v_in, dir2cam, light_vertex.isect); float cos_at_light = light_vertex.isect.n.dot(dir2cam); float light_dir_pdfW = light_bsdf->pdf(light_vertex.v_in, dir2cam, light_vertex.isect); float rev_light_dir_pdfW = light_bsdf->pdf(dir2cam, light_vertex.v_in, light_vertex.isect); if (light_bsdf_fac.isBlack() || light_dir_pdfW == 0.f || rev_light_dir_pdfW == 0.f) return Spectrum(0.f); // Compute geometry term float g = cos_at_light * cos_at_cam / dist2light2; if (g < 0.f) { return Spectrum(0.f); } // Convert pdfs to area pdf float cam_dir_pdfA = PdfWToA(cam_dir_pdfW, dist2light, cos_at_light); float light_dir_pdfA = PdfWToA(light_dir_pdfW, dist2light, cos_at_cam); // Partial light sub-path MIS weight [tech. rep. (40)] float weight_light = MIS(cam_dir_pdfA) * (m_MIS_VM_weight + light_vertex.dvcm + MIS(rev_light_dir_pdfW) * light_vertex.dvc); // Partial eye sub-path MIS weight [tech. rep. (41)] float weight_camera = MIS(light_dir_pdfA) * (m_MIS_VM_weight + cam_path.dvcm + MIS(rev_cam_dir_pdfW) * cam_path.dvc); // Full path MIS weight [tech. rep. (37)] float MIS_weight = 1.f / (weight_light + 1.f + weight_camera); Spectrum L = (MIS_weight * g) * light_bsdf_fac * cam_bsdf_fac; Ray ray2light(cam_pos, dir2light, intersection.m_mediumInterface.getMedium(dir2light, cam_n), 0.f, dist2light); if (L.isBlack() || scene->occluded(ray2light)) return Spectrum(0.f); return L; } bool VertexCMIntegrator::sampleScattering(const Scene *scene, RNG &rng, const RayDifferential &ray, const SurfaceIntersection &intersection, const Sample& bsdf_sample, PathState &path_state, const int RR_depth) const { // Sample the scattered direction const BSDF *bsdf = intersection.bsdf; Vector3 v_in; float pdf; ScatterType sampled_type; Spectrum L = bsdf->sample_f(-ray.m_dir, bsdf_sample, intersection, &v_in, &pdf, BSDF_ALL, &sampled_type); // Update Path state before walking to the next vertex if (L.isBlack() || pdf == 0.f) return false; bool non_specular = (sampled_type & BSDF_SPECULAR) == 0; // For specular bounce, reverse pdf equals to forward pdf float rev_pdf = non_specular ? bsdf->pdf(v_in, -ray.m_dir, intersection) : pdf; // Apply Russian Roulette if non-specular surface was hit if (non_specular && RR_depth != -1 && int(path_state.path_len) > RR_depth) { float RR_prob = Min(1.f, path_state.throughput.luminance()); if (rng.drand48() < RR_prob) { pdf *= RR_prob; rev_pdf *= RR_prob; } else { return false; } } path_state.ori = intersection.p; path_state.dir = v_in; float cos_out = Abs(intersection.n.dot(v_in)); if (non_specular) { path_state.specular_path &= 0; // Implements [tech. rep. (34)-(36)] (partially, as noted above) path_state.dvcm = MIS(1.f / pdf); path_state.dvc = MIS(cos_out / pdf) * (MIS(rev_pdf) * path_state.dvc + path_state.dvcm + m_MIS_VM_weight); path_state.dvm = MIS(cos_out / pdf) * (MIS(rev_pdf) * path_state.dvm + path_state.dvcm * m_MIS_VC_weight + 1.f); } else { path_state.specular_path &= 1; // Specular scattering case [tech. rep. (53)-(55)] (partially, as noted above) path_state.dvcm = 0.f; path_state.dvc *= MIS(cos_out); // rev_pdf / pdf equals to 1 path_state.dvm *= MIS(cos_out); // rev_pdf / pdf equals to 1 } path_state.throughput *= L * cos_out / pdf; return true; } }
26,994
C++
.cpp
606
39.80033
131
0.677817
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,901
PathTracing.cpp
g1n0st_AyaRay/src/Integrators/PathTracing.cpp
#include <Integrators/PathTracing.h> namespace Aya { Spectrum PathTracingIntegrator::li(const RayDifferential &ray, const Scene *scene, Sampler *sampler, RNG &rng, MemoryPool &memory) const { Spectrum L(0.f); Spectrum tp = Spectrum(1.f); bool spec_bounce = true; RayDifferential path_ray = ray; for (uint32_t bounce = 0; ; bounce++) { SurfaceIntersection intersection; bool intersected = scene->intersect(path_ray, &intersection); MediumIntersection medium; if (path_ray.mp_medium) tp *= path_ray.mp_medium->sample(path_ray, sampler, &medium); if (tp.isBlack()) break; // Surface if (!medium.isValid()) { if (intersected) scene->postIntersect(path_ray, &intersection); if (spec_bounce) { if (intersected) L += tp * intersection.emit(-path_ray.m_dir); else if (scene->getEnviromentLight()) L += tp * scene->getEnviromentLight()->emit(-path_ray.m_dir); } if (!intersected || bounce >= m_maxDepth) break; auto bsdf = intersection.bsdf; if (!bsdf->isSpecular()) { float sample1d = sampler->get1D(); int light_idx = Min(int(sample1d * scene->getLightCount()), int(scene->getLightCount() - 1)); L += tp * estimateDirectLighting(intersection, -path_ray.m_dir, scene->getLight(light_idx), scene, sampler) * float(scene->getLightCount()); } const Point3 &pos = intersection.p; const Normal3 &normal = intersection.n; Vector3 out = -path_ray.m_dir; Vector3 in; float pdf; ScatterType sample_types; Sample scatter_sample = sampler->getSample(); Spectrum f = bsdf->sample_f(out, scatter_sample, intersection, &in, &pdf, BSDF_ALL, &sample_types); if (f.isBlack() || pdf == 0.f) break; tp *= f * Abs(in.dot(normal)) / pdf; bool sample_subsurface = false; if (!sample_subsurface) { spec_bounce = (sample_types & BSDF_SPECULAR) != 0; path_ray = Ray(pos, in, intersection.m_mediumInterface.getMedium(in, normal)); } else { // There will be a BSSRDF integrator ... } } // Medium else { float sample1d = sampler->get1D(); int light_idx = Min(int(sample1d * scene->getLightCount()), int(scene->getLightCount() - 1)); L += tp * estimateDirectLighting(medium, -path_ray.m_dir, scene->getLight(light_idx), scene, sampler) * float(scene->getLightCount()); if (bounce >= m_maxDepth) break; auto func = medium.mp_func; Vector3 out = -path_ray.m_dir; Vector3 in; func->sample_f(out, &in, sampler->get2D()); spec_bounce = false; path_ray = Ray(medium.p, in, path_ray.mp_medium); } // Russian Roulette if (bounce > 3) { float RR = Min(1.f, tp.luminance()); if (rng.drand48() > RR) break; tp /= RR; } } return L; } }
2,808
C++
.cpp
82
29.329268
139
0.645387
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,902
MultiplexedMLT.cpp
g1n0st_AyaRay/src/Integrators/MultiplexedMLT.cpp
#include <Integrators/MultiplexedMLT.h> #include <Integrators/BidirectionalPathTracing.h> namespace Aya { float MetropolisSampler::get1D() { const int idx = getNextIndex(); mutate(idx); return m_samples[idx].value; } Vector2f MetropolisSampler::get2D() { return Vector2f(get1D(), get1D()); } Sample MetropolisSampler::getSample() { Sample ret; ret.u = get1D(); ret.v = get1D(); ret.w = get1D(); return ret; } void MetropolisSampler::generateSamples(const int pixel_x, const int pixel_y, CameraSample *samples, RNG &rng) { samples->lens_u = get1D(); samples->lens_v = get1D(); samples->time = get1D(); } std::unique_ptr<Sampler> MetropolisSampler::clone(const int seed) const { return std::make_unique<MetropolisSampler>(m_sigma, m_largeStepProb, seed); } std::unique_ptr<Sampler> MetropolisSampler::deepClone() const { return std::make_unique<MetropolisSampler>(m_sigma, m_largeStepProb, m_sampleIdx, m_streamIdx, m_largeStepTime, m_time, m_largeStep, m_rng, m_samples); } void MetropolisSampler::startIteration() { m_largeStep = m_rng.drand48() < m_largeStepProb; m_time++; } void MetropolisSampler::accept() { if (m_largeStep) m_largeStepTime = m_time; } void MetropolisSampler::reject() { for (auto &it : m_samples) { if (it.modify == m_time) it.restore(); } m_time--; } void MetropolisSampler::mutate(const int idx) { if (idx >= m_samples.size()) m_samples.resize(idx + 1); PrimarySample &sample = m_samples[idx]; if (sample.modify < m_largeStepTime) { sample.modify = m_largeStepTime; sample.value = m_rng.drand48(); } sample.backup(); // save state if (m_largeStep) { // large step sample.value = m_rng.drand48(); } else { // small step int num_small_steps = m_time - sample.modify; // Sample the standard normal distribution const float sqrt2 = 1.41421356237309504880f; float normal_sample = sqrt2 * ErfInv(2.f * m_rng.drand48() - 1.f); // The product of multiple mutations can be combined into an exponentially addition form float eff_sigma = m_sigma * Sqrt(float(num_small_steps)); sample.value += normal_sample * eff_sigma; sample.value -= FloorToInt(sample.value); } sample.modify = m_time; } void MultiplexMLTIntegrator::render(const Scene *scene, const Camera *camera, Sampler *sampler, Film *film) { // Generate bootstrap samples and compute normalization constant b int num_bootstrap_samples = m_numBootstrap * (int(m_maxDepth) + 1); std::vector<float> bootstrap_weights(num_bootstrap_samples, 0.f); concurrency::parallel_for(0, m_numBootstrap, [&](int i) { //for (int i = 0; i < m_numBootstrap; i++) { RNG rng(i); MemoryPool memory; for (int depth = 0; depth <= int(m_maxDepth); ++depth) { if (m_task.aborted()) return; int seed = depth + i * (m_maxDepth + 1); MetropolisSampler sampler(m_sigma, m_largeStepProb, seed); Vector2f raster_pos; bootstrap_weights[seed] = evalSample(scene, &sampler, depth, &raster_pos, rng, memory).luminance(); memory.freeAll(); } //} }); if (m_task.aborted()) return; Distribution1D bootstrap_distribution(bootstrap_weights.data(), int(bootstrap_weights.size())); float b = bootstrap_distribution.getIntegral() * (m_maxDepth + 1); // Mutations per chain roughly equals to samples per pixel float mutations_per_pixel = m_spp; uint64_t total_mutations = m_spp * mp_film->getPixelCount(); uint64_t total_samples = 0u; concurrency::parallel_for(0, m_numChains, [&](int i) { //for (int i = 0; i < m_numChains; i++) { if (m_task.aborted()) return; uint64_t chain_mutations = Min((i + 1) * total_mutations / m_numChains, total_mutations) - i * total_mutations / m_numChains; RNG rng(i); MemoryPool memory; int bootstrap_idx = bootstrap_distribution.sampleDiscrete(rng.drand48(), nullptr); int depth = bootstrap_idx % (m_maxDepth + 1); // Target the bootstrap corresponding depth // Initialize local variables for selected state MetropolisSampler sampler(m_sigma, m_largeStepProb, bootstrap_idx); // bootstrap_idx equals to the seed Vector2f current_raster; Spectrum current_Li = evalSample(scene, &sampler, depth, &current_raster, rng, memory); // Run the Markov chain for numChainMutations steps for (uint64_t j = 0; j < chain_mutations; j++) { if (m_task.aborted()) return; sampler.startIteration(); Vector2f proposed_raster; Spectrum proposed_Li = evalSample(scene, &sampler, depth, &proposed_raster, rng, memory); // Compute acceptance probability for proposed sample float accept_prob = Min(1.f, proposed_Li.luminance() / (current_Li.luminance() + 1e-4f)); if (accept_prob > 0.f) mp_film->splat(proposed_raster.x, proposed_raster.y, proposed_Li * accept_prob / (proposed_Li.luminance() + 1e-4f)); mp_film->splat(current_raster.x, current_raster.y, current_Li * (1.f - accept_prob) / (current_Li.luminance() + 1e-4f)); // Accept or reject the proposal if (rng.drand48() < accept_prob) { current_raster = proposed_raster; current_Li = proposed_Li; sampler.accept(); } else { sampler.reject(); } memory.freeAll(); // Progressive display { std::lock_guard<std::mutex> lck(m_mutex); total_samples += 1; if (total_samples % mp_film->getPixelCount() == 0) { mp_film->addSampleCount(); float current_mutations_per_pixel = (total_samples / float(mp_film->getPixelCount())); mp_film->updateDisplay(current_mutations_per_pixel / b); } } } //} }); mp_film->updateDisplay(mutations_per_pixel / b); } Spectrum MultiplexMLTIntegrator::evalSample(const Scene *scene, MetropolisSampler *sampler, const int connect_depth, Vector2f *raster_pos, RNG &rng, MemoryPool &memory) const { sampler->startStream(0); int light_length, eye_length, num_strategies; if (connect_depth == 0) { num_strategies = 1; light_length = 0; eye_length = 2; } else { num_strategies = connect_depth + 2; light_length = Min(int(sampler->get1D() * float(num_strategies)), num_strategies - 1); eye_length = num_strategies - light_length; } // Generate light sub-path BidirectionalPathTracingIntegrator::PathVertex *light_path = memory.alloc<BidirectionalPathTracingIntegrator::PathVertex>(light_length); int num_light_vertex; if (BidirectionalPathTracingIntegrator::generateLightPath(scene, sampler, rng, mp_camera, mp_film, light_length, light_path, &num_light_vertex, false, -1) != light_length) return Spectrum(0.f); // Generate primary ray sampler->startStream(1); CameraSample cam_sample; *raster_pos = sampler->get2D(); raster_pos->x *= m_task.getX(); raster_pos->y *= m_task.getY(); sampler->generateSamples(raster_pos->x, raster_pos->y, &cam_sample, rng); cam_sample.image_x = raster_pos->x; cam_sample.image_y = raster_pos->y; RayDifferential ray; Spectrum L(0.f); if (!mp_camera->generateRayDifferential(cam_sample, &ray)) return Spectrum(0.f); // Initialize the camera PathState BidirectionalPathTracingIntegrator::PathState cam_path; SurfaceIntersection cam_isect; const Light *env_light = nullptr; BidirectionalPathTracingIntegrator::sampleCamera(scene, mp_camera, mp_film, ray, cam_path); // Trace camera sub-path bool last_hitting = false; while (eye_length > 1) { RayDifferential path_ray(cam_path.ori, cam_path.dir); if (!scene->intersect(path_ray, &cam_isect)) { last_hitting = false; env_light = scene->getEnviromentLight(); if (env_light) ++cam_path.path_len; break; } scene->postIntersect(path_ray, &cam_isect); last_hitting = true; // Update MIS quantities from iteration (34) (35) // Divide by g_i-> factor, Forward pdf conversion factor from solid angle measure to area measure (4) (8) float cos_in = Abs(cam_isect.n.dot(-path_ray.m_dir)); cam_path.dvcm *= BidirectionalPathTracingIntegrator::MIS(cam_isect.dist * cam_isect.dist); cam_path.dvcm /= BidirectionalPathTracingIntegrator::MIS(cos_in); cam_path.dvc /= BidirectionalPathTracingIntegrator::MIS(cos_in); if (++cam_path.path_len >= uint32_t(eye_length)) break; if (!BidirectionalPathTracingIntegrator::sampleScattering(scene, rng, path_ray, cam_isect, sampler->getSample(), cam_path)) break; } Spectrum ret(0.f); // Connect eye sub-path and light sub-path if (cam_path.path_len == eye_length) { sampler->startStream(2); if (light_length == 0) { auto light = last_hitting ? (Light*)cam_isect.arealight : env_light; if (light) { ret = cam_path.throughput * BidirectionalPathTracingIntegrator::hittingLightSource(scene, rng, Ray(cam_path.ori, cam_path.dir), cam_isect, light, cam_path); } } else if (eye_length == 1) { if (num_light_vertex > 0) { const auto &light_vertex = light_path[num_light_vertex - 1]; if (light_vertex.path_len == light_length) { Point3 raster_p; ret = BidirectionalPathTracingIntegrator::connectToCamera(scene, sampler, rng, mp_camera, mp_film, light_vertex.isect, light_vertex, &raster_p); *raster_pos = Vector2f(raster_p.x, raster_p.y); } } } else if (light_length == 1) { if (last_hitting && !cam_isect.bsdf->isSpecular()) { // Connect to light source ret = cam_path.throughput * BidirectionalPathTracingIntegrator::connectToLight(scene, sampler, rng, Ray(cam_path.ori, cam_path.dir), cam_isect, cam_path); } } else { if (num_light_vertex > 0 && last_hitting && !cam_isect.bsdf->isSpecular()) { const auto &light_vertex = light_path[num_light_vertex - 1]; ret = light_vertex.throughput * cam_path.throughput * BidirectionalPathTracingIntegrator::connectVertex(scene, rng, cam_isect, light_vertex, cam_path); } } ret *= num_strategies; } return ret; } }
9,994
C++
.cpp
260
34.253846
126
0.691242
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,903
BidirectionalPathTracing.cpp
g1n0st_AyaRay/src/Integrators/BidirectionalPathTracing.cpp
#include <Integrators/BidirectionalPathTracing.h> namespace Aya { // Bidirectional Path Tracing Integrator, implementation refers to the papers: // http://pdfs.semanticscholar.org/383a/98f474dc482b9c1427d9408cf85a22e01dc0.pdf // Iliyan Georgiev. Implementing vertex connection and merging.Technical report, // Saarland University, 2012 // Formula references consistent with this paper // https://cescg.org/wp-content/uploads/2018/04/Vlnas-Bidirectional-Path-Tracing-1.pdf // Michal Vlnas. Bidirectional Path Tracing // Faculty of Information Technology. Brno University of Technology. Brno / Czech Republic // Algorithm framework consistent with this paper Spectrum BidirectionalPathTracingIntegrator::li(const RayDifferential &ray, const Scene *scene, Sampler *sampler, RNG &rng, MemoryPool &memory) const { // Randomly select a light source, and generate the light path PathVertex *light_path = memory.alloc<PathVertex>(m_maxDepth); int light_vertex_cnt; int light_path_len = generateLightPath(scene, sampler, rng, mp_cam, mp_film, m_maxDepth + 1, light_path, &light_vertex_cnt); // Initialize camera path with eye ray PathState cam_path; sampleCamera(scene, mp_cam, mp_film, ray, cam_path); // Iterate camera path with Path Tracing, and connect it with the light path Spectrum L(0.f); while (true) { RayDifferential path_ray(cam_path.ori, cam_path.dir); SurfaceIntersection local_isect; if (!scene->intersect(path_ray, &local_isect)) { // miss intersecting, but directly hitting IBL if (scene->getEnviromentLight()) { ++cam_path.path_len; L += cam_path.throughput * hittingLightSource(scene, rng, path_ray, local_isect, scene->getEnviromentLight(), cam_path); } break; } scene->postIntersect(ray, &local_isect); // Update MIS quantities from iteration (34) (35) // Divide by g_i-> factor, Forward pdf conversion factor from solid angle measure to area measure (4) (8) float cos_in = Abs(local_isect.n.dot(-path_ray.m_dir)); cam_path.dvcm *= MIS(local_isect.dist * local_isect.dist); cam_path.dvcm /= MIS(cos_in); cam_path.dvc /= MIS(cos_in); // Add contribution when directly hitting a light source if (local_isect.arealight != nullptr) { ++cam_path.path_len; L += cam_path.throughput * hittingLightSource(scene, rng, path_ray, local_isect, (Light*)local_isect.arealight, cam_path); break; } if (++cam_path.path_len >= m_maxDepth + 2) break; const BSDF *bsdf = local_isect.bsdf; // Excute vertex connection between light and camera on Diffuse Surface if (!bsdf->isSpecular()) { // Connect to light source L += cam_path.throughput * connectToLight(scene, sampler, rng, path_ray, local_isect, cam_path); // Connect to light vertices for (auto i = 0; i < light_vertex_cnt; ++i) { const PathVertex &light_vertex = light_path[i]; if (light_vertex.path_len + cam_path.path_len > m_maxDepth + 2) break; L += cam_path.throughput * light_vertex.throughput * connectVertex(scene, rng, local_isect, light_vertex, cam_path); } } // Extend camera path with importance sampling on BSDF if (!sampleScattering(scene, rng, path_ray, local_isect, sampler->getSample(), cam_path)) break; } return L; } BidirectionalPathTracingIntegrator::PathState BidirectionalPathTracingIntegrator::sampleLightSource(const Scene *scene, Sampler *sampler, RNG &rng) { float light_sample = sampler->get1D(); float light_pick_pdf; const Light *light = scene->chooseLightSource(light_sample, &light_pick_pdf); Ray light_ray; Normal3 emit_dir; float emit_pdf, direct_pdf; PathState path; path.throughput = light->sample(sampler->getSample(), sampler->getSample(), &light_ray, &emit_dir, &emit_pdf, &direct_pdf); if (emit_pdf == 0.f) return path; direct_pdf *= light_pick_pdf; emit_pdf *= light_pick_pdf; path.throughput /= emit_pdf; path.is_finite_light = light->isFinite(); path.specular_path = true; path.path_len = 1; path.dir = light_ray.m_dir; path.ori = light_ray.m_ori; float emit_cos = emit_dir.dot(light_ray.m_dir); path.dvcm = MIS(direct_pdf / emit_pdf); // Such light sources cannot be hit by random rays, as their emission is defined via a delta distribution, // i.e. we have pVC,0 = 0. (48) (49) if (light->isDelta()) path.dvc = 0.f; // formula (31) (32) else if (light->isFinite()) path.dvc = MIS(emit_cos / emit_pdf); // handling infinite lights via solid anglg integration, // and derive the corresponding path pdfs for use in MIS. else path.dvc = MIS(1.f / emit_pdf); return path; } int BidirectionalPathTracingIntegrator::generateLightPath(const Scene *scene, Sampler *sampler, RNG &rng, const Camera *camera, Film *film, const uint32_t max_depth, PathVertex *path, int *vertex_count, const bool connect_to_cam, const int RR_depth) { if (max_depth == 0) { *vertex_count = 0; return 0; } // Select a light source, and generate the light path PathState light_path = sampleLightSource(scene, sampler, rng); if (light_path.throughput.isBlack()) return 0; if (light_path.path_len >= max_depth) { *vertex_count = 0; return light_path.path_len; } // Light Tracing *vertex_count = 0; while (true) { Ray path_ray(light_path.ori, light_path.dir); SurfaceIntersection intersection; if (!scene->intersect(path_ray, &intersection)) break; scene->postIntersect(path_ray, &intersection); // Update MIS quantities from iteration (34) (35) // Divide by g_i-> factor, Forward pdf conversion factor from solid angle measure to area measure (4) (8) float cos_in = Abs(intersection.n.dot(-path_ray.m_dir)); // Special Case at Infinite Light Source (5.1) if (light_path.is_finite_light || light_path.path_len > 1) light_path.dvcm *= MIS(intersection.dist * intersection.dist); light_path.dvcm /= MIS(cos_in); light_path.dvc /= MIS(cos_in); // Store the current vertex and connect the light vertex with camera // Unless hitting specular surface const BSDF *bsdf = intersection.bsdf; if (!bsdf->isSpecular()) { // Store the light vertex PathVertex &light_vertex = path[(*vertex_count)++]; light_vertex.throughput = light_path.throughput; light_vertex.path_len = light_path.path_len + 1; light_vertex.isect = intersection; light_vertex.v_in = -light_path.dir; light_vertex.dvc = light_path.dvc; light_vertex.dvcm = light_path.dvcm; // Connect to camera if (connect_to_cam) { Point3 raster; Spectrum L = connectToCamera(scene, sampler, rng, camera, film, intersection, light_vertex, &raster); film->splat(raster.x, raster.y, L); } } // Terminate with hard limitation if (++light_path.path_len >= max_depth) break; // Extend light path with importance sampling on BSDF if (!sampleScattering(scene, rng, path_ray, intersection, sampler->getSample(), light_path, RR_depth)) break; } return light_path.path_len; } Spectrum BidirectionalPathTracingIntegrator::connectToCamera(const Scene *scene, Sampler *sampler, RNG &rng, const Camera *camera, Film *film, const SurfaceIntersection &intersection, const PathVertex &path_vertex, Point3 *raster_pos) { Point3 cam_pos = camera->m_pos; Vector3 cam_dir = camera->m_dir; // Check if the point lies within the raster range Vector3 dir2cam; if (camera->getCircleOfConfusionRadius() == 0.f) { // Pin Hole Model *raster_pos = camera->worldToRaster(intersection.p); dir2cam = cam_pos - intersection.p; } else { // Thin Lens Model *raster_pos = camera->worldToRaster(intersection.p); Vector2f scr_coord(2.f * float(raster_pos->x) / float(camera->getResolusionX()) - 1.f, 2.f * float(raster_pos->y) / float(camera->getResolusionY()) - 1.f); scr_coord.x *= camera->m_ratio; scr_coord.y *= -1.f; // Sampling on disk lens float U, V; ConcentricSampleDisk(sampler->get1D(), sampler->get1D(), &U, &V); if (Vector2f(scr_coord.x + U, scr_coord.v + V).length() > camera->m_vignetteFactor) return Spectrum(0.f); U *= camera->getCircleOfConfusionRadius(); V *= camera->getCircleOfConfusionRadius(); Ray eye_ray; eye_ray.m_ori = Point3(U, V, 0.f); eye_ray.m_dir = (camera->view(intersection.p) - eye_ray.m_ori).normalize(); Point3 focal = eye_ray(camera->getFocusDistance() / eye_ray.m_dir.z); *raster_pos = camera->cameraToRaster(focal); dir2cam = camera->viewInv(eye_ray.m_ori) - intersection.p; } // Check whether the ray is in front of camera if (cam_dir.dot(-dir2cam) <= 0.f || !camera->checkRaster(*raster_pos)) return Spectrum(0.f); float dist2cam = dir2cam.length(); dir2cam.normalized(); const BSDF *bsdf = intersection.bsdf; Spectrum bsdf_fac = bsdf->f(dir2cam, path_vertex.v_in, intersection, ScatterType(BSDF_ALL & ~BSDF_SPECULAR)) * Abs(path_vertex.v_in.dot(intersection.n)) / Abs(path_vertex.v_in.dot(intersection.gn)); if (bsdf_fac.isBlack()) return Spectrum(0.f); // Forward and reverse solid angle pdfs for sub-path vertex float pdf = bsdf->pdf(path_vertex.v_in, dir2cam, intersection, ScatterType(BSDF_ALL & ~BSDF_SPECULAR)); float rev_pdf = bsdf->pdf(dir2cam, path_vertex.v_in, intersection, ScatterType(BSDF_ALL & ~BSDF_SPECULAR)); if (pdf == 0.f || rev_pdf == 0.f) return Spectrum(0.f); float cos_cam2gn = intersection.gn.dot(dir2cam); float cos_cam2dir = cam_dir.dot(-dir2cam); float raster2cam_dist = camera->getImagePlaneDistance() / cos_cam2dir; float raster2SA_fac = raster2cam_dist * raster2cam_dist / cos_cam2dir; // Camera solid angle to area pdf factor float cam_pdfA = raster2SA_fac * Abs(cos_cam2gn) / (dist2cam * dist2cam); // Intersection solid angle to area pdf factor // nlight is the total number of light sub-paths float n_lights = float(film->getPixelCount()); // Vertex connection (t = 1). // The light sub-path vertex y_s-1 is connected to vertex z0 on the eye lens (a.k.a. eye/camera projectin) float weight_light = MIS(cam_pdfA / n_lights) * (path_vertex.dvcm + MIS(rev_pdf) * path_vertex.dvc); // formula (46) float MIS_weight = 1.f / (weight_light + 1.f); // formula (37) (weight_camera = 0 in formula (47)) Spectrum L = MIS_weight * path_vertex.throughput * bsdf_fac * cam_pdfA / n_lights; Ray ray2cam(intersection.p, dir2cam, intersection.m_mediumInterface.getMedium(dir2cam, intersection.n), 0.f, dist2cam); if (L.isBlack() || scene->occluded(ray2cam)) return Spectrum(0.f); return L; } void BidirectionalPathTracingIntegrator::sampleCamera(const Scene *scene, const Camera *camera, Film *film, const RayDifferential &ray, PathState &init_path) { float cos_cam2dir = camera->m_dir.dot(ray.m_dir); float raster2cam_dist = camera->getImagePlaneDistance() / cos_cam2dir; float camera_pdfW = raster2cam_dist * raster2cam_dist / cos_cam2dir; float n_lights = float(film->getPixelCount()); init_path.ori = ray.m_ori; init_path.dir = ray.m_dir; init_path.throughput = Spectrum(1.f); init_path.path_len = 1; init_path.specular_path = true; init_path.dvcm = MIS(n_lights / camera_pdfW); // formula (31) init_path.dvc = 0.f; // formula (32) } Spectrum BidirectionalPathTracingIntegrator::connectToLight(const Scene *scene, Sampler *sampler, RNG &rng, const RayDifferential &ray, const SurfaceIntersection &intersection, PathState &cam_path) { // Sample light source and get radiance float light_sample = sampler->get1D(); float light_pick_pdf; const Light *light = scene->chooseLightSource(light_sample, &light_pick_pdf); const Point3 &pos = intersection.p; Vector3 v_in; VisibilityTester tester; float light_pdfW, emit_pdfW, cos_at_light; Spectrum radiance = light->illuminate(intersection, sampler->getSample(), &v_in, &tester, &light_pdfW, &cos_at_light, &emit_pdfW); if (radiance.isBlack() || light_pdfW == 0.f) return Spectrum(0.f); const BSDF *bsdf = intersection.bsdf; Vector3 v_out = -ray.m_dir; Spectrum bsdf_fac = bsdf->f(v_out, v_in, intersection); if (bsdf_fac.isBlack()) return Spectrum(0.f); float bsdf_pdfW = bsdf->pdf(v_out, v_in, intersection); if (bsdf_pdfW == 0.f) return Spectrum(0.f); if (light->isDelta()) bsdf_pdfW = 0.f; // Vertex connection (s = 1). // The eye sub-path vertex z_t-1 is connected to vertex y0 on a light source (a.k.a. next event estimation) float rev_bsdf_pdfW = bsdf->pdf(v_in, v_out, intersection); float weight_light = MIS(bsdf_pdfW / (light_pdfW * light_pick_pdf)); // formula (44) float cos2light = Abs(intersection.n.dot(v_in)); float weight_camera = MIS(emit_pdfW * cos2light / (light_pdfW * cos_at_light)) // formula (45) * (cam_path.dvcm + cam_path.dvc * MIS(rev_bsdf_pdfW)); float MIS_weight = 1.f / (weight_light + 1.f + weight_camera); // formula (37) Spectrum L = (MIS_weight * cos2light / (light_pdfW * light_pick_pdf)) * bsdf_fac * radiance; if (L.isBlack() || !tester.unoccluded(scene)) return Spectrum(0.f); return L; } Spectrum BidirectionalPathTracingIntegrator::hittingLightSource(const Scene *scene, RNG &rng, const RayDifferential &ray, const SurfaceIntersection &intersection, const Light *light, PathState &cam_path) { float light_pick_pdf = scene->lightPdf(light); Vector3 v_out = -ray.m_dir; float direct_pdfA; float emit_pdfW; Spectrum radiance = light->emit(v_out, intersection.gn, &emit_pdfW, &direct_pdfA); if (radiance.isBlack()) return Spectrum(0.f); if (cam_path.path_len == 2) return radiance; // Vertex connection(s = 0). // The eye sub - path vertex z_t-1 is sampled on a light source, i.e.the light sub - path has zero vertices direct_pdfA *= light_pick_pdf; emit_pdfW *= light_pick_pdf; float weight_camera = MIS(direct_pdfA) * cam_path.dvcm + MIS(emit_pdfW) * cam_path.dvc; // formula (43) float MIS_weight = 1.f / (1.f + weight_camera); // formula (37) (weight_camera = 0 in formula (42)) return MIS_weight * radiance; } Spectrum BidirectionalPathTracingIntegrator::connectVertex(const Scene *scene, RNG &rng, const SurfaceIntersection &intersection, const PathVertex &light_vertex, const PathState &cam_path) { const Point3 &cam_pos = intersection.p; Vector3 dir2light = light_vertex.isect.p - cam_pos; float dist2light2 = dir2light.length2(); float dist2light = Sqrt(dist2light2); dir2light.normalized(); const BSDF *cam_bsdf = intersection.bsdf; const Normal3 &cam_n = intersection.n; Vector3 v_out_cam = -cam_path.dir; Spectrum cam_bsdf_fac = cam_bsdf->f(v_out_cam, dir2light, intersection); float cos_at_cam = cam_n.dot(dir2light); float cam_dir_pdfW = cam_bsdf->pdf(v_out_cam, dir2light, intersection); float rev_cam_dir_pdfW = cam_bsdf->pdf(dir2light, v_out_cam, intersection); if (cam_bsdf_fac.isBlack() || cam_dir_pdfW == 0.f || rev_cam_dir_pdfW == 0.f) return Spectrum(0.f); const BSDF *light_bsdf = light_vertex.isect.bsdf; Vector3 dir2cam = -dir2light; Spectrum light_bsdf_fac = light_bsdf->f(light_vertex.v_in, dir2cam, light_vertex.isect); float cos_at_light = light_vertex.isect.n.dot(dir2cam); float light_dir_pdfW = light_bsdf->pdf(light_vertex.v_in, dir2cam, light_vertex.isect); float rev_light_dir_pdfW = light_bsdf->pdf(dir2cam, light_vertex.v_in, light_vertex.isect); if (light_bsdf_fac.isBlack() || light_dir_pdfW == 0.f || rev_light_dir_pdfW == 0.f) return Spectrum(0.f); float g = cos_at_light * cos_at_cam / dist2light2; if (g < 0.f) { return Spectrum(0.f); } float cam_dir_pdfA = PdfWToA(cam_dir_pdfW, dist2light, cos_at_light); float light_dir_pdfA = PdfWToA(light_dir_pdfW, dist2light, cos_at_cam); // Vertex connection(s > 1, t > 1). // A path is constructed by connecting the light vertex y_s-1 to the eye vertex z_t-1 float weight_light = MIS(cam_dir_pdfA) * (light_vertex.dvcm + MIS(rev_light_dir_pdfW) * light_vertex.dvc); // formula (40) float weight_camera = MIS(light_dir_pdfA) * (cam_path.dvcm + MIS(rev_cam_dir_pdfW) * cam_path.dvc); // formula (41) float MIS_weight = 1.f / (weight_light + 1.f + weight_camera); // formula (37) Spectrum L = (MIS_weight * g) * light_bsdf_fac * cam_bsdf_fac; Ray ray2light(cam_pos, dir2light, intersection.m_mediumInterface.getMedium(dir2light, cam_n), 0.f, dist2light); if (L.isBlack() || scene->occluded(ray2light)) return Spectrum(0.f); return L; } bool BidirectionalPathTracingIntegrator::sampleScattering(const Scene *scene, RNG &rng, const RayDifferential &ray, const SurfaceIntersection &intersection, const Sample& bsdf_sample, PathState &path_state, const int RR_depth) { // Sample the scattered direction const BSDF *bsdf = intersection.bsdf; Vector3 v_in; float pdf; ScatterType sampled_type; Spectrum L = bsdf->sample_f(-ray.m_dir, bsdf_sample, intersection, &v_in, &pdf, BSDF_ALL, &sampled_type); // Update Path state before walking to the next vertex if (L.isBlack() || pdf == 0.f) return false; bool non_specular = (sampled_type & BSDF_SPECULAR) == 0; // For specular bounce, reverse pdf equals to forward pdf float rev_pdf = non_specular ? bsdf->pdf(v_in, -ray.m_dir, intersection) : pdf; // Apply Russian Roulette if non-specular surface was hit if (non_specular && RR_depth != -1 && int(path_state.path_len) > RR_depth) { float RR_prob = Min(1.f, path_state.throughput.luminance()); if (rng.drand48() < RR_prob) { pdf *= RR_prob; rev_pdf *= RR_prob; } else { return false; } } path_state.ori = intersection.p; path_state.dir = v_in; float cos_out = Abs(intersection.n.dot(v_in)); if (non_specular) { path_state.specular_path &= 0; path_state.dvc = MIS(cos_out / pdf) * (path_state.dvcm + MIS(rev_pdf) * path_state.dvc); // formula (35) path_state.dvcm = MIS(1.f / pdf); // formula (34) } else { path_state.specular_path &= 1; path_state.dvc *= MIS(cos_out); // rev_pdf / pdf equals to 1, formula (54) path_state.dvcm = 0.f; // formula (53) } path_state.throughput *= L * cos_out / pdf; return true; } }
18,159
C++
.cpp
391
42.716113
124
0.702901
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,904
FilmRHF.cpp
g1n0st_AyaRay/src/Films/FilmRHF.cpp
#include <Films/FilmRHF.h> namespace Aya { const float FilmRHF::Histogram::MAX_VAL = 7.5f; void FilmRHF::init(int width, int height, Filter *filter) { Film::init(width, height, filter); m_sampleHistogram.init(width, height); m_maxDist = { .6f }; m_halfPatchSize = { 1 }; m_halfWindowSize = { 6 }; m_scale = { 3 }; } void FilmRHF::resize(int width, int height) { Film::resize(width, height); m_sampleHistogram.free(); m_sampleHistogram.init(width, height); } void FilmRHF::free() { Film::free(); m_sampleHistogram.free(); } void FilmRHF::clear() { Film::clear(); concurrency::parallel_for(0, m_height, [this](int y) { for (int x = 0; x < m_width; x++) { m_sampleHistogram.totalWeights(x, y) = 0.f; for (int i = 0; i < Histogram::NUM_BINS; i++) { m_sampleHistogram.histogramWeights[i](x, y) = RGBSpectrum(0.f); } } }); } void FilmRHF::addSample(float x, float y, const Spectrum &sample) { x -= .5f; y -= .5f; int min_x = CeilToInt(x - mp_filter->getRadius()); int max_x = FloorToInt(x + mp_filter->getRadius()); int min_y = CeilToInt(y - mp_filter->getRadius()); int max_y = FloorToInt(y + mp_filter->getRadius()); min_x = Max(0, min_x); max_x = Min(max_x, m_width - 1); min_y = Max(0, min_y); max_y = Min(max_y, m_height - 1); for (int i = min_y; i <= max_y; i++) { for (int j = min_x; j <= max_x; j++) { int row = m_height - 1 - j; int col = j; Pixel &pixel = m_accumulateBuffer(col, row); float weight = mp_filter->evaluate(j - x, i - y); RGBSpectrum weighted_sample = Spectrum(weight * sample).toRGBSpectrum(); weighted_sample[0] = Max(0.f, weighted_sample[0]); weighted_sample[1] = Max(0.f, weighted_sample[1]); weighted_sample[2] = Max(0.f, weighted_sample[2]); RGBSpectrum normalized_sample = weighted_sample.pow(INV_GAMMA) / Histogram::MAX_VAL; const float S = 2.f; normalized_sample[0] = Min(S, normalized_sample[0]); normalized_sample[1] = Min(S, normalized_sample[1]); normalized_sample[2] = Min(S, normalized_sample[2]); std::array<float, 3> bin = { float(Histogram::NUM_BINS - 2) * normalized_sample[0], float(Histogram::NUM_BINS - 2) * normalized_sample[1], float(Histogram::NUM_BINS - 2) * normalized_sample[2] }; std::array<int, 3> bin_low = { FloorToInt(bin[0]), FloorToInt(bin[1]), FloorToInt(bin[2]) }; for (auto c = 0; c < 3; ++c) { float weight_H = { 0.f }, weight_L = { 0.f }; if (bin_low[c] < Histogram::NUM_BINS - 2) { weight_H = bin[c] - bin_low[c]; weight_L = 1.f - weight_H; m_sampleHistogram.histogramWeights[bin_low[c]](col, row)[c] += weight_L; m_sampleHistogram.histogramWeights[bin_low[c] + 1](col, row)[c] += weight_H; } else { weight_H = (normalized_sample[c] - 1.f) / (S - 1.f); weight_L = 1.f - weight_H; m_sampleHistogram.histogramWeights[Histogram::NUM_BINS - 2](col, row)[c] += weight_L; m_sampleHistogram.histogramWeights[Histogram::NUM_BINS - 1](col, row)[c] += weight_H; } } m_sampleHistogram.totalWeights(col, row) += 1.f; } } } void FilmRHF::denoise() { BlockedArray<RGBSpectrum> scaled_image; BlockedArray<RGBSpectrum> prev_image; Histogram scaled_histogram; float total_weight = { 0.f }; for (size_t i = 0; i < m_sampleHistogram.totalWeights.linearSize(); ++i) { total_weight += m_sampleHistogram.totalWeights.data()[i]; } for (auto s = m_scale - 1; s >= 0; --s) { float scale = 1.f / float(1 << s); if (s > 0) { concurrency::parallel_for(0, Histogram::NUM_BINS, [this, scale](int i) { gaussianDownSample(m_sampleHistogram.histogramWeights[i], m_sampleHistogram.histogramWeights[i], scale); }); gaussianDownSample(m_sampleHistogram.totalWeights, m_sampleHistogram.totalWeights, scale); float scaled_total_weight = { 0.f }; for (size_t i = 0; i < scaled_histogram.totalWeights.linearSize(); ++i) { scaled_total_weight += scaled_histogram.totalWeights.data()[i]; } float ratio = total_weight / scaled_total_weight; concurrency::parallel_for(0, Histogram::NUM_BINS, [this, ratio, &scaled_histogram](int b) { for (size_t i = 0; i < scaled_histogram.histogramWeights[b].linearSize(); ++i) { scaled_histogram.histogramWeights[b].data()[i] *= ratio; } }); gaussianDownSample(m_pixelBuffer, scaled_image, scale); } else { scaled_image = m_pixelBuffer; scaled_histogram = m_sampleHistogram; } histogramFusion(scaled_image, scaled_histogram); if (s < m_scale - 1) { BlockedArray<RGBSpectrum> pos_term; pos_term.init(scaled_image.u(), scaled_image.v()); bicubicInterpolation(prev_image, pos_term); BlockedArray<RGBSpectrum> neg_termD; gaussianDownSample(scaled_image, neg_termD, .5f); BlockedArray<RGBSpectrum> neg_term; neg_term.init(scaled_image.u(), scaled_image.v()); bicubicInterpolation(neg_termD, neg_term); for (size_t i = 0; i < scaled_image.linearSize(); ++i) { scaled_image.data()[i] += pos_term.data()[i] - neg_term.data()[i]; } } prev_image = scaled_image; } m_pixelBuffer = scaled_image; } void FilmRHF::histogramFusion(BlockedArray<RGBSpectrum> &input, const Histogram &histogram) { } float FilmRHF::chiSquareDistance(const Vector2i &x, const Vector2i &y, const int halfPathSize, const Histogram &histogram) { return 0.f; } template<typename T> void FilmRHF::gaussianDownSample(const BlockedArray<T> &input, BlockedArray<T> &output, float scale) { } void FilmRHF::bicubicInterpolation(const BlockedArray<RGBSpectrum> &input, BlockedArray<RGBSpectrum> &output) { } }
5,698
C++
.cpp
144
35.208333
125
0.654404
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,905
Film.cpp
g1n0st_AyaRay/src/Core/Film.cpp
#include <Core/Film.h> namespace Aya { const float Film::INV_GAMMA = .454545f; void Film::init(int width, int height, Filter *filter) { resize(width, height); mp_filter.reset(); mp_filter = std::unique_ptr<Filter>(filter); } void Film::resize(int width, int height) { m_width = width; m_height = height; m_pixelBuffer.free(); m_pixelBuffer.init(height, width); m_accumulateBuffer.free(); m_accumulateBuffer.init(width, height); m_sampleCount = 0; } void Film::clear() { std::lock_guard<std::mutex> lck(m_mt); concurrency::parallel_for(0, m_height, [this](int y) { for (int x = 0; x < m_width; x++) { Pixel &pixel = m_accumulateBuffer(x, y); pixel = { Spectrum(0.f), Spectrum(0.f), 0.f }; } }); m_sampleCount = 0; } void Film::free() { m_sampleCount = 0; m_pixelBuffer.free(); m_accumulateBuffer.free(); } void Film::addSample(float x, float y, const Spectrum& L) { std::lock_guard<std::mutex> lck(m_mt); x -= .5f; y -= .5f; int min_x = Clamp((int)std::ceil(x - mp_filter->getRadius()), 0, m_width - 1); int max_x = Clamp((int)std::floor(x + mp_filter->getRadius()), 0, m_width - 1); int min_y = Clamp((int)std::ceil(y - mp_filter->getRadius()), 0, m_height - 1); int max_y = Clamp((int)std::floor(y + mp_filter->getRadius()), 0, m_height - 1); for (auto i = min_y; i <= max_y; i++) { for (auto j = min_x; j <= max_x; j++) { Pixel &pixel = m_accumulateBuffer(j, m_height - 1 - i); float weight = mp_filter->evaluate(j - x, i - y); pixel.weight += weight; pixel.color += weight * L; } } } void Film::addFilm(const Film *film, float weight) { assert(m_width == film->m_width && m_height == film->m_height); std::lock_guard<std::mutex> lck(m_mt); concurrency::parallel_for(0, m_height, [this, film, weight](int y) { for (int x = 0; x < m_width; x++) { Pixel &pixel = m_accumulateBuffer(x, y); const Pixel &pixel0 = film->m_accumulateBuffer(x, y); pixel.color += pixel0.color * weight; pixel.weight += pixel0.weight * weight; pixel.splat += pixel0.splat * weight; } }); m_sampleCount += film->m_sampleCount; } void Film::splat(float x, float y, const Spectrum& L) { std::lock_guard<std::mutex> lck(m_mt); int xx = Clamp((int)std::floor(x), 0, m_width - 1); int yy = Clamp((int)std::floor(y), 0, m_height - 1); m_accumulateBuffer(xx, m_height - 1 - yy).splat += L; } void Film::updateDisplay(const float ss) { std::lock_guard<std::mutex> lck(m_mt); float splat_scale = ss > 0.f ? ss : m_sampleCount; concurrency::parallel_for(0, m_height, [this, splat_scale](int y) { for (int x = 0; x < m_width; x++) { Pixel pixel = m_accumulateBuffer(x, y); pixel.color.clamp(); Spectrum L = ((Spectrum)( pixel.color / (pixel.weight + float(AYA_EPSILON)) + pixel.splat / splat_scale ).pow(INV_GAMMA)).toRGBSpectrum().clamp(0.f, 1.f); L[3] = 1.f; m_pixelBuffer(y, x) = L; } }); } }
2,979
C++
.cpp
85
31.482353
82
0.624259
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,912
Camera.cpp
g1n0st_AyaRay/src/Core/Camera.cpp
#include <Core/Camera.h> namespace Aya { Camera::Camera(const Point3 &pos, const Point3 &tar, const Vector3 &up, int res_x, int res_y, float FOV, float _near, float _far, const float blur_radius, const float focal_dist, const float vignette) { init(pos, tar, up, res_x, res_y, FOV, _near, _far, blur_radius, focal_dist, vignette); } void Camera::init(const Point3 &pos, const Point3 &tar, const Vector3 &up, int res_x, int res_y, float FOV, float _near, float _far, const float blur_radius, const float focal_dist, const float vignette) { m_pos = pos; m_target = tar; m_dir = (m_target - m_pos).normalize(); m_up = up; m_resX = res_x; m_resY = res_y; m_FOV = FOV; m_near = _near; m_far = _far; m_view = Transform::lookAt(m_pos, m_target, m_up); m_viewInv = m_view.inverse(); resize(m_resX, m_resY); m_CoCRadius = blur_radius; m_focalPlaneDist = focal_dist; m_vignetteFactor = 3.f - vignette; float tanHalfAngle = tanf(Radian(m_FOV * .5f)); m_imagePlaneDist = m_resY * .5f / tanHalfAngle; const int size = 128; BlockedArray<float> apeture_func(size, size); for (int i = 0; i < size; i++) { float y = 2.f * i / float(size) - 1.f; for (int j = 0; j < size; j++) { float x = 2.f * j / float(size) - 1.f; apeture_func(i, j) = Vector2f(x, y).length() < 1.f ? 1.f : 0.f; } } mp_aperture = std::make_unique<Distribution2D>(apeture_func.data(), size, size); } void Camera::resize(int width, int height) { m_resX = width; m_resY = height; m_ratio = float(m_resX) / float(m_resY); m_proj = Transform::perspective(m_FOV, m_ratio, m_near, m_far); m_screenToRaster = Transform().setScale(float(m_resX), float(m_resY), 1.f) * Transform().setScale(.5f, -.5f, 1.f) * Transform().setTranslate(1.f, -1.f, 0.f); m_rasterToScreen = m_screenToRaster.inverse(); m_rasterToCamera = m_proj.inverse() * m_rasterToScreen; m_cameraToRaster = m_rasterToCamera.inverse(); m_rasterToWorld = m_viewInv * m_rasterToCamera; m_worldToRaster = m_rasterToWorld.inverse(); m_dxCam = rasterToCamera(Point3(1.f, 0.f, 0.f)) - rasterToCamera(Point3(0.f)); m_dyCam = rasterToCamera(Point3(0.f, 1.f, 0.f)) - rasterToCamera(Point3(0.f)); float tanHalfAngle = tanf(Radian(m_FOV * .5f)); m_imagePlaneDist = m_resY * .5f / tanHalfAngle; } bool Camera::generateRay(const CameraSample &sample, Ray *ray, const bool force_pinhole) const { Point3 cam_coord = rasterToCamera(Point3(sample.image_x, sample.image_y, 0.f)); ray->m_ori = Point3(0.f); ray->m_dir = cam_coord.normalize(); if (m_CoCRadius > 0.f && !force_pinhole) { float focal_hit = m_focalPlaneDist / ray->m_dir.z; Point3 focal = (*ray)(focal_hit); Vector2f scr_coord(2.f * float(sample.image_x) / float(m_resX) - 1.f, 2.f * float(sample.image_y) / float(m_resY) - 1.f); scr_coord.x *= m_ratio; scr_coord.y *= -1.f; float u, v, pdf; mp_aperture->sampleContinuous(sample.lens_u, sample.lens_v, &u, &v, &pdf); u = 2.f * u - 1.f; v = 2.f * v - 1.f; if (Vector2f(scr_coord.x + u, scr_coord.y + v).length() > m_vignetteFactor) return false; u *= m_CoCRadius; v *= m_CoCRadius; ray->m_ori = Point3(u, v, 0.f); ray->m_dir = (focal - ray->m_ori).normalize(); } *ray = m_viewInv(*ray); ray->m_mint = float(AYA_RAY_EPS); ray->m_maxt = float(INFINITY - AYA_RAY_EPS); return true; } bool Camera::generateRayDifferential(const CameraSample &sample, RayDifferential *ray) const { Point3 cam_coord = rasterToCamera(Point3(sample.image_x, sample.image_y, 0.f)); ray->m_ori = Point3(0.f); ray->m_dir = cam_coord.normalize(); if (m_CoCRadius > 0.f) { float focal_hit = m_focalPlaneDist / ray->m_dir.z; Point3 focal = (*ray)(focal_hit); Vector2f scr_coord(2.f * float(sample.image_x) / float(m_resX) - 1.f, 2.f * float(sample.image_y) / float(m_resY) - 1.f); scr_coord.x *= m_ratio; scr_coord.y *= -1.f; float u, v, pdf; mp_aperture->sampleContinuous(sample.lens_u, sample.lens_v, &u, &v, &pdf); u = 2.f * u - 1.f; v = 2.f * v - 1.f; if (Vector2f(scr_coord.x + u, scr_coord.y + v).length() > m_vignetteFactor) return false; u *= m_CoCRadius; v *= m_CoCRadius; ray->m_ori = Point3(u, v, 0.f); ray->m_dir = (focal - ray->m_ori).normalize(); } ray->m_rxOri = ray->m_ryOri = ray->m_ori; ray->m_rxDir = (cam_coord + m_dxCam).normalize(); ray->m_ryDir = (cam_coord + m_dyCam).normalize(); ray->m_hasDifferentials = true; *ray = m_viewInv(*ray); ray->m_mint = float(AYA_RAY_EPS); ray->m_maxt = float(INFINITY - AYA_RAY_EPS); return true; } void Camera::setApertureFunc(const char *path) { int width, height, channel; float *func = Bitmap::read<float>(path, &width, &height, &channel); mp_aperture = std::make_unique<Distribution2D>(func, height, width); SafeDeleteArray(func); } }
4,874
C++
.cpp
123
36.105691
97
0.647096
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,915
Primitive.cpp
g1n0st_AyaRay/src/Core/Primitive.cpp
#include <Core/Primitive.h> #include <BSDFs/LambertianDiffuse.h> #include <BSDFs/Glass.h> #include <BSDFs/Mirror.h> #include <BSDFs/Disney.h> namespace Aya { Primitive::~Primitive() { SafeDeleteArray(mp_materialIdx); SafeDeleteArray(mp_subsetStartIdx); SafeDeleteArray(mp_subsetMaterialIdx); } void Primitive::loadMesh(const Transform &o2w, const char *path, std::function<std::unique_ptr<BSDF>(const ObjMaterial&)> mtl_parser, const bool force_compute_normal, const bool left_handed, const MediumInterface &medium_interface) { ObjMesh *mesh = new ObjMesh; mesh->loadObj(path, force_compute_normal, left_handed); mp_mesh = std::make_unique<TriangleMesh>(); mp_mesh->loadMesh(o2w, mesh); const auto& mtl_info = mesh->getMaterialBuff(); mp_BSDFs.resize(mtl_info.size()); for (auto i = 0; i < mtl_info.size(); i++) { auto &mtl = mtl_info[i]; mp_BSDFs[i] = mtl_parser(mtl); m_mediumInterface.emplace_back(medium_interface); } mp_materialIdx = new uint32_t[mesh->getTriangleCount()]; for (uint32_t i = 0; i < mesh->getTriangleCount(); i++) mp_materialIdx[i] = mesh->getMaterialIdx(i); m_subsetCount = mesh->getSubsetCount(); mp_subsetMaterialIdx = new uint32_t[m_subsetCount]; mp_subsetStartIdx = new uint32_t[m_subsetCount]; for (uint32_t i = 0; i < m_subsetCount; i++) { mp_subsetMaterialIdx[i] = mesh->getSubsetMtlIdx(i); mp_subsetStartIdx[i] = mesh->getSubsetStartIdx(i); } SafeDelete(mesh); } void Primitive::loadSphere(const Transform &o2w, const float radius, std::unique_ptr<BSDF> bsdf, const MediumInterface &medium_interface) { mp_mesh = std::make_unique<TriangleMesh>(); mp_mesh->loadSphere(o2w, radius); setBSDF(std::move(bsdf), medium_interface); } void Primitive::loadPlane(const Transform &o2w, const float length, std::unique_ptr<BSDF> bsdf, const MediumInterface &medium_interface) { mp_mesh = std::make_unique<TriangleMesh>(); mp_mesh->loadPlane(o2w, length); setBSDF(std::move(bsdf), medium_interface); } void Primitive::postIntersect(const RayDifferential &ray, SurfaceIntersection *intersection) const { intersection->bsdf = mp_BSDFs[mp_materialIdx[intersection->tri_id]].get(); // BSSRDF Part intersection->arealight = mp_light; intersection->m_mediumInterface = m_mediumInterface[mp_materialIdx[intersection->tri_id]]; mp_mesh->postIntersect(ray, intersection); } void Primitive::setBSDF(std::unique_ptr<BSDF> bsdf, const MediumInterface &medium_interface) { mp_BSDFs.resize(1); mp_BSDFs[0] = std::move(bsdf); m_mediumInterface.emplace_back(medium_interface); mp_materialIdx = new uint32_t[mp_mesh->getTriangleCount()]; memset(mp_materialIdx, 0, sizeof(uint32_t) * mp_mesh->getTriangleCount()); m_subsetCount = 1; mp_subsetMaterialIdx = new uint32_t[1]; mp_subsetStartIdx = new uint32_t[1]; mp_subsetMaterialIdx[0] = mp_subsetStartIdx[0] = 0; } }
2,907
C++
.cpp
75
35.866667
101
0.733688
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,916
Memory.cpp
g1n0st_AyaRay/src/Core/Memory.cpp
#include <Core/Memory.h> namespace Aya { void FreeAligned(void *ptr) { if (!ptr) return; _aligned_free(ptr); } }
119
C++
.cpp
7
15.142857
30
0.6875
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,918
Filter.cpp
g1n0st_AyaRay/src/Core/Filter.cpp
#include <Core/Filter.h> namespace Aya { const float Filter::getRadius() const { return m_radius; } }
106
C++
.cpp
6
16
40
0.73
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,921
RoughConductor.cpp
g1n0st_AyaRay/src/BSDFs/RoughConductor.cpp
#include <BSDFs/RoughConductor.h> namespace Aya { Spectrum RoughConductor::sample_f(const Vector3 &v_out, const Sample &sample, const SurfaceIntersection &intersection, Vector3 *v_in, float *pdf, ScatterType types, ScatterType *sample_types) const { if (!matchesTypes(types)) { *pdf = 0.f; return Spectrum(0.f); } Vector3 wo = intersection.worldToLocal(v_out), wi; float microfacet_pdf; float roughness = getValue(m_roughness.get(), intersection, TextureFilter::Linear); roughness = Clamp(roughness, .02f, 1.f); roughness = roughness * roughness; Vector3 wh = GGX_SampleVisibleNormal(wo * (CosTheta(wo) >= 0.f ? 1.f : -1.f), sample.u, sample.v, &microfacet_pdf, roughness); if (microfacet_pdf == 0.f) return 0.f; wi = -wo + Vector3(2.f * wo.dot(wh) * wh); if (!sameHemisphere(wo, wi)) return Spectrum(0.f); *v_in = intersection.localToWorld(wi); float dwh_dwi = 1.f / (4.f * Abs(wi.dot(wh))); *pdf = microfacet_pdf * dwh_dwi; if (v_out.dot(intersection.gn) * v_in->dot(intersection.gn) > 0.f) types = ScatterType(types & ~BSDF_TRANSMISSION); else types = ScatterType(types & ~BSDF_REFLECTION); if (!matchesTypes(types)) { *pdf = 0.f; return Spectrum(0.f); } if (sample_types != nullptr) *sample_types = m_scatterType; float D = GGX_D(wh, roughness); if (D == 0.f) return 0.f; float F = fresnelConductor(wh.dot(wo), .4f, 1.6f); float G = GGX_G(wo, wi, wh, roughness); // Cook-Torrance microfacet model return getValue(mp_texture.get(), intersection) * F * D * G / (4.f * AbsCosTheta(wo) * AbsCosTheta(wi)); } float RoughConductor::evalInner(const Vector3 &wo, const Vector3 &wi, const SurfaceIntersection &intersection, ScatterType types) const { if (!sameHemisphere(wo, wi)) return 0.0f; Vector3 wh = (wo + wi).normalize(); wh *= (CosTheta(wh) >= 0.f ? 1.f : -1.f); float roughness = getValue(m_roughness.get(), intersection, TextureFilter::Linear); roughness = Clamp(roughness, .02f, 1.f); roughness = roughness * roughness; float D = GGX_D(wh, roughness); if (D == 0.f) return 0.f; float F = fresnelConductor(wh.dot(wo), .4f, 1.6f); float G = GGX_G(wo, wi, wh, roughness); // Cook-Torrance microfacet model return F * D * G / (4.f * AbsCosTheta(wo) * AbsCosTheta(wi)); } float RoughConductor::pdfInner(const Vector3 &wo, const Vector3 &wi, const SurfaceIntersection &intersection, ScatterType types) const { if (!sameHemisphere(wo, wi)) return 0.0f; Vector3 wh = (wo + wi).normalize(); wh *= (CosTheta(wh) >= 0.f ? 1.f : -1.f); float roughness = getValue(m_roughness.get(), intersection, TextureFilter::Linear); roughness = Clamp(roughness, .02f, 1.f); roughness = roughness * roughness; float dwh_dwi = 1.f / (4.f * wi.dot(wh)); float wh_prob = GGX_Pdf_VisibleNormal(wo * (CosTheta(wo) >= 0.f ? 1.f : -1.f), wh, roughness); return Abs(wh_prob * dwh_dwi); } }
2,922
C++
.cpp
69
39.028986
138
0.676907
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,922
Disney.cpp
g1n0st_AyaRay/src/BSDFs/Disney.cpp
#include <BSDFs/Disney.h> namespace Aya { float Disney::pdfInner(const Vector3 &l_out, const Vector3 &l_in, const SurfaceIntersection &intersection, ScatterType types) const { Vector3 wh = (l_out + l_in).normalize(); if (wh.length2() == 0.f) return 0.f; float roughness = getValue(mp_roughness.get(), intersection, TextureFilter::Linear); roughness = Clamp(roughness, .02f, 1.f); float specular = getValue(mp_specular.get(), intersection, TextureFilter::Linear); float microfacet_pdf = GGX_Pdf_VisibleNormal(l_out, wh, roughness * roughness); float pdf = 0.f; float dwh_dwi = 1.f / (4.f * Abs(l_in.dot(wh))); float spec_pdf = microfacet_pdf * dwh_dwi; float normal_ref = Lerp(specular, .0f, .08f); float OdotH = l_out.dot(wh); float prob_spec = Fresnel_Schlick(OdotH, normal_ref); pdf += spec_pdf * prob_spec; pdf += AbsCosTheta(l_in) * float(M_1_PI) * (1.f - prob_spec); if (m_clearCoat > 0.f) { Spectrum albedo = getValue(mp_texture.get(), intersection); float coat_weight = m_clearCoat / (m_clearCoat + albedo.luminance()); float fresnel_coat = Fresnel_Schlick_Coat(AbsCosTheta(l_out)); float prob_coat = (fresnel_coat * coat_weight) / (fresnel_coat * coat_weight + (1.f - fresnel_coat) * (1.f - coat_weight)); float coat_rough = Lerp(m_clearCoatGloss, .005f, .10f); float coat_half_pdf = GGX_Pdf_VisibleNormal(l_out, wh, coat_rough); float coat_pdf = coat_half_pdf * dwh_dwi; pdf *= 1.f - prob_coat; pdf += coat_pdf * prob_coat; } return pdf; } float Disney::evalInner(const Vector3 &v_out, const Vector3 &v_in, const SurfaceIntersection &intersection, ScatterType types) const { return 0.f; } Spectrum Disney::f(const Vector3 &v_out, const Vector3 &v_in, const SurfaceIntersection &intersection, ScatterType types) const { if (v_out.dot(intersection.gn) * v_in.dot(intersection.gn) > 0.f) types = ScatterType(types & ~BSDF_TRANSMISSION); else types = ScatterType(types & ~BSDF_REFLECTION); if (!matchesTypes(types)) return Spectrum(0.f); Vector3 l_out = intersection.worldToLocal(v_out); Vector3 l_in = intersection.worldToLocal(v_in); return evaluate(l_out, l_in, intersection, types); } Spectrum Disney::evaluate(const Vector3 &l_out, const Vector3 &l_in, const SurfaceIntersection &intersection, ScatterType types) const { Spectrum albedo = getValue(mp_texture.get(), intersection); float roughness = getValue(mp_roughness.get(), intersection, TextureFilter::Linear); roughness = Clamp(roughness, .02f, 1.f); float specular = getValue(mp_specular.get(), intersection, TextureFilter::Linear); Spectrum Ctint = albedo.luminance(); // luminance approx. Spectrum Cspec0 = Lerp(m_metallic, // dielectric -> metallic Lerp(1.f - m_specularTint, albedo, Ctint), // baseColor -> Colorless albedo); Spectrum Csheen = Lerp(m_sheenTint, Ctint, albedo); // Colorless -> baseColor Vector3 wh = (l_out + l_in).normalize(); float OdotH = l_out.dot(wh); float IdotH = l_in.dot(wh); float _1_OdotH = 1.f - OdotH; Cspec0 = Lerp(_1_OdotH * _1_OdotH * _1_OdotH, Cspec0, Ctint); // sheen float FH = Fresnel_Schlick(OdotH, 0.f); Spectrum sheen = FH * m_sheen * Csheen; return (1.f - m_metallic) * (albedo * Lerp(m_subsurface, diffuseTerm(l_out, l_in, IdotH, roughness), subsurfaceTerm(l_out, l_in, IdotH, roughness)) + sheen) + Cspec0 * specularTerm(l_out, l_in, wh, OdotH, roughness, specular, nullptr) + Spectrum(clearCoatTerm(l_out, l_in, wh, IdotH, m_clearCoatGloss)); } Spectrum Disney::sample_f(const Vector3 &v_out, const Sample &sample, const SurfaceIntersection &intersection, Vector3 *v_in, float *pdf, ScatterType types, ScatterType *sample_types) const { if (!matchesTypes(types)) { *pdf = 0.f; return Spectrum(0.f); } const Vector3 l_out = intersection.worldToLocal(v_out); Vector3 l_in, wh; bool sample_coat = false; Sample remapped_sample = sample; if (m_clearCoat > 0.f) { Spectrum albedo = getValue(mp_texture.get(), intersection); float coat_weight = m_clearCoat / (m_clearCoat + albedo.luminance()); float fresnel_coat = Fresnel_Schlick_Coat(AbsCosTheta(l_out)); float prob_coat = (fresnel_coat * coat_weight) / (fresnel_coat * coat_weight + (1.f - fresnel_coat) * (1.f - coat_weight)); if (sample.v < prob_coat) { sample_coat = true; remapped_sample.v /= prob_coat; float coat_rough = Lerp(m_clearCoatGloss, .005f, .1f); float coat_pdf; wh = GGX_SampleVisibleNormal(l_out, remapped_sample.u, remapped_sample.v, &coat_pdf, coat_rough); l_in = -l_out + 2.f * l_out.dot(wh) * wh; *sample_types = ScatterType(BSDF_REFLECTION | BSDF_GLOSSY); } else { sample_coat = false; remapped_sample.v = (sample.v - prob_coat) / (1.f - prob_coat); } } if (!sample_coat) { float microfacet_pdf; float roughness = getValue(mp_roughness.get(), intersection, TextureFilter::Linear); roughness = Clamp(roughness, .02f, 1.f); float specular = getValue(mp_specular.get(), intersection, TextureFilter::Linear); wh = GGX_SampleVisibleNormal(l_out, remapped_sample.u, remapped_sample.v, &microfacet_pdf, roughness * roughness); float normal_ref = Lerp(specular, .0f, .08f); float OdotH = l_out.dot(wh); float prob_spec = Fresnel_Schlick(OdotH, normal_ref); if (remapped_sample.w <= prob_spec) { l_in = -l_out + 2.f * l_out.dot(wh) * wh; *sample_types = ScatterType(BSDF_REFLECTION | BSDF_GLOSSY); } else { l_in = CosineSampleHemisphere(remapped_sample.u, remapped_sample.v); if (l_out.z < 0.f) l_in.z *= -1.f; *sample_types = ScatterType(BSDF_REFLECTION | BSDF_DIFFUSE); } } if (l_in.z <= 0.0f) { *pdf = 0.f; return Spectrum(0.f); } *v_in = intersection.localToWorld(l_in); *pdf = pdfInner(l_out, l_in, intersection, types); if (v_out.dot(intersection.gn) * v_in->dot(intersection.gn) > 0.f) types = ScatterType(types & ~BSDF_TRANSMISSION); else types = ScatterType(types & ~BSDF_REFLECTION); if (!matchesTypes(types)) { *pdf = 0.f; return Spectrum(0.f); } return evaluate(l_out, l_in, intersection, types); } }
6,172
C++
.cpp
139
40.654676
137
0.687385
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,925
RoughDielectric.cpp
g1n0st_AyaRay/src/BSDFs/RoughDielectric.cpp
#include <BSDFs/RoughDielectric.h> namespace Aya { float RoughDielectric::pdf(const Vector3 &v_out, const Vector3 &v_in, const SurfaceIntersection &intersection, ScatterType types) const { Vector3 l_out = intersection.worldToLocal(v_out); Vector3 l_in = intersection.worldToLocal(v_in); return pdfInner(l_out, l_in, intersection, types); } float RoughDielectric::pdfInner(const Vector3 &wo, const Vector3 &wi, const SurfaceIntersection &intersection, ScatterType types) const { bool sample_reflect = (types & reflect_scatter) == reflect_scatter; bool sample_refract = (types & refract_scatter) == refract_scatter; const float OdotN = CosTheta(wo); const float IdotN = CosTheta(wi); const float fac = OdotN * IdotN; if (fac == 0.f) return 0.f; bool reflect = fac > 0.f; bool entering = OdotN > 0.f; Vector3 wh; float dwh_dwi; if (reflect) { // reflect if (!sample_reflect) return 0.f; wh = (wo + wi).normalize(); dwh_dwi = 1.f / (4.f * wi.dot(wh)); } else { // refract if (!sample_refract) return 0.f; float etai = m_etai, etat = m_etat; if (!entering) std::swap(etai, etat); wh = -(etai * wo + etat * wi).normalize(); const float OdotH = wo.dot(wh); const float IdotH = wi.dot(wh); float sqrt_denom = etai * OdotH + etat * IdotH; dwh_dwi = (etat * etat * IdotH) / (sqrt_denom * sqrt_denom); } wh *= (CosTheta(wh) >= 0.f ? 1.f : -1.f); float roughness = getValue(m_roughness.get(), intersection, TextureFilter::Linear); roughness = Clamp(roughness, .02f, 1.f); roughness = roughness * roughness; float wh_prob = GGX_Pdf_VisibleNormal(wo * (CosTheta(wo) >= 0.f ? 1.f : -1.f), wh, roughness); if (sample_reflect && sample_refract) { float F = fresnelDielectric(wo.dot(wh), m_etai, m_etat); //F = 0.5f * F + 0.25f; wh_prob *= reflect ? F : 1.f - F; } assert(!std::isnan(wh_prob)); assert(!std::isnan(dwh_dwi)); return Abs(wh_prob * dwh_dwi); } Spectrum RoughDielectric::f(const Vector3 &v_out, const Vector3 &v_in, const SurfaceIntersection &intersection, ScatterType types) const { Vector3 l_out = intersection.worldToLocal(v_out); Vector3 l_in = intersection.worldToLocal(v_in); return getValue(mp_texture.get(), intersection) * evalInner(l_out, l_in, intersection, types); } float RoughDielectric::evalInner(const Vector3 &wo, const Vector3 &wi, const SurfaceIntersection &intersection, ScatterType types) const { bool sample_reflect = (types & reflect_scatter) == reflect_scatter; bool sample_refract = (types & refract_scatter) == refract_scatter; const float OdotN = CosTheta(wo); const float IdotN = CosTheta(wi); const float fac = OdotN * IdotN; if (fac == 0.f) return 0.f; bool reflect = fac > 0.f; bool entering = OdotN > 0.f; float etai = m_etai, etat = m_etat; if (!entering) std::swap(etai, etat); Vector3 wh; if (reflect) { // reflect if (!sample_reflect) return 0.f; wh = wo + wi; if (wh.length2() <= 1e-5f) return 0.f; wh.normalized(); } else { // refract if (!sample_refract) return 0.f; wh = -(etai * wo + etat * wi).normalize(); } wh *= (CosTheta(wh) >= 0.f ? 1.f : -1.f); float roughness = getValue(m_roughness.get(), intersection, TextureFilter::Linear); roughness = Clamp(roughness, .02f, 1.f); roughness = roughness * roughness; float D = GGX_D(wh, roughness); if (D == 0.f) return 0.f; float F = fresnelDielectric(wo.dot(wh), m_etai, m_etat); float G = GGX_G(wo, wi, wh, roughness); if (reflect) { return Abs(F * D * G / (4.f * CosTheta(wi) * CosTheta(wo))); } else { const float OdotH = wo.dot(wh); const float IdotH = wi.dot(wh); float sqrt_denom = etai * OdotH + etat * IdotH; float value = ((1.f - F) * D * G * etat * etat * OdotH * IdotH) / (sqrt_denom * sqrt_denom * OdotN * IdotN); // TODO: Fix solid angle compression when tracing radiance float factor = 1.0f; assert(!std::isnan(value)); return Abs(value * factor * factor); } } Spectrum RoughDielectric::sample_f(const Vector3 &v_out, const Sample &sample, const SurfaceIntersection &intersection, Vector3 *v_in, float *pdf, ScatterType types, ScatterType *sample_types) const { bool sample_reflect = (types & reflect_scatter) == reflect_scatter; bool sample_refract = (types & refract_scatter) == refract_scatter; if (!sample_reflect && !sample_refract) { *pdf = 0.f; return Spectrum(0.f); } bool sample_both = sample_reflect == sample_refract; const Vector3 wo = intersection.worldToLocal(v_out); float roughness = getValue(m_roughness.get(), intersection, TextureFilter::Linear); roughness = Clamp(roughness, .02f, 1.f); roughness = roughness * roughness; float microfacet_pdf; const Vector3 wh = GGX_SampleVisibleNormal(wo * (CosTheta(wo) >= 0.f ? 1.f : -1.f), sample.u, sample.v, &microfacet_pdf, roughness); if (microfacet_pdf == 0.f) return 0.f; float D = GGX_D(wh, roughness); if (D == 0.f) return 0.f; float F = fresnelDielectric(wo.dot(wh), m_etai, m_etat); float prob = F; Vector3 wi; if (sample.w <= prob && sample_both || (sample_reflect && !sample_both)) { // Sample reflection wi = -wo + Vector3(2.f * wo.dot(wh) * wh); if (CosTheta(wi) * CosTheta(wo) <= 0.f) { *pdf = 0.f; return Spectrum(0.f); } *v_in = intersection.localToWorld(wi); *pdf = !sample_both ? microfacet_pdf : microfacet_pdf * prob; float dwh_dwi = 1.f / (4.f * wi.dot(wh)); *pdf *= Abs(dwh_dwi); float G = GGX_G(wo, wi, wh, roughness); if (sample_types != nullptr) *sample_types = reflect_scatter; return getValue(mp_texture.get(), intersection) * Abs(F * D * G / (4.f * CosTheta(wi) * CosTheta(wo))); } else if (sample.w > prob && sample_both || (sample_refract && !sample_both)) { // Sample refraction float eta = m_etat / m_etai; float odoth = -wo.dot(wh); if (odoth < 0.f) eta = 1.f / eta; float idoth2 = 1.f - (1.f - odoth * odoth) * (eta * eta); if (idoth2 <= 0.f) { *pdf = 0.f; return Spectrum(0.f); } float sign = (odoth >= 0.f ? 1.f : -1.f); wi = wh * (-odoth * eta + sign * Sqrt(idoth2)) + (-wo) * eta; if (CosTheta(wi) * CosTheta(wo) >= 0.f) { *pdf = 0.f; return Spectrum(0.f); } *v_in = intersection.localToWorld(wi); *pdf = !sample_both ? microfacet_pdf : microfacet_pdf * (1.f - prob); bool entering = CosTheta(wo) > 0.f; float etai = m_etai, etat = m_etat; if (!entering) std::swap(etai, etat); const float OdotH = wo.dot(wh); const float IdotH = wi.dot(wh); float sqrt_denom = etai * OdotH + etat * IdotH; if (sqrt_denom == 0.f) { *pdf = 0.f; return Spectrum(0.f); } float dwh_dwi = (etat * etat * IdotH) / (sqrt_denom * sqrt_denom); *pdf *= Abs(dwh_dwi); if (sample_types != nullptr) *sample_types = refract_scatter; float G = GGX_G(wo, wi, wh, roughness); float value = ((1.f - F) * D * G * etat * etat * OdotH * IdotH) / (sqrt_denom * sqrt_denom * CosTheta(wo) * CosTheta(wi)); // TODO: Fix solid angle compression when tracing radiance float factor = 1.0f; return getValue(mp_texture.get(), intersection) * Abs(value * factor * factor); } return Spectrum(0.f); } }
7,293
C++
.cpp
189
34.761905
139
0.645765
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,926
SpotLight.h
g1n0st_AyaRay/src/Lights/SpotLight.h
#ifndef AYA_LIGHTS_SPOTLIGHT_H #define AYA_LIGHTS_SPOTLIGHT_H #include <Core/Light.h> namespace Aya { class SpotLight : public Light { private: Point3 m_pos; Spectrum m_intensity; Frame m_dirFrame; float m_cosTotal, m_cosFalloff; public: SpotLight(const Point3 &pos, const Spectrum &intens, const Vector3 &dir, const float total, const float falloff, const uint32_t sample_count = 1) : Light(sample_count), m_pos(pos), m_intensity(intens), m_dirFrame(dir.normalize()), m_cosTotal(std::cos(Radian(total))), m_cosFalloff(std::cos(Radian(falloff))) { } Spectrum illuminate(const Scatter &scatter, const Sample &light_sample, Vector3 *dir, VisibilityTester *tester, float *pdf, float *cos_at_light = nullptr, float *emit_pdf_w = nullptr) const override { const Point3 &pos = scatter.p; *dir = (m_pos - pos).normalize(); *pdf = (m_pos - pos).length2(); tester->setSegment(pos, m_pos); tester->setMedium(scatter.m_mediumInterface.getMedium(*dir, scatter.n)); if (cos_at_light) *cos_at_light = 1.f; if (emit_pdf_w) *emit_pdf_w = UniformConePDF(m_cosTotal); return m_intensity * falloff(-*dir); } Spectrum sample(const Sample &light_sample0, const Sample &light_sample1, Ray *ray, Normal3 *normal, float *pdf, float *direct_pdf = nullptr) const override { Vector3 dir = UniformSampleCone(light_sample0.u, light_sample0.v, m_cosTotal, m_dirFrame.U(), m_dirFrame.V(), m_dirFrame.W()); *ray = Ray(m_pos, dir); *normal = dir; *pdf = UniformConePDF(m_cosTotal); if (direct_pdf) *direct_pdf = 1.f; return m_intensity * falloff(ray->m_dir); } Spectrum emit(const Vector3 &dir, const Normal3 &normal = Normal3(0.f, 0.f, 0.f), float *pdf = nullptr, float *direct_pdf = nullptr) const override { return Spectrum(0.f); } float pdf(const Point3 &pos, const Vector3 &dir) const override { return 0.f; } bool isDelta() const override { return true; } bool isFinite() const override { return true; } private: float falloff(const Vector3 &w) const { Vector3 wl = m_dirFrame.worldToLocal(w).normalize(); float cos_theta = CosTheta(wl); if (cos_theta < m_cosTotal) return 0.f; if (cos_theta >= m_cosFalloff) return 1.f; float delta = (cos_theta - m_cosTotal) / (m_cosFalloff - m_cosTotal); return (delta * delta) * (delta * delta); } }; } #endif
2,443
C++
.h
83
25.746988
85
0.679165
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,927
DirectionalLight.h
g1n0st_AyaRay/src/Lights/DirectionalLight.h
#ifndef AYA_LIGHTS_DIRECTIONALLIGHT_H #define AYA_LIGHTS_DIRECTIONALLIGHT_H #include <Core/Light.h> #include <Core/Sampling.h> #include <Core/Scene.h> namespace Aya { class DirectionalLight : public Light { private: Spectrum m_intensity; Vector3 m_dir; Frame m_dirFrame; float m_coneCos; const Scene *mp_scene; public: DirectionalLight(const Vector3 &dir, const Spectrum &intens, const Scene *scene, const float cone_deg = 0.f, const uint32_t sample_count = 1) : Light(sample_count), m_intensity(intens), m_dir(-dir.normalize()), m_dirFrame(-dir.normalize()), mp_scene(scene), m_coneCos(std::cos(Radian(cone_deg))) { } Spectrum illuminate(const Scatter &scatter, const Sample &light_sample, Vector3 *dir, VisibilityTester *tester, float *pdf, float *cos_at_light = nullptr, float *emit_pdf_w = nullptr) const override { const Point3 &pos = scatter.p; *dir = UniformSampleCone(light_sample.u, light_sample.v, m_coneCos, m_dirFrame.U(), m_dirFrame.V(), m_dirFrame.W()); *pdf = UniformConePDF(m_coneCos); Point3 center; float radius; mp_scene->worldBound().boundingSphere(&center, &radius); tester->setSegment(pos, pos + 2.f * radius * (*dir)); tester->setMedium(scatter.m_mediumInterface.getMedium(*dir, scatter.n)); if (cos_at_light) *cos_at_light = dir->dot(m_dir); if (emit_pdf_w) *emit_pdf_w = ConcentricDiscPdf() / (radius * radius) * (*pdf); return m_intensity; } Spectrum sample(const Sample &light_sample0, const Sample &light_sample1, Ray *ray, Normal3 *normal, float *pdf, float *direct_pdf = nullptr) const override { float f1, f2; ConcentricSampleDisk(light_sample0.u, light_sample0.v, &f1, &f2); Point3 center; float radius; mp_scene->worldBound().boundingSphere(&center, &radius); Point3 origin = center + radius * (f1 * m_dirFrame.U() + f2 * m_dirFrame.V()); Vector3 dir = -UniformSampleCone(light_sample1.u, light_sample1.v, m_coneCos, m_dirFrame.U(), m_dirFrame.V(), m_dirFrame.W()); *ray = Ray(origin + radius * m_dir, dir); *normal = dir; float dir_pdf = UniformConePDF(m_coneCos); *pdf = ConcentricDiscPdf() / (radius * radius) * dir_pdf; if (direct_pdf) *direct_pdf = dir_pdf; return m_intensity; } Spectrum emit(const Vector3 &dir, const Normal3 &normal = Normal3(0.f, 0.f, 0.f), float *pdf = nullptr, float *direct_pdf = nullptr) const override { if (dir.dot(-m_dir) > m_coneCos) { float dir_pdf = UniformConePDF(m_coneCos); if (pdf) { Point3 center; float radius; mp_scene->worldBound().boundingSphere(&center, &radius); *pdf = ConcentricDiscPdf() / (radius * radius) * dir_pdf; } if (direct_pdf) *direct_pdf = dir_pdf; } return Spectrum(0.f); } float pdf(const Point3 &pos, const Vector3 &dir) const override { if (dir.dot(-m_dir) > m_coneCos) return UniformConePDF(m_coneCos); return 0.f; } bool isEnvironmentLight() const override { return true; } bool isDelta() const override { return m_coneCos == 1.f; } bool isFinite() const override { return false; } }; } #endif
3,216
C++
.h
109
25.541284
75
0.671951
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,928
PointLight.h
g1n0st_AyaRay/src/Lights/PointLight.h
#ifndef AYA_LIGHTS_POINTLIGHT_H #define AYA_LIGHTS_POINTLIGHT_H #include <Core/Light.h> #include <Core/Sampling.h> namespace Aya { class PointLight : public Light { private: Point3 m_pos; Spectrum m_intensity; public: PointLight(const Point3 &pos, const Spectrum &intens, const uint32_t sample_count = 1) : Light(sample_count), m_pos(pos), m_intensity(intens) { } Spectrum illuminate(const Scatter &scatter, const Sample &light_sample, Vector3 *dir, VisibilityTester *tester, float *pdf, float *cos_at_light = nullptr, float *emit_pdf_w = nullptr) const override { const Point3 &pos = scatter.p; *dir = (m_pos - pos).normalize(); *pdf = (m_pos - pos).length2(); tester->setSegment(pos, m_pos); tester->setMedium(scatter.m_mediumInterface.getMedium(*dir, scatter.n)); if (cos_at_light) *cos_at_light = 1.f; if (emit_pdf_w) *emit_pdf_w = UniformSpherePDF(); return m_intensity; } Spectrum sample(const Sample &light_sample0, const Sample &light_sample1, Ray *ray, Normal3 *normal, float *pdf, float *direct_pdf = nullptr) const override { Vector3 dir = UniformSampleSphere(light_sample0.u, light_sample0.v); *ray = Ray(m_pos, dir); *normal = dir; *pdf = UniformSpherePDF(); if (direct_pdf) *direct_pdf = 1.f; return m_intensity; } Spectrum emit(const Vector3 &dir, const Normal3 &normal = Normal3(0.f, 0.f, 0.f), float *pdf = nullptr, float *direct_pdf = nullptr) const override { return Spectrum(0.f); } float pdf(const Point3 &pos, const Vector3 &dir) const override { return 0.f; } bool isDelta() const override { return true; } bool isFinite() const override { return true; } }; } #endif
1,754
C++
.h
65
23.461538
75
0.685936
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,931
EmbreeAccelerator.h
g1n0st_AyaRay/src/Accelerators/EmbreeAccelerator.h
#ifndef AYA_ACCELERATOR_EMBREEACCLERATOR_H #define AYA_ACCELERATOR_EMBREEACCLERATOR_H #include <Core/Accelerator.h> #if defined AYA_USE_EMBREE #if defined (AYA_USE_EMBREE_STATIC_LIB) #define EMBREE_STATIC_LIB #endif #if (AYA_USE_EMBREE == 3) #include <embree3/rtcore.h> #elif (AYA_USE_EMBREE == 2) #include <embree2/rtcore_ray.h> #include <embree2/rtcore.h> #else #error "Wrong Intel Embree Version!" #endif namespace Aya { class EmbreeAccel : public Accelerator { private: RTCScene m_rtcScene = nullptr; RTCDevice m_device = nullptr; public: EmbreeAccel() {} ~EmbreeAccel() override; void construct(const std::vector<Primitive*> &prims) override; BBox worldBound() const override; bool intersect(const Ray &ray, Intersection *si) const override; bool occluded(const Ray &ray) const override; private: inline RTCRay toRTCRay(const Ray &ray) const { #if (AYA_USE_EMBREE == 3) RTCRay rtc_ray; rtc_ray.org_x = ray.m_ori.x; rtc_ray.org_y = ray.m_ori.y; rtc_ray.org_z = ray.m_ori.z; rtc_ray.dir_x = ray.m_dir.x; rtc_ray.dir_y = ray.m_dir.y; rtc_ray.dir_z = ray.m_dir.z; rtc_ray.tnear = ray.m_mint; rtc_ray.tfar = ray.m_maxt; rtc_ray.flags = 0; #elif (AYA_USE_EMBREE == 2) RTCRay rtc_ray; rtc_ray.org[0] = ray.m_ori.x; rtc_ray.org[1] = ray.m_ori.y; rtc_ray.org[2] = ray.m_ori.z; rtc_ray.dir[0] = ray.m_dir.x; rtc_ray.dir[1] = ray.m_dir.y; rtc_ray.dir[2] = ray.m_dir.z; rtc_ray.tnear = ray.m_mint; rtc_ray.tfar = ray.m_maxt; rtc_ray.time = 0.f; rtc_ray.geomID = RTC_INVALID_GEOMETRY_ID; rtc_ray.primID = RTC_INVALID_GEOMETRY_ID; rtc_ray.instID = RTC_INVALID_GEOMETRY_ID; #endif return rtc_ray; } #if (AYA_USE_EMBREE == 3) static void alphaTest(const struct RTCFilterFunctionNArguments* args) { Primitive *prim = (Primitive*)args->geometryUserPtr; uint32_t prim_id = RTCHitN_primID(args->hit, 1, 0); float u = RTCHitN_u(args->hit, 1, 0); float v = RTCHitN_v(args->hit, 1, 0); if (prim->getBSDF(prim_id)->getTexture()->hasAlpha()) { const TriangleMesh *mesh = prim->getMesh(); const Vector2f &uv1 = mesh->getUVAt(3 * prim_id + 0); const Vector2f &uv2 = mesh->getUVAt(3 * prim_id + 1); const Vector2f &uv3 = mesh->getUVAt(3 * prim_id + 2); const Vector2f uv = (1.0f - u - v) * uv1 + u * uv2 + v * uv3; if (!prim->getBSDF(prim_id)->getTexture()->alphaTest(uv)) RTCHitN_geomID(args->hit, 1, 0) = RTC_INVALID_GEOMETRY_ID; // reject hit } } #elif (AYA_USE_EMBREE == 2) static void alphaTest(void *user_ptr, RTCRay& ray) { Primitive *prim = (Primitive*)user_ptr; if (prim->getBSDF(ray.primID)->getTexture()->hasAlpha()) { const TriangleMesh *mesh = prim->getMesh(); const Vector2f &uv1 = mesh->getUVAt(3 * ray.primID + 0); const Vector2f &uv2 = mesh->getUVAt(3 * ray.primID + 1); const Vector2f &uv3 = mesh->getUVAt(3 * ray.primID + 2); const Vector2f uv = (1.0f - ray.u - ray.v) * uv1 + ray.u * uv2 + ray.v * uv3; if (!prim->getBSDF(ray.primID)->getTexture()->alphaTest(uv)) ray.geomID = RTC_INVALID_GEOMETRY_ID; // reject hit } } #endif }; #endif } #endif
3,170
C++
.h
95
29.978947
77
0.665904
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,938
ObjMesh.h
g1n0st_AyaRay/src/Loaders/ObjMesh.h
#ifndef AYA_LOADERS_OBJMESH_H #define AYA_LOADERS_OBJMESH_H #include <Math/Vector2.h> #include <Math/Vector3.h> #include <Core/Spectrum.h> #include <Core/Memory.h> #include <cstring> #include <string> #include <vector> #include <cstdio> #include <functional> #define AYA_MAX_PATH 1024 namespace Aya { struct MeshVertex { Point3 p; Normal3 n; Vector2f uv; MeshVertex() { p = Point3(0.f); n = Normal3(0.f); uv = Vector2f(0.f); } MeshVertex(const Point3 &pp, const Normal3 &nn, const float uu, const float vv) : p(pp), n(nn), uv(uu, vv) {} friend bool operator == (const MeshVertex &a, const MeshVertex &b) { return (a.p == b.p) && (a.n == b.n) && (a.uv == b.uv); } }; struct MeshFace { int idx[3]; int smoothing_group; MeshFace() = default; MeshFace(const int idx0, const int idx1, const int idx2, const int sg) : smoothing_group(sg) { idx[0] = idx0; idx[1] = idx1; idx[2] = idx2; } }; struct Cache { uint32_t idx; Cache *next; }; struct ObjMaterial { char name[AYA_MAX_PATH]; // newmtl name char map_Kd[AYA_MAX_PATH]; // texture map char map_Ks[AYA_MAX_PATH]; // specular map char map_Bump[AYA_MAX_PATH]; // bump map RGBSpectrum Ka; // ambient color RGBSpectrum Ke; // missive color RGBSpectrum Kd; // diffuse color RGBSpectrum Ks; // specular colore RGBSpectrum Tf; // transmission filter float Ns; // refractive index float Ni; // reflection index int illum; // illumination // 0 Color on and Ambient off // 1 Color on and Ambient on // 2 Highlight on // 3 Reflection on and Ray trace on // 4 Transparency: Glass on // Reflection : Ray trace on // 5 Reflection : Fresnel on and Ray trace on // 6 Transparency : Refraction on // Reflection : Fresnel off and Ray trace on // 7 Transparency : Refraction on // Reflection : Fresnel on and Ray trace on // 8 Reflection on and Ray trace off // 9 Transparency : Glass on Reflection : Ray trace off // 10 Casts shadows onto invisible surfaces ObjMaterial(const char *_name = "") : Ka(0.f), Ke(0.f), Kd(0.85f), Ks(0.f), Tf(0.f), Ni(0.f), Ns(0.f), illum(0) { strcpy_s(name, AYA_MAX_PATH, _name); std::memset(map_Kd, 0, AYA_MAX_PATH); std::memset(map_Bump, 0, AYA_MAX_PATH); std::memset(map_Ks, 0, AYA_MAX_PATH); } inline bool operator == (const ObjMaterial &rhs) const { return 0 == strcmp(name, rhs.name); } }; class ObjMesh { protected: uint32_t m_vertexCount, m_triangleCount; std::vector<MeshVertex> m_vertices; std::vector<uint32_t> m_indices; std::vector<MeshFace> m_faces; std::vector<Cache*> m_caches; std::vector<ObjMaterial> m_materials; std::vector<uint32_t> m_materialIdx; std::vector<uint32_t> m_subsetStartIdx; std::vector<uint32_t> m_subsetMtlIdx; uint32_t m_subsetCount; bool m_normaled; bool m_textured; public: ObjMesh() : m_vertexCount(0), m_triangleCount(0), m_subsetCount(0), m_normaled(false), m_textured(false) {} bool loadObj(const char *path, const bool force_compute_normal = false, const bool left_handed = true); void loadMtl(const char *path); uint32_t addVertex(uint32_t hash, const MeshVertex *vertex); void computeVertexNormals(); inline const uint32_t* getIndexAt(int num) const { return m_indices.data() + 3 * num; } inline const MeshFace& getFaceAt(int idx) const { return m_faces[idx]; } inline const std::vector<MeshFace>& getFacesBuff() const { return m_faces; } inline const MeshVertex& getVertexAt(int idx) const { return m_vertices[idx]; } inline const std::vector<MeshVertex>& getVerticesBuff() const { return m_vertices; } inline uint32_t getVertexCount() const { return m_vertexCount; } inline uint32_t getTriangleCount() const { return m_triangleCount; } inline bool isNormaled() const { return m_normaled; } inline bool isTextured() const { return m_textured; } inline const std::vector<ObjMaterial>& getMaterialBuff() const { return m_materials; } inline const std::vector<uint32_t>& getMaterialIdxBuff() const { return m_materialIdx; } inline uint32_t getMaterialIdx(int idx) const { return m_materialIdx[idx]; } inline const uint32_t getSubsetCount() const { return m_subsetCount; } inline const uint32_t getSubsetStartIdx(int idx) const { return m_subsetStartIdx[idx]; } inline const uint32_t getSubsetMtlIdx(int idx) const { return m_subsetMtlIdx[idx]; } private: void parserFramework(const char *filename, std::function<void(char*, char *)> callback); }; } #endif
4,639
C++
.h
163
25.343558
105
0.689183
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,940
MultiplexedMLT.h
g1n0st_AyaRay/src/Integrators/MultiplexedMLT.h
#ifndef AYA_INTEGRATORS_MULTIPLEXMLT_H #define AYA_INTEGRATORS_MULTIPLEXMLT_H #include <Core/Integrator.h> #include <thread> #include <mutex> namespace Aya { class MetropolisSampler : public Sampler { private: struct PrimarySample { float value = 0.f; uint64_t modify = 0u; // When did the sample last mutate // If mutation rejected, use backup infomation to restore float backup_value = 0.f; uint64_t backup_modify = 0u; void backup() { backup_value = value; backup_modify = modify; } void restore() { value = backup_value; modify = backup_modify; } }; private: std::vector<PrimarySample> m_samples; const float m_sigma; // Parameter used to control the pace of mutation const float m_largeStepProb; int m_sampleIdx; int m_streamIdx; const int stream_count = 3; uint64_t m_largeStepTime = 0u; // Number of accepted mutations after last large step uint64_t m_time = 0u; // Current number of accepted mutations bool m_largeStep = true; RNG m_rng; public: MetropolisSampler(const float sigma, const float large_step_prob, int sample_idx, int stream_idx, uint64_t large_step_time, uint64_t time, bool large_step, RNG rng, std::vector<PrimarySample> samples) : m_sigma(sigma), m_largeStepProb(large_step_prob), m_rng(rng), m_sampleIdx(sample_idx), m_streamIdx(stream_idx), m_largeStepTime(large_step_time), m_time(time), m_largeStep(large_step), m_samples(samples) { } MetropolisSampler(const float sigma, const float large_step_prob, const int seed) : m_sigma(sigma), m_largeStepProb(large_step_prob), m_rng(seed) { } float get1D() override; Vector2f get2D() override; Sample getSample() override; void generateSamples(const int pixel_x, const int pixel_y, CameraSample *samples, RNG &rng) override; std::unique_ptr<Sampler> clone(const int seed) const override; std::unique_ptr<Sampler> deepClone() const override; void startIteration(); void accept(); void reject(); void mutate(const int idx); void startStream(const int idx) { assert(idx < stream_count); m_streamIdx = idx; m_sampleIdx = 0; } private: int getNextIndex() { return m_streamIdx + stream_count * m_sampleIdx++; } }; class MultiplexMLTIntegrator : public Integrator { private: const Camera *mp_camera; Film *mp_film; uint32_t m_maxDepth; int m_numBootstrap; int m_numChains; float m_sigma; float m_largeStepProb; mutable std::mutex m_mutex; public: MultiplexMLTIntegrator(const TaskSynchronizer &task, const uint32_t &spp, uint32_t max_depth, const Camera *camera, Film *film, int num_bootstrap = 1 << 17, int num_chains = 1 << 11, float sigma = .01f, float large_step_prob = .3f) : Integrator(task, spp), m_maxDepth(max_depth), mp_camera(camera), mp_film(film), m_numBootstrap(num_bootstrap), m_numChains(num_chains), m_sigma(sigma), m_largeStepProb(large_step_prob) { } ~MultiplexMLTIntegrator() = default; void render(const Scene *scene, const Camera *camera, Sampler *sampler, Film *film) override; public: Spectrum evalSample(const Scene *scene, MetropolisSampler *sampler, const int connect_depth, Vector2f *raster_pos, RNG &rng, MemoryPool &memory) const; }; } #endif
3,288
C++
.h
97
30.525773
106
0.720732
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,941
GuidedPathTracer.h
g1n0st_AyaRay/src/Integrators/GuidedPathTracer.h
#ifndef AYA_INTEGRATORS_GUIDEDPATHTRACER_H #define AYA_INTEGRATORS_GUIDEDPATHTRACER_H #include <Core/Integrator.h> #include <array> #include <atomic> #include <stack> #include <chrono> #include <fstream> #include <functional> #include <iomanip> #include <sstream> namespace Aya { enum class SampleCombination { Discard, DiscardWithAutomaticBudget, InverseVariance, }; enum class BsdfSamplingFractionLoss { None, KL, Variance, }; enum class SpatialFilter { Nearest, StochasticBox, Box, }; enum class DirectionalFilter { Nearest, Box, }; static void addToAtomicFloat(std::atomic<float> &var, float val) { auto current = var.load(); while (!var.compare_exchange_weak(current, current + val)); } inline float logistic(float x) { return 1.f / (1.f + std::expf(-x)); } // Implements the stochastic-gradient-based Adam optimizer [Kingma and Ba 2014] class AdamOptimizer { private: struct State { int iter = { 0 }; float first_moment = { 0.f }; float second_moment = { 0.f }; float variable = { 0.f }; float batch_accumulation = { 0.f }; float batch_gradient = { 0.f }; } m_state; struct Hyperparameters { float learning_rate; int batch_size; float epsilon; float beta1; float beta2; } m_hparams; public: AdamOptimizer(float learning_rate, int batch_size = 1, float epsilon = 1e-08f, float beta1 = 0.9f, float beta2 = 0.999f) { m_hparams = { learning_rate ,batch_size , epsilon ,beta1 ,beta2 }; } AdamOptimizer& operator = (const AdamOptimizer &arg) { m_state = arg.m_state; m_hparams = arg.m_hparams; return *this; } AdamOptimizer(const AdamOptimizer &arg) { *this = arg; } void append(float gradient, float statistical_weight) { m_state.batch_gradient += gradient * statistical_weight; m_state.batch_accumulation += statistical_weight; if (m_state.batch_accumulation > m_hparams.batch_size) { step(m_state.batch_gradient / m_state.batch_accumulation); m_state.batch_gradient = 0.f; m_state.batch_accumulation = 0.f; } } void step(float gradient) { ++m_state.iter; ++m_state.iter; float actual_learning_rate = m_hparams.learning_rate * std::sqrtf(1.f - std::powf(m_hparams.beta2, m_state.iter)) / (1.f - std::powf(m_hparams.beta1, m_state.iter)); m_state.first_moment = m_hparams.beta1 * m_state.first_moment + (1.f - m_hparams.beta1) * gradient; m_state.second_moment = m_hparams.beta2 * m_state.second_moment + (1.f - m_hparams.beta2) * gradient * gradient; m_state.variable -= actual_learning_rate * m_state.first_moment / (std::sqrtf(m_state.second_moment) + m_hparams.epsilon); // Clamp the variable to the range [-20, 20] as a safeguard to avoid numerical instability: // since the sigmoid involves the exponential of the variable, value of -20 or 20 already yield // in *extremely* small and large results that are pretty much never necessary in practice. m_state.variable = Clamp(m_state.variable, -20.f, 20.f); } float variable() const { return m_state.variable; } }; class QuadTreeNode { private: std::array<std::atomic<float>, 4> m_sum; std::array<uint16_t, 4> m_children; public: QuadTreeNode() { m_children = {}; for (size_t i = 0; i < m_sum.size(); ++i) { m_sum[i].store(0.f, std::memory_order::memory_order_relaxed); } } void setSum(int idx, float val) { m_sum[idx].store(val, std::memory_order::memory_order_relaxed); } void setSum(float val) { for (int i = 0; i < 4; ++i) { setSum(i, val); } } float sum(int idx) const { return m_sum[idx].load(std::memory_order::memory_order_relaxed); } QuadTreeNode(const QuadTreeNode &arg) { for (int i = 0; i < 4; i++) { setSum(i, arg.sum(i)); m_children[i] = arg.m_children[i]; } } QuadTreeNode& operator = (const QuadTreeNode &arg) { for (int i = 0; i < 4; i++) { setSum(i, arg.sum(i)); m_children[i] = arg.m_children[i]; } return *this; } void setChild(int idx, uint16_t val) { m_children[idx] = val; } uint16_t child(int idx) const { return m_children[idx]; } int childIndex(Point2f &p) const { int res = { 0 }; for (int i = 0; i < 2; ++i) { if (p[i] < .5f) { p[i] *= 2.f; } else { p[i] = (p[i] - .5f) * 2.f; res |= 1 << i; } } return res; } bool isLeaf(int idx) const { return child(idx) == 0; } // Evaluates the directional irradiance *sum density* (i.e. sum / area) at a given location p. // To obtain radiance, the sum density (result of this function) must be divided // by the total statistical weight of the estimates that were summed up. float eval(Point2f &p, const std::vector<QuadTreeNode> &nodes) const { assert(p.x >= 0.f && p.x <= 1.f && p.y >= 0.f && p.y <= 1.f); const int idx = childIndex(p); if (isLeaf(idx)) { return 4.f * sum(idx); } else { return 4.f * nodes[child(idx)].eval(p, nodes); } } float pdf(Point2f &p, const std::vector<QuadTreeNode> &nodes) const { assert(p.x >= 0.f && p.x <= 1.f && p.y >= 0.f && p.y <= 1.f); const int idx = childIndex(p); if (!(sum(idx) > 0.f)) { return 0.f; } const float factor = 4.f * sum(idx) / (sum(0) + sum(1) + sum(2) + sum(3)); if (isLeaf(idx)) { return factor; } else { return factor * nodes[child(idx)].pdf(p, nodes); } } int depthAt(Point2f &p, const std::vector<QuadTreeNode> &nodes) const { assert(p.x >= 0.f && p.x <= 1.f && p.y >= 0.f && p.y <= 1.f); const int idx = childIndex(p); if (isLeaf(idx)) { return 1; } else { return nodes[child(idx)].depthAt(p, nodes) + 1; } } Point2f sample(Sampler *sampler, const std::vector<QuadTreeNode> &nodes) const { int idx = { 0 }; float top_left = sum(0); float top_right = sum(1); float partial = top_left + sum(2); float total = partial + top_right + sum(3); // Should only happen when there are numerical instabilities. if (!(total > 0.f)) { return sampler->get2D(); } float boundary = partial / total; Point2f origin = Point2f{ 0.f, 0.f }; float sample = sampler->get1D(); if (sample < boundary) { assert(partial > 0.f); sample /= boundary; boundary = top_left / partial; } else { partial = total - partial; assert(partial > 0.f); origin.x = .5f; sample = (sample - boundary) / (1.f - boundary); boundary = top_right / partial; idx |= 1 << 0; } if (sample < boundary) { sample /= boundary; } else { origin.y = .5f; sample = (sample - boundary) / (1.f - boundary); idx |= 1 << 1; } if (isLeaf(idx)) { return origin + .5f * sampler->get2D(); } else { return origin + .5f * nodes[child(idx)].sample(sampler, nodes); } } void record(Point2f &p, float irradiance, std::vector<QuadTreeNode> &nodes) { assert(p.x >= 0.f && p.x <= 1.f && p.y >= 0.f && p.y <= 1.f); const int idx = childIndex(p); if (isLeaf(idx)) { addToAtomicFloat(m_sum[idx], irradiance); } else { nodes[child(idx)].record(p, irradiance, nodes); } } float computeOverlappingArea(const Point2f &min1, const Point2f &max1, const Point2f &min2, const Point2f &max2) const { float lengths[2]; for (int i = 0; i < 2; i++) { lengths[i] = Max(Min(max1[i], max2[i]) - Max(min1[i], min2[i]), 0.f); } return lengths[0] * lengths[1]; } void record(const Point2f &origin, float size, Point2f node_origin, float node_size, float value, std::vector<QuadTreeNode> &nodes) { float child_size = node_size / 2.f; for (int i = 0; i < 4; i++) { Point2f child_origin = node_origin; if (i & 1) { child_origin[0] += child_size; } if (i & 2) { child_origin[1] += child_size; } float w = computeOverlappingArea(origin, origin + Point2f(size), child_origin, child_origin + Point2f(child_size)); if (w > 0.f) { if (isLeaf(i)) { addToAtomicFloat(m_sum[i], value * w); } else { nodes[child(i)].record(origin, size, child_origin, child_size, value, nodes); } } } } // Ensure that each quadtree node's sum of irradiance estimates // equals that of all its children. void build(std::vector<QuadTreeNode>& nodes) { for (int i = 0; i < 4; ++i) { // During sampling, all irradiance estimates are accumulated in // the leaves, so the leaves are built by definition. if (isLeaf(i)) { continue; } QuadTreeNode& c = nodes[child(i)]; // Recursively build each child such that their sum becomes valid... c.build(nodes); // ...then sum up the children's sums. float sum = 0; for (int j = 0; j < 4; ++j) { sum += c.sum(j); } setSum(i, sum); } } }; class DTree { private: std::vector<QuadTreeNode> m_nodes; struct Atomic { std::atomic<float> sum; std::atomic<float> statistical_weight; Atomic() { sum.store(0.f, std::memory_order::memory_order_relaxed); statistical_weight.store(0.f, std::memory_order::memory_order_relaxed); } Atomic(const Atomic &arg) { *this = arg; } Atomic& operator = (const Atomic &arg) { sum.store(arg.sum.load(std::memory_order::memory_order_relaxed), std::memory_order::memory_order_relaxed); statistical_weight.store(arg.statistical_weight.load(std::memory_order::memory_order_relaxed), std::memory_order::memory_order_relaxed); return *this; } } m_atomic; int m_maxDepth; public: DTree() { m_atomic.sum.store(0.f, std::memory_order::memory_order_relaxed); m_atomic.statistical_weight.store(0.f, std::memory_order::memory_order_relaxed); m_maxDepth = { 0 }; m_nodes.emplace_back(); m_nodes.front().setSum(0.f); } const QuadTreeNode& node(size_t i) const { return m_nodes[i]; } float mean() const { if (m_atomic.statistical_weight == 0.f) { return 0.f; } const float factor = 1.f / (float(M_PI) * 4.f * m_atomic.statistical_weight); return factor * m_atomic.sum; } void recordIrradiance(Point2f p, float irradiance, float statistical_weight, DirectionalFilter directional_filter) { if (std::isfinite(statistical_weight) && statistical_weight > 0.f) { addToAtomicFloat(m_atomic.statistical_weight, statistical_weight); if (std::isfinite(irradiance) && irradiance > 0.f) { if (directional_filter == DirectionalFilter::Nearest) { m_nodes[0].record(p, irradiance * statistical_weight, m_nodes); } else { int depth = depthAt(p); float size = std::powf(.5f, depth); Point2f origin = p; origin.x -= size / 2.f; origin.y -= size / 2.f; m_nodes[0].record(origin, size, Point2f(0.f), 1.f, irradiance * statistical_weight / (size * size), m_nodes); } } } } float pdf(Point2f p) const { if (!(mean() > 0.f)) { return 1.f / (4.f * float(M_PI)); } return m_nodes[0].pdf(p, m_nodes) / (4.f * float(M_PI)); } int depthAt(Point2f p) const { return m_nodes[0].depthAt(p, m_nodes); } int depth() const { return m_maxDepth; } Point2f sample(Sampler *sampler) const { if (!(mean() > 0.f)) { return sampler->get2D(); } Point2f res = m_nodes[0].sample(sampler, m_nodes); res.x = Clamp(res.x, 0.f, 1.f); res.y = Clamp(res.y, 0.f, 1.f); return res; } size_t numNodes() const { return m_nodes.size(); } float statisticalWeight() const { return m_atomic.statistical_weight; } void setStatisticalWeight(float statistical_weight) { m_atomic.statistical_weight = statistical_weight; } void reset(const DTree &previous_DTree, int maxdepth, float subdivision_threshold) { m_atomic = Atomic{}; m_maxDepth = 0; m_nodes.clear(); m_nodes.emplace_back(); struct StackNode { size_t node_index; size_t other_index; const DTree *other_DTree; int depth; }; std::stack<StackNode> node_indices; node_indices.push({ 0, 0, &previous_DTree, 1 }); const float total = previous_DTree.m_atomic.sum; // Create the topology of the new DTree to be the refined version // of the previous DTree. Subdivision is recursive if enough energy is there. while (!node_indices.empty()) { StackNode node = node_indices.top(); node_indices.pop(); m_maxDepth = Max(m_maxDepth, node.depth); for (int i = 0; i < 4; i++) { const QuadTreeNode &other_node = node.other_DTree->m_nodes[node.other_index]; const float fraction = total > 0.f ? (other_node.sum(i) / total) : std::powf(.25f, node.depth); assert(fraction <= 1.f + float(AYA_EPSILON)); if (node.depth < maxdepth && fraction > subdivision_threshold) { if (!other_node.isLeaf(i)) { assert(node.other_DTree == &previous_DTree); node_indices.push({ m_nodes.size(), other_node.child(i), &previous_DTree, node.depth + 1 }); } else { node_indices.push({ m_nodes.size(), m_nodes.size(), this, node.depth + 1 }); } m_nodes[node.node_index].setChild(i, static_cast<uint16_t>(m_nodes.size())); m_nodes.emplace_back(); m_nodes.back().setSum(other_node.sum(i) / 4.f); if (m_nodes.size() > (std::numeric_limits<uint16_t>::max)()) { std::runtime_error("DTreeWrapper hit maximum children count."); node_indices = std::stack<StackNode>(); break; } } } } // Uncomment once memory becomes an issue. //m_nodes.shrink_to_fit(); for (auto& node : m_nodes) { node.setSum(0.f); } } size_t approxMemoryFootprint() const { return m_nodes.capacity() * sizeof(QuadTreeNode) + sizeof(*this); } void build() { auto& root = m_nodes[0]; // Build the quadtree recursively, starting from its root. root.build(m_nodes); // Ensure that the overall sum of irradiance estimates equals // the sum of irradiance estimates found in the quadtree. float sum = 0.f; for (int i = 0; i < 4; ++i) { sum += root.sum(i); } m_atomic.sum.store(sum); } }; struct DTreeRecord { Vector3 d; float radiance, product; float wo_pdf, bsdf_pdf, DTree_pdf; float statistical_weight; bool is_delta; }; struct DTreeWrapper { private: DTree building; DTree sampling; AdamOptimizer bsdfSamplingFractionOptimizer{ 0.01f }; class SpinLock { private: std::atomic_flag m_mutex; public: SpinLock() { m_mutex.clear(std::memory_order::memory_order_release); } SpinLock(const SpinLock &other) { m_mutex.clear(std::memory_order::memory_order_release); } SpinLock& operator = (const SpinLock &other) { return *this; } void lock() { while (m_mutex.test_and_set(std::memory_order::memory_order_acquire)) {} } void unlock() { m_mutex.clear(std::memory_order::memory_order_release); } } m_lock; public: DTreeWrapper() { } void record(const DTreeRecord &rec, DirectionalFilter directional_filter, BsdfSamplingFractionLoss sampling_loss) { if (!rec.is_delta) { float irradiance = rec.radiance / rec.wo_pdf; building.recordIrradiance(dirToCanonical(rec.d), irradiance, rec.statistical_weight, directional_filter); } if (sampling_loss != BsdfSamplingFractionLoss::None && rec.product > 0.f) { } } static Vector3 canonicalToDir(const Point2f &p) { const float cos_theta = 2.f * p.x - 1.f; const float phi = 2.f * float(M_PI) * p.y; const float sin_theta = std::sqrtf(1.f - cos_theta * cos_theta); const float sin_phi = std::sinf(phi); const float cos_phi = std::cosf(phi); return Vector3(sin_theta * cos_phi, sin_theta * sin_phi, cos_theta); } static Point2f dirToCanonical(const Vector3 &d) { if (!std::isfinite(d.x) || !std::isfinite(d.y) || !std::isfinite(d.z)) { return Point2f(0.f); } const float cos_theta = Clamp(d.z, -1.f, 1.f); float phi = std::atan2f(d.y, d.x); while (phi < 0.f) phi += 2.f * float(M_PI); return Point2f((cos_theta + 1.f) / 2.f, phi / (2.f * float(M_PI))); } void build() { building.build(); sampling = building; } void reset(int maxdepth, float subdivision_threshold) { building.reset(sampling, maxdepth, subdivision_threshold); } Vector3 sample(Sampler *sampler) const { return canonicalToDir(sampling.sample(sampler)); } float pdf(const Vector3 &dir) const { return sampling.pdf(dirToCanonical(dir)); } int depth() const { return sampling.depth(); } size_t numNodes() const { return sampling.numNodes(); } float meanRadiance() const { return sampling.mean(); } float statisticalWeight() const { return sampling.statisticalWeight(); } float statisticalWeightBuilding() const { return building.statisticalWeight(); } void setStatisticalWeightBuilding(float statistical_weight) { building.setStatisticalWeight(statistical_weight); } size_t approxMemoryFootprint() const { return building.approxMemoryFootprint() + sampling.approxMemoryFootprint(); } inline float bsdfSamplingFraction(float variable) const { return logistic(variable); } inline float dBsdfSamplingFraction_dVariable(float variable) const { float fraction = bsdfSamplingFraction(variable); return fraction * (1.f - fraction); } inline float bsdfSamplingFraction() const { return bsdfSamplingFraction(bsdfSamplingFractionOptimizer.variable()); } void optimizeBsdfSamplingFraction(const DTreeRecord& rec, float ratio_power) { m_lock.lock(); // GRADIENT COMPUTATION float variable = bsdfSamplingFractionOptimizer.variable(); float sampling_fraction = bsdfSamplingFraction(variable); // Loss gradient w.r.t. sampling fraction float mix_pdf = sampling_fraction * rec.bsdf_pdf + (1.f - sampling_fraction) * rec.DTree_pdf; float ratio = std::powf(rec.product / mix_pdf, ratio_power); float dLoss_dSamplingFraction = -ratio / rec.wo_pdf * (rec.bsdf_pdf - rec.DTree_pdf); // Chain rule to get loss gradient w.r.t. trainable variable float dLoss_dVariable = dLoss_dSamplingFraction * dBsdfSamplingFraction_dVariable(variable); // We want some regularization such that our parameter does not become too big. // We use l2 regularization, resulting in the following linear gradient. float l2Reg_gradient = .01f * variable; float loss_gradient = l2Reg_gradient + dLoss_dVariable; // ADAM GRADIENT DESCENT bsdfSamplingFractionOptimizer.append(loss_gradient, rec.statistical_weight); m_lock.unlock(); } }; struct STreeNode { bool is_leaf; DTreeWrapper dTree; int axis; std::array<uint32_t, 2> children; STreeNode() { children = {}; is_leaf = true; axis = 0; } int childIndex(Point3 &p) const { if (p[axis] < .5f) { p[axis] *= 2.f; return 0; } else { p[axis] = (p[axis] - .5f) * 2.f; return 1; } } int nodeIndex(Point3 &p) const { return children[childIndex(p)]; } DTreeWrapper* dTreeWrapper(Point3 &p, Vector3 &size, std::vector<STreeNode> &nodes) { assert(p[axis] >= 0.f && p[axis] <= 1.f); if (is_leaf) { return &dTree; } else { size[axis] /= 2.f; return nodes[nodeIndex(p)].dTreeWrapper(p, size, nodes); } } const DTreeWrapper* dTreeWrapper() const { return &dTree; } int depth(Point3 &p, const std::vector<STreeNode> &nodes) const { assert(p[axis] >= 0.f && p[axis] <= 1.f); if (is_leaf) { return 1; } else { return 1 + nodes[nodeIndex(p)].depth(p, nodes); } } int depth(const std::vector<STreeNode> &nodes) const { int result = 1; if (!is_leaf) { for (auto c : children) { result = Max(result, 1 + nodes[c].depth(nodes)); } } return result; } void forEachLeaf( std::function<void(const DTreeWrapper *, const Point3 &, const Vector3 &)> func, Point3 p, Vector3 size, const std::vector<STreeNode> &nodes) const { if (is_leaf) { func(&dTree, p, size); } else { size[axis] /= 2.f; for (int i = 0; i < 2; ++i) { Point3 child_p = p; if (i == 1) { child_p[axis] += size[axis]; } nodes[children[i]].forEachLeaf(func, child_p, size, nodes); } } } float computeOverlappingVolume(const Point3 &min1, const Point3 &max1, const Point3 &min2, const Point3 &max2) { float lengths[3]; for (int i = 0; i < 3; ++i) { lengths[i] = Max(Min(max1[i], max2[i]) - Max(min1[i], min2[i]), 0.f); } return lengths[0] * lengths[1] * lengths[2]; } void record(const Point3 &min1, const Point3 &max1, Point3 &min2, Vector3 size2, const DTreeRecord &rec, DirectionalFilter directional_filter, BsdfSamplingFractionLoss sampling_loss, std::vector<STreeNode> &nodes) { float w = computeOverlappingVolume(min1, max1, min2, min2 + size2); if (w > 0.f) { if (is_leaf) { dTree.record({rec.d, rec.radiance, rec.product, rec.wo_pdf, rec.bsdf_pdf, rec.DTree_pdf, rec.statistical_weight * w, rec.is_delta}, directional_filter, sampling_loss); } else { size2[axis] /= 2.f; for (int i = 0; i < 2; ++i) { if (i & 1) { min2[axis] += size2[axis]; } nodes[children[i]].record(min1, max1, min2, size2, rec, directional_filter, sampling_loss, nodes); } } } } }; class STree { private: std::vector<STreeNode> m_nodes; BBox m_aabb; public: STree(const BBox &aabb) { clear(); m_aabb = aabb; // Enlarge AABB to turn it into a cube. This has the effect // of nicer hierarchical subdivisions. Vector3 size = m_aabb.m_pmax - m_aabb.m_pmin; float max_size = Max(Max(size.x, size.y), size.z); m_aabb.m_pmax = m_aabb.m_pmin + Vector3(max_size); } void clear() { m_nodes.clear(); m_nodes.emplace_back(); } void subdivideAll() { for (size_t i = 0; i < m_nodes.size(); ++i) { if (m_nodes[i].is_leaf) { subdivide((int)i, m_nodes); } } } void subdivide(int node_idx, std::vector<STreeNode> &nodes) { // Add 2 child nodes nodes.resize(nodes.size() + 2); if (nodes.size() > (std::numeric_limits<uint32_t>::max)()) { std::runtime_error("DTreeWrapper hit maximum children count."); } STreeNode &cur = nodes[node_idx]; for (int i = 0; i < 2; ++i) { uint32_t idx = static_cast<uint32_t>(nodes.size()) - 2 + i; cur.children[i] = idx; nodes[idx].axis = (cur.axis + 1) % 3; nodes[idx].dTree = cur.dTree; nodes[idx].dTree.setStatisticalWeightBuilding(nodes[idx].dTree.statisticalWeightBuilding() / 2.f); } cur.is_leaf = false; cur.dTree = {}; // Reset to an empty dtree to save memory. } DTreeWrapper* dTreeWrapper(Point3 p, Vector3 &size) { size = m_aabb.m_pmax - m_aabb.m_pmin; p = Point3(p - m_aabb.m_pmin); p.x /= size.x; p.y /= size.y; p.z /= size.z; return m_nodes[0].dTreeWrapper(p, size, m_nodes); } DTreeWrapper* dTreeWrapper(Point3 p) { Vector3 size; return dTreeWrapper(p, size); } void forEachDTreeWrapperConst(std::function<void(const DTreeWrapper *)> func) const { for (auto &node : m_nodes) { if (node.is_leaf) { func(&node.dTree); } } } void forEachDTreeWrapperConstP(std::function<void(const DTreeWrapper *, const Point3 &, const Vector3 &)> func) const { m_nodes[0].forEachLeaf(func, m_aabb.m_pmin, m_aabb.m_pmax - m_aabb.m_pmin, m_nodes); } void forEachDTreeWrapperParallel(std::function<void(DTreeWrapper *)> func) { #pragma omp parallel for for (size_t i = 0; i < m_nodes.size(); ++i) { if (m_nodes[i].is_leaf) { func(&m_nodes[i].dTree); } } } void record(const Point3 &p, const Vector3 &voxel_size, DTreeRecord rec, DirectionalFilter directional_filter, BsdfSamplingFractionLoss sampling_loss) { float volume = { 1.f }; for (int i = 0; i < 3; ++i) { volume *= voxel_size[i]; } rec.statistical_weight /= volume; m_nodes[0].record(p - voxel_size * .5f, p + voxel_size * .5f, m_aabb.m_pmin, m_aabb.m_pmax - m_aabb.m_pmin, rec, directional_filter, sampling_loss, m_nodes); } bool shallSplit(const STreeNode &node, int depth, size_t samples_required) { return m_nodes.size() < (std::numeric_limits<uint32_t>::max)() - 1 && node.dTree.statisticalWeightBuilding() > samples_required; } void refine(size_t sTree_threshold, int maxMB) { if (maxMB >= 0) { size_t approxMemoryFootprint = { 0 }; for (const auto &node : m_nodes) { approxMemoryFootprint += node.dTreeWrapper()->approxMemoryFootprint(); } if (approxMemoryFootprint / 1000000 >= static_cast<size_t>(maxMB)) { return; } } struct StackNode { size_t index; int depth; }; std::stack<StackNode> node_indices; node_indices.push({ 0, 1 }); while (!node_indices.empty()) { StackNode node = node_indices.top(); node_indices.pop(); // Subdivide if needed and leaf if (m_nodes[node.index].is_leaf) { if (shallSplit(m_nodes[node.index], node.depth, sTree_threshold)) { subdivide((int)node.index, m_nodes); } } // Add children to stack if we're not if (!m_nodes[node.index].is_leaf) { const STreeNode &s_node = m_nodes[node.index]; for (int i = 0; i < 2; ++i) { node_indices.push({ s_node.children[i], node.depth + 1 }); } } } // Uncomment once memory becomes an issue. //m_nodes.shrink_to_fit(); } const BBox& aabb() const { return m_aabb; } }; class GuidedPathTracerIntegrator : public Integrator { private: // The datastructure for guiding paths. std::unique_ptr<STree> m_sdTree; // The squared values of our currently rendered image. Used to estimate variance. mutable std::shared_ptr<Film> m_squaredImage; // The currently rendered image. Used to estimate variance. mutable std::shared_ptr<Film> m_image; std::vector<std::shared_ptr<Film>> m_images; std::vector<float> m_variances; // This contains the currently estimated variance. mutable std::shared_ptr<Film> m_varianceBuffer; // The modes of NEE which are supported. enum Nee { Never, Kickstart, Always, }; /** How to perform next event estimation (NEE). The following values are valid: - "never": Never performs NEE. - "kickstart": Performs NEE for the first few iterations to initialize the SDTree with good direct illumination estimates. - "always": Always performs NEE. Default = "always" */ Nee m_nee; // Whether Li should currently perform NEE (automatically set during rendering based on m_nee). bool m_doNee; bool m_isBuilt = false; int m_iter; bool m_isFinalIter = false; int m_sppPerPass; int m_passesRendered; int m_passesRenderedThisIter; /** How to combine the samples from all path-guiding iterations: - "discard": Discard all but the last iteration. - "automatic": Discard all but the last iteration, but automatically assign an appropriately larger budget to the last [Mueller et al. 2018]. - "inversevar": Combine samples of the last 4 iterations based on their mean pixel variance [Mueller et al. 2018]. Default = "inversevar" */ SampleCombination m_sampleCombination; // Maximum memory footprint of the SDTree in MB. Stops subdividing once reached. -1 to disable. int m_sdTreeMaxMemory; /** The spatial filter to use when splatting radiance samples into the SDTree. The following values are valid: - "nearest": No filtering [Mueller et al. 2017]. - "stochastic": Stochastic box filter; improves upon Mueller et al. [2017] at nearly no computational cost. - "box": Box filter; improves the quality further at significant additional computational cost. Default = "stochastic" */ SpatialFilter m_spatialFilter; /** The directional filter to use when splatting radiance samples into the SDTree. The following values are valid: - "nearest": No filtering [Mueller et al. 2017]. - "box": Box filter; improves upon Mueller et al. [2017] at nearly no computational cost. Default = "box" */ DirectionalFilter m_directionalFilter; /** Leaf nodes of the spatial binary tree are subdivided if the number of samples they received in the last iteration exceeds c * sqrt(2^k) where c is this value and k is the iteration index. The first iteration has k==0. Default = 4000 */ int m_sTreeThreshold; /** Leaf nodes of the directional quadtree are subdivided if the fraction of energy they carry exceeds this value. Default = 0.01 (1%) */ float m_dTreeThreshold; /** When guiding, we perform MIS with the balance heuristic between the guiding distribution and the BSDF, combined with probabilistically choosing one of the two sampling methods. This factor controls how often the BSDF is sampled vs. how often the guiding distribution is sampled. Default = 0.5 (50%) */ float m_bsdfSamplingFraction; /** The loss function to use when learning the bsdfSamplingFraction using gradient descent, following the theory of Neural Importance Sampling [Mueller et al. 2018]. The following values are valid: - "none": No learning (uses the fixed `m_bsdfSamplingFraction`). - "kl": Optimizes bsdfSamplingFraction w.r.t. the KL divergence. - "var": Optimizes bsdfSamplingFraction w.r.t. variance. Default = "kl" (for reproducibility) */ BsdfSamplingFractionLoss m_bsdfSamplingFractionLoss; int m_maxDepth; public: GuidedPathTracerIntegrator(const TaskSynchronizer &task, const uint32_t &spp, int maxDepth, GuidedPathTracerIntegrator::Nee nee = GuidedPathTracerIntegrator::Nee::Always, SampleCombination sampleCombination = SampleCombination::InverseVariance, SpatialFilter spatialFilter = SpatialFilter::StochasticBox, DirectionalFilter directionalFilter = DirectionalFilter::Box, BsdfSamplingFractionLoss bsdfSamplingFractionLoss = BsdfSamplingFractionLoss::KL, int sppPerPass = 4, int sdTreeMaxMemory = -1, int sTreeThreshold = 4000, float dTreeThreshold = 0.01f, float bsdfSamplingFraction = 0.5f) : Integrator(task, spp) { m_maxDepth = { maxDepth }; m_nee = { nee }; m_sampleCombination = { sampleCombination }; m_spatialFilter = { spatialFilter }; m_directionalFilter = { directionalFilter }; m_bsdfSamplingFractionLoss = { bsdfSamplingFractionLoss }; m_sppPerPass = { sppPerPass }; m_sdTreeMaxMemory = { sdTreeMaxMemory }; m_sTreeThreshold = { sTreeThreshold }; m_dTreeThreshold = { dTreeThreshold }; m_bsdfSamplingFraction = { bsdfSamplingFraction }; } void render(const Scene *scene, const Camera *camera, Sampler *sampler, Film *film) override; bool renderPasses(float &variance, int num_passes, const Scene *scene, const Camera *camera, Sampler *sampler, Film *film); Spectrum li(const RayDifferential &ray, const Scene *scene, Sampler *sampler, RNG &rng, MemoryPool &memory) const; private: void resetSDTree(); void buildSDTree(); bool doNeeWithSpp(int spp); // ... }; } #endif
30,946
C++
.h
912
29.767544
160
0.664253
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,943
BidirectionalPathTracing.h
g1n0st_AyaRay/src/Integrators/BidirectionalPathTracing.h
#ifndef AYA_BIDIRECTIONALINTEGRATORS_PATHTRACING_H #define AYA_BIDIRECTIONALINTEGRATORS_PATHTRACING_H #include <Core/Integrator.h> namespace Aya { class BidirectionalPathTracingIntegrator : public TiledIntegrator { public: struct PathState { Point3 ori; Vector3 dir; Spectrum throughput; // Shared a 32-bit field uint32_t path_len : 30; bool is_finite_light : 1; bool specular_path : 1; // Multiple Importance Sampling // Implementing Vertex Connection and Merging float dvcm; float dvc; }; struct PathVertex { Spectrum throughput; // Path throughput including emission uint32_t path_len; // Diffuse surface Intersection local infomation SurfaceIntersection isect; Vector3 v_in; float dvcm; float dvc; }; private: uint32_t m_maxDepth; const Camera *mp_cam; Film *mp_film; public: BidirectionalPathTracingIntegrator(const TaskSynchronizer &task, const uint32_t &spp, uint32_t max_depth, const Camera *camera, Film *film) : TiledIntegrator(task, spp), m_maxDepth(max_depth), mp_cam(camera), mp_film(film) { } ~BidirectionalPathTracingIntegrator() { } Spectrum li(const RayDifferential &ray, const Scene *scene, Sampler *sampler, RNG &rng, MemoryPool &memory) const override; static PathState sampleLightSource(const Scene *scene, Sampler *sampler, RNG &rng); static int generateLightPath(const Scene *scene, Sampler *sampler, RNG &rng, const Camera *camera, Film *film, const uint32_t max_depth, PathVertex *path, int *vertex_count, const bool connect_to_cam = true, const int RR_depth = 3); static Spectrum connectToCamera(const Scene *scene, Sampler *sampler, RNG &rng, const Camera *camera, Film *film, const SurfaceIntersection &intersection, const PathVertex &path_vertex, Point3 *raster_pos); static void sampleCamera(const Scene *scene, const Camera *camera, Film *film, const RayDifferential &ray, PathState &init_path); static Spectrum connectToLight(const Scene *scene, Sampler *sampler, RNG &rng, const RayDifferential &ray, const SurfaceIntersection &intersection, PathState &cam_path); static Spectrum hittingLightSource(const Scene *scene, RNG &rng, const RayDifferential &ray, const SurfaceIntersection &intersection, const Light *light, PathState &cam_path); static Spectrum connectVertex(const Scene *scene, RNG &rng, const SurfaceIntersection &intersection, const PathVertex &light_vertex, const PathState &cam_path); static bool sampleScattering(const Scene *scene, RNG &rng, const RayDifferential &ray, const SurfaceIntersection &intersection, const Sample& bsdf_sample, PathState &path_state, const int RR_depth = -1); inline static float MIS(const float val) { // Power Heuristic Method return val * val; } }; } #endif
2,807
C++
.h
68
37.852941
125
0.760264
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,944
VertexCM.h
g1n0st_AyaRay/src/Integrators/VertexCM.h
#ifndef AYA_INTEGRATORS_VERTEXCM_H #define AYA_INTEGRATORS_VERTEXCM_H #include <Core/Integrator.h> #include <thread> #include <mutex> namespace Aya { class VertexCMIntegrator : public Integrator { public: // The sole point of this structure is to make carrying around the ray baggage easier. struct PathState { Point3 ori; // Path origin Vector3 dir; // Where to go next Spectrum throughput; // Path throughput // Shared a 32-bit field uint32_t path_len : 30; // Number of path segments, including this bool is_finite_light : 1; // Just generate by finite light bool specular_path : 1; // All scattering events so far were specular float dvcm; // MIS quantity used for vertex connection and merging float dvc; // MIS quantity used for vertex connection float dvm; // MIS quantity used for vertex merging }; // Path vertex, used for merging and connection struct PathVertex { Spectrum throughput; // Path throughput (including emission) uint32_t path_len; // Number of segments between source and vertex // Stores all required local information, including incoming direction. SurfaceIntersection isect; Vector3 v_in; float dvcm; // MIS quantity used for vertex connection and merging float dvc; // MIS quantity used for vertex connection float dvm; // MIS quantity used for vertex merging // Used by HashGrid const Point3& getPosition() const { return isect.p; } }; class RangeQuery { private: const VertexCMIntegrator &m_VCM; const SurfaceIntersection &m_cam_isect; const BSDF *m_cam_bsdf; const PathState &m_cam_state; Spectrum m_contrib; public: RangeQuery( const VertexCMIntegrator &vcm, const SurfaceIntersection &intersection, const BSDF *cam_bsdf, const PathState &cam_state ) : m_VCM(vcm), m_cam_isect(intersection), m_cam_bsdf(cam_bsdf), m_cam_state(cam_state), m_contrib(0.f) { } const Point3& getPostion() const { return m_cam_isect.p; } const Spectrum& getContrib() const { return m_contrib; } void process(const PathVertex &light_vertex) { // Reject if full path length below/above min/max path length if ((light_vertex.path_len + m_cam_state.path_len > m_VCM.m_maxDepth) || (light_vertex.path_len + m_cam_state.path_len < m_VCM.m_minDepth)) return; const Vector3 light_dir = light_vertex.isect.n; const BSDF *cam_bsdf = m_cam_isect.bsdf; Vector3 v_out_cam = -m_cam_state.dir; Spectrum cam_bsdf_fac = cam_bsdf->f(v_out_cam, light_dir, m_cam_isect); float cam_dir_pdfW = cam_bsdf->pdf(v_out_cam, light_dir, m_cam_isect); float rev_cam_dir_pdfW = cam_bsdf->pdf(light_dir, v_out_cam, m_cam_isect); if (cam_bsdf_fac.isBlack() || cam_dir_pdfW == 0.f || rev_cam_dir_pdfW == 0.f) return; // Partial light sub-path MIS weight [tech. rep. (38)] const float weight_light = light_vertex.dvcm * m_VCM.m_MIS_VC_weight + light_vertex.dvm * m_VCM.MIS(cam_dir_pdfW); // Partial eye sub-path MIS weight [tech. rep. (39)] const float weight_camera = m_cam_state.dvcm * m_VCM.m_MIS_VC_weight + m_cam_state.dvm * m_VCM.MIS(rev_cam_dir_pdfW); // Full path MIS weight [tech. rep. (37)]. No MIS for PPM const float MIS_weight = m_VCM.m_PPM ? 1.f : 1.f / (weight_light + 1.f + weight_camera); m_contrib += MIS_weight * cam_bsdf_fac * light_vertex.throughput; } }; class HashGrid { private: BBox m_bbox; std::vector<int> m_indices; std::vector<int> m_cell_ends; float m_radius; float m_radius_sqr; float m_cell_size; float m_cell_size_inv; public: void reserve(int num) { m_cell_ends.resize(num); } void build(const std::vector<PathVertex> &particles, float radius) { m_radius = radius; m_radius_sqr = radius * radius; m_cell_size = m_radius * 2.f; m_cell_size_inv = 1.f / m_cell_size; m_bbox = BBox(); for (size_t i = 0; i < particles.size(); i++) { const Point3 &pos = particles[i].getPosition(); m_bbox.unity(pos); } m_indices.resize(particles.size()); memset(&m_cell_ends[0], 0, m_cell_ends.size() * sizeof(int)); // set mCellEnds[x] to number of particles within x for (size_t i = 0; i < particles.size(); i++) { const Point3 &pos = particles[i].getPosition(); m_cell_ends[getCellIndex(pos)]++; } // run exclusive prefix sum to really get the cell starts // mCellEnds[x] is now where the cell starts int sum = 0; for (size_t i = 0; i < m_cell_ends.size(); i++) { int temp = m_cell_ends[i]; m_cell_ends[i] = sum; sum += temp; } for (size_t i = 0; i < particles.size(); i++) { const Point3 &pos = particles[i].getPosition(); const int target_idx = m_cell_ends[getCellIndex(pos)]++; m_indices[target_idx] = int(i); } } void process(const std::vector<PathVertex> &particles, RangeQuery &query) const { const Point3 query_pos = query.getPostion(); const Vector3 dist_min = query_pos - m_bbox.m_pmin; const Vector3 dist_max = m_bbox.m_pmax - query_pos; for (int i = 0; i < 3; i++) { if (dist_min[i] < 0.f) return; if (dist_max[i] < 0.f) return; } const Vector3 cell_pt = m_cell_size_inv * dist_min; const Vector3 coord_f( std::floorf(cell_pt.x), std::floorf(cell_pt.y), std::floorf(cell_pt.z)); const int px = int(coord_f.x); const int py = int(coord_f.y); const int pz = int(coord_f.z); const Vector3 fract_coord = cell_pt - coord_f; const int pxo = px + (fract_coord.x < 0.5f ? -1 : +1); const int pyo = py + (fract_coord.y < 0.5f ? -1 : +1); const int pzo = pz + (fract_coord.z < 0.5f ? -1 : +1); int found = 0; for (int j = 0; j < 8; j++) { Vector2i active_range; switch (j) { case 0: active_range = getCellRange(getCellIndex(px, py, pz)); break; case 1: active_range = getCellRange(getCellIndex(px, py, pzo)); break; case 2: active_range = getCellRange(getCellIndex(px, pyo, pz)); break; case 3: active_range = getCellRange(getCellIndex(px, pyo, pzo)); break; case 4: active_range = getCellRange(getCellIndex(pxo, py, pz)); break; case 5: active_range = getCellRange(getCellIndex(pxo, py, pzo)); break; case 6: active_range = getCellRange(getCellIndex(pxo, pyo, pz)); break; case 7: active_range = getCellRange(getCellIndex(pxo, pyo, pzo)); break; } for (; active_range.x < active_range.y; ++active_range.x) { const int particle_idx = m_indices[active_range.x]; const PathVertex &particle = particles[particle_idx]; const float dist_sqr = (query.getPostion() - particle.getPosition()).length2(); if (dist_sqr <= m_radius_sqr) query.process(particle); } } } private: Vector2i getCellRange(int cell_index) const { if (!cell_index) { return Vector2i(0, m_cell_ends[0]); } return Vector2i(m_cell_ends[cell_index - 1], m_cell_ends[cell_index]); } int getCellIndex(const int _x, const int _y, const int _z) const { uint32_t x = uint32_t(_x); uint32_t y = uint32_t(_y); uint32_t z = uint32_t(_z); return int(((x * 73856093) ^ (y * 19349663) ^ (z * 83492791)) % uint32_t(m_cell_ends.size())); } int getCellIndex(const Point3 &pos) const { Vector3 dis_min = pos - m_bbox.m_pmin; return getCellIndex(FloorToInt(dis_min.x * m_cell_size_inv), FloorToInt(dis_min.y * m_cell_size_inv), FloorToInt(dis_min.z * m_cell_size_inv)); } }; public: enum AlgorithmType { // Camera and light vertices merged on first non-specular surface from camera. // Cannot handle mixed specular + non-specular materials. // No MIS weights (dVCM, dVM, dVC all ignored) kPpm, // Camera and light vertices merged on along full path. // dVCM and dVM used for MIS kBpm, // Standard bidirectional path tracing // dVCM and dVC used for MIS kBpt, // Vertex connection and mering // dVCM, dVM, and dVC used for MIS kVcm }; public: VertexCMIntegrator(const TaskSynchronizer &task, const uint32_t &spp, uint32_t min_depth, uint32_t max_depth, const Camera *camera, Film *film, AlgorithmType algorithm_type = AlgorithmType::kVcm, const float radius_factor = .003f, const float radius_alpha = .75f); ~VertexCMIntegrator() = default; void render(const Scene *scene, const Camera *camera, Sampler *sampler, Film *film) override; PathState sampleLightSource(const Scene *scene, Sampler *sampler, RNG &rng) const; int generateLightPath(const Scene *scene, Sampler *sampler, RNG &rng, const Camera *camera, Film *film, const uint32_t max_depth, PathVertex *path, int *vertex_count, const bool connect_to_cam = true, const int RR_depth = 3) const; Spectrum connectToCamera(const Scene *scene, Sampler *sampler, RNG &rng, const Camera *camera, Film *film, const SurfaceIntersection &intersection, const PathVertex &path_vertex, Point3 *raster_pos) const; void sampleCamera(const Scene *scene, const Camera *camera, Film *film, const RayDifferential &ray, PathState &init_path) const; Spectrum connectToLight(const Scene *scene, Sampler *sampler, RNG &rng, const RayDifferential &ray, const SurfaceIntersection &intersection, PathState &cam_path) const; Spectrum hittingLightSource(const Scene *scene, RNG &rng, const RayDifferential &ray, const SurfaceIntersection &intersection, const Light *light, PathState &cam_path) const; Spectrum connectVertex(const Scene *scene, RNG &rng, const SurfaceIntersection &intersection, const PathVertex &light_vertex, const PathState &cam_path) const; bool sampleScattering(const Scene *scene, RNG &rng, const RayDifferential &ray, const SurfaceIntersection &intersection, const Sample& bsdf_sample, PathState &path_state, const int RR_depth = -1) const; private: bool m_useVM; // Vertex merging (of some form) is used bool m_useVC; // Vertex connection (BPT) is used bool m_PPM; // Do PPM, same terminates camera after first merge float m_radiusAlpha; // Radius reduction rate parameter float m_baseRadius; // Initial merging radius float m_lightPathCount; // Number of light sub-paths float m_screenPixelCount; // Number of pixels mutable float m_MIS_VC_weight; // Weight of vertex merging (used in VC) mutable float m_MIS_VM_weight; // Weight of vertex connection (used in VM) mutable float m_VM_normalization; // 1 / (Pi * radius^2 * light_path_count) uint32_t m_maxDepth; uint32_t m_minDepth; const Camera *mp_cam; Film *mp_film; inline static float MIS(const float val) { // Power Heuristic Method return val * val; } }; } #endif
10,817
C++
.h
265
36.215094
121
0.676235
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,945
PathTracing.h
g1n0st_AyaRay/src/Integrators/PathTracing.h
#ifndef AYA_INTEGRATORS_PATHTRACING_H #define AYA_INTEGRATORS_PATHTRACING_H #include <Core/Integrator.h> namespace Aya { class PathTracingIntegrator : public TiledIntegrator { private: uint32_t m_maxDepth; public: PathTracingIntegrator(const TaskSynchronizer &task, const uint32_t &spp, uint32_t max_depth) : TiledIntegrator(task, spp), m_maxDepth(max_depth) { } ~PathTracingIntegrator() { } Spectrum li(const RayDifferential &ray, const Scene *scene, Sampler *sampler, RNG &rng, MemoryPool &memory) const override; }; } #endif
551
C++
.h
17
30.058824
125
0.777358
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,946
FilmRHF.h
g1n0st_AyaRay/src/Films/FilmRHF.h
#ifndef AYA_FILMS_FILMRHF_H #define AYA_FILMS_FILMRHF_H #include <Core/Film.h> #include <array> namespace Aya { class FilmRHF : public Film { protected: struct Histogram { static const int NUM_BINS = 20; static const float MAX_VAL; BlockedArray<RGBSpectrum> histogramWeights[NUM_BINS]; BlockedArray<float> totalWeights; void init(int w, int h) { totalWeights.init(w, h); for (size_t i = 0; i < NUM_BINS; i++) { histogramWeights[i].init(w, h); } } void free() { totalWeights.free(); for (size_t i = 0; i < NUM_BINS; i++) { histogramWeights[i].free(); } } }; static const int MAX_SCALE = 3; Histogram m_sampleHistogram; float m_maxDist; int m_halfPatchSize; int m_halfWindowSize; int m_scale; mutable std::mutex m_RHFLock; public: void init(int width, int height, Filter *filter) override; void resize(int width, int height) override; void free() override; void clear() override; void addSample(float x, float y, const Spectrum &L) override; void denoise() override; private: void histogramFusion(BlockedArray<RGBSpectrum> &input, const Histogram &histogram); float chiSquareDistance(const Vector2i &x, const Vector2i &y, const int halfPathSize, const Histogram &histogram); template<typename T> void gaussianDownSample(const BlockedArray<T> &input, BlockedArray<T> &output, float scale); void bicubicInterpolation(const BlockedArray<RGBSpectrum> &input, BlockedArray<RGBSpectrum> &output); }; } #endif
1,516
C++
.h
48
28.1875
116
0.724588
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,950
Film.h
g1n0st_AyaRay/src/Core/Film.h
#ifndef AYA_CORE_FILM_H #define AYA_CORE_FILM_H #include <Core/Config.h> #include <Core/Filter.h> #include <Core/Memory.h> #include <Core/Spectrum.h> #include <Math/Vector2.h> #include <ppl.h> #include <thread> #include <mutex> namespace Aya { class Film { protected : struct Pixel { Spectrum color; Spectrum splat; float weight; }; int m_width, m_height; uint32_t m_sampleCount; BlockedArray<RGBSpectrum> m_pixelBuffer; BlockedArray<Pixel> m_accumulateBuffer; std::unique_ptr<Filter> mp_filter; mutable std::mutex m_mt; static const float INV_GAMMA; public: Film() = default; Film(int width, int height, Filter *filter) { init(width, height, filter); } virtual ~Film() { free(); } virtual void init(int width, int height, Filter *filter); virtual void resize(int width, int height); virtual void free(); virtual void clear(); int getPixelCount() const { return m_width * m_height; } Vector2i getSize() const { return { m_width, m_height }; } virtual void addSample(float x, float y, const Spectrum &L); virtual void addFilm(const Film *film, float weight = 1.f); virtual void splat(float x, float y, const Spectrum &L); void updateDisplay(const float splat_scale = 0.f); inline void addSampleCount() { ++m_sampleCount; printf("\033[01;31m %d spp(s) \033[0m is rendered\n", m_sampleCount); } const RGBSpectrum* getPixelBuffer() const { return m_pixelBuffer.data(); } const Spectrum getPixel(int x, int y) const { const Pixel &pixel = m_accumulateBuffer(x, y); return pixel.color / (pixel.weight + float(AYA_EPSILON)) + pixel.splat / static_cast<float>(m_sampleCount); } void setPixel(int x, int y, const Spectrum &L) { Pixel &pixel = m_accumulateBuffer(x, y); pixel.color = L; pixel.weight = 1.f; pixel.splat = Spectrum(0.f); } const int getSampleCount() const { return m_sampleCount; } virtual void denoise() {} }; } #endif
1,964
C++
.h
71
24.704225
110
0.702071
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,954
Sampler.h
g1n0st_AyaRay/src/Core/Sampler.h
#ifndef AYA_CORE_SAMPLER_H #define AYA_CORE_SAMPLER_H #include <Core/Config.h> #include <Core/Memory.h> #include <Core/RNG.h> #include <Math/Vector2.h> namespace Aya { struct CameraSample { float image_x, image_y; float lens_u, lens_v; float time; }; struct Sample { float u, v, w; Sample() : u(0.f), v(0.f), w(0.f) {} Sample(RNG &rng); }; class Sampler { public: virtual ~Sampler() = default; virtual void generateSamples( const int pixel_x, const int pixel_y, CameraSample *samples, RNG &rng ) = 0; virtual void advanceSampleIndex() {} virtual void startPixel(const int pixel_x, const int pixel_y) {} virtual float get1D() = 0; virtual Vector2f get2D() = 0; virtual Sample getSample() = 0; virtual std::unique_ptr<Sampler> clone(const int seed) const = 0; virtual std::unique_ptr<Sampler> deepClone() const = 0; }; } #endif
884
C++
.h
36
21.944444
67
0.694411
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,956
Filter.h
g1n0st_AyaRay/src/Core/Filter.h
#ifndef AYA_CORE_FILTER_H #define AYA_CORE_FILTER_H #include <Core/Config.h> #include <Math/MathUtility.h> namespace Aya { class Filter { protected: float m_radius; public: Filter(const float &rad) : m_radius(rad) {} virtual ~Filter() = default; const float getRadius() const; virtual const float evaluate(const float dx, const float dy) const = 0; }; } #endif
378
C++
.h
16
21.5625
73
0.735376
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,958
Accelerator.h
g1n0st_AyaRay/src/Core/Accelerator.h
#ifndef AYA_CORE_ACCELERATOR_H #define AYA_CORE_ACCELERATOR_H #include <Core/Config.h> #include <Math/BBox.h> #include <Core/Accelerator.h> #include <Core/Primitive.h> namespace Aya { class Accelerator { public: Accelerator() = default; virtual ~Accelerator(); virtual void construct(const std::vector<Primitive*> &prims) = 0; virtual BBox worldBound() const = 0; virtual bool intersect(const Ray &ray, Intersection *si) const = 0; virtual bool occluded(const Ray &ray) const = 0; }; } #endif
511
C++
.h
18
26.388889
69
0.746939
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,959
Camera.h
g1n0st_AyaRay/src/Core/Camera.h
#ifndef AYA_CORE_CAMERA_H #define AYA_CORE_CAMERA_H #include <Core/Config.h> #include <Core/Ray.h> #include <Core/RNG.h> #include <Core/Sampling.h> #include <Core/Sampler.h> #include <Math/Transform.h> #include <Loaders/Bitmap.h> namespace Aya { class Camera { public: Point3 m_pos; Point3 m_target; Vector3 m_up; Vector3 m_dir; float m_FOV; float m_ratio; float m_near; float m_far; float m_CoCRadius, m_focalPlaneDist; float m_imagePlaneDist; float m_vignetteFactor; Vector3 m_dxCam, m_dyCam; protected: int m_resX, m_resY; Transform m_view, m_viewInv; Transform m_proj; Transform m_screenToRaster, m_rasterToScreen; Transform m_rasterToCamera, m_cameraToRaster; Transform m_rasterToWorld, m_worldToRaster; std::unique_ptr<Distribution2D> mp_aperture; public: Camera() = default; Camera(const Point3 &pos, const Point3 &tar, const Vector3 &up, int res_x, int res_y, float FOV = 35.f, float _near = .1f, float _far = 1000.f, const float blur_radius = 0.f, const float focal_dist = 0.f, const float vignette = 3.f); virtual ~Camera() { } virtual void init(const Point3 &pos, const Point3 &tar, const Vector3 &up, int res_x, int res_y, float FOV = 35.f, float _near = .1f, float _far = 1000.f, const float blur_radius = 0.f, const float focal_dist = 0.f, const float vignette = 3.f); virtual void resize(int width, int height); bool generateRay(const CameraSample &sample, Ray *ray, const bool force_pinhole = false) const; bool generateRayDifferential(const CameraSample &sample, RayDifferential *ray) const; template<class T> inline T view(const T elem) const { return m_view(elem); } template<class T> inline T viewInv(const T elem) const { return m_viewInv(elem); } template<class T> inline T proj(const T elem) const { return m_proj(elem); } template<class T> inline T worldToRaster(const T elem) const { return m_worldToRaster(elem); } template<class T> inline T rasterToWorld(const T elem) const { return m_rasterToWorld(elem); } template<class T> inline T rasterToCamera(const T elem) const { return m_rasterToCamera(elem); } template<class T> inline T cameraToRaster(const T elem) const { return m_cameraToRaster(elem); } inline int getResolusionX() const { return m_resX; } inline int getResolusionY() const { return m_resY; } inline bool checkRaster(const Point3 &pos) const { return pos.x < float(m_resX) && pos.x >= 0.f && pos.y < float(m_resY) && pos.y >= 0.f; } void setApertureFunc(const char *path); float getCircleOfConfusionRadius() const { return m_CoCRadius; } float getFocusDistance() const { return m_focalPlaneDist; } float getImagePlaneDistance() const { return m_imagePlaneDist; } }; } #endif
2,802
C++
.h
89
28.41573
98
0.719689
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,965
Memory.h
g1n0st_AyaRay/src/Core/Memory.h
#ifndef AYA_CORE_MEMORY_H #define AYA_CORE_MEMORY_H #include <Core/Config.h> #include <atomic> #include <vector> namespace Aya { template<typename T> AYA_FORCE_INLINE T *AllocAligned(uint32_t count) { return (T *)_aligned_malloc(count * sizeof(T), AYA_L1_CACHE_LINE_SIZE); } void FreeAligned(void *ptr); template<class T> static AYA_FORCE_INLINE void SafeDelete(T*& ptr) { if (ptr != NULL) { delete ptr; ptr = NULL; } } template<class T> static AYA_FORCE_INLINE void SafeDeleteArray(T*& ptr) { if (ptr != NULL) { delete[] ptr; ptr = NULL; } } template <typename T> class BlockedArray { private: T *m_data; uint32_t u_res, v_res; public: BlockedArray() { m_data = NULL; } BlockedArray(uint32_t nu, uint32_t nv) { init(nu, nv); } ~BlockedArray() { free(); } void init(uint32_t nu, uint32_t nv, const T* data) { u_res = nu; v_res = nv; auto roundUp = [this](const uint32_t x) { return (x + 3) & ~(3); }; uint32_t n_alloc = roundUp(u_res) * roundUp(v_res); m_data = AllocAligned<T>(n_alloc); for (uint32_t i = 0; i < n_alloc; ++i) new (&m_data[i]) T(); for (uint32_t i = 0; i < u_res * v_res; i++) m_data[i] = data[i]; } void init(uint32_t nu, uint32_t nv) { u_res = nu; v_res = nv; auto roundUp = [this](const uint32_t x) { return (x + 3) & ~(3); }; uint32_t n_alloc = roundUp(u_res) * roundUp(v_res); m_data = AllocAligned<T>(n_alloc); for (uint32_t i = 0; i < n_alloc; ++i) new (&m_data[i]) T(); } void free() { for (uint32_t i = 0; i < u_res * v_res; ++i) m_data[i].~T(); FreeAligned(m_data); } AYA_FORCE_INLINE uint32_t linearSize() const { return v_res * u_res; } AYA_FORCE_INLINE T &operator()(uint32_t u, uint32_t v) { return m_data[u * v_res + v]; } AYA_FORCE_INLINE const T &operator()(uint32_t u, uint32_t v) const { return m_data[u * v_res + v]; } AYA_FORCE_INLINE const T* data() const { return m_data; } AYA_FORCE_INLINE T* data() { return m_data; } AYA_FORCE_INLINE int x() const { return u_res; } AYA_FORCE_INLINE int y() const { return v_res; } AYA_FORCE_INLINE int u() const { return u_res; } AYA_FORCE_INLINE int v() const { return v_res; } }; class MemoryPool { private: uint32_t m_size; uint32_t m_offset; uint8_t *mp_current; std::vector<uint8_t*> m_used, m_avail; public: MemoryPool(uint32_t size = 32768) { m_size = size; m_offset = 0; mp_current = AllocAligned<uint8_t>(m_size); } ~MemoryPool() { FreeAligned(mp_current); for (auto p : m_used) FreeAligned(p); for (auto p : m_avail) FreeAligned(p); } template<class T> inline T* alloc(uint32_t count = 1) { uint32_t size = (count * sizeof(T) + 15) & (~15); if (m_offset + size > m_size) { m_used.emplace_back(mp_current); if (m_avail.size() > 0 && size < m_size) { mp_current = m_avail.back(); m_avail.pop_back(); } else { mp_current = AllocAligned<uint8_t>(Max(size, m_size)); } m_offset = 0; } T *ret = (T*)(mp_current + m_offset); m_offset += size; return ret; } inline void freeAll() { m_offset = 0; while (m_used.size()) { m_avail.emplace_back(m_used.back()); m_used.pop_back(); } } }; } #endif
3,320
C++
.h
140
20.221429
73
0.604489
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,967
MitchellNetravaliFilter.h
g1n0st_AyaRay/src/Filters/MitchellNetravaliFilter.h
#ifndef AYA_FILTERS_MITCHELLNETRAVALIFILTER_H #define AYA_FILTERS_MITCHELLNETRAVALIFILTER_H #include <Core/Filter.h> namespace Aya { class MitchellNetravaliFilter : public Filter { private: float m_B, m_C; public: MitchellNetravaliFilter(const float rad = 2.f, const float B = 1.f / 3.f, const float C = 1.f / 3.f) : Filter(rad), m_B(B), m_C(C) {} const float evaluate(const float dx, const float dy) const { auto MitchellNetravali = [this](const float d) { float dd = Abs(d); float sqr = d * d, cc = sqr * dd; if (dd < 1.f) { return 1.f / 6.f * ((12.f - 9.f * m_B - 6.f * m_C) * cc + (-18.f + 12.f * m_B + 6.f * m_C) * sqr + (6.f - 2.f * m_B)); } else if (dd < 2.f) { return 1.f / 6.f * ((-m_B - 6.f * m_C) * cc + (6.f * m_B + 30.f * m_C) * sqr + (-12.f * m_B - 48.f * m_C) * dd + (8.f * m_B + 24.f * m_C)); } else return 0.f; }; return MitchellNetravali(dx) * MitchellNetravali(dy); } }; } #endif
981
C++
.h
30
28.966667
81
0.56871
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,968
BoxFilter.h
g1n0st_AyaRay/src/Filters/BoxFilter.h
#ifndef AYA_FILTERS_BOXFILTER_H #define AYA_FILTERS_BOXFILTER_H #include <Core/Filter.h> namespace Aya { class BoxFilter : public Filter { public: BoxFilter() : Filter(0.25f) {} const float evaluate(const float dx, const float dy) const { return 1.0f; } }; } #endif
280
C++
.h
13
19.461538
62
0.732075
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,969
TriangleFilter.h
g1n0st_AyaRay/src/Filters/TriangleFilter.h
#ifndef AYA_FILTERS_TRIANGLEFILTER_H #define AYA_FILTERS_TRIANGLEFILTER_H #include <Core/Filter.h> namespace Aya { class TriangleFilter : public Filter { TriangleFilter() : Filter(0.25f) {} const float evaluate(const float dx, const float dy) const { return Max(0.f, m_radius - dx) * Max(0.f, m_radius - dy); } }; } #endif
336
C++
.h
12
25.916667
62
0.723602
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,970
GaussianFilter.h
g1n0st_AyaRay/src/Filters/GaussianFilter.h
#ifndef AYA_FILTERS_GAUSSIANFILTER_H #define AYA_FILTERS_GAUSSIANFILTER_H #include <Core/Filter.h> namespace Aya { class GaussianFilter : public Filter { private: float m_std, m_alpha, m_expR; public: GaussianFilter(const float std = .5f) : Filter(4 * std), m_std(std) { m_alpha = -1.f / (2.f * m_std * m_std); m_expR = std::exp(m_alpha * m_radius * m_radius); } const float evaluate(const float dx, const float dy) const { auto Gaussian = [this](const float d) { return Max(0.f, std::exp(m_alpha * d * d) - m_expR); }; return Gaussian(dx) * Gaussian(dy); } }; } #endif
607
C++
.h
21
26.142857
71
0.66323
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,980
RoughDielectric.h
g1n0st_AyaRay/src/BSDFs/RoughDielectric.h
#ifndef AYA_BSDFS_ROUGHDIELECTRIC_H #define AYA_BSDFS_ROUGHDIELECTRIC_H #include <Core/BSDF.h> namespace Aya { class RoughDielectric : public BSDF { private: std::unique_ptr<Texture2D<float>> m_roughness; float m_etai, m_etat; static const ScatterType reflect_scatter = ScatterType(BSDF_REFLECTION | BSDF_GLOSSY); static const ScatterType refract_scatter = ScatterType(BSDF_TRANSMISSION | BSDF_GLOSSY); public: RoughDielectric(const Spectrum &color = Spectrum(), float roughness = .3f, float etai = 1.0f, float etat = 1.5f) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_TRANSMISSION | BSDF_GLOSSY), BSDFType::RoughDielectric, color), m_roughness(new ConstantTexture2D<float>(roughness)), m_etai(etai), m_etat(etat) {} RoughDielectric(std::unique_ptr<Texture2D<Spectrum>> tex, std::unique_ptr<Texture2D<RGBSpectrum>> normal, float roughness = .3f, float etai = 1.0f, float etat = 1.5f) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_TRANSMISSION | BSDF_GLOSSY), BSDFType::RoughDielectric, std::move(tex), std::move(normal)), m_roughness(new ConstantTexture2D<float>(roughness)), m_etai(etai), m_etat(etat) {} RoughDielectric(const char *texture_file, float roughness = .3f, float etai = 1.0f, float etat = 1.5f) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_TRANSMISSION | BSDF_GLOSSY), BSDFType::RoughDielectric, texture_file), m_roughness(new ConstantTexture2D<float>(roughness)), m_etai(etai), m_etat(etat) {} RoughDielectric(const char *texture_file, const char *normal_file, float roughness = .3f, float etai = 1.0f, float etat = 1.5f) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_TRANSMISSION | BSDF_GLOSSY), BSDFType::RoughDielectric, texture_file, normal_file), m_roughness(new ConstantTexture2D<float>(roughness)), m_etai(etai), m_etat(etat) {} RoughDielectric(const Spectrum &color, char *roughness_texture, float etai = 1.0f, float etat = 1.5f) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_TRANSMISSION | BSDF_GLOSSY), BSDFType::RoughDielectric, color), m_roughness(new ImageTexture2D<float, float>(roughness_texture)), m_etai(etai), m_etat(etat) {} RoughDielectric(std::unique_ptr<Texture2D<Spectrum>> tex, std::unique_ptr<Texture2D<RGBSpectrum>> normal, char *roughness_texture, float etai = 1.0f, float etat = 1.5f) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_TRANSMISSION | BSDF_GLOSSY), BSDFType::RoughDielectric, std::move(tex), std::move(normal)), m_roughness(new ImageTexture2D<float, float>(roughness_texture)), m_etai(etai), m_etat(etat) {} RoughDielectric(const char *texture_file, char *roughness_texture, float etai = 1.0f, float etat = 1.5f) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_TRANSMISSION | BSDF_GLOSSY), BSDFType::RoughDielectric, texture_file), m_roughness(new ImageTexture2D<float, float>(roughness_texture)), m_etai(etai), m_etat(etat) {} RoughDielectric(const char *texture_file, const char *normal_file, char *roughness_texture, float etai = 1.0f, float etat = 1.5f) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_TRANSMISSION | BSDF_GLOSSY), BSDFType::RoughDielectric, texture_file, normal_file), m_roughness(new ImageTexture2D<float, float>(roughness_texture)), m_etai(etai), m_etat(etat) {} RoughDielectric(const Spectrum &color, std::unique_ptr<Texture2D<float>> roughness, float etai = 1.0f, float etat = 1.5f) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_TRANSMISSION | BSDF_GLOSSY), BSDFType::RoughDielectric, color), m_roughness(std::move(roughness)), m_etai(etai), m_etat(etat) {} RoughDielectric(std::unique_ptr<Texture2D<Spectrum>> tex, std::unique_ptr<Texture2D<RGBSpectrum>> normal, std::unique_ptr<Texture2D<float>> roughness, float etai = 1.0f, float etat = 1.5f) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_TRANSMISSION | BSDF_GLOSSY), BSDFType::RoughDielectric, std::move(tex), std::move(normal)), m_roughness(std::move(roughness)), m_etai(etai), m_etat(etat) {} RoughDielectric(const char *texture_file, std::unique_ptr<Texture2D<float>> roughness, float etai = 1.0f, float etat = 1.5f) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_TRANSMISSION | BSDF_GLOSSY), BSDFType::RoughDielectric, texture_file), m_roughness(std::move(roughness)), m_etai(etai), m_etat(etat) {} RoughDielectric(const char *texture_file, const char *normal_file, std::unique_ptr<Texture2D<float>> roughness, float etai = 1.0f, float etat = 1.5f) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_TRANSMISSION | BSDF_GLOSSY), BSDFType::RoughDielectric, texture_file, normal_file), m_roughness(std::move(roughness)), m_etai(etai), m_etat(etat) {} virtual Spectrum f(const Vector3 &v_out, const Vector3 &v_in, const SurfaceIntersection &intersection, ScatterType types = BSDF_ALL) const override; virtual float pdf(const Vector3 &v_out, const Vector3 &v_in, const SurfaceIntersection &intersection, ScatterType types = BSDF_ALL) const override; virtual Spectrum sample_f(const Vector3 &v_out, const Sample &sample, const SurfaceIntersection &intersection, Vector3 *v_in, float *pdf, ScatterType types = BSDF_ALL, ScatterType *sample_types = nullptr) const override; private: virtual float evalInner(const Vector3 &v_out, const Vector3 &v_in, const SurfaceIntersection &intersection, ScatterType types = BSDF_ALL) const override; virtual float pdfInner(const Vector3 &v_out, const Vector3 &v_in, const SurfaceIntersection &intersection, ScatterType types = BSDF_ALL) const override; }; } #endif
5,443
C++
.h
69
75.478261
190
0.749348
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,983
RoughConductor.h
g1n0st_AyaRay/src/BSDFs/RoughConductor.h
#ifndef AYA_BSDFS_ROUGHCONDUCTOR_H #define AYA_BSDFS_ROUGHCONDUCTOR_H #include <Core/BSDF.h> namespace Aya { class RoughConductor : public BSDF { private: std::unique_ptr<Texture2D<float>> m_roughness; public: RoughConductor(const Spectrum &color = Spectrum(), float roughness = .3f) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_GLOSSY), BSDFType::RoughConductor, color), m_roughness(new ConstantTexture2D<float>(roughness)) {} RoughConductor(std::unique_ptr<Texture2D<Spectrum>> tex, std::unique_ptr<Texture2D<RGBSpectrum>> normal, float roughness = .3f) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_GLOSSY), BSDFType::RoughConductor, std::move(tex), std::move(normal)), m_roughness(new ConstantTexture2D<float>(roughness)) {} RoughConductor(const char *texture_file, float roughness = .3f) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_GLOSSY), BSDFType::RoughConductor, texture_file), m_roughness(new ConstantTexture2D<float>(roughness)) {} RoughConductor(const char *texture_file, const char *normal_file, float roughness = .3f) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_GLOSSY), BSDFType::RoughConductor, texture_file, normal_file), m_roughness(new ConstantTexture2D<float>(roughness)) {} RoughConductor(const Spectrum &color, char *roughness_texture) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_GLOSSY), BSDFType::RoughConductor, color), m_roughness(new ImageTexture2D<float, float>(roughness_texture)) {} RoughConductor(std::unique_ptr<Texture2D<Spectrum>> tex, std::unique_ptr<Texture2D<RGBSpectrum>> normal, char *roughness_texture) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_GLOSSY), BSDFType::RoughConductor, std::move(tex), std::move(normal)), m_roughness(new ImageTexture2D<float, float>(roughness_texture)) {} RoughConductor(const char *texture_file, char *roughness_texture) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_GLOSSY), BSDFType::RoughConductor, texture_file), m_roughness(new ImageTexture2D<float, float>(roughness_texture)) {} RoughConductor(const char *texture_file, const char *normal_file, char *roughness_texture) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_GLOSSY), BSDFType::RoughConductor, texture_file, normal_file), m_roughness(new ImageTexture2D<float, float>(roughness_texture)) {} RoughConductor(const Spectrum &color, std::unique_ptr<Texture2D<float>> roughness) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_GLOSSY), BSDFType::RoughConductor, color), m_roughness(std::move(roughness)) {} RoughConductor(std::unique_ptr<Texture2D<Spectrum>> tex, std::unique_ptr<Texture2D<RGBSpectrum>> normal, std::unique_ptr<Texture2D<float>> roughness) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_GLOSSY), BSDFType::RoughConductor, std::move(tex), std::move(normal)), m_roughness(std::move(roughness)) {} RoughConductor(const char *texture_file, std::unique_ptr<Texture2D<float>> roughness) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_GLOSSY), BSDFType::RoughConductor, texture_file), m_roughness(std::move(roughness)) {} RoughConductor(const char *texture_file, const char *normal_file, std::unique_ptr<Texture2D<float>> roughness) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_GLOSSY), BSDFType::RoughConductor, texture_file, normal_file), m_roughness(std::move(roughness)) {} virtual Spectrum sample_f(const Vector3 &v_out, const Sample &sample, const SurfaceIntersection &intersection, Vector3 *v_in, float *pdf, ScatterType types = BSDF_ALL, ScatterType *sample_types = nullptr) const override; private: virtual float evalInner(const Vector3 &v_out, const Vector3 &v_in, const SurfaceIntersection &intersection, ScatterType types = BSDF_ALL) const override; virtual float pdfInner(const Vector3 &v_out, const Vector3 &v_in, const SurfaceIntersection &intersection, ScatterType types = BSDF_ALL) const override; }; } #endif
3,842
C++
.h
52
70.596154
155
0.767116
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,984
Disney.h
g1n0st_AyaRay/src/BSDFs/Disney.h
#ifndef AYA_BSDFS_DISNEY_H #define AYA_BSDFS_DISNEY_H #include <Core/BSDF.h> namespace Aya { class Disney : public BSDF { private: std::unique_ptr<Texture2D<float>> mp_roughness; std::unique_ptr<Texture2D<float>> mp_specular; float m_metallic; float m_specularTint; float m_sheen; float m_sheenTint; float m_subsurface; float m_clearCoat; float m_clearCoatGloss; public: Disney(const Spectrum &reflectance, std::unique_ptr<Texture2D<float>> roughness, std::unique_ptr<Texture2D<float>> specular, float metallic = 0.0f, float specular_tint = 0.0f, float sheen = 0.0f, float sheen_tint = 0.5f, float subsurface = 0.0f, float clear_coat = 0.0f, float clear_coat_gloss = 0.0f ) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_DIFFUSE | BSDF_GLOSSY), BSDFType::Disney, reflectance), mp_roughness(std::move(roughness)), mp_specular(std::move(specular)), m_metallic(metallic), m_specularTint(specular_tint), m_sheen(sheen), m_sheenTint(sheen_tint), m_subsurface(subsurface), m_clearCoat(clear_coat), m_clearCoatGloss(clear_coat_gloss) {} Disney(std::unique_ptr<Texture2D<Spectrum>> texture, std::unique_ptr<Texture2D<RGBSpectrum>> normal, std::unique_ptr<Texture2D<float>> roughness, std::unique_ptr<Texture2D<float>> specular, float metallic = 0.0f, float specular_tint = 0.0f, float sheen = 0.0f, float sheen_tint = 0.5f, float subsurface = 0.0f, float clear_coat = 0.0f, float clear_coat_gloss = 0.0f ) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_DIFFUSE | BSDF_GLOSSY), BSDFType::Disney, std::move(texture), std::move(normal)), mp_roughness(std::move(roughness)), mp_specular(std::move(specular)), m_metallic(metallic), m_specularTint(specular_tint), m_sheen(sheen), m_sheenTint(sheen_tint), m_subsurface(subsurface), m_clearCoat(clear_coat), m_clearCoatGloss(clear_coat_gloss) {} Disney(const char *file_tex, std::unique_ptr<Texture2D<float>> roughness, std::unique_ptr<Texture2D<float>> specular, float metallic = 0.0f, float specular_tint = 0.0f, float sheen = 0.0f, float sheen_tint = 0.5f, float subsurface = 0.0f, float clear_coat = 0.0f, float clear_coat_gloss = 0.0f ) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_DIFFUSE | BSDF_GLOSSY), BSDFType::Disney, file_tex), mp_roughness(std::move(roughness)), mp_specular(std::move(specular)), m_metallic(metallic), m_specularTint(specular_tint), m_sheen(sheen), m_sheenTint(sheen_tint), m_subsurface(subsurface), m_clearCoat(clear_coat), m_clearCoatGloss(clear_coat_gloss) {} Disney(const char *file_tex, const char *file_normal, std::unique_ptr<Texture2D<float>> roughness, std::unique_ptr<Texture2D<float>> specular, float metallic = 0.0f, float specular_tint = 0.0f, float sheen = 0.0f, float sheen_tint = 0.5f, float subsurface = 0.0f, float clear_coat = 0.0f, float clear_coat_gloss = 0.0f ) : BSDF(ScatterType(BSDF_REFLECTION | BSDF_DIFFUSE | BSDF_GLOSSY), BSDFType::Disney, file_tex, file_normal), mp_roughness(std::move(roughness)), mp_specular(std::move(specular)), m_metallic(metallic), m_specularTint(specular_tint), m_sheen(sheen), m_sheenTint(sheen_tint), m_subsurface(subsurface), m_clearCoat(clear_coat), m_clearCoatGloss(clear_coat_gloss) {} Spectrum sample_f(const Vector3 &v_out, const Sample &sample, const SurfaceIntersection &intersection, Vector3 *v_in, float *pdf, ScatterType types = BSDF_ALL, ScatterType *sample_types = nullptr) const override; Spectrum f(const Vector3 &v_out, const Vector3 &v_in, const SurfaceIntersection &intersection, ScatterType types = BSDF_ALL) const override; Spectrum evaluate(const Vector3 &l_out, const Vector3 &l_in, const SurfaceIntersection &intersection, ScatterType types = BSDF_ALL) const; void setRoughness(const char *path) { mp_roughness = std::make_unique<ImageTexture2D<float, float>>(path); } void setRoughness(const float roughness) { mp_roughness = std::make_unique<ConstantTexture2D<float>>(roughness); } void setSpecular(const char *path) { mp_specular = std::make_unique<ImageTexture2D<float, float>>(path); } void setSpecular(const float specular) { mp_specular = std::make_unique<ConstantTexture2D<float>>(specular); } private: float pdfInner(const Vector3 &v_out, const Vector3 &v_in, const SurfaceIntersection &intersection, ScatterType types = BSDF_ALL) const override; float evalInner(const Vector3 &v_out, const Vector3 &v_in, const SurfaceIntersection &intersection, ScatterType types = BSDF_ALL) const override; float Fresnel_Schlick(const float cosd) const { float R = 1.f - cosd; float sqr_R = R * R; return sqr_R * sqr_R * R; } float Fresnel_Schlick(const float cosd, const float reflectance) const { float R = 1.f - cosd; float sqr_R = R * R; float fresnel = reflectance + (1.f - reflectance) * sqr_R * sqr_R * R; float fresnel_conductor = fresnelConductor(cosd, .4f, 1.6f); return Lerp(m_metallic, fresnel, fresnel_conductor); } float Fresnel_Schlick_Coat(const float cosd) const { float R = 1.f - cosd; float sqr_R = R * R; float fresnel = .04f + (1.f - .04f) * sqr_R * sqr_R * R; return fresnel; } // Each Disney independent Term float diffuseTerm(const Vector3 &l_out, const Vector3 &l_in, const float IdotH, const float roughness) const { if (m_metallic == 1.f) return 0.f; // Diffuse fresnel - go from 1 at normal incidence to .5 at grazing // and mix in diffuse retro-reflection based on roughness float FL = Fresnel_Schlick(AbsCosTheta(l_in)); float FV = Fresnel_Schlick(AbsCosTheta(l_out)); float F_D90 = .5f + 2.f * IdotH * IdotH * roughness; return (1.f + (F_D90 - 1.f) * FL) * (1.f + (F_D90 - 1.f) * FV) * float(M_1_PI); } float specularTerm(const Vector3 &l_out, const Vector3 &l_in, const Vector3 &wh, const float OdotH, const float roughness, const float specular, const float *fresnel = nullptr) const { if (CosTheta(l_out) * CosTheta(l_in) <= 0.f) return 0.f; float Ds = GGX_D(wh, roughness * roughness); if (Ds == 0.f) return 0.f; float normal_ref = Lerp(specular, .0f, .08f); float Fs = fresnel ? *fresnel : Fresnel_Schlick(OdotH, normal_ref); float rough_G = (.5f + .5f * roughness); float Gs = GGX_G(l_out, l_in, wh, rough_G * rough_G); return Fs * Ds * Gs / (4.f * AbsCosTheta(l_out) * AbsCosTheta(l_in)); } float subsurfaceTerm(const Vector3 &l_out, const Vector3 &l_in, const float IdotH, const float roughness) const { if (m_subsurface == 0.f) return 0.f; float FL = Fresnel_Schlick(AbsCosTheta(l_in)); float FV = Fresnel_Schlick(AbsCosTheta(l_out)); // Based on Hanrahan-Krueger brdf approximation of isotropic bssrdf // 1.25 scale is used to (roughly) preserve albedo // Fss90 used to "flatten" retroreflection based on roughness float Fss90 = IdotH * IdotH * roughness; float Fss = (1.f + (Fss90 - 1.f) * FL) * (1.f + (Fss90 - 1.f) * FV); return 1.25f * (Fss * (1.f / (AbsCosTheta(l_in) + AbsCosTheta(l_out)) - .5f) + .5f) * float(M_1_PI); } float clearCoatTerm(const Vector3 &l_out, const Vector3 &l_in, const Vector3 &wh, const float IdotH, const float roughness) const { if (m_clearCoat == 0.f) return 0.f; float rough = Lerp(roughness, .005f, .1f); // clearcoat (ior = 1.5 -> F0 = 0.04) float Dr = GGX_D(wh, rough); if (Dr == 0.f) return 0.f; float Fr = Fresnel_Schlick_Coat(IdotH); float Gr = GGX_G(l_out, l_in, wh, .25f); return m_clearCoat * Fr * Dr * Gr / (4.f * AbsCosTheta(l_out) * AbsCosTheta(l_in)); } }; } #endif
7,816
C++
.h
189
37.52381
153
0.685319
g1n0st/AyaRay
37
2
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,985
Configuration.h
artillery3d_genius-firmware/Marlin/Configuration.h
/** * Marlin 3D Printer Firmware * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm * * 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 3 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/>. * */ /** * Configuration.h * * Basic settings such as: * * - Type of electronics * - Type of temperature sensor * - Printer geometry * - Endstop configuration * - LCD controller * - Extra features * * Advanced settings can be found in Configuration_adv.h * */ #ifndef CONFIGURATION_H #define CONFIGURATION_H #define CONFIGURATION_H_VERSION 010109 //=========================================================================== //============================= Getting Started ============================= //=========================================================================== /** * Here are some standard links for getting your machine calibrated: * * http://reprap.org/wiki/Calibration * http://youtu.be/wAL9d7FgInk * http://calculator.josefprusa.cz * http://reprap.org/wiki/Triffid_Hunter%27s_Calibration_Guide * http://www.thingiverse.com/thing:5573 * https://sites.google.com/site/repraplogphase/calibration-of-your-reprap * http://www.thingiverse.com/thing:298812 */ //=========================================================================== //============================= DELTA Printer =============================== //=========================================================================== // For a Delta printer start with one of the configuration files in the // example_configurations/delta directory and customize for your machine. // //=========================================================================== //============================= SCARA Printer =============================== //=========================================================================== // For a SCARA printer start with the configuration files in // example_configurations/SCARA and customize for your machine. // //=========================================================================== //============================= HANGPRINTER ================================= //=========================================================================== // For a Hangprinter start with the configuration file in the // example_configurations/hangprinter directory and customize for your machine. // // @section info // User-specified version info of this build to display in [Pronterface, etc] terminal window during // startup. Implementation of an idea by Prof Braino to inform user that any changes made to this // build by the user have been successfully uploaded into firmware. #define STRING_CONFIG_H_AUTHOR "(none, default config)" // Who made the changes. //#define SHOW_BOOTSCREEN //#define STRING_SPLASH_LINE1 SHORT_BUILD_VERSION // will be shown during bootup in line 1 //#define STRING_SPLASH_LINE2 WEBSITE_URL // will be shown during bootup in line 2 /** * *** VENDORS PLEASE READ *** * * Marlin allows you to add a custom boot image for Graphical LCDs. * With this option Marlin will first show your custom screen followed * by the standard Marlin logo with version number and web URL. * * We encourage you to take advantage of this new feature and we also * respectfully request that you retain the unmodified Marlin boot screen. */ // Enable to show the bitmap in Marlin/_Bootscreen.h on startup. //#define SHOW_CUSTOM_BOOTSCREEN // Enable to show the bitmap in Marlin/_Statusscreen.h on the status screen. //#define CUSTOM_STATUS_SCREEN_IMAGE // @section machine /** * Select the serial port on the board to use for communication with the host. * This allows the connection of wireless adapters (for instance) to non-default port pins. * Serial port 0 is always used by the Arduino bootloader regardless of this setting. * * :[0, 1, 2, 3, 4, 5, 6, 7] */ #define SERIAL_PORT 0 /** * This setting determines the communication speed of the printer. * * 250000 works in most cases, but you might try a lower speed if * you commonly experience drop-outs during host printing. * You may try up to 1000000 to speed up SD file transfer. * * :[2400, 9600, 19200, 38400, 57600, 115200, 250000, 500000, 1000000] */ #define BAUDRATE 250000 // Enable the Bluetooth serial interface on AT90USB devices //#define BLUETOOTH // The following define selects which electronics board you have. // Please choose the name from boards.h that matches your setup #ifndef MOTHERBOARD #define MOTHERBOARD BOARD_MKS_GEN_L #endif // Optional custom name for your RepStrap or other custom machine // Displayed in the LCD "Ready" message //#define CUSTOM_MACHINE_NAME "3D Printer" // Define this to set a unique identifier for this printer, (Used by some programs to differentiate between machines) // You can use an online service to generate a random UUID. (eg http://www.uuidgenerator.net/version4) //#define MACHINE_UUID "00000000-0000-0000-0000-000000000000" // @section extruder // This defines the number of extruders // :[1, 2, 3, 4, 5] #define EXTRUDERS 1 // Generally expected filament diameter (1.75, 2.85, 3.0, ...). Used for Volumetric, Filament Width Sensor, etc. #define DEFAULT_NOMINAL_FILAMENT_DIA 1.75 // For Cyclops or any "multi-extruder" that shares a single nozzle. //#define SINGLENOZZLE /** * Průša MK2 Single Nozzle Multi-Material Multiplexer, and variants. * * This device allows one stepper driver on a control board to drive * two to eight stepper motors, one at a time, in a manner suitable * for extruders. * * This option only allows the multiplexer to switch on tool-change. * Additional options to configure custom E moves are pending. */ //#define MK2_MULTIPLEXER #if ENABLED(MK2_MULTIPLEXER) // Override the default DIO selector pins here, if needed. // Some pins files may provide defaults for these pins. //#define E_MUX0_PIN 40 // Always Required //#define E_MUX1_PIN 42 // Needed for 3 to 8 steppers //#define E_MUX2_PIN 44 // Needed for 5 to 8 steppers #endif // A dual extruder that uses a single stepper motor //#define SWITCHING_EXTRUDER #if ENABLED(SWITCHING_EXTRUDER) #define SWITCHING_EXTRUDER_SERVO_NR 0 #define SWITCHING_EXTRUDER_SERVO_ANGLES { 0, 90 } // Angles for E0, E1[, E2, E3] #if EXTRUDERS > 3 #define SWITCHING_EXTRUDER_E23_SERVO_NR 1 #endif #endif // A dual-nozzle that uses a servomotor to raise/lower one of the nozzles //#define SWITCHING_NOZZLE #if ENABLED(SWITCHING_NOZZLE) #define SWITCHING_NOZZLE_SERVO_NR 0 #define SWITCHING_NOZZLE_SERVO_ANGLES { 0, 90 } // Angles for E0, E1 //#define HOTEND_OFFSET_Z { 0.0, 0.0 } #endif /** * Two separate X-carriages with extruders that connect to a moving part * via a magnetic docking mechanism. Requires SOL1_PIN and SOL2_PIN. */ //#define PARKING_EXTRUDER #if ENABLED(PARKING_EXTRUDER) #define PARKING_EXTRUDER_SOLENOIDS_INVERT // If enabled, the solenoid is NOT magnetized with applied voltage #define PARKING_EXTRUDER_SOLENOIDS_PINS_ACTIVE LOW // LOW or HIGH pin signal energizes the coil #define PARKING_EXTRUDER_SOLENOIDS_DELAY 250 // Delay (ms) for magnetic field. No delay if 0 or not defined. #define PARKING_EXTRUDER_PARKING_X { -78, 184 } // X positions for parking the extruders #define PARKING_EXTRUDER_GRAB_DISTANCE 1 // mm to move beyond the parking point to grab the extruder #define PARKING_EXTRUDER_SECURITY_RAISE 5 // Z-raise before parking #define HOTEND_OFFSET_Z { 0.0, 1.3 } // Z-offsets of the two hotends. The first must be 0. #endif /** * "Mixing Extruder" * - Adds G-codes M163 and M164 to set and "commit" the current mix factors. * - Extends the stepping routines to move multiple steppers in proportion to the mix. * - Optional support for Repetier Firmware's 'M164 S<index>' supporting virtual tools. * - This implementation supports up to two mixing extruders. * - Enable DIRECT_MIXING_IN_G1 for M165 and mixing in G1 (from Pia Taubert's reference implementation). */ //#define MIXING_EXTRUDER #if ENABLED(MIXING_EXTRUDER) #define MIXING_STEPPERS 2 // Number of steppers in your mixing extruder #define MIXING_VIRTUAL_TOOLS 16 // Use the Virtual Tool method with M163 and M164 //#define DIRECT_MIXING_IN_G1 // Allow ABCDHI mix factors in G1 movement commands #endif // Offset of the extruders (uncomment if using more than one and relying on firmware to position when changing). // The offset has to be X=0, Y=0 for the extruder 0 hotend (default extruder). // For the other hotends it is their distance from the extruder 0 hotend. //#define HOTEND_OFFSET_X {0.0, 20.00} // (in mm) for each extruder, offset of the hotend on the X axis //#define HOTEND_OFFSET_Y {0.0, 5.00} // (in mm) for each extruder, offset of the hotend on the Y axis // @section machine /** * Select your power supply here. Use 0 if you haven't connected the PS_ON_PIN * * 0 = No Power Switch * 1 = ATX * 2 = X-Box 360 203Watts (the blue wire connected to PS_ON and the red wire to VCC) * * :{ 0:'No power switch', 1:'ATX', 2:'X-Box 360' } */ #define POWER_SUPPLY 0 #if POWER_SUPPLY > 0 // Enable this option to leave the PSU off at startup. // Power to steppers and heaters will need to be turned on with M80. //#define PS_DEFAULT_OFF //#define AUTO_POWER_CONTROL // Enable automatic control of the PS_ON pin #if ENABLED(AUTO_POWER_CONTROL) #define AUTO_POWER_FANS // Turn on PSU if fans need power #define AUTO_POWER_E_FANS #define AUTO_POWER_CONTROLLERFAN #define POWER_TIMEOUT 30 #endif #endif // @section temperature //=========================================================================== //============================= Thermal Settings ============================ //=========================================================================== /** * --NORMAL IS 4.7kohm PULLUP!-- 1kohm pullup can be used on hotend sensor, using correct resistor and table * * Temperature sensors available: * * -4 : thermocouple with AD8495 * -3 : thermocouple with MAX31855 (only for sensor 0) * -2 : thermocouple with MAX6675 (only for sensor 0) * -1 : thermocouple with AD595 * 0 : not used * 1 : 100k thermistor - best choice for EPCOS 100k (4.7k pullup) * 2 : 200k thermistor - ATC Semitec 204GT-2 (4.7k pullup) * 3 : Mendel-parts thermistor (4.7k pullup) * 4 : 10k thermistor !! do not use it for a hotend. It gives bad resolution at high temp. !! * 5 : 100K thermistor - ATC Semitec 104GT-2/104NT-4-R025H42G (Used in ParCan & J-Head) (4.7k pullup) * 501 : 100K Zonestar (Tronxy X3A) Thermistor * 6 : 100k EPCOS - Not as accurate as table 1 (created using a fluke thermocouple) (4.7k pullup) * 7 : 100k Honeywell thermistor 135-104LAG-J01 (4.7k pullup) * 71 : 100k Honeywell thermistor 135-104LAF-J01 (4.7k pullup) * 8 : 100k 0603 SMD Vishay NTCS0603E3104FXT (4.7k pullup) * 9 : 100k GE Sensing AL03006-58.2K-97-G1 (4.7k pullup) * 10 : 100k RS thermistor 198-961 (4.7k pullup) * 11 : 100k beta 3950 1% thermistor (4.7k pullup) * 12 : 100k 0603 SMD Vishay NTCS0603E3104FXT (4.7k pullup) (calibrated for Makibox hot bed) * 13 : 100k Hisens 3950 1% up to 300°C for hotend "Simple ONE " & "Hotend "All In ONE" * 15 : 100k thermistor calibration for JGAurora A5 hotend * 20 : the PT100 circuit found in the Ultimainboard V2.x * 60 : 100k Maker's Tool Works Kapton Bed Thermistor beta=3950 * 66 : 4.7M High Temperature thermistor from Dyze Design * 70 : the 100K thermistor found in the bq Hephestos 2 * 75 : 100k Generic Silicon Heat Pad with NTC 100K MGB18-104F39050L32 thermistor * * 1k ohm pullup tables - This is atypical, and requires changing out the 4.7k pullup for 1k. * (but gives greater accuracy and more stable PID) * 51 : 100k thermistor - EPCOS (1k pullup) * 52 : 200k thermistor - ATC Semitec 204GT-2 (1k pullup) * 55 : 100k thermistor - ATC Semitec 104GT-2 (Used in ParCan & J-Head) (1k pullup) * * 1047 : Pt1000 with 4k7 pullup * 1010 : Pt1000 with 1k pullup (non standard) * 147 : Pt100 with 4k7 pullup * 110 : Pt100 with 1k pullup (non standard) * * Use these for Testing or Development purposes. NEVER for production machine. * 998 : Dummy Table that ALWAYS reads 25°C or the temperature defined below. * 999 : Dummy Table that ALWAYS reads 100°C or the temperature defined below. * * :{ '0': "Not used", '1':"100k / 4.7k - EPCOS", '2':"200k / 4.7k - ATC Semitec 204GT-2", '3':"Mendel-parts / 4.7k", '4':"10k !! do not use for a hotend. Bad resolution at high temp. !!", '5':"100K / 4.7k - ATC Semitec 104GT-2 (Used in ParCan & J-Head)", '501':"100K Zonestar (Tronxy X3A)", '6':"100k / 4.7k EPCOS - Not as accurate as Table 1", '7':"100k / 4.7k Honeywell 135-104LAG-J01", '8':"100k / 4.7k 0603 SMD Vishay NTCS0603E3104FXT", '9':"100k / 4.7k GE Sensing AL03006-58.2K-97-G1", '10':"100k / 4.7k RS 198-961", '11':"100k / 4.7k beta 3950 1%", '12':"100k / 4.7k 0603 SMD Vishay NTCS0603E3104FXT (calibrated for Makibox hot bed)", '13':"100k Hisens 3950 1% up to 300°C for hotend 'Simple ONE ' & hotend 'All In ONE'", '20':"PT100 (Ultimainboard V2.x)", '51':"100k / 1k - EPCOS", '52':"200k / 1k - ATC Semitec 204GT-2", '55':"100k / 1k - ATC Semitec 104GT-2 (Used in ParCan & J-Head)", '60':"100k Maker's Tool Works Kapton Bed Thermistor beta=3950", '66':"Dyze Design 4.7M High Temperature thermistor", '70':"the 100K thermistor found in the bq Hephestos 2", '71':"100k / 4.7k Honeywell 135-104LAF-J01", '147':"Pt100 / 4.7k", '1047':"Pt1000 / 4.7k", '110':"Pt100 / 1k (non-standard)", '1010':"Pt1000 / 1k (non standard)", '-4':"Thermocouple + AD8495", '-3':"Thermocouple + MAX31855 (only for sensor 0)", '-2':"Thermocouple + MAX6675 (only for sensor 0)", '-1':"Thermocouple + AD595",'998':"Dummy 1", '999':"Dummy 2" } */ #define TEMP_SENSOR_0 1 #define TEMP_SENSOR_1 0 #define TEMP_SENSOR_2 0 #define TEMP_SENSOR_3 0 #define TEMP_SENSOR_4 0 #define TEMP_SENSOR_BED 1 #define TEMP_SENSOR_CHAMBER 0 // Dummy thermistor constant temperature readings, for use with 998 and 999 #define DUMMY_THERMISTOR_998_VALUE 25 #define DUMMY_THERMISTOR_999_VALUE 100 // Use temp sensor 1 as a redundant sensor with sensor 0. If the readings // from the two sensors differ too much the print will be aborted. //#define TEMP_SENSOR_1_AS_REDUNDANT #define MAX_REDUNDANT_TEMP_SENSOR_DIFF 10 // Extruder temperature must be close to target for this long before M109 returns success #define TEMP_RESIDENCY_TIME 10 // (seconds) #define TEMP_HYSTERESIS 5 // (degC) range of +/- temperatures considered "close" to the target one #define TEMP_WINDOW 1 // (degC) Window around target to start the residency timer x degC early. // Bed temperature must be close to target for this long before M190 returns success #define TEMP_BED_RESIDENCY_TIME 10 // (seconds) #define TEMP_BED_HYSTERESIS 3 // (degC) range of +/- temperatures considered "close" to the target one #define TEMP_BED_WINDOW 1 // (degC) Window around target to start the residency timer x degC early. // The minimal temperature defines the temperature below which the heater will not be enabled It is used // to check that the wiring to the thermistor is not broken. // Otherwise this would lead to the heater being powered on all the time. #define HEATER_0_MINTEMP 5 #define HEATER_1_MINTEMP 5 #define HEATER_2_MINTEMP 5 #define HEATER_3_MINTEMP 5 #define HEATER_4_MINTEMP 5 #define BED_MINTEMP 5 // When temperature exceeds max temp, your heater will be switched off. // This feature exists to protect your hotend from overheating accidentally, but *NOT* from thermistor short/failure! // You should use MINTEMP for thermistor short/failure protection. #define HEATER_0_MAXTEMP 275 #define HEATER_1_MAXTEMP 275 #define HEATER_2_MAXTEMP 275 #define HEATER_3_MAXTEMP 275 #define HEATER_4_MAXTEMP 275 #define BED_MAXTEMP 150 //=========================================================================== //============================= PID Settings ================================ //=========================================================================== // PID Tuning Guide here: http://reprap.org/wiki/PID_Tuning // Comment the following line to disable PID and enable bang-bang. #define PIDTEMP #define BANG_MAX 255 // Limits current to nozzle while in bang-bang mode; 255=full current #define PID_MAX BANG_MAX // Limits current to nozzle while PID is active (see PID_FUNCTIONAL_RANGE below); 255=full current #define PID_K1 0.95 // Smoothing factor within any PID loop #if ENABLED(PIDTEMP) //#define PID_AUTOTUNE_MENU // Add PID Autotune to the LCD "Temperature" menu to run M303 and apply the result. //#define PID_DEBUG // Sends debug data to the serial port. //#define PID_OPENLOOP 1 // Puts PID in open loop. M104/M140 sets the output power from 0 to PID_MAX //#define SLOW_PWM_HEATERS // PWM with very low frequency (roughly 0.125Hz=8s) and minimum state time of approximately 1s useful for heaters driven by a relay //#define PID_PARAMS_PER_HOTEND // Uses separate PID parameters for each extruder (useful for mismatched extruders) // Set/get with gcode: M301 E[extruder number, 0-2] #define PID_FUNCTIONAL_RANGE 10 // If the temperature difference between the target temperature and the actual temperature // is more than PID_FUNCTIONAL_RANGE then the PID will be shut off and the heater will be set to min/max. // If you are using a pre-configured hotend then you can use one of the value sets by uncommenting it // Ultimaker #define DEFAULT_Kp 9.31 #define DEFAULT_Ki 0.57 #define DEFAULT_Kd 37.76 // MakerGear //#define DEFAULT_Kp 7.0 //#define DEFAULT_Ki 0.1 //#define DEFAULT_Kd 12 // Mendel Parts V9 on 12V //#define DEFAULT_Kp 63.0 //#define DEFAULT_Ki 2.25 //#define DEFAULT_Kd 440 #endif // PIDTEMP //=========================================================================== //============================= PID > Bed Temperature Control =============== //=========================================================================== /** * PID Bed Heating * * If this option is enabled set PID constants below. * If this option is disabled, bang-bang will be used and BED_LIMIT_SWITCHING will enable hysteresis. * * The PID frequency will be the same as the extruder PWM. * If PID_dT is the default, and correct for the hardware/configuration, that means 7.689Hz, * which is fine for driving a square wave into a resistive load and does not significantly * impact FET heating. This also works fine on a Fotek SSR-10DA Solid State Relay into a 250W * heater. If your configuration is significantly different than this and you don't understand * the issues involved, don't use bed PID until someone else verifies that your hardware works. */ #define PIDTEMPBED //#define BED_LIMIT_SWITCHING /** * Max Bed Power * Applies to all forms of bed control (PID, bang-bang, and bang-bang with hysteresis). * When set to any value below 255, enables a form of PWM to the bed that acts like a divider * so don't use it unless you are OK with PWM on your bed. (See the comment on enabling PIDTEMPBED) */ #define MAX_BED_POWER 255 // limits duty cycle to bed; 255=full current #if ENABLED(PIDTEMPBED) //#define PID_BED_DEBUG // Sends debug data to the serial port. //120V 250W silicone heater into 4mm borosilicate (MendelMax 1.5+) //from FOPDT model - kp=.39 Tp=405 Tdead=66, Tc set to 79.2, aggressive factor of .15 (vs .1, 1, 10) #define DEFAULT_bedKp 92.46 #define DEFAULT_bedKi 16.12 #define DEFAULT_bedKd 132.55 //120V 250W silicone heater into 4mm borosilicate (MendelMax 1.5+) //from pidautotune //#define DEFAULT_bedKp 97.1 //#define DEFAULT_bedKi 1.41 //#define DEFAULT_bedKd 1675.16 // FIND YOUR OWN: "M303 E-1 C8 S90" to run autotune on the bed at 90 degreesC for 8 cycles. #endif // PIDTEMPBED // @section extruder /** * Prevent extrusion if the temperature is below EXTRUDE_MINTEMP. * Add M302 to set the minimum extrusion temperature and/or turn * cold extrusion prevention on and off. * * *** IT IS HIGHLY RECOMMENDED TO LEAVE THIS OPTION ENABLED! *** */ #define PREVENT_COLD_EXTRUSION #define EXTRUDE_MINTEMP 170 /** * Prevent a single extrusion longer than EXTRUDE_MAXLENGTH. * Note: For Bowden Extruders make this large enough to allow load/unload. */ #define PREVENT_LENGTHY_EXTRUDE #define EXTRUDE_MAXLENGTH 200 //=========================================================================== //======================== Thermal Runaway Protection ======================= //=========================================================================== /** * Thermal Protection provides additional protection to your printer from damage * and fire. Marlin always includes safe min and max temperature ranges which * protect against a broken or disconnected thermistor wire. * * The issue: If a thermistor falls out, it will report the much lower * temperature of the air in the room, and the the firmware will keep * the heater on. * * If you get "Thermal Runaway" or "Heating failed" errors the * details can be tuned in Configuration_adv.h */ #define THERMAL_PROTECTION_HOTENDS // Enable thermal protection for all extruders #define THERMAL_PROTECTION_BED // Enable thermal protection for the heated bed //=========================================================================== //============================= Mechanical Settings ========================= //=========================================================================== // @section machine // Uncomment one of these options to enable CoreXY, CoreXZ, or CoreYZ kinematics // either in the usual order or reversed //#define COREXY //#define COREXZ //#define COREYZ //#define COREYX //#define COREZX //#define COREZY //=========================================================================== //============================== Endstop Settings =========================== //=========================================================================== // @section homing // Specify here all the endstop connectors that are connected to any endstop or probe. // Almost all printers will be using one per axis. Probes will use one or more of the // extra connectors. Leave undefined any used for non-endstop and non-probe purposes. #define USE_XMIN_PLUG #define USE_YMIN_PLUG #define USE_ZMIN_PLUG //#define USE_XMAX_PLUG //#define USE_YMAX_PLUG //#define USE_ZMAX_PLUG // Enable pullup for all endstops to prevent a floating state #define ENDSTOPPULLUPS #if DISABLED(ENDSTOPPULLUPS) // Disable ENDSTOPPULLUPS to set pullups individually //#define ENDSTOPPULLUP_XMAX //#define ENDSTOPPULLUP_YMAX //#define ENDSTOPPULLUP_ZMAX //#define ENDSTOPPULLUP_XMIN //#define ENDSTOPPULLUP_YMIN //#define ENDSTOPPULLUP_ZMIN //#define ENDSTOPPULLUP_ZMIN_PROBE #endif // Mechanical endstop with COM to ground and NC to Signal uses "false" here (most common setup). #define X_MIN_ENDSTOP_INVERTING true // set to true to invert the logic of the endstop. #define Y_MIN_ENDSTOP_INVERTING true // set to true to invert the logic of the endstop. #define Z_MIN_ENDSTOP_INVERTING true // set to true to invert the logic of the endstop. #define X_MAX_ENDSTOP_INVERTING false // set to true to invert the logic of the endstop. #define Y_MAX_ENDSTOP_INVERTING false // set to true to invert the logic of the endstop. #define Z_MAX_ENDSTOP_INVERTING false // set to true to invert the logic of the endstop. #define Z_MIN_PROBE_ENDSTOP_INVERTING false // set to true to invert the logic of the probe. /** * Stepper Drivers * * These settings allow Marlin to tune stepper driver timing and enable advanced options for * stepper drivers that support them. You may also override timing options in Configuration_adv.h. * * A4988 is assumed for unspecified drivers. * * Options: A4988, DRV8825, LV8729, L6470, TB6560, TB6600, TMC2100, * TMC2130, TMC2130_STANDALONE, TMC2208, TMC2208_STANDALONE, * TMC26X, TMC26X_STANDALONE, TMC2660, TMC2660_STANDALONE, * TMC5130, TMC5130_STANDALONE * :['A4988', 'DRV8825', 'LV8729', 'L6470', 'TB6560', 'TB6600', 'TMC2100', 'TMC2130', 'TMC2130_STANDALONE', 'TMC2208', 'TMC2208_STANDALONE', 'TMC26X', 'TMC26X_STANDALONE', 'TMC2660', 'TMC2660_STANDALONE', 'TMC5130', 'TMC5130_STANDALONE'] */ #define X_DRIVER_TYPE TMC2100 #define Y_DRIVER_TYPE TMC2100 #define Z_DRIVER_TYPE TMC2100 //#define X2_DRIVER_TYPE TMC2100 //#define Y2_DRIVER_TYPE TMC2100 #define Z2_DRIVER_TYPE TMC2100 #define E0_DRIVER_TYPE TMC2100 //#define E1_DRIVER_TYPE TMC2100 //#define E2_DRIVER_TYPE TMC2100 //#define E3_DRIVER_TYPE TMC2100 //#define E4_DRIVER_TYPE TMC2100 // Enable this feature if all enabled endstop pins are interrupt-capable. // This will remove the need to poll the interrupt pins, saving many CPU cycles. //#define ENDSTOP_INTERRUPTS_FEATURE /** * Endstop Noise Filter * * Enable this option if endstops falsely trigger due to noise. * NOTE: Enabling this feature means adds an error of +/-0.2mm, so homing * will end up at a slightly different position on each G28. This will also * reduce accuracy of some bed probes. * For mechanical switches, the better approach to reduce noise is to install * a 100 nanofarads ceramic capacitor in parallel with the switch, making it * essentially noise-proof without sacrificing accuracy. * This option also increases MCU load when endstops or the probe are enabled. * So this is not recommended. USE AT YOUR OWN RISK. * (This feature is not required for common micro-switches mounted on PCBs * based on the Makerbot design, since they already include the 100nF capacitor.) */ #define ENDSTOP_NOISE_FILTER //============================================================================= //============================== Movement Settings ============================ //============================================================================= // @section motion /** * Default Settings * * These settings can be reset by M502 * * Note that if EEPROM is enabled, saved values will override these. */ /** * With this option each E stepper can have its own factors for the * following movement settings. If fewer factors are given than the * total number of extruders, the last value applies to the rest. */ //#define DISTINCT_E_FACTORS /** * Default Axis Steps Per Unit (steps/mm) * Override with M92 * X, Y, Z, E0 [, E1[, E2[, E3[, E4]]]] */ #define DEFAULT_AXIS_STEPS_PER_UNIT { 80.121, 80.121, 399.778, 445 } /** * Default Max Feed Rate (mm/s) * Override with M203 * X, Y, Z, E0 [, E1[, E2[, E3[, E4]]]] */ #define DEFAULT_MAX_FEEDRATE { 300, 300, 50, 40 } /** * Default Max Acceleration (change/s) change = mm/s * (Maximum start speed for accelerated moves) * Override with M201 * X, Y, Z, E0 [, E1[, E2[, E3[, E4]]]] */ #define DEFAULT_MAX_ACCELERATION { 2000, 2000, 100, 10000 } /** * Default Acceleration (change/s) change = mm/s * Override with M204 * * M204 P Acceleration * M204 R Retract Acceleration * M204 T Travel Acceleration */ #define DEFAULT_ACCELERATION 800 // X, Y, Z and E acceleration for printing moves #define DEFAULT_RETRACT_ACCELERATION 10000 // E acceleration for retracts #define DEFAULT_TRAVEL_ACCELERATION 2000 // X, Y, Z acceleration for travel (non printing) moves /** * Default Jerk (mm/s) * Override with M205 X Y Z E * * "Jerk" specifies the minimum speed change that requires acceleration. * When changing speed and direction, if the difference is less than the * value set here, it may happen instantaneously. */ #define DEFAULT_XJERK 8.0 #define DEFAULT_YJERK 8.0 #define DEFAULT_ZJERK 0.3 #define DEFAULT_EJERK 5.0 /** * S-Curve Acceleration * * This option eliminates vibration during printing by fitting a Bézier * curve to move acceleration, producing much smoother direction changes. * * See https://github.com/synthetos/TinyG/wiki/Jerk-Controlled-Motion-Explained */ #define S_CURVE_ACCELERATION //=========================================================================== //============================= Z Probe Options ============================= //=========================================================================== // @section probes // // See http://marlinfw.org/docs/configuration/probes.html // /** * Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN * * Enable this option for a probe connected to the Z Min endstop pin. */ #define Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN /** * Z_MIN_PROBE_ENDSTOP * * Enable this option for a probe connected to any pin except Z-Min. * (By default Marlin assumes the Z-Max endstop pin.) * To use a custom Z Probe pin, set Z_MIN_PROBE_PIN below. * * - The simplest option is to use a free endstop connector. * - Use 5V for powered (usually inductive) sensors. * * - RAMPS 1.3/1.4 boards may use the 5V, GND, and Aux4->D32 pin: * - For simple switches connect... * - normally-closed switches to GND and D32. * - normally-open switches to 5V and D32. * * WARNING: Setting the wrong pin may have unexpected and potentially * disastrous consequences. Use with caution and do your homework. * */ //#define Z_MIN_PROBE_ENDSTOP /** * Probe Type * * Allen Key Probes, Servo Probes, Z-Sled Probes, FIX_MOUNTED_PROBE, etc. * Activate one of these to use Auto Bed Leveling below. */ /** * The "Manual Probe" provides a means to do "Auto" Bed Leveling without a probe. * Use G29 repeatedly, adjusting the Z height at each point with movement commands * or (with LCD_BED_LEVELING) the LCD controller. */ //#define PROBE_MANUALLY //#define MANUAL_PROBE_START_Z 0.2 /** * A Fix-Mounted Probe either doesn't deploy or needs manual deployment. * (e.g., an inductive probe or a nozzle-based probe-switch.) */ //#define FIX_MOUNTED_PROBE /** * Z Servo Probe, such as an endstop switch on a rotating arm. */ //#define Z_PROBE_SERVO_NR 0 // Defaults to SERVO 0 connector. //#define Z_SERVO_ANGLES {70,0} // Z Servo Deploy and Stow angles /** * The BLTouch probe uses a Hall effect sensor and emulates a servo. */ //#define BLTOUCH #if ENABLED(BLTOUCH) //#define BLTOUCH_DELAY 375 // (ms) Enable and increase if needed #endif /** * Enable one or more of the following if probing seems unreliable. * Heaters and/or fans can be disabled during probing to minimize electrical * noise. A delay can also be added to allow noise and vibration to settle. * These options are most useful for the BLTouch probe, but may also improve * readings with inductive probes and piezo sensors. */ //#define PROBING_HEATERS_OFF // Turn heaters off when probing #if ENABLED(PROBING_HEATERS_OFF) //#define WAIT_FOR_BED_HEATER // Wait for bed to heat back up between probes (to improve accuracy) #endif //#define PROBING_FANS_OFF // Turn fans off when probing //#define DELAY_BEFORE_PROBING 200 // (ms) To prevent vibrations from triggering piezo sensors // A probe that is deployed and stowed with a solenoid pin (SOL1_PIN) //#define SOLENOID_PROBE // A sled-mounted probe like those designed by Charles Bell. //#define Z_PROBE_SLED //#define SLED_DOCKING_OFFSET 5 // The extra distance the X axis must travel to pickup the sled. 0 should be fine but you can push it further if you'd like. // // For Z_PROBE_ALLEN_KEY see the Delta example configurations. // /** * Z Probe to nozzle (X,Y) offset, relative to (0, 0). * X and Y offsets must be integers. * * In the following example the X and Y offsets are both positive: * #define X_PROBE_OFFSET_FROM_EXTRUDER 10 * #define Y_PROBE_OFFSET_FROM_EXTRUDER 10 * * +-- BACK ---+ * | | * L | (+) P | R <-- probe (20,20) * E | | I * F | (-) N (+) | G <-- nozzle (10,10) * T | | H * | (-) | T * | | * O-- FRONT --+ * (0,0) */ #define X_PROBE_OFFSET_FROM_EXTRUDER 10 // X offset: -left +right [of the nozzle] #define Y_PROBE_OFFSET_FROM_EXTRUDER 10 // Y offset: -front +behind [the nozzle] #define Z_PROBE_OFFSET_FROM_EXTRUDER 0 // Z offset: -below +above [the nozzle] // Certain types of probes need to stay away from edges #define MIN_PROBE_EDGE 10 // X and Y axis travel speed (mm/m) between probes #define XY_PROBE_SPEED 8000 // Feedrate (mm/m) for the first approach when double-probing (MULTIPLE_PROBING == 2) #define Z_PROBE_SPEED_FAST HOMING_FEEDRATE_Z // Feedrate (mm/m) for the "accurate" probe of each point #define Z_PROBE_SPEED_SLOW (Z_PROBE_SPEED_FAST / 2) // The number of probes to perform at each point. // Set to 2 for a fast/slow probe, using the second probe result. // Set to 3 or more for slow probes, averaging the results. //#define MULTIPLE_PROBING 2 /** * Z probes require clearance when deploying, stowing, and moving between * probe points to avoid hitting the bed and other hardware. * Servo-mounted probes require extra space for the arm to rotate. * Inductive probes need space to keep from triggering early. * * Use these settings to specify the distance (mm) to raise the probe (or * lower the bed). The values set here apply over and above any (negative) * probe Z Offset set with Z_PROBE_OFFSET_FROM_EXTRUDER, M851, or the LCD. * Only integer values >= 1 are valid here. * * Example: `M851 Z-5` with a CLEARANCE of 4 => 9mm from bed to nozzle. * But: `M851 Z+1` with a CLEARANCE of 2 => 2mm from bed to nozzle. */ #define Z_CLEARANCE_DEPLOY_PROBE 10 // Z Clearance for Deploy/Stow #define Z_CLEARANCE_BETWEEN_PROBES 5 // Z Clearance between probe points #define Z_CLEARANCE_MULTI_PROBE 5 // Z Clearance between multiple probes //#define Z_AFTER_PROBING 5 // Z position after probing is done #define Z_PROBE_LOW_POINT -2 // Farthest distance below the trigger-point to go before stopping // For M851 give a range for adjusting the Z probe offset #define Z_PROBE_OFFSET_RANGE_MIN -20 #define Z_PROBE_OFFSET_RANGE_MAX 20 // Enable the M48 repeatability test to test probe accuracy //#define Z_MIN_PROBE_REPEATABILITY_TEST // For Inverting Stepper Enable Pins (Active Low) use 0, Non Inverting (Active High) use 1 // :{ 0:'Low', 1:'High' } #define X_ENABLE_ON 0 #define Y_ENABLE_ON 0 #define Z_ENABLE_ON 0 #define E_ENABLE_ON 0 // For all extruders // Disables axis stepper immediately when it's not being used. // WARNING: When motors turn off there is a chance of losing position accuracy! #define DISABLE_X false #define DISABLE_Y false #define DISABLE_Z false // Warn on display about possibly reduced accuracy //#define DISABLE_REDUCED_ACCURACY_WARNING // @section extruder #define DISABLE_E false // For all extruders #define DISABLE_INACTIVE_EXTRUDER true // Keep only the active extruder enabled. // @section machine // Invert the stepper direction. Change (or reverse the motor connector) if an axis goes the wrong way. #define INVERT_X_DIR false #define INVERT_Y_DIR false #define INVERT_Z_DIR true // @section extruder // For direct drive extruder v9 set to true, for geared extruder set to false. #define INVERT_E0_DIR false #define INVERT_E1_DIR false #define INVERT_E2_DIR false #define INVERT_E3_DIR false #define INVERT_E4_DIR false // @section homing //#define NO_MOTION_BEFORE_HOMING // Inhibit movement until all axes have been homed //#define UNKNOWN_Z_NO_RAISE // Don't raise Z (lower the bed) if Z is "unknown." For beds that fall when Z is powered off. //#define Z_HOMING_HEIGHT 4 // (in mm) Minimal z height before homing (G28) for Z clearance above the bed, clamps, ... // Be sure you have this distance over your Z_MAX_POS in case. // Direction of endstops when homing; 1=MAX, -1=MIN // :[-1,1] #define X_HOME_DIR -1 #define Y_HOME_DIR -1 #define Z_HOME_DIR -1 // @section machine // The size of the print bed #define X_BED_SIZE 220 #define Y_BED_SIZE 220 // Travel limits (mm) after homing, corresponding to endstop positions. #define X_MIN_POS 0 #define Y_MIN_POS -5 #define Z_MIN_POS 0 #define X_MAX_POS X_BED_SIZE #define Y_MAX_POS Y_BED_SIZE #define Z_MAX_POS 250 /** * Software Endstops * * - Prevent moves outside the set machine bounds. * - Individual axes can be disabled, if desired. * - X and Y only apply to Cartesian robots. * - Use 'M211' to set software endstops on/off or report current state */ // Min software endstops constrain movement within minimum coordinate bounds #define MIN_SOFTWARE_ENDSTOPS #if ENABLED(MIN_SOFTWARE_ENDSTOPS) #define MIN_SOFTWARE_ENDSTOP_X #define MIN_SOFTWARE_ENDSTOP_Y #define MIN_SOFTWARE_ENDSTOP_Z #endif // Max software endstops constrain movement within maximum coordinate bounds #define MAX_SOFTWARE_ENDSTOPS #if ENABLED(MAX_SOFTWARE_ENDSTOPS) #define MAX_SOFTWARE_ENDSTOP_X #define MAX_SOFTWARE_ENDSTOP_Y #define MAX_SOFTWARE_ENDSTOP_Z #endif #if ENABLED(MIN_SOFTWARE_ENDSTOPS) || ENABLED(MAX_SOFTWARE_ENDSTOPS) //#define SOFT_ENDSTOPS_MENU_ITEM // Enable/Disable software endstops from the LCD #endif /** * Filament Runout Sensors * Mechanical or opto endstops are used to check for the presence of filament. * * RAMPS-based boards use SERVO3_PIN for the first runout sensor. * For other boards you may need to define FIL_RUNOUT_PIN, FIL_RUNOUT2_PIN, etc. * By default the firmware assumes HIGH=FILAMENT PRESENT. */ //#define FILAMENT_RUNOUT_SENSOR #if ENABLED(FILAMENT_RUNOUT_SENSOR) #define NUM_RUNOUT_SENSORS 1 // Number of sensors, up to one per extruder. Define a FIL_RUNOUT#_PIN for each. #define FIL_RUNOUT_INVERTING false // set to true to invert the logic of the sensor. #define FIL_RUNOUT_PULLUP // Use internal pullup for filament runout pins. #define FILAMENT_RUNOUT_SCRIPT "M600" #endif //=========================================================================== //=============================== Bed Leveling ============================== //=========================================================================== // @section calibrate /** * Choose one of the options below to enable G29 Bed Leveling. The parameters * and behavior of G29 will change depending on your selection. * * If using a Probe for Z Homing, enable Z_SAFE_HOMING also! * * - AUTO_BED_LEVELING_3POINT * Probe 3 arbitrary points on the bed (that aren't collinear) * You specify the XY coordinates of all 3 points. * The result is a single tilted plane. Best for a flat bed. * * - AUTO_BED_LEVELING_LINEAR * Probe several points in a grid. * You specify the rectangle and the density of sample points. * The result is a single tilted plane. Best for a flat bed. * * - AUTO_BED_LEVELING_BILINEAR * Probe several points in a grid. * You specify the rectangle and the density of sample points. * The result is a mesh, best for large or uneven beds. * * - AUTO_BED_LEVELING_UBL (Unified Bed Leveling) * A comprehensive bed leveling system combining the features and benefits * of other systems. UBL also includes integrated Mesh Generation, Mesh * Validation and Mesh Editing systems. * * - MESH_BED_LEVELING * Probe a grid manually * The result is a mesh, suitable for large or uneven beds. (See BILINEAR.) * For machines without a probe, Mesh Bed Leveling provides a method to perform * leveling in steps so you can manually adjust the Z height at each grid-point. * With an LCD controller the process is guided step-by-step. */ //#define AUTO_BED_LEVELING_3POINT //#define AUTO_BED_LEVELING_LINEAR //#define AUTO_BED_LEVELING_BILINEAR //#define AUTO_BED_LEVELING_UBL //#define MESH_BED_LEVELING /** * Normally G28 leaves leveling disabled on completion. Enable * this option to have G28 restore the prior leveling state. */ //#define RESTORE_LEVELING_AFTER_G28 /** * Enable detailed logging of G28, G29, M48, etc. * Turn on with the command 'M111 S32'. * NOTE: Requires a lot of PROGMEM! */ //#define DEBUG_LEVELING_FEATURE #if ENABLED(MESH_BED_LEVELING) || ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(AUTO_BED_LEVELING_UBL) // Gradually reduce leveling correction until a set height is reached, // at which point movement will be level to the machine's XY plane. // The height can be set with M420 Z<height> #define ENABLE_LEVELING_FADE_HEIGHT // For Cartesian machines, instead of dividing moves on mesh boundaries, // split up moves into short segments like a Delta. This follows the // contours of the bed more closely than edge-to-edge straight moves. #define SEGMENT_LEVELED_MOVES #define LEVELED_SEGMENT_LENGTH 5.0 // (mm) Length of all segments (except the last one) /** * Enable the G26 Mesh Validation Pattern tool. */ //#define G26_MESH_VALIDATION #if ENABLED(G26_MESH_VALIDATION) #define MESH_TEST_NOZZLE_SIZE 0.4 // (mm) Diameter of primary nozzle. #define MESH_TEST_LAYER_HEIGHT 0.2 // (mm) Default layer height for the G26 Mesh Validation Tool. #define MESH_TEST_HOTEND_TEMP 205.0 // (°C) Default nozzle temperature for the G26 Mesh Validation Tool. #define MESH_TEST_BED_TEMP 60.0 // (°C) Default bed temperature for the G26 Mesh Validation Tool. #endif #endif #if ENABLED(AUTO_BED_LEVELING_LINEAR) || ENABLED(AUTO_BED_LEVELING_BILINEAR) // Set the number of grid points per dimension. #define GRID_MAX_POINTS_X 3 #define GRID_MAX_POINTS_Y GRID_MAX_POINTS_X // Set the boundaries for probing (where the probe can reach). //#define LEFT_PROBE_BED_POSITION MIN_PROBE_EDGE //#define RIGHT_PROBE_BED_POSITION (X_BED_SIZE - MIN_PROBE_EDGE) //#define FRONT_PROBE_BED_POSITION MIN_PROBE_EDGE //#define BACK_PROBE_BED_POSITION (Y_BED_SIZE - MIN_PROBE_EDGE) // Probe along the Y axis, advancing X after each column //#define PROBE_Y_FIRST #if ENABLED(AUTO_BED_LEVELING_BILINEAR) // Beyond the probed grid, continue the implied tilt? // Default is to maintain the height of the nearest edge. //#define EXTRAPOLATE_BEYOND_GRID // // Experimental Subdivision of the grid by Catmull-Rom method. // Synthesizes intermediate points to produce a more detailed mesh. // //#define ABL_BILINEAR_SUBDIVISION #if ENABLED(ABL_BILINEAR_SUBDIVISION) // Number of subdivisions between probe points #define BILINEAR_SUBDIVISIONS 3 #endif #endif #elif ENABLED(AUTO_BED_LEVELING_UBL) //=========================================================================== //========================= Unified Bed Leveling ============================ //=========================================================================== //#define MESH_EDIT_GFX_OVERLAY // Display a graphics overlay while editing the mesh #define MESH_INSET 1 // Set Mesh bounds as an inset region of the bed #define GRID_MAX_POINTS_X 10 // Don't use more than 15 points per axis, implementation limited. #define GRID_MAX_POINTS_Y GRID_MAX_POINTS_X #define UBL_MESH_EDIT_MOVES_Z // Sophisticated users prefer no movement of nozzle #define UBL_SAVE_ACTIVE_ON_M500 // Save the currently active mesh in the current slot on M500 //#define UBL_Z_RAISE_WHEN_OFF_MESH 2.5 // When the nozzle is off the mesh, this value is used // as the Z-Height correction value. #elif ENABLED(MESH_BED_LEVELING) //=========================================================================== //=================================== Mesh ================================== //=========================================================================== #define MESH_INSET 10 // Set Mesh bounds as an inset region of the bed #define GRID_MAX_POINTS_X 3 // Don't use more than 7 points per axis, implementation limited. #define GRID_MAX_POINTS_Y GRID_MAX_POINTS_X //#define MESH_G28_REST_ORIGIN // After homing all axes ('G28' or 'G28 XYZ') rest Z at Z_MIN_POS #endif // BED_LEVELING /** * Points to probe for all 3-point Leveling procedures. * Override if the automatically selected points are inadequate. */ #if ENABLED(AUTO_BED_LEVELING_3POINT) || ENABLED(AUTO_BED_LEVELING_UBL) //#define PROBE_PT_1_X 15 //#define PROBE_PT_1_Y 180 //#define PROBE_PT_2_X 15 //#define PROBE_PT_2_Y 20 //#define PROBE_PT_3_X 170 //#define PROBE_PT_3_Y 20 #endif /** * Add a bed leveling sub-menu for ABL or MBL. * Include a guided procedure if manual probing is enabled. */ //#define LCD_BED_LEVELING #if ENABLED(LCD_BED_LEVELING) #define MBL_Z_STEP 0.025 // Step size while manually probing Z axis. #define LCD_PROBE_Z_RANGE 4 // Z Range centered on Z_MIN_POS for LCD Z adjustment #endif // Add a menu item to move between bed corners for manual bed adjustment //#define LEVEL_BED_CORNERS #if ENABLED(LEVEL_BED_CORNERS) #define LEVEL_CORNERS_INSET 30 // (mm) An inset for corner leveling //#define LEVEL_CENTER_TOO // Move to the center after the last corner #endif /** * Commands to execute at the end of G29 probing. * Useful to retract or move the Z probe out of the way. */ //#define Z_PROBE_END_SCRIPT "G1 Z10 F12000\nG1 X15 Y330\nG1 Z0.5\nG1 Z10" // @section homing // The center of the bed is at (X=0, Y=0) //#define BED_CENTER_AT_0_0 // Manually set the home position. Leave these undefined for automatic settings. // For DELTA this is the top-center of the Cartesian print volume. //#define MANUAL_X_HOME_POS 0 //#define MANUAL_Y_HOME_POS 0 //#define MANUAL_Z_HOME_POS 0 // Use "Z Safe Homing" to avoid homing with a Z probe outside the bed area. // // With this feature enabled: // // - Allow Z homing only after X and Y homing AND stepper drivers still enabled. // - If stepper drivers time out, it will need X and Y homing again before Z homing. // - Move the Z probe (or nozzle) to a defined XY point before Z Homing when homing all axes (G28). // - Prevent Z homing when the Z probe is outside bed area. // //#define Z_SAFE_HOMING #if ENABLED(Z_SAFE_HOMING) #define Z_SAFE_HOMING_X_POINT ((X_BED_SIZE) / 2) // X point for Z homing when homing all axes (G28). #define Z_SAFE_HOMING_Y_POINT ((Y_BED_SIZE) / 2) // Y point for Z homing when homing all axes (G28). #endif // Homing speeds (mm/m) #define HOMING_FEEDRATE_XY (80*60) #define HOMING_FEEDRATE_Z (20*60) // @section calibrate /** * Bed Skew Compensation * * This feature corrects for misalignment in the XYZ axes. * * Take the following steps to get the bed skew in the XY plane: * 1. Print a test square (e.g., https://www.thingiverse.com/thing:2563185) * 2. For XY_DIAG_AC measure the diagonal A to C * 3. For XY_DIAG_BD measure the diagonal B to D * 4. For XY_SIDE_AD measure the edge A to D * * Marlin automatically computes skew factors from these measurements. * Skew factors may also be computed and set manually: * * - Compute AB : SQRT(2*AC*AC+2*BD*BD-4*AD*AD)/2 * - XY_SKEW_FACTOR : TAN(PI/2-ACOS((AC*AC-AB*AB-AD*AD)/(2*AB*AD))) * * If desired, follow the same procedure for XZ and YZ. * Use these diagrams for reference: * * Y Z Z * ^ B-------C ^ B-------C ^ B-------C * | / / | / / | / / * | / / | / / | / / * | A-------D | A-------D | A-------D * +-------------->X +-------------->X +-------------->Y * XY_SKEW_FACTOR XZ_SKEW_FACTOR YZ_SKEW_FACTOR */ //#define SKEW_CORRECTION #if ENABLED(SKEW_CORRECTION) // Input all length measurements here: #define XY_DIAG_AC 282.8427124746 #define XY_DIAG_BD 282.8427124746 #define XY_SIDE_AD 200 // Or, set the default skew factors directly here // to override the above measurements: #define XY_SKEW_FACTOR 0.0 //#define SKEW_CORRECTION_FOR_Z #if ENABLED(SKEW_CORRECTION_FOR_Z) #define XZ_DIAG_AC 282.8427124746 #define XZ_DIAG_BD 282.8427124746 #define YZ_DIAG_AC 282.8427124746 #define YZ_DIAG_BD 282.8427124746 #define YZ_SIDE_AD 200 #define XZ_SKEW_FACTOR 0.0 #define YZ_SKEW_FACTOR 0.0 #endif // Enable this option for M852 to set skew at runtime //#define SKEW_CORRECTION_GCODE #endif //============================================================================= //============================= Additional Features =========================== //============================================================================= // @section extras // // EEPROM // // The microcontroller can store settings in the EEPROM, e.g. max velocity... // M500 - stores parameters in EEPROM // M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily). // M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to. // //#define EEPROM_SETTINGS // Enable for M500 and M501 commands //#define DISABLE_M503 // Saves ~2700 bytes of PROGMEM. Disable for release! #define EEPROM_CHITCHAT // Give feedback on EEPROM commands. Disable to save PROGMEM. // // Host Keepalive // // When enabled Marlin will send a busy status message to the host // every couple of seconds when it can't accept commands. // #define HOST_KEEPALIVE_FEATURE // Disable this if your host doesn't like keepalive messages #define DEFAULT_KEEPALIVE_INTERVAL 2 // Number of seconds between "busy" messages. Set with M113. #define BUSY_WHILE_HEATING // Some hosts require "busy" messages even during heating // // M100 Free Memory Watcher // //#define M100_FREE_MEMORY_WATCHER // Add M100 (Free Memory Watcher) to debug memory usage // // G20/G21 Inch mode support // //#define INCH_MODE_SUPPORT // // M149 Set temperature units support // //#define TEMPERATURE_UNITS_SUPPORT // @section temperature // Preheat Constants #define PREHEAT_1_TEMP_HOTEND 180 #define PREHEAT_1_TEMP_BED 70 #define PREHEAT_1_FAN_SPEED 0 // Value from 0 to 255 #define PREHEAT_2_TEMP_HOTEND 240 #define PREHEAT_2_TEMP_BED 110 #define PREHEAT_2_FAN_SPEED 0 // Value from 0 to 255 /** * Nozzle Park * * Park the nozzle at the given XYZ position on idle or G27. * * The "P" parameter controls the action applied to the Z axis: * * P0 (Default) If Z is below park Z raise the nozzle. * P1 Raise the nozzle always to Z-park height. * P2 Raise the nozzle by Z-park amount, limited to Z_MAX_POS. */ //#define NOZZLE_PARK_FEATURE #if ENABLED(NOZZLE_PARK_FEATURE) // Specify a park position as { X, Y, Z } #define NOZZLE_PARK_POINT { (X_MIN_POS + 10), (Y_MAX_POS - 10), 20 } #define NOZZLE_PARK_XY_FEEDRATE 100 // X and Y axes feedrate in mm/s (also used for delta printers Z axis) #define NOZZLE_PARK_Z_FEEDRATE 5 // Z axis feedrate in mm/s (not used for delta printers) #endif /** * Clean Nozzle Feature -- EXPERIMENTAL * * Adds the G12 command to perform a nozzle cleaning process. * * Parameters: * P Pattern * S Strokes / Repetitions * T Triangles (P1 only) * * Patterns: * P0 Straight line (default). This process requires a sponge type material * at a fixed bed location. "S" specifies strokes (i.e. back-forth motions) * between the start / end points. * * P1 Zig-zag pattern between (X0, Y0) and (X1, Y1), "T" specifies the * number of zig-zag triangles to do. "S" defines the number of strokes. * Zig-zags are done in whichever is the narrower dimension. * For example, "G12 P1 S1 T3" will execute: * * -- * | (X0, Y1) | /\ /\ /\ | (X1, Y1) * | | / \ / \ / \ | * A | | / \ / \ / \ | * | | / \ / \ / \ | * | (X0, Y0) | / \/ \/ \ | (X1, Y0) * -- +--------------------------------+ * |________|_________|_________| * T1 T2 T3 * * P2 Circular pattern with middle at NOZZLE_CLEAN_CIRCLE_MIDDLE. * "R" specifies the radius. "S" specifies the stroke count. * Before starting, the nozzle moves to NOZZLE_CLEAN_START_POINT. * * Caveats: The ending Z should be the same as starting Z. * Attention: EXPERIMENTAL. G-code arguments may change. * */ //#define NOZZLE_CLEAN_FEATURE #if ENABLED(NOZZLE_CLEAN_FEATURE) // Default number of pattern repetitions #define NOZZLE_CLEAN_STROKES 12 // Default number of triangles #define NOZZLE_CLEAN_TRIANGLES 3 // Specify positions as { X, Y, Z } #define NOZZLE_CLEAN_START_POINT { 30, 30, (Z_MIN_POS + 1)} #define NOZZLE_CLEAN_END_POINT {100, 60, (Z_MIN_POS + 1)} // Circular pattern radius #define NOZZLE_CLEAN_CIRCLE_RADIUS 6.5 // Circular pattern circle fragments number #define NOZZLE_CLEAN_CIRCLE_FN 10 // Middle point of circle #define NOZZLE_CLEAN_CIRCLE_MIDDLE NOZZLE_CLEAN_START_POINT // Moves the nozzle to the initial position #define NOZZLE_CLEAN_GOBACK #endif /** * Print Job Timer * * Automatically start and stop the print job timer on M104/M109/M190. * * M104 (hotend, no wait) - high temp = none, low temp = stop timer * M109 (hotend, wait) - high temp = start timer, low temp = stop timer * M190 (bed, wait) - high temp = start timer, low temp = none * * The timer can also be controlled with the following commands: * * M75 - Start the print job timer * M76 - Pause the print job timer * M77 - Stop the print job timer */ #define PRINTJOB_TIMER_AUTOSTART /** * Print Counter * * Track statistical data such as: * * - Total print jobs * - Total successful print jobs * - Total failed print jobs * - Total time printing * * View the current statistics with M78. */ //#define PRINTCOUNTER //============================================================================= //============================= LCD and SD support ============================ //============================================================================= // @section lcd /** * LCD LANGUAGE * * Select the language to display on the LCD. These languages are available: * * en, an, bg, ca, cn, cz, cz_utf8, de, el, el-gr, es, es_utf8, * eu, fi, fr, fr_utf8, gl, hr, it, kana, kana_utf8, nl, pl, pt, * pt_utf8, pt-br, pt-br_utf8, ru, sk_utf8, tr, uk, zh_CN, zh_TW, test * * :{ 'en':'English', 'an':'Aragonese', 'bg':'Bulgarian', 'ca':'Catalan', 'cn':'Chinese', 'cz':'Czech', 'cz_utf8':'Czech (UTF8)', 'de':'German', 'el':'Greek', 'el-gr':'Greek (Greece)', 'es':'Spanish', 'es_utf8':'Spanish (UTF8)', 'eu':'Basque-Euskera', 'fi':'Finnish', 'fr':'French', 'fr_utf8':'French (UTF8)', 'gl':'Galician', 'hr':'Croatian', 'it':'Italian', 'kana':'Japanese', 'kana_utf8':'Japanese (UTF8)', 'nl':'Dutch', 'pl':'Polish', 'pt':'Portuguese', 'pt-br':'Portuguese (Brazilian)', 'pt-br_utf8':'Portuguese (Brazilian UTF8)', 'pt_utf8':'Portuguese (UTF8)', 'ru':'Russian', 'sk_utf8':'Slovak (UTF8)', 'tr':'Turkish', 'uk':'Ukrainian', 'zh_CN':'Chinese (Simplified)', 'zh_TW':'Chinese (Taiwan)', 'test':'TEST' } */ #define LCD_LANGUAGE en /** * LCD Character Set * * Note: This option is NOT applicable to Graphical Displays. * * All character-based LCDs provide ASCII plus one of these * language extensions: * * - JAPANESE ... the most common * - WESTERN ... with more accented characters * - CYRILLIC ... for the Russian language * * To determine the language extension installed on your controller: * * - Compile and upload with LCD_LANGUAGE set to 'test' * - Click the controller to view the LCD menu * - The LCD will display Japanese, Western, or Cyrillic text * * See http://marlinfw.org/docs/development/lcd_language.html * * :['JAPANESE', 'WESTERN', 'CYRILLIC'] */ #define DISPLAY_CHARSET_HD44780 JAPANESE /** * SD CARD * * SD Card support is disabled by default. If your controller has an SD slot, * you must uncomment the following option or it won't work. * */ //#define SDSUPPORT /** * SD CARD: SPI SPEED * * Enable one of the following items for a slower SPI transfer speed. * This may be required to resolve "volume init" errors. */ //#define SPI_SPEED SPI_HALF_SPEED //#define SPI_SPEED SPI_QUARTER_SPEED //#define SPI_SPEED SPI_EIGHTH_SPEED /** * SD CARD: ENABLE CRC * * Use CRC checks and retries on the SD communication. */ //#define SD_CHECK_AND_RETRY /** * LCD Menu Items * * Disable all menus and only display the Status Screen, or * just remove some extraneous menu items to recover space. */ //#define NO_LCD_MENUS //#define SLIM_LCD_MENUS // // ENCODER SETTINGS // // This option overrides the default number of encoder pulses needed to // produce one step. Should be increased for high-resolution encoders. // //#define ENCODER_PULSES_PER_STEP 4 // // Use this option to override the number of step signals required to // move between next/prev menu items. // //#define ENCODER_STEPS_PER_MENU_ITEM 1 /** * Encoder Direction Options * * Test your encoder's behavior first with both options disabled. * * Reversed Value Edit and Menu Nav? Enable REVERSE_ENCODER_DIRECTION. * Reversed Menu Navigation only? Enable REVERSE_MENU_DIRECTION. * Reversed Value Editing only? Enable BOTH options. */ // // This option reverses the encoder direction everywhere. // // Set this option if CLOCKWISE causes values to DECREASE // //#define REVERSE_ENCODER_DIRECTION // // This option reverses the encoder direction for navigating LCD menus. // // If CLOCKWISE normally moves DOWN this makes it go UP. // If CLOCKWISE normally moves UP this makes it go DOWN. // //#define REVERSE_MENU_DIRECTION // // Individual Axis Homing // // Add individual axis homing items (Home X, Home Y, and Home Z) to the LCD menu. // //#define INDIVIDUAL_AXIS_HOMING_MENU // // SPEAKER/BUZZER // // If you have a speaker that can produce tones, enable it here. // By default Marlin assumes you have a buzzer with a fixed frequency. // //#define SPEAKER // // The duration and frequency for the UI feedback sound. // Set these to 0 to disable audio feedback in the LCD menus. // // Note: Test audio output with the G-Code: // M300 S<frequency Hz> P<duration ms> // //#define LCD_FEEDBACK_FREQUENCY_DURATION_MS 2 //#define LCD_FEEDBACK_FREQUENCY_HZ 5000 //============================================================================= //======================== LCD / Controller Selection ========================= //======================== (Character-based LCDs) ========================= //============================================================================= // // RepRapDiscount Smart Controller. // http://reprap.org/wiki/RepRapDiscount_Smart_Controller // // Note: Usually sold with a white PCB. // //#define REPRAP_DISCOUNT_SMART_CONTROLLER // // ULTIMAKER Controller. // //#define ULTIMAKERCONTROLLER // // ULTIPANEL as seen on Thingiverse. // //#define ULTIPANEL // // PanelOne from T3P3 (via RAMPS 1.4 AUX2/AUX3) // http://reprap.org/wiki/PanelOne // //#define PANEL_ONE // // GADGETS3D G3D LCD/SD Controller // http://reprap.org/wiki/RAMPS_1.3/1.4_GADGETS3D_Shield_with_Panel // // Note: Usually sold with a blue PCB. // //#define G3D_PANEL // // RigidBot Panel V1.0 // http://www.inventapart.com/ // //#define RIGIDBOT_PANEL // // Makeboard 3D Printer Parts 3D Printer Mini Display 1602 Mini Controller // https://www.aliexpress.com/item/Micromake-Makeboard-3D-Printer-Parts-3D-Printer-Mini-Display-1602-Mini-Controller-Compatible-with-Ramps-1/32765887917.html // //#define MAKEBOARD_MINI_2_LINE_DISPLAY_1602 // // ANET and Tronxy 20x4 Controller // //#define ZONESTAR_LCD // Requires ADC_KEYPAD_PIN to be assigned to an analog pin. // This LCD is known to be susceptible to electrical interference // which scrambles the display. Pressing any button clears it up. // This is a LCD2004 display with 5 analog buttons. // // Generic 16x2, 16x4, 20x2, or 20x4 character-based LCD. // //#define ULTRA_LCD //============================================================================= //======================== LCD / Controller Selection ========================= //===================== (I2C and Shift-Register LCDs) ===================== //============================================================================= // // CONTROLLER TYPE: I2C // // Note: These controllers require the installation of Arduino's LiquidCrystal_I2C // library. For more info: https://github.com/kiyoshigawa/LiquidCrystal_I2C // // // Elefu RA Board Control Panel // http://www.elefu.com/index.php?route=product/product&product_id=53 // //#define RA_CONTROL_PANEL // // Sainsmart (YwRobot) LCD Displays // // These require F.Malpartida's LiquidCrystal_I2C library // https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/Home // //#define LCD_SAINSMART_I2C_1602 //#define LCD_SAINSMART_I2C_2004 // // Generic LCM1602 LCD adapter // //#define LCM1602 // // PANELOLU2 LCD with status LEDs, // separate encoder and click inputs. // // Note: This controller requires Arduino's LiquidTWI2 library v1.2.3 or later. // For more info: https://github.com/lincomatic/LiquidTWI2 // // Note: The PANELOLU2 encoder click input can either be directly connected to // a pin (if BTN_ENC defined to != -1) or read through I2C (when BTN_ENC == -1). // //#define LCD_I2C_PANELOLU2 // // Panucatt VIKI LCD with status LEDs, // integrated click & L/R/U/D buttons, separate encoder inputs. // //#define LCD_I2C_VIKI // // CONTROLLER TYPE: Shift register panels // // // 2 wire Non-latching LCD SR from https://goo.gl/aJJ4sH // LCD configuration: http://reprap.org/wiki/SAV_3D_LCD // //#define SAV_3DLCD //============================================================================= //======================= LCD / Controller Selection ======================= //========================= (Graphical LCDs) ======================== //============================================================================= // // CONTROLLER TYPE: Graphical 128x64 (DOGM) // // IMPORTANT: The U8glib library is required for Graphical Display! // https://github.com/olikraus/U8glib_Arduino // // // RepRapDiscount FULL GRAPHIC Smart Controller // http://reprap.org/wiki/RepRapDiscount_Full_Graphic_Smart_Controller // //#define REPRAP_DISCOUNT_FULL_GRAPHIC_SMART_CONTROLLER // // ReprapWorld Graphical LCD // https://reprapworld.com/?products_details&products_id/1218 // //#define REPRAPWORLD_GRAPHICAL_LCD // // Activate one of these if you have a Panucatt Devices // Viki 2.0 or mini Viki with Graphic LCD // http://panucatt.com // //#define VIKI2 //#define miniVIKI // // MakerLab Mini Panel with graphic // controller and SD support - http://reprap.org/wiki/Mini_panel // //#define MINIPANEL // // MaKr3d Makr-Panel with graphic controller and SD support. // http://reprap.org/wiki/MaKr3d_MaKrPanel // //#define MAKRPANEL // // Adafruit ST7565 Full Graphic Controller. // https://github.com/eboston/Adafruit-ST7565-Full-Graphic-Controller/ // //#define ELB_FULL_GRAPHIC_CONTROLLER // // BQ LCD Smart Controller shipped by // default with the BQ Hephestos 2 and Witbox 2. // //#define BQ_LCD_SMART_CONTROLLER // // Cartesio UI // http://mauk.cc/webshop/cartesio-shop/electronics/user-interface // //#define CARTESIO_UI // // LCD for Melzi Card with Graphical LCD // //#define LCD_FOR_MELZI // // SSD1306 OLED full graphics generic display // //#define U8GLIB_SSD1306 // // SAV OLEd LCD module support using either SSD1306 or SH1106 based LCD modules // //#define SAV_3DGLCD #if ENABLED(SAV_3DGLCD) //#define U8GLIB_SSD1306 #define U8GLIB_SH1106 #endif // // Original Ulticontroller from Ultimaker 2 printer with SSD1309 I2C display and encoder // https://github.com/Ultimaker/Ultimaker2/tree/master/1249_Ulticontroller_Board_(x1) // //#define ULTI_CONTROLLER // // TinyBoy2 128x64 OLED / Encoder Panel // //#define OLED_PANEL_TINYBOY2 // // MKS MINI12864 with graphic controller and SD support // http://reprap.org/wiki/MKS_MINI_12864 // //#define MKS_MINI_12864 // // Factory display for Creality CR-10 // https://www.aliexpress.com/item/Universal-LCD-12864-3D-Printer-Display-Screen-With-Encoder-For-CR-10-CR-7-Model/32833148327.html // // This is RAMPS-compatible using a single 10-pin connector. // (For CR-10 owners who want to replace the Melzi Creality board but retain the display) // //#define CR10_STOCKDISPLAY // // ANET and Tronxy Graphical Controller // //#define ANET_FULL_GRAPHICS_LCD // Anet 128x64 full graphics lcd with rotary encoder as used on Anet A6 // A clone of the RepRapDiscount full graphics display but with // different pins/wiring (see pins_ANET_10.h). // // MKS OLED 1.3" 128 × 64 FULL GRAPHICS CONTROLLER // http://reprap.org/wiki/MKS_12864OLED // // Tiny, but very sharp OLED display // //#define MKS_12864OLED // Uses the SH1106 controller (default) //#define MKS_12864OLED_SSD1306 // Uses the SSD1306 controller // // Silvergate GLCD controller // http://github.com/android444/Silvergate // //#define SILVER_GATE_GLCD_CONTROLLER //============================================================================= //============================ Other Controllers ============================ //============================================================================= // // CONTROLLER TYPE: Standalone / Serial // // // LCD for Malyan M200 printers. // This requires SDSUPPORT to be enabled // //#define MALYAN_LCD // // CONTROLLER TYPE: Keypad / Add-on // // // RepRapWorld REPRAPWORLD_KEYPAD v1.1 // http://reprapworld.com/?products_details&products_id=202&cPath=1591_1626 // // REPRAPWORLD_KEYPAD_MOVE_STEP sets how much should the robot move when a key // is pressed, a value of 10.0 means 10mm per click. // //#define REPRAPWORLD_KEYPAD //#define REPRAPWORLD_KEYPAD_MOVE_STEP 10.0 //============================================================================= //=============================== Extra Features ============================== //============================================================================= // @section extras // Increase the FAN PWM frequency. Removes the PWM noise but increases heating in the FET/Arduino //#define FAST_PWM_FAN // Use software PWM to drive the fan, as for the heaters. This uses a very low frequency // which is not as annoying as with the hardware PWM. On the other hand, if this frequency // is too low, you should also increment SOFT_PWM_SCALE. //#define FAN_SOFT_PWM // Incrementing this by 1 will double the software PWM frequency, // affecting heaters, and the fan if FAN_SOFT_PWM is enabled. // However, control resolution will be halved for each increment; // at zero value, there are 128 effective control positions. #define SOFT_PWM_SCALE 0 // If SOFT_PWM_SCALE is set to a value higher than 0, dithering can // be used to mitigate the associated resolution loss. If enabled, // some of the PWM cycles are stretched so on average the desired // duty cycle is attained. //#define SOFT_PWM_DITHER // Temperature status LEDs that display the hotend and bed temperature. // If all hotends, bed temperature, and target temperature are under 54C // then the BLUE led is on. Otherwise the RED led is on. (1C hysteresis) //#define TEMP_STAT_LEDS // M240 Triggers a camera by emulating a Canon RC-1 Remote // Data from: http://www.doc-diy.net/photo/rc-1_hacked/ //#define PHOTOGRAPH_PIN 23 // SkeinForge sends the wrong arc g-codes when using Arc Point as fillet procedure //#define SF_ARC_FIX // Support for the BariCUDA Paste Extruder //#define BARICUDA // Support for BlinkM/CyzRgb //#define BLINKM // Support for PCA9632 PWM LED driver //#define PCA9632 /** * RGB LED / LED Strip Control * * Enable support for an RGB LED connected to 5V digital pins, or * an RGB Strip connected to MOSFETs controlled by digital pins. * * Adds the M150 command to set the LED (or LED strip) color. * If pins are PWM capable (e.g., 4, 5, 6, 11) then a range of * luminance values can be set from 0 to 255. * For Neopixel LED an overall brightness parameter is also available. * * *** CAUTION *** * LED Strips require a MOSFET Chip between PWM lines and LEDs, * as the Arduino cannot handle the current the LEDs will require. * Failure to follow this precaution can destroy your Arduino! * NOTE: A separate 5V power supply is required! The Neopixel LED needs * more current than the Arduino 5V linear regulator can produce. * *** CAUTION *** * * LED Type. Enable only one of the following two options. * */ #define RGB_LED //#define RGBW_LED #if ENABLED(RGB_LED) || ENABLED(RGBW_LED) #define RGB_LED_R_PIN 5 #define RGB_LED_G_PIN 4 #define RGB_LED_B_PIN 6 #define RGB_LED_W_PIN -1 #endif // Support for Adafruit Neopixel LED driver //#define NEOPIXEL_LED #if ENABLED(NEOPIXEL_LED) #define NEOPIXEL_TYPE NEO_GRBW // NEO_GRBW / NEO_GRB - four/three channel driver type (defined in Adafruit_NeoPixel.h) #define NEOPIXEL_PIN 4 // LED driving pin on motherboard 4 => D4 (EXP2-5 on Printrboard) / 30 => PC7 (EXP3-13 on Rumba) #define NEOPIXEL_PIXELS 30 // Number of LEDs in the strip #define NEOPIXEL_IS_SEQUENTIAL // Sequential display for temperature change - LED by LED. Disable to change all LEDs at once. #define NEOPIXEL_BRIGHTNESS 127 // Initial brightness (0-255) //#define NEOPIXEL_STARTUP_TEST // Cycle through colors at startup #endif /** * Printer Event LEDs * * During printing, the LEDs will reflect the printer status: * * - Gradually change from blue to violet as the heated bed gets to target temp * - Gradually change from violet to red as the hotend gets to temperature * - Change to white to illuminate work surface * - Change to green once print has finished * - Turn off after the print has finished and the user has pushed a button */ #if ENABLED(BLINKM) || ENABLED(RGB_LED) || ENABLED(RGBW_LED) || ENABLED(PCA9632) || ENABLED(NEOPIXEL_LED) #define PRINTER_EVENT_LEDS #endif /** * R/C SERVO support * Sponsored by TrinityLabs, Reworked by codexmas */ /** * Number of servos * * For some servo-related options NUM_SERVOS will be set automatically. * Set this manually if there are extra servos needing manual control. * Leave undefined or set to 0 to entirely disable the servo subsystem. */ //#define NUM_SERVOS 3 // Servo index starts with 0 for M280 command // Delay (in milliseconds) before the next move will start, to give the servo time to reach its target angle. // 300ms is a good value but you can try less delay. // If the servo can't reach the requested position, increase it. #define SERVO_DELAY { 300 } // Only power servos during movement, otherwise leave off to prevent jitter //#define DEACTIVATE_SERVOS_AFTER_MOVE #endif // CONFIGURATION_H
72,028
C++
.h
1,652
41.596247
1,428
0.669087
artillery3d/genius-firmware
37
31
2
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,986
LedDriver.cpp
ch570512_Qlockwork/LedDriver.cpp
//***************************************************************************** // LedDriver.cpp //***************************************************************************** #include "LedDriver.h" LedDriver::LedDriver() { strip = new Adafruit_NeoPixel(NUMPIXELS, PIN_LEDS_DATA, NEOPIXEL_TYPE); strip->begin(); } LedDriver::~LedDriver() { } void LedDriver::clear() { strip->clear(); } void LedDriver::show() { strip->show(); } void LedDriver::setPixel(uint8_t x, uint8_t y, uint8_t color, uint8_t brightness) { setPixel(x + y * 11, color, brightness); } void LedDriver::setPixel(uint8_t num, uint8_t color, uint8_t brightness) { #ifdef LED_LAYOUT_HORIZONTAL_1 uint8_t ledMap[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 109, 108, 107, 106, 105, 104, 103, 102, 101, 100, 99, 111, 112, 113, 110, 114 }; #endif #ifdef LED_LAYOUT_VERTICAL_1 uint8_t ledMap[] = { 1, 21, 22, 41, 42, 61, 62, 81, 82, 101, 103, 2, 20, 23, 40, 43, 60, 63, 80, 83, 100, 104, 3, 19, 24, 39, 44, 59, 64, 79, 84, 99, 105, 4, 18, 25, 38, 45, 58, 65, 78, 85, 98, 106, 5, 17, 26, 37, 46, 57, 66, 77, 86, 97, 107, 6, 16, 27, 36, 47, 56, 67, 76, 87, 96, 108, 7, 15, 28, 35, 48, 55, 68, 75, 88, 95, 109, 8, 14, 29, 34, 49, 54, 69, 74, 89, 94, 110, 9, 13, 30, 33, 50, 53, 70, 73, 90, 93, 111, 10, 12, 31, 32, 51, 52, 71, 72, 91, 92, 112, 0, 102, 113, 11, 114 }; #endif #ifdef LED_LAYOUT_VERTICAL_2 uint8_t ledMap[] = { 9, 10, 29, 30, 49, 50, 69, 70, 89, 90, 109, 8, 11, 28, 31, 48, 51, 68, 71, 88, 91, 108, 7, 12, 27, 32, 47, 52, 67, 72, 87, 92, 107, 6, 13, 26, 33, 46, 53, 66, 73, 86, 93, 106, 5, 14, 25, 34, 45, 54, 65, 74, 85, 94, 105, 4, 15, 24, 35, 44, 55, 64, 75, 84, 95, 104, 3, 16, 23, 36, 43, 56, 63, 76, 83, 96, 103, 2, 17, 22, 37, 42, 57, 62, 77, 82, 97, 102, 1, 18, 21, 38, 41, 58, 61, 78, 81, 98, 101, 0, 19, 20, 39, 40, 59, 60, 79, 80, 99, 100, 112, 110, 114, 113, 111 }; #endif #ifdef LED_LAYOUT_VERTICAL_3 uint8_t ledMap[] = { 9, 10, 29, 30, 49, 50, 69, 70, 89, 90, 109, 8, 11, 28, 31, 48, 51, 68, 71, 88, 91, 108, 7, 12, 27, 32, 47, 52, 67, 72, 87, 92, 107, 6, 13, 26, 33, 46, 53, 66, 73, 86, 93, 106, 5, 14, 25, 34, 45, 54, 65, 74, 85, 94, 105, 4, 15, 24, 35, 44, 55, 64, 75, 84, 95, 104, 3, 16, 23, 36, 43, 56, 63, 76, 83, 96, 103, 2, 17, 22, 37, 42, 57, 62, 77, 82, 97, 102, 1, 18, 21, 38, 41, 58, 61, 78, 81, 98, 101, 0, 19, 20, 39, 40, 59, 60, 79, 80, 99, 100, 111, 110, 113, 112, 114 }; #endif uint8_t red = brightness * 0.0039 * defaultColors[color].red; uint8_t green = brightness * 0.0039 * defaultColors[color].green; uint8_t blue = brightness * 0.0039 * defaultColors[color].blue; #ifdef NEOPIXEL_RGBW uint8_t white = 0xFF; if (red < white) white = red; if (green < white) white = green; if (blue < white) white = blue; strip->setPixelColor(ledMap[num], red - white, green - white, blue - white, white); #endif #ifdef NEOPIXEL_RGB strip->setPixelColor(ledMap[num], red, green, blue); #endif return; }
4,250
C++
.cpp
95
37
88
0.435394
ch570512/Qlockwork
36
22
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
1,535,987
MeteoWeather.cpp
ch570512_Qlockwork/MeteoWeather.cpp
//***************************************************************************** // MeteoWeather.cpp - Get weather data from Open-Meteo //***************************************************************************** #include "MeteoWeather.h" MeteoWeather::MeteoWeather() { } MeteoWeather::~MeteoWeather() { } uint8_t MeteoWeather::getOutdoorConditions(String lat, String lon, String timezone) { String response; WiFiClient client; JsonDocument doc; timezone.replace("/","%2F"); if (client.connect("api.open-meteo.com", 80)) { String url = "/v1/forecast?latitude=" + String(lat) + "&longitude=" + String(lon) + "&current=temperature_2m,relative_humidity_2m,surface_pressure&daily=sunrise,sunset&timeformat=unixtime&timezone=" + timezone + "&forecast_days=1"; client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: api.open-meteo.com" + "\r\n" + "Connection: close\r\n\r\n"); unsigned long startMillis = millis(); while (client.available() == 0) { if (millis() - startMillis > 5000) { client.stop(); return 0; } } while (client.available()) response = client.readString(); #ifdef DEBUG Serial.println("Weather api response:"); Serial.println(response); #endif response.trim(); int first = response.indexOf("{"); // Extract json file content of message. String extract = response.substring(first); // Created with https://arduinojson.org/v7/assistant/ DeserializationError error = deserializeJson(doc, extract); if (error) { Serial.print("deserializeJson() failed: "); Serial.println(error.c_str()); return 0; } float latitude = doc["latitude"]; // 52.52 double longitude = doc["longitude"]; // 13.419998 double generationtime_ms = doc["generationtime_ms"]; // 0.054001808166503906 int utc_offset_seconds = doc["utc_offset_seconds"]; // 7200 const char* timezone = doc["timezone"]; // "Europe/Berlin" const char* timezone_abbreviation = doc["timezone_abbreviation"]; // "CEST" int elevation = doc["elevation"]; // 38 JsonObject current_units = doc["current_units"]; const char* current_units_time = current_units["time"]; // "unixtime" const char* current_units_interval = current_units["interval"]; // "seconds" const char* current_units_temperature_2m = current_units["temperature_2m"]; // "°C" const char* current_units_relative_humidity_2m = current_units["relative_humidity_2m"]; // "%" const char* current_units_surface_pressure = current_units["surface_pressure"]; // "hPa" JsonObject current = doc["current"]; long current_time = current["time"]; // 1725390000 int current_interval = current["interval"]; // 900 float current_temperature_2m = current["temperature_2m"]; // 27.1 int current_relative_humidity_2m = current["relative_humidity_2m"]; // 53 float current_surface_pressure = current["surface_pressure"]; // 1010.1 JsonObject daily_units = doc["daily_units"]; const char* daily_units_time = daily_units["time"]; // "unixtime" const char* daily_units_sunrise = daily_units["sunrise"]; // "unixtime" const char* daily_units_sunset = daily_units["sunset"]; // "unixtime" JsonObject daily = doc["daily"]; long daily_time_0 = daily["time"][0]; // 1725314400 long daily_sunrise_0 = daily["sunrise"][0]; // 1725337296 long daily_sunset_0 = daily["sunset"][0]; // 1725385761 temperature = (double)current_temperature_2m; humidity = (int)current_relative_humidity_2m; pressure = (int)current_surface_pressure; sunrise = (int)daily_sunrise_0; // api also provides sunrise / sunset times. Just use them as well. sunset = (int)daily_sunset_0; return 1; } return 0; }
4,027
C++
.cpp
75
45.333333
239
0.607434
ch570512/Qlockwork
36
22
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,989
Settings.cpp
ch570512_Qlockwork/Settings.cpp
//***************************************************************************** // Settings.cpp //***************************************************************************** #include "Settings.h" Settings::Settings() { loadFromEEPROM(); } Settings::~Settings() { } // Set all defaults void Settings::resetToDefault() { mySettings.magicNumber = SETTINGS_MAGIC_NUMBER; mySettings.version = SETTINGS_VERSION; mySettings.useAbc = false; mySettings.brightness = 50; mySettings.color = WHITE; mySettings.colorChange = COLORCHANGE_NO; mySettings.transition = TRANSITION_FADE; mySettings.timeout = 10; mySettings.modeChange = false; mySettings.itIs = true; mySettings.alarm1 = false; mySettings.alarm1Time = 0; mySettings.alarm1Weekdays = 0b11111110; mySettings.alarm2 = false; mySettings.alarm2Time = 0; mySettings.alarm2Weekdays = 0b11111110; mySettings.nightOffTime = 3600; mySettings.dayOnTime = 18000; mySettings.hourBeep = false; saveToEEPROM(); } // Load settings from EEPROM void Settings::loadFromEEPROM() { EEPROM.begin(512); EEPROM.get(0, mySettings); if ((mySettings.magicNumber != SETTINGS_MAGIC_NUMBER) || (mySettings.version != SETTINGS_VERSION)) resetToDefault(); EEPROM.end(); } // Write settings to EEPROM void Settings::saveToEEPROM() { Serial.println("Settings saved to EEPROM."); EEPROM.begin(512); EEPROM.put(0, mySettings); //EEPROM.commit(); EEPROM.end(); }
1,566
C++
.cpp
48
27.666667
103
0.617021
ch570512/Qlockwork
36
22
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,535,991
MeteoWeather.h
ch570512_Qlockwork/MeteoWeather.h
//***************************************************************************** // MeteoWeather.h - Get weather data and sunrise/sunset times from Open-Meteo //***************************************************************************** #ifndef METEOWEATHER_H #define METEOWEATHER_H // #include <Arduino_JSON.h> #include <ArduinoJson.h> #include <ESP8266WiFi.h> class MeteoWeather { public: MeteoWeather(); ~MeteoWeather(); String description; double temperature; uint8_t humidity; uint16_t pressure; time_t sunrise; time_t sunset; uint8_t getOutdoorConditions(String lat, String lon, String timezone); private: }; #endif
667
C++
.h
22
27.318182
79
0.563579
ch570512/Qlockwork
36
22
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,992
LedDriver.h
ch570512_Qlockwork/LedDriver.h
//***************************************************************************** // LedDriver.h //***************************************************************************** #ifndef LEDDRIVER_H #define LEDDRIVER_H #include <Adafruit_NeoPixel.h> #include "Configuration.h" #include "Colors.h" class LedDriver { public: LedDriver(); ~LedDriver(); void clear(); void show(); void setPixel(uint8_t x, uint8_t y, uint8_t color, uint8_t brightness); void setPixel(uint8_t num, uint8_t color, uint8_t brightness); private: Adafruit_NeoPixel* strip; }; #endif
615
C++
.h
20
26.65
80
0.499139
ch570512/Qlockwork
36
22
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,993
Letters.h
ch570512_Qlockwork/Letters.h
/****************************************************************************** Letters.h ******************************************************************************/ #ifndef LETTERS_H #define LETTERS_H const char letters[][5] = { { // 0:A 0b00001100, 0b00010010, 0b00011110, 0b00010010, 0b00010010 } , { // 1:B 0b00011100, 0b00010010, 0b00011100, 0b00010010, 0b00011100 } , { // 2:C 0b00001110, 0b00010000, 0b00010000, 0b00010000, 0b00001110 } , { // 3:D 0b00011100, 0b00010010, 0b00010010, 0b00010010, 0b00011100 } , { // 4:E 0b00011110, 0b00010000, 0b00011100, 0b00010000, 0b00011110 } , { // 5:F 0b00011110, 0b00010000, 0b00011100, 0b00010000, 0b00010000 } , { // 6:G 0b00001110, 0b00010000, 0b00010110, 0b00010010, 0b00001100 } , { // 7:H 0b00010010, 0b00010010, 0b00011110, 0b00010010, 0b00010010 } , { // 8:I 0b00001110, 0b00000100, 0b00000100, 0b00000100, 0b00001110 } , { // 9:J 0b00011110, 0b00000010, 0b00000010, 0b00010010, 0b00001100 } , { // 10:K 0b00010010, 0b00010100, 0b00011000, 0b00010100, 0b00010010 } , { // 11:L 0b00010000, 0b00010000, 0b00010000, 0b00010000, 0b00011110 } , { // 12:M 0b00010001, 0b00011011, 0b00010101, 0b00010001, 0b00010001 } , { // 13:N 0b00010001, 0b00011001, 0b00010101, 0b00010011, 0b00010001 } , { // 14:O 0b00011110, 0b00010010, 0b00010010, 0b00010010, 0b00011110 } , { // 15:P 0b00011100, 0b00010010, 0b00011100, 0b00010000, 0b00010000 } , { // 16:Q 0b00001100, 0b00010010, 0b00010010, 0b00001100, 0b00000010 } , { // 17:R 0b00011100, 0b00010010, 0b00011100, 0b00010100, 0b00010010 } , { // 18:S 0b00001110, 0b00010000, 0b00001100, 0b00000010, 0b00011100 } , { // 19:T 0b00011111, 0b00000100, 0b00000100, 0b00000100, 0b00000100 } , { // 20:U 0b00010001, 0b00010001, 0b00010001, 0b00010001, 0b00001110 } , { // 21:V 0b00010001, 0b00010001, 0b00010001, 0b00001010, 0b00000100 } , { // 22:W 0b00010001, 0b00010001, 0b00010101, 0b00011011, 0b00010001 } , { // 23:X 0b00010001, 0b00001010, 0b00000100, 0b00001010, 0b00010001 } , { // 24:Y 0b00010001, 0b00001010, 0b00000100, 0b00000100, 0b00000100 } , { // 25:Z 0b00011110, 0b00000010, 0b00000100, 0b00001000, 0b00011110 } }; const char lettersBig[][7] = { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // ASCII-Code 0x20 => (32) { 0x04, 0x04, 0x04, 0x04, 0x04, 0x00, 0x04 }, // ASCII-Code 0x21 => ! (33) { 0x14, 0x14, 0x14, 0x00, 0x00, 0x00, 0x00 }, // ASCII-Code 0x22 => " (34) { 0x0a, 0x0a, 0x1f, 0x0a, 0x1f, 0x0a, 0x0a }, // ASCII-Code 0x23 => # (35) { 0x04, 0x0f, 0x14, 0x0e, 0x05, 0x1e, 0x04 }, // ASCII-Code 0x24 => $ (36) { 0x18, 0x19, 0x02, 0x04, 0x08, 0x13, 0x03 }, // ASCII-Code 0x25 => % (37) { 0x0c, 0x12, 0x14, 0x08, 0x15, 0x12, 0x0d }, // ASCII-Code 0x26 => & (38) { 0x18, 0x08, 0x10, 0x00, 0x00, 0x00, 0x00 }, // ASCII-Code 0x27 => ' (39) { 0x02, 0x04, 0x08, 0x08, 0x08, 0x04, 0x02 }, // ASCII-Code 0x28 => ( (40) { 0x10, 0x08, 0x04, 0x04, 0x04, 0x08, 0x10 }, // ASCII-Code 0x29 => ) (41) { 0x00, 0x04, 0x15, 0x0e, 0x15, 0x04, 0x00 }, // ASCII-Code 0x2A => * (42) { 0x00, 0x04, 0x04, 0x1f, 0x04, 0x04, 0x00 }, // ASCII-Code 0x2B => + (43) { 0x00, 0x00, 0x00, 0x00, 0x18, 0x08, 0x10 }, // ASCII-Code 0x2C => , (44) { 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00 }, // ASCII-Code 0x2D => - (45) { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04 }, // ASCII-Code 0x2E => . (46) { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x00 }, // ASCII-Code 0x2F => / (47) #ifdef NONE_TECHNICAL_ZERO { 0x0e, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0e }, // ASCII-Code 0x30 => 0 (48) #else { 0x0e, 0x11, 0x13, 0x15, 0x19, 0x11, 0x0e }, // ASCII-Code 0x30 => 0 (48) #endif { 0x04, 0x0c, 0x04, 0x04, 0x04, 0x04, 0x0e }, // ASCII-Code 0x31 => 1 (49) { 0x0e, 0x11, 0x01, 0x02, 0x04, 0x08, 0x1f }, // ASCII-Code 0x32 => 2 (50) { 0x1f, 0x02, 0x04, 0x02, 0x01, 0x11, 0x0e }, // ASCII-Code 0x33 => 3 (51) { 0x02, 0x06, 0x0a, 0x12, 0x1f, 0x02, 0x02 }, // ASCII-Code 0x34 => 4 (52) { 0x1f, 0x10, 0x1e, 0x01, 0x01, 0x11, 0x0e }, // ASCII-Code 0x35 => 5 (53) { 0x06, 0x08, 0x10, 0x1e, 0x11, 0x11, 0x0e }, // ASCII-Code 0x36 => 6 (54) { 0x1f, 0x01, 0x02, 0x04, 0x08, 0x08, 0x08 }, // ASCII-Code 0x37 => 7 (55) { 0x0e, 0x11, 0x11, 0x0e, 0x11, 0x11, 0x0e }, // ASCII-Code 0x38 => 8 (56) { 0x0e, 0x11, 0x11, 0x0f, 0x01, 0x02, 0x0c }, // ASCII-Code 0x39 => 9 (57) { 0x00, 0x00, 0x04, 0x00, 0x00, 0x04, 0x00 }, // ASCII-Code 0x3A => : (58) { 0x00, 0x18, 0x18, 0x00, 0x18, 0x08, 0x10 }, // ASCII-Code 0x3B => ; (59) { 0x02, 0x04, 0x08, 0x10, 0x08, 0x04, 0x02 }, // ASCII-Code 0x3C => < (60) { 0x00, 0x00, 0x1f, 0x00, 0x1f, 0x00, 0x00 }, // ASCII-Code 0x3D => = (61) { 0x10, 0x08, 0x04, 0x02, 0x04, 0x08, 0x10 }, // ASCII-Code 0x3E => > (62) { 0x0e, 0x11, 0x01, 0x02, 0x04, 0x00, 0x04 }, // ASCII-Code 0x3F => ? (63) { 0x0e, 0x11, 0x01, 0x0d, 0x15, 0x15, 0x0e }, // ASCII-Code 0x40 => @ (64) { 0x0e, 0x11, 0x11, 0x1f, 0x11, 0x11, 0x11 }, // ASCII-Code 0x41 => A (65) { 0x1e, 0x11, 0x11, 0x1e, 0x11, 0x11, 0x1e }, // ASCII-Code 0x42 => B (66) { 0x0e, 0x11, 0x10, 0x10, 0x10, 0x11, 0x0e }, // ASCII-Code 0x43 => C (67) { 0x1c, 0x12, 0x11, 0x11, 0x11, 0x12, 0x1c }, // ASCII-Code 0x44 => D (68) { 0x1f, 0x10, 0x10, 0x1e, 0x10, 0x10, 0x1f }, // ASCII-Code 0x45 => E (69) { 0x1f, 0x10, 0x10, 0x1e, 0x10, 0x10, 0x10 }, // ASCII-Code 0x46 => F (70) { 0x0e, 0x11, 0x10, 0x16, 0x11, 0x11, 0x0e }, // ASCII-Code 0x47 => G (71) { 0x11, 0x11, 0x11, 0x1f, 0x11, 0x11, 0x11 }, // ASCII-Code 0x48 => H (72) { 0x0e, 0x04, 0x04, 0x04, 0x04, 0x04, 0x0e }, // ASCII-Code 0x49 => I (73) { 0x07, 0x02, 0x02, 0x02, 0x02, 0x12, 0x0c }, // ASCII-Code 0x4A => J (74) { 0x11, 0x12, 0x14, 0x18, 0x14, 0x12, 0x11 }, // ASCII-Code 0x4B => K (75) { 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x1f }, // ASCII-Code 0x4C => L (76) { 0x11, 0x1b, 0x15, 0x15, 0x11, 0x11, 0x11 }, // ASCII-Code 0x4D => M (77) { 0x11, 0x11, 0x19, 0x15, 0x13, 0x11, 0x11 }, // ASCII-Code 0x4E => N (78) { 0x0e, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0e }, // ASCII-Code 0x4F => O (79) { 0x1e, 0x11, 0x11, 0x1e, 0x10, 0x10, 0x10 }, // ASCII-Code 0x50 => P (80) { 0x0e, 0x11, 0x11, 0x11, 0x15, 0x12, 0x0d }, // ASCII-Code 0x51 => Q (81) { 0x1e, 0x11, 0x11, 0x1e, 0x14, 0x12, 0x11 }, // ASCII-Code 0x52 => R (82) { 0x0e, 0x11, 0x10, 0x0e, 0x01, 0x11, 0x0e }, // ASCII-Code 0x53 => S (83) { 0x1f, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04 }, // ASCII-Code 0x54 => T (84) { 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0e }, // ASCII-Code 0x55 => U (85) { 0x11, 0x11, 0x11, 0x11, 0x11, 0x0a, 0x04 }, // ASCII-Code 0x56 => V (86) { 0x11, 0x11, 0x11, 0x15, 0x15, 0x15, 0x0a }, // ASCII-Code 0x57 => W (87) { 0x11, 0x11, 0x0a, 0x04, 0x0a, 0x11, 0x11 }, // ASCII-Code 0x58 => X (88) { 0x11, 0x11, 0x11, 0x0a, 0x04, 0x04, 0x04 }, // ASCII-Code 0x59 => Y (89) { 0x1f, 0x01, 0x02, 0x04, 0x08, 0x10, 0x1f }, // ASCII-Code 0x5A => Z (90) { 0x1c, 0x10, 0x10, 0x10, 0x10, 0x10, 0x1c }, // ASCII-Code 0x5B => [ (91) � { 0x00, 0x10, 0x08, 0x04, 0x02, 0x01, 0x00 }, // ASCII-Code 0x5C => \ (92) � { 0x1c, 0x04, 0x04, 0x04, 0x04, 0x04, 0x1c }, // ASCII-Code 0x5D => ] (93) � { 0x04, 0x0a, 0x11, 0x00, 0x00, 0x00, 0x00 }, // ASCII-Code 0x5E => ^ (94) { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f }, // ASCII-Code 0x5F => _ (95) { 0x10, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00 }, // ASCII-Code 0x60 => ` (96) { 0x00, 0x00, 0x0e, 0x01, 0x0f, 0x11, 0x0f }, // ASCII-Code 0x61 => a (97) { 0x10, 0x10, 0x10, 0x16, 0x19, 0x11, 0x1e }, // ASCII-Code 0x62 => b (98) { 0x00, 0x00, 0x0e, 0x10, 0x10, 0x11, 0x0e }, // ASCII-Code 0x63 => c (99) { 0x01, 0x01, 0x01, 0x0d, 0x13, 0x11, 0x0f }, // ASCII-Code 0x64 => d (100) { 0x00, 0x00, 0x0e, 0x11, 0x1f, 0x10, 0x0e }, // ASCII-Code 0x65 => e (101) { 0x06, 0x09, 0x08, 0x1c, 0x08, 0x08, 0x08 }, // ASCII-Code 0x66 => f (102) { 0x00, 0x0f, 0x11, 0x11, 0x0f, 0x01, 0x0e }, // ASCII-Code 0x67 => g (103) { 0x10, 0x10, 0x16, 0x19, 0x11, 0x11, 0x11 }, // ASCII-Code 0x68 => h (104) { 0x00, 0x04, 0x00, 0x04, 0x04, 0x04, 0x04 }, // ASCII-Code 0x69 => i (105) { 0x02, 0x00, 0x06, 0x02, 0x02, 0x12, 0x0c }, // ASCII-Code 0x6A => j (106) { 0x10, 0x10, 0x12, 0x14, 0x18, 0x14, 0x12 }, // ASCII-Code 0x6B => k (107) { 0x0c, 0x04, 0x04, 0x04, 0x04, 0x04, 0x0e }, // ASCII-Code 0x6C => l (108) { 0x00, 0x00, 0x1a, 0x15, 0x15, 0x11, 0x11 }, // ASCII-Code 0x6D => m (109) { 0x00, 0x00, 0x16, 0x19, 0x11, 0x11, 0x11 }, // ASCII-Code 0x6E => n (110) { 0x00, 0x00, 0x0e, 0x11, 0x11, 0x11, 0x0e }, // ASCII-Code 0x6F => o (111) { 0x00, 0x00, 0x1e, 0x11, 0x1e, 0x10, 0x10 }, // ASCII-Code 0x70 => p (112) { 0x00, 0x00, 0x0d, 0x13, 0x0f, 0x01, 0x01 }, // ASCII-Code 0x71 => q (113) { 0x00, 0x00, 0x16, 0x19, 0x10, 0x10, 0x10 }, // ASCII-Code 0x72 => r (114) { 0x00, 0x00, 0x0e, 0x10, 0x0e, 0x01, 0x1e }, // ASCII-Code 0x73 => s (115) { 0x08, 0x08, 0x1c, 0x08, 0x08, 0x08, 0x06 }, // ASCII-Code 0x74 => t (116) { 0x00, 0x00, 0x11, 0x11, 0x11, 0x13, 0x0d }, // ASCII-Code 0x75 => u (117) { 0x00, 0x00, 0x11, 0x11, 0x11, 0x0a, 0x04 }, // ASCII-Code 0x76 => v (118) { 0x00, 0x00, 0x11, 0x11, 0x15, 0x15, 0x0a }, // ASCII-Code 0x77 => w (119) { 0x00, 0x00, 0x11, 0x0a, 0x04, 0x0a, 0x11 }, // ASCII-Code 0x78 => x (120) { 0x00, 0x00, 0x11, 0x11, 0x0f, 0x01, 0x0e }, // ASCII-Code 0x79 => y (121) { 0x00, 0x00, 0x1f, 0x02, 0x04, 0x08, 0x1f }, // ASCII-Code 0x7A => z (122) { 0x04, 0x08, 0x08, 0x10, 0x08, 0x08, 0x04 }, // ASCII-Code 0x7B => { (123) � { 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04 }, // ASCII-Code 0x7C => | (124) � { 0x10, 0x08, 0x08, 0x04, 0x08, 0x08, 0x10 }, // ASCII-Code 0x7D => } (125) � { 0x00, 0x00, 0x00, 0x19, 0x26, 0x00, 0x00 } // ASCII-Code 0x7E => ~ (126) � }; #endif
10,471
C++
.h
293
31.235495
81
0.560531
ch570512/Qlockwork
36
22
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,994
Configuration.h
ch570512_Qlockwork/Configuration.h
//***************************************************************************** // Configuration.h // See README.txt for help //***************************************************************************** #ifndef CONFIGURATION_H #define CONFIGURATION_H //***************************************************************************** // Software settings //***************************************************************************** #define HOSTNAME "QLOCKWORK" #define WEBSITE_TITLE "QLOCKWORKs page" //#define DEDICATION "The only reason for time is so that everything doesn't happen at once.<br>(Albert Einstein)" #define WIFI_SETUP_TIMEOUT 120 #define WIFI_AP_PASS "12345678" #define OTA_PASS "1234" #define NTP_SERVER "pool.ntp.org" #define SHOW_IP //#define WIFI_BEEPS //#define NONE_TECHNICAL_ZERO #define AUTO_MODECHANGE_TIME 60 // seconds #define EVENT_TIME 300 // seconds #define ALARM_LED_COLOR RED //#define ABUSE_CORNER_LED_FOR_ALARM //#define POWERON_SELFTEST #define SHOW_MODE_AMPM #define SHOW_MODE_SECONDS #define SHOW_MODE_WEEKDAY #define SHOW_MODE_DATE #define SHOW_MODE_MOONPHASE //#define SHOW_MODE_SUNRISE_SUNSET // works only if APIKEY is defined #define SHOW_MODE_TEST #define WEATHER // Show weather data // Enter the location for which you want the current weather data displayed as latitude and longitude and the time zone. #define LATITUDE "56.2345678" #define LONGITUDE "12.123456789" #define TIMEZONE "Europe/Berlin" //#define FRONTCOVER_EN #define FRONTCOVER_DE_DE //#define FRONTCOVER_DE_SW //#define FRONTCOVER_DE_BA //#define FRONTCOVER_DE_SA //#define FRONTCOVER_DE_MKF_DE //#define FRONTCOVER_DE_MKF_SW //#define FRONTCOVER_DE_MKF_BA //#define FRONTCOVER_DE_MKF_SA //#define FRONTCOVER_D3 //#define FRONTCOVER_CH //#define FRONTCOVER_CH_GS //#define FRONTCOVER_ES //#define FRONTCOVER_FR //#define FRONTCOVER_IT //#define FRONTCOVER_NL //#define FRONTCOVER_BINARY //***************************************************************************** // Timezone //***************************************************************************** //#define TIMEZONE_IDLW // IDLW International Date Line West UTC-12 //#define TIMEZONE_SST // SST Samoa Standard Time UTC-11 //#define TIMEZONE_HST // HST Hawaiian Standard Time UTC-10 //#define TIMEZONE_AKST // AKST Alaska Standard Time UTC-9 //#define TIMEZONE_USPST // USPST Pacific Standard Time (USA) UTC-8 //#define TIMEZONE_USMST // USMST Mountain Standard Time (USA) UTC-7 //#define TIMEZONE_USAZ // USAZ Mountain Standard Time (USA) UTC-7 (no DST) //#define TIMEZONE_USCST // USCST Central Standard Time (USA) UTC-6 //#define TIMEZONE_USEST // USEST Eastern Standard Time (USA) UTC-5 //#define TIMEZONE_AST // AST Atlantic Standard Time UTC-4 //#define TIMEZONE_BST // BST Eastern Brazil Standard Time UTC-3 //#define TIMEZONE_VTZ // VTZ Greenland Eastern Standard Time UTC-2 //#define TIMEZONE_AZOT // AZOT Azores Time UTC-1 //#define TIMEZONE_GMT // GMT Greenwich Mean Time UTC #define TIMEZONE_CET // CET Central Europe Time UTC+1 //#define TIMEZONE_EST // EST Eastern Europe Time UTC+2 //#define TIMEZONE_MSK // MSK Moscow Time UTC+3 (no DST) //#define TIMEZONE_GST // GST Gulf Standard Time UTC+4 //#define TIMEZONE_PKT // PKT Pakistan Time UTC+5 //#define TIMEZONE_BDT // BDT Bangladesh Time UTC+6 //#define TIMEZONE_JT // JT Java Time UTC+7 //#define TIMEZONE_CNST // CNST China Standard Time UTC+8 //#define TIMEZONE_HKT // HKT Hong Kong Time UTC+8 //#define TIMEZONE_PYT // PYT Pyongyang Time (North Korea) UTC+8.5 //#define TIMEZONE_CWT // CWT Central West Time (Australia) UTC+8.75 //#define TIMEZONE_JST // JST Japan Standard Time UTC+9 //#define TIMEZONE_ACST // ACST Australian Central Standard Time UTC+9.5 //#define TIMEZONE_AEST // AEST Australian Eastern Standard Time UTC+10 //#define TIMEZONE_LHST // LHST Lord Howe Standard Time UTC+10.5 //#define TIMEZONE_SBT // SBT Solomon Islands Time UTC+11 //#define TIMEZONE_NZST // NZST New Zealand Standard Time UTC+12 //***************************************************************************** // Hardware settings //***************************************************************************** #define SERIAL_SPEED 115200 #define NUMPIXELS 115 //#define ONOFF_BUTTON //#define MODE_BUTTON //#define TIME_BUTTON #define ESP_LED #define MIN_BRIGHTNESS 20 #define MAX_BRIGHTNESS 255 #define TEST_BRIGHTNESS 80 //#define SENSOR_DHT22 #define DHT_TEMPERATURE_OFFSET 0.5 #define DHT_HUMIDITY_OFFSET -2.0 //#define RTC_BACKUP #define RTC_TEMPERATURE_OFFSET -1.15 //#define LDR //#define LDR_IS_INVERSE //#define BUZZER #define BUZZTIME_ALARM_1 30 #define BUZZTIME_ALARM_2 30 #define BUZZTIME_TIMER 30 //#define IR_RECEIVER //#define IR_CODE_ONOFF 16769565 // HX1838 Remote CH+ //#define IR_CODE_TIME 16753245 // HX1838 Remote CH- //#define IR_CODE_MODE 16736925 // HX1838 Remote CH #define IR_CODE_ONOFF 0xFFE01F // CLT2 V1.1 Remote Power #define IR_CODE_TIME 0xFFA05F // CLT2 V1.1 Remote Time #define IR_CODE_MODE 0xFF20DF // CLT2 V1.1 Remote Region //#define IR_LETTER_OFF #define IR_LETTER_X 8 #define IR_LETTER_Y 10 #define LED_LAYOUT_HORIZONTAL_1 //#define LED_LAYOUT_VERTICAL_1 //#define LED_LAYOUT_VERTICAL_2 //#define LED_LAYOUT_VERTICAL_3 #define NEOPIXEL_RGB //#define NEOPIXEL_RGBW #define NEOPIXEL_TYPE NEO_GRB + NEO_KHZ800 // see Adafruit_NeoPixel.h for help //#define NEOPIXEL_TYPE NEO_WRGB + NEO_KHZ800 //#define NEOPIXEL_TYPE NEO_GRBW + NEO_KHZ800 //***************************************************************************** // Misc //***************************************************************************** //#define DEBUG //#define DEBUG_WEB //#define DEBUG_IR //#define DEBUG_MATRIX //#define DEBUG_FPS //#define SYSLOGSERVER_SERVER "192.168.0.1" //#define SYSLOGSERVER_PORT 514 #define UPDATE_INFOSERVER "thorsten-wahl.ch" #define UPDATE_INFOFILE "/qlockwork/updateinfo.json" // ESP8266 #define PIN_IR_RECEIVER 16 // D0 (no interrupt) //#define PIN_WIRE_SCL 05 // D1 SCL //#define PIN_WIRE_SDA 04 // D2 SDA #define PIN_MODE_BUTTON 00 // D3 LOW_Flash #define PIN_LED 02 // D4 ESP8266_LED #define PIN_BUZZER 14 // D5 #define PIN_DHT22 12 // D6 #define PIN_LEDS_CLOCK 13 // D7 #define PIN_LEDS_DATA 15 // D8 #define PIN_LDR A0 // ADC #define PIN_TIME_BUTTON 01 // TXD0 #define PIN_ONOFF_BUTTON 03 // RXD0 // GPIO 06 to GPIO 11 are // used for flash memory databus #endif
6,711
C++
.h
157
40.33758
121
0.63698
ch570512/Qlockwork
36
22
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,996
Events.h
ch570512_Qlockwork/Events.h
/****************************************************************************** Events.h ******************************************************************************/ #ifndef EVENTS_H #define EVENTS_H struct event_t { uint8_t month; uint8_t day; String text; uint16_t year; eColor color; }; event_t events[] = { { 0, 0, "", 0, WHITE }, // Do not change { 1, 1, "Happy New Year!", 0, YELLOW_25 }, { 3, 14, "Albert Einsteins birthday!", 1879, MAGENTA }, { 12, 24, "It's Christmas!", 0, RED }, { 3, 12, "Qlockworks birthday!", 2017, MAGENTA } }; #endif
597
C++
.h
20
26.65
79
0.427574
ch570512/Qlockwork
36
22
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,997
Settings.h
ch570512_Qlockwork/Settings.h
//***************************************************************************** // Settings.h //***************************************************************************** #ifndef SETTINGS_H #define SETTINGS_H #include <Arduino.h> #include <EEPROM.h> #include "Colors.h" #include "Configuration.h" #include "Languages.h" #include "Modes.h" #define SETTINGS_MAGIC_NUMBER 0x2A #define SETTINGS_VERSION 25 class Settings { public: Settings(); ~Settings(); struct MySettings { uint8_t magicNumber; uint8_t version; boolean useAbc; int16_t brightness; uint8_t color; uint8_t colorChange; uint8_t transition; uint8_t timeout; boolean modeChange; boolean itIs; boolean alarm1; time_t alarm1Time; uint8_t alarm1Weekdays; boolean alarm2; time_t alarm2Time; uint8_t alarm2Weekdays; time_t nightOffTime; time_t dayOnTime; boolean hourBeep; } mySettings; void saveToEEPROM(); private: void resetToDefault(); void loadFromEEPROM(); }; #endif
1,123
C++
.h
44
20.25
79
0.556489
ch570512/Qlockwork
36
22
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,998
Numbers.h
ch570512_Qlockwork/Numbers.h
/****************************************************************************** Numbers.h ******************************************************************************/ #ifndef NUMBERS_H #define NUMBERS_H const char numbers[][5] = { { // 0 0b00011110, 0b00010010, 0b00010010, 0b00010010, 0b00011110 }, { // 1 0b00000100, 0b00001100, 0b00000100, 0b00000100, 0b00001110 }, { // 2 0b00011110, 0b00000010, 0b00011110, 0b00010000, 0b00011110 }, { // 3 0b00011110, 0b00000010, 0b00001110, 0b00000010, 0b00011110 }, { // 4 0b00010010, 0b00010010, 0b00011110, 0b00000010, 0b00000010 }, { // 5 0b00011110, 0b00010000, 0b00011110, 0b00000010, 0b00011110 }, { // 6 0b00011110, 0b00010000, 0b00011110, 0b00010010, 0b00011110 }, { // 7 0b00011110, 0b00000010, 0b00000100, 0b00000100, 0b00000100 }, { // 8 0b00011110, 0b00010010, 0b00011110, 0b00010010, 0b00011110 }, { // 9 0b00011110, 0b00010010, 0b00011110, 0b00000010, 0b00011110 } }; const char numbersBig[][7] = { { // 0 #ifdef NONE_TECHNICAL_ZERO 0b00001110, 0b00010001, 0b00010001, 0b00010001, 0b00010001, 0b00010001, 0b00001110 #else 0b00001110, 0b00010001, 0b00010011, 0b00010101, 0b00011001, 0b00010001, 0b00001110 #endif }, { // 1 0b00000100, 0b00001100, 0b00000100, 0b00000100, 0b00000100, 0b00000100, 0b00001110 }, { // 2 0b00001110, 0b00010001, 0b00000001, 0b00000010, 0b00000100, 0b00001000, 0b00011111 }, { // 3 0b00011111, 0b00000010, 0b00000100, 0b00000010, 0b00000001, 0b00010001, 0b00001110 }, { // 4 0b00000010, 0b00000110, 0b00001010, 0b00010010, 0b00011111, 0b00000010, 0b00000010 }, { // 5 0b00011111, 0b00010000, 0b00011110, 0b00000001, 0b00000001, 0b00010001, 0b00001110 }, { // 6 0b00000110, 0b00001000, 0b00010000, 0b00011110, 0b00010001, 0b00010001, 0b00001110 }, { // 7 0b00011111, 0b00000001, 0b00000010, 0b00000100, 0b00001000, 0b00001000, 0b00001000 }, { // 8 0b00001110, 0b00010001, 0b00010001, 0b00001110, 0b00010001, 0b00010001, 0b00001110 }, { // 9 0b00001110, 0b00010001, 0b00010001, 0b00001111, 0b00000001, 0b00000010, 0b00001100 } }; #endif
2,317
C++
.h
182
10.093407
79
0.656499
ch570512/Qlockwork
36
22
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,999
Colors.h
ch570512_Qlockwork/Colors.h
/****************************************************************************** Colors.h ******************************************************************************/ #ifndef COLORS_H #define COLORS_H enum eColorChange : uint8_t { COLORCHANGE_NO, // 0 COLORCHANGE_FIVE, // 1 COLORCHANGE_HOUR, // 2 COLORCHANGE_DAY, // 3 COLORCHANGE_COUNT = COLORCHANGE_DAY }; enum eColor : uint8_t { WHITE, RED, RED_25, RED_50, ORANGE, YELLOW, YELLOW_25, YELLOW_50, GREENYELLOW, GREEN, GREEN_25, GREEN_50, MINTGREEN, CYAN, CYAN_25, CYAN_50, LIGHTBLUE, BLUE, BLUE_25, BLUE_50, VIOLET, MAGENTA, MAGENTA_25, MAGENTA_50, PINK, COLOR_COUNT = PINK }; struct color_s { uint8_t red; uint8_t green; uint8_t blue; }; const color_s defaultColors[] = { { 0xFF, 0xFF, 0xFF }, // 00 WHITE { 0xFF, 0x00, 0x00 }, // 01 RED { 0xFF, 0x40, 0x40 }, // 02 RED_25 { 0xFF, 0x80, 0x80 }, // 03 RED_50 { 0xFF, 0x7F, 0x00 }, // 04 ORANGE { 0xFF, 0xFF, 0x00 }, // 05 YELLOW { 0xFF, 0xFF, 0x40 }, // 06 YELLOW_25 { 0xFF, 0xFF, 0x80 }, // 07 YELLOW_50 { 0x7F, 0xFF, 0x00 }, // 08 GREENYELLOW { 0x00, 0xFF, 0x00 }, // 09 GREEN { 0x40, 0xFF, 0x40 }, // 10 GREEN_25 { 0x80, 0xFF, 0x80 }, // 11 GREEN_50 { 0x00, 0xFF, 0x7F }, // 12 MINTGREEN { 0x00, 0xFF, 0xFF }, // 13 CYAN { 0x40, 0xFF, 0xFF }, // 14 CYAN_25 { 0x80, 0xFF, 0xFF }, // 15 CYAN_50 { 0x00, 0x7F, 0xFF }, // 16 LIGHTBLUE { 0x00, 0x00, 0xFF }, // 17 BLUE { 0x40, 0x40, 0xFF }, // 18 BLUE_25 { 0x80, 0x80, 0xFF }, // 19 BLUE_50 { 0x7F, 0x00, 0xFF }, // 20 VIOLET { 0xFF, 0x00, 0xFF }, // 21 MAGENTA { 0xFF, 0x40, 0xFF }, // 22 MAGENTA_25 { 0xFF, 0x80, 0xFF }, // 23 MAGENTA_50 { 0xFF, 0x00, 0x7F } // 24 PINK }; #endif
1,790
C++
.h
77
21.246753
79
0.542183
ch570512/Qlockwork
36
22
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,000
Modes.h
ch570512_Qlockwork/Modes.h
//****************************************************************************** // Modes.h //****************************************************************************** #ifndef MODES_H #define MODES_H typedef enum eMode : uint8_t { MODE_TIME, // 0 #ifdef SHOW_MODE_AMPM MODE_AMPM, // 1 #endif #ifdef SHOW_MODE_SECONDS MODE_SECONDS, // 2 if SHOW_MODE_AMPM is set - 1 if not set and so on... #endif #ifdef SHOW_MODE_WEEKDAY MODE_WEEKDAY, // 3 if... #endif #ifdef SHOW_MODE_DATE MODE_DATE, // 4 #endif #if defined(SHOW_MODE_SUNRISE_SUNSET) && defined(WEATHER) MODE_SUNRISE, // 5 MODE_SUNSET, // 6 #endif #ifdef SHOW_MODE_MOONPHASE MODE_MOONPHASE, // 7 #endif #if defined(RTC_BACKUP) || defined(SENSOR_DHT22) MODE_TEMP, // 8 #endif #ifdef SENSOR_DHT22 MODE_HUMIDITY, // 9 #endif #ifdef WEATHER MODE_EXT_TEMP, // 10 MODE_EXT_HUMIDITY, // 11 #endif #ifdef BUZZER MODE_TIMER, // 12 #endif #ifdef SHOW_MODE_TEST MODE_TEST, // 13 MODE_RED, // 14 MODE_GREEN, // 15 MODE_BLUE, // 16 MODE_WHITE, // 17 #endif MODE_COUNT, // 18 MODE_BLANK, // 19 MODE_FEED // 20 } Mode; // Overload the ControlType++ operator. inline Mode& operator++(Mode& eDOW, int) { const uint8_t i = static_cast<uint8_t>(eDOW) + 1; eDOW = static_cast<Mode>((i) % MODE_COUNT); return eDOW; } enum eTransition { TRANSITION_NORMAL, // 0 TRANSITION_MOVEUP, // 1 TRANSITION_FADE // 2 }; #endif
1,593
C++
.h
65
20.692308
81
0.535573
ch570512/Qlockwork
36
22
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,001
Words.h
ch570512_Qlockwork/Words.h
//****************************************************************************** // Words.h //****************************************************************************** #ifndef WORDS_H #define WORDS_H #if defined(FRONTCOVER_CH) || defined(FRONTCOVER_CH_GS) #define CH_VOR matrix[2] |= 0b0000000011100000 #define CH_AB matrix[3] |= 0b1100000000000000 #define CH_ESISCH matrix[0] |= 0b1101111000000000 #define CH_GSI matrix[9] |= 0b0000000011100000 #define CH_AM matrix[9] |= 0b0000001100000000 #define CH_PM matrix[3] |= 0b0000000001100000 #define CH_FUEF matrix[0] |= 0b0000000011100000 #define CH_ZAEAE matrix[1] |= 0b0000000011100000 #define CH_VIERTU matrix[1] |= 0b1111110000000000 #define CH_ZWAENZG matrix[2] |= 0b1111110000000000 #define CH_HAUBI matrix[3] |= 0b0001111100000000 #define CH_H_EIS matrix[4] |= 0b1110000000000000 #define CH_H_ZWOEI matrix[4] |= 0b0001111000000000 #define CH_H_DRUE matrix[4] |= 0b0000000011100000 #define CH_H_VIER matrix[5] |= 0b1111100000000000 #define CH_H_FUEFI matrix[5] |= 0b0000011110000000 #define CH_H_SAECHSI matrix[6] |= 0b1111110000000000 #define CH_H_SIEBNI matrix[6] |= 0b0000001111100000 #define CH_H_ACHTI matrix[7] |= 0b1111100000000000 #define CH_H_NUENI matrix[7] |= 0b0000011110000000 #define CH_H_ZAENI matrix[8] |= 0b1111000000000000 #define CH_H_EUFI matrix[8] |= 0b0000000111100000 #define CH_H_ZWOEUFI matrix[9] |= 0b1111110000000000 #endif #if defined(FRONTCOVER_D3) #define D3_ESISCH matrix[0] |= 0b1101111000000000 #define D3_VOR matrix[3] |= 0b0000000011100000 #define D3_NACH matrix[3] |= 0b1111000000000000 #define D3_AM matrix[0] |= 0b1000000000000000 #define D3_PM matrix[0] |= 0b0100000000000000 #define D3_FUENF matrix[2] |= 0b0000000111100000 #define D3_ZEHN matrix[2] |= 0b1111000000000000 #define D3_VIERTL matrix[1] |= 0b0000111111000000 #define D3_HALB matrix[4] |= 0b1111000000000000 #define D3_DREIVIERTL matrix[1] |= 0b1111111111000000 #define D3_H_OISE matrix[5] |= 0b1111000000000000 #define D3_H_ZWOIE matrix[6] |= 0b1111100000000000 #define D3_H_DREIE matrix[7] |= 0b1111100000000000 #define D3_H_VIERE matrix[9] |= 0b0000001111100000 #define D3_H_FUENFE matrix[4] |= 0b0000011111000000 #define D3_H_SECHSE matrix[5] |= 0b0011111100000000 #define D3_H_SIEBNE matrix[9] |= 0b1111110000000000 #define D3_H_ACHTE matrix[6] |= 0b0000011111000000 #define D3_H_NEUNE matrix[8] |= 0b0001111100000000 #define D3_H_ZEHNE matrix[8] |= 0b1111100000000000 #define D3_H_ELFE matrix[5] |= 0b0000000111100000 #define D3_H_ZWOELFE matrix[7] |= 0b0000011111100000 #endif #if defined(FRONTCOVER_DE_DE) || defined(FRONTCOVER_DE_SW) || defined(FRONTCOVER_DE_BA) || defined(FRONTCOVER_DE_SA) #define DE_VOR matrix[3] |= 0b1110000000000000 #define DE_NACH matrix[3] |= 0b0000000111100000 #define DE_ESIST matrix[0] |= 0b1101110000000000 #define DE_UHR matrix[9] |= 0b0000000011100000 #define DE_AM matrix[5] |= 0b0000011000000000 #define DE_PM matrix[6] |= 0b0000110000000000 #define DE_FUENF matrix[0] |= 0b0000000111100000 #define DE_ZEHN matrix[1] |= 0b1111000000000000 #define DE_VIERTEL matrix[2] |= 0b0000111111100000 #define DE_ZWANZIG matrix[1] |= 0b0000111111100000 #define DE_HALB matrix[4] |= 0b1111000000000000 #define DE_DREIVIERTEL matrix[2] |= 0b1111111111100000 #define DE_H_EIN matrix[5] |= 0b1110000000000000 #define DE_H_EINS matrix[5] |= 0b1111000000000000 #define DE_H_ZWEI matrix[5] |= 0b0000000111100000 #define DE_H_DREI matrix[6] |= 0b1111000000000000 #define DE_H_VIER matrix[6] |= 0b0000000111100000 #define DE_H_FUENF matrix[4] |= 0b0000000111100000 #define DE_H_SECHS matrix[7] |= 0b1111100000000000 #define DE_H_SIEBEN matrix[8] |= 0b1111110000000000 #define DE_H_ACHT matrix[7] |= 0b0000000111100000 #define DE_H_NEUN matrix[9] |= 0b0001111000000000 #define DE_H_ZEHN matrix[9] |= 0b1111000000000000 #define DE_H_ELF matrix[4] |= 0b0000011100000000 #define DE_H_ZWOELF matrix[8] |= 0b0000001111100000 #endif #if defined(FRONTCOVER_DE_MKF_DE) || defined(FRONTCOVER_DE_MKF_SW) || defined(FRONTCOVER_DE_MKF_BA) || defined(FRONTCOVER_DE_MKF_SA) #define DE_MKF_VOR matrix[3] |= 0b0000001110000000 #define DE_MKF_NACH matrix[3] |= 0b0011110000000000 #define DE_MKF_ESIST matrix[0] |= 0b1101110000000000 #define DE_MKF_UHR matrix[9] |= 0b0000000011100000 #define DE_MKF_AM matrix[0] |= 0b1000000000000000 #define DE_MKF_PM matrix[0] |= 0b0100000000000000 #define DE_MKF_FUENF matrix[0] |= 0b0000000111100000 #define DE_MKF_ZEHN matrix[1] |= 0b1111000000000000 #define DE_MKF_VIERTEL matrix[2] |= 0b0000111111100000 #define DE_MKF_ZWANZIG matrix[1] |= 0b0000111111100000 #define DE_MKF_HALB matrix[4] |= 0b1111000000000000 #define DE_MKF_DREIVIERTEL matrix[2] |= 0b1111111111100000 #define DE_MKF_H_EIN matrix[5] |= 0b0011100000000000 #define DE_MKF_H_EINS matrix[5] |= 0b0011110000000000 #define DE_MKF_H_ZWEI matrix[5] |= 0b1111000000000000 #define DE_MKF_H_DREI matrix[6] |= 0b0111100000000000 #define DE_MKF_H_VIER matrix[7] |= 0b0000000111100000 #define DE_MKF_H_FUENF matrix[6] |= 0b0000000111100000 #define DE_MKF_H_SECHS matrix[9] |= 0b0111110000000000 #define DE_MKF_H_SIEBEN matrix[5] |= 0b0000011111100000 #define DE_MKF_H_ACHT matrix[8] |= 0b0111100000000000 #define DE_MKF_H_NEUN matrix[7] |= 0b0001111000000000 #define DE_MKF_H_ZEHN matrix[8] |= 0b0000011110000000 #define DE_MKF_H_ELF matrix[7] |= 0b1110000000000000 #define DE_MKF_H_ZWOELF matrix[4] |= 0b0000011111000000 #endif #if defined(FRONTCOVER_EN) #define EN_ITIS matrix[0] |= 0b1101100000000000 #define EN_TIME matrix[0] |= 0b0000000111100000 #define EN_A matrix[1] |= 0b1000000000000000 #define EN_OCLOCK matrix[9] |= 0b0000011111100000 #define EN_AM matrix[0] |= 0b0000000110000000 #define EN_PM matrix[0] |= 0b0000000001100000 #define EN_QUATER matrix[1] |= 0b0011111110000000 #define EN_TWENTY matrix[2] |= 0b1111110000000000 #define EN_FIVE matrix[2] |= 0b0000001111000000 #define EN_HALF matrix[3] |= 0b1111000000000000 #define EN_TEN matrix[3] |= 0b0000011100000000 #define EN_TO matrix[3] |= 0b0000000001100000 #define EN_PAST matrix[4] |= 0b1111000000000000 #define EN_H_NINE matrix[4] |= 0b0000000111100000 #define EN_H_ONE matrix[5] |= 0b1110000000000000 #define EN_H_SIX matrix[5] |= 0b0001110000000000 #define EN_H_THREE matrix[5] |= 0b0000001111100000 #define EN_H_FOUR matrix[6] |= 0b1111000000000000 #define EN_H_FIVE matrix[6] |= 0b0000111100000000 #define EN_H_TWO matrix[6] |= 0b0000000011100000 #define EN_H_EIGHT matrix[7] |= 0b1111100000000000 #define EN_H_ELEVEN matrix[7] |= 0b0000011111100000 #define EN_H_SEVEN matrix[8] |= 0b1111100000000000 #define EN_H_TWELVE matrix[8] |= 0b0000011111100000 #define EN_H_TEN matrix[9] |= 0b1110000000000000 #endif #if defined(FRONTCOVER_ES) #define ES_SONLAS matrix[0] |= 0b0111011100000000 #define ES_ESLA matrix[0] |= 0b1100011000000000 #define ES_Y matrix[6] |= 0b0000010000000000 #define ES_MENOS matrix[6] |= 0b0000001111100000 #define ES_AM matrix[0] |= 0b1000000000000000 #define ES_PM matrix[0] |= 0b0100000000000000 #define ES_CINCO matrix[8] |= 0b0000001111100000 #define ES_DIEZ matrix[7] |= 0b0000000111100000 #define ES_CUARTO matrix[9] |= 0b0000011111100000 #define ES_VEINTE matrix[7] |= 0b0111111000000000 #define ES_VEINTICINCO matrix[8] |= 0b1111111111100000 #define ES_MEDIA matrix[9] |= 0b1111100000000000 #define ES_H_UNA matrix[0] |= 0b0000000011100000 #define ES_H_DOS matrix[1] |= 0b1110000000000000 #define ES_H_TRES matrix[1] |= 0b0000111100000000 #define ES_H_CUATRO matrix[2] |= 0b1111110000000000 #define ES_H_CINCO matrix[2] |= 0b0000001111100000 #define ES_H_SEIS matrix[3] |= 0b1111000000000000 #define ES_H_SIETE matrix[3] |= 0b0000011111000000 #define ES_H_OCHO matrix[4] |= 0b1111000000000000 #define ES_H_NUEVE matrix[4] |= 0b0000111110000000 #define ES_H_DIEZ matrix[5] |= 0b0011110000000000 #define ES_H_ONCE matrix[5] |= 0b0000000111100000 #define ES_H_DOCE matrix[6] |= 0b1111000000000000 #endif #if defined(FRONTCOVER_FR) #define FR_TRAIT matrix[8] |= 0b0000010000000000 #define FR_ET matrix[7] |= 0b1100000000000000 #define FR_LE matrix[6] |= 0b0000001100000000 #define FR_MOINS matrix[6] |= 0b1111100000000000 #define FR_ILEST matrix[0] |= 0b1101110000000000 #define FR_HEURE matrix[5] |= 0b0000011111000000 #define FR_HEURES matrix[5] |= 0b0000011111100000 #define FR_AM matrix[7] |= 0b0000000001100000 #define FR_PM matrix[9] |= 0b0000000011000000 #define FR_CINQ matrix[8] |= 0b0000001111000000 #define FR_DIX matrix[6] |= 0b0000000011100000 #define FR_QUART matrix[7] |= 0b0001111100000000 #define FR_VINGT matrix[8] |= 0b1111100000000000 #define FR_DEMIE matrix[9] |= 0b0001111100000000 #define FR_H_UNE matrix[2] |= 0b0000111000000000 #define FR_H_DEUX matrix[0] |= 0b0000000111100000 #define FR_H_TROIS matrix[1] |= 0b0000001111100000 #define FR_H_QUATRE matrix[1] |= 0b1111110000000000 #define FR_H_CINQ matrix[3] |= 0b0000000111100000 #define FR_H_SIX matrix[3] |= 0b0000111000000000 #define FR_H_SEPT matrix[2] |= 0b0000000111100000 #define FR_H_HUIT matrix[3] |= 0b1111000000000000 #define FR_H_NEUF matrix[2] |= 0b1111000000000000 #define FR_H_DIX matrix[4] |= 0b0011100000000000 #define FR_H_ONZE matrix[5] |= 0b1111000000000000 #define FR_H_MIDI matrix[4] |= 0b1111000000000000 #define FR_H_MINUIT matrix[4] |= 0b0000011111100000 #endif #if defined(FRONTCOVER_IT) #define IT_SONOLE matrix[0] |= 0b1111011000000000 #define IT_LE matrix[0] |= 0b0000011000000000 #define IT_ORE matrix[0] |= 0b0000000011100000 #define IT_E matrix[1] |= 0b1000000000000000 #define IT_AM matrix[0] |= 0b1000000000000000 #define IT_PM matrix[0] |= 0b0100000000000000 #define IT_H_LUNA matrix[1] |= 0b0011110000000000 #define IT_H_DUE matrix[1] |= 0b0000000111000000 #define IT_H_TRE matrix[2] |= 0b1110000000000000 #define IT_H_OTTO matrix[2] |= 0b0001111000000000 #define IT_H_NOVE matrix[2] |= 0b0000000111100000 #define IT_H_DIECI matrix[3] |= 0b1111100000000000 #define IT_H_UNDICI matrix[3] |= 0b0000011111100000 #define IT_H_DODICI matrix[4] |= 0b1111110000000000 #define IT_H_SETTE matrix[4] |= 0b0000001111100000 #define IT_H_QUATTRO matrix[5] |= 0b1111111000000000 #define IT_H_SEI matrix[5] |= 0b0000000011100000 #define IT_H_CINQUE matrix[6] |= 0b1111110000000000 #define IT_MENO matrix[6] |= 0b0000000111100000 #define IT_E2 matrix[7] |= 0b1000000000000000 #define IT_UN matrix[7] |= 0b0011000000000000 #define IT_QUARTO matrix[7] |= 0b0000011111100000 #define IT_VENTI matrix[8] |= 0b1111100000000000 #define IT_CINQUE matrix[8] |= 0b0000011111100000 #define IT_DIECI matrix[9] |= 0b1111100000000000 #define IT_MEZZA matrix[9] |= 0b0000001111100000 #endif #if defined(FRONTCOVER_NL) #define NL_VOOR matrix[1] |= 0b0000000111100000 #define NL_OVER matrix[2] |= 0b1111000000000000 #define NL_VOOR2 matrix[4] |= 0b1111000000000000 #define NL_OVER2 matrix[3] |= 0b0000000111100000 #define NL_HETIS matrix[0] |= 0b1110110000000000 #define NL_UUR matrix[9] |= 0b0000000011100000 #define NL_AM matrix[0] |= 0b1000000000000000 #define NL_PM matrix[0] |= 0b0100000000000000 #define NL_VIJF matrix[0] |= 0b0000000111100000 #define NL_TIEN matrix[1] |= 0b1111000000000000 #define NL_KWART matrix[2] |= 0b0000001111100000 #define NL_ZWANZIG matrix[1] |= 0b0000111111100000 #define NL_HALF matrix[3] |= 0b1111000000000000 #define NL_H_EEN matrix[4] |= 0b0000000111000000 #define NL_H_EENS matrix[4] |= 0b0000000111100000 #define NL_H_TWEE matrix[5] |= 0b1111000000000000 #define NL_H_DRIE matrix[5] |= 0b0000000111100000 #define NL_H_VIER matrix[6] |= 0b1111000000000000 #define NL_H_VIJF matrix[6] |= 0b0000111100000000 #define NL_H_ZES matrix[6] |= 0b0000000011100000 #define NL_H_ZEVEN matrix[7] |= 0b1111100000000000 #define NL_H_ACHT matrix[8] |= 0b1111000000000000 #define NL_H_NEGEN matrix[7] |= 0b0000001111100000 #define NL_H_TIEN matrix[8] |= 0b0000111100000000 #define NL_H_ELF matrix[8] |= 0b0000000011100000 #define NL_H_TWAALF matrix[9] |= 0b1111110000000000 #endif #endif
12,373
C++
.h
247
48.902834
132
0.740873
ch570512/Qlockwork
36
22
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,003
Languages.h
ch570512_Qlockwork/Languages.h
//***************************************************************************** // Languages.h //***************************************************************************** #ifndef LANGUAGES_H #define LANGUAGES_H #if defined(FRONTCOVER_EN) || defined(FRONTCOVER_BINARY) const char sWeekday[][2] = { { ' ', ' ' }, // 00 { 'S', 'U' }, // 01 { 'M', 'O' }, // 02 { 'T', 'U' }, // 03 { 'W', 'E' }, // 04 { 'T', 'H' }, // 05 { 'F', 'R' }, // 06 { 'S', 'A' } // 07 }; #define LANGSTR "en" #define TXT_SETTINGS "Settings" #define TXT_ALARM "Alarm" #define TXT_ON "on" #define TXT_OFF "off" #define TXT_HOURBEEP "Hourly beep" #define TXT_TIMER "Timer" #define TXT_MINUTES "minutes" #endif #if defined(FRONTCOVER_DE_DE) || defined(FRONTCOVER_DE_SW) || defined(FRONTCOVER_DE_BA) || defined(FRONTCOVER_DE_SA) || defined(FRONTCOVER_D3) || defined(FRONTCOVER_DE_MKF_DE) || defined(FRONTCOVER_DE_MKF_SW) || defined(FRONTCOVER_DE_MKF_BA) || defined(FRONTCOVER_DE_MKF_SA) || defined(FRONTCOVER_CH) || defined(FRONTCOVER_CH_GS) const char sWeekday[][2] = { { ' ', ' ' }, // 00 { 'S', 'O' }, // 01 { 'M', 'O' }, // 02 { 'D', 'I' }, // 03 { 'M', 'I' }, // 04 { 'D', 'O' }, // 05 { 'F', 'R' }, // 06 { 'S', 'A' } // 07 }; #define LANGSTR "de" #define TXT_SETTINGS "Einstellungen" #define TXT_ALARM "Wecker" #define TXT_ON "ein" #define TXT_OFF "aus" #define TXT_HOURBEEP "Stundenalarm" #define TXT_TIMER "Timer" #define TXT_MINUTES "Minuten" #endif #if defined(FRONTCOVER_FR) const char sWeekday[][2] = { { ' ', ' ' }, // 00 { 'D', 'I' }, // 01 { 'L', 'U' }, // 02 { 'M', 'A' }, // 03 { 'M', 'E' }, // 04 { 'J', 'E' }, // 05 { 'V', 'E' }, // 06 { 'S', 'A' } // 07 }; #define LANGSTR "fr" #define TXT_SETTINGS "Param�tres" #define TXT_ALARM "R�veil" #define TXT_ON "on" #define TXT_OFF "off" #define TXT_HOURBEEP "Alarme heure" #define TXT_TIMER "Minuteur" #define TXT_MINUTES "Minutes" #endif #if defined(FRONTCOVER_IT) const char sWeekday[][2] = { { ' ', ' ' }, // 00 { 'D', 'O' }, // 01 { 'L', 'U' }, // 02 { 'M', 'A' }, // 03 { 'M', 'E' }, // 04 { 'G', 'I' }, // 05 { 'V', 'E' }, // 06 { 'S', 'A' } // 07 }; #define LANGSTR "it" #define TXT_SETTINGS "Settings" #define TXT_ALARM "Alarm" #define TXT_ON "on" #define TXT_OFF "off" #define TXT_HOURBEEP "Hourly beep" #define TXT_TIMER "Timer" #define TXT_MINUTES "minutes" #endif #if defined(FRONTCOVER_ES) const char sWeekday[][2] = { { ' ', ' ' }, // 00 { 'D', 'O' }, // 01 { 'L', 'U' }, // 02 { 'M', 'A' }, // 03 { 'M', 'I' }, // 04 { 'J', 'U' }, // 05 { 'V', 'I' }, // 06 { 'S', 'A' } // 07 }; #define LANGSTR "es" #define TXT_SETTINGS "Settings" #define TXT_ALARM "Alarm" #define TXT_ON "on" #define TXT_OFF "off" #define TXT_HOURBEEP "Hourly beep" #define TXT_TIMER "Timer" #define TXT_MINUTES "minutes" #endif #if defined(FRONTCOVER_NL) const char sWeekday[][2] = { { ' ', ' ' }, // 00 { 'Z', 'O' }, // 01 { 'M', 'A' }, // 02 { 'D', 'I' }, // 03 { 'W', 'O' }, // 04 { 'D', 'O' }, // 05 { 'V', 'R' }, // 06 { 'Z', 'A' } // 07 }; #define LANGSTR "nl" #define TXT_SETTINGS "Settings" #define TXT_ALARM "Alarm" #define TXT_ON "on" #define TXT_OFF "off" #define TXT_HOURBEEP "Hourly beep" #define TXT_TIMER "Timer" #define TXT_MINUTES "minutes" #endif #endif
3,402
C++
.h
126
24.380952
329
0.515931
ch570512/Qlockwork
36
22
0
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,005
Meander.cpp
knchaffin_Meander/src/Meander.cpp
/* Copyright (C) 2019-2020 Ken Chaffin 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, version 3. 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 <https://www.gnu.org/licenses/>. */ #include <rack.hpp> #include "plugin.hpp" #include <sstream> #include <iomanip> #include <time.h> #include <iostream> #include <fstream> #include <string> #include <mutex> #include "Meander.hpp" // the following is for performance profiling under Windows by the developer and should not be defined in the release distribution // #define _USE_WINDOWS_PERFTIME #if defined(_USE_WINDOWS_PERFTIME) #include <windows.h> #endif struct Meander : Module { bool instanceRunning = false; enum ParamIds { BUTTON_RUN_PARAM, BUTTON_RESET_PARAM, CONTROL_TEMPOBPM_PARAM, CONTROL_TIMESIGNATURETOP_PARAM, CONTROL_TIMESIGNATUREBOTTOM_PARAM, CONTROL_ROOT_KEY_PARAM, CONTROL_SCALE_PARAM, BUTTON_CIRCLESTEP_C_PARAM, BUTTON_CIRCLESTEP_G_PARAM, BUTTON_CIRCLESTEP_D_PARAM, BUTTON_CIRCLESTEP_A_PARAM, BUTTON_CIRCLESTEP_E_PARAM, BUTTON_CIRCLESTEP_B_PARAM, BUTTON_CIRCLESTEP_GBFS_PARAM, BUTTON_CIRCLESTEP_DB_PARAM, BUTTON_CIRCLESTEP_AB_PARAM, BUTTON_CIRCLESTEP_EB_PARAM, BUTTON_CIRCLESTEP_BB_PARAM, BUTTON_CIRCLESTEP_F_PARAM, BUTTON_HARMONY_SETSTEP_1_PARAM, BUTTON_HARMONY_SETSTEP_2_PARAM, BUTTON_HARMONY_SETSTEP_3_PARAM, BUTTON_HARMONY_SETSTEP_4_PARAM, BUTTON_HARMONY_SETSTEP_5_PARAM, BUTTON_HARMONY_SETSTEP_6_PARAM, BUTTON_HARMONY_SETSTEP_7_PARAM, BUTTON_HARMONY_SETSTEP_8_PARAM, BUTTON_HARMONY_SETSTEP_9_PARAM, BUTTON_HARMONY_SETSTEP_10_PARAM, BUTTON_HARMONY_SETSTEP_11_PARAM, BUTTON_HARMONY_SETSTEP_12_PARAM, BUTTON_HARMONY_SETSTEP_13_PARAM, BUTTON_HARMONY_SETSTEP_14_PARAM, BUTTON_HARMONY_SETSTEP_15_PARAM, BUTTON_HARMONY_SETSTEP_16_PARAM, BUTTON_ENABLE_MELODY_PARAM, CONTROL_MELODY_VOLUME_PARAM, BUTTON_MELODY_DESTUTTER_PARAM, CONTROL_MELODY_NOTE_LENGTH_DIVISOR_PARAM, CONTROL_MELODY_TARGETOCTAVE_PARAM, CONTROL_MELODY_ALPHA_PARAM, CONTROL_MELODY_RANGE_PARAM, BUTTON_ENABLE_ARP_PARAM, CONTROL_ARP_COUNT_PARAM, CONTROL_ARP_INCREMENT_PARAM, CONTROL_ARP_DECAY_PARAM, CONTROL_ARP_PATTERN_PARAM, BUTTON_ENABLE_ARP_CHORDAL_PARAM, BUTTON_ENABLE_ARP_SCALER_PARAM, BUTTON_ENABLE_HARMONY_PARAM, BUTTON_HARMONY_DESTUTTER_PARAM, CONTROL_HARMONY_VOLUME_PARAM, CONTROL_HARMONY_STEPS_PARAM, CONTROL_HARMONY_TARGETOCTAVE_PARAM, CONTROL_HARMONY_ALPHA_PARAM, CONTROL_HARMONY_RANGE_PARAM, CONTROL_HARMONY_DIVISOR_PARAM, CONTROL_HARMONYPRESETS_PARAM, BUTTON_ENABLE_BASS_PARAM, CONTROL_BASS_VOLUME_PARAM, CONTROL_BASS_TARGETOCTAVE_PARAM, BUTTON_BASS_ACCENT_PARAM, BUTTON_BASS_SYNCOPATE_PARAM, BUTTON_BASS_SHUFFLE_PARAM, CONTROL_BASS_DIVISOR_PARAM, CONTROL_HARMONY_FBM_OCTAVES_PARAM, CONTROL_MELODY_FBM_OCTAVES_PARAM, CONTROL_ARP_FBM_OCTAVES_PARAM, CONTROL_HARMONY_FBM_PERIOD_PARAM, CONTROL_MELODY_FBM_PERIOD_PARAM, CONTROL_ARP_FBM_PERIOD_PARAM, BUTTON_ENABLE_MELODY_CHORDAL_PARAM, BUTTON_ENABLE_MELODY_SCALER_PARAM, BUTTON_ENABLE_HARMONY_ALL7THS_PARAM, BUTTON_ENABLE_HARMONY_V7THS_PARAM, BUTTON_ENABLE_HARMONY_STACCATO_PARAM, BUTTON_ENABLE_MELODY_STACCATO_PARAM, BUTTON_ENABLE_BASS_STACCATO_PARAM, BUTTON_BASS_OCTAVES_PARAM, BUTTON_PROG_STEP_PARAM, NUM_PARAMS }; enum InputIds { IN_RUN_EXT_CV, IN_RESET_EXT_CV, IN_TEMPO_EXT_CV, IN_TIMESIGNATURETOP_EXT_CV, IN_TIMESIGNATUREBOTTOM_EXT_CV, IN_ROOT_KEY_EXT_CV, IN_SCALE_EXT_CV, IN_CLOCK_EXT_CV, IN_HARMONY_CIRCLE_DEGREE_EXT_CV, IN_HARMONY_CIRCLE_DEGREE_GATE_EXT_CV, IN_MELODY_ENABLE_EXT_CV, IN_MELODY_VOLUME_EXT_CV, IN_MELODY_DESTUTTER_EXT_CV, IN_MELODY_NOTE_LENGTH_DIVISOR_EXT_CV, IN_MELODY_TARGETOCTAVE_EXT_CV, IN_MELODY_ALPHA_EXT_CV, IN_MELODY_RANGE_EXT_CV, IN_ARP_ENABLE_EXT_CV, IN_ARP_COUNT_EXT_CV, IN_ARP_INCREMENT_EXT_CV, IN_ARP_DECAY_EXT_CV, IN_ARP_PATTERN_EXT_CV, IN_ENABLE_ARP_CHORDAL_EXT_CV, IN_ENABLE_ARP_SCALER_EXT_CV, IN_HARMONY_ENABLE_EXT_CV, IN_HARMONY_DESTUTTER_EXT_CV, IN_HARMONY_VOLUME_EXT_CV, IN_HARMONY_STEPS_EXT_CV, IN_HARMONY_TARGETOCTAVE_EXT_CV, IN_HARMONY_ALPHA_EXT_CV, IN_HARMONY_RANGE_EXT_CV, IN_HARMONY_DIVISOR_EXT_CV, IN_HARMONYPRESETS_EXT_CV, IN_BASS_ENABLE_EXT_CV, IN_BASS_VOLUME_EXT_CV, IN_BASS_TARGETOCTAVE_EXT_CV, IN_BASS_ACCENT_EXT_CV, IN_BASS_SYNCOPATE_EXT_CV, IN_BASS_SHUFFLE_EXT_CV, IN_BASS_DIVISOR_EXT_CV, IN_HARMONY_FBM_OCTAVES_EXT_CV, IN_MELODY_FBM_OCTAVES_EXT_CV, IN_ARP_FBM_OCTAVES_EXT_CV, IN_HARMONY_FBM_PERIOD_EXT_CV, IN_MELODY_FBM_PERIOD_EXT_CV, IN_ARP_FBM_PERIOD_EXT_CV, IN_ENABLE_MELODY_CHORDAL_EXT_CV, IN_MELODY_SCALER_EXT_CV, IN_ENABLE_HARMONY_ALL7THS_EXT_CV, IN_ENABLE_HARMONY_V7THS_EXT_CV, IN_ENABLE_HARMONY_STACCATO_EXT_CV, IN_ENABLE_MELODY_STACCATO_EXT_CV, IN_ENABLE_BASS_STACCATO_EXT_CV, IN_BASS_OCTAVES_EXT_CV, IN_PROG_STEP_EXT_CV, IN_MELODY_SCALE_DEGREE_EXT_CV, IN_MELODY_SCALE_GATE_EXT_CV, NUM_INPUTS }; enum OutputIds { OUT_RUN_OUT, OUT_RESET_OUT, OUT_TEMPO_OUT, OUT_CLOCK_OUT, OUT_MELODY_GATE_OUTPUT, OUT_HARMONY_GATE_OUTPUT, OUT_BASS_GATE_OUTPUT, OUT_FBM_HARMONY_OUTPUT, OUT_MELODY_CV_OUTPUT, OUT_FBM_MELODY_OUTPUT, OUT_BASS_CV_OUTPUT, OUT_HARMONY_CV_OUTPUT, OUT_CLOCK_BEATX2_OUTPUT, OUT_CLOCK_BAR_OUTPUT, OUT_CLOCK_BEATX4_OUTPUT, OUT_CLOCK_BEATX8_OUTPUT, OUT_CLOCK_BEAT_OUTPUT, OUT_BASS_TRIGGER_OUTPUT, OUT_HARMONY_TRIGGER_OUTPUT, OUT_MELODY_TRIGGER_OUTPUT, OUT_FBM_ARP_OUTPUT, OUT_MELODY_VOLUME_OUTPUT, OUT_HARMONY_VOLUME_OUTPUT, OUT_BASS_VOLUME_OUTPUT, OUT_EXT_POLY_SCALE_OUTPUT, NUM_OUTPUTS }; enum LightIds { LIGHT_LEDBUTTON_HARMONY_ENABLE, LIGHT_LEDBUTTON_MELODY_ENABLE, LIGHT_LEDBUTTON_ARP_ENABLE, LIGHT_LEDBUTTON_ARP_ENABLE_CHORDAL, LIGHT_LEDBUTTON_ARP_ENABLE_SCALER, LIGHT_LEDBUTTON_BASS_ENABLE, LIGHT_LEDBUTTON_RUN, LIGHT_LEDBUTTON_RESET, LIGHT_LEDBUTTON_MELODY_DESTUTTER, LIGHT_LEDBUTTON_CIRCLESTEP_1, LIGHT_LEDBUTTON_CIRCLESTEP_2, LIGHT_LEDBUTTON_CIRCLESTEP_3, LIGHT_LEDBUTTON_CIRCLESTEP_4, LIGHT_LEDBUTTON_CIRCLESTEP_5, LIGHT_LEDBUTTON_CIRCLESTEP_6, LIGHT_LEDBUTTON_CIRCLESTEP_7, LIGHT_LEDBUTTON_CIRCLESTEP_8, LIGHT_LEDBUTTON_CIRCLESTEP_9, LIGHT_LEDBUTTON_CIRCLESTEP_10, LIGHT_LEDBUTTON_CIRCLESTEP_11, LIGHT_LEDBUTTON_CIRCLESTEP_12, LIGHT_CIRCLE_ROOT_KEY_POSITION_1_LIGHT, LIGHT_CIRCLE_ROOT_KEY_POSITION_2_LIGHT, LIGHT_CIRCLE_ROOT_KEY_POSITION_3_LIGHT, LIGHT_CIRCLE_ROOT_KEY_POSITION_4_LIGHT, LIGHT_CIRCLE_ROOT_KEY_POSITION_5_LIGHT, LIGHT_CIRCLE_ROOT_KEY_POSITION_6_LIGHT, LIGHT_CIRCLE_ROOT_KEY_POSITION_7_LIGHT, LIGHT_CIRCLE_ROOT_KEY_POSITION_8_LIGHT, LIGHT_CIRCLE_ROOT_KEY_POSITION_9_LIGHT, LIGHT_CIRCLE_ROOT_KEY_POSITION_10_LIGHT, LIGHT_CIRCLE_ROOT_KEY_POSITION_11_LIGHT, LIGHT_CIRCLE_ROOT_KEY_POSITION_12_LIGHT, LIGHT_LEDBUTTON_CIRCLESETSTEP_1, LIGHT_LEDBUTTON_CIRCLESETSTEP_2, LIGHT_LEDBUTTON_CIRCLESETSTEP_3, LIGHT_LEDBUTTON_CIRCLESETSTEP_4, LIGHT_LEDBUTTON_CIRCLESETSTEP_5, LIGHT_LEDBUTTON_CIRCLESETSTEP_6, LIGHT_LEDBUTTON_CIRCLESETSTEP_7, LIGHT_LEDBUTTON_CIRCLESETSTEP_8, LIGHT_LEDBUTTON_CIRCLESETSTEP_9, LIGHT_LEDBUTTON_CIRCLESETSTEP_10, LIGHT_LEDBUTTON_CIRCLESETSTEP_11, LIGHT_LEDBUTTON_CIRCLESETSTEP_12, LIGHT_LEDBUTTON_CIRCLESETSTEP_13, LIGHT_LEDBUTTON_CIRCLESETSTEP_14, LIGHT_LEDBUTTON_CIRCLESETSTEP_15, LIGHT_LEDBUTTON_CIRCLESETSTEP_16, LIGHT_CLOCK_IN_LIGHT, LIGHT_LEDBUTTON_MELODY_ENABLE_CHORDAL, LIGHT_LEDBUTTON_MELODY_ENABLE_SCALER, LIGHT_LEDBUTTON_ENABLE_HARMONY_ALL7THS_PARAM, LIGHT_LEDBUTTON_ENABLE_HARMONY_V7THS_PARAM, LIGHT_LEDBUTTON_BASS_SYNCOPATE_PARAM, LIGHT_LEDBUTTON_BASS_ACCENT_PARAM, LIGHT_LEDBUTTON_BASS_SHUFFLE_PARAM, LIGHT_LEDBUTTON_ENABLE_HARMONY_STACCATO_PARAM, LIGHT_LEDBUTTON_ENABLE_MELODY_STACCATO_PARAM, LIGHT_LEDBUTTON_ENABLE_BASS_STACCATO_PARAM, LIGHT_LEDBUTTON_BASS_OCTAVES_PARAM, LIGHT_LEDBUTTON_PROG_STEP_PARAM, NUM_LIGHTS }; // Clock code adapted from Strum and AS struct LFOGenerator { float phase = 0.0f; float pw = 0.5f; float freq = 1.0f; dsp::SchmittTrigger resetTrigger; void setFreq(float freq_to_set) { freq = freq_to_set; } void step(float dt) { float deltaPhase = fminf(freq * dt, 0.5f); phase += deltaPhase; if (phase >= 1.0f) phase -= 1.0f; } void setReset(float reset) { if (resetTrigger.process(reset)) { phase = 0.0f; } } float sqr() { float sqr = (phase < pw) ? 1.0f : -1.0f; return sqr; } }; // struct LFOGenerator void userPlaysCirclePositionHarmony(int circle_position, float octaveOffset) // C=0 play immediate { if (doDebug) DEBUG("userPlaysCirclePositionHarmony(%d)", circle_position); if (doDebug) DEBUG("circle_position=%d", circle_position); theMeanderState.last_harmony_chord_root_note=circle_of_fifths[circle_position]; if (octaveOffset>9) octaveOffset=9; for (int i=0; i<7; ++i) // melody and bass will use this to accompany { if (theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].CircleIndex==circle_position) { int theDegree=theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].Degree; for (int j=0;j<MAX_STEPS;++j) { if (theHarmonyTypes[harmony_type].harmony_steps[j]==theDegree) { theMeanderState.last_harmony_step=j; break; } } break; } } theMeanderState.theMelodyParms.last_step=theMeanderState.last_harmony_step; int note_index= (int)(theMeanderState.theMelodyParms.note_avg*num_step_chord_notes[theMeanderState.last_harmony_step]); // not sure this is necessary theMeanderState.theMelodyParms.last_chord_note_index= note_index; int current_chord_note=0; int root_key_note=circle_of_fifths[circle_position]; if (doDebug) DEBUG("root_key_note=%d %s", root_key_note, note_desig[root_key_note%12]); int circle_chord_type= theCircleOf5ths.Circle5ths[circle_position].chordType; theMeanderState.theHarmonyParms.last_chord_type=circle_chord_type; if (doDebug) DEBUG("circle_chord_type=%d", circle_chord_type); int num_chord_members=chord_type_num_notes[circle_chord_type]; if (doDebug) DEBUG("num_chord_members=%d", num_chord_members); if (((theMeanderState.theHarmonyParms.enable_all_7ths)||(theMeanderState.theHarmonyParms.enable_V_7ths)) && ((circle_chord_type==2) || (circle_chord_type==3) || (circle_chord_type==4) || (circle_chord_type==5))) outputs[OUT_HARMONY_CV_OUTPUT].setChannels(4); // set polyphony else outputs[OUT_HARMONY_CV_OUTPUT].setChannels(3); // set polyphony for (int j=0;j<num_chord_members;++j) { current_chord_note=(int)((int)root_key_note+(int)chord_type_intervals[circle_chord_type][j]); if (doDebug) DEBUG(" current_chord_note=%d %s", current_chord_note, note_desig[current_chord_note%12]); int note_to_play=current_chord_note+(octaveOffset*12); outputs[OUT_HARMONY_CV_OUTPUT].setVoltage((note_to_play/12.0)-4.0,j); // (note, channel) if (j<4) { theMeanderState.theHarmonyParms.last[j].note=note_to_play; theMeanderState.theHarmonyParms.last[j].noteType=NOTE_TYPE_CHORD; theMeanderState.theHarmonyParms.last[j].length=1; // whole note for now theMeanderState.theHarmonyParms.last[j].time32s=barts_count; theMeanderState.theHarmonyParms.last[j].countInBar=bar_note_count; if (bar_note_count<256) played_notes_circular_buffer[bar_note_count++]=theMeanderState.theHarmonyParms.last[j]; } } float durationFactor=1.0; if (theMeanderState.theHarmonyParms.enable_staccato) durationFactor=0.5; else durationFactor=1.0; float note_duration=durationFactor*time_sig_top/(frequency*theMeanderState.theHarmonyParms.note_length_divisor); harmonyGatePulse.reset(); // kill the pulse in case it is active harmonyGatePulse.trigger(note_duration); } void doHarmony(int barChordNumber=1, bool playFlag=false) { if (doDebug) DEBUG("doHarmony"); if (doDebug) DEBUG("doHarmony() theActiveHarmonyType.min_steps=%d, theActiveHarmonyType.max_steps=%d", theActiveHarmonyType.min_steps, theActiveHarmonyType.max_steps ); outputs[OUT_HARMONY_VOLUME_OUTPUT].setVoltage(theMeanderState.theHarmonyParms.volume); clock_t current_cpu_t= clock(); // cpu clock ticks since program began double current_cpu_time_double= (double)(current_cpu_t) / (double)CLOCKS_PER_SEC; if (doDebug) DEBUG("\nHarmony: barCount=%d Time=%.3lf", bar_count, (double)current_cpu_time_double); current_melody_note += 1.0/12.0; current_melody_note=fmod(current_melody_note, 1.0f); for (int i=0; i<MAX_CIRCLE_STATIONS; ++i) { CircleStepStates[i] = false; lights[LIGHT_LEDBUTTON_CIRCLESTEP_1+i].setBrightness(0.0f); } for (int i=0; i<16; ++i) { if (i<theActiveHarmonyType.num_harmony_steps) lights[LIGHT_LEDBUTTON_CIRCLESETSTEP_1+i].setBrightness(0.25f); else lights[LIGHT_LEDBUTTON_CIRCLESETSTEP_1+i].setBrightness(0.0f); } if (doDebug) DEBUG("theHarmonyTypes[%d].num_harmony_steps=%d", harmony_type, theActiveHarmonyType.num_harmony_steps); int step=(bar_count%theActiveHarmonyType.num_harmony_steps); // 0-(n-1) if ((harmony_type==22)&&(step==0)&&(barChordNumber==0)) // random coming home { float rnd = rack::random::uniform(); int temp_num_harmony_steps=1 + (int)((rnd*(theHarmonyTypes[22].num_harmony_steps-1))); bar_count += (theHarmonyTypes[22].num_harmony_steps-temp_num_harmony_steps); } if (randomize_harmony) // this could be used to randomize any progression { if (barChordNumber==0) { float rnd = rack::random::uniform(); step = (int)((rnd*theActiveHarmonyType.num_harmony_steps)); step=step%theActiveHarmonyType.num_harmony_steps; } else { step=theMeanderState.theHarmonyParms.last_circle_step; } } else if (harmony_type==22) // random coming home { if (barChordNumber!=0) { step=theMeanderState.theHarmonyParms.last_circle_step; } } else if (harmony_type==23) // random order { if (barChordNumber==0) { float rnd = rack::random::uniform(); step = (int)((rnd*theActiveHarmonyType.num_harmony_steps)); step=step%theActiveHarmonyType.num_harmony_steps; } else { step=theMeanderState.theHarmonyParms.last_circle_step; } } else if ((harmony_type==31)||(harmony_type==42)||(harmony_type==43)||(harmony_type==44)||(harmony_type==45)||(harmony_type==46)||(harmony_type==47)||(harmony_type==48)) // Markov chains { if (barChordNumber==0) { float rnd = rack::random::uniform(); if (doDebug) DEBUG("rnd=%.2f",rnd); if (theMeanderState.theHarmonyParms.last_circle_step==-1) { step=0; } else { float probabilityTargetBottom[8]={0}; // skip first array index since this is 1 based float probabilityTargetTop[8]={0}; // skip first array index since this is 1 based float bottom=0; step=1; for (int i=1; i<8; ++i) // skip first array index since this is 1 based { probabilityTargetBottom[i]=bottom; if (harmony_type==31) probabilityTargetTop[i]=bottom+MarkovProgressionTransitionMatrixBach1[theMeanderState.theHarmonyParms.last_circle_step+1][i]; else if (harmony_type==42) probabilityTargetTop[i]=bottom+MarkovProgressionTransitionMatrixBach2[theMeanderState.theHarmonyParms.last_circle_step+1][i]; else if (harmony_type==43) probabilityTargetTop[i]=bottom+MarkovProgressionTransitionMatrixMozart1[theMeanderState.theHarmonyParms.last_circle_step+1][i]; else if (harmony_type==44) probabilityTargetTop[i]=bottom+MarkovProgressionTransitionMatrixMozart2[theMeanderState.theHarmonyParms.last_circle_step+1][i]; else if (harmony_type==45) probabilityTargetTop[i]=bottom+MarkovProgressionTransitionMatrixPalestrina1[theMeanderState.theHarmonyParms.last_circle_step+1][i]; else if (harmony_type==46) probabilityTargetTop[i]=bottom+MarkovProgressionTransitionMatrixBeethoven1[theMeanderState.theHarmonyParms.last_circle_step+1][i]; else if (harmony_type==47) probabilityTargetTop[i]=bottom+MarkovProgressionTransitionMatrixTraditional1[theMeanderState.theHarmonyParms.last_circle_step+1][i]; else if (harmony_type==48) probabilityTargetTop[i]=bottom+MarkovProgressionTransitionMatrix_I_IV_V[theMeanderState.theHarmonyParms.last_circle_step+1][i]; bottom=probabilityTargetTop[i]; } if (doDebug) DEBUG("Markov Probabilities:"); for (int i=1; i<8; ++i) // skip first array index since this is 1 based { if (harmony_type==31) { if (doDebug) DEBUG("i=%d: p=%.2f b=%.2f t=%.2f", i, MarkovProgressionTransitionMatrixBach1[theMeanderState.theHarmonyParms.last_circle_step+1][i], probabilityTargetBottom[i], probabilityTargetTop[i]); } else if (harmony_type==42) { if (doDebug) DEBUG("i=%d: p=%.2f b=%.2f t=%.2f", i, MarkovProgressionTransitionMatrixBach2[theMeanderState.theHarmonyParms.last_circle_step+1][i], probabilityTargetBottom[i], probabilityTargetTop[i]); } else if (harmony_type==43) { if (doDebug) DEBUG("i=%d: p=%.2f b=%.2f t=%.2f", i, MarkovProgressionTransitionMatrixMozart1[theMeanderState.theHarmonyParms.last_circle_step+1][i], probabilityTargetBottom[i], probabilityTargetTop[i]); } else if (harmony_type==44) { if (doDebug) DEBUG("i=%d: p=%.2f b=%.2f t=%.2f", i, MarkovProgressionTransitionMatrixMozart2[theMeanderState.theHarmonyParms.last_circle_step+1][i], probabilityTargetBottom[i], probabilityTargetTop[i]); } else if (harmony_type==45) { if (doDebug) DEBUG("i=%d: p=%.2f b=%.2f t=%.2f", i, MarkovProgressionTransitionMatrixPalestrina1[theMeanderState.theHarmonyParms.last_circle_step+1][i], probabilityTargetBottom[i], probabilityTargetTop[i]); } else if (harmony_type==46) { if (doDebug) DEBUG("i=%d: p=%.2f b=%.2f t=%.2f", i, MarkovProgressionTransitionMatrixBeethoven1[theMeanderState.theHarmonyParms.last_circle_step+1][i], probabilityTargetBottom[i], probabilityTargetTop[i]); } else if (harmony_type==47) { if (doDebug) DEBUG("i=%d: p=%.2f b=%.2f t=%.2f", i, MarkovProgressionTransitionMatrixTraditional1[theMeanderState.theHarmonyParms.last_circle_step+1][i], probabilityTargetBottom[i], probabilityTargetTop[i]); } else if (harmony_type==48) { if (doDebug) DEBUG("i=%d: p=%.2f b=%.2f t=%.2f", i, MarkovProgressionTransitionMatrix_I_IV_V[theMeanderState.theHarmonyParms.last_circle_step+1][i], probabilityTargetBottom[i], probabilityTargetTop[i]); } if ((rnd>probabilityTargetBottom[i])&&(rnd<= probabilityTargetTop[i])) { step=i-1; if (doDebug) DEBUG("step=%d", step); } } } } else { step=theMeanderState.theHarmonyParms.last_circle_step; } } if (doDebug) DEBUG("step=%d", step); int degreeStep=(theActiveHarmonyType.harmony_steps[step])%8; if (doDebug) DEBUG("degreeStep=%d", degreeStep); theMeanderState.theHarmonyParms.last_circle_step=step; // used for Markov chain //find this in semicircle for (int i=0; i<7; ++i) { if (theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].Degree==degreeStep) { current_circle_position = theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].CircleIndex; break; } if (i==7) { if (doDebug) DEBUG(" warning circleposition could not be found 2"); } } lights[LIGHT_LEDBUTTON_CIRCLESETSTEP_1+step].setBrightness(1.0f); lights[LIGHT_LEDBUTTON_CIRCLESTEP_1+ (current_circle_position)%12].setBrightness(1.0f); if (doDebug) DEBUG("current_circle_position=%d root=%d %s", current_circle_position, circle_of_fifths[current_circle_position], note_desig[circle_of_fifths[current_circle_position]]); if (doDebug) DEBUG("theCircleOf5ths.Circle5ths[current_circle_position].chordType=%d", theCircleOf5ths.Circle5ths[current_circle_position].chordType); double period=1.0/theMeanderState.theHarmonyParms.period; // 1/seconds double fBmarg=theMeanderState.theHarmonyParms.seed + (double)(period*current_cpu_time_double); double fBmrand=(FastfBm1DNoise(fBmarg,theMeanderState.theHarmonyParms.noctaves) +1.)/2; theMeanderState.theHarmonyParms.note_avg = (1.0-theMeanderState.theHarmonyParms.alpha)*theMeanderState.theHarmonyParms.note_avg + theMeanderState.theHarmonyParms.alpha*(theMeanderState.theHarmonyParms.range_bottom + (fBmrand*theMeanderState.theHarmonyParms.r1)); if (theMeanderState.theHarmonyParms.note_avg>theMeanderState.theHarmonyParms.range_top) theMeanderState.theHarmonyParms.note_avg=theMeanderState.theHarmonyParms.range_top; if (theMeanderState.theHarmonyParms.note_avg<theMeanderState.theHarmonyParms.range_bottom) theMeanderState.theHarmonyParms.note_avg=theMeanderState.theHarmonyParms.range_bottom; int step_chord_type= theCircleOf5ths.Circle5ths[current_circle_position].chordType; if (((theMeanderState.theHarmonyParms.enable_all_7ths)||(theMeanderState.theHarmonyParms.enable_V_7ths)) && ((theCircleOf5ths.Circle5ths[current_circle_position].chordType==2) || (theCircleOf5ths.Circle5ths[current_circle_position].chordType==3) || (theCircleOf5ths.Circle5ths[current_circle_position].chordType==4) || (theCircleOf5ths.Circle5ths[current_circle_position].chordType==5))) outputs[OUT_HARMONY_CV_OUTPUT].setChannels(4); // set polyphony else outputs[OUT_HARMONY_CV_OUTPUT].setChannels(3); // set polyphony if (doDebug) DEBUG("step_chord_type=%d", step_chord_type); int num_chord_members=chord_type_num_notes[step_chord_type]; if (doDebug) DEBUG("num_chord_members=%d", num_chord_members); theMeanderState.theHarmonyParms.last_chord_type=step_chord_type; theMeanderState.last_harmony_chord_root_note=circle_of_fifths[current_circle_position]; theMeanderState.last_harmony_step=step; if (doDebug) DEBUG("theMeanderState.last_harmony_chord_root_note=%d %s", theMeanderState.last_harmony_chord_root_note, note_desig[theMeanderState.last_harmony_chord_root_note%MAX_NOTES]); if (doDebug) DEBUG("1st 3 step_chord_notes=%d %s, %d %s, %d %s", step_chord_notes[step][0], note_desig[step_chord_notes[step][0]%MAX_NOTES], step_chord_notes[step][1], note_desig[step_chord_notes[step][1]%MAX_NOTES], step_chord_notes[step][2], note_desig[step_chord_notes[step][2]%MAX_NOTES]); bool tonicFound=false; for (int j=0;j<num_chord_members;++j) { if (doDebug) DEBUG("num_step_chord_notes[%d]=%d", step, num_step_chord_notes[step]); current_chord_notes[j]= step_chord_notes[step][(int)(theMeanderState.theHarmonyParms.note_avg*num_step_chord_notes[step])+j]; // may create inversion if (doDebug) DEBUG("current_chord_notes[%d]=%d %s", j, current_chord_notes[j], note_desig[current_chord_notes[j]%MAX_NOTES]); int note_to_play=current_chord_notes[j]-12; // drop it an octave to get target octave right if (doDebug) DEBUG(" h_note_to_play=%d %s", note_to_play, note_desig[note_to_play%MAX_NOTES]); if (playFlag) { if (j<4) { theMeanderState.theHarmonyParms.last[j].note=note_to_play; theMeanderState.theHarmonyParms.last[j].noteType=NOTE_TYPE_CHORD; theMeanderState.theHarmonyParms.last[j].length=1; // need chords per measure theMeanderState.theHarmonyParms.last[j].time32s=barts_count; theMeanderState.theHarmonyParms.last[j].countInBar=bar_note_count; if (bar_note_count<256) played_notes_circular_buffer[bar_note_count++]=theMeanderState.theHarmonyParms.last[j]; } // get tonic in channel 0 if ( (note_to_play%MAX_NOTES)==(theMeanderState.last_harmony_chord_root_note%MAX_NOTES)) { outputs[OUT_HARMONY_CV_OUTPUT].setVoltage((note_to_play/12.0)-4.0,0); // (note, channel) tonicFound=true; } else { if (!tonicFound) outputs[OUT_HARMONY_CV_OUTPUT].setVoltage((note_to_play/12.0)-4.0,j+1); // (note, channel) else outputs[OUT_HARMONY_CV_OUTPUT].setVoltage((note_to_play/12.0)-4.0,j); // (note, channel) } } } if (playFlag) { outputs[OUT_HARMONY_VOLUME_OUTPUT].setVoltage(theMeanderState.theHarmonyParms.volume); // output some fBm noise outputs[OUT_FBM_HARMONY_OUTPUT].setChannels(1); // set polyphony float durationFactor=1.0; if (theMeanderState.theHarmonyParms.enable_staccato) durationFactor=0.5; else durationFactor=0.95; if (theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port==OUT_CLOCK_BAR_OUTPUT) durationFactor*=1.0; else if (theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port==OUT_CLOCK_BEAT_OUTPUT) durationFactor*=.25; else if (theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port==OUT_CLOCK_BEATX2_OUTPUT) durationFactor*=.125; else if (theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port==OUT_CLOCK_BEATX4_OUTPUT) durationFactor*=.0625; else if (theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port==OUT_CLOCK_BEATX8_OUTPUT) durationFactor*=.03125; else if ( inputs[IN_PROG_STEP_EXT_CV].isConnected()) // something is connected to the circle STEP input but we do not know what. Assume it is an 16X BPM frequency durationFactor *= .01562; float note_duration=durationFactor*4/(frequency*theMeanderState.theHarmonyParms.note_length_divisor); harmonyGatePulse.reset(); // kill the pulse in case it is active harmonyGatePulse.trigger(note_duration); } outputs[OUT_FBM_HARMONY_OUTPUT].setVoltage((float)clamp((10.f*fBmrand), 0.f, 10.f) ,0); // rescale fBm output to 0-10V so it can be used better for CV. Output even if harmony disabled ++circle_step_index; if (circle_step_index>=theActiveHarmonyType.num_harmony_steps) circle_step_index=0; if ((harmony_type==22)&&(step==0)&&(barChordNumber==0)) // random coming home { float rnd = rack::random::uniform(); int temp_num_harmony_steps=1 + (int)((rnd*(theHarmonyTypes[22].num_harmony_steps-1))); bar_count += (theHarmonyTypes[22].num_harmony_steps-temp_num_harmony_steps); } } void userPlaysScaleDegreeMelody(int degree, float octaveOffset) // C=0 play immediate { if (degree<1) degree=1; if (degree>7) degree=7; int note_to_play=root_key_notes[root_key][degree-1]+(octaveOffset*12); outputs[OUT_MELODY_CV_OUTPUT].setVoltage((note_to_play/12.0)-4.0,0); // (note, channel) shift down 1 ocatve/v theMeanderState.theMelodyParms.last[0].note=note_to_play; theMeanderState.theMelodyParms.last[0].noteType=NOTE_TYPE_MELODY; theMeanderState.theMelodyParms.last[0].length=1; // whole note for now theMeanderState.theMelodyParms.last[0].time32s=barts_count; theMeanderState.theMelodyParms.last[0].countInBar=bar_note_count; if (bar_note_count<256) played_notes_circular_buffer[bar_note_count++]=theMeanderState.theMelodyParms.last[0]; float durationFactor=1.0; if (theMeanderState.theMelodyParms.enable_staccato) durationFactor=0.5; else durationFactor=1.0; float note_duration=durationFactor*time_sig_top/(frequency*theMeanderState.theMelodyParms.note_length_divisor); melodyGatePulse.reset(); // kill the pulse in case it is active melodyGatePulse.trigger(note_duration); } void doMelody() { if (doDebug) DEBUG("doMelody()"); outputs[OUT_MELODY_VOLUME_OUTPUT].setVoltage(theMeanderState.theMelodyParms.volume); clock_t current_cpu_t= clock(); // cpu clock ticks since program began double current_cpu_time_double= (double)(current_cpu_t) / (double)CLOCKS_PER_SEC; if (doDebug) DEBUG("Melody: Time=%.3lf", (double)current_cpu_time_double); ++theMeanderState.theMelodyParms.bar_melody_counted_note; theMeanderState.theArpParms.note_count=0; // where does this really go, at the begining of a melody note double period=1.0/theMeanderState.theMelodyParms.period; // 1/seconds double fBmarg=theMeanderState.theMelodyParms.seed + (double)(period*current_cpu_time_double); double fBmrand=(FastfBm1DNoise(fBmarg,theMeanderState.theMelodyParms.noctaves) +1.)/2; theMeanderState.theMelodyParms.note_avg = (1.0-theMeanderState.theMelodyParms.alpha)*theMeanderState.theMelodyParms.note_avg + theMeanderState.theMelodyParms.alpha*(theMeanderState.theMelodyParms.range_bottom + (fBmrand*theMeanderState.theMelodyParms.r1)); if (theMeanderState.theMelodyParms.note_avg>theMeanderState.theMelodyParms.range_top) theMeanderState.theMelodyParms.note_avg=theMeanderState.theMelodyParms.range_top; if (theMeanderState.theMelodyParms.note_avg<theMeanderState.theMelodyParms.range_bottom) theMeanderState.theMelodyParms.note_avg=theMeanderState.theMelodyParms.range_bottom; int step=theMeanderState.last_harmony_step; theMeanderState.theMelodyParms.last_step= step; int note_index= (int)(theMeanderState.theMelodyParms.note_avg*num_step_chord_notes[step]); theMeanderState.theMelodyParms.last_chord_note_index= note_index; int note_to_play=step_chord_notes[step][note_index]; if (theMeanderState.theMelodyParms.chordal) { note_index= (int)(theMeanderState.theMelodyParms.note_avg*num_step_chord_notes[step]); note_to_play=step_chord_notes[step][note_index]; } else if (theMeanderState.theMelodyParms.scaler) { note_index= (int)(theMeanderState.theMelodyParms.note_avg*num_root_key_notes[root_key]); note_to_play=root_key_notes[root_key][note_index]; } if (false) // accidentals are probably not notated correctly Flat accidentals may sound better than sharp { if ((theMeanderState.theMelodyParms.bar_melody_counted_note!=1)&&(theMeanderState.theMelodyParms.bar_melody_counted_note==(theMeanderState.theMelodyParms.note_length_divisor-1))) // allow accidentals, but not on first or last melody note in bar { float rnd = rack::random::uniform(); if (rnd<.05) note_to_play += 1; else if (rnd>.90) note_to_play -= 1; } } if (doDebug) DEBUG(" melody note_to_play=%d %s", note_to_play, note_desig[note_to_play%MAX_NOTES]); if (true) // do it even if melody notes will not be played, so arp will have roots { if ((theMeanderState.theMelodyParms.destutter) && (note_to_play==theMeanderState.theMelodyParms.last[0].note) && (theMeanderState.theMelodyParms.last_stutter_step==step)) // seems like gate always fires { theMeanderState.theMelodyParms.stutter_detected=true; theMeanderState.theMelodyParms.last_stutter_step=step; } else { theMeanderState.theMelodyParms.last_stutter_step=step; theMeanderState.theMelodyParms.stutter_detected=false; theMeanderState.theMelodyParms.last[0].note=note_to_play; theMeanderState.theMelodyParms.last[0].noteType=NOTE_TYPE_MELODY; theMeanderState.theMelodyParms.last[0].length=theMeanderState.theMelodyParms.note_length_divisor; theMeanderState.theMelodyParms.last[0].time32s=barts_count; theMeanderState.theMelodyParms.last[0].countInBar=bar_note_count; if ((theMeanderState.theMelodyParms.enabled)&&(bar_note_count<256)) played_notes_circular_buffer[bar_note_count++]=theMeanderState.theMelodyParms.last[0]; if (theMeanderState.theMelodyParms.enabled) { outputs[OUT_MELODY_CV_OUTPUT].setChannels(1); // set polyphony may need to deal with unset channel voltages outputs[OUT_MELODY_CV_OUTPUT].setVoltage(((note_to_play/12.0) -4.0) ,0); // (note, channel) -4 since midC=c4=0voutputs[OUT_MELODY_CV_OUTPUT].setVoltage((note_to_play -4 + theMeanderState.theMelodyParms.target_octave,0); // (note, channel) -4 since midC=c4=0v } // output some fBm noise outputs[OUT_FBM_MELODY_OUTPUT].setChannels(1); // set polyphony outputs[OUT_FBM_MELODY_OUTPUT].setVoltage((float)clamp((10.f*fBmrand), 0.f, 10.f) ,0); // rescale fBm output to 0-10V so it can be used better for CV float durationFactor=1.0; if (theMeanderState.theMelodyParms.enable_staccato) durationFactor=0.5; else durationFactor=0.95; float note_duration=durationFactor*4/(frequency*theMeanderState.theMelodyParms.note_length_divisor); // adjust melody note duration if arp enabled if (theMeanderState.theArpParms.enabled) note_duration=durationFactor*4/(frequency*theMeanderState.theArpParms.note_length_divisor); if (theMeanderState.theMelodyParms.enabled) melodyGatePulse.trigger(note_duration); // Test 1s duration need to use .process to detect this and then send it to output } } } void doArp() { if (doDebug) DEBUG("doArp()"); if (theMeanderState.theArpParms.note_count>=theMeanderState.theArpParms.count) return; int arp_note=0; if ((theMeanderState.theArpParms.pattern>=-1)&&(theMeanderState.theArpParms.pattern<=1)) arp_note=theMeanderState.theArpParms.note_count*theMeanderState.theArpParms.pattern; else if (theMeanderState.theArpParms.pattern==2) { if (theMeanderState.theArpParms.note_count<=((theMeanderState.theArpParms.count)/2)) arp_note=theMeanderState.theArpParms.note_count; else arp_note=theMeanderState.theArpParms.count-theMeanderState.theArpParms.note_count-1; } else if (theMeanderState.theArpParms.pattern==-2) { if (theMeanderState.theArpParms.note_count<=((theMeanderState.theArpParms.count)/2)) arp_note-=theMeanderState.theArpParms.note_count; else arp_note=-theMeanderState.theArpParms.count+theMeanderState.theArpParms.note_count-1; } else arp_note=theMeanderState.theArpParms.note_count*theMeanderState.theArpParms.pattern; if (theMeanderState.theArpParms.pattern!=0) ++arp_note; // above the melody note ++theMeanderState.theArpParms.note_count; float volume=theMeanderState.theMelodyParms.volume; float volume_factor=pow((1.0-theMeanderState.theArpParms.decay), theMeanderState.theArpParms.note_count); volume *= volume_factor; if (doDebug) DEBUG("theMeanderState.theMelodyParms.last_chord_note_index=%d", theMeanderState.theMelodyParms.last_chord_note_index); if (doDebug) DEBUG("num_step_chord_notes[%d]=%d", theMeanderState.theMelodyParms.last_step, num_step_chord_notes[theMeanderState.theMelodyParms.last_step]); int note_to_play=100; // bogus if (theMeanderState.theArpParms.chordal) // use step_chord_notes { note_to_play=step_chord_notes[theMeanderState.theMelodyParms.last_step][(theMeanderState.theMelodyParms.last_chord_note_index + arp_note)% num_step_chord_notes[theMeanderState.theMelodyParms.last_step]]; } else if (theMeanderState.theArpParms.scaler) // use root_key_notes rather than step_chord_notes. This is slower since scale note index has to be looked up { if (false) // old brute force search from beginning { for (int x=0; x<num_root_key_notes[root_key]; ++x) { if (root_key_notes[root_key][x]==theMeanderState.theMelodyParms.last[0].note) { note_to_play=root_key_notes[root_key][x+arp_note]; if (doDebug) DEBUG("note fount at index=%d root_key_notes[root_key][x]=%d", x, root_key_notes[root_key][x]); break; } } } if (true) // new // BSP search . { int note_to_search_for=theMeanderState.theMelodyParms.last[0].note; if (doDebug) DEBUG("BSP note_to_search_for=%d", note_to_search_for); int num_to_search=num_root_key_notes[root_key]; if (doDebug) DEBUG("BSP num_to_search=%d", num_to_search); int start_search_index=0; int end_search_index=num_root_key_notes[root_key]-1; int pass=0; int partition_index=0; while (pass<8) { if (doDebug) DEBUG("start_search_index=%d end_search_index=%d", start_search_index, end_search_index); partition_index=(end_search_index+start_search_index)/2; if (doDebug) DEBUG("BSP start_search_index=%d end_search_index=%d partition_index=%d", start_search_index, end_search_index, partition_index); if ( note_to_search_for>root_key_notes[root_key][partition_index]) { start_search_index=partition_index; if (doDebug) DEBUG(">BSP root_key_notes[root_key][partition_index]=%d", root_key_notes[root_key][partition_index]); } else if ( note_to_search_for<root_key_notes[root_key][partition_index]) { end_search_index=partition_index; if (doDebug) DEBUG("<BSP root_key_notes[root_key][partition_index]=%d", root_key_notes[root_key][partition_index]); } else { /* we found it */ if (doDebug) DEBUG("value %d found at index %d", root_key_notes[root_key][partition_index], partition_index); pass=8; break; } ++pass; } if ((partition_index>=0) && (partition_index<num_to_search)) note_to_play=root_key_notes[root_key][partition_index+arp_note]; } } if (((theMeanderState.theMelodyParms.enabled)||(theMeanderState.theArpParms.enabled))&&theMeanderState.theArpParms.note_count<32) { theMeanderState.theArpParms.last[theMeanderState.theArpParms.note_count].note=note_to_play; theMeanderState.theArpParms.last[theMeanderState.theArpParms.note_count].noteType=NOTE_TYPE_ARP; theMeanderState.theArpParms.last[theMeanderState.theArpParms.note_count].length=theMeanderState.theArpParms.note_length_divisor; theMeanderState.theArpParms.last[theMeanderState.theArpParms.note_count].time32s=barts_count; theMeanderState.theArpParms.last[theMeanderState.theArpParms.note_count].countInBar=bar_note_count; if (bar_note_count<256) played_notes_circular_buffer[bar_note_count++]=theMeanderState.theArpParms.last[theMeanderState.theArpParms.note_count]; } outputs[OUT_MELODY_CV_OUTPUT].setChannels(1); // set polyphony may need to deal with unset channel voltages outputs[OUT_MELODY_CV_OUTPUT].setVoltage(((note_to_play/12.0) -4.0) ,0); // (note, channel) -4 since midC=c4=0voutputs[OUT_MELODY_CV_OUTPUT].setVoltage((note_to_play -4 + theMeanderState.theMelodyParms.target_octave,0); // (note, channel) -4 since midC=c4=0v outputs[OUT_MELODY_VOLUME_OUTPUT].setVoltage(volume); // this is strictly for arp decay melodyGatePulse.reset(); // kill the pulse in case it is active float durationFactor=1.0; if (theMeanderState.theMelodyParms.enable_staccato) durationFactor=0.5; else durationFactor=0.95; float note_duration=durationFactor*4/(frequency*theMeanderState.theArpParms.note_length_divisor); melodyGatePulse.trigger(note_duration); } void doBass() { if (doDebug) DEBUG("doBass()"); outputs[OUT_BASS_VOLUME_OUTPUT].setVoltage(theMeanderState.theBassParms.volume); if (theMeanderState.theBassParms.enabled) { ++theMeanderState.theBassParms.bar_bass_counted_note; if ((theMeanderState.theBassParms.syncopate)&&(theMeanderState.theBassParms.bar_bass_counted_note==2)) // experimenting with bass patterns return; if ((theMeanderState.theBassParms.shuffle)&&((theMeanderState.theBassParms.bar_bass_counted_note%3)==2)) // experimenting with bass patterns return; if (theMeanderState.theBassParms.octave_enabled) outputs[OUT_BASS_CV_OUTPUT].setChannels(2); // set polyphony may need to deal with unset channel voltages else outputs[OUT_BASS_CV_OUTPUT].setChannels(1); // set polyphony may need to deal with unset channel voltages if (doDebug) DEBUG(" bass note to play=%d %s", theMeanderState.last_harmony_chord_root_note, note_desig[theMeanderState.last_harmony_chord_root_note%MAX_NOTES]); theMeanderState.theBassParms.last[0].note=theMeanderState.last_harmony_chord_root_note+ (theMeanderState.theBassParms.target_octave*12); theMeanderState.theBassParms.last[0].noteType=NOTE_TYPE_BASS; theMeanderState.theBassParms.last[0].length=1; // need bass notes per measure theMeanderState.theBassParms.last[0].time32s=barts_count; theMeanderState.theBassParms.last[0].countInBar=bar_note_count; if (bar_note_count<256) played_notes_circular_buffer[bar_note_count++]=theMeanderState.theBassParms.last[0]; outputs[OUT_BASS_CV_OUTPUT].setVoltage((theMeanderState.last_harmony_chord_root_note/12.0)-4.0 +theMeanderState.theBassParms.target_octave ,0); //(note, channel) if (theMeanderState.theBassParms.octave_enabled) { theMeanderState.theBassParms.last[1].note=theMeanderState.theBassParms.last[0].note+12; theMeanderState.theBassParms.last[1].noteType=NOTE_TYPE_BASS; theMeanderState.theBassParms.last[1].length=1; // need bass notes per measure theMeanderState.theBassParms.last[1].time32s=barts_count; theMeanderState.theBassParms.last[1].countInBar=bar_note_count; if (bar_note_count<256) played_notes_circular_buffer[bar_note_count++]=theMeanderState.theBassParms.last[1]; outputs[OUT_BASS_CV_OUTPUT].setVoltage((theMeanderState.last_harmony_chord_root_note/12.0)-3.0 +theMeanderState.theBassParms.target_octave ,1); } if (!theMeanderState.theBassParms.accent) // need to redo with new gate procedure { theMeanderState.theBassParms.note_accented=false; } else { if (theMeanderState.theBassParms.bar_bass_counted_note==1) // experimenting with bass patterns theMeanderState.theBassParms.note_accented=true; else theMeanderState.theBassParms.note_accented=false; } float durationFactor=1.0; if (theMeanderState.theBassParms.enable_staccato) durationFactor=0.5; else durationFactor=0.95; if (theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port==OUT_CLOCK_BAR_OUTPUT) durationFactor*=1.0; else if (theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port==OUT_CLOCK_BEAT_OUTPUT) durationFactor*=.25; else if (theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port==OUT_CLOCK_BEATX2_OUTPUT) durationFactor*=.125; else if (theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port==OUT_CLOCK_BEATX4_OUTPUT) durationFactor*=.0625; else if (theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port==OUT_CLOCK_BEATX8_OUTPUT) durationFactor*=.03125; else if ( inputs[IN_PROG_STEP_EXT_CV].isConnected()) // something is connected to the circle STEP input but we do not know what. Assume it is an 16X BPM frequency durationFactor *= .01562; float note_duration=durationFactor*time_sig_top/(frequency*theMeanderState.theBassParms.note_length_divisor); bassGatePulse.trigger(note_duration); } } LFOGenerator LFOclock; dsp::SchmittTrigger ST_32ts_trig; // 32nd note timer tick dsp::SchmittTrigger run_button_trig; dsp::SchmittTrigger ext_run_trig; dsp::SchmittTrigger reset_btn_trig; dsp::SchmittTrigger reset_ext_trig; dsp::SchmittTrigger bpm_mode_trig; dsp::SchmittTrigger step_button_trig; dsp::PulseGenerator resetPulse; bool reset_pulse = false; dsp::PulseGenerator runPulse; bool run_pulse = false; dsp::PulseGenerator stepPulse; bool step_pulse = false; // PULSES FOR TRIGGER OUTPUTS INSTEAD OF GATES dsp::PulseGenerator clockPulse32ts; bool pulse32ts = false; dsp::PulseGenerator clockPulse16ts; bool pulse16ts = false; dsp::PulseGenerator clockPulse8ts; bool pulse8ts = false; dsp::PulseGenerator clockPulse4ts; bool pulse4ts = false; dsp::PulseGenerator clockPulse2ts; bool pulse2ts = false; dsp::PulseGenerator clockPulse1ts; bool pulse1ts = false; float trigger_length = 0.0001f; const float lightLambda = 0.075f; float resetLight = 0.0f; float stepLight = 0.0f; bool running = true; int bar_count = 0; // number of bars running count int i16ts_count = 0; // counted 32s notes per sixteenth note int i8ts_count = 0; // counted 32s notes per eighth note int i4ts_count = 0; // counted 32s notes per quarter note int i2ts_count = 0; // counted 32s notes per half note int barts_count = 0; // counted 32s notes per bar float tempo =120.0f; float frequency = 2.0f; int i16ts_count_limit = 2;// 32s notes per sixteenth note int i8ts_count_limit = 4; // 32s notes per eighth note int i4ts_count_limit = 8; // 32s notes per quarter note int i2ts_count_limit =16; // 32s notes per half note int barts_count_limit = 32; // 32s notes per bar float min_bpm = 10.0f; float max_bpm = 300.0f; float extHarmonyIn=-99; // end of clock ************************** dsp::ClockDivider lowFreqClock; dsp::ClockDivider sec1Clock; dsp::ClockDivider lightDivider; float phase = 0.f; float last_melody_note=0; float current_melody_note=0; int circle_step_index=0; dsp::SchmittTrigger HarmonyEnableToggle; dsp::SchmittTrigger MelodyEnableToggle; dsp::SchmittTrigger BassEnableToggle; dsp::SchmittTrigger ArpEnableToggle; dsp::SchmittTrigger ArpEnableChordalToggle; dsp::SchmittTrigger ArpEnableScalerToggle; dsp::SchmittTrigger HarmonyEnableAll7thsToggle; dsp::SchmittTrigger HarmonyEnableV7thsToggle; dsp::SchmittTrigger HarmonyEnableStaccatoToggle; dsp::SchmittTrigger MelodyDestutterToggle; dsp::SchmittTrigger MelodyEnableChordalToggle; dsp::SchmittTrigger MelodyEnableScalerToggle; dsp::SchmittTrigger MelodyEnableStaccatoToggle; dsp::SchmittTrigger BassSyncopateToggle; dsp::SchmittTrigger BassAccentToggle; dsp::SchmittTrigger BassShuffleToggle; dsp::SchmittTrigger BassOctavesToggle; dsp::SchmittTrigger BassEnableStaccatoToggle; dsp::SchmittTrigger RunToggle; dsp::SchmittTrigger CircleStepToggles[MAX_STEPS]; dsp::SchmittTrigger CircleStepSetToggles[MAX_STEPS]; bool CircleStepStates[MAX_STEPS]={}; bool CircleStepSetStates[MAX_STEPS]={}; rack::dsp::PulseGenerator barTriggerPulse; rack::dsp::PulseGenerator harmonyGatePulse; rack::dsp::PulseGenerator melodyGatePulse; rack::dsp::PulseGenerator bassGatePulse; rack::dsp::PulseGenerator barGaterPulse; bool time_sig_changed=false; int override_step=1; // save button states json_t *dataToJson() override { json_t *rootJ = json_object(); // running // running json_object_set_new(rootJ, "running", json_boolean(running)); json_object_set_new(rootJ, "theHarmonyParmsenabled", json_boolean(theMeanderState.theHarmonyParms.enabled)); json_object_set_new(rootJ, "harmony_staccato_enable", json_boolean(theMeanderState.theHarmonyParms.enable_staccato)); json_object_set_new(rootJ, "theHarmonyParmsenable_all_7ths", json_boolean(theMeanderState.theHarmonyParms.enable_all_7ths)); json_object_set_new(rootJ, "theHarmonyParmsenable_V_7ths", json_boolean(theMeanderState.theHarmonyParms.enable_V_7ths)); json_object_set_new(rootJ, "theMelodyParmsenabled", json_boolean(theMeanderState.theMelodyParms.enabled)); json_object_set_new(rootJ, "theMelodyParmsdestutter", json_boolean(theMeanderState.theMelodyParms.destutter)); json_object_set_new(rootJ, "theMelodyParmsenable_staccato", json_boolean(theMeanderState.theMelodyParms.enable_staccato)); json_object_set_new(rootJ, "theMelodyParmschordal", json_boolean(theMeanderState.theMelodyParms.chordal)); json_object_set_new(rootJ, "theMelodyParmsscaler", json_boolean(theMeanderState.theMelodyParms.scaler)); json_object_set_new(rootJ, "theArpParmsenabled", json_boolean(theMeanderState.theArpParms.enabled)); json_object_set_new(rootJ, "theArpParmschordal", json_boolean(theMeanderState.theArpParms.chordal)); json_object_set_new(rootJ, "theArpParmsscaler", json_boolean(theMeanderState.theArpParms.scaler)); json_object_set_new(rootJ, "theBassParmsenabled", json_boolean(theMeanderState.theBassParms.enabled)); json_object_set_new(rootJ, "theBassParmsenable_staccato", json_boolean(theMeanderState.theBassParms.enable_staccato)); json_object_set_new(rootJ, "theBassParmssyncopate", json_boolean(theMeanderState.theBassParms.syncopate)); json_object_set_new(rootJ, "theBassParmsaccent", json_boolean(theMeanderState.theBassParms.accent)); json_object_set_new(rootJ, "theBassParmsshuffle", json_boolean(theMeanderState.theBassParms.shuffle)); json_object_set_new(rootJ, "theBassParmsoctave_enabled", json_boolean(theMeanderState.theBassParms.octave_enabled)); return rootJ; } void dataFromJson(json_t *rootJ) override { // running json_t *runningJ = json_object_get(rootJ, "running"); if (runningJ) running = json_is_true(runningJ); json_t *HarmonyParmsenabledJ = json_object_get(rootJ, "theHarmonyParmsenabled"); if (HarmonyParmsenabledJ) theMeanderState.theHarmonyParms.enabled = json_is_true(HarmonyParmsenabledJ); json_t *HarmonyParmsstaccato_enableJ = json_object_get(rootJ, "harmony_staccato_enable"); if (HarmonyParmsstaccato_enableJ) theMeanderState.theHarmonyParms.enable_staccato = json_is_true(HarmonyParmsstaccato_enableJ); json_t *HarmonyParmsenable_all_7thsJ = json_object_get(rootJ, "theHarmonyParmsenable_all_7ths"); if (HarmonyParmsenable_all_7thsJ) theMeanderState.theHarmonyParms.enable_all_7ths = json_is_true(HarmonyParmsenable_all_7thsJ); json_t *HarmonyParmsenable_V_7thsJ = json_object_get(rootJ, "theHarmonyParmsenable_V_7ths"); if (HarmonyParmsenable_V_7thsJ) theMeanderState.theHarmonyParms.enable_V_7ths = json_is_true(HarmonyParmsenable_V_7thsJ); json_t *MelodyParmsenabledJ = json_object_get(rootJ, "theMelodyParmsenabled"); if (MelodyParmsenabledJ) theMeanderState.theMelodyParms.enabled = json_is_true(MelodyParmsenabledJ); json_t *MelodyParmsdestutterJ = json_object_get(rootJ, "theMelodyParmsdestutter"); if (MelodyParmsdestutterJ) theMeanderState.theMelodyParms.destutter = json_is_true(MelodyParmsdestutterJ); json_t *MelodyParmsenable_staccatoJ = json_object_get(rootJ, "theMelodyParmsenable_staccato"); if (MelodyParmsenable_staccatoJ) theMeanderState.theMelodyParms.enable_staccato = json_is_true(MelodyParmsenable_staccatoJ); json_t *MelodyParmschordalJ = json_object_get(rootJ, "theMelodyParmschordal"); if (MelodyParmschordalJ) theMeanderState.theMelodyParms.chordal = json_is_true(MelodyParmschordalJ); json_t *MelodyParmsscalerJ = json_object_get(rootJ, "theMelodyParmsscaler"); if (MelodyParmsscalerJ) theMeanderState.theMelodyParms.scaler = json_is_true(MelodyParmsscalerJ); json_t *ArpParmsenabledJ = json_object_get(rootJ, "theArpParmsenabled"); if (ArpParmsenabledJ) theMeanderState.theArpParms.enabled = json_is_true(ArpParmsenabledJ); json_t *ArpParmschordalJ = json_object_get(rootJ, "theArpParmschordal"); if (ArpParmschordalJ) theMeanderState.theArpParms.chordal = json_is_true(ArpParmschordalJ); json_t *ArpParmsscalerJ = json_object_get(rootJ, "theArpParmsscaler"); if (ArpParmsscalerJ) theMeanderState.theArpParms.scaler = json_is_true(ArpParmsscalerJ); json_t *BassParmsenabledJ = json_object_get(rootJ, "theBassParmsenabled"); if (BassParmsenabledJ) theMeanderState.theBassParms.enabled = json_is_true(BassParmsenabledJ); json_t *BassParmsenable_staccatoJ = json_object_get(rootJ, "theBassParmsenable_staccato"); if (BassParmsenable_staccatoJ) theMeanderState.theBassParms.enable_staccato = json_is_true(BassParmsenable_staccatoJ); json_t *BassParmssyncopateJ = json_object_get(rootJ, "theBassParmssyncopate"); if (BassParmssyncopateJ) theMeanderState.theBassParms.syncopate = json_is_true(BassParmssyncopateJ); json_t *BassParmsaccentJ = json_object_get(rootJ, "theBassParmsaccent"); if (BassParmsaccentJ) theMeanderState.theBassParms.accent = json_is_true(BassParmsaccentJ); json_t *BassParmsshuffleJ = json_object_get(rootJ, "theBassParmsshuffle"); if (BassParmsshuffleJ) theMeanderState.theBassParms.shuffle = json_is_true(BassParmsshuffleJ); json_t *BassParmsoctave_enabledJ = json_object_get(rootJ, "theBassParmsoctave_enabled"); if (BassParmsoctave_enabledJ) theMeanderState.theBassParms.octave_enabled = json_is_true(BassParmsoctave_enabledJ); } void process(const ProcessArgs &args) override { if (!instanceRunning) return; if (!globalsInitialized) return; //Run if (RunToggle.process(params[BUTTON_RUN_PARAM].getValue() || inputs[IN_RUN_EXT_CV].getVoltage())) { running=!running; if(!running) { i16ts_count = 0; i8ts_count = 0; i4ts_count = 0; i2ts_count = 0; barts_count = 0; theMeanderState.theMelodyParms.bar_melody_counted_note=0; theMeanderState.theArpParms.note_count=0; theMeanderState.theBassParms.bar_bass_counted_note=0; outputs[OUT_CLOCK_BAR_OUTPUT].setVoltage(0.0f); // bars outputs[OUT_CLOCK_BEAT_OUTPUT].setVoltage(0.0f); // 4ts outputs[OUT_CLOCK_BEATX2_OUTPUT].setVoltage(0.0f); // 8ts outputs[OUT_CLOCK_BEATX4_OUTPUT].setVoltage(0.0f); // 16ts outputs[OUT_CLOCK_BEATX8_OUTPUT].setVoltage(0.0f); // 32ts } else { LFOclock.setFreq(frequency*(32/time_sig_bottom)); // for 32ts barts_count_limit = (32*time_sig_top/time_sig_bottom); } theMeanderState.theHarmonyParms.pending_step_edit=0; runPulse.trigger(0.01f); // delay 10ms } lights[LIGHT_LEDBUTTON_RUN].setBrightness(running ? 1.0f : 0.0f); run_pulse = runPulse.process(1.0 / args.sampleRate); outputs[OUT_RUN_OUT].setVoltage((run_pulse ? 10.0f : 0.0f)); if (inputs[IN_TEMPO_EXT_CV].isConnected()) { float fvalue=inputs[IN_TEMPO_EXT_CV].getVoltage(); tempo=std::round(std::pow(2.0, fvalue)*120); if (tempo<10) tempo=10; if (tempo>300) tempo=300; if (true) // adjust the tempo knob and param { params[CONTROL_TEMPOBPM_PARAM].setValue(tempo); } } else { float fvalue = std::round(params[CONTROL_TEMPOBPM_PARAM].getValue()); if (fvalue!=tempo) tempo=fvalue; } frequency = tempo/60.0f; // drives 1 tick per 32nd note // Reset if (reset_btn_trig.process(params[BUTTON_RESET_PARAM].getValue() || inputs[IN_RESET_EXT_CV].getVoltage() || time_sig_changed)) { // setup_harmony(); time_sig_changed=false; LFOclock.setReset(1.0f); bar_count = 0; bar_note_count=0; i16ts_count = 0; i8ts_count = 0; i4ts_count = 0; i2ts_count = 0; barts_count = 0; theMeanderState.theMelodyParms.bar_melody_counted_note=0; theMeanderState.theArpParms.note_count=0; theMeanderState.theBassParms.bar_bass_counted_note=0; theMeanderState.theHarmonyParms.last_circle_step=-1; // for Markov chain resetLight = 1.0; resetPulse.trigger(0.01f); // necessary to pass on reset below vis resetPuls.process() if (!running) { harmonyGatePulse.reset(); // kill the pulse in case it is active melodyGatePulse.reset(); // kill the pulse in case it is active bassGatePulse.reset(); // kill the pulse in case it is active outputs[OUT_HARMONY_GATE_OUTPUT].setVoltage(0); outputs[OUT_MELODY_GATE_OUTPUT].setVoltage(0); outputs[OUT_BASS_GATE_OUTPUT].setVoltage(0); outputs[OUT_HARMONY_VOLUME_OUTPUT].setVoltage(0); outputs[OUT_MELODY_VOLUME_OUTPUT].setVoltage(0); outputs[OUT_BASS_VOLUME_OUTPUT].setVoltage(0); } } resetLight -= resetLight / lightLambda / args.sampleRate; lights[LIGHT_LEDBUTTON_RESET].setBrightness(resetLight); reset_pulse = resetPulse.process(1.0 / args.sampleRate); outputs[OUT_RESET_OUT].setVoltage((reset_pulse ? 10.0f : 0.0f)); if ((step_button_trig.process(params[BUTTON_PROG_STEP_PARAM].getValue() || ( inputs[IN_PROG_STEP_EXT_CV].isConnected() && (inputs[IN_PROG_STEP_EXT_CV].getVoltage() > 0.))))) { ++bar_count; if (theMeanderState.theHarmonyParms.enabled) { theMeanderState.theHarmonyParms.enabled = false; override_step=0; } else { ++override_step; if (override_step>=theActiveHarmonyType.num_harmony_steps) override_step=0; } theMeanderState.userControllingHarmonyFromCircle=true; theMeanderState.last_harmony_step=override_step; int current_circle_position=0; int degreeStep=(theActiveHarmonyType.harmony_steps[override_step])%8; //find this in semicircle for (int j=0; j<7; ++j) { if (theCircleOf5ths.theDegreeSemiCircle.degreeElements[j].Degree==degreeStep) { current_circle_position = theCircleOf5ths.theDegreeSemiCircle.degreeElements[j].CircleIndex; if (doDebug) DEBUG("harmony step edit-pt2 current_circle_position=%d", current_circle_position); break; } } stepLight = 1.0; stepPulse.trigger(0.01f); // necessary to pass on reset below vis resetPuls.process() if (running) { doHarmony(0, true); if (theMeanderState.theBassParms.enabled) doBass(); } } stepLight -= stepLight / lightLambda / args.sampleRate; lights[LIGHT_LEDBUTTON_PROG_STEP_PARAM].setBrightness(stepLight); step_pulse = stepPulse.process(1.0 / args.sampleRate); if(running) { // these should be done in initialization rather than every process() call LFOclock.setFreq(frequency*(32/time_sig_bottom)); // for 32ts should not hurt top call this each sample barts_count_limit = (32*time_sig_top/time_sig_bottom); //************************************************************************ LFOclock.step(1.0 / args.sampleRate); bool clockTick=false; if ( inputs[IN_CLOCK_EXT_CV].isConnected()) // external clock connected to Clock input { if (!inportStates[IN_CLOCK_EXT_CV].inTransition) { if (ST_32ts_trig.process(inputs[IN_CLOCK_EXT_CV].getVoltage())) // triggers from each external clock tick ONLY once when input reaches 1.0V { clockTick=true; outputs[OUT_CLOCK_OUT].setChannels(1); // set polyphony outputs[OUT_CLOCK_OUT].setVoltage(10.0f); inportStates[IN_CLOCK_EXT_CV].inTransition=true; } } if (inportStates[IN_CLOCK_EXT_CV].inTransition) { if (ST_32ts_trig.process(math::rescale(inputs[IN_CLOCK_EXT_CV].getVoltage(),10.f,0.f,0.f,10.f))) // triggers from each external clock tick ONLY once when inverted input reaches 0.0V { outputs[OUT_CLOCK_OUT].setChannels(1); // set polyphony outputs[OUT_CLOCK_OUT].setVoltage(0.0f); inportStates[IN_CLOCK_EXT_CV].inTransition=false; } } } else // no external clock connected to Clock input, use internal clock { float IntClockLevel=5.0f*(LFOclock.sqr()+1.0f); if (ST_32ts_trig.process(LFOclock.sqr())) // triggers from each external clock tick ONLY once when .sqr() reaches 1.0V { clockTick=true; } outputs[OUT_CLOCK_OUT].setChannels(1); // set polyphony outputs[OUT_CLOCK_OUT].setVoltage(IntClockLevel); } if (clockTick) { bool melodyPlayed=false; // set to prevent arp note being played on the melody beat int barChordNumber=(int)((int)(barts_count*theMeanderState.theHarmonyParms.note_length_divisor)/(int)32); // bar if (barts_count == 0) { theMeanderState.theMelodyParms.bar_melody_counted_note=0; theMeanderState.theBassParms.bar_bass_counted_note=0; bar_note_count=0; if ((theMeanderState.theHarmonyParms.note_length_divisor==1)&&(!theMeanderState.userControllingHarmonyFromCircle)) doHarmony(barChordNumber, theMeanderState.theHarmonyParms.enabled); if ((theMeanderState.theBassParms.note_length_divisor==1)&&(!theMeanderState.userControllingHarmonyFromCircle)) doBass(); if ((theMeanderState.theMelodyParms.note_length_divisor==1)&&(!theMeanderState.userControllingMelody)) { doMelody(); melodyPlayed=true; } clockPulse1ts.trigger(trigger_length); // Pulse the output gate barTriggerPulse.trigger(1e-3f); // 1ms duration need to use .process to detect this and then send it to output } // i2ts if (i2ts_count == 0) { if ((theMeanderState.theHarmonyParms.note_length_divisor==2)&&(!theMeanderState.userControllingHarmonyFromCircle)) doHarmony(barChordNumber, theMeanderState.theHarmonyParms.enabled); if ((theMeanderState.theBassParms.note_length_divisor==2)&&(!theMeanderState.userControllingHarmonyFromCircle)) doBass(); if ((theMeanderState.theMelodyParms.note_length_divisor==2)&&(!theMeanderState.userControllingMelody)) { doMelody(); melodyPlayed=true; } i2ts_count++; if (!theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port) clockPulse2ts.trigger(trigger_length); } else if (i2ts_count == (i2ts_count_limit-1)) { i2ts_count = 0; if (theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port) clockPulse2ts.trigger(trigger_length); } else { i2ts_count++; } // i4ts if (i4ts_count == 0) { if ((theMeanderState.theHarmonyParms.note_length_divisor==4)&&(!theMeanderState.userControllingHarmonyFromCircle)) doHarmony(barChordNumber, theMeanderState.theHarmonyParms.enabled); if ((theMeanderState.theBassParms.note_length_divisor==4)&&(!theMeanderState.userControllingHarmonyFromCircle)) doBass(); if ((theMeanderState.theMelodyParms.note_length_divisor==4)&&(!theMeanderState.userControllingMelody)) { doMelody(); melodyPlayed=true; } if ((theMeanderState.theArpParms.enabled)&&(theMeanderState.theArpParms.note_length_divisor==4)&&(!melodyPlayed)) doArp(); i4ts_count++; if (!theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port) clockPulse4ts.trigger(trigger_length); } else if (i4ts_count == (i4ts_count_limit-1)) { i4ts_count = 0; if (theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port) clockPulse4ts.trigger(trigger_length); } else { i4ts_count++; } // i8ts if (i8ts_count == 0) { if ((theMeanderState.theHarmonyParms.note_length_divisor==8)&&(!theMeanderState.userControllingHarmonyFromCircle)) doHarmony(barChordNumber, theMeanderState.theHarmonyParms.enabled); if ((theMeanderState.theBassParms.note_length_divisor==8)&&(!theMeanderState.userControllingHarmonyFromCircle)) doBass(); if ((theMeanderState.theMelodyParms.note_length_divisor==8)&&(!theMeanderState.userControllingMelody)) { doMelody(); melodyPlayed=true; } if ((theMeanderState.theArpParms.enabled)&&(theMeanderState.theArpParms.note_length_divisor==8)&&(!melodyPlayed)) doArp(); i8ts_count++; if (!theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port) clockPulse8ts.trigger(trigger_length); } else if (i8ts_count == (i8ts_count_limit-1)) { i8ts_count = 0; if (theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port) clockPulse8ts.trigger(trigger_length); } else { i8ts_count++; } // i16ts if (i16ts_count == 0) { if ((theMeanderState.theMelodyParms.note_length_divisor==16)&&(!theMeanderState.userControllingMelody)) { doMelody(); melodyPlayed=true; } if ((theMeanderState.theArpParms.enabled)&&(theMeanderState.theArpParms.note_length_divisor==16)&&(!melodyPlayed)) doArp(); i16ts_count++; if (!theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port) clockPulse16ts.trigger(trigger_length); } else if (i16ts_count == (i16ts_count_limit-1)) { i16ts_count = 0; if (theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port) clockPulse16ts.trigger(trigger_length); } else { i16ts_count++; } //32nds *********************************** clock_t current_cpu_t= clock(); // cpu clock ticks since program began double current_cpu_time_double= (double)(current_cpu_t) / (double)CLOCKS_PER_SEC; // do on each 1/32nd clock tick if ((theMeanderState.theMelodyParms.note_length_divisor==32)&&(!theMeanderState.userControllingMelody)) { doMelody(); melodyPlayed=true; } if ((theMeanderState.theArpParms.enabled)&&(theMeanderState.theArpParms.note_length_divisor==32)&&(!melodyPlayed)) doArp(); // output some fBm noise double period=1.0/theMeanderState.theArpParms.period; // 1/seconds double fBmarg=theMeanderState.theArpParms.seed + (double)(period*current_cpu_time_double); double fBmrand=(FastfBm1DNoise(fBmarg,theMeanderState.theArpParms.noctaves) +1.)/2; outputs[OUT_FBM_ARP_OUTPUT].setChannels(1); // set polyphony outputs[OUT_FBM_ARP_OUTPUT].setVoltage((float)clamp((10.f*fBmrand), 0.f, 10.f) ,0); // rescale fBm output to 0-10V so it can be used better for CV if (barts_count == (barts_count_limit-1)) // do this after all processing so bar_count does not get incremented too early { barts_count = 0; theMeanderState.theMelodyParms.bar_melody_counted_note=0; theMeanderState.theBassParms.bar_bass_counted_note=0; bar_note_count=0; if (!theMeanderState.userControllingHarmonyFromCircle) // don't mess up bar count ++bar_count; } else { barts_count++; } clockPulse32ts.trigger(trigger_length); // retrigger the pulse after all done in this loop // outputs[OUT_CLOCK_OUT].setChannels(1); // set polyphony // outputs[OUT_CLOCK_OUT].setVoltage(10.0f); } else // !clockTick { // outputs[OUT_CLOCK_OUT].setChannels(1); // set polyphony // outputs[OUT_CLOCK_OUT].setVoltage(0.0f); } } pulse1ts = clockPulse1ts.process(1.0 / args.sampleRate); pulse2ts = clockPulse2ts.process(1.0 / args.sampleRate); pulse4ts = clockPulse4ts.process(1.0 / args.sampleRate); pulse8ts = clockPulse8ts.process(1.0 / args.sampleRate); pulse16ts = clockPulse16ts.process(1.0 / args.sampleRate); pulse32ts = clockPulse32ts.process(1.0 / args.sampleRate); // end the gate if pulse timer has expired if (false) // standard gate voltages { outputs[OUT_HARMONY_GATE_OUTPUT].setVoltage( harmonyGatePulse.process( 1.0 / APP->engine->getSampleRate() ) ? CV_MAX10 : 0.0 ); outputs[OUT_MELODY_GATE_OUTPUT].setVoltage( melodyGatePulse.process( 1.0 / APP->engine->getSampleRate() ) ? CV_MAX10 : 0.0 ); outputs[OUT_BASS_GATE_OUTPUT].setVoltage( bassGatePulse.process( 1.0 / APP->engine->getSampleRate() ) ? CV_MAX10 : 0.0 ); float bassVolumeLevel=theMeanderState.theBassParms.volume; if (theMeanderState.theBassParms.accent) { if (theMeanderState.theBassParms.note_accented) bassVolumeLevel=theMeanderState.theBassParms.volume; else bassVolumeLevel=0.5*theMeanderState.theBassParms.volume; bassVolumeLevel=clamp(bassVolumeLevel, 0.0f, 10.f); } outputs[OUT_BASS_VOLUME_OUTPUT].setVoltage(bassVolumeLevel); } else // non-standard volume over gate voltages { float harmonyGateLevel=theMeanderState.theHarmonyParms.volume; harmonyGateLevel=clamp(harmonyGateLevel, 2.1f, 10.f); // don't let gate on level drop below 2.0v so it will trigger ADSR etc. outputs[OUT_HARMONY_GATE_OUTPUT].setVoltage( harmonyGatePulse.process( 1.0 / APP->engine->getSampleRate() ) ? harmonyGateLevel : 0.0 ); float melodyGateLevel=theMeanderState.theMelodyParms.volume; melodyGateLevel=clamp(melodyGateLevel, 2.1f, 10.f); // don't let gate on level drop below 2.0v so it will trigger ADSR etc. outputs[OUT_MELODY_GATE_OUTPUT].setVoltage( melodyGatePulse.process( 1.0 / APP->engine->getSampleRate() ) ? melodyGateLevel : 0.0 ); float bassGateLevel=theMeanderState.theBassParms.volume; if (theMeanderState.theBassParms.accent) { if (!theMeanderState.theBassParms.note_accented) bassGateLevel*=.8; } bassGateLevel=clamp(bassGateLevel, 2.1f, 10.f); // don't let gate on level drop below 2.0v so it will trigger ADSR etc. outputs[OUT_BASS_GATE_OUTPUT].setVoltage( bassGatePulse.process( 1.0 / APP->engine->getSampleRate() ) ?bassGateLevel : 0.0 ); } outputs[OUT_CLOCK_BAR_OUTPUT].setVoltage((pulse1ts ? 10.0f : 0.0f)); // barts outputs[OUT_CLOCK_BEAT_OUTPUT].setVoltage((pulse4ts ? 10.0f : 0.0f)); // 4ts outputs[OUT_CLOCK_BEATX2_OUTPUT].setVoltage((pulse8ts ? 10.0f : 0.0f)); // 8ts outputs[OUT_CLOCK_BEATX4_OUTPUT].setVoltage((pulse16ts ? 10.0f : 0.0f)); // 16ts outputs[OUT_CLOCK_BEATX8_OUTPUT].setVoltage((pulse32ts ? 10.0f : 0.0f)); // 32ts if (HarmonyEnableToggle.process(params[BUTTON_ENABLE_HARMONY_PARAM].getValue())) { theMeanderState.theHarmonyParms.enabled = !theMeanderState.theHarmonyParms.enabled; theMeanderState.userControllingHarmonyFromCircle=false; } lights[LIGHT_LEDBUTTON_HARMONY_ENABLE].setBrightness(theMeanderState.theHarmonyParms.enabled ? 1.0f : 0.0f); if (HarmonyEnableAll7thsToggle.process(params[BUTTON_ENABLE_HARMONY_ALL7THS_PARAM].getValue())) { theMeanderState.theHarmonyParms.enable_all_7ths = !theMeanderState.theHarmonyParms.enable_all_7ths; if (theMeanderState.theHarmonyParms.enable_all_7ths) theMeanderState.theHarmonyParms.enable_V_7ths=false; setup_harmony(); // calculate harmony notes circleChanged=true; } lights[LIGHT_LEDBUTTON_ENABLE_HARMONY_ALL7THS_PARAM].setBrightness(theMeanderState.theHarmonyParms.enable_all_7ths ? 1.0f : 0.0f); if (HarmonyEnableV7thsToggle.process(params[BUTTON_ENABLE_HARMONY_V7THS_PARAM].getValue())) { theMeanderState.theHarmonyParms.enable_V_7ths = !theMeanderState.theHarmonyParms.enable_V_7ths; if (theMeanderState.theHarmonyParms.enable_V_7ths) theMeanderState.theHarmonyParms.enable_all_7ths=false; setup_harmony(); circleChanged=true; } lights[LIGHT_LEDBUTTON_ENABLE_HARMONY_V7THS_PARAM].setBrightness(theMeanderState.theHarmonyParms.enable_V_7ths ? 1.0f : 0.0f); // if (HarmonyEnableStaccatoToggle.process(params[BUTTON_ENABLE_HARMONY_STACCATO_PARAM].getValue())) { theMeanderState.theHarmonyParms.enable_staccato = !theMeanderState.theHarmonyParms.enable_staccato; } lights[LIGHT_LEDBUTTON_ENABLE_HARMONY_STACCATO_PARAM].setBrightness(theMeanderState.theHarmonyParms.enable_staccato); if (MelodyEnableStaccatoToggle.process(params[BUTTON_ENABLE_MELODY_STACCATO_PARAM].getValue())) { theMeanderState.theMelodyParms.enable_staccato = !theMeanderState.theMelodyParms.enable_staccato; } lights[LIGHT_LEDBUTTON_ENABLE_MELODY_STACCATO_PARAM].setBrightness(theMeanderState.theMelodyParms.enable_staccato ? 1.0f : 0.0f); if (BassEnableStaccatoToggle.process(params[BUTTON_ENABLE_BASS_STACCATO_PARAM].getValue())) { theMeanderState.theBassParms.enable_staccato = !theMeanderState.theBassParms.enable_staccato; } lights[LIGHT_LEDBUTTON_ENABLE_BASS_STACCATO_PARAM].setBrightness(theMeanderState.theBassParms.enable_staccato ? 1.0f : 0.0f); // if (BassEnableToggle.process(params[BUTTON_ENABLE_BASS_PARAM].getValue())) { theMeanderState.theBassParms.enabled = !theMeanderState.theBassParms.enabled; } lights[LIGHT_LEDBUTTON_BASS_ENABLE].setBrightness(theMeanderState.theBassParms.enabled ? 1.0f : 0.0f); if (MelodyEnableToggle.process(params[BUTTON_ENABLE_MELODY_PARAM].getValue())) { theMeanderState.theMelodyParms.enabled = !theMeanderState.theMelodyParms.enabled; if (theMeanderState.theMelodyParms.enabled) theMeanderState.userControllingMelody=false; } lights[LIGHT_LEDBUTTON_MELODY_ENABLE].setBrightness(theMeanderState.theMelodyParms.enabled ? 1.0f : 0.0f); if (MelodyDestutterToggle.process(params[BUTTON_MELODY_DESTUTTER_PARAM].getValue())) { theMeanderState.theMelodyParms.destutter = !theMeanderState.theMelodyParms.destutter; } lights[LIGHT_LEDBUTTON_MELODY_DESTUTTER].setBrightness(theMeanderState.theMelodyParms.destutter ? 1.0f : 0.0f); if (MelodyEnableChordalToggle.process(params[BUTTON_ENABLE_MELODY_CHORDAL_PARAM].getValue())) { theMeanderState.theMelodyParms.chordal = !theMeanderState.theMelodyParms.chordal; theMeanderState.theMelodyParms.scaler = !theMeanderState.theMelodyParms.scaler; } lights[LIGHT_LEDBUTTON_MELODY_ENABLE_CHORDAL].setBrightness(theMeanderState.theMelodyParms.chordal ? 1.0f : 0.0f); if (MelodyEnableScalerToggle.process(params[BUTTON_ENABLE_MELODY_SCALER_PARAM].getValue())) { theMeanderState.theMelodyParms.scaler = !theMeanderState.theMelodyParms.scaler; theMeanderState.theMelodyParms.chordal = !theMeanderState.theMelodyParms.chordal; } lights[LIGHT_LEDBUTTON_MELODY_ENABLE_SCALER].setBrightness(theMeanderState.theMelodyParms.scaler ? 1.0f : 0.0f); if (ArpEnableToggle.process(params[BUTTON_ENABLE_ARP_PARAM].getValue())) { theMeanderState.theArpParms.enabled = !theMeanderState.theArpParms.enabled; } lights[LIGHT_LEDBUTTON_ARP_ENABLE].setBrightness(theMeanderState.theArpParms.enabled ? 1.0f : 0.0f); if (ArpEnableChordalToggle.process(params[BUTTON_ENABLE_ARP_CHORDAL_PARAM].getValue())) { theMeanderState.theArpParms.chordal = !theMeanderState.theArpParms.chordal; theMeanderState.theArpParms.scaler = !theMeanderState.theArpParms.scaler; } lights[LIGHT_LEDBUTTON_ARP_ENABLE_CHORDAL].setBrightness(theMeanderState.theArpParms.chordal ? 1.0f : 0.0f); if (ArpEnableScalerToggle.process(params[BUTTON_ENABLE_ARP_SCALER_PARAM].getValue())) { theMeanderState.theArpParms.scaler = !theMeanderState.theArpParms.scaler; theMeanderState.theArpParms.chordal = !theMeanderState.theArpParms.chordal; } lights[LIGHT_LEDBUTTON_ARP_ENABLE_SCALER].setBrightness(theMeanderState.theArpParms.scaler ? 1.0f : 0.0f); //****Bass if (BassSyncopateToggle.process(params[BUTTON_BASS_SYNCOPATE_PARAM].getValue())) { theMeanderState.theBassParms.syncopate = !theMeanderState.theBassParms.syncopate; } lights[LIGHT_LEDBUTTON_BASS_SYNCOPATE_PARAM].setBrightness(theMeanderState.theBassParms.syncopate ? 1.0f : 0.0f); if (BassAccentToggle.process(params[BUTTON_BASS_ACCENT_PARAM].getValue())) { theMeanderState.theBassParms.accent = !theMeanderState.theBassParms.accent; } lights[LIGHT_LEDBUTTON_BASS_ACCENT_PARAM].setBrightness(theMeanderState.theBassParms.accent ? 1.0f : 0.0f); if (BassShuffleToggle.process(params[BUTTON_BASS_SHUFFLE_PARAM].getValue())) { theMeanderState.theBassParms.shuffle = !theMeanderState.theBassParms.shuffle; } lights[LIGHT_LEDBUTTON_BASS_SHUFFLE_PARAM].setBrightness(theMeanderState.theBassParms.shuffle ? 1.0f : 0.0f); if (BassOctavesToggle.process(params[BUTTON_BASS_OCTAVES_PARAM].getValue())) { theMeanderState.theBassParms.octave_enabled = !theMeanderState.theBassParms.octave_enabled; } lights[LIGHT_LEDBUTTON_BASS_OCTAVES_PARAM].setBrightness(theMeanderState.theBassParms.octave_enabled ? 1.0f : 0.0f); //*************** for (int i=0; i<12; ++i) { if (CircleStepToggles[i].process(params[BUTTON_CIRCLESTEP_C_PARAM+i].getValue())) // circle button clicked { int current_circle_position=i; if (doDebug) DEBUG("harmony step edit-pt3 current_circle_position=%d", current_circle_position); for (int j=0; j<12; ++j) { if (j!=current_circle_position) { CircleStepStates[j] = false; lights[LIGHT_LEDBUTTON_CIRCLESTEP_1+j].setBrightness(CircleStepStates[j] ? 1.0f : 0.0f); } } CircleStepStates[current_circle_position] = !CircleStepStates[current_circle_position]; lights[LIGHT_LEDBUTTON_CIRCLESTEP_1+current_circle_position].setBrightness(CircleStepStates[current_circle_position] ? 1.0f : 0.0f); userPlaysCirclePositionHarmony(current_circle_position, theMeanderState.theHarmonyParms.target_octave); theMeanderState.userControllingHarmonyFromCircle=true; theMeanderState.theHarmonyParms.enabled=false; lights[LIGHT_LEDBUTTON_HARMONY_ENABLE].setBrightness(theMeanderState.theHarmonyParms.enabled ? 1.0f : 0.0f); //find this in circle for (int j=0; j<7; ++j) { if (theCircleOf5ths.theDegreeSemiCircle.degreeElements[j].CircleIndex==current_circle_position) { int theDegree=theCircleOf5ths.theDegreeSemiCircle.degreeElements[j].Degree; if (doDebug) DEBUG("harmony step edit-pt4 theDegree=%d", theDegree); if ((theDegree>=1)&&(theDegree<=7)) { if (theMeanderState.theHarmonyParms.pending_step_edit) { if (doDebug) DEBUG("harmony step edit-pt5 theMeanderState.theHarmonyParms.pending_step_edit=%d", theMeanderState.theHarmonyParms.pending_step_edit); if (doDebug) DEBUG("harmony step edit-pt6 theDegree=%d found", theDegree); theHarmonyTypes[harmony_type].harmony_steps[theMeanderState.theHarmonyParms.pending_step_edit-BUTTON_HARMONY_SETSTEP_1_PARAM]=theDegree; // strcpy(theHarmonyTypes[harmony_type].harmony_degrees_desc,""); for (int k=0;k<theHarmonyTypes[harmony_type].num_harmony_steps;++k) { strcat(theHarmonyTypes[harmony_type].harmony_degrees_desc,circle_of_fifths_arabic_degrees[theHarmonyTypes[harmony_type].harmony_steps[k]]); strcat(theHarmonyTypes[harmony_type].harmony_degrees_desc," "); } // copyHarmonyTypeToActiveHarmonyType(harmony_type); setup_harmony(); } } break; } } } } if (!running) { for (int i=0; i<theActiveHarmonyType.num_harmony_steps; ++i) { if (CircleStepSetToggles[i].process(params[BUTTON_HARMONY_SETSTEP_1_PARAM+i].getValue())) { if (doDebug) DEBUG("harmony step edit-pt1 step=%d clicked", i); int selectedStep=i; theMeanderState.theHarmonyParms.pending_step_edit=BUTTON_HARMONY_SETSTEP_1_PARAM+selectedStep; int current_circle_position=0; if (true) { int degreeStep=(theActiveHarmonyType.harmony_steps[selectedStep])%8; //find this in semicircle for (int j=0; j<7; ++j) { if (theCircleOf5ths.theDegreeSemiCircle.degreeElements[j].Degree==degreeStep) { current_circle_position = theCircleOf5ths.theDegreeSemiCircle.degreeElements[j].CircleIndex; if (doDebug) DEBUG("harmony step edit-pt2 current_circle_position=%d", current_circle_position); break; } } } for (int i=0; i<12; ++i) { lights[LIGHT_LEDBUTTON_CIRCLESTEP_1+i].setBrightness(0.0f); } lights[LIGHT_LEDBUTTON_CIRCLESTEP_1+current_circle_position].setBrightness(1.0f); userPlaysCirclePositionHarmony(current_circle_position, theMeanderState.theHarmonyParms.target_octave); CircleStepSetStates[i] = !CircleStepSetStates[i]; lights[LIGHT_LEDBUTTON_CIRCLESETSTEP_1+i].setBrightness(CircleStepSetStates[i] ? 1.0f : 0.25f); for (int j=0; j<theActiveHarmonyType.num_harmony_steps; ++j) { if (j!=i) { CircleStepSetStates[j] = false; lights[LIGHT_LEDBUTTON_CIRCLESETSTEP_1+j].setBrightness(0.25f); } } } } } float fvalue=0; float circleDegree=0; // for harmony float scaleDegree=0; // for melody float gateValue=0; if ( (inputs[IN_HARMONY_CIRCLE_DEGREE_GATE_EXT_CV].isConnected()) && (inputs[IN_HARMONY_CIRCLE_DEGREE_EXT_CV].isConnected()) ) { circleDegree=inputs[IN_HARMONY_CIRCLE_DEGREE_EXT_CV].getVoltage(); gateValue=inputs[IN_HARMONY_CIRCLE_DEGREE_GATE_EXT_CV].getVoltage(); theMeanderState.theHarmonyParms.lastCircleDegreeIn=circleDegree; extHarmonyIn=circleDegree; float octave=(float)((int)(circleDegree)); // from the keyboard if (octave>3) octave=3; if (octave<-3) octave=-3; bool degreeChanged=false; // assume false unless determined true below bool skipStep=false; if ((gateValue==circleDegree)&&(circleDegree>=1)&&(circleDegree<=7.7)) // MarkovSeq or other 1-7V degree degree.octave 0.0-7.7V { if (inportStates[IN_HARMONY_CIRCLE_DEGREE_EXT_CV].inTransition) { if (circleDegree==inportStates[IN_HARMONY_CIRCLE_DEGREE_EXT_CV].lastValue) { // was in transition but now is not inportStates[IN_HARMONY_CIRCLE_DEGREE_EXT_CV].inTransition=false; inportStates[IN_HARMONY_CIRCLE_DEGREE_EXT_CV].lastValue=circleDegree; octave = (int)(10.0*std::fmod(circleDegree, 1.0f)); if (octave>7) octave=7; circleDegree=(float)((int)circleDegree); theMeanderState.circleDegree=(int)circleDegree; degreeChanged=true; } else if (circleDegree!=inportStates[IN_HARMONY_CIRCLE_DEGREE_EXT_CV].lastValue) { inportStates[IN_HARMONY_CIRCLE_DEGREE_EXT_CV].lastValue=circleDegree; } } else { if (circleDegree!=inportStates[IN_HARMONY_CIRCLE_DEGREE_EXT_CV].lastValue) { inportStates[IN_HARMONY_CIRCLE_DEGREE_EXT_CV].inTransition=true; inportStates[IN_HARMONY_CIRCLE_DEGREE_EXT_CV].lastValue=circleDegree; } } if (circleDegree==0) { degreeChanged=false; } } else if ((gateValue==circleDegree)&&((circleDegree<1.0)||(circleDegree>=8.0))) // MarkovSeq or other 1-7V degree degree.octave 1.0-7.7V <1 or >=8V means skip step { inportStates[IN_HARMONY_CIRCLE_DEGREE_EXT_CV].lastValue=fvalue; degreeChanged=true; skipStep=true; } else // keyboard C-B { float fgvalue=inputs[IN_HARMONY_CIRCLE_DEGREE_GATE_EXT_CV].getVoltage(); if (inportStates[IN_HARMONY_CIRCLE_DEGREE_GATE_EXT_CV].inTransition) { if (fgvalue==inportStates[IN_HARMONY_CIRCLE_DEGREE_GATE_EXT_CV].lastValue) { // was in transition but now is not inportStates[IN_HARMONY_CIRCLE_DEGREE_GATE_EXT_CV].inTransition=false; inportStates[IN_HARMONY_CIRCLE_DEGREE_GATE_EXT_CV].lastValue=fgvalue; if (fgvalue) // gate has gone high { if ( circleDegree==inportStates[IN_HARMONY_CIRCLE_DEGREE_EXT_CV].lastValue) // the gate has changed but the degree has not degreeChanged=true; // not really, but play like it has so it will be replayed below } } else if (fgvalue!=inportStates[IN_HARMONY_CIRCLE_DEGREE_GATE_EXT_CV].lastValue) { inportStates[IN_HARMONY_CIRCLE_DEGREE_GATE_EXT_CV].lastValue=fgvalue; } } else { if (fgvalue!=inportStates[IN_HARMONY_CIRCLE_DEGREE_GATE_EXT_CV].lastValue) { inportStates[IN_HARMONY_CIRCLE_DEGREE_GATE_EXT_CV].inTransition=true; inportStates[IN_HARMONY_CIRCLE_DEGREE_GATE_EXT_CV].lastValue=fgvalue; } } if ( (degreeChanged) || (circleDegree!=inportStates[IN_HARMONY_CIRCLE_DEGREE_EXT_CV].lastValue)) { inportStates[IN_HARMONY_CIRCLE_DEGREE_EXT_CV].lastValue=circleDegree; if (circleDegree>=0) circleDegree=(float)std::fmod(std::fabs(circleDegree), 1.0f); else circleDegree=-(float)std::fmod(std::fabs(circleDegree), 1.0f); degreeChanged=true; if (doDebug) DEBUG("IN_HARMONY_CIRCLE_DEGREE_EXT_CV circleDegree=%f", circleDegree); if (circleDegree>=0) { if ((std::abs(circleDegree)<.005f)) theMeanderState.circleDegree=1; else if ((std::abs(circleDegree-.167f)<.005f)) theMeanderState.circleDegree=2; else if ((std::abs(circleDegree-.333f)<.005f)) theMeanderState.circleDegree=3; else if ((std::abs(circleDegree-.417f)<.005f)) theMeanderState.circleDegree=4; else if ((std::abs(circleDegree-.583f)<.005f)) theMeanderState.circleDegree=5; else if ((std::abs(circleDegree-.750f)<.005f)) theMeanderState.circleDegree=6; else if ((std::abs(circleDegree-.917f)<.005f)) theMeanderState.circleDegree=7; else degreeChanged=false; } else { octave-=1; if ((std::abs(circleDegree)<.005f)) theMeanderState.circleDegree=1; else if (std::abs(std::abs(circleDegree)-.083)<.005f) theMeanderState.circleDegree=7; else if (std::abs(std::abs(circleDegree)-.250)<.005f) theMeanderState.circleDegree=6; else if (std::abs(std::abs(circleDegree)-.417)<.005f) theMeanderState.circleDegree=5; else if (std::abs(std::abs(circleDegree)-.583)<.005f) theMeanderState.circleDegree=4; else if (std::abs(std::abs(circleDegree)-.667)<.005f) theMeanderState.circleDegree=3; else if (std::abs(std::abs(circleDegree)-.833)<.005f) theMeanderState.circleDegree=2; else degreeChanged=false; } } } if ((degreeChanged)&&(!skipStep)) { if (theMeanderState.circleDegree<1) theMeanderState.circleDegree=1; if (theMeanderState.circleDegree>7) theMeanderState.circleDegree=7; if (doDebug) DEBUG("IN_HARMONY_CIRCLE_DEGREE_EXT_CV=%d", (int)theMeanderState.circleDegree); // DEBUG("IN_HARMONY_CIRCLE_DEGREE_EXT_CV=%d", (int)theMeanderState.circleDegree); int step=1; // default if not found below for (int i=0; i<MAX_STEPS; ++i) { if (theActiveHarmonyType.harmony_steps[i]==theMeanderState.circleDegree) { step=i; break; } } theMeanderState.last_harmony_step=step; int theCirclePosition=0; for (int i=0; i<7; ++i) { if (theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].Degree==theMeanderState.circleDegree) { theCirclePosition=theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].CircleIndex; break; } } last_circle_position=theCirclePosition; userPlaysCirclePositionHarmony(theCirclePosition, octave+theMeanderState.theHarmonyParms.target_octave); // play immediate if (doDebug) DEBUG("userPlaysCirclePositionHarmony()"); if (theMeanderState.theBassParms.enabled) doBass(); if (running) { theMeanderState.userControllingHarmonyFromCircle=true; theMeanderState.theHarmonyParms.enabled=false; } for (int i=0; i<12; ++i) { CircleStepStates[i] = false; lights[LIGHT_LEDBUTTON_CIRCLESTEP_1+i].setBrightness(CircleStepStates[i] ? 1.0f : 0.0f); } lights[LIGHT_LEDBUTTON_CIRCLESTEP_1+theCirclePosition].setBrightness(1.0f); } } //************************** if (lightDivider.process()) { } if (lowFreqClock.process()) { if (!instanceRunning) return; // check controls for changes if ((fvalue=std::round(params[CONTROL_TEMPOBPM_PARAM].getValue()))!=tempo) { tempo = fvalue; if (doDebug) DEBUG("tempo changed to %d", (int)tempo); } int ivalue=std::round(params[CONTROL_TIMESIGNATURETOP_PARAM].getValue()); if (ivalue!=time_sig_top) { time_sig_top = ivalue; time_sig_changed=true; } ivalue=std::round(params[CONTROL_TIMESIGNATUREBOTTOM_PARAM].getValue()); if (std::pow(2,ivalue+1)!=time_sig_bottom) { time_sig_bottom = std::pow(2,ivalue+1); int melody_note_length_divisor=0; if (time_sig_bottom==2) melody_note_length_divisor=1; else if (time_sig_bottom==4) melody_note_length_divisor=2; else if (time_sig_bottom==8) melody_note_length_divisor=3; else if (time_sig_bottom==16) melody_note_length_divisor=4; theMeanderState.theMelodyParms.note_length_divisor=(int)std::pow(2,melody_note_length_divisor); params[CONTROL_MELODY_NOTE_LENGTH_DIVISOR_PARAM].setValue(melody_note_length_divisor); theMeanderState.theArpParms.note_length_divisor=(int)std::pow(2,melody_note_length_divisor+1); params[CONTROL_ARP_INCREMENT_PARAM].setValue(melody_note_length_divisor+1); time_sig_changed=true; } frequency = tempo/60.0f; // BPS if ((fvalue=std::round(params[CONTROL_ROOT_KEY_PARAM].getValue()))!=circle_root_key) { circle_root_key=(int)fvalue; root_key=circle_of_fifths[circle_root_key]; if (doDebug) DEBUG("root_key changed to %d = %s", root_key, note_desig[root_key]); for (int i=0; i<12; ++i) lights[LIGHT_CIRCLE_ROOT_KEY_POSITION_1_LIGHT+i].setBrightness(0.0f); lights[LIGHT_CIRCLE_ROOT_KEY_POSITION_1_LIGHT+circle_root_key].setBrightness(1.0f); circleChanged=true; } if ((fvalue=std::round(params[CONTROL_SCALE_PARAM].getValue()))!=mode) { mode = fvalue; if (doDebug) DEBUG("mode changed to %d", mode); circleChanged=true; } // check input ports for change for (int i=0; i<Meander::NUM_INPUTS; ++i) { if (inputs[i].isConnected()) { float fvalue=inputs[i].getVoltage(); if ((i==IN_MELODY_SCALE_DEGREE_EXT_CV)||(fvalue!=inportStates[i].lastValue)) // don't do anything unless input changed { if (i!=IN_MELODY_SCALE_DEGREE_EXT_CV) inportStates[i].lastValue=fvalue; switch (i) { // process misc input ports case IN_TIMESIGNATURETOP_EXT_CV: if (fvalue>=0.01) { float ratio=(fvalue/10.0); float range=(13); int newValue=2 + (int)(ratio*range); newValue=clamp(newValue, 2, 15); if (newValue!=time_sig_top) { time_sig_top=newValue; params[CONTROL_TIMESIGNATURETOP_PARAM].setValue((float)newValue); time_sig_changed=true; } } break; case IN_TIMESIGNATUREBOTTOM_EXT_CV: if (fvalue>=0.01) { float ratio=(fvalue/10.0); int exp=(int)(ratio*3); exp=clamp(exp, 0, 3); int newValue=pow(2,exp+1); if (newValue!=time_sig_bottom) { time_sig_bottom=newValue; params[CONTROL_TIMESIGNATUREBOTTOM_PARAM].setValue((float)exp); int melody_note_length_divisor=0; if (time_sig_bottom==2) melody_note_length_divisor=1; else if (time_sig_bottom==4) melody_note_length_divisor=2; else if (time_sig_bottom==8) melody_note_length_divisor=3; else if (time_sig_bottom==16) melody_note_length_divisor=4; theMeanderState.theMelodyParms.note_length_divisor=(int)std::pow(2,melody_note_length_divisor); params[CONTROL_MELODY_NOTE_LENGTH_DIVISOR_PARAM].setValue(melody_note_length_divisor); theMeanderState.theArpParms.note_length_divisor=(int)std::pow(2,melody_note_length_divisor+1); params[CONTROL_ARP_INCREMENT_PARAM].setValue(melody_note_length_divisor+1); time_sig_changed=true; } } break; // process harmony input ports case IN_HARMONY_ENABLE_EXT_CV: if (fvalue>0) theMeanderState.theHarmonyParms.enabled = true; else if (fvalue==0) theMeanderState.theHarmonyParms.enabled = false; else if (fvalue<0) { // Do nothing. Allow local parameter control } break; case IN_HARMONY_VOLUME_EXT_CV: if (fvalue>=0.01) if (fvalue!=theMeanderState.theHarmonyParms.volume) { fvalue=clamp(fvalue, 0., 10.); theMeanderState.theHarmonyParms.volume=fvalue; params[CONTROL_HARMONY_VOLUME_PARAM].setValue(fvalue); outputs[OUT_HARMONY_VOLUME_OUTPUT].setVoltage(theMeanderState.theHarmonyParms.volume); } break; case IN_HARMONY_STEPS_EXT_CV: if (fvalue>0) { float ratio=(fvalue/10.0); float range=(theActiveHarmonyType.max_steps-theActiveHarmonyType.min_steps); int newValue=theActiveHarmonyType.min_steps + (int)(ratio*range); newValue=clamp(newValue, theActiveHarmonyType.min_steps, theActiveHarmonyType.max_steps); if (newValue!=params[CONTROL_HARMONY_STEPS_PARAM].getValue()) { if ((newValue>=theActiveHarmonyType.min_steps)&&(newValue<=theActiveHarmonyType.max_steps)) { theActiveHarmonyType.num_harmony_steps=(int)newValue; params[CONTROL_HARMONY_STEPS_PARAM].setValue(newValue); } } } else { // Do nothing. Allow local control } break; case IN_HARMONY_TARGETOCTAVE_EXT_CV: if (fvalue>=0.01) { float ratio=(fvalue/10.0); int newValue=1+ (int)(ratio*5); newValue=clamp(newValue, 1, 6); if (newValue!=theMeanderState.theHarmonyParms.target_octave) { theMeanderState.theHarmonyParms.target_octave=(int)newValue; theMeanderState.theHarmonyParms.note_avg_target=theMeanderState.theHarmonyParms.target_octave/10.0; theMeanderState.theHarmonyParms.range_top= theMeanderState.theHarmonyParms.note_avg_target + (theMeanderState.theHarmonyParms.note_octave_range/10.0); theMeanderState.theHarmonyParms.range_bottom= theMeanderState.theHarmonyParms.note_avg_target - (theMeanderState.theHarmonyParms.note_octave_range/10.0); theMeanderState.theHarmonyParms.r1=(theMeanderState.theHarmonyParms.range_top-theMeanderState.theHarmonyParms.range_bottom); params[CONTROL_HARMONY_TARGETOCTAVE_PARAM].setValue(newValue); } } break; case IN_HARMONY_ALPHA_EXT_CV: if (fvalue>=0.01) { float newValue=(fvalue/10.0); newValue=clamp(newValue, 0., 1.); if (newValue!=theMeanderState.theHarmonyParms.alpha) { theMeanderState.theHarmonyParms.alpha=newValue; params[CONTROL_HARMONY_ALPHA_PARAM].setValue(newValue); } } break; case IN_HARMONY_RANGE_EXT_CV: if (fvalue>=0.01) { float ratio=(fvalue/10.0); float newValue=ratio*3; newValue=clamp(newValue, 0., 3.); if (newValue!=theMeanderState.theHarmonyParms.note_octave_range) { theMeanderState.theHarmonyParms.note_octave_range=newValue; theMeanderState.theHarmonyParms.note_avg_target=theMeanderState.theHarmonyParms.target_octave/10.0; theMeanderState.theHarmonyParms.range_top= theMeanderState.theHarmonyParms.note_avg_target + (theMeanderState.theHarmonyParms.note_octave_range/10.0); theMeanderState.theHarmonyParms.range_bottom= theMeanderState.theHarmonyParms.note_avg_target - (theMeanderState.theHarmonyParms.note_octave_range/10.0); theMeanderState.theHarmonyParms.r1=(theMeanderState.theHarmonyParms.range_top-theMeanderState.theHarmonyParms.range_bottom); params[CONTROL_HARMONY_RANGE_PARAM].setValue(newValue); } } break; case IN_HARMONY_DIVISOR_EXT_CV: if (fvalue>=0.01) { // float ratio=(fvalue/10.0); float ratio=(fvalue/9.0); // allow for CV that doesn't quite get to 10.0 int exp=(int)(ratio*3); exp=clamp(exp, 0, 3); // int exp=(int)(ratio*4); // exp=clamp(exp, 0, 4); int newValue=pow(2,exp); if (newValue!=theMeanderState.theHarmonyParms.note_length_divisor) { theMeanderState.theHarmonyParms.note_length_divisor=newValue; params[CONTROL_HARMONY_DIVISOR_PARAM].setValue((float)exp); } } break; case IN_ENABLE_HARMONY_ALL7THS_EXT_CV: if (fvalue>0) { theMeanderState.theHarmonyParms.enable_all_7ths = true; theMeanderState.theHarmonyParms.enable_V_7ths=false; setup_harmony(); // calculate harmony notes } else if (fvalue==0) { theMeanderState.theHarmonyParms.enable_all_7ths = false; setup_harmony(); // calculate harmony notes } else if (fvalue<0) { // Do nothing. Allow local parameter control } break; case IN_ENABLE_HARMONY_V7THS_EXT_CV: if (fvalue>0) { theMeanderState.theHarmonyParms.enable_V_7ths = true; theMeanderState.theHarmonyParms.enable_all_7ths=false; setup_harmony(); // calculate harmony notes } else if (fvalue==0) { theMeanderState.theHarmonyParms.enable_V_7ths = false; setup_harmony(); // calculate harmony notes } else if (fvalue<0) { // Do nothing. Allow local parameter control } break; case IN_ENABLE_HARMONY_STACCATO_EXT_CV: if (fvalue>0) { theMeanderState.theHarmonyParms.enable_staccato = true; } else if (fvalue==0) { theMeanderState.theHarmonyParms.enable_staccato = false; } else if (fvalue<0) { // Do nothing. Allow local parameter control } break; case IN_HARMONYPRESETS_EXT_CV: if (fvalue>=0.01) { float ratio=(fvalue/10.0); float newValue=1.+ (ratio*(MAX_AVAILABLE_HARMONY_PRESETS-1)); newValue=clamp(newValue, 1., (float)MAX_AVAILABLE_HARMONY_PRESETS); if ((int)newValue!=harmony_type) { if (doDebug) DEBUG("getVoltage harmony type=%d", (int)newValue); harmonyPresetChanged=(int)newValue; // don't changed until between sequences. The new harmony_type is in harmonyPresetChanged } else { // Ao nothing. Allow local control } } break; // process melody input ports case IN_MELODY_ENABLE_EXT_CV: if (fvalue>0) { theMeanderState.theMelodyParms.enabled = true; theMeanderState.userControllingMelody=false; } else if (fvalue==0) theMeanderState.theMelodyParms.enabled = false; else if (fvalue<0) { // Do nothing. Allow local parameter control } break; case IN_MELODY_SCALE_DEGREE_EXT_CV: if (inputs[IN_MELODY_SCALE_DEGREE_EXT_CV].isConnected() && inputs[IN_MELODY_SCALE_GATE_EXT_CV].isConnected()) { scaleDegree=inputs[IN_MELODY_SCALE_DEGREE_EXT_CV].getVoltage(); gateValue=inputs[IN_MELODY_SCALE_GATE_EXT_CV].getVoltage(); float octave=(float)((int)(scaleDegree)); // from the keyboard if (octave>3) octave=3; if (octave<-3) octave=-3; bool degreeChanged=false; // assume false unless determined true below bool skipStep=false; if ((gateValue==scaleDegree)&&(scaleDegree>=1)&&(scaleDegree<=7.7)) // MarkovSeq or other 1-7V degree degree.octave 1.0-7.7V { if (inportStates[IN_MELODY_SCALE_DEGREE_EXT_CV].inTransition) { if (fvalue==inportStates[IN_MELODY_SCALE_DEGREE_EXT_CV].lastValue) { // was in transition but now is not inportStates[IN_MELODY_SCALE_DEGREE_EXT_CV].inTransition=false; inportStates[IN_MELODY_SCALE_DEGREE_EXT_CV].lastValue=fvalue; theMeanderState.theMelodyParms.lastMelodyDegreeIn=fvalue; octave = (int)(10.0*std::fmod(scaleDegree, 1.0f)); if (octave>7) octave=7; scaleDegree=(float)((int)scaleDegree); degreeChanged=true; // not really, but replay the note below } else if (fvalue!=inportStates[IN_MELODY_SCALE_DEGREE_EXT_CV].lastValue) { inportStates[IN_MELODY_SCALE_DEGREE_EXT_CV].lastValue=fvalue; } } else { if (fvalue!=inportStates[IN_MELODY_SCALE_DEGREE_EXT_CV].lastValue) { inportStates[IN_MELODY_SCALE_DEGREE_EXT_CV].inTransition=true; inportStates[IN_MELODY_SCALE_DEGREE_EXT_CV].lastValue=fvalue; } } } else if ((gateValue==scaleDegree)&&((scaleDegree<1.0)||(scaleDegree>=8.0))) // MarkovSeq or other 1-7V degree degree.octave 1.0-7.7V <1 or >=8V means skip step { inportStates[IN_MELODY_SCALE_DEGREE_EXT_CV].lastValue=fvalue; degreeChanged=true; skipStep=true; } else // keyboard C-B if (!(gateValue==scaleDegree)) { float fgvalue=inputs[IN_MELODY_SCALE_GATE_EXT_CV].getVoltage(); if (inportStates[IN_MELODY_SCALE_GATE_EXT_CV].inTransition) { if (fgvalue==inportStates[IN_MELODY_SCALE_GATE_EXT_CV].lastValue) { // was in transition but now is not inportStates[IN_MELODY_SCALE_GATE_EXT_CV].inTransition=false; inportStates[IN_MELODY_SCALE_GATE_EXT_CV].lastValue=fgvalue; if (fgvalue) // gate has gone high { if ( scaleDegree==inportStates[IN_MELODY_SCALE_DEGREE_EXT_CV].lastValue) // the gate has changed but the degree has not degreeChanged=true; // not really, but play like it has so it will be replayed below } } else if (fgvalue!=inportStates[IN_MELODY_SCALE_GATE_EXT_CV].lastValue) { inportStates[IN_MELODY_SCALE_GATE_EXT_CV].lastValue=fgvalue; } } else { if (fgvalue!=inportStates[IN_MELODY_SCALE_GATE_EXT_CV].lastValue) { inportStates[IN_MELODY_SCALE_GATE_EXT_CV].inTransition=true; inportStates[IN_MELODY_SCALE_GATE_EXT_CV].lastValue=fgvalue; } } if ( (degreeChanged) || (scaleDegree!=inportStates[IN_MELODY_SCALE_DEGREE_EXT_CV].lastValue)) { inportStates[IN_MELODY_SCALE_DEGREE_EXT_CV].lastValue= scaleDegree; octave=(float)((int)(scaleDegree)); // from the keyboard if (octave>3) octave=3; if (octave<-3) octave=-3; if (scaleDegree>=0) scaleDegree=(float)std::fmod(std::fabs(scaleDegree), 1.0f); else scaleDegree=-(float)std::fmod(std::fabs(scaleDegree), 1.0f); degreeChanged=true; if (doDebug) DEBUG("IN_MELODY_SCALE_DEGREE_EXT_CV scaleDegree=%f", scaleDegree); if (scaleDegree>=0) { if ((std::abs(scaleDegree)<.005f)) scaleDegree=1; else if ((std::abs(scaleDegree-.167f)<.005f)) scaleDegree=2; else if ((std::abs(scaleDegree-.333f)<.005f)) scaleDegree=3; else if ((std::abs(scaleDegree-.417f)<.005f)) scaleDegree=4; else if ((std::abs(scaleDegree-.583f)<.005f)) scaleDegree=5; else if ((std::abs(scaleDegree-.750f)<.005f)) scaleDegree=6; else if ((std::abs(scaleDegree-.917f)<.005f)) scaleDegree=7; else degreeChanged=false; } else { octave-=1; if ((std::abs(scaleDegree)<.005f)) scaleDegree=1; else if (std::abs(std::abs(scaleDegree)-.083)<.005f) scaleDegree=7; else if (std::abs(std::abs(scaleDegree)-.250)<.005f) scaleDegree=6; else if (std::abs(std::abs(scaleDegree)-.417)<.005f) scaleDegree=5; else if (std::abs(std::abs(scaleDegree)-.583)<.005f) scaleDegree=4; else if (std::abs(std::abs(scaleDegree)-.667)<.005f) scaleDegree=3; else if (std::abs(std::abs(scaleDegree)-.833)<.005f) scaleDegree=2; else degreeChanged=false; } } } if ((degreeChanged)&&(!skipStep)) { if (scaleDegree<1) scaleDegree=1; if (scaleDegree>7) scaleDegree=7; if (doDebug) DEBUG("IN_HARMONY_CIRCLE_DEGREE_EXT_CV=%d", (int)theMeanderState.circleDegree); // DEBUG("IN_HARMONY_CIRCLE_DEGREE_EXT_CV=%d", (int)theMeanderState.circleDegree); if (scaleDegree>0) { userPlaysScaleDegreeMelody(scaleDegree, octave+theMeanderState.theMelodyParms.target_octave); theMeanderState.theArpParms.note_count=0; } if (running) { if (theMeanderState.theMelodyParms.enabled) theMeanderState.theMelodyParms.enabled = false; theMeanderState.userControllingMelody=true; } } } break; case IN_MELODY_VOLUME_EXT_CV: if (fvalue>=.01) if (fvalue!=theMeanderState.theMelodyParms.volume) { fvalue=clamp(fvalue, 0., 10.); theMeanderState.theMelodyParms.volume=fvalue; params[CONTROL_MELODY_VOLUME_PARAM].setValue(fvalue); outputs[OUT_MELODY_VOLUME_OUTPUT].setVoltage(theMeanderState.theMelodyParms.volume); } break; case IN_MELODY_NOTE_LENGTH_DIVISOR_EXT_CV: if (fvalue>=.01) { // float ratio=(fvalue/10.0); float ratio=(fvalue/9.0); // allow for CV that doesn't quite get to 10V int exp=(int)(ratio*5); exp=clamp(exp, 0, 5); int newValue=pow(2,exp); if (newValue!=theMeanderState.theMelodyParms.note_length_divisor) { theMeanderState.theMelodyParms.note_length_divisor=newValue; params[CONTROL_MELODY_NOTE_LENGTH_DIVISOR_PARAM].setValue((float)exp); } } break; case IN_MELODY_TARGETOCTAVE_EXT_CV: if (fvalue>=.01) { float ratio=(fvalue/10.0); int newValue=1+ (int)(ratio*5); newValue=clamp(newValue, 1, 6); if (newValue!=theMeanderState.theMelodyParms.target_octave) { theMeanderState.theMelodyParms.target_octave=(int)newValue; theMeanderState.theMelodyParms.note_avg_target=theMeanderState.theMelodyParms.target_octave/10.0; theMeanderState.theMelodyParms.range_top= theMeanderState.theMelodyParms.note_avg_target + (theMeanderState.theMelodyParms.note_octave_range/10.0); theMeanderState.theMelodyParms.range_bottom= theMeanderState.theMelodyParms.note_avg_target - (theMeanderState.theMelodyParms.note_octave_range/10.0); theMeanderState.theMelodyParms.r1=(theMeanderState.theMelodyParms.range_top-theMeanderState.theMelodyParms.range_bottom); params[CONTROL_MELODY_TARGETOCTAVE_PARAM].setValue(newValue); } } break; case IN_MELODY_ALPHA_EXT_CV: if (fvalue>=.01) { float newValue=(fvalue/10.0); newValue=clamp(newValue, 0., 1.); if (newValue!=theMeanderState.theMelodyParms.alpha) { theMeanderState.theMelodyParms.alpha=newValue; params[CONTROL_MELODY_ALPHA_PARAM].setValue(newValue); } } break; case IN_MELODY_RANGE_EXT_CV: if (fvalue>=.01) { float ratio=(fvalue/10.0); float newValue=ratio*3; newValue=clamp(newValue, 0., 3.); if (newValue!=theMeanderState.theMelodyParms.note_octave_range) { theMeanderState.theMelodyParms.note_octave_range=newValue; theMeanderState.theMelodyParms.note_avg_target=theMeanderState.theMelodyParms.target_octave/10.0; theMeanderState.theMelodyParms.range_top= theMeanderState.theMelodyParms.note_avg_target + (theMeanderState.theMelodyParms.note_octave_range/10.0); theMeanderState.theMelodyParms.range_bottom= theMeanderState.theMelodyParms.note_avg_target - (theMeanderState.theMelodyParms.note_octave_range/10.0); theMeanderState.theMelodyParms.r1=(theMeanderState.theMelodyParms.range_top-theMeanderState.theMelodyParms.range_bottom); params[CONTROL_MELODY_RANGE_PARAM].setValue(newValue); } } break; //// case IN_MELODY_DESTUTTER_EXT_CV: if (fvalue>0) { theMeanderState.theMelodyParms.destutter = true; } else if (fvalue==0) { theMeanderState.theMelodyParms.destutter = false; } else if (fvalue<0) { // Do nothing. Allow local parameter control } break; case IN_ENABLE_MELODY_STACCATO_EXT_CV: if (fvalue>0) { theMeanderState.theMelodyParms.enable_staccato = true; } else if (fvalue==0) { theMeanderState.theMelodyParms.enable_staccato = false; } else if (fvalue<0) { // Do nothing. Allow local parameter control } break; case IN_ENABLE_MELODY_CHORDAL_EXT_CV: if (fvalue>0) { theMeanderState.theMelodyParms.chordal = true; theMeanderState.theMelodyParms.scaler = false; } else if (fvalue==0) { theMeanderState.theMelodyParms.chordal = false; theMeanderState.theMelodyParms.scaler = true; } else if (fvalue<0) { // Do nothing. Allow local parameter control } break; case IN_MELODY_SCALER_EXT_CV: if (fvalue>0) { theMeanderState.theMelodyParms.scaler = true; theMeanderState.theMelodyParms.chordal = false; } else if (fvalue==0) { theMeanderState.theMelodyParms.scaler = false; theMeanderState.theMelodyParms.chordal = true; } else if (fvalue<0) { // Do nothing. Allow local parameter control } break; // process arp input ports case IN_ARP_ENABLE_EXT_CV: if (fvalue>0) theMeanderState.theArpParms.enabled = true; else if (fvalue==0) theMeanderState.theArpParms.enabled = false; else if (fvalue<0) { // Do nothing. Allow local parameter control } break; case IN_ARP_COUNT_EXT_CV: if (fvalue>=.01) { float ratio=(fvalue/10.0); // int newValue=(int)(ratio*7); int newValue=(int)(ratio*31); // newValue=clamp(newValue, 0, 7); newValue=clamp(newValue, 0, 31); if (newValue!=theMeanderState.theArpParms.count) { theMeanderState.theArpParms.count=newValue; params[CONTROL_ARP_COUNT_PARAM].setValue((float)newValue); } } break; case IN_ARP_INCREMENT_EXT_CV: if (fvalue>=.01) { // float ratio=(fvalue/10.0); float ratio=(fvalue/9.0); // allow for CV that doesn't quite get to 10.0 int exp=(int)(ratio*3); exp=clamp(exp, 0, 3)+2; int newValue=pow(2,exp); if (newValue!=theMeanderState.theArpParms.note_length_divisor) { theMeanderState.theArpParms.note_length_divisor=newValue; params[CONTROL_ARP_INCREMENT_PARAM].setValue((float)exp); } } break; case IN_ARP_DECAY_EXT_CV: if (fvalue>=.01) { float newValue=(fvalue/10.0); newValue=clamp(newValue, 0., 1.); if (newValue!=theMeanderState.theArpParms.decay) { theMeanderState.theArpParms.decay=newValue; params[CONTROL_ARP_DECAY_PARAM].setValue(newValue); } } break; case IN_ENABLE_ARP_CHORDAL_EXT_CV: if (fvalue>0) { theMeanderState.theArpParms.chordal = true; theMeanderState.theArpParms.scaler = false; } else if (fvalue==0) { theMeanderState.theArpParms.chordal = false; theMeanderState.theArpParms.scaler = true; } else if (fvalue<0) { // Do nothing. Allow local parameter control } break; case IN_ENABLE_ARP_SCALER_EXT_CV: if (fvalue>0) { theMeanderState.theArpParms.scaler = true; theMeanderState.theArpParms.chordal = false; } else if (fvalue==0) { theMeanderState.theArpParms.scaler = false; theMeanderState.theArpParms.chordal = true; } else if (fvalue<0) { // Do nothing. Allow local parameter control } break; case IN_ARP_PATTERN_EXT_CV: // issue with range of -3 to +3 if (true) // just for local variable scope { // float ratio=(fvalue/10.0); float ratio=(fvalue/9.0); // handle CV's that do not quite make it to 10.0V // int newValue=(int)(ratio*3); // newValue=clamp(newValue, -3, 3); // int newValue=(int)(ratio*2); int newValue=(int)(ratio*4); newValue -= 2; newValue=clamp(newValue, -2, 2); if (newValue!=theMeanderState.theArpParms.pattern) { theMeanderState.theArpParms.pattern=newValue; params[CONTROL_ARP_PATTERN_PARAM].setValue(newValue); } } break; // process bass input ports case IN_BASS_ENABLE_EXT_CV: if (fvalue>0) theMeanderState.theBassParms.enabled = true; else if (fvalue==0) theMeanderState.theBassParms.enabled = false; else if (fvalue<0) { // Do nothing. Allow local parameter control } break; case IN_BASS_VOLUME_EXT_CV: if (fvalue>=.01) if (fvalue!=theMeanderState.theBassParms.volume) { fvalue=clamp(fvalue, 0., 10.); theMeanderState.theBassParms.volume=fvalue; params[CONTROL_BASS_VOLUME_PARAM].setValue(fvalue); outputs[OUT_BASS_VOLUME_OUTPUT].setVoltage(theMeanderState.theBassParms.volume); } break; case IN_BASS_TARGETOCTAVE_EXT_CV: if (fvalue>=.01) { float ratio=(fvalue/10.0); int newValue=1+ (int)(ratio*5); newValue=clamp(newValue, 1, 6); if (newValue!=theMeanderState.theBassParms.target_octave) { theMeanderState.theBassParms.target_octave=(int)newValue; params[CONTROL_BASS_TARGETOCTAVE_PARAM].setValue(newValue); } } break; case IN_BASS_DIVISOR_EXT_CV: if (fvalue>=.01) { //float ratio=(fvalue/10.0); float ratio=(fvalue/9.0); // allow for CV that doesn't quite get to 10.0 int exp=(int)(ratio*3); exp=clamp(exp, 0, 3); int newValue=pow(2,exp); if (newValue!=theMeanderState.theBassParms.note_length_divisor) { theMeanderState.theBassParms.note_length_divisor=newValue; params[CONTROL_BASS_DIVISOR_PARAM].setValue((float)exp); } } break; case IN_ENABLE_BASS_STACCATO_EXT_CV: if (fvalue>0) { theMeanderState.theBassParms.enable_staccato = true; } else if (fvalue==0) { theMeanderState.theBassParms.enable_staccato = false; } else if (fvalue<0) { // Do nothing. Allow local parameter control } break; case IN_BASS_ACCENT_EXT_CV: if (fvalue>0) { theMeanderState.theBassParms.accent = true; } else if (fvalue==0) { theMeanderState.theBassParms.accent = false; } else if (fvalue<0) { // Do nothing. Allow local parameter control } break; case IN_BASS_SYNCOPATE_EXT_CV: if (fvalue>0) { theMeanderState.theBassParms.syncopate = true; } else if (fvalue==0) { theMeanderState.theBassParms.syncopate = false; } else if (fvalue<0) { // Do nothing. Allow local parameter control } break; case IN_BASS_SHUFFLE_EXT_CV: if (fvalue>0) { theMeanderState.theBassParms.shuffle = true; } else if (fvalue==0) { theMeanderState.theBassParms.shuffle = false; } else if (fvalue<0) { // Do nothing. Allow local parameter control } break; case IN_BASS_OCTAVES_EXT_CV: if (fvalue>0) { theMeanderState.theBassParms.octave_enabled = true; } else if (fvalue==0) { theMeanderState.theBassParms.octave_enabled = false; } else if (fvalue<0) { // Do nothing. Allow local parameter control } break; // process fBn input ports case IN_HARMONY_FBM_OCTAVES_EXT_CV: if (fvalue>=.01) { float ratio=(fvalue/10.0); int newValue=1+(int)(ratio*5); newValue=clamp(newValue, 1, 6); if (newValue!=theMeanderState.theHarmonyParms.noctaves) { theMeanderState.theHarmonyParms.noctaves=newValue; params[CONTROL_HARMONY_FBM_OCTAVES_PARAM].setValue((float)newValue); } } break; case IN_HARMONY_FBM_PERIOD_EXT_CV: if (fvalue>=.01) { float ratio=(fvalue/10.0); int newValue=1+(int)(ratio*100); newValue=clamp(newValue, 1, 100); if (newValue!=theMeanderState.theHarmonyParms.period) { theMeanderState.theHarmonyParms.period=newValue; params[CONTROL_HARMONY_FBM_PERIOD_PARAM].setValue((float)newValue); } } break; case IN_MELODY_FBM_OCTAVES_EXT_CV: if (fvalue>=.01) { float ratio=(fvalue/10.0); int newValue=1+(int)(ratio*5); newValue=clamp(newValue, 1, 6); if (newValue!=theMeanderState.theMelodyParms.noctaves) { theMeanderState.theMelodyParms.noctaves=newValue; params[CONTROL_MELODY_FBM_OCTAVES_PARAM].setValue((float)newValue); } } break; case IN_MELODY_FBM_PERIOD_EXT_CV: if (fvalue>=.01) { float ratio=(fvalue/10.0); int newValue=1+(int)(ratio*100); newValue=clamp(newValue, 1, 100); if (newValue!=theMeanderState.theMelodyParms.period) { theMeanderState.theMelodyParms.period=newValue; params[CONTROL_MELODY_FBM_PERIOD_PARAM].setValue((float)newValue); } } break; case IN_ARP_FBM_OCTAVES_EXT_CV: if (fvalue>=.01) { float ratio=(fvalue/10.0); int newValue=1+(int)(ratio*5); newValue=clamp(newValue, 1, 6); if (newValue!=theMeanderState.theArpParms.noctaves) { theMeanderState.theArpParms.noctaves=newValue; params[CONTROL_ARP_FBM_OCTAVES_PARAM].setValue((float)newValue); } } break; case IN_ARP_FBM_PERIOD_EXT_CV: if (fvalue>=.01) { float ratio=(fvalue/10.0); int newValue=1+(int)(ratio*100); newValue=clamp(newValue, 1, 100); if (newValue!=theMeanderState.theArpParms.period) { theMeanderState.theArpParms.period=newValue; params[CONTROL_ARP_FBM_PERIOD_PARAM].setValue((float)newValue); } } break; // handle mode and root input changes case IN_ROOT_KEY_EXT_CV: if (fvalue>=.01) { float ratio=(fvalue/10.0); int newValue=(int)(ratio*11); newValue=clamp(newValue, 0, 11); if (newValue!=circle_root_key) { circle_root_key=(int)newValue; root_key=circle_of_fifths[circle_root_key]; params[CONTROL_ROOT_KEY_PARAM].setValue(circle_root_key); if (doDebug) DEBUG("root_key changed to %d = %s", root_key, note_desig[root_key]); for (int i=0; i<12; ++i) lights[LIGHT_CIRCLE_ROOT_KEY_POSITION_1_LIGHT+i].setBrightness(0.0f); lights[LIGHT_CIRCLE_ROOT_KEY_POSITION_1_LIGHT+circle_root_key].setBrightness(1.0f); circleChanged=true; } } break; case IN_SCALE_EXT_CV: if (fvalue>=.01) { float ratio=(fvalue/10.0); int newValue=(int)(ratio*6); newValue=clamp(newValue, 0, 6); if (newValue!=mode) { mode=(int)newValue; params[CONTROL_SCALE_PARAM].setValue(mode); circleChanged=true; } } break; }; // end switch } } } // harmony params fvalue=(params[CONTROL_HARMONY_VOLUME_PARAM].getValue()); if (fvalue!=theMeanderState.theHarmonyParms.volume) { theMeanderState.theHarmonyParms.volume=fvalue; outputs[OUT_HARMONY_VOLUME_OUTPUT].setVoltage(theMeanderState.theHarmonyParms.volume); } fvalue=std::round(params[CONTROL_HARMONY_TARGETOCTAVE_PARAM].getValue()); if (fvalue!=theMeanderState.theHarmonyParms.target_octave) { theMeanderState.theHarmonyParms.target_octave=fvalue; theMeanderState.theHarmonyParms.note_avg_target=theMeanderState.theHarmonyParms.target_octave/10.0; theMeanderState.theHarmonyParms.range_top= theMeanderState.theHarmonyParms.note_avg_target + (theMeanderState.theHarmonyParms.note_octave_range/10.0); theMeanderState.theHarmonyParms.range_bottom= theMeanderState.theHarmonyParms.note_avg_target - (theMeanderState.theHarmonyParms.note_octave_range/10.0); theMeanderState.theHarmonyParms.r1=(theMeanderState.theHarmonyParms.range_top-theMeanderState.theHarmonyParms.range_bottom); } fvalue=params[CONTROL_HARMONY_DIVISOR_PARAM].getValue(); ivalue=(int)fvalue; ivalue=pow(2,ivalue); if ((ivalue)!=theMeanderState.theHarmonyParms.note_length_divisor) { theMeanderState.theHarmonyParms.note_length_divisor=ivalue; } fvalue=(params[CONTROL_HARMONY_RANGE_PARAM].getValue()); if (fvalue!=theMeanderState.theMelodyParms.note_octave_range) { theMeanderState.theHarmonyParms.note_octave_range=fvalue; theMeanderState.theHarmonyParms.note_avg_target=theMeanderState.theHarmonyParms.target_octave/10.0; theMeanderState.theHarmonyParms.range_top= theMeanderState.theHarmonyParms.note_avg_target + (theMeanderState.theHarmonyParms.note_octave_range/10.0); theMeanderState.theHarmonyParms.range_bottom= theMeanderState.theHarmonyParms.note_avg_target - (theMeanderState.theHarmonyParms.note_octave_range/10.0); theMeanderState.theHarmonyParms.r1=(theMeanderState.theHarmonyParms.range_top-theMeanderState.theHarmonyParms.range_bottom); } fvalue=(params[CONTROL_HARMONY_ALPHA_PARAM].getValue()); if ((fvalue)!=theMeanderState.theHarmonyParms.alpha) { theMeanderState.theHarmonyParms.alpha=fvalue; } fvalue=params[CONTROL_HARMONY_FBM_OCTAVES_PARAM].getValue(); if (fvalue!=theMeanderState.theHarmonyParms.noctaves) { theMeanderState.theHarmonyParms.noctaves=fvalue; } fvalue=params[CONTROL_HARMONY_FBM_PERIOD_PARAM].getValue(); if (fvalue!=theMeanderState.theHarmonyParms.period) { theMeanderState.theHarmonyParms.period=fvalue; } //********* if ((fvalue=std::round(params[CONTROL_HARMONYPRESETS_PARAM].getValue()))!=harmony_type) { if (doDebug) DEBUG(" getValue harmony type=%d", (int)fvalue); harmonyPresetChanged=(int)fvalue; // don't changed until between sequences. The new harmony_type is in harmonyPresetChanged } fvalue=std::round(params[CONTROL_HARMONY_STEPS_PARAM].getValue()); if ((fvalue!=theActiveHarmonyType.num_harmony_steps)&&(fvalue>=theActiveHarmonyType.min_steps)&&(fvalue<=theActiveHarmonyType.max_steps)&&(fvalue!=theActiveHarmonyType.num_harmony_steps)) { if (doDebug) DEBUG("theActiveHarmonyType.min_steps=%d, theActiveHarmonyType.max_steps=%d", theActiveHarmonyType.min_steps, theActiveHarmonyType.max_steps ); if (doDebug) DEBUG("theActiveHarmonyType.num_harmony_steps changed to %d %s", (int)fvalue, "test"); // need actual descriptor if ((fvalue>=theActiveHarmonyType.min_steps)&&(fvalue<=theActiveHarmonyType.max_steps)) theActiveHarmonyType.num_harmony_steps=(int)fvalue; } // Melody Params fvalue=(params[CONTROL_MELODY_VOLUME_PARAM].getValue()); if (fvalue!=theMeanderState.theMelodyParms.volume) { theMeanderState.theMelodyParms.volume=fvalue; outputs[OUT_MELODY_VOLUME_OUTPUT].setVoltage(theMeanderState.theMelodyParms.volume); } fvalue=std::round(params[CONTROL_MELODY_TARGETOCTAVE_PARAM].getValue()); if (fvalue!=theMeanderState.theMelodyParms.target_octave) { theMeanderState.theMelodyParms.target_octave=fvalue; theMeanderState.theMelodyParms.note_avg_target=theMeanderState.theMelodyParms.target_octave/10.0; theMeanderState.theMelodyParms.range_top= theMeanderState.theMelodyParms.note_avg_target + (theMeanderState.theMelodyParms.note_octave_range/10.0); theMeanderState.theMelodyParms.range_bottom= theMeanderState.theMelodyParms.note_avg_target - (theMeanderState.theMelodyParms.note_octave_range/10.0); theMeanderState.theMelodyParms.r1=(theMeanderState.theMelodyParms.range_top-theMeanderState.theMelodyParms.range_bottom); } fvalue=(params[CONTROL_MELODY_RANGE_PARAM].getValue()); if (fvalue!=theMeanderState.theMelodyParms.note_octave_range) { theMeanderState.theMelodyParms.note_octave_range=fvalue; theMeanderState.theMelodyParms.note_avg_target=theMeanderState.theMelodyParms.target_octave/10.0; theMeanderState.theMelodyParms.range_top= theMeanderState.theMelodyParms.note_avg_target + (theMeanderState.theMelodyParms.note_octave_range/10.0); theMeanderState.theMelodyParms.range_bottom= theMeanderState.theMelodyParms.note_avg_target - (theMeanderState.theMelodyParms.note_octave_range/10.0); theMeanderState.theMelodyParms.r1=(theMeanderState.theMelodyParms.range_top-theMeanderState.theMelodyParms.range_bottom); } fvalue=(params[CONTROL_MELODY_ALPHA_PARAM].getValue()); if ((fvalue)!=theMeanderState.theMelodyParms.alpha) { theMeanderState.theMelodyParms.alpha=fvalue; } fvalue=params[CONTROL_MELODY_NOTE_LENGTH_DIVISOR_PARAM].getValue(); ivalue=(int)fvalue; ivalue=pow(2,ivalue); if ((ivalue)!=theMeanderState.theMelodyParms.note_length_divisor) { theMeanderState.theMelodyParms.note_length_divisor=ivalue; } fvalue=params[CONTROL_MELODY_FBM_OCTAVES_PARAM].getValue(); if (fvalue!=theMeanderState.theMelodyParms.noctaves) { theMeanderState.theMelodyParms.noctaves=fvalue; } fvalue=params[CONTROL_MELODY_FBM_PERIOD_PARAM].getValue(); if (fvalue!=theMeanderState.theMelodyParms.period) { theMeanderState.theMelodyParms.period=fvalue; } // bass params*********** fvalue=(params[CONTROL_BASS_VOLUME_PARAM].getValue()); if (fvalue!=theMeanderState.theBassParms.volume) { theMeanderState.theBassParms.volume=fvalue; outputs[OUT_BASS_VOLUME_OUTPUT].setVoltage(theMeanderState.theBassParms.volume); } fvalue=params[CONTROL_BASS_DIVISOR_PARAM].getValue(); ivalue=(int)fvalue; ivalue=pow(2,ivalue); if ((ivalue)!=theMeanderState.theBassParms.note_length_divisor) { theMeanderState.theBassParms.note_length_divisor=ivalue; } fvalue=std::round(params[CONTROL_BASS_TARGETOCTAVE_PARAM].getValue()); if (fvalue!=theMeanderState.theBassParms.target_octave) { theMeanderState.theBassParms.target_octave=fvalue; } fvalue=std::round(params[CONTROL_ARP_COUNT_PARAM].getValue()); if (fvalue!=theMeanderState.theArpParms.count) { theMeanderState.theArpParms.count=fvalue; } fvalue=std::round(params[CONTROL_ARP_INCREMENT_PARAM].getValue()); ivalue=(int)fvalue; ivalue=pow(2,ivalue); if (ivalue!=theMeanderState.theArpParms.note_length_divisor) { theMeanderState.theArpParms.note_length_divisor=ivalue; } fvalue=(params[ CONTROL_ARP_DECAY_PARAM].getValue()); if (fvalue!=theMeanderState.theArpParms.decay) { theMeanderState.theArpParms.decay=fvalue; } fvalue=std::round(params[CONTROL_ARP_PATTERN_PARAM].getValue()); if (fvalue!=theMeanderState.theArpParms.pattern) { theMeanderState.theArpParms.pattern=fvalue; } fvalue=params[CONTROL_ARP_FBM_OCTAVES_PARAM].getValue(); if (fvalue!=theMeanderState.theArpParms.noctaves) { theMeanderState.theArpParms.noctaves=fvalue; } fvalue=params[CONTROL_ARP_FBM_PERIOD_PARAM].getValue(); if (fvalue!=theMeanderState.theArpParms.period) { theMeanderState.theArpParms.period=fvalue; } // ************************** if (harmonyPresetChanged) { harmony_type=harmonyPresetChanged; copyHarmonyTypeToActiveHarmonyType(harmony_type); harmonyPresetChanged=0; circleChanged=true; // trigger off reconstruction and setup init_harmony(); // reinitialize in case user has changed harmony parms setup_harmony(); // calculate harmony notes params[CONTROL_HARMONYPRESETS_PARAM].setValue(harmony_type); params[CONTROL_HARMONY_STEPS_PARAM].setValue(theHarmonyTypes[harmony_type].num_harmony_steps); time_sig_changed=true; // forces a reset so things start over // AuditHarmonyData(2); } // reconstruct initially and when dirty if (circleChanged) { if (doDebug) DEBUG("circleChanged"); notate_mode_as_signature_root_key=((root_key-(mode_natural_roots[mode_root_key_signature_offset[mode]]))+12)%12; if (doDebug) DEBUG("notate_mode_as_signature_root_key=%d", notate_mode_as_signature_root_key); if ((notate_mode_as_signature_root_key==1) // Db ||(notate_mode_as_signature_root_key==3) // Eb ||(notate_mode_as_signature_root_key==5) // F ||(notate_mode_as_signature_root_key==8) // Ab ||(notate_mode_as_signature_root_key==10)) // Bb { for (int i=0; i<12; ++i) strcpy(note_desig[i], note_desig_flats[i]); } else { for (int i=0; i<12; ++i) strcpy(note_desig[i], note_desig_sharps[i]); } ConstructCircle5ths(circle_root_key, mode); ConstructDegreesSemicircle(circle_root_key, mode); //int circleroot_key, int mode) init_notes(); // depends on mode and root_key init_harmony(); // sets up original progressions AuditHarmonyData(3); setup_harmony(); // calculate harmony notes params[CONTROL_HARMONY_STEPS_PARAM].setValue(theHarmonyTypes[harmony_type].num_harmony_steps); AuditHarmonyData(3); circleChanged=false; } // send Poly External Scale to output // using Aria standard outputs[OUT_EXT_POLY_SCALE_OUTPUT].setChannels(12); // set polyphony for (int i=0; i<12; ++i) { outputs[OUT_EXT_POLY_SCALE_OUTPUT].setVoltage(0.0,i); // (not scale note, channel) } for (int i=0;i<mode_step_intervals[mode][0];++i) { int note=(int)(notes[i]%MAX_NOTES); if (note==root_key) outputs[OUT_EXT_POLY_SCALE_OUTPUT].setVoltage(10.0,(int)note); // (scale note, channel) else outputs[OUT_EXT_POLY_SCALE_OUTPUT].setVoltage(8.0,(int)note); // (scale note, channel) } } if (sec1Clock.process()) { } } // end module process() ~Meander() { if (instanceRunning) { // Release ownership of singleton owned = false; } } Meander() { if (doDebug) DEBUG(""); // clear debug log file if (!owned) { // Take ownership of singleton owned = true; instanceRunning = true; } time_t rawtime; time( &rawtime ); lowFreqClock.setDivision(512); // every 86 samples, 2ms sec1Clock.setDivision(44000); lightDivider.setDivision(512); // every 86 samples, 2ms initPerlin(); MeanderMusicStructuresInitialize(); // sets global globalsInitialized=true config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS); for (int i=0; i<12; ++i) lights[LIGHT_CIRCLE_ROOT_KEY_POSITION_1_LIGHT+i].setBrightness(0.0f); lights[LIGHT_CIRCLE_ROOT_KEY_POSITION_1_LIGHT+root_key].setBrightness(1.0f); // loaded root_key might not be 0/C CircleStepStates[0]=1.0f; lights[LIGHT_LEDBUTTON_CIRCLESTEP_1].setBrightness(1.0f); CircleStepSetStates[0]=1.0f; lights[LIGHT_LEDBUTTON_CIRCLESETSTEP_1].setBrightness(1.0f); configParam(BUTTON_RUN_PARAM, 0.f, 1.f, 0.f, "Run"); configParam(BUTTON_RESET_PARAM, 0.f, 1.f, 0.f, "Reset"); configParam(CONTROL_TEMPOBPM_PARAM, min_bpm, max_bpm, 120.0f, "Tempo", " BPM"); configParam(CONTROL_TIMESIGNATURETOP_PARAM,2.0f, 15.0f, 4.0f, "Time Signature Top"); configParam(CONTROL_TIMESIGNATUREBOTTOM_PARAM,0.0f, 3.0f, 1.0f, "Time Signature Bottom"); // configParam(CONTROL_ROOT_KEY_PARAM, 0, 11, 1.f, "Root/Key"); configParam(CONTROL_ROOT_KEY_PARAM, 0, 11, 0.f, "Root/Key"); configParam(CONTROL_SCALE_PARAM, 0.f, num_modes-1, 1.f, "Mode"); configParam(BUTTON_ENABLE_MELODY_PARAM, 0.f, 1.f, 0.f, "Enable"); configParam(CONTROL_MELODY_VOLUME_PARAM, 0.f, 10.f, 8.0f, "Volume"); configParam(BUTTON_MELODY_DESTUTTER_PARAM, 0.f, 1.f, 0.f, "Hold Tied Notes"); configParam(CONTROL_MELODY_NOTE_LENGTH_DIVISOR_PARAM, 0.f, 5.f, 2.f, "Notes on 1/N"); configParam(CONTROL_MELODY_TARGETOCTAVE_PARAM, 1.f, 6.f, 3.f, "Target Octave"); configParam(CONTROL_MELODY_ALPHA_PARAM, 0.f, 1.f, .9f, "Variablility"); configParam(CONTROL_MELODY_RANGE_PARAM, 0.f, 3.f, 1.f, "Octave Range"); configParam(BUTTON_ENABLE_MELODY_STACCATO_PARAM, 0.f, 1.f, 1.f, "Staccato"); configParam(BUTTON_ENABLE_HARMONY_PARAM, 0.f, 1.f, 0.f, "Enable"); configParam(BUTTON_ENABLE_MELODY_CHORDAL_PARAM, 0.f, 1.f, 1.f, "Chordal Notes"); configParam(BUTTON_ENABLE_MELODY_SCALER_PARAM, 0.f, 1.f, 0.f, "Scaler Notes"); configParam(CONTROL_HARMONY_VOLUME_PARAM, 0.f, 10.f, 8.0f, "Volume (0-10)"); configParam(CONTROL_HARMONY_STEPS_PARAM, 1.f, 16.f, 16.f, "Steps"); configParam(CONTROL_HARMONY_TARGETOCTAVE_PARAM, 1.f, 6.f, 3.f, "Target Octave"); configParam(CONTROL_HARMONY_ALPHA_PARAM, 0.f, 1.f, .9f, "Variability"); configParam(CONTROL_HARMONY_RANGE_PARAM, 0.f, 3.f, 1.f, "Octave Range"); configParam(CONTROL_HARMONY_DIVISOR_PARAM, 0.f, 3.f, 0.f, "Notes Length"); configParam(BUTTON_ENABLE_HARMONY_ALL7THS_PARAM, 0.f, 1.f, 0.f, "7ths"); configParam(BUTTON_ENABLE_HARMONY_V7THS_PARAM, 0.f, 1.f, 0.f, "V 7ths"); configParam(BUTTON_ENABLE_HARMONY_STACCATO_PARAM, 0.f, 1.f, 0.f, "Staccato"); configParam(CONTROL_HARMONYPRESETS_PARAM, 1.0f, (float)MAX_AVAILABLE_HARMONY_PRESETS, 1.0f, "Progression Preset"); configParam(BUTTON_ENABLE_ARP_PARAM, 0.f, 1.f, 0.f, "Enable"); configParam(BUTTON_ENABLE_ARP_CHORDAL_PARAM, 0.f, 1.f, 1.f, "Chordal Notes"); configParam(BUTTON_ENABLE_ARP_SCALER_PARAM, 0.f, 1.f, 0.f, "Scaler Notes"); configParam(CONTROL_ARP_COUNT_PARAM, 0.f, 31.f, 0.f, "Arp Notes Played"); configParam(CONTROL_ARP_INCREMENT_PARAM, 2.f, 5.f, 4.f, "Arp Notes Length"); configParam(CONTROL_ARP_DECAY_PARAM, 0.f, 1.f, 0.f, "Volume Decay"); configParam(CONTROL_ARP_PATTERN_PARAM, -3.f, 3.f, 1.f, "Pattern Preset"); configParam(BUTTON_ENABLE_BASS_PARAM, 0.f, 1.f, 0.f, "Enable"); configParam(CONTROL_BASS_VOLUME_PARAM, 0.f, 10.f, 8.0f, "Volume"); configParam(CONTROL_BASS_DIVISOR_PARAM, 0.f, 3.f, 0.f, "Notes Length"); configParam(CONTROL_BASS_TARGETOCTAVE_PARAM, 0.f, 3.f, 2.f, "Target Octave"); configParam(BUTTON_BASS_ACCENT_PARAM, 0.f, 1.f, 0.f, "Accent"); configParam(BUTTON_BASS_SYNCOPATE_PARAM, 0.f, 1.f, 0.f, "Syncopate"); configParam(BUTTON_BASS_SHUFFLE_PARAM, 0.f, 1.f, 0.f, "Shuffle"); configParam(BUTTON_ENABLE_BASS_STACCATO_PARAM, 0.f, 1.f, 1.f, "Staccato"); configParam(BUTTON_BASS_OCTAVES_PARAM, 0.f, 1.f, 1.f, "Play as Octaves"); configParam(CONTROL_HARMONY_FBM_OCTAVES_PARAM, 1.f, 6.f, 3.f, ""); configParam(CONTROL_MELODY_FBM_OCTAVES_PARAM, 1.f, 6.f, 3.f, ""); configParam(CONTROL_ARP_FBM_OCTAVES_PARAM, 1.f, 6.f, 3.f, ""); configParam(CONTROL_HARMONY_FBM_PERIOD_PARAM, 1.f, 100.f, 60.f, ""); configParam(CONTROL_MELODY_FBM_PERIOD_PARAM, 1.f, 100.f, 10.f, ""); configParam(CONTROL_ARP_FBM_PERIOD_PARAM, 1.f, 100.f, 1.f, ""); configParam(BUTTON_HARMONY_SETSTEP_1_PARAM, 0.f, 1.f, 0.f, "Step 1"); configParam(BUTTON_HARMONY_SETSTEP_2_PARAM, 0.f, 1.f, 0.f, "Step 2"); configParam(BUTTON_HARMONY_SETSTEP_3_PARAM, 0.f, 1.f, 0.f, "Step 3"); configParam(BUTTON_HARMONY_SETSTEP_4_PARAM, 0.f, 1.f, 0.f, "Step 4"); configParam(BUTTON_HARMONY_SETSTEP_5_PARAM, 0.f, 1.f, 0.f, "Step 5"); configParam(BUTTON_HARMONY_SETSTEP_6_PARAM, 0.f, 1.f, 0.f, "Step 6"); configParam(BUTTON_HARMONY_SETSTEP_7_PARAM, 0.f, 1.f, 0.f, "Step 7"); configParam(BUTTON_HARMONY_SETSTEP_8_PARAM, 0.f, 1.f, 0.f, "Step 8"); configParam(BUTTON_HARMONY_SETSTEP_9_PARAM, 0.f, 1.f, 0.f, "Step 9"); configParam(BUTTON_HARMONY_SETSTEP_10_PARAM, 0.f, 1.f, 0.f, "Step 10"); configParam(BUTTON_HARMONY_SETSTEP_11_PARAM, 0.f, 1.f, 0.f, "Step 11"); configParam(BUTTON_HARMONY_SETSTEP_12_PARAM, 0.f, 1.f, 0.f, "Step 12"); configParam(BUTTON_HARMONY_SETSTEP_13_PARAM, 0.f, 1.f, 0.f, "Step 13"); configParam(BUTTON_HARMONY_SETSTEP_14_PARAM, 0.f, 1.f, 0.f, "Step 14"); configParam(BUTTON_HARMONY_SETSTEP_15_PARAM, 0.f, 1.f, 0.f, "Step 15"); configParam(BUTTON_HARMONY_SETSTEP_16_PARAM, 0.f, 1.f, 0.f, "Step 16"); configParam(BUTTON_CIRCLESTEP_C_PARAM, 0.f, 1.f, 1.f, "C"); configParam(BUTTON_CIRCLESTEP_G_PARAM, 0.f, 1.f, 0.f, "G"); configParam(BUTTON_CIRCLESTEP_D_PARAM, 0.f, 1.f, 0.f, "D"); configParam(BUTTON_CIRCLESTEP_A_PARAM, 0.f, 1.f, 0.f, "A"); configParam(BUTTON_CIRCLESTEP_E_PARAM, 0.f, 1.f, 0.f, "E"); configParam(BUTTON_CIRCLESTEP_B_PARAM, 0.f, 1.f, 0.f, "B"); configParam(BUTTON_CIRCLESTEP_GBFS_PARAM, 0.f, 1.f, 0.f, "Gb/F#"); configParam(BUTTON_CIRCLESTEP_DB_PARAM, 0.f, 1.f, 0.f, "Db"); configParam(BUTTON_CIRCLESTEP_AB_PARAM, 0.f, 1.f, 0.f, "Ab"); configParam(BUTTON_CIRCLESTEP_EB_PARAM, 0.f, 1.f, 0.f, "Eb"); configParam(BUTTON_CIRCLESTEP_BB_PARAM, 0.f, 1.f, 0.f, "Bb"); configParam(BUTTON_CIRCLESTEP_F_PARAM, 0.f, 1.f, 0.f, "F"); configParam(BUTTON_PROG_STEP_PARAM, 0.f, 1.f, 0.f, "Step Harmony"); } // end Meander() }; // end of struct Meander struct RootKeySelectLineDisplay : LightWidget { int frame = 0; std::shared_ptr<Font> font; RootKeySelectLineDisplay() { font = APP->window->loadFont(asset::plugin(pluginInstance, "res/Ubuntu Condensed 400.ttf")); } void draw(const DrawArgs &ctx) override { Vec pos = Vec(18,-11); // this is the offset if any in the passed box position, particularly x indention -7.3=box height // Background NVGcolor backgroundColor = nvgRGB(0x0, 0x0, 0x0); NVGcolor borderColor = nvgRGB(0x10, 0x10, 0x10); nvgBeginPath(ctx.vg); nvgRoundedRect(ctx.vg, 0.0, -22.0, box.size.x, box.size.y, 4.0); nvgFillColor(ctx.vg, backgroundColor); nvgFill(ctx.vg); nvgStrokeWidth(ctx.vg, 1.0); nvgStrokeColor(ctx.vg, borderColor); nvgStroke(ctx.vg); if (globalsInitialized) // global fully initialized if Module!=NULL { nvgFontSize(ctx.vg,18 ); nvgFontFaceId(ctx.vg, font->handle); nvgTextLetterSpacing(ctx.vg, -1); nvgTextAlign(ctx.vg,NVG_ALIGN_CENTER|NVG_ALIGN_MIDDLE); nvgFillColor(ctx.vg, nvgRGBA(0xff, 0xff, 0x2c, 0xFF)); char text[128]; snprintf(text, sizeof(text), "%s", root_key_names[root_key]); nvgText(ctx.vg, pos.x, pos.y, text, NULL); } } }; struct ScaleSelectLineDisplay : LightWidget { int frame = 0; std::shared_ptr<Font> font; ScaleSelectLineDisplay() { font = APP->window->loadFont(asset::plugin(pluginInstance, "res/Ubuntu Condensed 400.ttf")); } void draw(const DrawArgs &ctx) override { Vec pos = Vec(60,12); // Background NVGcolor backgroundColor = nvgRGB(0x0, 0x0, 0x0); NVGcolor borderColor = nvgRGB(0x10, 0x10, 0x10); nvgBeginPath(ctx.vg); nvgRoundedRect(ctx.vg, 0.0, 0, box.size.x, box.size.y, 4.0); nvgFillColor(ctx.vg, backgroundColor); nvgFill(ctx.vg); nvgStrokeWidth(ctx.vg, 1.0); nvgStrokeColor(ctx.vg, borderColor); nvgStroke(ctx.vg); if (globalsInitialized) // global fully initialized if Module!=NULL { nvgFontSize(ctx.vg, 16); nvgFontFaceId(ctx.vg, font->handle); nvgTextLetterSpacing(ctx.vg, -1); nvgTextAlign(ctx.vg,NVG_ALIGN_CENTER|NVG_ALIGN_MIDDLE); nvgFillColor(ctx.vg, nvgRGBA(0xff, 0xff, 0x2c, 0xFF)); char text[128]; snprintf(text, sizeof(text), "%s", mode_names[mode]); nvgText(ctx.vg, pos.x, pos.y, text, NULL); // add on the scale notes display out of this box nvgFillColor(ctx.vg, nvgRGBA(0x00, 0x0, 0x0, 0xFF)); strcpy(text,""); for (int i=0;i<mode_step_intervals[mode][0];++i) { strcat(text,note_desig[notes[i]%MAX_NOTES]); strcat(text," "); } nvgText(ctx.vg, pos.x, pos.y+24, text, NULL); } } }; //////////////////////////////////// struct BpmDisplayWidget : LightWidget { float *val = NULL; std::shared_ptr<Font> font; BpmDisplayWidget() { font = APP->window->loadFont(asset::plugin(pluginInstance, "res/Segment7Standard.ttf")); }; void draw(const DrawArgs &args) override { // draw the display background even if there is no module // Background NVGcolor backgroundColor = nvgRGB(0x20, 0x10, 0x10); NVGcolor borderColor = nvgRGB(0x10, 0x10, 0x10); nvgBeginPath(args.vg); nvgRoundedRect(args.vg, 0.0, 0.0, box.size.x, box.size.y, 4.0); nvgFillColor(args.vg, backgroundColor); nvgFill(args.vg); nvgStrokeWidth(args.vg, 1.0); nvgStrokeColor(args.vg, borderColor); nvgStroke(args.vg); // if val is null (Module null) if (!val) { return; } nvgFontSize(args.vg, 36); nvgFontFaceId(args.vg, font->handle); nvgTextLetterSpacing(args.vg, 2.5); std::string to_display = std::to_string((int)(*val)); while(to_display.length()<3) to_display = ' ' + to_display; Vec textPos = Vec(6.0f, 34.0f); NVGcolor textColor = nvgRGB(0xdf, 0xd2, 0x2c); nvgFillColor(args.vg, nvgTransRGBA(textColor, 16)); nvgText(args.vg, textPos.x, textPos.y, "~~~", NULL); textColor = nvgRGB(0xda, 0xe9, 0x29); nvgFillColor(args.vg, nvgTransRGBA(textColor, 16)); nvgText(args.vg, textPos.x, textPos.y, "\\\\\\", NULL); textColor = nvgRGB(0xff, 0xff, 0x2c); nvgFillColor(args.vg, textColor); nvgText(args.vg, textPos.x, textPos.y, to_display.c_str(), NULL); } }; //////////////////////////////////// struct SigDisplayWidget : LightWidget { int *value = NULL; std::shared_ptr<Font> font; SigDisplayWidget() { font = APP->window->loadFont(asset::plugin(pluginInstance, "res/Segment7Standard.ttf")); }; void draw(const DrawArgs &args) override { // Display Background is now drawn on the svg panel, even if Module is null (value=null) NVGcolor backgroundColor = nvgRGB(0x20, 0x10, 0x10); NVGcolor borderColor = nvgRGB(0x10, 0x10, 0x10); nvgBeginPath(args.vg); nvgRoundedRect(args.vg, 0.0, 0.0, box.size.x, box.size.y, 4.0); nvgFillColor(args.vg, backgroundColor); nvgFill(args.vg); nvgStrokeWidth(args.vg, 1.0); nvgStrokeColor(args.vg, borderColor); nvgStroke(args.vg); if (!value) { return; } // text nvgFontSize(args.vg, 20); nvgFontFaceId(args.vg, font->handle); nvgTextLetterSpacing(args.vg, 2.2); std::stringstream to_display; to_display << std::setw(2) << *value; Vec textPos = Vec(-2.0f, 17.0f); // this is a relative offset within the box NVGcolor textColor = nvgRGB(0xdf, 0xd2, 0x2c); nvgFillColor(args.vg, nvgTransRGBA(textColor, 16)); nvgText(args.vg, textPos.x, textPos.y, "~~", NULL); textColor = nvgRGB(0xda, 0xe9, 0x29); nvgFillColor(args.vg, nvgTransRGBA(textColor, 16)); nvgText(args.vg, textPos.x, textPos.y, "\\\\", NULL); textColor = nvgRGBA(0xff, 0xff, 0x2c, 0xff); nvgFillColor(args.vg, textColor); nvgText(args.vg, textPos.x, textPos.y, to_display.str().c_str(), NULL); } }; ////////////////////////////////// struct RSLabelCentered : LedDisplay { std::shared_ptr<Font> font; int fontSize; std::string text; NVGcolor color; // RSLabelCentered(int x, int y, const char* str = "", int fontSize = 10, const NVGcolor& colour = COLOR_RS_GREY) { RSLabelCentered(int x, int y, const char* str = "", int fontSize = 10, const NVGcolor& colour = nvgRGB(0x00, 0x00, 0x00)) { // font = APP->window->loadFont(asset::plugin(pluginInstance, "res/fonts/Ubuntu Condensed 400.ttf")); // can't load if this is the textfont font = APP->window->loadFont(asset::plugin(pluginInstance, "res/DejaVuSansMono.ttf")); // load a not textfont this->fontSize = fontSize; box.pos = Vec(x, y); text = str; color = colour; } void draw(const DrawArgs &args) override { if(font->handle >= 0) { bndSetFont(font->handle); nvgFontSize(args.vg, fontSize); nvgFontFaceId(args.vg, font->handle); nvgTextLetterSpacing(args.vg, 0); nvgTextAlign(args.vg, NVG_ALIGN_CENTER); nvgBeginPath(args.vg); nvgFillColor(args.vg, color); nvgText(args.vg, 0, 0, text.c_str(), NULL); nvgStroke(args.vg); bndSetFont(APP->window->uiFont->handle); } } }; /////////////////////////////// struct MeanderWidget : ModuleWidget { rack::math::Rect ParameterRect[MAX_PARAMS]; // warning, don't exceed the dimension rack::math::Rect InportRect[MAX_INPORTS]; // warning, don't exceed the dimension rack::math::Rect OutportRect[MAX_OUTPORTS]; // warning, don't exceed the dimension ParamWidget* paramWidgets[Meander::NUM_PARAMS]={0}; // keep track of all ParamWidgets as they are created so they can be moved around later by the enum parmam ID LightWidget* lightWidgets[Meander::NUM_LIGHTS]={0}; // keep track of all LightWidgets as they are created so they can be moved around later by the enum parmam ID PortWidget* outPortWidgets[Meander::NUM_OUTPUTS]={0}; // keep track of all output TPortWidgets as they are created so they can be moved around later by the enum parmam ID PortWidget* inPortWidgets[Meander::NUM_INPUTS]={0}; // keep track of all output TPortWidgets as they are created so they can be moved around later by the enum parmam ID struct CircleOf5thsDisplay : TransparentWidget { rack::math::Rect* ParameterRectLocal; // warning, don't exceed the dimension rack::math::Rect* InportRectLocal; // warning, don't exceed the dimension rack::math::Rect* OutportRectLocal; // warning, don't exceed the dimension int frame = 0; std::shared_ptr<Font> textfont; std::shared_ptr<Font> musicfont; CircleOf5thsDisplay() { // textfont = APP->window->loadFont(asset::plugin(pluginInstance, "res/DejaVuSansMono.ttf")); textfont = APP->window->loadFont(asset::plugin(pluginInstance, "res/Ubuntu Condensed 400.ttf")); musicfont = APP->window->loadFont(asset::plugin(pluginInstance, "res/Musisync-KVLZ.ttf")); } void DrawCircle5ths(const DrawArgs &args, int root_key) { if (doDebug) DEBUG("DrawCircle5ths()"); for (int i=0; i<MAX_CIRCLE_STATIONS; ++i) { // draw root_key annulus sector int relativeCirclePosition = ((i - circle_root_key + mode)+12) % MAX_CIRCLE_STATIONS; if (doDebug) DEBUG("\nrelativeCirclePosition-1=%d", relativeCirclePosition); nvgBeginPath(args.vg); float opacity = 128; nvgStrokeColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xff)); nvgStrokeWidth(args.vg, 2); if((relativeCirclePosition == 0)||(relativeCirclePosition == 1)||(relativeCirclePosition == 2)) nvgFillColor(args.vg, nvgRGBA(0xff, 0x20, 0x20, (int)opacity)); // reddish else if((relativeCirclePosition == 3)||(relativeCirclePosition == 4)||(relativeCirclePosition == 5)) nvgFillColor(args.vg, nvgRGBA(0x20, 0x20, 0xff, (int)opacity)); //bluish else if(relativeCirclePosition == 6) nvgFillColor(args.vg, nvgRGBA(0x20, 0xff, 0x20, (int)opacity)); // greenish else nvgFillColor(args.vg, nvgRGBA(0x20, 0x20, 0x20, (int)opacity)); // grayish nvgArc(args.vg,theCircleOf5ths.CircleCenter.x,theCircleOf5ths.CircleCenter.y,theCircleOf5ths.MiddleCircleRadius,theCircleOf5ths.Circle5ths[i].startDegree,theCircleOf5ths.Circle5ths[i].endDegree,NVG_CW); nvgLineTo(args.vg,theCircleOf5ths.Circle5ths[i].pt3.x,theCircleOf5ths.Circle5ths[i].pt3.y); nvgArc(args.vg,theCircleOf5ths.CircleCenter.x,theCircleOf5ths.CircleCenter.y,theCircleOf5ths.InnerCircleRadius,theCircleOf5ths.Circle5ths[i].endDegree,theCircleOf5ths.Circle5ths[i].startDegree,NVG_CCW); nvgLineTo(args.vg,theCircleOf5ths.Circle5ths[i].pt2.x,theCircleOf5ths.Circle5ths[i].pt2.y); nvgFill(args.vg); nvgStroke(args.vg); nvgClosePath(args.vg); // draw text nvgFontSize(args.vg, 12); nvgFontFaceId(args.vg, textfont->handle); nvgTextLetterSpacing(args.vg, -1); nvgFillColor(args.vg, nvgRGBA(0x00, 0x00, 0x00, 0xff)); char text[32]; snprintf(text, sizeof(text), "%s", CircleNoteNames[i]); if (doDebug) DEBUG("radialDirection= %.3f %.3f", theCircleOf5ths.Circle5ths[i].radialDirection.x, theCircleOf5ths.Circle5ths[i].radialDirection.y); Vec TextPosition=theCircleOf5ths.CircleCenter.plus(theCircleOf5ths.Circle5ths[i].radialDirection.mult(theCircleOf5ths.MiddleCircleRadius*.93f)); nvgTextAlign(args.vg,NVG_ALIGN_CENTER|NVG_ALIGN_MIDDLE); nvgText(args.vg, TextPosition.x, TextPosition.y, text, NULL); } }; void DrawDegreesSemicircle(const DrawArgs &args, int root_key) { if (doDebug) DEBUG("DrawDegreesSemicircle()"); int chord_type=0; for (int i=0; i<MAX_HARMONIC_DEGREES; ++i) { // draw degree annulus sector nvgBeginPath(args.vg); float opacity = 128; nvgStrokeColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xff)); nvgStrokeWidth(args.vg, 2); chord_type=theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].chordType; if (false) { if (chord_type==0) // major nvgFillColor(args.vg, nvgRGBA(0xff, 0x20, 0x20, (int)opacity)); // reddish else if (chord_type==1) //minor nvgFillColor(args.vg, nvgRGBA(0x20, 0x20, 0xff, (int)opacity)); //bluish else if (chord_type==6) // diminished nvgFillColor(args.vg, nvgRGBA(0x20, 0xff, 0x20, (int)opacity)); // greenish } else nvgFillColor(args.vg, nvgRGBA(0xf9, 0xf9, 0x20, (int)opacity)); // yellowish nvgArc(args.vg,theCircleOf5ths.CircleCenter.x,theCircleOf5ths.CircleCenter.y,theCircleOf5ths.OuterCircleRadius,theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].startDegree,theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].endDegree,NVG_CW); nvgLineTo(args.vg,theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].pt3.x,theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].pt3.y); nvgArc(args.vg,theCircleOf5ths.CircleCenter.x,theCircleOf5ths.CircleCenter.y,theCircleOf5ths.MiddleCircleRadius,theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].endDegree,theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].startDegree,NVG_CCW); nvgLineTo(args.vg,theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].pt2.x,theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].pt2.y); nvgFill(args.vg); nvgStroke(args.vg); nvgClosePath(args.vg); // draw text nvgFontSize(args.vg, 10); nvgFontFaceId(args.vg, textfont->handle); nvgTextLetterSpacing(args.vg, -1); // as close as possible nvgFillColor(args.vg, nvgRGBA(0x00, 0x00, 0x00, 0xff)); char text[32]; if (chord_type==0) // major snprintf(text, sizeof(text), "%s", circle_of_fifths_degrees_UC[(i - theCircleOf5ths.theDegreeSemiCircle.RootKeyCircle5thsPosition+7)%7]); else if ((chord_type==1)||(chord_type==6)) // minor or diminished snprintf(text, sizeof(text), "%s", circle_of_fifths_degrees_LC[(i - theCircleOf5ths.theDegreeSemiCircle.RootKeyCircle5thsPosition+7)%7]); if (doDebug) DEBUG("radialDirection= %.3f %.3f", theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].radialDirection.x, theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].radialDirection.y); Vec TextPosition=theCircleOf5ths.CircleCenter.plus(theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].radialDirection.mult(theCircleOf5ths.OuterCircleRadius*.92f)); nvgTextAlign(args.vg,NVG_ALIGN_CENTER|NVG_ALIGN_MIDDLE); nvgText(args.vg, TextPosition.x, TextPosition.y, text, NULL); if (i==6) // draw diminished { Vec TextPositionBdim=Vec(TextPosition.x+9, TextPosition.y-4); sprintf(text, "o"); if (doDebug) DEBUG(text); nvgTextAlign(args.vg,NVG_ALIGN_CENTER|NVG_ALIGN_MIDDLE); nvgFontSize(args.vg, 8); nvgText(args.vg, TextPositionBdim.x, TextPositionBdim.y, text, NULL); } } }; Vec convertSVGtoNVG(float x, float y, float w, float h) { Vec nvgPos=mm2px(Vec(x+(w/2.0), (128.93-y-(h/2.0)))); // this writes in the center return nvgPos; } void drawHarmonyControlParamLine(const DrawArgs &args, Vec paramControlPos, const char* label, float value, int valueDecimalPoints) { Vec displayRectPos= paramControlPos.plus(Vec(128, 0)); nvgBeginPath(args.vg); if (valueDecimalPoints>=0) nvgRoundedRect(args.vg, displayRectPos.x,displayRectPos.y, 45.f, 20.f, 4.f); char text[128]; snprintf(text, sizeof(text), "%s", label); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xff)); nvgFontSize(args.vg, 14); nvgTextAlign(args.vg,NVG_ALIGN_LEFT|NVG_ALIGN_MIDDLE); nvgText(args.vg, paramControlPos.x+20, paramControlPos.y+10, text, NULL); nvgFillColor(args.vg, nvgRGBA( 0x2f, 0x27, 0x0a, 0xff)); nvgFill(args.vg); nvgStroke(args.vg); nvgFillColor(args.vg, nvgRGBA(0xFF, 0xFF, 0x2C, 0xff)); nvgFontSize(args.vg, 17); if (valueDecimalPoints>=0) { nvgTextAlign(args.vg,NVG_ALIGN_CENTER|NVG_ALIGN_MIDDLE); if (valueDecimalPoints==0) snprintf(text, sizeof(text), "%d", (int)value); else if (valueDecimalPoints==1) snprintf(text, sizeof(text), "%.1lf", value); else if (valueDecimalPoints==2) snprintf(text, sizeof(text), "%.2lf", value); nvgText(args.vg, displayRectPos.x+25, displayRectPos.y+10, text, NULL); } } void drawMelodyControlParamLine(const DrawArgs &args, Vec paramControlPos, const char* label, float value, int valueDecimalPoints) { Vec displayRectPos= paramControlPos.plus(Vec(115, 0)); nvgBeginPath(args.vg); if (valueDecimalPoints>=0) nvgRoundedRect(args.vg, displayRectPos.x,displayRectPos.y, 45.f, 20.f, 4.f); char text[128]; snprintf(text, sizeof(text), "%s", label); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xff)); nvgFontSize(args.vg, 14); nvgTextAlign(args.vg,NVG_ALIGN_LEFT|NVG_ALIGN_MIDDLE); nvgText(args.vg, paramControlPos.x+20, paramControlPos.y+10, text, NULL); nvgFillColor(args.vg, nvgRGBA( 0x2f, 0x27, 0x0a, 0xff)); nvgFill(args.vg); nvgStroke(args.vg); nvgFillColor(args.vg, nvgRGBA(0xFF, 0xFF, 0x2C, 0xff)); nvgFontSize(args.vg, 17); if (valueDecimalPoints>=0) { nvgTextAlign(args.vg,NVG_ALIGN_CENTER|NVG_ALIGN_MIDDLE); if (valueDecimalPoints==0) snprintf(text, sizeof(text), "%d", (int)value); else if (valueDecimalPoints==1) snprintf(text, sizeof(text), "%.1lf", value); else if (valueDecimalPoints==2) snprintf(text, sizeof(text), "%.2lf", value); nvgText(args.vg, displayRectPos.x+25, displayRectPos.y+10, text, NULL); } } void drawBassControlParamLine(const DrawArgs &args, Vec paramControlPos, const char* label, float value, int valueDecimalPoints) { Vec displayRectPos= paramControlPos.plus(Vec(85, 0)); nvgBeginPath(args.vg); if (valueDecimalPoints>=0) nvgRoundedRect(args.vg, displayRectPos.x,displayRectPos.y, 45.f, 20.f, 4.f); char text[128]; snprintf(text, sizeof(text), "%s", label); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xff)); nvgFontSize(args.vg, 14); nvgTextAlign(args.vg,NVG_ALIGN_LEFT|NVG_ALIGN_MIDDLE); nvgText(args.vg, paramControlPos.x+20, paramControlPos.y+10, text, NULL); nvgFillColor(args.vg, nvgRGBA( 0x2f, 0x27, 0x0a, 0xff)); nvgFill(args.vg); nvgStroke(args.vg); nvgFillColor(args.vg, nvgRGBA(0xFF, 0xFF, 0x2C, 0xff)); nvgFontSize(args.vg, 17); if (valueDecimalPoints>=0) { nvgTextAlign(args.vg,NVG_ALIGN_CENTER|NVG_ALIGN_MIDDLE); if (valueDecimalPoints==0) snprintf(text, sizeof(text), "%d", (int)value); else if (valueDecimalPoints==1) snprintf(text, sizeof(text), "%.1lf", value); else if (valueDecimalPoints==2) snprintf(text, sizeof(text), "%.2lf", value); nvgText(args.vg, displayRectPos.x+25, displayRectPos.y+10, text, NULL); } } void drawfBmControlParamLine(const DrawArgs &args, Vec paramControlPos, const char* label, float value, int valueDecimalPoints) { Vec displayRectPos= paramControlPos.plus(Vec(105, 0)); nvgBeginPath(args.vg); if (valueDecimalPoints>=0) nvgRoundedRect(args.vg, displayRectPos.x,displayRectPos.y, 45.f, 20.f, 4.f); char text[128]; snprintf(text, sizeof(text), "%s", label); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xff)); nvgFontSize(args.vg, 14); nvgTextAlign(args.vg,NVG_ALIGN_LEFT|NVG_ALIGN_MIDDLE); nvgText(args.vg, paramControlPos.x+20, paramControlPos.y+10, text, NULL); nvgFillColor(args.vg, nvgRGBA( 0x2f, 0x27, 0x0a, 0xff)); nvgFill(args.vg); nvgStroke(args.vg); nvgFillColor(args.vg, nvgRGBA(0xFF, 0xFF, 0x2C, 0xff)); nvgFontSize(args.vg, 17); if (valueDecimalPoints>=0) { nvgTextAlign(args.vg,NVG_ALIGN_CENTER|NVG_ALIGN_MIDDLE); if (valueDecimalPoints==0) snprintf(text, sizeof(text), "%d", (int)value); else if (valueDecimalPoints==1) snprintf(text, sizeof(text), "%.1lf", value); else if (valueDecimalPoints==2) snprintf(text, sizeof(text), "%.2lf", value); nvgText(args.vg, displayRectPos.x+25, displayRectPos.y+10, text, NULL); } } void drawLabelAbove(const DrawArgs &args, Rect rect, const char* label, float fontSize) { nvgBeginPath(args.vg); nvgFillColor(args.vg, nvgRGBA( 0x0, 0x0, 0x0, 0xff)); nvgFontSize(args.vg, fontSize); nvgFontFaceId(args.vg, textfont->handle); nvgTextLetterSpacing(args.vg, -1); nvgTextAlign(args.vg,NVG_ALIGN_CENTER|NVG_ALIGN_MIDDLE); // nvgText(args.vg, rect.pos.x+rect.size.x/2.,rect.pos.y-4, label, NULL); nvgText(args.vg, rect.pos.x+rect.size.x/2.,rect.pos.y-8, label, NULL); } void drawLabelRight(const DrawArgs &args, Rect rect, const char* label) { nvgBeginPath(args.vg); nvgFillColor(args.vg, nvgRGBA( 0x0, 0x0, 0x0, 0xff)); nvgFontSize(args.vg, 14); nvgFontFaceId(args.vg, textfont->handle); nvgTextLetterSpacing(args.vg, -1); nvgTextAlign(args.vg,NVG_ALIGN_LEFT|NVG_ALIGN_MIDDLE); nvgText(args.vg, rect.pos.x+rect.size.x+2, rect.pos.y+rect.size.y/2., label, NULL); } void drawLabelLeft(const DrawArgs &args, Rect rect, const char* label, float xoffset) { nvgBeginPath(args.vg); nvgFillColor(args.vg, nvgRGBA( 0x0, 0x0, 0x0, 0xff)); nvgFontSize(args.vg, 14); nvgFontFaceId(args.vg, textfont->handle); nvgTextLetterSpacing(args.vg, -1); nvgTextAlign(args.vg,NVG_ALIGN_LEFT|NVG_ALIGN_MIDDLE); nvgText(args.vg, rect.pos.x-rect.size.x-2+xoffset, rect.pos.y+rect.size.y/2., label, NULL); } void drawLabelOffset(const DrawArgs &args, Rect rect, const char* label, float xoffset, float yoffset) { nvgBeginPath(args.vg); nvgFillColor(args.vg, nvgRGBA( 0x0, 0x0, 0x0, 0xff)); nvgFontSize(args.vg, 14); nvgFontFaceId(args.vg, textfont->handle); nvgTextLetterSpacing(args.vg, -1); nvgTextAlign(args.vg,NVG_ALIGN_LEFT|NVG_ALIGN_MIDDLE); nvgText(args.vg, rect.pos.x+xoffset, rect.pos.y+yoffset, label, NULL); } void drawOutport(const DrawArgs &args, Vec OutportPos, const char* label, float value, int valueDecimalPoints) // test draw a rounded corner rect for jack border testing { Vec displayRectPos= OutportPos.plus(Vec(-3, -15)); nvgBeginPath(args.vg); nvgRoundedRect(args.vg, displayRectPos.x,displayRectPos.y, 30.f, 43.f, 3.f); nvgFillColor(args.vg, nvgRGBA( 0x0, 0x0, 0x0, 0xff)); nvgFill(args.vg); nvgFontSize(args.vg, 10); nvgFontFaceId(args.vg, textfont->handle); nvgTextLetterSpacing(args.vg, -1); nvgFillColor(args.vg, nvgRGBA(0xff, 0xff, 0xff, 0xFF)); nvgTextAlign(args.vg,NVG_ALIGN_CENTER|NVG_ALIGN_MIDDLE); nvgText(args.vg, OutportPos.x+12, OutportPos.y-8, label, NULL); } void drawGrid(const DrawArgs &args) { float panelWidth=mm2px(406); float panelHeight=mm2px(129); if (doDebug) DEBUG("panel size (WxH) in px=%.2f x %.2f", panelWidth, panelHeight); // panel size (WxH) in px=1198.82 x 380.91 int gridWidthDivisions=(int)(panelWidth/10.0); // 112 int gridHeightDivisions=(int)(panelHeight/10.0); // 38 float gridWidth=10.0; float gridHeight=10.0; nvgStrokeColor(args.vg, nvgRGB(0, 0, 0)); nvgStrokeWidth(args.vg, 1.0); for (int x=0; x<gridWidthDivisions; ++x) { if (x%10==0) { nvgStrokeWidth(args.vg, 2.0); nvgStrokeColor(args.vg, nvgRGBA(0, 0, 0xff, 0x80)); } else { nvgStrokeWidth(args.vg, 1.0); nvgStrokeColor(args.vg, nvgRGBA(0xff, 0, 0, 0x80)); } nvgBeginPath(args.vg); nvgMoveTo(args.vg, x*gridWidth, 0); nvgLineTo(args.vg, x*gridWidth, gridHeightDivisions*gridHeight); nvgStroke(args.vg); } for (int y=0; y<gridHeightDivisions; ++y) { if (y%10==0) { nvgStrokeWidth(args.vg, 2.0); nvgStrokeColor(args.vg, nvgRGBA(0, 0, 0xff, 0x80)); } else { nvgStrokeWidth(args.vg, 1.0); nvgStrokeColor(args.vg, nvgRGBA(0xff, 0, 0, 0x80)); } nvgBeginPath(args.vg); nvgMoveTo(args.vg, 0, y*gridHeight); nvgLineTo(args.vg, gridWidthDivisions*gridWidth, y*gridHeight); nvgStroke(args.vg); } } void updatePanel(const DrawArgs &args) { if (true) // Harmony position a paramwidget can't access paramWidgets here { nvgBeginPath(args.vg); nvgRoundedRect(args.vg, 484.f,25.f, 196.f, 353.f, 4.f); nvgFillColor(args.vg, nvgRGBA( 0xe6, 0xe6, 0xe6, 0xff)); nvgFill(args.vg); nvgStrokeColor(args.vg,nvgRGBA( 0x80, 0x80 , 0x80, 0x80)); nvgStrokeWidth(args.vg, 2.5); nvgStroke(args.vg); Vec pos; Vec displayRectPos; Vec paramControlPos; char text[128]; char labeltext[128]; nvgFontSize(args.vg, 17); nvgFontFaceId(args.vg, textfont->handle); nvgTextLetterSpacing(args.vg, -1); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xff)); nvgStrokeColor(args.vg,nvgRGBA( 0x80, 0x80 , 0x80, 0x80)); nvgStrokeWidth(args.vg, 2.0); // draw set steps text for(int i = 0; i<MAX_STEPS;++i) { if (i==0) { sprintf(labeltext, "Set Step"); drawLabelAbove(args, ParameterRectLocal[Meander::BUTTON_HARMONY_SETSTEP_1_PARAM+i], labeltext, 15.); } sprintf(labeltext, "%d", i+1); drawLabelLeft(args,ParameterRectLocal[Meander::BUTTON_HARMONY_SETSTEP_1_PARAM+i], labeltext, 0.); } //*************** // update harmony panel begin snprintf(labeltext, sizeof(labeltext), "%s", "Harmony Enable"); drawHarmonyControlParamLine(args,ParameterRectLocal[Meander::BUTTON_ENABLE_HARMONY_PARAM].pos, labeltext, 0, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Volume (0-10.0)"); drawHarmonyControlParamLine(args,ParameterRectLocal[Meander::CONTROL_HARMONY_VOLUME_PARAM].pos, labeltext, theMeanderState.theHarmonyParms.volume, 1); snprintf(labeltext, sizeof(labeltext), "Steps (%d-%d)", theActiveHarmonyType.min_steps, theActiveHarmonyType.max_steps); drawHarmonyControlParamLine(args,ParameterRectLocal[Meander::CONTROL_HARMONY_STEPS_PARAM].pos, labeltext, (float)theActiveHarmonyType.num_harmony_steps, 0); snprintf(labeltext, sizeof(labeltext), "%s", "Target Oct.(1-6)"); drawHarmonyControlParamLine(args,ParameterRectLocal[Meander::CONTROL_HARMONY_TARGETOCTAVE_PARAM].pos, labeltext, theMeanderState.theHarmonyParms.target_octave, 0); snprintf(labeltext, sizeof(labeltext), "%s", "Variability (0-1)"); drawHarmonyControlParamLine(args,ParameterRectLocal[Meander::CONTROL_HARMONY_ALPHA_PARAM].pos, labeltext, theMeanderState.theHarmonyParms.alpha, 2); snprintf(labeltext, sizeof(labeltext), "%s", "+-Octave Range (0-3)"); drawHarmonyControlParamLine(args,ParameterRectLocal[Meander::CONTROL_HARMONY_RANGE_PARAM].pos, labeltext, theMeanderState.theHarmonyParms.note_octave_range, 2); snprintf(labeltext, sizeof(labeltext), "%s", "Notes on 1/"); drawHarmonyControlParamLine(args,ParameterRectLocal[Meander::CONTROL_HARMONY_DIVISOR_PARAM].pos, labeltext, theMeanderState.theHarmonyParms.note_length_divisor, 0); snprintf(labeltext, sizeof(labeltext), "%s", "~Nice 7ths"); drawHarmonyControlParamLine(args,ParameterRectLocal[Meander::BUTTON_ENABLE_HARMONY_ALL7THS_PARAM].pos, labeltext, 0, -1); snprintf(labeltext, sizeof(labeltext), "%s", "V 7ths"); drawHarmonyControlParamLine(args,ParameterRectLocal[Meander::BUTTON_ENABLE_HARMONY_V7THS_PARAM].pos, labeltext, 0, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Staccato"); drawHarmonyControlParamLine(args,ParameterRectLocal[Meander::BUTTON_ENABLE_HARMONY_STACCATO_PARAM].pos, labeltext, 0, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Presets"); drawHarmonyControlParamLine(args,ParameterRectLocal[Meander::CONTROL_HARMONYPRESETS_PARAM].pos, labeltext, 0, -1); snprintf(labeltext, sizeof(labeltext), "%s", " STEP"); drawHarmonyControlParamLine(args,ParameterRectLocal[Meander::BUTTON_PROG_STEP_PARAM].pos, labeltext, 0, -1); // do the progression displays pos =ParameterRectLocal[Meander::CONTROL_HARMONYPRESETS_PARAM].pos.plus(Vec(-20,20)); nvgBeginPath(args.vg); nvgFillColor(args.vg, nvgRGBA( 0x2f, 0x27, 0x0a, 0xff)); nvgRoundedRect(args.vg, pos.x,pos.y, 195.f, 20.f, 4.f); nvgStrokeColor(args.vg,nvgRGBA( 0x80, 0x80 , 0x80, 0x80)); nvgStrokeWidth(args.vg, 2.0); nvgFill(args.vg); nvgStroke(args.vg); if (globalsInitialized) // global fully initialized if Module!=NULL { nvgBeginPath(args.vg); nvgFontSize(args.vg, 14); nvgFontFaceId(args.vg, textfont->handle); nvgTextLetterSpacing(args.vg, -1); nvgFillColor(args.vg, nvgRGBA(0xFF, 0xFF, 0x2C, 0xFF)); snprintf(text, sizeof(text), "#%d: %s", harmony_type, theActiveHarmonyType.harmony_type_desc); nvgText(args.vg, pos.x+5, pos.y+10, text, NULL); } pos = pos.plus(Vec(0,20)); nvgBeginPath(args.vg); nvgFillColor(args.vg, nvgRGBA( 0x2f, 0x27, 0x0a, 0xff)); nvgStrokeColor(args.vg,nvgRGBA( 0x80, 0x80 , 0x80, 0x80)); nvgStrokeWidth(args.vg, 2.0); nvgRoundedRect(args.vg, pos.x,pos.y, 195.f, 20.f, 4.f); nvgFill(args.vg); nvgStroke(args.vg); if (globalsInitialized) // global fully initialized if Module!=NULL { nvgBeginPath(args.vg); nvgFontSize(args.vg, 12); nvgFillColor(args.vg, nvgRGBA(0xFF, 0xFF, 0x2C, 0xFF)); snprintf(text, sizeof(text), "%s ", theActiveHarmonyType.harmony_degrees_desc); nvgText(args.vg, pos.x+5, pos.y+10, text, NULL); } } if (true) // update melody control display { nvgBeginPath(args.vg); nvgRoundedRect(args.vg, 680.f,25.f, 187.f, 353.f, 4.f); nvgFillColor(args.vg, nvgRGBA( 0xe6, 0xe6, 0xe6, 0xff)); nvgFill(args.vg); nvgStrokeColor(args.vg,nvgRGBA( 0x80, 0x80 , 0x80, 0x80)); nvgStrokeWidth(args.vg, 2.5); nvgStroke(args.vg); Vec pos; Vec displayRectPos; Vec paramControlPos; char text[128]; char labeltext[128]; nvgFontSize(args.vg, 17); nvgFontFaceId(args.vg, textfont->handle); nvgTextLetterSpacing(args.vg, -1); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xff)); nvgStrokeColor(args.vg,nvgRGBA( 0x80, 0x80 , 0x80, 0x80)); nvgStrokeWidth(args.vg, 2.0); //*************** // update melody panel begin snprintf(labeltext, sizeof(labeltext), "%s", "Melody Enable"); drawMelodyControlParamLine(args,ParameterRectLocal[Meander::BUTTON_ENABLE_MELODY_PARAM].pos, labeltext, 0, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Degree(1-7)"); drawMelodyControlParamLine(args,ParameterRectLocal[Meander::BUTTON_ENABLE_MELODY_PARAM].pos.plus(Vec(92,-8)), labeltext, 0, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Gate"); drawMelodyControlParamLine(args,ParameterRectLocal[Meander::BUTTON_ENABLE_MELODY_PARAM].pos.plus(Vec(92,6)), labeltext, 0, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Chordal"); drawMelodyControlParamLine(args,ParameterRectLocal[Meander::BUTTON_ENABLE_MELODY_CHORDAL_PARAM].pos, labeltext, 0, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Scaler"); drawMelodyControlParamLine(args,ParameterRectLocal[Meander::BUTTON_ENABLE_MELODY_SCALER_PARAM].pos, labeltext, 0, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Volume (0-10.0)"); drawMelodyControlParamLine(args,ParameterRectLocal[Meander::CONTROL_MELODY_VOLUME_PARAM].pos, labeltext, theMeanderState.theMelodyParms.volume, 1); snprintf(labeltext, sizeof(labeltext), "%s", "Hold tied"); drawMelodyControlParamLine(args,ParameterRectLocal[Meander::BUTTON_MELODY_DESTUTTER_PARAM].pos, labeltext, 0, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Notes on 1/"); drawMelodyControlParamLine(args,ParameterRectLocal[Meander::CONTROL_MELODY_NOTE_LENGTH_DIVISOR_PARAM].pos, labeltext, theMeanderState.theMelodyParms.note_length_divisor, 0); snprintf(labeltext, sizeof(labeltext), "%s", "Target Oct.(1-6)"); drawMelodyControlParamLine(args,ParameterRectLocal[Meander::CONTROL_MELODY_TARGETOCTAVE_PARAM].pos, labeltext, theMeanderState.theMelodyParms.target_octave, 0); snprintf(labeltext, sizeof(labeltext), "%s", "Variability (0-1)"); drawMelodyControlParamLine(args,ParameterRectLocal[Meander::CONTROL_MELODY_ALPHA_PARAM].pos, labeltext, theMeanderState.theMelodyParms.alpha, 2); snprintf(labeltext, sizeof(labeltext), "%s", "+-Octave Range (0-3)"); drawMelodyControlParamLine(args,ParameterRectLocal[Meander::CONTROL_MELODY_RANGE_PARAM].pos, labeltext, theMeanderState.theMelodyParms.note_octave_range, 2); snprintf(labeltext, sizeof(labeltext), "%s", "Staccato"); drawMelodyControlParamLine(args,ParameterRectLocal[Meander::BUTTON_ENABLE_MELODY_STACCATO_PARAM].pos, labeltext, 0, -1); // draw division line pos = ParameterRectLocal[Meander::BUTTON_ENABLE_ARP_PARAM].pos.plus(Vec(-20,-2)); nvgMoveTo(args.vg, pos.x, pos.y); pos=pos.plus(Vec(190,0)); nvgLineTo(args.vg, pos.x, pos.y); nvgStrokeColor(args.vg, nvgRGB(0, 0, 0)); nvgStrokeWidth(args.vg, 1.0); nvgStroke(args.vg); // snprintf(labeltext, sizeof(labeltext), "%s", "Arp Enable"); drawMelodyControlParamLine(args,ParameterRectLocal[Meander::BUTTON_ENABLE_ARP_PARAM].pos, labeltext, 0, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Count (0-31)"); drawMelodyControlParamLine(args,ParameterRectLocal[Meander::CONTROL_ARP_COUNT_PARAM].pos, labeltext, theMeanderState.theArpParms.count, 0); snprintf(labeltext, sizeof(labeltext), "%s", "Notes on 1/"); drawMelodyControlParamLine(args,ParameterRectLocal[Meander::CONTROL_ARP_INCREMENT_PARAM].pos, labeltext, theMeanderState.theArpParms.note_length_divisor, 0); snprintf(labeltext, sizeof(labeltext), "%s", "Decay (0-1.0)"); drawMelodyControlParamLine(args,ParameterRectLocal[Meander::CONTROL_ARP_DECAY_PARAM].pos, labeltext, theMeanderState.theArpParms.decay, 2); snprintf(labeltext, sizeof(labeltext), "%s", "Chordal"); drawMelodyControlParamLine(args,ParameterRectLocal[Meander::BUTTON_ENABLE_ARP_CHORDAL_PARAM].pos, labeltext, 0, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Scaler"); drawMelodyControlParamLine(args,ParameterRectLocal[Meander::BUTTON_ENABLE_ARP_SCALER_PARAM].pos, labeltext, 0, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Pattern (-3-+3"); drawMelodyControlParamLine(args,ParameterRectLocal[Meander::CONTROL_ARP_PATTERN_PARAM].pos, labeltext, theMeanderState.theArpParms.pattern, -1); pos =ParameterRectLocal[Meander::CONTROL_ARP_PATTERN_PARAM].pos.plus(Vec(102,0)); nvgBeginPath(args.vg); nvgFillColor(args.vg, nvgRGBA( 0x2f, 0x27, 0x0a, 0xff)); nvgRoundedRect(args.vg, pos.x,pos.y, 60.f, 20.f, 4.f); nvgStrokeColor(args.vg,nvgRGBA( 0x80, 0x80 , 0x80, 0x80)); nvgStrokeWidth(args.vg, 2.0); nvgFill(args.vg); nvgStroke(args.vg); nvgFontSize(args.vg, 17); nvgFillColor(args.vg, nvgRGBA(0xFF, 0xFF, 0x2C, 0xFF)); if (theMeanderState.theArpParms.pattern==0) snprintf(text, sizeof(text), "%d: 0-echo", theMeanderState.theArpParms.pattern); else if (theMeanderState.theArpParms.pattern==1) snprintf(text, sizeof(text), "%d: +1", theMeanderState.theArpParms.pattern); else if (theMeanderState.theArpParms.pattern==2) snprintf(text, sizeof(text), "%d: +1,-1", theMeanderState.theArpParms.pattern); else if (theMeanderState.theArpParms.pattern==3) snprintf(text, sizeof(text), "%d: +2", theMeanderState.theArpParms.pattern); else if (theMeanderState.theArpParms.pattern==-1) snprintf(text, sizeof(text), "%d: -1", theMeanderState.theArpParms.pattern); else if (theMeanderState.theArpParms.pattern==-2) snprintf(text, sizeof(text), "%d: -1,+1", theMeanderState.theArpParms.pattern); else if (theMeanderState.theArpParms.pattern==-3) snprintf(text, sizeof(text), "%d: -2", theMeanderState.theArpParms.pattern); else snprintf(text, sizeof(text), "%s", " "); // since text is used above, needs to be cleared in fallthrough case nvgText(args.vg, pos.x+10, pos.y+10, text, NULL); } if (true) // update bass panel { nvgBeginPath(args.vg); nvgRoundedRect(args.vg, 869.f, 120.f, 155.f, 258.f, 4.f); nvgFillColor(args.vg, nvgRGBA( 0xe6, 0xe6, 0xe6, 0xff)); nvgFill(args.vg); nvgStrokeColor(args.vg,nvgRGBA( 0x80, 0x80 , 0x80, 0x80)); nvgStrokeWidth(args.vg, 2.5); nvgStroke(args.vg); Vec pos; Vec displayRectPos; Vec paramControlPos; char labeltext[128]; nvgFontSize(args.vg, 17); nvgFontFaceId(args.vg, textfont->handle); nvgTextLetterSpacing(args.vg, -1); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xff)); nvgStrokeColor(args.vg,nvgRGBA( 0x80, 0x80 , 0x80, 0x80)); nvgStrokeWidth(args.vg, 2.0); snprintf(labeltext, sizeof(labeltext), "%s", "Bass Enable"); drawBassControlParamLine(args,ParameterRectLocal[Meander::BUTTON_ENABLE_BASS_PARAM].pos, labeltext, 0, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Volume (0-10)"); drawBassControlParamLine(args,ParameterRectLocal[Meander::CONTROL_BASS_VOLUME_PARAM].pos, labeltext, theMeanderState.theBassParms.volume, 1); snprintf(labeltext, sizeof(labeltext), "%s", "Target Oct.(1-6)"); drawBassControlParamLine(args,ParameterRectLocal[Meander::CONTROL_BASS_TARGETOCTAVE_PARAM].pos, labeltext, theMeanderState.theBassParms.target_octave, 0); snprintf(labeltext, sizeof(labeltext), "%s", "Notes on 1/"); drawBassControlParamLine(args,ParameterRectLocal[Meander::CONTROL_BASS_DIVISOR_PARAM].pos, labeltext, theMeanderState.theBassParms.note_length_divisor, 0); snprintf(labeltext, sizeof(labeltext), "%s", "Staccato"); drawBassControlParamLine(args,ParameterRectLocal[Meander::BUTTON_ENABLE_BASS_STACCATO_PARAM].pos, labeltext, theMeanderState.theBassParms.enable_staccato, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Accent"); drawBassControlParamLine(args,ParameterRectLocal[Meander::BUTTON_BASS_ACCENT_PARAM].pos, labeltext, theMeanderState.theBassParms.accent, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Syncopate"); drawBassControlParamLine(args,ParameterRectLocal[Meander::BUTTON_BASS_SYNCOPATE_PARAM].pos, labeltext, theMeanderState.theBassParms.syncopate, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Shuffle"); drawBassControlParamLine(args,ParameterRectLocal[Meander::BUTTON_BASS_SHUFFLE_PARAM].pos, labeltext, theMeanderState.theBassParms.shuffle, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Octaves"); drawBassControlParamLine(args,ParameterRectLocal[Meander::BUTTON_BASS_OCTAVES_PARAM].pos, labeltext, theMeanderState.theBassParms.octave_enabled, -1); } if (true) // update fBm panel { nvgBeginPath(args.vg); nvgRoundedRect(args.vg, 1025.f, 120.f, 171.f, 258.f, 4.f); nvgFillColor(args.vg, nvgRGBA( 0xe6, 0xe6, 0xe6, 0xff)); nvgFill(args.vg); nvgStrokeColor(args.vg,nvgRGBA( 0x80, 0x80 , 0x80, 0x80)); nvgStrokeWidth(args.vg, 2.5); nvgStroke(args.vg); Vec pos; Vec displayRectPos; Vec paramControlPos; char labeltext[128]; nvgFontSize(args.vg, 17); nvgFontFaceId(args.vg, textfont->handle); nvgTextLetterSpacing(args.vg, -1); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xff)); nvgStrokeColor(args.vg,nvgRGBA( 0x80, 0x80 , 0x80, 0x80)); nvgStrokeWidth(args.vg, 2.0); snprintf(labeltext, sizeof(labeltext), "%s", "fBm 1/f Noise"); drawfBmControlParamLine(args,ParameterRectLocal[Meander::CONTROL_HARMONY_FBM_OCTAVES_PARAM].pos.plus(Vec(30,-25)), labeltext, 0, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Harmony"); drawfBmControlParamLine(args,ParameterRectLocal[Meander::CONTROL_HARMONY_FBM_OCTAVES_PARAM].pos.plus(Vec(37,-13)), labeltext, 0, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Octaves (1-6)"); drawfBmControlParamLine(args,ParameterRectLocal[Meander::CONTROL_HARMONY_FBM_OCTAVES_PARAM].pos, labeltext, theMeanderState.theHarmonyParms.noctaves, 0); snprintf(labeltext, sizeof(labeltext), "%s", "Period Sec. (1-100)"); drawfBmControlParamLine(args,ParameterRectLocal[Meander::CONTROL_HARMONY_FBM_PERIOD_PARAM].pos, labeltext, theMeanderState.theHarmonyParms.period, 1); snprintf(labeltext, sizeof(labeltext), "%s", "Melody"); drawBassControlParamLine(args,ParameterRectLocal[Meander::CONTROL_MELODY_FBM_OCTAVES_PARAM].pos.plus(Vec(41,-13)), labeltext, 0, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Octaves (1-6)"); drawfBmControlParamLine(args,ParameterRectLocal[Meander::CONTROL_MELODY_FBM_OCTAVES_PARAM].pos, labeltext, theMeanderState.theMelodyParms.noctaves, 0); snprintf(labeltext, sizeof(labeltext), "%s", "Period Sec. (1-100)"); drawfBmControlParamLine(args,ParameterRectLocal[Meander::CONTROL_MELODY_FBM_PERIOD_PARAM].pos, labeltext, theMeanderState.theMelodyParms.period, 1); snprintf(labeltext, sizeof(labeltext), "%s", "32nds"); drawfBmControlParamLine(args,ParameterRectLocal[Meander::CONTROL_ARP_FBM_OCTAVES_PARAM].pos.plus(Vec(47,-13)), labeltext, 0, -1); snprintf(labeltext, sizeof(labeltext), "%s", "Octaves (1-6)"); drawfBmControlParamLine(args,ParameterRectLocal[Meander::CONTROL_ARP_FBM_OCTAVES_PARAM].pos, labeltext, theMeanderState.theArpParms.noctaves, 0); snprintf(labeltext, sizeof(labeltext), "%s", "Period Sec. (1-100)"); drawfBmControlParamLine(args,ParameterRectLocal[Meander::CONTROL_ARP_FBM_PERIOD_PARAM].pos, labeltext, theMeanderState.theArpParms.period, 1); } if (true) // draw rounded corner rects for input jacks border { char labeltext[128]; snprintf(labeltext, sizeof(labeltext), "%s", "RUN"); drawLabelAbove(args,ParameterRectLocal[Meander::BUTTON_RUN_PARAM], labeltext, 12.); snprintf(labeltext, sizeof(labeltext), "%s", "Out"); drawOutport(args, OutportRectLocal[Meander::OUT_RUN_OUT].pos, labeltext, 0, 1); snprintf(labeltext, sizeof(labeltext), "%s", "RESET"); drawLabelAbove(args,ParameterRectLocal[Meander::BUTTON_RESET_PARAM], labeltext, 12.); snprintf(labeltext, sizeof(labeltext), "%s", "Out"); drawOutport(args, OutportRectLocal[Meander::OUT_RESET_OUT].pos, labeltext, 0, 1); snprintf(labeltext, sizeof(labeltext), "%s", "BPM"); drawLabelAbove(args,ParameterRectLocal[Meander::CONTROL_TEMPOBPM_PARAM], labeltext, 12.); snprintf(labeltext, sizeof(labeltext), "%s", "Time Sig Top"); drawLabelRight(args,ParameterRectLocal[Meander::CONTROL_TIMESIGNATURETOP_PARAM], labeltext); snprintf(labeltext, sizeof(labeltext), "%s", "Time Sig Bottom"); drawLabelRight(args,ParameterRectLocal[Meander::CONTROL_TIMESIGNATUREBOTTOM_PARAM], labeltext); snprintf(labeltext, sizeof(labeltext), "%s", "Root (~Key)"); drawLabelRight(args,ParameterRectLocal[Meander::CONTROL_ROOT_KEY_PARAM], labeltext); snprintf(labeltext, sizeof(labeltext), "%s", "Mode"); drawLabelRight(args,ParameterRectLocal[Meander::CONTROL_SCALE_PARAM], labeltext); snprintf(labeltext, sizeof(labeltext), "%s", " 8x BPM Clock"); drawLabelOffset(args, InportRectLocal[Meander::IN_CLOCK_EXT_CV], labeltext, -14., -11.); snprintf(labeltext, sizeof(labeltext), "%s", "Poly Ext. Scale"); drawLabelLeft(args, OutportRectLocal[Meander::OUT_EXT_POLY_SCALE_OUTPUT], labeltext, -40.); snprintf(labeltext, sizeof(labeltext), "%s", "Out"); drawOutport(args, OutportRectLocal[Meander::OUT_EXT_POLY_SCALE_OUTPUT].pos, labeltext, 0, 1); } if (true) // draw rounded corner rects for output jacks border { char labeltext[128]; snprintf(labeltext, sizeof(labeltext), "%s", "1V/Oct"); drawOutport(args, OutportRectLocal[Meander::OUT_HARMONY_CV_OUTPUT].pos, labeltext, 0, 1); snprintf(labeltext, sizeof(labeltext), "%s", "Gate"); drawOutport(args, OutportRectLocal[Meander::OUT_HARMONY_GATE_OUTPUT].pos, labeltext, 0, 1); snprintf(labeltext, sizeof(labeltext), "%s", "Volume"); drawOutport(args, OutportRectLocal[Meander::OUT_HARMONY_VOLUME_OUTPUT].pos, labeltext, 0, 1); snprintf(labeltext, sizeof(labeltext), "%s", "1V/Oct"); drawOutport(args, OutportRectLocal[Meander::OUT_MELODY_CV_OUTPUT].pos, labeltext, 0, 1); snprintf(labeltext, sizeof(labeltext), "%s", "Gate"); drawOutport(args, OutportRectLocal[Meander::OUT_MELODY_GATE_OUTPUT].pos, labeltext, 0, 1); snprintf(labeltext, sizeof(labeltext), "%s", "Volume"); drawOutport(args, OutportRectLocal[Meander::OUT_MELODY_VOLUME_OUTPUT].pos, labeltext, 0, 1); snprintf(labeltext, sizeof(labeltext), "%s", "1V/Oct"); drawOutport(args, OutportRectLocal[Meander::OUT_BASS_CV_OUTPUT].pos, labeltext, 0, 1); snprintf(labeltext, sizeof(labeltext), "%s", "Gate"); drawOutport(args, OutportRectLocal[Meander::OUT_BASS_GATE_OUTPUT].pos, labeltext, 0, 1); snprintf(labeltext, sizeof(labeltext), "%s", "Volume"); drawOutport(args, OutportRectLocal[Meander::OUT_BASS_VOLUME_OUTPUT].pos, labeltext, 0, 1); snprintf(labeltext, sizeof(labeltext), "%s", "Melody"); drawOutport(args, OutportRectLocal[Meander::OUT_FBM_MELODY_OUTPUT].pos, labeltext, 0, 1); sprintf(labeltext, "%s", "Outputs are 0-10V fBm noise"); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xff)); nvgStrokeColor(args.vg,nvgRGBA( 0x80, 0x80 , 0x80, 0x80)); nvgFontSize(args.vg, 17); nvgFontFaceId(args.vg, textfont->handle); nvgTextLetterSpacing(args.vg, -1); nvgBeginPath(args.vg); nvgFontFaceId(args.vg, textfont->handle); nvgTextAlign(args.vg,NVG_ALIGN_CENTER|NVG_ALIGN_MIDDLE); nvgText(args.vg, OutportRectLocal[Meander::OUT_FBM_MELODY_OUTPUT].pos.x+13, OutportRectLocal[Meander::OUT_FBM_MELODY_OUTPUT].pos.y-30, labeltext, NULL); snprintf(labeltext, sizeof(labeltext), "%s", "Harmony"); drawOutport(args, OutportRectLocal[Meander::OUT_FBM_HARMONY_OUTPUT].pos, labeltext, 0, 1); snprintf(labeltext, sizeof(labeltext), "%s", "32nds"); drawOutport(args, OutportRectLocal[Meander::OUT_FBM_ARP_OUTPUT].pos, labeltext, 0, 1); snprintf(labeltext, sizeof(labeltext), "%s", "Bar"); drawOutport(args, OutportRectLocal[Meander::OUT_CLOCK_BAR_OUTPUT].pos, labeltext, 0, 1); snprintf(labeltext, sizeof(labeltext), "%s", "Beat"); drawOutport(args, OutportRectLocal[Meander::OUT_CLOCK_BEAT_OUTPUT].pos, labeltext, 0, 1); snprintf(labeltext, sizeof(labeltext), "%s", "Beatx2"); drawOutport(args, OutportRectLocal[Meander::OUT_CLOCK_BEATX2_OUTPUT].pos, labeltext, 0, 1); snprintf(labeltext, sizeof(labeltext), "%s", "1ms Clocked Trigger Pulses"); rack::math::Rect rect=OutportRectLocal[Meander::OUT_CLOCK_BEATX2_OUTPUT]; rect.pos=rect.pos.plus(Vec(0,-16)); drawLabelAbove(args, rect, labeltext, 18.); snprintf(labeltext, sizeof(labeltext), "%s", "Beatx4"); drawOutport(args, OutportRectLocal[Meander::OUT_CLOCK_BEATX4_OUTPUT].pos, labeltext, 0, 1); snprintf(labeltext, sizeof(labeltext), "%s", "Beatx8"); drawOutport(args, OutportRectLocal[Meander::OUT_CLOCK_BEATX8_OUTPUT].pos, labeltext, 0, 1); snprintf(labeltext, sizeof(labeltext), "%s", "These can trigger STEP above"); rect=OutportRectLocal[Meander::OUT_CLOCK_BEATX8_OUTPUT]; rect.pos=rect.pos.plus(Vec(5,0)); drawLabelRight(args, rect, labeltext); snprintf(labeltext, sizeof(labeltext), "%s", "Out"); drawOutport(args, OutportRectLocal[Meander::OUT_EXT_POLY_SCALE_OUTPUT].pos, labeltext, 0, 1); snprintf(labeltext, sizeof(labeltext), "%s", "Out"); drawOutport(args, OutportRectLocal[Meander::OUT_CLOCK_OUT].pos, labeltext, 0, 1); } Vec pos; char text[128]; nvgFontSize(args.vg, 17); nvgFontFaceId(args.vg, textfont->handle); nvgTextLetterSpacing(args.vg, -1); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xFF)); //************************ // circle area float beginEdge = 295; float beginTop =115; float lineWidth=1.0; float stafflineLength=100; float barLineVoffset=36.; float barLineVlength=60.; int yLineSpacing=6; float yHalfLineSpacing=3.0f; // draw bar left vertical edge if (beginEdge > 0) { nvgBeginPath(args.vg); nvgMoveTo(args.vg, beginEdge, beginTop+barLineVoffset); nvgLineTo(args.vg, beginEdge, beginTop+barLineVlength); nvgStrokeColor(args.vg, nvgRGB(0, 0, 0)); nvgStrokeWidth(args.vg, lineWidth); nvgStroke(args.vg); } // draw staff lines nvgBeginPath(args.vg); for (int staff = 36, y = staff; y <= staff + 24; y += yLineSpacing) { nvgMoveTo(args.vg, beginEdge, beginTop+y); nvgLineTo(args.vg, beginEdge+stafflineLength, beginTop+y); } nvgStrokeColor(args.vg, nvgRGB(0x7f, 0x7f, 0x7f)); nvgStrokeWidth(args.vg, lineWidth); nvgStroke(args.vg); nvgFontSize(args.vg, 45); nvgFontFaceId(args.vg, musicfont->handle); nvgTextLetterSpacing(args.vg, -1); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xFF)); // pos=Vec(beginEdge+10, beginTop+45); // had to change for some unknown reason pos=Vec(beginEdge, beginTop+45); snprintf(text, sizeof(text), "%s", "G"); // treble clef nvgText(args.vg, pos.x, pos.y, text, NULL); nvgFontSize(args.vg, 35); nvgTextAlign(args.vg,NVG_ALIGN_CENTER|NVG_ALIGN_MIDDLE); snprintf(text, sizeof(text), "%s", "B"); // sharp int num_sharps1=0; int vertical_offset1=0; for (int i=0; i<7; ++i) { nvgBeginPath(args.vg); if (root_key_signatures_chromaticForder[notate_mode_as_signature_root_key][i]==1) { vertical_offset1=root_key_sharps_vertical_display_offset[num_sharps1]; pos=Vec(beginEdge+20+(num_sharps1*5), beginTop+24+(vertical_offset1*yHalfLineSpacing)); nvgText(args.vg, pos.x, pos.y, text, NULL); ++num_sharps1; } nvgClosePath(args.vg); } snprintf(text, sizeof(text), "%s", "b"); // flat int num_flats1=0; vertical_offset1=0; for (int i=6; i>=0; --i) { nvgBeginPath(args.vg); if (root_key_signatures_chromaticForder[notate_mode_as_signature_root_key][i]==-1) { vertical_offset1=root_key_flats_vertical_display_offset[num_flats1]; pos=Vec(beginEdge+20+(num_flats1*5), beginTop+24+(vertical_offset1*yHalfLineSpacing)); nvgText(args.vg, pos.x, pos.y, text, NULL); ++num_flats1; } nvgClosePath(args.vg); } nvgFontSize(args.vg, 12); nvgFontFaceId(args.vg, textfont->handle); nvgTextLetterSpacing(args.vg, -1); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xFF)); pos=Vec(beginEdge+30, beginTop+95); snprintf(text, sizeof(text), "%s", "In"); nvgText(args.vg, pos.x, pos.y, text, NULL); pos=Vec(beginEdge+30, beginTop+115); snprintf(text, sizeof(text), "%s", "In"); nvgText(args.vg, pos.x, pos.y, text, NULL); pos=Vec(beginEdge+90, beginTop+95); snprintf(text, sizeof(text), "%s", "Degree (1-7)"); nvgText(args.vg, pos.x, pos.y, text, NULL); pos=Vec(beginEdge+74, beginTop+115); snprintf(text, sizeof(text), "%s", "Gate"); nvgText(args.vg, pos.x, pos.y, text, NULL); //************************ // display area // draw staff lines beginEdge = 890; beginTop =8; lineWidth=1.0; stafflineLength=300; barLineVoffset=36.; barLineVlength=60.; yLineSpacing=6; yHalfLineSpacing=3.0f; // draw bar left vertical edge if (beginEdge > 0) { nvgBeginPath(args.vg); nvgMoveTo(args.vg, beginEdge, beginTop+barLineVoffset); nvgLineTo(args.vg, beginEdge, beginTop+(1.60*barLineVlength)); nvgStrokeColor(args.vg, nvgRGB(0, 0, 0)); nvgStrokeWidth(args.vg, lineWidth); nvgStroke(args.vg); } // draw bar right vertical edge if (beginEdge > 0) { nvgBeginPath(args.vg); nvgMoveTo(args.vg, beginEdge+stafflineLength, beginTop+barLineVoffset); nvgLineTo(args.vg, beginEdge+stafflineLength, beginTop+(1.60*barLineVlength)); nvgStrokeColor(args.vg, nvgRGB(0, 0, 0)); nvgStrokeWidth(args.vg, lineWidth); nvgStroke(args.vg); } // draw staff lines nvgBeginPath(args.vg); for (int staff = 36; staff <= 72; staff += 36) { for (int y = staff; y <= staff + 24; y += 6) { nvgMoveTo(args.vg, beginEdge, beginTop+y); nvgLineTo(args.vg, beginEdge+stafflineLength, beginTop+y); } } nvgStrokeColor(args.vg, nvgRGB(0x7f, 0x7f, 0x7f)); nvgStrokeWidth(args.vg, lineWidth); nvgStroke(args.vg); nvgFontSize(args.vg, 45); nvgFontFaceId(args.vg, musicfont->handle); nvgTextLetterSpacing(args.vg, -1); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xFF)); pos=Vec(beginEdge+10, beginTop+45); snprintf(text, sizeof(text), "%s", "G"); // treble clef nvgText(args.vg, pos.x, pos.y, text, NULL); nvgFontSize(args.vg, 36); pos=Vec(beginEdge+10, beginTop+80); snprintf(text, sizeof(text), "%s", "?"); // bass clef nvgText(args.vg, pos.x, pos.y, text, NULL); nvgFontSize(args.vg, 40); pos=Vec(beginEdge+53, beginTop+33); snprintf(text, sizeof(text), "%d",time_sig_top); nvgText(args.vg, pos.x, pos.y, text, NULL); nvgFontSize(args.vg, 40); pos=Vec(beginEdge+53, beginTop+69); snprintf(text, sizeof(text), "%d",time_sig_top); nvgText(args.vg, pos.x, pos.y, text, NULL); nvgFontSize(args.vg, 40); pos=Vec(beginEdge+53, beginTop+45); snprintf(text, sizeof(text), "%d",time_sig_bottom); nvgText(args.vg, pos.x, pos.y, text, NULL); nvgFontSize(args.vg, 40); pos=Vec(beginEdge+53, beginTop+81); snprintf(text, sizeof(text), "%d",time_sig_bottom); nvgText(args.vg, pos.x, pos.y, text, NULL); // do root_key signature nvgFontSize(args.vg, 35); nvgTextAlign(args.vg,NVG_ALIGN_CENTER|NVG_ALIGN_MIDDLE); snprintf(text, sizeof(text), "%s", "B"); // # sharp num_sharps1=0; vertical_offset1=0; for (int i=0; i<7; ++i) { nvgBeginPath(args.vg); if (root_key_signatures_chromaticForder[notate_mode_as_signature_root_key][i]==1) { vertical_offset1=root_key_sharps_vertical_display_offset[num_sharps1]; pos=Vec(beginEdge+20+(num_sharps1*5), beginTop+24+(vertical_offset1*yHalfLineSpacing)); nvgText(args.vg, pos.x, pos.y, text, NULL); ++num_sharps1; } nvgClosePath(args.vg); } snprintf(text, sizeof(text), "%s", "b"); // b flat num_flats1=0; vertical_offset1=0; for (int i=6; i>=0; --i) { nvgBeginPath(args.vg); if (root_key_signatures_chromaticForder[notate_mode_as_signature_root_key][i]==-1) { vertical_offset1=root_key_flats_vertical_display_offset[num_flats1]; pos=Vec(beginEdge+20+(num_flats1*5), beginTop+24+(vertical_offset1*yHalfLineSpacing)); nvgText(args.vg, pos.x, pos.y, text, NULL); ++num_flats1; } nvgClosePath(args.vg); } // now do for bass clef nvgFontSize(args.vg, 35); nvgTextAlign(args.vg,NVG_ALIGN_CENTER|NVG_ALIGN_MIDDLE); snprintf(text, sizeof(text), "%s", "B"); // # sharp num_sharps1=0; vertical_offset1=0; for (int i=0; i<7; ++i) { nvgBeginPath(args.vg); if (root_key_signatures_chromaticForder[notate_mode_as_signature_root_key][i]==1) { vertical_offset1=root_key_sharps_vertical_display_offset[num_sharps1]; pos=Vec(beginEdge+20+(num_sharps1*5), beginTop+67+(vertical_offset1*yHalfLineSpacing)); nvgText(args.vg, pos.x, pos.y, text, NULL); ++num_sharps1; } nvgClosePath(args.vg); } snprintf(text, sizeof(text), "%s", "b"); // b flat num_flats1=0; vertical_offset1=0; for (int i=6; i>=0; --i) { nvgBeginPath(args.vg); if (root_key_signatures_chromaticForder[notate_mode_as_signature_root_key][i]==-1) { vertical_offset1=root_key_flats_vertical_display_offset[num_flats1]; pos=Vec(beginEdge+20+(num_flats1*5), beginTop+67+(vertical_offset1*yHalfLineSpacing)); nvgText(args.vg, pos.x, pos.y, text, NULL); ++num_flats1; } nvgClosePath(args.vg); } //**************** float display_note_position=0; if (globalsInitialized) // global fully initialized if Module!=NULL { nvgFontSize(args.vg, 30); nvgFontFaceId(args.vg, musicfont->handle); nvgTextLetterSpacing(args.vg, -1); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xFF)); for (int i=0; ((i<bar_note_count)&&(i<256)); ++i) { int display_note=played_notes_circular_buffer[i].note; if (doDebug) DEBUG("display_note=%d %s", display_note, note_desig[display_note%12]); int scale_note=0; if (strstr(note_desig[display_note%12],"C")) scale_note=0; else if (strstr(note_desig[display_note%12],"D")) scale_note=1; else if (strstr(note_desig[display_note%12],"E")) scale_note=2; else if (strstr(note_desig[display_note%12],"F")) scale_note=3; else if (strstr(note_desig[display_note%12],"G")) scale_note=4; else if (strstr(note_desig[display_note%12],"A")) scale_note=5; else if (strstr(note_desig[display_note%12],"B")) scale_note=6; if (doDebug) DEBUG("scale_note=%d", scale_note%12); int octave=(display_note/12)-2; if (doDebug) DEBUG("octave=%d", octave); display_note_position = 108.0-(octave*21.0)-(scale_note*3.0)-7.5; if (doDebug) DEBUG("display_note_position=%d", (int)display_note_position); float note_x_spacing= 230.0/(32*time_sig_top/time_sig_bottom); // experimenting with note spacing function of time_signature. barts_count_limit is not in scope, needs to be global pos=Vec(beginEdge+70+(played_notes_circular_buffer[i].time32s*note_x_spacing), beginTop+display_note_position); if (true) // color code notes in staff rendering { if (played_notes_circular_buffer[i].noteType==NOTE_TYPE_CHORD) nvgFillColor(args.vg, nvgRGBA(0xFF, 0x0, 0x0, 0xFF)); else if (played_notes_circular_buffer[i].noteType==NOTE_TYPE_MELODY) nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xFF)); else if (played_notes_circular_buffer[i].noteType==NOTE_TYPE_ARP) nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0xFF, 0xFF)); else if (played_notes_circular_buffer[i].noteType==NOTE_TYPE_BASS) nvgFillColor(args.vg, nvgRGBA(0x0, 0xFF, 0x0, 0xFF)); } nvgFontSize(args.vg, 30); if (played_notes_circular_buffer[i].length==1) snprintf(text, sizeof(text), "%s", "w"); // mnemonic W=whole, h=half, q-quarter, e=eighth, s=sixteenth notes else if (played_notes_circular_buffer[i].length==2) snprintf(text, sizeof(text), "%s", "h"); // mnemonic W=whole, h=half, q-quarter, e=eighth, s=sixteenth notes else if (played_notes_circular_buffer[i].length==4) snprintf(text, sizeof(text), "%s", "q"); // mnemonic W=whole, h=half, q-quarter, e=eighth, s=sixteenth notes else if (played_notes_circular_buffer[i].length==8) snprintf(text, sizeof(text), "%s", "e"); // mnemonic W=whole, h=half, q-quarter, e=eighth, s=sixteenth notes else if (played_notes_circular_buffer[i].length==16) snprintf(text, sizeof(text), "%s", "s"); // mnemonic W=whole, h=half, q-quarter, e=eighth, s=sixteenth notes else if (played_notes_circular_buffer[i].length==32) snprintf(text, sizeof(text), "%s", "s"); // mnemonic W=whole, h=half, q-quarter, e=eighth, s=sixteenth notes nvgText(args.vg, pos.x, pos.y, text, NULL); if (played_notes_circular_buffer[i].length==32) // do overstrike for 1/32 symbol { nvgFontSize(args.vg, 15); snprintf(text, sizeof(text), "%s", "e"); // mnemonic W=whole, h=half, q-quarter, e=eighth, s=sixteenth notes nvgText(args.vg, pos.x-.5, pos.y+4.5, text, NULL); } if (((scale_note==5)&&(octave==3)) //A3 ||((scale_note==0)&&(octave==4)) //C4 ||((scale_note==0)&&(octave==2)) //C2 ||((scale_note==2)&&(octave==0)) //E0 ||((scale_note==0)&&(octave==0))) //C0 { nvgFontSize(args.vg, 30); pos.x -= 2.0; pos.y -= 4.4; snprintf(text, sizeof(text), "%s", "_"); nvgText(args.vg, pos.x, pos.y, text, NULL); } } } //********************* if (globalsInitialized) // global fully initialized if Module!=NULL { nvgFontSize(args.vg, 14); nvgFontFaceId(args.vg, textfont->handle); nvgTextLetterSpacing(args.vg, -1); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xFF)); // write last melody note played pos=convertSVGtoNVG(261.4, 120.3, 12.1, 6.5); // X,Y,W,H in Inkscape mm units snprintf(text, sizeof(text), "%s%d", note_desig[(theMeanderState.theMelodyParms.last[0].note%12)], (int)(theMeanderState.theMelodyParms.last[0].note/12 )); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xFF)); nvgText(args.vg, pos.x, pos.y, text, NULL); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xFF)); // write last arp note played if (theMeanderState.theArpParms.note_count>0) { pos=convertSVGtoNVG(261.4, 120.3, 12.1, 6.5); // X,Y,W,H in Inkscape mm units snprintf(text, sizeof(text), "%s%d", note_desig[(theMeanderState.theArpParms.last[theMeanderState.theArpParms.note_count].note%12)], (int)(theMeanderState.theArpParms.last[theMeanderState.theArpParms.note_count].note/12 )); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0xFF, 0xFF)); nvgText(args.vg, pos.x+20, pos.y+200, text, NULL); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xFF)); } // write last harmony note played 1 pos=convertSVGtoNVG(187.8, 119.8, 12.1, 6.5); // X,Y,W,H in Inkscape mm units snprintf(text, sizeof(text), "%s%d", note_desig[(theMeanderState.theHarmonyParms.last[0].note%12)] , theMeanderState.theHarmonyParms.last[0].note/12); nvgFillColor(args.vg, nvgRGBA(0xFF, 0x0, 0x0, 0xFF)); nvgText(args.vg, pos.x, pos.y, text, NULL); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xFF)); // write last harmony note played 2 pos=convertSVGtoNVG(199.1, 119.8, 12.1, 6.5); // X,Y,W,H in Inkscape mm units snprintf(text, sizeof(text), "%s%d", note_desig[(theMeanderState.theHarmonyParms.last[1].note%12)], theMeanderState.theHarmonyParms.last[1].note/12); nvgFillColor(args.vg, nvgRGBA(0xFF, 0x0, 0x0, 0xFF)); nvgText(args.vg, pos.x, pos.y, text, NULL); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xFF)); // write last harmony note played 3 pos=convertSVGtoNVG(210.4, 119.8, 12.1, 6.5); // X,Y,W,H in Inkscape mm units snprintf(text, sizeof(text), "%s%d", note_desig[(theMeanderState.theHarmonyParms.last[2].note%12)], theMeanderState.theHarmonyParms.last[2].note/12); nvgFillColor(args.vg, nvgRGBA(0xFF, 0x0, 0x0, 0xFF)); nvgText(args.vg, pos.x, pos.y, text, NULL); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xFF)); // write last harmony note played 4 pos=convertSVGtoNVG(221.7, 119.8, 12.1, 6.5); // X,Y,W,H in Inkscape mm units if ((theMeanderState.theHarmonyParms.last_chord_type==2)||(theMeanderState.theHarmonyParms.last_chord_type==3)||(theMeanderState.theHarmonyParms.last_chord_type==4)||(theMeanderState.theHarmonyParms.last_chord_type==5)) snprintf(text, sizeof(text), "%s%d", note_desig[(theMeanderState.theHarmonyParms.last[3].note%12)], theMeanderState.theHarmonyParms.last[3].note/12); else snprintf(text, sizeof(text), "%s", " "); nvgFillColor(args.vg, nvgRGBA(0xFF, 0x0, 0x0, 0xFF)); nvgText(args.vg, pos.x, pos.y, text, NULL); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xFF)); // write last bass note played pos=convertSVGtoNVG(319.1, 121.0, 12.1, 6.5); // X,Y,W,H in Inkscape mm units snprintf(text, sizeof(text), "%s%d", note_desig[(theMeanderState.theBassParms.last[0].note%12)], (theMeanderState.theBassParms.last[0].note/12)); nvgFillColor(args.vg, nvgRGBA(0x0, 0xFF, 0x0, 0xFF)); nvgText(args.vg, pos.x, pos.y, text, NULL); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xFF)); // write last octave bass note played if (theMeanderState.theBassParms.octave_enabled) { pos=convertSVGtoNVG(330.1, 121.0, 12.1, 6.5); // X,Y,W,H in Inkscape mm units snprintf(text, sizeof(text), "%s%d", note_desig[(theMeanderState.theBassParms.last[1].note%12)], (theMeanderState.theBassParms.last[1].note/12)); nvgFillColor(args.vg, nvgRGBA(0x0, 0xFF, 0x0, 0xFF)); nvgText(args.vg, pos.x, pos.y, text, NULL); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xFF)); } } int last_chord_root=theMeanderState.last_harmony_chord_root_note%12; int last_chord_bass_note=theMeanderState.theHarmonyParms.last[0].note%12; // pos=convertSVGtoNVG(110, 60, 12.1, 6.5); // X,Y,W,H in Inkscape mm units pos=convertSVGtoNVG(110, 62, 12.1, 6.5); // X,Y,W,H in Inkscape mm units nvgFontSize(args.vg, 30); char chord_type_desc[16]; if (theMeanderState.theHarmonyParms.last_chord_type==0) strcpy(chord_type_desc, ""); if (theMeanderState.theHarmonyParms.last_chord_type==2) // dom strcpy(chord_type_desc, "dom7"); if (theMeanderState.theHarmonyParms.last_chord_type==1) strcpy(chord_type_desc, "m"); if (theMeanderState.theHarmonyParms.last_chord_type==3) strcpy(chord_type_desc, "7"); if (theMeanderState.theHarmonyParms.last_chord_type==4) strcpy(chord_type_desc, "m7"); if (theMeanderState.theHarmonyParms.last_chord_type==5) strcpy(chord_type_desc, "dim7"); if (theMeanderState.theHarmonyParms.last_chord_type==6) strcpy(chord_type_desc, "dim"); if (last_chord_bass_note!=last_chord_root) snprintf(text, sizeof(text), "%s%s/%s", note_desig[last_chord_root], chord_type_desc, note_desig[last_chord_bass_note]); else snprintf(text, sizeof(text), "%s%s", note_desig[last_chord_root], chord_type_desc); nvgText(args.vg, pos.x, pos.y, text, NULL); // drawGrid(args); // here after all updates are completed so grid is on top if (doDebug) DEBUG("UpdatePanel()-end"); } // end UpdatePanel() double smoothedDt=.016; // start out at 1/60 int numZeroes=0; void draw(const DrawArgs &args) override { if (true) // disable nanovg rendering for testing { #if defined(_USE_WINDOWS_PERFTIME) LARGE_INTEGER t; QueryPerformanceFrequency(&t); double frequency=double(t.QuadPart); QueryPerformanceCounter(&t); int64_t n= t.QuadPart; double count= (double)(n)/frequency; double time1=count; #endif DrawCircle5ths(args, root_key); // has to be done each frame as panel redraws as SVG and needs to be blanked and cirecles redrawn DrawDegreesSemicircle(args, root_key); updatePanel(args); #if defined(_USE_WINDOWS_PERFTIME) QueryPerformanceCounter(&t); n= t.QuadPart; count= (double)(n)/frequency; double time2=count; double deltaTime=time2-time1; smoothedDt=(.9*smoothedDt) + (.1*(deltaTime)); nvgFontSize(args.vg, 12); nvgFontFaceId(args.vg, textfont->handle); nvgTextAlign(args.vg,NVG_ALIGN_LEFT|NVG_ALIGN_MIDDLE); nvgTextLetterSpacing(args.vg, -1); nvgFillColor(args.vg, nvgRGBA(0x0, 0x0, 0x0, 0xFF)); Vec pos=Vec(10, 338); char text[128]; snprintf(text, sizeof(text), "UI %.2lf ms", smoothedDt*1000.0); nvgText(args.vg, pos.x, pos.y, text, NULL); #endif } } }; // end struct CircleOf5thsDisplay MeanderWidget(Meander* module) // all plugins I've looked at use this constructor with module*, even though docs show it deprecated. { if (doDebug) DEBUG("MeanderWidget()"); setModule(module); // most plugins do this this->module = module; // most plugins do not do this. It was introduced in singleton implementation setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Meander.svg"))); rack::random::init(); // must be called per thread if (true) // must be executed in order to see ModuleWidget panel display in preview, module* is checked for null below as it is null in browser preview { if ((module) &&(!module->instanceRunning)) { box.size.x = mm2px(5.08 * 32); int middle = box.size.x / 2 + 7; addChild(new RSLabelCentered(middle, (box.size.y / 2), "DISABLED", 28)); addChild(new RSLabelCentered(middle, (box.size.y / 2)+30, "ONLY ONE INSTANCE OF MEANDER REQUIRED",20)); return; } RootKeySelectLineDisplay *MeanderRootKeySelectDisplay = createWidget<RootKeySelectLineDisplay>(Vec(120.,198.)); MeanderRootKeySelectDisplay->box.size = Vec(40, 22); addChild(MeanderRootKeySelectDisplay); ScaleSelectLineDisplay *MeanderScaleSelectDisplay = createWidget<ScaleSelectLineDisplay>(Vec(40.,225.)); MeanderScaleSelectDisplay->box.size = Vec(120, 22); addChild(MeanderScaleSelectDisplay); CircleOf5thsDisplay *display = new CircleOf5thsDisplay(); display->ParameterRectLocal=ParameterRect; display->InportRectLocal=InportRect; display->OutportRectLocal=OutportRect; display->box.pos = Vec(0, 0); display->box.size = Vec(box.size.x, box.size.y); addChild(display); addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0))); addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0))); addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); //BPM DISPLAY BpmDisplayWidget *BPMdisplay = new BpmDisplayWidget(); BPMdisplay->box.pos = Vec(70,90); BPMdisplay->box.size = Vec(80, 35); if (module) BPMdisplay->val = &module->tempo; addChild(BPMdisplay); //SIG TOP DISPLAY SigDisplayWidget *SigTopDisplay = new SigDisplayWidget(); SigTopDisplay->box.pos = Vec(130,130); SigTopDisplay->box.size = Vec(25, 20); if (module) SigTopDisplay->value = &time_sig_top; addChild(SigTopDisplay); //SIG TOP KNOB //SIG BOTTOM DISPLAY SigDisplayWidget *SigBottomDisplay = new SigDisplayWidget(); SigBottomDisplay->box.pos = Vec(130,150); SigBottomDisplay->box.size = Vec(25, 20); if (module) SigBottomDisplay->value = &time_sig_bottom; addChild(SigBottomDisplay); //************* Note: Each LEDButton needs its light and that light needs a unique ID, needs to be added to an array and then needs to be repositioned along with the button. Also needs to be enumed with other lights so lights[] picks it up. paramWidgets[Meander::BUTTON_CIRCLESTEP_C_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(116.227, 37.257)), module, Meander::BUTTON_CIRCLESTEP_C_PARAM); addParam(paramWidgets[Meander::BUTTON_CIRCLESTEP_C_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_1]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(116.227, 37.257)), module, Meander::LIGHT_LEDBUTTON_CIRCLESTEP_1); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_1]); paramWidgets[Meander::BUTTON_CIRCLESTEP_G_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(132.479, 41.32)), module, Meander::BUTTON_CIRCLESTEP_G_PARAM); addParam(paramWidgets[Meander::BUTTON_CIRCLESTEP_G_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_2]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(132.479, 41.32)), module, Meander::LIGHT_LEDBUTTON_CIRCLESTEP_2); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_2]); paramWidgets[Meander::BUTTON_CIRCLESTEP_D_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(143.163, 52.155)), module, Meander::BUTTON_CIRCLESTEP_D_PARAM); addParam(paramWidgets[Meander::BUTTON_CIRCLESTEP_D_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_3]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(143.163, 52.155)), module, Meander::LIGHT_LEDBUTTON_CIRCLESTEP_3); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_3]); paramWidgets[Meander::BUTTON_CIRCLESTEP_A_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(147.527, 67.353)), module, Meander::BUTTON_CIRCLESTEP_A_PARAM); addParam(paramWidgets[Meander::BUTTON_CIRCLESTEP_A_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_4]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(147.527, 67.353)), module, Meander::LIGHT_LEDBUTTON_CIRCLESTEP_4); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_4]); paramWidgets[Meander::BUTTON_CIRCLESTEP_E_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(141.96, 83.906)), module, Meander::BUTTON_CIRCLESTEP_E_PARAM); addParam(paramWidgets[Meander::BUTTON_CIRCLESTEP_E_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_5]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(141.96, 83.906)), module, Meander::LIGHT_LEDBUTTON_CIRCLESTEP_5); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_5]); paramWidgets[Meander::BUTTON_CIRCLESTEP_B_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(132.931, 94.44)), module, Meander::BUTTON_CIRCLESTEP_B_PARAM); addParam(paramWidgets[Meander::BUTTON_CIRCLESTEP_B_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_6]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(132.931, 94.44)), module, Meander::LIGHT_LEDBUTTON_CIRCLESTEP_6); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_6]); paramWidgets[Meander::BUTTON_CIRCLESTEP_GBFS_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(116.378, 98.804)), module, Meander::BUTTON_CIRCLESTEP_GBFS_PARAM); addParam(paramWidgets[Meander::BUTTON_CIRCLESTEP_GBFS_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_7]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(116.378, 98.804)), module, Meander::LIGHT_LEDBUTTON_CIRCLESTEP_7); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_7]); paramWidgets[Meander::BUTTON_CIRCLESTEP_DB_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(101.029, 93.988)), module, Meander::BUTTON_CIRCLESTEP_DB_PARAM); addParam(paramWidgets[Meander::BUTTON_CIRCLESTEP_DB_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_8]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(101.029, 93.988)), module, Meander::LIGHT_LEDBUTTON_CIRCLESTEP_8); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_8]); paramWidgets[Meander::BUTTON_CIRCLESTEP_AB_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(91.097, 83.906)), module, Meander::BUTTON_CIRCLESTEP_AB_PARAM); addParam(paramWidgets[Meander::BUTTON_CIRCLESTEP_AB_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_9]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(91.097, 83.906)), module, Meander::LIGHT_LEDBUTTON_CIRCLESTEP_9); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_9]); paramWidgets[Meander::BUTTON_CIRCLESTEP_EB_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(86.282, 68.106)), module, Meander::BUTTON_CIRCLESTEP_EB_PARAM); addParam(paramWidgets[Meander::BUTTON_CIRCLESTEP_EB_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_10]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(86.282, 68.106)), module, Meander::LIGHT_LEDBUTTON_CIRCLESTEP_10); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_10]); paramWidgets[Meander::BUTTON_CIRCLESTEP_BB_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(89.743, 52.004)), module, Meander::BUTTON_CIRCLESTEP_BB_PARAM); addParam(paramWidgets[Meander::BUTTON_CIRCLESTEP_BB_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_11]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(189.743, 52.004)), module, Meander::LIGHT_LEDBUTTON_CIRCLESTEP_11); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_11]); paramWidgets[Meander::BUTTON_CIRCLESTEP_F_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(101.781, 40.568)), module, Meander::BUTTON_CIRCLESTEP_F_PARAM); addParam(paramWidgets[Meander::BUTTON_CIRCLESTEP_F_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_12]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(101.781, 40.568)), module, Meander::LIGHT_LEDBUTTON_CIRCLESTEP_12); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_12]); //************* lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_1_LIGHT]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(116.227, 43.878)), module, Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_1_LIGHT); addChild(lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_1_LIGHT]); lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_2_LIGHT]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(129.018, 47.189)), module, Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_2_LIGHT); addChild(lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_2_LIGHT]); lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_3_LIGHT]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(137.295, 56.067)), module, Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_3_LIGHT); addChild(lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_3_LIGHT]); lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_4_LIGHT]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(140.455, 67.654)), module, Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_4_LIGHT); addChild(lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_4_LIGHT]); lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_5_LIGHT]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(137.144, 80.295)), module, Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_5_LIGHT); addChild(lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_5_LIGHT]); lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_6_LIGHT]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(128.868, 88.571)), module, Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_6_LIGHT); addChild(lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_6_LIGHT]); lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_7_LIGHT]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(116.077, 92.183)), module, Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_7_LIGHT); addChild(lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_7_LIGHT]); lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_8_LIGHT]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(104.791, 88.872)), module, Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_8_LIGHT); addChild(lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_8_LIGHT]); lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_9_LIGHT]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(96.213, 80.596)), module, Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_9_LIGHT); addChild(lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_9_LIGHT]); lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_10_LIGHT]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(92.602, 67.654)), module, Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_10_LIGHT); addChild(lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_10_LIGHT]); lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_11_LIGHT]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(95.912, 55.465)), module, Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_11_LIGHT); addChild(lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_11_LIGHT]); lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_12_LIGHT]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(105.393, 46.587)), module, Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_12_LIGHT); addChild(lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_12_LIGHT]); //*********** Harmony step set selection paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_1_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(65.197, 106.483)), module, Meander::BUTTON_HARMONY_SETSTEP_1_PARAM); addParam(paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_1_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_1]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(65.197, 106.483)), module, Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_1); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_1]); paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_2_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(64.918, 98.02)), module, Meander::BUTTON_HARMONY_SETSTEP_2_PARAM); addParam(paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_2_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_2]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(64.918, 98.02)), module, Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_2); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_2]); paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_3_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(65.193, 89.271)), module, Meander::BUTTON_HARMONY_SETSTEP_3_PARAM); addParam(paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_3_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_3]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(65.193, 89.271)), module, Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_3); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_3]); paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_4_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(64.918, 81.9233)), module, Meander::BUTTON_HARMONY_SETSTEP_4_PARAM); addParam(paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_4_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_4]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(64.918, 81.923)), module, Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_4); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_4]); paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_5_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(65.193, 73.184)), module, Meander::BUTTON_HARMONY_SETSTEP_5_PARAM); addParam(paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_5_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_5]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(65.193, 73.184)), module, Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_5); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_5]); paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_6_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(64.918, 66.129)), module, Meander::BUTTON_HARMONY_SETSTEP_6_PARAM); addParam(paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_6_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_6]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(64.918, 66.129)), module, Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_6); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_6]); paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_7_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(65.193, 57.944)), module, Meander::BUTTON_HARMONY_SETSTEP_7_PARAM); addParam(paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_7_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_7]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(65.193, 57.944)), module, Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_7); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_7]); paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_8_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(64.911, 49.474)), module, Meander::BUTTON_HARMONY_SETSTEP_8_PARAM); addParam(paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_8_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_8]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(64.911, 49.474)), module, Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_8); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_8]); paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_9_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(4.629, 41.011)), module, Meander::BUTTON_HARMONY_SETSTEP_9_PARAM); addParam(paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_9_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_9]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(4.629, 41.011)), module, Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_9); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_9]); paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_10_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(64.629, 32.827)), module, Meander::BUTTON_HARMONY_SETSTEP_10_PARAM); addParam(paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_10_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_10]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(64.629, 32.827)), module, Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_10); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_10]); paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_11_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(64.629, 24.649)), module, Meander::BUTTON_HARMONY_SETSTEP_11_PARAM); addParam(paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_11_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_11]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(64.629, 24.649)), module, Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_11); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_11]); paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_12_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(64.632, 16.176)), module, Meander::BUTTON_HARMONY_SETSTEP_12_PARAM); addParam(paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_12_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_12]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(64.632, 16.176)), module, Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_12); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_12]); paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_13_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(64.632, 16.176)), module, Meander::BUTTON_HARMONY_SETSTEP_13_PARAM); addParam(paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_13_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_13]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(64.632, 16.176)), module, Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_13); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_13]); paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_14_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(64.632, 16.176)), module, Meander::BUTTON_HARMONY_SETSTEP_14_PARAM); addParam(paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_14_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_14]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(64.632, 16.176)), module, Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_14); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_14]); paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_15_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(64.632, 16.176)), module, Meander::BUTTON_HARMONY_SETSTEP_15_PARAM); addParam(paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_15_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_15]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(64.632, 16.176)), module, Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_15); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_15]); paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_16_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(64.632, 16.176)), module, Meander::BUTTON_HARMONY_SETSTEP_16_PARAM); addParam(paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_16_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_16]=createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(64.632, 16.176)), module, Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_16); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_16]); //**********General************************ paramWidgets[Meander::BUTTON_RUN_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(19.7, 10.45)), module, Meander::BUTTON_RUN_PARAM); addParam(paramWidgets[Meander::BUTTON_RUN_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_RUN]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(19.7, 10.45)), module, Meander::LIGHT_LEDBUTTON_RUN); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_RUN]); paramWidgets[Meander::BUTTON_RESET_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(19.7, 22.55)), module, Meander::BUTTON_RESET_PARAM); addParam(paramWidgets[Meander::BUTTON_RESET_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_RESET]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(19.7, 22.55)), module, Meander::LIGHT_LEDBUTTON_RESET); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_RESET]); paramWidgets[Meander::CONTROL_TEMPOBPM_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(8.12, 35.4)), module, Meander::CONTROL_TEMPOBPM_PARAM); addParam(paramWidgets[Meander::CONTROL_TEMPOBPM_PARAM]); paramWidgets[Meander::CONTROL_TIMESIGNATURETOP_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(8.12, 47.322+3.0)), module, Meander::CONTROL_TIMESIGNATURETOP_PARAM); addParam(paramWidgets[Meander::CONTROL_TIMESIGNATURETOP_PARAM]); paramWidgets[Meander::CONTROL_TIMESIGNATUREBOTTOM_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(8.12, 54.84+3.0)), module, Meander::CONTROL_TIMESIGNATUREBOTTOM_PARAM); addParam(paramWidgets[Meander::CONTROL_TIMESIGNATUREBOTTOM_PARAM]); paramWidgets[Meander::CONTROL_ROOT_KEY_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(8.12, 68.179)), module, Meander::CONTROL_ROOT_KEY_PARAM); dynamic_cast<Knob*>(paramWidgets[Meander::CONTROL_ROOT_KEY_PARAM])->snap=true; addParam(paramWidgets[Meander::CONTROL_ROOT_KEY_PARAM]); paramWidgets[Meander::CONTROL_SCALE_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(8.12, 78.675)), module, Meander::CONTROL_SCALE_PARAM); dynamic_cast<Knob*>(paramWidgets[Meander::CONTROL_SCALE_PARAM])->snap=true; addParam(paramWidgets[Meander::CONTROL_SCALE_PARAM]); //***************Harmony****************** paramWidgets[Meander::BUTTON_ENABLE_HARMONY_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(173.849, 12.622)), module, Meander::BUTTON_ENABLE_HARMONY_PARAM); addParam(paramWidgets[Meander::BUTTON_ENABLE_HARMONY_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_HARMONY_ENABLE]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(173.849, 12.622)), module, Meander::LIGHT_LEDBUTTON_HARMONY_ENABLE); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_HARMONY_ENABLE]); paramWidgets[Meander::CONTROL_HARMONY_VOLUME_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(173.849, 20.384)), module, Meander::CONTROL_HARMONY_VOLUME_PARAM); addParam(paramWidgets[Meander::CONTROL_HARMONY_VOLUME_PARAM]); paramWidgets[Meander::CONTROL_HARMONY_STEPS_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(174.028, 28)), module, Meander::CONTROL_HARMONY_STEPS_PARAM); dynamic_cast<Knob*>(paramWidgets[Meander::CONTROL_HARMONY_STEPS_PARAM])->snap=true; addParam(paramWidgets[Meander::CONTROL_HARMONY_STEPS_PARAM]); paramWidgets[Meander::CONTROL_HARMONY_TARGETOCTAVE_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(174.01, 37.396)), module, Meander::CONTROL_HARMONY_TARGETOCTAVE_PARAM); dynamic_cast<Knob*>(paramWidgets[Meander::CONTROL_HARMONY_TARGETOCTAVE_PARAM])->snap=true; addParam(paramWidgets[Meander::CONTROL_HARMONY_TARGETOCTAVE_PARAM]); paramWidgets[Meander::CONTROL_HARMONY_ALPHA_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(174.27, 45.982)), module, Meander::CONTROL_HARMONY_ALPHA_PARAM); addParam(paramWidgets[Meander::CONTROL_HARMONY_ALPHA_PARAM]); paramWidgets[Meander::CONTROL_HARMONY_RANGE_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(173.991, 53.788)), module, Meander::CONTROL_HARMONY_RANGE_PARAM); addParam(paramWidgets[Meander::CONTROL_HARMONY_RANGE_PARAM]); paramWidgets[Meander::CONTROL_HARMONY_DIVISOR_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(173.953, 62.114)), module, Meander::CONTROL_HARMONY_DIVISOR_PARAM); dynamic_cast<Knob*>(paramWidgets[Meander::CONTROL_HARMONY_DIVISOR_PARAM])->snap=true; addParam(paramWidgets[Meander::CONTROL_HARMONY_DIVISOR_PARAM]); paramWidgets[Meander::BUTTON_ENABLE_HARMONY_ALL7THS_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(173.849, 69)), module, Meander::BUTTON_ENABLE_HARMONY_ALL7THS_PARAM); addParam(paramWidgets[Meander::BUTTON_ENABLE_HARMONY_ALL7THS_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_ENABLE_HARMONY_ALL7THS_PARAM]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(173.849, 69)), module, Meander::LIGHT_LEDBUTTON_ENABLE_HARMONY_ALL7THS_PARAM); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_ENABLE_HARMONY_ALL7THS_PARAM]); paramWidgets[Meander::BUTTON_ENABLE_HARMONY_V7THS_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(203.849, 69)), module, Meander::BUTTON_ENABLE_HARMONY_V7THS_PARAM); addParam(paramWidgets[Meander::BUTTON_ENABLE_HARMONY_V7THS_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_ENABLE_HARMONY_V7THS_PARAM]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(203.849, 69)), module, Meander::LIGHT_LEDBUTTON_ENABLE_HARMONY_V7THS_PARAM); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_ENABLE_HARMONY_V7THS_PARAM]); paramWidgets[Meander::BUTTON_ENABLE_HARMONY_STACCATO_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(173.849, 75)), module, Meander::BUTTON_ENABLE_HARMONY_STACCATO_PARAM); addParam(paramWidgets[Meander::BUTTON_ENABLE_HARMONY_STACCATO_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_ENABLE_HARMONY_STACCATO_PARAM]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(173.849, 75)), module, Meander::LIGHT_LEDBUTTON_ENABLE_HARMONY_STACCATO_PARAM); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_ENABLE_HARMONY_STACCATO_PARAM]); paramWidgets[Meander::CONTROL_HARMONYPRESETS_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(174.027, 81.524)), module, Meander::CONTROL_HARMONYPRESETS_PARAM); dynamic_cast<Knob*>(paramWidgets[Meander::CONTROL_HARMONYPRESETS_PARAM])->snap=true; addParam(paramWidgets[Meander::CONTROL_HARMONYPRESETS_PARAM]); //**************Melody******************** paramWidgets[Meander::BUTTON_ENABLE_MELODY_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(240.353, 10.986)), module, Meander::BUTTON_ENABLE_MELODY_PARAM); addParam(paramWidgets[Meander::BUTTON_ENABLE_MELODY_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_MELODY_ENABLE]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(240.353, 10.986)), module, Meander::LIGHT_LEDBUTTON_MELODY_ENABLE); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_MELODY_ENABLE]); paramWidgets[Meander::BUTTON_ENABLE_MELODY_CHORDAL_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(270.353, 10.986)), module, Meander::BUTTON_ENABLE_MELODY_CHORDAL_PARAM); addParam(paramWidgets[Meander::BUTTON_ENABLE_MELODY_CHORDAL_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_MELODY_ENABLE_CHORDAL]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(270.353, 10.986)), module, Meander::LIGHT_LEDBUTTON_MELODY_ENABLE_CHORDAL); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_MELODY_ENABLE_CHORDAL]); paramWidgets[Meander::BUTTON_ENABLE_MELODY_SCALER_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(287.274, 10.986)), module, Meander::BUTTON_ENABLE_MELODY_SCALER_PARAM); addParam(paramWidgets[Meander::BUTTON_ENABLE_MELODY_SCALER_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_MELODY_ENABLE_SCALER]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(287.274, 10.986)), module, Meander::LIGHT_LEDBUTTON_MELODY_ENABLE_SCALER); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_MELODY_ENABLE_SCALER]); paramWidgets[Meander::BUTTON_MELODY_DESTUTTER_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(240.409, 25.524)), module, Meander::BUTTON_MELODY_DESTUTTER_PARAM); addParam(paramWidgets[Meander::BUTTON_MELODY_DESTUTTER_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_MELODY_DESTUTTER]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(240.409, 25.524)), module, Meander::LIGHT_LEDBUTTON_MELODY_DESTUTTER); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_MELODY_DESTUTTER]); paramWidgets[Meander::CONTROL_MELODY_VOLUME_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(240.353, 19.217)), module, Meander::CONTROL_MELODY_VOLUME_PARAM); addParam(paramWidgets[Meander::CONTROL_MELODY_VOLUME_PARAM]); paramWidgets[Meander::CONTROL_MELODY_NOTE_LENGTH_DIVISOR_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(240.353, 32.217)), module, Meander::CONTROL_MELODY_NOTE_LENGTH_DIVISOR_PARAM); dynamic_cast<Knob*>(paramWidgets[Meander::CONTROL_MELODY_NOTE_LENGTH_DIVISOR_PARAM])->snap=true; addParam(paramWidgets[Meander::CONTROL_MELODY_NOTE_LENGTH_DIVISOR_PARAM]); paramWidgets[Meander::CONTROL_MELODY_TARGETOCTAVE_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(240.353, 39.217)), module, Meander::CONTROL_MELODY_TARGETOCTAVE_PARAM); dynamic_cast<Knob*>(paramWidgets[Meander::CONTROL_MELODY_TARGETOCTAVE_PARAM])->snap=true; addParam(paramWidgets[Meander::CONTROL_MELODY_TARGETOCTAVE_PARAM]); paramWidgets[Meander::CONTROL_MELODY_ALPHA_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(240.334, 47.803)), module, Meander::CONTROL_MELODY_ALPHA_PARAM); addParam(paramWidgets[Meander::CONTROL_MELODY_ALPHA_PARAM]); paramWidgets[Meander::CONTROL_MELODY_RANGE_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(240.334, 55.33)), module, Meander::CONTROL_MELODY_RANGE_PARAM); addParam(paramWidgets[Meander::CONTROL_MELODY_RANGE_PARAM]); //*******************Arp******************** paramWidgets[Meander::BUTTON_ENABLE_ARP_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(240.274, 62.01)), module, Meander::BUTTON_ENABLE_ARP_PARAM); addParam(paramWidgets[Meander::BUTTON_ENABLE_ARP_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_ARP_ENABLE]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(240.274, 62.01)), module, Meander::LIGHT_LEDBUTTON_ARP_ENABLE); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_ARP_ENABLE]); paramWidgets[Meander::BUTTON_ENABLE_ARP_CHORDAL_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(265.274, 62.01)), module, Meander::BUTTON_ENABLE_ARP_CHORDAL_PARAM); addParam(paramWidgets[Meander::BUTTON_ENABLE_ARP_CHORDAL_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_ARP_ENABLE_CHORDAL]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(265.274, 62.01)), module, Meander::LIGHT_LEDBUTTON_ARP_ENABLE_CHORDAL); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_ARP_ENABLE_CHORDAL]); paramWidgets[Meander::BUTTON_ENABLE_ARP_SCALER_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(283.274, 62.01)), module, Meander::BUTTON_ENABLE_ARP_SCALER_PARAM); addParam(paramWidgets[Meander::BUTTON_ENABLE_ARP_SCALER_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_ARP_ENABLE_SCALER]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(283.274, 62.01)), module, Meander::LIGHT_LEDBUTTON_ARP_ENABLE_SCALER); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_ARP_ENABLE_SCALER]); paramWidgets[Meander::CONTROL_ARP_COUNT_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(240.274, 68.014)), module, Meander::CONTROL_ARP_COUNT_PARAM); dynamic_cast<Knob*>(paramWidgets[Meander::CONTROL_ARP_COUNT_PARAM])->snap=true; addParam(paramWidgets[Meander::CONTROL_ARP_COUNT_PARAM]); paramWidgets[Meander::BUTTON_ENABLE_MELODY_STACCATO_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(240.274, 75)), module, Meander::BUTTON_ENABLE_MELODY_STACCATO_PARAM); addParam(paramWidgets[Meander::BUTTON_ENABLE_MELODY_STACCATO_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_ENABLE_MELODY_STACCATO_PARAM]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(240.274, 75)), module, Meander::LIGHT_LEDBUTTON_ENABLE_MELODY_STACCATO_PARAM); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_ENABLE_MELODY_STACCATO_PARAM]); paramWidgets[Meander::CONTROL_ARP_INCREMENT_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(240.256, 82.807)), module, Meander::CONTROL_ARP_INCREMENT_PARAM); dynamic_cast<Knob*>(paramWidgets[Meander::CONTROL_ARP_INCREMENT_PARAM])->snap=true; addParam(paramWidgets[Meander::CONTROL_ARP_INCREMENT_PARAM]); paramWidgets[Meander::CONTROL_ARP_DECAY_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(240.237, 91.691)), module, Meander::CONTROL_ARP_DECAY_PARAM); addParam(paramWidgets[Meander::CONTROL_ARP_DECAY_PARAM]); paramWidgets[Meander::CONTROL_ARP_PATTERN_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(240.757, 99.497)), module, Meander::CONTROL_ARP_PATTERN_PARAM); dynamic_cast<Knob*>(paramWidgets[Meander::CONTROL_ARP_PATTERN_PARAM])->snap=true; addParam(paramWidgets[Meander::CONTROL_ARP_PATTERN_PARAM]); //*************Bass******************** paramWidgets[Meander::BUTTON_ENABLE_BASS_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(305, 10.378)), module, Meander::BUTTON_ENABLE_BASS_PARAM); addParam(paramWidgets[Meander::BUTTON_ENABLE_BASS_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_BASS_ENABLE]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(305, 10.378)), module, Meander::LIGHT_LEDBUTTON_BASS_ENABLE); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_BASS_ENABLE]); paramWidgets[Meander::CONTROL_BASS_VOLUME_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(305, 21.217)), module, Meander::CONTROL_BASS_VOLUME_PARAM); addParam(paramWidgets[Meander::CONTROL_BASS_VOLUME_PARAM]); paramWidgets[Meander::CONTROL_BASS_TARGETOCTAVE_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(305, 29.217)), module, Meander::CONTROL_BASS_TARGETOCTAVE_PARAM); dynamic_cast<Knob*>(paramWidgets[Meander::CONTROL_BASS_TARGETOCTAVE_PARAM])->snap=true; addParam(paramWidgets[Meander::CONTROL_BASS_TARGETOCTAVE_PARAM]); paramWidgets[Meander::BUTTON_BASS_ACCENT_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(305, 37.217)), module, Meander::BUTTON_BASS_ACCENT_PARAM); addParam(paramWidgets[Meander::BUTTON_BASS_ACCENT_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_BASS_ACCENT_PARAM]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(305, 37.217)), module, Meander::LIGHT_LEDBUTTON_BASS_ACCENT_PARAM); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_BASS_ACCENT_PARAM]); paramWidgets[Meander::BUTTON_BASS_SYNCOPATE_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(305, 45.217)), module, Meander::BUTTON_BASS_SYNCOPATE_PARAM); addParam(paramWidgets[Meander::BUTTON_BASS_SYNCOPATE_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_BASS_SYNCOPATE_PARAM]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(305, 45.217)), module, Meander::LIGHT_LEDBUTTON_BASS_SYNCOPATE_PARAM); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_BASS_SYNCOPATE_PARAM]); paramWidgets[Meander::BUTTON_BASS_SHUFFLE_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(305, 53.217)), module, Meander::BUTTON_BASS_SHUFFLE_PARAM); addParam(paramWidgets[Meander::BUTTON_BASS_SHUFFLE_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_BASS_SHUFFLE_PARAM]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(305, 53.217)), module, Meander::LIGHT_LEDBUTTON_BASS_SHUFFLE_PARAM); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_BASS_SHUFFLE_PARAM]); paramWidgets[Meander::BUTTON_BASS_OCTAVES_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(305, 53.217)), module, Meander::BUTTON_BASS_OCTAVES_PARAM); addParam(paramWidgets[Meander::BUTTON_BASS_OCTAVES_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_BASS_OCTAVES_PARAM]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(305, 53.217)), module, Meander::LIGHT_LEDBUTTON_BASS_OCTAVES_PARAM); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_BASS_OCTAVES_PARAM]); paramWidgets[Meander::CONTROL_BASS_DIVISOR_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(305, 61.217)), module, Meander::CONTROL_BASS_DIVISOR_PARAM); dynamic_cast<Knob*>(paramWidgets[Meander::CONTROL_BASS_DIVISOR_PARAM])->snap=true; addParam(paramWidgets[Meander::CONTROL_BASS_DIVISOR_PARAM]); paramWidgets[Meander::BUTTON_ENABLE_BASS_STACCATO_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(305, 70)), module, Meander::BUTTON_ENABLE_BASS_STACCATO_PARAM); addParam(paramWidgets[Meander::BUTTON_ENABLE_BASS_STACCATO_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_ENABLE_BASS_STACCATO_PARAM]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(305, 70)), module, Meander::LIGHT_LEDBUTTON_ENABLE_BASS_STACCATO_PARAM); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_ENABLE_BASS_STACCATO_PARAM]); //**************fBm************************ paramWidgets[Meander::CONTROL_HARMONY_FBM_OCTAVES_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(358, 19)), module, Meander::CONTROL_HARMONY_FBM_OCTAVES_PARAM); dynamic_cast<Knob*>(paramWidgets[Meander::CONTROL_HARMONY_FBM_OCTAVES_PARAM])->snap=true; addParam(paramWidgets[Meander::CONTROL_HARMONY_FBM_OCTAVES_PARAM]); paramWidgets[Meander::CONTROL_HARMONY_FBM_PERIOD_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(358, 25)), module, Meander::CONTROL_HARMONY_FBM_PERIOD_PARAM); addParam(paramWidgets[Meander::CONTROL_HARMONY_FBM_PERIOD_PARAM]); paramWidgets[Meander::CONTROL_MELODY_FBM_OCTAVES_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(358, 34)), module, Meander::CONTROL_MELODY_FBM_OCTAVES_PARAM); dynamic_cast<Knob*>(paramWidgets[Meander::CONTROL_MELODY_FBM_OCTAVES_PARAM])->snap=true; addParam(paramWidgets[Meander::CONTROL_MELODY_FBM_OCTAVES_PARAM]); paramWidgets[Meander::CONTROL_MELODY_FBM_PERIOD_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(358, 43)), module, Meander::CONTROL_MELODY_FBM_PERIOD_PARAM); addParam(paramWidgets[Meander::CONTROL_MELODY_FBM_PERIOD_PARAM]); paramWidgets[Meander::CONTROL_ARP_FBM_OCTAVES_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(358, 51)), module, Meander::CONTROL_ARP_FBM_OCTAVES_PARAM); dynamic_cast<Knob*>(paramWidgets[Meander::CONTROL_ARP_FBM_OCTAVES_PARAM])->snap=true; addParam(paramWidgets[Meander::CONTROL_ARP_FBM_OCTAVES_PARAM]); paramWidgets[Meander::CONTROL_ARP_FBM_PERIOD_PARAM]=createParamCentered<Trimpot>(mm2px(Vec(358, 59)), module, Meander::CONTROL_ARP_FBM_PERIOD_PARAM); addParam(paramWidgets[Meander::CONTROL_ARP_FBM_PERIOD_PARAM]); // Progression control paramWidgets[Meander::BUTTON_PROG_STEP_PARAM]=createParamCentered<LEDButton>(mm2px(Vec(350, 250)), module, Meander::BUTTON_PROG_STEP_PARAM); addParam(paramWidgets[Meander::BUTTON_PROG_STEP_PARAM]); lightWidgets[Meander::LIGHT_LEDBUTTON_PROG_STEP_PARAM]=createLightCentered<MediumLight<RedLight>>(mm2px(Vec(350, 250)), module, Meander::LIGHT_LEDBUTTON_PROG_STEP_PARAM); addChild(lightWidgets[Meander::LIGHT_LEDBUTTON_PROG_STEP_PARAM]); //************** // add input ports for (int i=0; i<Meander::NUM_INPUTS; ++i) { if (i==Meander::IN_HARMONY_DESTUTTER_EXT_CV) // this inport is not used, so set to null inPortWidgets[i]=NULL; else { inPortWidgets[i]=createInputCentered<TinyPJ301MPort>(mm2px(Vec(10*i,5)), module, i); // temporarily place them along the top before they are repositioned above addInput(inPortWidgets[i]); } } // add output ports outPortWidgets[Meander::OUT_RUN_OUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(30.2, 10.95)), module, Meander::OUT_RUN_OUT); addOutput(outPortWidgets[Meander::OUT_RUN_OUT]); outPortWidgets[Meander::OUT_RESET_OUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(30.2, 23.35)), module, Meander::OUT_RESET_OUT); addOutput(outPortWidgets[Meander::OUT_RESET_OUT]); outPortWidgets[Meander::OUT_MELODY_VOLUME_OUTPUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(266.982, 107.333)), module, Meander::OUT_MELODY_VOLUME_OUTPUT); addOutput(outPortWidgets[Meander::OUT_MELODY_VOLUME_OUTPUT]); outPortWidgets[Meander::OUT_HARMONY_VOLUME_OUTPUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(201.789, 107.616)), module, Meander::OUT_HARMONY_VOLUME_OUTPUT); addOutput(outPortWidgets[Meander::OUT_HARMONY_VOLUME_OUTPUT]); outPortWidgets[Meander::OUT_BASS_VOLUME_OUTPUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(325.12, 107.616)), module, Meander::OUT_BASS_VOLUME_OUTPUT); addOutput(outPortWidgets[Meander::OUT_BASS_VOLUME_OUTPUT]); outPortWidgets[Meander::OUT_MELODY_CV_OUTPUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(266.899, 115.813)), module, Meander::OUT_MELODY_CV_OUTPUT); addOutput(outPortWidgets[Meander::OUT_MELODY_CV_OUTPUT]); outPortWidgets[Meander::OUT_BASS_CV_OUTPUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(325.266, 115.817)), module, Meander::OUT_BASS_CV_OUTPUT); addOutput(outPortWidgets[Meander::OUT_BASS_CV_OUTPUT]); outPortWidgets[Meander::OUT_HARMONY_CV_OUTPUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(202.176, 115.909)), module, Meander::OUT_HARMONY_CV_OUTPUT); addOutput(outPortWidgets[Meander::OUT_HARMONY_CV_OUTPUT]); outPortWidgets[Meander::OUT_CLOCK_BEATX2_OUTPUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(78.74, 122.291)), module, Meander::OUT_CLOCK_BEATX2_OUTPUT); addOutput(outPortWidgets[Meander::OUT_CLOCK_BEATX2_OUTPUT]); outPortWidgets[Meander::OUT_CLOCK_BAR_OUTPUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(37.143, 122.537)), module, Meander::OUT_CLOCK_BAR_OUTPUT); addOutput(outPortWidgets[Meander::OUT_CLOCK_BAR_OUTPUT]); outPortWidgets[Meander::OUT_CLOCK_BEATX4_OUTPUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(99.342, 122.573)), module, Meander::OUT_CLOCK_BEATX4_OUTPUT); addOutput(outPortWidgets[Meander::OUT_CLOCK_BEATX4_OUTPUT]); outPortWidgets[Meander::OUT_CLOCK_BEATX8_OUTPUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(121.073, 122.573)), module, Meander::OUT_CLOCK_BEATX8_OUTPUT); addOutput(outPortWidgets[Meander::OUT_CLOCK_BEATX8_OUTPUT]); outPortWidgets[Meander::OUT_CLOCK_BEAT_OUTPUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(57.856, 122.856)), module, Meander::OUT_CLOCK_BEAT_OUTPUT); addOutput(outPortWidgets[Meander::OUT_CLOCK_BEAT_OUTPUT]); outPortWidgets[Meander::OUT_BASS_GATE_OUTPUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(325.402, 123.984)), module, Meander::OUT_BASS_GATE_OUTPUT); addOutput(outPortWidgets[Meander::OUT_BASS_GATE_OUTPUT]); outPortWidgets[Meander::OUT_HARMONY_GATE_OUTPUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(202.071, 124.267)), module, Meander::OUT_HARMONY_GATE_OUTPUT); addOutput(outPortWidgets[Meander::OUT_HARMONY_GATE_OUTPUT]); outPortWidgets[Meander::OUT_MELODY_GATE_OUTPUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(266.982, 124.549)), module, Meander::OUT_MELODY_GATE_OUTPUT); addOutput(outPortWidgets[Meander::OUT_MELODY_GATE_OUTPUT]); outPortWidgets[Meander::OUT_FBM_HARMONY_OUTPUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(380.0, 107.616)), module, Meander::OUT_FBM_HARMONY_OUTPUT); addOutput(outPortWidgets[Meander::OUT_FBM_HARMONY_OUTPUT]); outPortWidgets[Meander::OUT_FBM_MELODY_OUTPUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(380.0, 115.815)), module, Meander::OUT_FBM_MELODY_OUTPUT); addOutput(outPortWidgets[Meander::OUT_FBM_MELODY_OUTPUT]); outPortWidgets[Meander::OUT_FBM_ARP_OUTPUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(380.0, 124.831)), module, Meander::OUT_FBM_ARP_OUTPUT); addOutput(outPortWidgets[Meander::OUT_FBM_ARP_OUTPUT]); outPortWidgets[Meander::OUT_EXT_POLY_SCALE_OUTPUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(380.0, 124.831)), module, Meander::OUT_EXT_POLY_SCALE_OUTPUT); addOutput(outPortWidgets[Meander::OUT_EXT_POLY_SCALE_OUTPUT]); outPortWidgets[Meander::OUT_CLOCK_OUT]=createOutputCentered<PJ301MPort>(mm2px(Vec(45.0, 350.0)), module, Meander::OUT_CLOCK_OUT); addOutput(outPortWidgets[Meander::OUT_CLOCK_OUT]); //********************************** // now, procedurally rearrange the control param panel locations Vec CircleCenter= Vec(mm2px(116.75),mm2px(67.75)); float OuterCircleRadius=mm2px(39); float InnerCircleRadius3=mm2px(26); // re-layout the circle BUTTONS and LIGHTS programatically // does not draw circles and segments and text. That is done by drawCircleOf5ths() for(int i = 0; i<MAX_NOTES;++i) { const float rotate90 = (M_PI) / 2.0; double startDegree = (M_PI * 2.0 * ((double)i - 0.5) / MAX_NOTES) - rotate90; double endDegree = (M_PI * 2.0 * ((double)i + 0.5) / MAX_NOTES) - rotate90; double x1= cos(startDegree) * InnerCircleRadius3 + CircleCenter.x; double y1= sin(startDegree) * InnerCircleRadius3 + CircleCenter.y; double x2= cos(endDegree) * InnerCircleRadius3 + CircleCenter.x; double y2= sin(endDegree) * InnerCircleRadius3 + CircleCenter.y; Vec radialLine1=Vec(x1,y1).minus(CircleCenter); Vec radialLine2=Vec(x2,y2).minus(CircleCenter); Vec centerLine=(radialLine1.plus(radialLine2)).div(2.); Vec radialDirection=centerLine.normalize(); Vec controlPosition=CircleCenter.plus(radialDirection.mult(OuterCircleRadius*.78f)); controlPosition=controlPosition.minus((paramWidgets[Meander::BUTTON_CIRCLESTEP_C_PARAM+i]->box.size).div(2.)); // adjust for box size paramWidgets[Meander::BUTTON_CIRCLESTEP_C_PARAM+i]->box.pos=controlPosition; controlPosition=CircleCenter.plus(radialDirection.mult(OuterCircleRadius*.78f)); controlPosition=controlPosition.minus((lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_1+i]->box.size).div(2.)); // adjust for box size lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESTEP_1+i]->box.pos=controlPosition; controlPosition=CircleCenter.plus(radialDirection.mult(OuterCircleRadius*.61f)); controlPosition=controlPosition.minus((lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_1_LIGHT+i]->box.size).div(2.)); lightWidgets[Meander::LIGHT_CIRCLE_ROOT_KEY_POSITION_1_LIGHT+i]->box.pos=controlPosition; } // re-layout the circle step set buttons and lights programatically Vec start_position=Vec(0,0); float verticalIncrement=mm2px(5.92f); for(int i = 0; i<MAX_STEPS;++i) { start_position=mm2px(Vec(62, 128.9- 109.27)); // for Y subtract SVG Y from panel height 128.9 and then convert to px Vec buttonPosition=start_position.plus(Vec(0, (i*verticalIncrement))); buttonPosition.y -= paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_1_PARAM+i]->box.size.y; // adjust for box height paramWidgets[Meander::BUTTON_HARMONY_SETSTEP_1_PARAM+i]->box.pos=buttonPosition; start_position=mm2px(Vec(63.5, 128.9- 110.8)); // for Y subtract SVG Y from panel height 128.9 and then convert to px buttonPosition=start_position.plus(Vec(0, (i*verticalIncrement))); buttonPosition.y -= lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_1+i]->box.size.y; // adjust for box height lightWidgets[Meander::LIGHT_LEDBUTTON_CIRCLESETSTEP_1+i]->box.pos=buttonPosition; } // relayout all param controls and lights Vec drawCenter=Vec(5., 30.); // do upper left controls and ports drawCenter=drawCenter.plus(Vec(37,0)); paramWidgets[Meander::BUTTON_RUN_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_RUN_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_RUN]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_RUN]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(37,0)); outPortWidgets[Meander::OUT_RUN_OUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_RUN_OUT]->box.size.div(2.)); drawCenter=drawCenter.minus(Vec(37,0)); drawCenter=drawCenter.plus(Vec(0,40)); paramWidgets[Meander::BUTTON_RESET_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_RESET_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_RESET]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_RESET]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(37,0)); outPortWidgets[Meander::OUT_RESET_OUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_RESET_OUT]->box.size.div(2.)); drawCenter=Vec(42., 110.); paramWidgets[Meander::CONTROL_TEMPOBPM_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_TEMPOBPM_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,25)); paramWidgets[Meander::CONTROL_TIMESIGNATURETOP_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_TIMESIGNATURETOP_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,25)); paramWidgets[Meander::CONTROL_TIMESIGNATUREBOTTOM_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_TIMESIGNATUREBOTTOM_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,25)); paramWidgets[Meander::CONTROL_ROOT_KEY_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_ROOT_KEY_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,25)); paramWidgets[Meander::CONTROL_SCALE_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_SCALE_PARAM]->box.size.div(2.)); // redo all harmony controls positions drawCenter=Vec(512., 40.); paramWidgets[Meander::BUTTON_ENABLE_HARMONY_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_ENABLE_HARMONY_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_HARMONY_ENABLE]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_HARMONY_ENABLE]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_HARMONY_VOLUME_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_HARMONY_VOLUME_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(-20,22)); inPortWidgets[Meander::IN_HARMONY_STEPS_EXT_CV]->box.pos=drawCenter.minus(inPortWidgets[Meander::IN_HARMONY_STEPS_EXT_CV]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(20,0)); paramWidgets[Meander::CONTROL_HARMONY_STEPS_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_HARMONY_STEPS_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_HARMONY_TARGETOCTAVE_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_HARMONY_TARGETOCTAVE_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_HARMONY_ALPHA_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_HARMONY_ALPHA_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_HARMONY_RANGE_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_HARMONY_RANGE_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_HARMONY_DIVISOR_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_HARMONY_DIVISOR_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::BUTTON_ENABLE_HARMONY_ALL7THS_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_ENABLE_HARMONY_ALL7THS_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_ENABLE_HARMONY_ALL7THS_PARAM]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_ENABLE_HARMONY_ALL7THS_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(85,0)); paramWidgets[Meander::BUTTON_ENABLE_HARMONY_V7THS_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_ENABLE_HARMONY_V7THS_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_ENABLE_HARMONY_V7THS_PARAM]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_ENABLE_HARMONY_V7THS_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(-85,22)); paramWidgets[Meander::BUTTON_ENABLE_HARMONY_STACCATO_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_ENABLE_HARMONY_STACCATO_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_ENABLE_HARMONY_STACCATO_PARAM]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_ENABLE_HARMONY_STACCATO_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_HARMONYPRESETS_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_HARMONYPRESETS_PARAM]->box.size.div(2.)); // redo all melody controls positions drawCenter=Vec(710., 40.); paramWidgets[Meander::BUTTON_ENABLE_MELODY_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_ENABLE_MELODY_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_MELODY_ENABLE]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_MELODY_ENABLE]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_MELODY_VOLUME_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_MELODY_VOLUME_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_MELODY_NOTE_LENGTH_DIVISOR_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_MELODY_NOTE_LENGTH_DIVISOR_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_MELODY_TARGETOCTAVE_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_MELODY_TARGETOCTAVE_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_MELODY_ALPHA_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_MELODY_ALPHA_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_MELODY_RANGE_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_MELODY_RANGE_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::BUTTON_MELODY_DESTUTTER_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_MELODY_DESTUTTER_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_MELODY_DESTUTTER]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_MELODY_DESTUTTER]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(90,0)); paramWidgets[Meander::BUTTON_ENABLE_MELODY_STACCATO_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_ENABLE_MELODY_STACCATO_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_ENABLE_MELODY_STACCATO_PARAM]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_ENABLE_MELODY_STACCATO_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(-90,22)); paramWidgets[Meander::BUTTON_ENABLE_MELODY_CHORDAL_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_ENABLE_MELODY_CHORDAL_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_MELODY_ENABLE_CHORDAL]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_MELODY_ENABLE_CHORDAL]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(90,0)); paramWidgets[Meander::BUTTON_ENABLE_MELODY_SCALER_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_ENABLE_MELODY_SCALER_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_MELODY_ENABLE_SCALER]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_MELODY_ENABLE_SCALER]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(-90,0)); // arp drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::BUTTON_ENABLE_ARP_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_ENABLE_ARP_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_ARP_ENABLE]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_ARP_ENABLE]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_ARP_COUNT_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_ARP_COUNT_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_ARP_INCREMENT_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_ARP_INCREMENT_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_ARP_DECAY_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_ARP_DECAY_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_ARP_PATTERN_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_ARP_PATTERN_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::BUTTON_ENABLE_ARP_CHORDAL_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_ENABLE_ARP_CHORDAL_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_ARP_ENABLE_CHORDAL]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_ARP_ENABLE_CHORDAL]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(90,0)); paramWidgets[Meander::BUTTON_ENABLE_ARP_SCALER_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_ENABLE_ARP_SCALER_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_ARP_ENABLE_SCALER]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_ARP_ENABLE_SCALER]->box.size.div(2.)); drawCenter=Vec(900., 130.); paramWidgets[Meander::BUTTON_ENABLE_BASS_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_ENABLE_BASS_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_BASS_ENABLE]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_BASS_ENABLE]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_BASS_VOLUME_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_BASS_VOLUME_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_BASS_TARGETOCTAVE_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_BASS_TARGETOCTAVE_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_BASS_DIVISOR_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_BASS_DIVISOR_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::BUTTON_ENABLE_BASS_STACCATO_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_ENABLE_BASS_STACCATO_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_ENABLE_BASS_STACCATO_PARAM]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_ENABLE_BASS_STACCATO_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::BUTTON_BASS_ACCENT_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_BASS_ACCENT_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_BASS_ACCENT_PARAM]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_BASS_ACCENT_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::BUTTON_BASS_SYNCOPATE_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_BASS_SYNCOPATE_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_BASS_SYNCOPATE_PARAM]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_BASS_SYNCOPATE_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::BUTTON_BASS_SHUFFLE_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_BASS_SHUFFLE_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_BASS_SHUFFLE_PARAM]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_BASS_SHUFFLE_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::BUTTON_BASS_OCTAVES_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_BASS_OCTAVES_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_BASS_OCTAVES_PARAM]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_BASS_OCTAVES_PARAM]->box.size.div(2.)); // fBm controls drawCenter=Vec(1055., 150.); paramWidgets[Meander::CONTROL_HARMONY_FBM_OCTAVES_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_HARMONY_FBM_OCTAVES_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_HARMONY_FBM_PERIOD_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_HARMONY_FBM_PERIOD_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,33)); paramWidgets[Meander::CONTROL_MELODY_FBM_OCTAVES_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_MELODY_FBM_OCTAVES_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_MELODY_FBM_PERIOD_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_MELODY_FBM_PERIOD_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,33)); paramWidgets[Meander::CONTROL_ARP_FBM_OCTAVES_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_ARP_FBM_OCTAVES_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); paramWidgets[Meander::CONTROL_ARP_FBM_PERIOD_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::CONTROL_ARP_FBM_PERIOD_PARAM]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(0,22)); drawCenter=Vec(345., 250.); paramWidgets[Meander::BUTTON_PROG_STEP_PARAM]->box.pos=drawCenter.minus(paramWidgets[Meander::BUTTON_PROG_STEP_PARAM]->box.size.div(2.)); lightWidgets[Meander::LIGHT_LEDBUTTON_PROG_STEP_PARAM]->box.pos=drawCenter.minus(lightWidgets[Meander::LIGHT_LEDBUTTON_PROG_STEP_PARAM]->box.size.div(2.)); // re-layout all input ports. Work around parm and input enum value mismatch due to history for (int i=0; i<Meander::NUM_INPUTS; ++i) { if (i<=Meander::IN_SCALE_EXT_CV) { if ((inPortWidgets[i]!=NULL)&&(paramWidgets[i]!=NULL)) inPortWidgets[i]->box.pos= paramWidgets[i]->box.pos.minus(Vec(20,-1)); } else if (i==Meander::IN_CLOCK_EXT_CV) { Vec drawCenter=Vec(20., 335.); // raise panel vertical position a bit to not conflict with CPU meter display inPortWidgets[Meander::IN_CLOCK_EXT_CV]->box.pos=drawCenter.minus(inPortWidgets[Meander::IN_CLOCK_EXT_CV]->box.size.div(2.)); } else if (i==Meander::IN_HARMONY_CIRCLE_DEGREE_EXT_CV) { Vec drawCenter=Vec(345., 210.); inPortWidgets[Meander::IN_HARMONY_CIRCLE_DEGREE_EXT_CV]->box.pos=drawCenter.minus(inPortWidgets[Meander::IN_HARMONY_CIRCLE_DEGREE_EXT_CV]->box.size.div(2.)); } else if (i==Meander::IN_HARMONY_CIRCLE_DEGREE_GATE_EXT_CV) { Vec drawCenter=Vec(345., 230.); inPortWidgets[Meander::IN_HARMONY_CIRCLE_DEGREE_GATE_EXT_CV]->box.pos=drawCenter.minus(inPortWidgets[Meander::IN_HARMONY_CIRCLE_DEGREE_GATE_EXT_CV]->box.size.div(2.)); } else if (i==Meander::IN_MELODY_SCALE_DEGREE_EXT_CV) { Vec drawCenter=Vec(512.+290, 31.); inPortWidgets[Meander::IN_MELODY_SCALE_DEGREE_EXT_CV]->box.pos=drawCenter.minus(inPortWidgets[Meander::IN_MELODY_SCALE_DEGREE_EXT_CV]->box.size.div(2.)); } else if (i==Meander::IN_MELODY_SCALE_GATE_EXT_CV) { Vec drawCenter=Vec(512.+290, 47.); inPortWidgets[Meander::IN_MELODY_SCALE_GATE_EXT_CV]->box.pos=drawCenter.minus(inPortWidgets[Meander::IN_MELODY_SCALE_GATE_EXT_CV]->box.size.div(2.)); } else { int parmIndex=Meander::BUTTON_ENABLE_MELODY_PARAM+i-Meander::IN_HARMONY_CIRCLE_DEGREE_GATE_EXT_CV-1; if ((inPortWidgets[i]!=NULL)&&(paramWidgets[parmIndex]!=NULL)) inPortWidgets[i]->box.pos= paramWidgets[parmIndex]->box.pos.minus(Vec(20,-1)); } } // re-layout all output port drawCenter=Vec(520., 365.); outPortWidgets[Meander::OUT_HARMONY_CV_OUTPUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_HARMONY_CV_OUTPUT]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(60,0)); outPortWidgets[Meander::OUT_HARMONY_GATE_OUTPUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_HARMONY_GATE_OUTPUT]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(60,0)); outPortWidgets[Meander::OUT_HARMONY_VOLUME_OUTPUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_HARMONY_VOLUME_OUTPUT]->box.size.div(2.)); drawCenter=Vec(717., 365.); outPortWidgets[Meander::OUT_MELODY_CV_OUTPUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_MELODY_CV_OUTPUT]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(60,0)); outPortWidgets[Meander::OUT_MELODY_GATE_OUTPUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_MELODY_GATE_OUTPUT]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(60,0)); outPortWidgets[Meander::OUT_MELODY_VOLUME_OUTPUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_MELODY_VOLUME_OUTPUT]->box.size.div(2.)); drawCenter=Vec(895., 365.); outPortWidgets[Meander::OUT_BASS_CV_OUTPUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_BASS_CV_OUTPUT]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(50,0)); outPortWidgets[Meander::OUT_BASS_GATE_OUTPUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_BASS_GATE_OUTPUT]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(50,0)); outPortWidgets[Meander::OUT_BASS_VOLUME_OUTPUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_BASS_VOLUME_OUTPUT]->box.size.div(2.)); drawCenter=Vec(1060., 365.); outPortWidgets[Meander::OUT_FBM_HARMONY_OUTPUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_FBM_HARMONY_OUTPUT]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(50,0)); outPortWidgets[Meander::OUT_FBM_MELODY_OUTPUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_FBM_MELODY_OUTPUT]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(50,0)); outPortWidgets[Meander::OUT_FBM_ARP_OUTPUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_FBM_ARP_OUTPUT]->box.size.div(2.)); // drawCenter=Vec(100., 365.); outPortWidgets[Meander::OUT_CLOCK_BAR_OUTPUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_CLOCK_BAR_OUTPUT]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(40,0)); outPortWidgets[Meander::OUT_CLOCK_BEAT_OUTPUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_CLOCK_BEAT_OUTPUT]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(40,0)); outPortWidgets[Meander::OUT_CLOCK_BEATX2_OUTPUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_CLOCK_BEATX2_OUTPUT]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(40,0)); outPortWidgets[Meander::OUT_CLOCK_BEATX4_OUTPUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_CLOCK_BEATX4_OUTPUT]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(40,0)); outPortWidgets[Meander::OUT_CLOCK_BEATX8_OUTPUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_CLOCK_BEATX8_OUTPUT]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(40,0)); drawCenter=Vec(145., 300.); outPortWidgets[Meander::OUT_EXT_POLY_SCALE_OUTPUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_EXT_POLY_SCALE_OUTPUT]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(40,0)); drawCenter=Vec(60., 350.); // adjust the port a bit to right to avoid CPU meter display outPortWidgets[Meander::OUT_CLOCK_OUT]->box.pos=drawCenter.minus(outPortWidgets[Meander::OUT_CLOCK_OUT]->box.size.div(2.)); drawCenter=drawCenter.plus(Vec(40,0)); //******************** for (int i=0; ((i<Meander::NUM_PARAMS)&&(i<MAX_PARAMS)); ++i) // get the paramWidget box into a MeanderWidget array so it can be accessed as needed { if (paramWidgets[i]!=NULL) ParameterRect[i]=paramWidgets[i]->box; } for (int i=0; ((i<Meander::NUM_OUTPUTS)&&(i<MAX_OUTPORTS)); ++i) // get the paramWidget box into a MeanderWidget array so it can be accessed as needed { if (outPortWidgets[i]!=NULL) OutportRect[i]=outPortWidgets[i]->box; } for (int i=0; ((i<Meander::NUM_INPUTS)&&(i<MAX_INPORTS)); ++i) // get the paramWidget box into a MeanderWidget array so it can be accessed as needed { if (inPortWidgets[i]!=NULL) InportRect[i]=inPortWidgets[i]->box; } } // end if (true) line 5336 } // end MeanderWidget(Meander* module) void step() override // note, this is a widget step() which is not deprecated and is a GUI call. This advances UI by one "frame" { Meander *module = dynamic_cast<Meander*>(this->module); // some plugins do this if(module == NULL) return; if ((module != NULL)&&(module->instanceRunning)) { theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port=0; for (CableWidget* cwIn : APP->scene->rack->getCablesOnPort(inPortWidgets[Meander::IN_PROG_STEP_EXT_CV])) { // DEBUG("cwIn!==NULL cableID=%d", cwIn->cable->id); for (CableWidget* cwOut : APP->scene->rack->getCablesOnPort(outPortWidgets[Meander::OUT_CLOCK_BAR_OUTPUT])) { if (cwOut->cable->id == cwIn->cable->id) { // DEBUG("cwOut!==NULL cableID=%d STEP in port connected to OUT_CLOCK_BAR_OUTPUT port", cwOut->cable->id); theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port=Meander::OUT_CLOCK_BAR_OUTPUT; } } for (CableWidget* cwOut : APP->scene->rack->getCablesOnPort(outPortWidgets[Meander::OUT_CLOCK_BEAT_OUTPUT])) { if (cwOut->cable->id == cwIn->cable->id) { // DEBUG("cwOut!==NULL cableID=%d STEP in port connected to OUT_CLOCK_BEAT_OUTPUT port", cwOut->cable->id); theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port=Meander::OUT_CLOCK_BEAT_OUTPUT; } } for (CableWidget* cwOut : APP->scene->rack->getCablesOnPort(outPortWidgets[Meander::OUT_CLOCK_BEATX2_OUTPUT])) { if (cwOut->cable->id == cwIn->cable->id) { // DEBUG("cwOut!==NULL cableID=%d STEP in port connected to OUT_CLOCK_BEATX2_OUTPUT port", cwOut->cable->id); theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port=Meander::OUT_CLOCK_BEATX2_OUTPUT; } } for (CableWidget* cwOut : APP->scene->rack->getCablesOnPort(outPortWidgets[Meander::OUT_CLOCK_BEATX4_OUTPUT])) { if (cwOut->cable->id == cwIn->cable->id) { // DEBUG("cwOut!==NULL cableID=%d STEP in port connected to OUT_CLOCK_BEATX4_OUTPUT port", cwOut->cable->id); theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port=Meander::OUT_CLOCK_BEATX4_OUTPUT; } } for (CableWidget* cwOut : APP->scene->rack->getCablesOnPort(outPortWidgets[Meander::OUT_CLOCK_BEATX8_OUTPUT])) { if (cwOut->cable->id == cwIn->cable->id) { // DEBUG("cwOut!==NULL cableID=%d STEP in port connected to OUT_CLOCK_BEATX8_OUTPUT port", cwOut->cable->id); theMeanderState.theHarmonyParms.STEP_inport_connected_to_Meander_trigger_port=Meander::OUT_CLOCK_BEATX8_OUTPUT; } } } } ModuleWidget::step(); } // end step() }; // end struct MeanderWidget Model* modelMeander = createModel<Meander, MeanderWidget>("Meander");
283,765
C++
.cpp
5,301
46.236182
296
0.703675
knchaffin/Meander
36
5
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,006
Common-Noise.hpp
knchaffin_Meander/src/Common-Noise.hpp
/* Copyright (C) 2019-2020 Ken Chaffin 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, version 3. 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 <https://www.gnu.org/licenses/>. */ #include "math.hpp" //double InversePersistence=NoiseFactor.a; // for fBms. Persistence indicates how the frequencies are scaled when adding. Normally a value of 2.0 is used for InversePersistance so that scale goes as 1/pow(invpersistence,i) or 1/pow(2,i). if ip=1->equal low and high noise. if ip<1,more high noise. //double Lacunarity=(INT)(NoiseFactor.b); // for fBms. Lacunarity indicates how the frequency is changed for each iteration. Normally a value of 2.0xxxx is used so frequency ~doubles at each iteration. A value of 1 is the same as 1 octave since no harmonics. //int n_octaves=(INT)(NoiseFactor.c); // for fBms. number of octaves should be no more than log2(texturewidth) due to nyquist limit ///////////Perlin Noise setup #define B 0x100 #define BM 0xff #define NN 0x1000000 // This needs to be a very large value so that when setup adds a value to it it is always positive, regardless of size of argument which may get quite large in fracal sums int pp[512]; // used by npnoise functions int permutation[] = { 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 }; int p[B + B + 2]; // used by pnoise functions // gradients double g1[B + B + 2]; // 1D double g2[B + B + 2][2]; // 2D double g3[B + B + 2][3]; // 3D #define setup(i,b0,b1,r0,r1) t = vec[i] + NN; b0 = ((int)t) & BM; b1 = (b0+1) & BM; r0 = t - (int)t; r1 = r0 - 1.; static double g_precomputed[][3]= { {0.881927, 0.00933256, -0.471294}, {0.783613, 0.523784, 0.334067}, {0.16021, -0.224294, 0.961262}, {0.476773, -0.630021, 0.612994}, {-0.299992, -0.549216, 0.779979}, {-0.437603, -0.389943, 0.810215}, {0.474441, -0.809644, -0.345517}, {0.250258, 0.896758, 0.36496}, {0.664083, -0.723553, 0.188322}, {-0.955856, -0.00391744, -0.293808}, {0.430173, -0.337663, -0.837219}, {-0.608608, 0.107774, 0.786118}, {-0.161776, 0.0276203, 0.986441}, {-0.900782, 0.407496, -0.15013}, {0.67719, -0.735235, -0.0290224}, {0.435259, 0.383347, 0.814613}, {0.990155, 0.0594093, -0.12674}, {-0.0900124, 0.565078, -0.820113}, {0.877974, 0.321742, -0.354462}, {-0.292866, -0.348273, -0.89047}, {-0.493484, -0.626647, 0.603148}, {-0.018251, -0.748291, 0.66312}, {0.442048, -0.191684, 0.876271}, {-0.039175, -0.415255, -0.908861}, {-0.375172, -0.875401, 0.304827}, {0.816216, -0.575061, 0.0556511}, {0.688177, 0.478367, -0.545506}, {-0.519943, -0.0310413, 0.853637}, {0.732517, 0.677232, -0.0691053}, {-0.387999, -0.383872, 0.837913}, {-0.495871, 0.602129, -0.625742}, {-0.557869, -0.825864, -0.0820395}, {-0.252615, 0.959939, -0.121255}, {0.656728, -0.682583, 0.320607}, {-0.0722408, 0.995318, -0.0642141}, {0.0264206, 0.970958, 0.237786}, {0.566363, -0.257857, -0.782779}, {-0.79241, 0.608663, -0.0401947}, {-0.61328, -0.789435, -0.026097}, {0.621471, -0.777896, 0.0930093}, {0.179964, 0.439912, -0.879824}, {0.920163, -0.387437, 0.0565012}, {0.731388, 0.427997, 0.530933}, {0.696311, -0.575795, 0.428499}, {0.714037, 0.409693, -0.567718}, {-0.954945, 0.296734, 0.00539517}, {-0.261215, 0.931668, -0.252508}, {-0.0466522, 0.419869, 0.906385}, {0.901551, -0.353311, -0.249754}, {-0.0734223, -0.682827, -0.726881}, {0.789875, 0.490128, -0.368608}, {-0.842201, -0.191409, 0.504044}, {0.768506, 0.286146, 0.572292}, {0.659914, -0.611391, -0.436708}, {0.637383, -0.174766, 0.750467}, {0.0181811, -0.645428, -0.763605}, {0.903195, 0.428914, -0.0164967}, {-0.680163, 0.216645, -0.700316}, {0.157334, 0.875823, 0.456267}, {-0.725857, 0.488843, -0.483905}, {-0.268821, -0.604847, -0.749597}, {-0.206278, 0.56349, -0.799955}, {-0.759064, -0.586905, 0.281715}, {-0.626585, 0.779282, -0.0105308}, {0.453898, 0.841373, 0.293373}, {0.335068, -0.687101, -0.644687}, {0.605501, -0.70011, 0.378438}, {0.368652, 0.741971, 0.559978}, {0.200715, -0.0821105, 0.976203}, {0.870031, -0.487923, 0.0705431}, {0.657558, -0.307665, -0.687721}, {-0.803072, 0.317494, -0.504255}, {-0.940811, -0.338894, 0.00505812}, {0.945164, -0.219413, -0.241917}, {0.543321, -0.628883, 0.556155}, {0.117745, -0.781828, 0.612275}, {-0.162865, 0.35381, -0.921029}, {0.625338, 0.695941, -0.353013}, {0.823315, 0.476656, 0.308141}, {-0.586069, -0.138442, 0.798346}, {-0.991332, 0.097024, -0.0885871}, {-0.781887, -0.414443, 0.465714}, {-0.370439, -0.928134, -0.0366369}, {0.371806, 0.87668, -0.305273}, {0.0246669, -0.999011, -0.0370004}, {-0.777502, -0.622795, -0.0872707}, {0.881495, -0.25652, -0.39644}, {0.32106, 0.840871, -0.435724}, {-0.908547, -0.204628, -0.364237}, {-0.18656, -0.457919, -0.869198}, {-0.0928068, 0.625437, -0.774735}, {-0.80303, -0.499758, -0.324629}, {0.467011, -0.862955, -0.192896}, {-0.844156, 0.427559, 0.32341}, {-0.366754, -0.171152, 0.914439}, {-0.37027, -0.590118, -0.717398}, {-0.327903, -0.595403, 0.733468}, {0.0786493, 0.992192, -0.0967992}, {0.470555, 0.796323, 0.380063}, {-0.778758, -0.0450149, -0.625707}, {0.287529, 0.406964, 0.867011}, {-0.935035, -0.21864, 0.279115}, {-0.333575, -0.942711, 0.00483442}, {-0.487224, -0.861555, -0.142602}, {0.524416, 0.348022, 0.77709}, {-0.315749, -0.874779, 0.367511}, {0.718447, 0.662256, -0.212724}, {-0.108332, 0.526184, -0.843442}, {-0.312189, 0.70359, 0.638357}, {0.719518, -0.575614, -0.388539}, {-0.116052, 0.98644, -0.116052}, {0.835012, -0.0392024, -0.548834}, {-0.263718, -0.61403, 0.743922}, {0.662808, -0.14685, 0.734248}, {-0.567505, 0.823282, -0.0119895}, {0.0315202, -0.737572, -0.674532}, {-0.463101, 0.767773, 0.44279}, {0.760856, -0.502826, -0.4102}, {-0.884402, 0.136062, -0.446453}, {-0.820505, -0.0444609, 0.569908}, {0.261755, 0.251285, -0.931848}, {0.538347, 0.507289, -0.672934}, {-0.833848, -0.489191, -0.255713}, {-0.981969, 0.0892699, -0.166637}, {0.567306, 0.669131, -0.480029}, {0.471825, 0.845723, -0.249266}, {0.178178, -0.0633521, 0.981957}, {0.531368, -0.315365, 0.786252}, {0.568053, 0.0272665, -0.82254}, {-0.660161, 0.746849, -0.0800196}, {-0.743197, 0.276539, 0.609249}, {-0.121776, -0.748052, 0.652371}, {0.90717, 0.415575, -0.0658838}, {0.899211, -0.333993, -0.282609}, {-0.929721, 0.164693, -0.329387}, {-0.301401, -0.943517, -0.137596}, {0.572063, -0.631428, 0.523491}, {0.960138, 0.262223, 0.0968206}, {0.956128, -0.0670967, -0.285161}, {0.492877, -0.341223, -0.800399}, {-0.0509833, -0.846322, -0.530226}, {-0.119676, 0.977353, 0.174527}, {0.579728, -0.614119, 0.535512}, {-0.0165382, 0.70701, 0.70701}, {0.776577, -0.496146, -0.388288}, {-0.267511, -0.312852, -0.911351}, {0.043586, -0.966156, -0.254251}, {-0.619005, -0.706807, 0.342428}, {0.34909, 0.934329, -0.0718715}, {-0.207273, 0.288556, -0.934759}, {0.191337, 0.569106, 0.799692}, {0.706407, -0.307333, -0.637601}, {-0.549731, -0.768827, 0.326652}, {-0.597983, -0.776328, 0.199328}, {0, 0.21279, 0.977098}, {0.836218, 0.380099, -0.395303}, {-0.347158, -0.586415, -0.731846}, {-0.74361, 0.358621, -0.5643}, {-0.119613, 0.967308, -0.223625}, {0.521332, 0.392343, -0.757813}, {0.333037, -0.636249, 0.695898}, {-0.736632, -0.0687523, -0.67279}, {-0.368305, -0.830733, 0.417413}, {0.802572, 0.401286, 0.441415}, {0.618643, -0.520566, -0.588466}, {0.340475, -0.89686, 0.282345}, {0.416618, 0.901255, -0.119034}, {0.980928, -0.159461, -0.11114}, {-0.874596, -0.477977, -0.0813578}, {0.617716, 0.677112, -0.399932}, {-0.719814, 0.482602, 0.498962}, {0.312856, -0.483006, 0.817818}, {0.319034, -0.0294493, 0.947286}, {-0.691378, -0.550129, 0.468353}, {-0.435125, 0.255549, -0.863343}, {-0.484711, -0.803235, 0.346222}, {0.170271, 0.887471, -0.428256}, {0.112697, -0.798272, 0.59166}, {-0.790477, -0.560622, 0.246674}, {0.145604, -0.208006, -0.967229}, {0.125644, -0.225292, -0.966156}, {0.685839, 0.719918, -0.106497}, {-0.501538, -0.3869, -0.773801}, {0.416413, 0.904898, -0.0880874}, {-0.615626, -0.619649, -0.486867}, {0.669855, 0.525021, 0.525021}, {-0.270705, 0.0887557, 0.958562}, {-0.184426, -0.493999, 0.849678}, {0.207925, -0.855237, -0.474696}, {-0.35043, -0.133075, 0.927087}, {-0.890682, -0.356273, 0.282411}, {0.39093, 0.349045, 0.85167}, {0.346808, -0.579477, 0.737516}, {0.677666, 0.687347, 0.261386}, {0.448941, 0.104405, -0.887441}, {-0.769922, -0.558906, 0.307969}, {0.863871, 0.497192, -0.0807937}, {0.88277, -0.387558, -0.265549}, {0.316139, 0.724484, -0.612519}, {-0.156561, -0.305093, 0.939365}, {-0.863919, 0.493668, -0.0996829}, {-0.399274, 0.432948, 0.808169}, {-0.201097, -0.827772, -0.523788}, {0.649832, -0.69096, -0.31669}, {0.58329, -0.762109, -0.281001}, {-0.0146116, 0.0535757, -0.998457}, {0.0301203, 0.85843, 0.512046}, {0.122289, -0.778574, -0.615522}, {-0.6378, -0.621855, -0.454432}, {0.572703, -0.381802, 0.725423}, {0.283725, -0.671761, -0.684278}, {0.482124, 0.583624, 0.653405}, {-0.464375, -0.883445, 0.0622942}, {-0.343074, 0.810902, 0.474066}, {0.362148, 0.354905, -0.861912}, {0.245597, -0.30927, 0.918713}, {0.404371, 0.269581, 0.873963}, {0.104848, 0.986809, 0.123351}, {0.600225, -0.104626, -0.792958}, {-0.27876, -0.931313, 0.234412}, {0, 0.987007, -0.160676}, {-0.570647, -0.723605, 0.388276}, {0.865457, 0.397092, -0.305455}, {0.619109, 0.754539, -0.217656}, {-0.112209, -0.0290913, -0.993259}, {-0.481007, -0.15838, -0.862292}, {-0.805298, 0.592131, -0.0296065}, {-0.101503, -0.882635, 0.45897}, {-0.84889, 0.523013, 0.0764403}, {-0.0694843, -0.67499, 0.734548}, {-0.0984886, 0.977007, 0.189098}, {0.823002, 0.564805, 0.0605149}, {-0.996435, -0.08052, 0.0251625}, {0.319592, -0.834754, -0.448382}, {0.798493, 0.550685, 0.243219}, {-0.265283, -0.631625, 0.728474}, {-0.678481, 0.325353, 0.658642}, {0.729404, 0.070763, -0.680414}, {-0.95973, 0.280536, -0.0147651}, {-0.866431, -0.404334, -0.292936}, {-0.528207, 0.803314, 0.275108}, {-0.459883, 0.27593, -0.84402}, {-0.164752, 0.804749, -0.570295}, {0.616383, 0.273302, 0.738497}, {-0.122193, 0.882944, -0.453297}, {-0.643681, 0.760714, 0.083595}, {-0.0738983, 0.468023, 0.880621}, {0.314462, -0.612935, 0.724862}, {-0.35677, 0.932466, 0.0567588}, {0.511392, -0.146711, -0.846731}, {-0.185801, 0.170318, 0.967714}, {-0.171952, -0.96137, -0.214941}, {-0.81662, 0.361197, 0.450188}, {-0.0538588, 0.65977, 0.749535}, {0.317011, -0.926956, -0.20064}, {0.190026, 0.740102, -0.645089}, {0.881927, 0.00933256, -0.471294}, {0.783613, 0.523784, 0.334067}, {0.16021, -0.224294, 0.961262}, {0.476773, -0.630021, 0.612994}, {-0.299992, -0.549216, 0.779979}, {-0.437603, -0.389943, 0.810215}, {0.474441, -0.809644, -0.345517}, {0.250258, 0.896758, 0.36496}, {0.664083, -0.723553, 0.188322}, {-0.955856, -0.00391744, -0.293808}, {0.430173, -0.337663, -0.837219}, {-0.608608, 0.107774, 0.786118}, {-0.161776, 0.0276203, 0.986441}, {-0.900782, 0.407496, -0.15013}, {0.67719, -0.735235, -0.0290224}, {0.435259, 0.383347, 0.814613}, {0.990155, 0.0594093, -0.12674}, {-0.0900124, 0.565078, -0.820113}, {0.877974, 0.321742, -0.354462}, {-0.292866, -0.348273, -0.89047}, {-0.493484, -0.626647, 0.603148}, {-0.018251, -0.748291, 0.66312}, {0.442048, -0.191684, 0.876271}, {-0.039175, -0.415255, -0.908861}, {-0.375172, -0.875401, 0.304827}, {0.816216, -0.575061, 0.0556511}, {0.688177, 0.478367, -0.545506}, {-0.519943, -0.0310413, 0.853637}, {0.732517, 0.677232, -0.0691053}, {-0.387999, -0.383872, 0.837913}, {-0.495871, 0.602129, -0.625742}, {-0.557869, -0.825864, -0.0820395}, {-0.252615, 0.959939, -0.121255}, {0.656728, -0.682583, 0.320607}, {-0.0722408, 0.995318, -0.0642141}, {0.0264206, 0.970958, 0.237786}, {0.566363, -0.257857, -0.782779}, {-0.79241, 0.608663, -0.0401947}, {-0.61328, -0.789435, -0.026097}, {0.621471, -0.777896, 0.0930093}, {0.179964, 0.439912, -0.879824}, {0.920163, -0.387437, 0.0565012}, {0.731388, 0.427997, 0.530933}, {0.696311, -0.575795, 0.428499}, {0.714037, 0.409693, -0.567718}, {-0.954945, 0.296734, 0.00539517}, {-0.261215, 0.931668, -0.252508}, {-0.0466522, 0.419869, 0.906385}, {0.901551, -0.353311, -0.249754}, {-0.0734223, -0.682827, -0.726881}, {0.789875, 0.490128, -0.368608}, {-0.842201, -0.191409, 0.504044}, {0.768506, 0.286146, 0.572292}, {0.659914, -0.611391, -0.436708}, {0.637383, -0.174766, 0.750467}, {0.0181811, -0.645428, -0.763605}, {0.903195, 0.428914, -0.0164967}, {-0.680163, 0.216645, -0.700316}, {0.157334, 0.875823, 0.456267}, {-0.725857, 0.488843, -0.483905}, {-0.268821, -0.604847, -0.749597}, {-0.206278, 0.56349, -0.799955}, {-0.759064, -0.586905, 0.281715}, {-0.626585, 0.779282, -0.0105308}, {0.453898, 0.841373, 0.293373}, {0.335068, -0.687101, -0.644687}, {0.605501, -0.70011, 0.378438}, {0.368652, 0.741971, 0.559978}, {0.200715, -0.0821105, 0.976203}, {0.870031, -0.487923, 0.0705431}, {0.657558, -0.307665, -0.687721}, {-0.803072, 0.317494, -0.504255}, {-0.940811, -0.338894, 0.00505812}, {0.945164, -0.219413, -0.241917}, {0.543321, -0.628883, 0.556155}, {0.117745, -0.781828, 0.612275}, {-0.162865, 0.35381, -0.921029}, {0.625338, 0.695941, -0.353013}, {0.823315, 0.476656, 0.308141}, {-0.586069, -0.138442, 0.798346}, {-0.991332, 0.097024, -0.0885871}, {-0.781887, -0.414443, 0.465714}, {-0.370439, -0.928134, -0.0366369}, {0.371806, 0.87668, -0.305273}, {0.0246669, -0.999011, -0.0370004}, {-0.777502, -0.622795, -0.0872707}, {0.881495, -0.25652, -0.39644}, {0.32106, 0.840871, -0.435724}, {-0.908547, -0.204628, -0.364237}, {-0.18656, -0.457919, -0.869198}, {-0.0928068, 0.625437, -0.774735}, {-0.80303, -0.499758, -0.324629}, {0.467011, -0.862955, -0.192896}, {-0.844156, 0.427559, 0.32341}, {-0.366754, -0.171152, 0.914439}, {-0.37027, -0.590118, -0.717398}, {-0.327903, -0.595403, 0.733468}, {0.0786493, 0.992192, -0.0967992}, {0.470555, 0.796323, 0.380063}, {-0.778758, -0.0450149, -0.625707}, {0.287529, 0.406964, 0.867011}, {-0.935035, -0.21864, 0.279115}, {-0.333575, -0.942711, 0.00483442}, {-0.487224, -0.861555, -0.142602}, {0.524416, 0.348022, 0.77709}, {-0.315749, -0.874779, 0.367511}, {0.718447, 0.662256, -0.212724}, {-0.108332, 0.526184, -0.843442}, {-0.312189, 0.70359, 0.638357}, {0.719518, -0.575614, -0.388539}, {-0.116052, 0.98644, -0.116052}, {0.835012, -0.0392024, -0.548834}, {-0.263718, -0.61403, 0.743922}, {0.662808, -0.14685, 0.734248}, {-0.567505, 0.823282, -0.0119895}, {0.0315202, -0.737572, -0.674532}, {-0.463101, 0.767773, 0.44279}, {0.760856, -0.502826, -0.4102}, {-0.884402, 0.136062, -0.446453}, {-0.820505, -0.0444609, 0.569908}, {0.261755, 0.251285, -0.931848}, {0.538347, 0.507289, -0.672934}, {-0.833848, -0.489191, -0.255713}, {-0.981969, 0.0892699, -0.166637}, {0.567306, 0.669131, -0.480029}, {0.471825, 0.845723, -0.249266}, {0.178178, -0.0633521, 0.981957}, {0.531368, -0.315365, 0.786252}, {0.568053, 0.0272665, -0.82254}, {-0.660161, 0.746849, -0.0800196}, {-0.743197, 0.276539, 0.609249}, {-0.121776, -0.748052, 0.652371}, {0.90717, 0.415575, -0.0658838}, {0.899211, -0.333993, -0.282609}, {-0.929721, 0.164693, -0.329387}, {-0.301401, -0.943517, -0.137596}, {0.572063, -0.631428, 0.523491}, {0.960138, 0.262223, 0.0968206}, {0.956128, -0.0670967, -0.285161}, {0.492877, -0.341223, -0.800399}, {-0.0509833, -0.846322, -0.530226}, {-0.119676, 0.977353, 0.174527}, {0.579728, -0.614119, 0.535512}, {-0.0165382, 0.70701, 0.70701}, {0.776577, -0.496146, -0.388288}, {-0.267511, -0.312852, -0.911351}, {0.043586, -0.966156, -0.254251}, {-0.619005, -0.706807, 0.342428}, {0.34909, 0.934329, -0.0718715}, {-0.207273, 0.288556, -0.934759}, {0.191337, 0.569106, 0.799692}, {0.706407, -0.307333, -0.637601}, {-0.549731, -0.768827, 0.326652}, {-0.597983, -0.776328, 0.199328}, {0, 0.21279, 0.977098}, {0.836218, 0.380099, -0.395303}, {-0.347158, -0.586415, -0.731846}, {-0.74361, 0.358621, -0.5643}, {-0.119613, 0.967308, -0.223625}, {0.521332, 0.392343, -0.757813}, {0.333037, -0.636249, 0.695898}, {-0.736632, -0.0687523, -0.67279}, {-0.368305, -0.830733, 0.417413}, {0.802572, 0.401286, 0.441415}, {0.618643, -0.520566, -0.588466}, {0.340475, -0.89686, 0.282345}, {0.416618, 0.901255, -0.119034}, {0.980928, -0.159461, -0.11114}, {-0.874596, -0.477977, -0.0813578}, {0.617716, 0.677112, -0.399932}, {-0.719814, 0.482602, 0.498962}, {0.312856, -0.483006, 0.817818}, {0.319034, -0.0294493, 0.947286}, {-0.691378, -0.550129, 0.468353}, {-0.435125, 0.255549, -0.863343}, {-0.484711, -0.803235, 0.346222}, {0.170271, 0.887471, -0.428256}, {0.112697, -0.798272, 0.59166}, {-0.790477, -0.560622, 0.246674}, {0.145604, -0.208006, -0.967229}, {0.125644, -0.225292, -0.966156}, {0.685839, 0.719918, -0.106497}, {-0.501538, -0.3869, -0.773801}, {0.416413, 0.904898, -0.0880874}, {-0.615626, -0.619649, -0.486867}, {0.669855, 0.525021, 0.525021}, {-0.270705, 0.0887557, 0.958562}, {-0.184426, -0.493999, 0.849678}, {0.207925, -0.855237, -0.474696}, {-0.35043, -0.133075, 0.927087}, {-0.890682, -0.356273, 0.282411}, {0.39093, 0.349045, 0.85167}, {0.346808, -0.579477, 0.737516}, {0.677666, 0.687347, 0.261386}, {0.448941, 0.104405, -0.887441}, {-0.769922, -0.558906, 0.307969}, {0.863871, 0.497192, -0.0807937}, {0.88277, -0.387558, -0.265549}, {0.316139, 0.724484, -0.612519}, {-0.156561, -0.305093, 0.939365}, {-0.863919, 0.493668, -0.0996829}, {-0.399274, 0.432948, 0.808169}, {-0.201097, -0.827772, -0.523788}, {0.649832, -0.69096, -0.31669}, {0.58329, -0.762109, -0.281001}, {-0.0146116, 0.0535757, -0.998457}, {0.0301203, 0.85843, 0.512046}, {0.122289, -0.778574, -0.615522}, {-0.6378, -0.621855, -0.454432}, {0.572703, -0.381802, 0.725423}, {0.283725, -0.671761, -0.684278}, {0.482124, 0.583624, 0.653405}, {-0.464375, -0.883445, 0.0622942}, {-0.343074, 0.810902, 0.474066}, {0.362148, 0.354905, -0.861912}, {0.245597, -0.30927, 0.918713}, {0.404371, 0.269581, 0.873963}, {0.104848, 0.986809, 0.123351}, {0.600225, -0.104626, -0.792958}, {-0.27876, -0.931313, 0.234412}, {0, 0.987007, -0.160676}, {-0.570647, -0.723605, 0.388276}, {0.865457, 0.397092, -0.305455}, {0.619109, 0.754539, -0.217656}, {-0.112209, -0.0290913, -0.993259}, {-0.481007, -0.15838, -0.862292}, {-0.805298, 0.592131, -0.0296065}, {-0.101503, -0.882635, 0.45897}, {-0.84889, 0.523013, 0.0764403}, {-0.0694843, -0.67499, 0.734548}, {-0.0984886, 0.977007, 0.189098}, {0.823002, 0.564805, 0.0605149}, {-0.996435, -0.08052, 0.0251625}, {0.319592, -0.834754, -0.448382}, {0.798493, 0.550685, 0.243219}, {-0.265283, -0.631625, 0.728474}, {-0.678481, 0.325353, 0.658642}, {0.729404, 0.070763, -0.680414}, {-0.95973, 0.280536, -0.0147651}, {-0.866431, -0.404334, -0.292936}, {-0.528207, 0.803314, 0.275108}, {-0.459883, 0.27593, -0.84402}, {-0.164752, 0.804749, -0.570295}, {0.616383, 0.273302, 0.738497}, {-0.122193, 0.882944, -0.453297}, {-0.643681, 0.760714, 0.083595}, {-0.0738983, 0.468023, 0.880621}, {0.314462, -0.612935, 0.724862}, {-0.35677, 0.932466, 0.0567588}, {0.511392, -0.146711, -0.846731}, {-0.185801, 0.170318, 0.967714}, {-0.171952, -0.96137, -0.214941}, {-0.81662, 0.361197, 0.450188}, {-0.0538588, 0.65977, 0.749535}, {0.317011, -0.926956, -0.20064}, {0.190026, 0.740102, -0.645089}, {0.881927, 0.00933256, -0.471294}, {0.783613, 0.523784, 0.334067}, }; //#define fade(t) ( t ) // linear linterpolation fast but poor //#define fade(t) ( t * t * (3. - 2. * t) ) // cubic interplation #define fade(t) ( t * t * t * (t * (t * 6 - 15) + 10) ) // quintic interpolation does better on integer lattice points but mostly only if derivatives of noise are used such as in bumpmapping #define lerp(t, a, b) ( a + t * (b - a) ) // lerp="linear interpolation" static void normalize2(double v[2]) { double s; s = sqrt(v[0] * v[0] + v[1] * v[1]); v[0] = v[0] / s; v[1] = v[1] / s; } /* to avoid unused warning static void normalize3(double v[3]) { double s; s = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); v[0] = v[0] / s; v[1] = v[1] / s; v[2] = v[2] / s; } */ //double pnoise1(double vec[]); /* Coherent Perlin noise function over 1, 2 or 3 dimensions */ // actually lattice noise of the gradient variety static double pnoise1(double vec[]) { int bx0=0, bx1=0; double rx0=0., rx1=0., sx=0., t=0., u=0., v=0.; // #define setup(i,b0,b1,r0,r1) t = vec[i] + NN; b0 = ((int)t) & BM; b1 = (b0+1) & BM; r0 = t - (int)t; r1 = r0 - 1.; setup(0, bx0,bx1, rx0,rx1); // by define this is dependent on vec[0] sx = fade(rx0); u = rx0 * g1[ p[ bx0 ] ]; v = rx1 * g1[ p[ bx1 ] ]; return 2.1*lerp(sx, u, v); // essentially scales a -.5 to +.5 distribution to -1 to 1 } static double pnoise2(double vec[]) { int bx0, bx1, by0, by1, b00, b10, b01, b11; double rx0, rx1, ry0, ry1, *q, sx, sy, a, b, t, u, v; int i, j; setup(0, bx0,bx1, rx0,rx1); setup(1, by0,by1, ry0,ry1); i = p[ bx0 ]; j = p[ bx1 ]; b00 = p[ i + by0 ]; b10 = p[ j + by0 ]; b01 = p[ i + by1 ]; b11 = p[ j + by1 ]; sx = fade(rx0); sy = fade(ry0); #define at2(rx,ry) ( rx * q[0] + ry * q[1] ) q = g2[ b00 ] ; u = at2(rx0,ry0); q = g2[ b10 ] ; v = at2(rx1,ry0); a = lerp(sx, u, v); q = g2[ b01 ] ; u = at2(rx0,ry1); q = g2[ b11 ] ; v = at2(rx1,ry1); b = lerp(sx, u, v); return 1.5*lerp(sy, a, b); // essentially scales a gaussian -.7 to +.7 distribution to -1 to 1 } int test_count=0; static double pnoise3(double vec[]) { int bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11; double rx0, rx1, ry0, ry1, rz0, rz1, *q, sy, sz, a, b, c, d, t, u, v; int i, j; setup(0, bx0,bx1, rx0,rx1); setup(1, by0,by1, ry0,ry1); setup(2, bz0,bz1, rz0,rz1); i = p[ bx0 ]; j = p[ bx1 ]; b00 = p[ i + by0 ]; b10 = p[ j + by0 ]; b01 = p[ i + by1 ]; b11 = p[ j + by1 ]; t = fade(rx0); sy = fade(ry0); sz = fade(rz0); #define at3(rx,ry,rz) ( rx * q[0] + ry * q[1] + rz * q[2] ) q = g3[ (b00 + bz0) ] ; u = at3(rx0,ry0,rz0); q = g3[ (b10 + bz0) ] ; v = at3(rx1,ry0,rz0); a = lerp(t, u, v); q = g3[ (b01 + bz0) ] ; u = at3(rx0,ry1,rz0); q = g3[ (b11 + bz0) ] ; v = at3(rx1,ry1,rz0); b = lerp(t, u, v); c = lerp(sy, a, b); q = g3[ (b00 + bz1) ] ; u = at3(rx0,ry0,rz1); q = g3[ (b10 + bz1) ] ; v = at3(rx1,ry0,rz1); a = lerp(t, u, v); q = g3[ (b01 + bz1) ] ; u = at3(rx0,ry1,rz1); q = g3[ (b11 + bz1) ] ; v = at3(rx1,ry1,rz1); b = lerp(t, u, v); d = lerp(sy, a, b); return 1.5*lerp(sz, c, d); // essentially scales a gaussian -.7 to +.7 distribution to -1 to 1 } /* --- fBm harmonic summing functions - PDB --------------------------*/ // actually these are fBM (fractional Brownian motion) functions // -1 to +1 noise double fBm1DNoise(double x,double InversePersistence,double Lacunarity,int n_octaves) { if (n_octaves<1) n_octaves=1; if (n_octaves>6) n_octaves=6; if (InversePersistence<.5) InversePersistence=.5; if (InversePersistence>4.0) InversePersistence=4.0; if (Lacunarity<1.0) Lacunarity=1.0; if (Lacunarity>4.0) Lacunarity=4.0; int i; double val,sum = 0; double p[1],scale = 1; p[0] = x; for (i=0;i<n_octaves;i++) { val = pnoise1(p); sum += val / scale; scale *= InversePersistence; p[0] *= Lacunarity; } return(sum); } double FastfBm1DNoise(double x,int n_octaves) // fixed invpersistence=2. and lacunarity=2. { if (n_octaves<1) n_octaves=1; if (n_octaves>6) n_octaves=6; int i; double val,sum = 0; double p[1],scale = 1; p[0] = x; for (i=0;i<n_octaves;i++) { val = pnoise1(p); sum += val / scale; scale *= 2.; p[0] *= 2.02345; } return(sum); } // -1 to +1 noise double fBm2DNoise(double x,double y,double InversePersistence,double Lacunarity,int n_octaves,bool *NoiseResetFlag) { if (n_octaves<1) n_octaves=1; if (n_octaves>6) n_octaves=6; if (InversePersistence<.5) InversePersistence=.5; if (InversePersistence>4.0) InversePersistence=4.0; if (Lacunarity<1.0) Lacunarity=1.0; if (Lacunarity>4.0) Lacunarity=4.0; int i; double val,sum = 0; double p[2],scale = 1; static double normalscale=1.; // used to renormalize added octaves static double currentInversePersistence=0; static double currentLacunarity=0; static int currentnoctaves=0; if (*NoiseResetFlag) if ((InversePersistence!=currentInversePersistence)||(Lacunarity!=currentLacunarity)||(n_octaves!=currentnoctaves)) { double dfscale=1.; // based on sqrt of sum of squares of scales double inversescale=1.; normalscale=0; for (i=0;i<n_octaves;i++) { inversescale = 1./dfscale; normalscale += inversescale*inversescale; dfscale *= InversePersistence; } normalscale=sqrt(normalscale); currentInversePersistence=InversePersistence; currentLacunarity=Lacunarity; currentnoctaves=n_octaves; *NoiseResetFlag=false; } p[0] = x; p[1] = y; for (i=0;i<n_octaves;i++) { val = pnoise2(p); sum += val / scale; scale *= InversePersistence; p[0] *= Lacunarity; p[1] *= Lacunarity; } return(sum/(1.2*normalscale)); // the 1.2 is fudge to make 8 octave sum correct, but introduces some error at low octave counts } double FastfBm2DNoise(double x,double y,int n_octaves,bool *NoiseResetFlag) // fixed invpersistence=2. and lacunarity=2. { if (n_octaves<1) n_octaves=1; if (n_octaves>6) n_octaves=6; int i; double val,sum = 0; double p[2],scale = 1; static double normalscale=1.; // used to renormalize added octaves static int currentnoctaves=0; if (*NoiseResetFlag) if (n_octaves!=currentnoctaves) { double dfscale=1.; // based on sqrt of sum of squares of scales double inversescale=1.; normalscale=0; for (i=0;i<n_octaves;i++) { inversescale = 1./dfscale; normalscale += inversescale*inversescale; dfscale *= 2.; } normalscale=sqrt(normalscale); currentnoctaves=n_octaves; *NoiseResetFlag=false; } p[0] = x; p[1] = y; for (i=0;i<n_octaves;i++) { val = pnoise2(p); sum += val / scale; scale *= 2.; p[0] *= 2.05645; // to avoid artifacts avoid lacunarity of 2.0 p[1] *= 2.05467; // to avoid artifacts avoid lacunarity of 2.0 } return(sum/(1.2*normalscale)); // the 1.2 is fudge to make 8 octave sum correct, but introduces some error at low octave counts } double grad3(int hash, double x, double y, double z) { int h = hash & 15; // CONVERT LO 4 BITS OF HASH CODE double u = h < 8 ? x : y, // INTO 12 GRADIENT DIRECTIONS. v = h < 4 ? y : h==12||h==14 ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); } double npnoise3(double vec[]) // new improved perlin noise3 { double x=vec[0]; double y=vec[1]; double z=vec[2]; int X = (int)floor(x) & 255, // FIND UNIT CUBE THAT Y = (int)floor(y) & 255, // CONTAINS POINT. Z = (int)floor(z) & 255; x -= floor(x); // FIND RELATIVE X,Y,Z y -= floor(y); // OF POINT IN CUBE. z -= floor(z); double u = fade(x), // COMPUTE FADE CURVES v = fade(y), // FOR EACH OF X,Y,Z. w = fade(z); int A = p[X]+Y, AA = p[A]+Z, AB = p[A+1]+Z, // HASH COORDINATES OF C = p[X+1]+Y, BA = p[C]+Z, BB = p[C+1]+Z; // THE 8 CUBE CORNERS, return lerp(w,lerp(v,lerp(u, grad3(p[AA ], x, y, z), // AND ADD grad3(p[BA ], x-1, y, z)), // BLENDED lerp(u, grad3(p[AB ], x, y-1, z), // RESULTS grad3(p[BB ], x-1, y-1, z))), // FROM 8 lerp(v, lerp(u, grad3(p[AA+1], x, y, z-1 ),// CORNERS grad3(p[BA+1], x-1, y, z-1)), // OF CUBE lerp(u, grad3(p[AB+1], x, y-1, z-1), grad3(p[BB+1], x-1, y-1, z-1)))); } static double grad4(int hash, double x, double y, double z, double w) { int h = hash & 31; // CONVERT LO 5 BITS OF HASH TO 32 GRAD DIRECTIONS. double a=y,b=z,c=w; // X,Y,Z switch (h >> 3) { // OR, DEPENDING ON HIGH ORDER 2 BITS: case 1: a=w;b=x;c=y;break; // W,X,Y case 2: a=z;b=w;c=x;break; // Z,W,X case 3: a=y;b=z;c=w;break; // Y,Z,W }; return ((h&4)==0 ? -a:a) + ((h&2)==0 ? -b:b) + ((h&1)==0 ? -c:c); } double npnoise4(double vec[]) { double x=vec[0]; double y=vec[1]; double z=vec[2]; double w=vec[3]; int X = (int)floor(x) & 255; // FIND UNIT HYPERCUBE int Y = (int)floor(y) & 255; // THAT CONTAINS POINT. int Z = (int)floor(z) & 255; int W = (int)floor(w) & 255; x -= floor(x); // FIND RELATIVE X,Y,Z,W y -= floor(y); // OF POINT IN CUBE. z -= floor(z); w -= floor(w); double a = fade(x); // COMPUTE FADE CURVES double b = fade(y); // FOR EACH OF X,Y,Z,W. double c = fade(z); double d = fade(w); int A = pp[X]+Y; // HASH COORDINATES OF int AA = pp[A]+Z; // THE 16 CORNERS OF int AB = pp[A+1]+Z; // THE HYPERCUBE. int C = pp[X+1]+Y; int BA = pp[C]+Z; int BB = pp[C+1]+Z; int AAA = pp[AA]+W; int AAB = pp[AA+1]+W; int ABA = pp[AB]+W; int ABB = pp[AB+1]+W; int BAA = pp[BA]+W; int BAB = pp[BA+1]+W; int BBA = pp[BB]+W; int BBB = pp[BB+1]+W; return lerp(d, // INTERPOLATE DOWN. lerp(c,lerp(b,lerp(a,grad4(pp[AAA ], x , y , z , w), grad4(pp[BAA ], x-1, y , z , w)), lerp(a,grad4(pp[ABA ], x , y-1, z , w), grad4(pp[BBA ], x-1, y-1, z , w))), lerp(b,lerp(a,grad4(pp[AAB ], x , y , z-1, w), grad4(pp[BAB ], x-1, y , z-1, w)), lerp(a,grad4(pp[ABB ], x , y-1, z-1, w), grad4(pp[BBB ], x-1, y-1, z-1, w)))), lerp(c,lerp(b,lerp(a,grad4(pp[AAA+1], x , y , z , w-1), grad4(pp[BAA+1], x-1, y , z , w-1)), lerp(a,grad4(pp[ABA+1], x , y-1, z , w-1), grad4(pp[BBA+1], x-1, y-1, z , w-1))), lerp(b,lerp(a,grad4(pp[AAB+1], x , y , z-1, w-1), grad4(pp[BAB+1], x-1, y , z-1, w-1)), lerp(a,grad4(pp[ABB+1], x , y-1, z-1, w-1), grad4(pp[BBB+1], x-1, y-1, z-1, w-1))))); } // -1 to +1 noise double fBm3DNoise(double x,double y,double z,double InversePersistence,double Lacunarity,int n_octaves, bool *NoiseResetFlag) { if (n_octaves<1) n_octaves=1; if (n_octaves>6) n_octaves=6; if (InversePersistence<.5) InversePersistence=.5; if (InversePersistence>4.0) InversePersistence=4.0; if (Lacunarity<1.0) Lacunarity=1.0; if (Lacunarity>4.0) Lacunarity=4.0; int i; double val,sum = 0; double p[3],scale = 1; static double normalscale=1.; // used to renormalize added octaves static double currentInversePersistence=0; static double currentLacunarity=0; static int currentnoctaves=0; if (*NoiseResetFlag) if ((InversePersistence!=currentInversePersistence)||(Lacunarity!=currentLacunarity)||(n_octaves!=currentnoctaves)) { double dfscale=1.; // based on sqrt of sum of squares of scales double inversescale=1.; normalscale=0; for (i=0;i<n_octaves;i++) { inversescale = 1./dfscale; normalscale += inversescale*inversescale; dfscale *= InversePersistence; } normalscale=sqrt(normalscale); currentInversePersistence=InversePersistence; currentLacunarity=Lacunarity; currentnoctaves=n_octaves; *NoiseResetFlag=false; } p[0] = x; p[1] = y; p[2] = z; val=0; sum=0; for (i=0;i<n_octaves;i++) { val = pnoise3(p); sum += val / scale; scale *= InversePersistence; p[0] *= Lacunarity; p[1] *= Lacunarity; p[2] *= Lacunarity; } return(sum/(1.1*normalscale)); // the 1.1 is fudge to make 8 octave sum correct, but introduces some error at low octave counts } double FastfBm3DNoise(double x,double y,double z,int n_octaves,bool *NoiseResetFlag) // fixed invpersistence=2. and lacunarity=2. { if (n_octaves<1) n_octaves=1; if (n_octaves>6) n_octaves=6; int i; double val,sum = 0; double p[3],scale = 1; static double normalscale=1.; // used to renormalize added octaves static int currentnoctaves=0; if (*NoiseResetFlag) if (n_octaves!=currentnoctaves) { double dfscale=1.; // based on sqrt of sum of squares of scales double inversescale=1.; normalscale=0; for (i=0;i<n_octaves;i++) { inversescale = 1./dfscale; normalscale += inversescale*inversescale; dfscale *= 2.; } normalscale=sqrt(normalscale); currentnoctaves=n_octaves; *NoiseResetFlag=false; } p[0] = x; p[1] = y; p[2] = z; for (i=0;i<n_octaves;i++) { val = pnoise3(p); sum += val / scale; scale *= 2.; p[0] *= 2.05656; // to avoid artifacts avoid lacunarity of 2.0 p[1] *= 2.06756; // to avoid artifacts avoid lacunarity of 2.0 p[2] *= 2.06345; // to avoid artifacts avoid lacunarity of 2.0 } return(sum/(1.1*normalscale)); // the 1.1 is fudge to make 8 octave sum correct, but introduces some error at low octave counts } // -1 to +1 noise double fBm4DNoise(double x,double y,double z,double w,double InversePersistence,double Lacunarity,int n_octaves, bool *NoiseResetFlag) { if (n_octaves<1) n_octaves=1; if (n_octaves>6) n_octaves=6; if (InversePersistence<.5) InversePersistence=.5; if (InversePersistence>4.0) InversePersistence=4.0; if (Lacunarity<1.0) Lacunarity=1.0; if (Lacunarity>4.0) Lacunarity=4.0; int i; double val,sum = 0; double p[4],scale = 1; static double normalscale=1.; // used to renormalize added octaves static double currentInversePersistence=0; static double currentLacunarity=0; static int currentnoctaves=0; if (*NoiseResetFlag) if ((InversePersistence!=currentInversePersistence)||(Lacunarity!=currentLacunarity)||(n_octaves!=currentnoctaves)) { double dfscale=1.; // based on sqrt of sum of squares of scales double inversescale=1.; normalscale=0; for (i=0;i<n_octaves;i++) { inversescale = 1./dfscale; normalscale += inversescale*inversescale; dfscale *= InversePersistence; } normalscale=sqrt(normalscale); currentInversePersistence=InversePersistence; currentLacunarity=Lacunarity; currentnoctaves=n_octaves; *NoiseResetFlag=false; } p[0] = x; p[1] = y; p[2] = z; p[3] = w; for (i=0;i<n_octaves;i++) { val = npnoise4(p); sum += val / scale; scale *= InversePersistence; p[0] *= Lacunarity; p[1] *= Lacunarity; p[2] *= Lacunarity; p[3] *= Lacunarity; } return(sum/(1.3*normalscale)); // the 1.3 is fudge to make 8 octave sum correct, but introduces some error at low octave counts } double FastfBm4DNoise(double x,double y,double z,double w,int n_octaves, bool *NoiseResetFlag) { if (n_octaves<1) n_octaves=1; if (n_octaves>6) n_octaves=6; int i; double val,sum = 0; double p[4],scale = 1; static double normalscale=1.; // used to renormalize added octaves static int currentnoctaves=0; if (*NoiseResetFlag) if (n_octaves!=currentnoctaves) { double dfscale=1.; // based on sqrt of sum of squares of scales double inversescale=1.; normalscale=0; for (i=0;i<n_octaves;i++) { inversescale = 1./dfscale; normalscale += inversescale*inversescale; dfscale *= 2.; } normalscale=sqrt(normalscale); currentnoctaves=n_octaves; *NoiseResetFlag=false; } p[0] = x; p[1] = y; p[2] = z; p[3] = w; for (i=0;i<n_octaves;i++) { val = npnoise4(p); sum += val / scale; scale *= 2.; p[0] *= 2.05654; // to avoid artifacts avoid lacunarity of 2.0 p[1] *= 2.02384; p[2] *= 2.02378; p[3] *= 2.04532; } return(sum/(1.3*normalscale)); // the 1.3 is fudge to make 8 octave sum correct, but introduces some error at low octave counts } void initPerlin(void) { int i, j; for (i=0; i< 256; ++i) pp[256+i]=pp[i]=permutation[i]; for (i = 0 ; i < B ; i++) { p[i] = pp[i]; g1[i] = g_precomputed[i][0]; for (j = 0 ; j < 2 ; j++) g2[i][j] = g_precomputed[i][j]; normalize2(g2[i]); for (j = 0 ; j < 3 ; j++) g3[i][j] = g_precomputed[i][j]; // normalize3(g3[i]); // already normalized } for (i = 0 ; i < B + 2 ; i++) { p[B + i] = p[i]; g1[B + i] = g1[i]; for (j = 0 ; j < 2 ; j++) g2[B + i][j] = g2[i][j]; for (j = 0 ; j < 3 ; j++) g3[B + i][j] = g3[i][j]; } }
41,110
C++
.h
1,071
32.708683
303
0.569549
knchaffin/Meander
36
5
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,007
Meander.hpp
knchaffin_Meander/src/Meander.hpp
/* Copyright (C) 2019-2020 Ken Chaffin 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, version 3. 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 <https://www.gnu.org/licenses/>. */ #include "Common-Noise.hpp" bool doDebug = false; // set this to true to enable verbose DEBUG() logging static bool owned = false; bool globalsInitialized=false; // globals as initialized only during Module(), otherwise the global values are whatever they were set to here, if anything. bool Audit_enable=false; using namespace rack; #define CV_MAX10 (10.0f) #define CV_MAXn5 (5.0f) #define AUDIO_MAX (6.0f) #define VOCT_MAX (8.0f) #define AMP_MAX (2.0f) #define MAX_NOTES 12 #define MAX_STEPS 16 #define MAX_CIRCLE_STATIONS 12 #define MAX_HARMONIC_DEGREES 7 #define MAX_AVAILABLE_HARMONY_PRESETS 59 // change this as new harmony presets are created #define MAX_PARAMS 200 #define MAX_INPORTS 100 #define MAX_OUTPORTS 100 struct inPortState { bool inTransition=false; float lastValue=-999.; }; struct inPortState inportStates[MAX_INPORTS]; struct TinyPJ301MPort : SvgPort { TinyPJ301MPort() { setSvg(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyPJ301M.svg"))); } }; int time_sig_top = 4; int time_sig_bottom = 4; // make it a power of 8 #define MAXSHORTSTRLEN 16 struct CircleElement { // this data is mostly static, once created int chordType=0; // may be overridden by degree semicircle float startDegree; // of annular segment float endDegree; // of annular segment Vec pt1; //vertices of annular ring segment Vec pt2; Vec pt3; Vec pt4; Vec radialDirection; }; struct DegreeElement { // this data varies with root_key and mode int chordType=0; float startDegree; // of pie slice float endDegree; Vec pt1; //vertices of annular ring segment Vec pt2; Vec pt3; Vec pt4; Vec radialDirection; int Degree=1; // 1-7 corresponding to I-VII int CircleIndex=0; // correspondence between degree element and circle element. All degrees have one. }; struct DegreeSemiCircle { int RootKeyCircle5thsPosition=0; // semicircle [index] of "I" degree int OffsetSteps=0; // how many 30 degree steps the semicircle must be rotated to display correctly DegreeElement degreeElements[MAX_HARMONIC_DEGREES]; }; struct CircleOf5ths { float OuterCircleRadius=mm2px(47); float MiddleCircleRadius=mm2px(39); float InnerCircleRadius=mm2px(26); Vec CircleCenter= Vec(mm2px(116.75),mm2px(67.75)); int root_keyCirclePosition=0; int root_key_note=0; struct CircleElement Circle5ths[MAX_CIRCLE_STATIONS]; struct DegreeElement degreeElements[MAX_CIRCLE_STATIONS]; struct DegreeSemiCircle theDegreeSemiCircle; } theCircleOf5ths; bool circleChanged=true; int harmonyPresetChanged=0; int semiCircleDegrees[]={1, 5, 2, 6, 3, 7, 4}; // default order if starting at C int circleDegreeLookup[]= {0, 0, 2, 4, 6, 1, 3, 5}; // to convert from arabic roman equivalents to circle degrees int arabicStepDegreeSemicircleIndex[8]; // where is 1, 2... step in degree semicircle // [8] so 1 based indexing can be used //******************************************* struct HarmonyProgressionStepSettings // not currently utilized { int CircleOf5thsPosition=0; int ChordType=0; int Inversion=1; int Spread=0; int NumNotes=3; }; struct HarmonyProgressionStepSettings HarmonicProgression[MAX_STEPS]; // up to 16 steps in a progression int NumHarmonicProgressionSteps=4; // what is this? int mode_step_intervals[7][13]= { // num mode scale notes, semitones to next note 7 modes { 7, 2,2,2,1,2,2,1,0,0,0,0,0}, // Lydian { 7, 2,2,1,2,2,2,1,0,0,0,0,0}, // Major/Ionian { 7, 2,2,1,2,2,1,2,0,0,0,0,0}, // Mixolydian { 7, 2,1,2,2,2,1,2,0,0,0,0,0}, // Dorian { 7, 2,1,2,2,1,2,2,0,0,0,0,0}, // NMinor/Aeolian { 7, 1,2,2,2,1,2,2,0,0,0,0,0}, // Phrygian { 7, 1,2,2,1,2,2,2,0,0,0,0,0} // Locrian }; int root_key_signatures_chromaticForder[12][7]= // chromatic order 0=natural, 1=sharp, -1=flat { // F C G D A E B in order of root_key signature sharps and flats starting with F { 0, 0, 0, 0, 0, 0, 0}, // C - 0 { 0, 0,-1,-1,-1,-1,-1}, // Db - 1 { 1, 1, 0, 0, 0, 0, 0}, // D - 2 { 0, 0, 0, 0,-1,-1,-1}, // Eb - 3 { 1, 1, 1, 1, 0, 0, 0}, // E - 4 { 0, 0, 0, 0, 0, 0,-1}, // F - 5 { 1, 1, 1, 1, 1, 1, 0}, // F# - 6 { 1, 0, 0, 0, 0, 0, 0}, // G - 7 { 0, 0, 0,-1,-1,-1,-1}, // Ab - 8 { 1, 1, 1, 0, 0, 0, 0}, // A - 9 { 0, 0, 0, 0, 0,-1,-1}, // Bb - 10 { 1, 1, 1, 1, 1, 0, 0}, // B - 11 }; int root_key_sharps_vertical_display_offset[]={1, 4, 0, 3, 6, 2}; // left to right int root_key_flats_vertical_display_offset[]={5, 2, 6, 3, 7, 4}; // right to left #define MAX_MODES 7 int num_modes=MAX_MODES; char mode_names[MAX_MODES][16]; int mode=1; // Ionian/Major enum noteTypes { NOTE_TYPE_CHORD, NOTE_TYPE_MELODY, NOTE_TYPE_ARP, NOTE_TYPE_BASS, NOTE_TYPE_EXTERNAL }; struct note { int note; int noteType; // NOTE_TYPE_CHORD etc. int time32s; int length; // 1/1,2,4,8 int countInBar; }; int bar_note_count=0; // how many notes have been played in bar. Use it as index into played_notes_circular_buffer[] struct note played_notes_circular_buffer[256]; // worst case maximum of 256 harmony, melody and bass notes can be played per bar. const char* noteNames[MAX_NOTES] = {"C","C#/Db","D","D#/Eb","E","F","F#/Gb","G","G#/Ab","A","A#/Bb","B"}; const char* CircleNoteNames[MAX_NOTES] = {"C","G","D","A","E","B","F#","Db","Ab","Eb","Bb","F"}; #define MAX_ROOT_KEYS 12 int circle_root_key=0; // root_key position on the circle 0,1,2... CW int root_key=0; // 0 initially int notate_mode_as_signature_root_key=0; // 0 initially // any mode and root_key is equivalent to a maj key by transposing down these numbers of major scale semitones // Mode Transpose down by interval or semitones // Ionian Perfrect Unison 0 // Dorian Major second 2 // Phrygian Major third 4 // Lydian Perfect fourth 5 // Mixolydian Perfect fifth 7 // Aeolian Major sixth 9 // Locrian Major seventh 11 // more simply modes can also be transposed to major scale by using the mode natural roots semitone counts for white keys CDEFGAB int mode_natural_roots[MAX_MODES] = { // for which scale is all white notes these can also be used as transpose semitones if modes in IDPLMAL order 0, //C Ionian 2, //D Dorian 4, //E Phrygian 5, //F Lydian 7, //G Mixolydian 9, //A Aeolian 11 //B Locrian }; int mode_root_key_signature_offset[]={3,0,4,1,5,2,6}; // index into mode_natural_roots[] using the IDPLyMALo = 1,2,3,4,5,6,7 rule for Meander mode ordering char root_key_name[MAXSHORTSTRLEN]; char root_key_names[MAX_ROOT_KEYS][MAXSHORTSTRLEN]; #define MAX_NOTES_CANDIDATES 130 int notes[MAX_NOTES_CANDIDATES]; int num_notes=0; int root_key_notes[MAX_ROOT_KEYS][MAX_NOTES_CANDIDATES]; int num_root_key_notes[MAX_ROOT_KEYS]; int meter_numerator=4; // need to unify with sig_top... int meter_denominator=4; char note_desig[MAX_NOTES][MAXSHORTSTRLEN]; char note_desig_sharps[MAX_NOTES][MAXSHORTSTRLEN]; char note_desig_flats[MAX_NOTES][MAXSHORTSTRLEN]; struct HarmonyParms { bool enabled=true; float volume=10.0f; // 0-10 V int note_length_divisor=1; // 1, 2, 4, 8 doHarmony() on these boundaries int target_octave=4; double note_octave_range=1.0; double note_avg_target=target_octave/10.0; double range_top= note_avg_target + (note_octave_range/10.0); double range_bottom= note_avg_target - (note_octave_range/10.0); double r1=(range_top-range_bottom); double note_avg= note_avg_target; double alpha=.1; double seed=1234; int noctaves=3; float period=100.0; int last_circle_step=-1; // used for Markov chains int last_chord_type=0; int bar_harmony_chords_counted_note=0; bool enable_all_7ths=false; bool enable_V_7ths=false; bool enable_staccato=false; int pending_step_edit=0; struct note last[4]; float lastCircleDegreeIn=0; int STEP_inport_connected_to_Meander_trigger_port=0; }; struct MelodyParms { bool enabled=true; bool chordal=true; bool scaler=false; float volume=8.0f; // 0-10 V int note_length_divisor=4; double target_octave=3.0; // 4=middle-C C4 0v must be an integer value double note_octave_range=1.0; double note_avg_target=target_octave/10.0; double range_top= note_avg_target + (note_octave_range/10.0); double range_bottom= note_avg_target - (note_octave_range/10.0); double r1=(range_top-range_bottom); double note_avg= note_avg_target; double alpha=.9; double seed=12345; int noctaves=4; float period=10.0; bool destutter=false; bool stutter_detected=false; int last_stutter_step=0; int last_chord_note_index=0; int last_step=1; int bar_melody_counted_note=0; bool enable_staccato=true; struct note last[1]; float lastMelodyDegreeIn=0.0f; }; struct ArpParms { bool enabled=false; bool chordal=true; bool scaler=false; int count=3; int note_length_divisor=16; // 8, 16, 32 float decay=0; int pattern=0; int note_count=0; // number of arp notes played per current melody note double seed=123344; int noctaves=5; float period=1.0; struct note last[32]; // may not need this if arp is considered melody }; struct BassParms { bool enabled=true; int target_octave=2; int note_length_divisor=1; // 1, 2, 4, 8 doHarmony() on these boundaries bool octave_enabled=true; // play bass as 2 notes an octave apart float volume=10.0f; // 0-10 V int bar_bass_counted_note=0; bool accent=false; // enables accents bool syncopate=false; bool shuffle=false; struct note last[4]; bool enable_staccato= true; bool note_accented=false; // is current played note accented }; struct MeanderState { HarmonyParms theHarmonyParms; MelodyParms theMelodyParms; BassParms theBassParms; ArpParms theArpParms; bool userControllingHarmonyFromCircle=false; int last_harmony_chord_root_note=0; int last_harmony_step=0; int circleDegree=1; bool userControllingMelody=false; } theMeanderState; char chord_type_name[30][MAXSHORTSTRLEN]; int chord_type_intervals[30][16]; int chord_type_num_notes[30]; int current_chord_notes[16]; #define MAX_HARMONY_TYPES 100 // for up to MAX_HARMONY_TYPES harmony_types, up to MAX_STEPS steps int harmony_type=14; // 1- MAX_AVAILABLE_HARMONY_PRESETS bool randomize_harmony=false; struct HarmonyType { int harmony_type; // used by theActiveHarmonyType char harmony_type_desc[64]; char harmony_degrees_desc[128]; int num_harmony_steps=1; int min_steps=1; int max_steps=1; int harmony_step_chord_type[MAX_STEPS]; int harmony_steps[MAX_STEPS]={1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}; // initialize to a valid step degree }; struct HarmonyType theHarmonyTypes[MAX_HARMONY_TYPES]; struct HarmonyType theActiveHarmonyType; int circle_of_fifths[MAX_CIRCLE_STATIONS]; int home_circle_position; int current_circle_position; int last_circle_position; char circle_of_fifths_degrees[][MAXSHORTSTRLEN]= { "I", "V", "II", "vi", "iii", "vii", "IV" }; char circle_of_fifths_arabic_degrees[][MAXSHORTSTRLEN]= { "", "I", "II", "III", "IV", "V", "IV", "VII" }; char circle_of_fifths_degrees_UC[][MAXSHORTSTRLEN]= { "I", "V", "II", "VI", "III", "VII", "IV" }; char circle_of_fifths_degrees_LC[][MAXSHORTSTRLEN]= { "i", "v", "ii", "vi", "iii", "vii", "iv" }; int step_chord_notes[MAX_STEPS][MAX_NOTES_CANDIDATES]; int num_step_chord_notes[MAX_STEPS]={}; // Markov 1st order row to column transition probabiliites float MarkovProgressionTransitionMatrixTemplate[8][8]={ // 8x8 so degrees can be 1 indexed {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00}, // dummy {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00}, // I {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00}, // II {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00}, // III {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00}, // IV {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00}, // V {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00}, // VI {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00}}; // VII // dummy I II III IV V VI VII // Markov 1st order row to column transition probabiliites float MarkovProgressionTransitionMatrix_I_IV_V[8][8]={ // 8x8 so degrees can be 1 indexed {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00}, // dummy {0.00, 0.00, 0.00, 0.00, 0.60, 0.40, 0.00, 0.00}, // I {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00}, // II {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00}, // III {0.00, 0.20, 0.00, 0.00, 0.00, 0.80, 0.00, 0.00}, // IV {0.00, 0.70, 0.00, 0.00, 0.30, 0.00, 0.00, 0.00}, // V {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00}, // VI {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00}}; // VII // dummy I II III IV V VI VII // Markov 1st order row to column transition probabiliites float MarkovProgressionTransitionMatrixBach1[8][8]={ // 8x8 so degrees can be 1 indexed {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00}, // dummy {0.00, 0.00, 0.18, 0.01, 0.20, 0.41, 0.09, 0.12}, // I {0.00, 0.01, 0.00, 0.03, 0.00, 0.89, 0.00, 0.07}, // II {0.00, 0.06, 0.06, 0.00, 0.25, 0.19, 0.31, 0.13}, // III {0.00, 0.22, 0.14, 0.00, 0.00, 0.48, 0.00, 0.15}, // IV {0.00, 0.80, 0.00, 0.02, 0.06, 0.00, 0.10, 0.20}, // V {0.00, 0.03, 0.54, 0.03, 0.14, 0.19, 0.00, 0.08}, // VI {0.00, 0.81, 0.00, 0.01, 0.03, 0.15, 0.00, 0.00}}; // VII // dummy I II III IV V VI VII // Markov 1st order row to column transition probabiliites float MarkovProgressionTransitionMatrixBach2[8][8]={ // 8x8 so degrees can be 1 indexed {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00}, // dummy {0.00, 0.00, 0.15, 0.01, 0.28, 0.41, 0.09, 0.06}, // I {0.00, 0.01, 0.00, 0.00, 0.00, 0.71, 0.01, 0.25}, // II {0.00, 0.03, 0.03, 0.00, 0.52, 0.06, 0.32, 0.03}, // III {0.00, 0.22, 0.13, 0.00, 0.00, 0.39, 0.02, 0.23}, // IV {0.00, 0.82, 0.01, 0.00, 0.07, 0.00, 0.09, 0.00}, // V {0.00, 0.15, 0.29, 0.05, 0.11, 0.32, 0.00, 0.09}, // VI {0.00, 0.91, 0.00, 0.01, 0.02, 0.04, 0.03, 0.00}}; // VII // dummy I II III IV V VI VII // Markov 1st order row to column transition probabiliites float MarkovProgressionTransitionMatrixMozart1[8][8]={ // 8x8 so degrees can be 1 indexed {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00}, // dummy {0.00, 0.00, 0.08, 0.00, 0.07, 0.68, 0.06, 0.11}, // I {0.00, 0.37, 0.00, 0.00, 0.00, 0.46, 0.00, 0.17}, // II {0.00, 0.00, 0.00, 0.00, 1.00, 0.00, 0.00, 0.00}, // III {0.00, 0.42, 0.10, 0.00, 0.00, 0.39, 0.00, 0.09}, // IV {0.00, 0.82, 0.00, 0.00, 0.05, 0.00, 0.07, 0.05}, // V {0.00, 0.14, 0.51, 0.00, 0.16, 0.05, 0.00, 0.14}, // VI {0.00, 0.76, 0.01, 0.00, 0.00, 0.23, 0.00, 0.00}}; // VII // dummy I II III IV V VI VII // Markov 1st order row to column transition probabiliites float MarkovProgressionTransitionMatrixMozart2[8][8]={ // 8x8 so degrees can be 1 indexed {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00}, // dummy {0.00, 0.00, 0.13, 0.00, 0.15, 0.62, 0.05, 0.05}, // I {0.00, 0.49, 0.00, 0.01, 0.00, 0.40, 0.01, 0.09}, // II {0.00, 0.67, 0.00, 0.00, 0.00, 0.00, 0.33, 0.00}, // III {0.00, 0.64, 0.14, 0.00, 0.00, 0.15, 0.00, 0.07}, // IV {0.00, 0.94, 0.00, 0.00, 0.01, 0.00, 0.04, 0.01}, // V {0.00, 0.11, 0.51, 0.00, 0.14, 0.20, 0.00, 0.04}, // VI {0.00, 0.82, 0.00, 0.01, 0.01, 0.16, 0.00, 0.00}}; // VII // dummy I II III IV V VI VII // Markov 1st order row to column transition probabiliites float MarkovProgressionTransitionMatrixPalestrina1[8][8]={ // 8x8 so degrees can be 1 indexed {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00}, // dummy {0.00, 0.00, 0.15, 0.13, 0.28, 0.14, 0.22, 0.08}, // I {0.00, 0.08, 0.00, 0.15, 0.13, 0.28, 0.14, 0.22}, // II {0.00, 0.22, 0.08, 0.00, 0.15, 0.13, 0.28, 0.14}, // III {0.00, 0.14, 0.22, 0.08, 0.00, 0.15, 0.13, 0.28}, // IV {0.00, 0.28, 0.14, 0.22, 0.08, 0.00, 0.15, 0.13}, // V {0.00, 0.13, 0.28, 0.14, 0.22, 0.08, 0.00, 0.15}, // VI {0.00, 0.15, 0.13, 0.28, 0.14, 0.22, 0.08, 0.00}}; // VII // dummy I II III IV V VI VII // Markov 1st order row to column transition probabiliites float MarkovProgressionTransitionMatrixBeethoven1[8][8]={ // 8x8 so degrees can be 1 indexed {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00}, // dummy {0.00, 0.00, 0.10, 0.01, 0.13, 0.52, 0.02, 0.22}, // I {0.00, 0.06, 0.00, 0.02, 0.00, 0.87, 0.00, 0.05}, // II {0.00, 0.00, 0.00, 0.00, 0.00, 0.67, 0.33, 0.00}, // III {0.00, 0.33, 0.03, 0.07, 0.00, 0.40, 0.03, 0.13}, // IV {0.00, 0.56, 0.22, 0.01, 0.04, 0.00, 0.07, 0.11}, // V {0.00, 0.06, 0.44, 0.00, 0.06, 0.11, 0.00, 0.33}, // VI {0.00, 0.80, 0.00, 0.00, 0.03, 0.17, 0.00, 0.00}}; // VII // dummy I II III IV V VI VII // Markov 1st order row to column transition probabiliites float MarkovProgressionTransitionMatrixTraditional1[8][8]={ // 8x8 so degrees can be 1 indexed {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00}, // dummy {0.00, 0.00, 0.00, 0.25, 0.25, 0.25, 0.25, 0.00}, // I {0.00, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.50}, // II {0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 1.00, 0.00}, // III {0.00, 0.25, 0.25, 0.00, 0.00, 0.25, 0.00, 0.25}, // IV {0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00}, // V {0.00, 0.00, 0.50, 0.00, 0.50, 0.00, 0.00, 0.00}, // VI {0.00, 0.50, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00}}; // VII // dummy I II III IV V VI VII struct chord_type_info { char name[MAXSHORTSTRLEN]=""; int num_notes=0; int intervals[8]={0,0,0,0,0,0,0,0}; }; struct chord_type_info chordTypeInfo[30]; void init_vars() { if (doDebug) DEBUG("init_vars()"); circle_of_fifths[0]=0; circle_of_fifths[1]=7; circle_of_fifths[2]=2; circle_of_fifths[3]=9; circle_of_fifths[4]=4; circle_of_fifths[5]=11; circle_of_fifths[6]=6; circle_of_fifths[7]=1; circle_of_fifths[8]=8; circle_of_fifths[9]=3; circle_of_fifths[10]=10; circle_of_fifths[11]=5; strcpy(note_desig[0],"C"); strcpy(note_desig[1],"Db"); strcpy(note_desig[2],"D"); strcpy(note_desig[3],"Eb"); strcpy(note_desig[4],"E"); strcpy(note_desig[5],"F"); strcpy(note_desig[6],"F#"); strcpy(note_desig[7],"G"); strcpy(note_desig[8],"Ab"); strcpy(note_desig[9],"A"); strcpy(note_desig[10],"Bb"); strcpy(note_desig[11],"B"); strcpy(note_desig_sharps[0],"C"); strcpy(note_desig_sharps[1],"C#"); strcpy(note_desig_sharps[2],"D"); strcpy(note_desig_sharps[3],"D#"); strcpy(note_desig_sharps[4],"E"); strcpy(note_desig_sharps[5],"F"); strcpy(note_desig_sharps[6],"F#"); strcpy(note_desig_sharps[7],"G"); strcpy(note_desig_sharps[8],"G#"); strcpy(note_desig_sharps[9],"A"); strcpy(note_desig_sharps[10],"A#"); strcpy(note_desig_sharps[11],"B"); strcpy(note_desig_flats[0],"C"); strcpy(note_desig_flats[1],"Db"); strcpy(note_desig_flats[2],"D"); strcpy(note_desig_flats[3],"Eb"); strcpy(note_desig_flats[4],"E"); strcpy(note_desig_flats[5],"F"); strcpy(note_desig_flats[6],"Gb"); strcpy(note_desig_flats[7],"G"); strcpy(note_desig_flats[8],"Ab"); strcpy(note_desig_flats[9],"A"); strcpy(note_desig_flats[10],"Bb"); strcpy(note_desig_flats[11],"B"); strcpy(root_key_names[0],"C"); strcpy(root_key_names[1],"Db"); strcpy(root_key_names[2],"D"); strcpy(root_key_names[3],"Eb"); strcpy(root_key_names[4],"E"); strcpy(root_key_names[5],"F"); strcpy(root_key_names[6],"F#"); strcpy(root_key_names[7],"G"); strcpy(root_key_names[8],"Ab"); strcpy(root_key_names[9],"A"); strcpy(root_key_names[10],"Bb"); strcpy(root_key_names[11],"B"); strcpy(mode_names[0],"Lydian"); strcpy(mode_names[1],"Ionian/Major"); strcpy(mode_names[2],"Mixolydian"); strcpy(mode_names[3],"Dorian"); strcpy(mode_names[4],"Aeolian/NMinor"); strcpy(mode_names[5],"Phrygian"); strcpy(mode_names[6],"Locrian"); strcpy(chord_type_name[0],"Major"); chord_type_num_notes[0]=3; chord_type_intervals[0][0]=0; chord_type_intervals[0][1]=4; chord_type_intervals[0][2]=7; strcpy(chord_type_name[1],"Minor"); chord_type_num_notes[1]=3; chord_type_intervals[1][0]=0; chord_type_intervals[1][1]=3; chord_type_intervals[1][2]=7; strcpy(chord_type_name[2],"7th"); // usually a dominant 7th chord is a major triad with minor 7th chord_type_num_notes[2]=4; chord_type_intervals[2][0]=0; chord_type_intervals[2][1]=4; chord_type_intervals[2][2]=7; chord_type_intervals[2][3]=10; strcpy(chord_type_name[3],"maj7th"); chord_type_num_notes[3]=4; chord_type_intervals[3][0]=0; chord_type_intervals[3][1]=4; chord_type_intervals[3][2]=7; chord_type_intervals[3][3]=11; strcpy(chord_type_name[4],"min7th"); chord_type_num_notes[4]=4; chord_type_intervals[4][0]=0; chord_type_intervals[4][1]=3; chord_type_intervals[4][2]=7; chord_type_intervals[4][3]=10; strcpy(chord_type_name[5],"dim7th"); chord_type_num_notes[5]=4; chord_type_intervals[5][0]=0; chord_type_intervals[5][1]=3; chord_type_intervals[5][2]=6; chord_type_intervals[5][3]=10; strcpy(chord_type_name[6],"Dim"); chord_type_num_notes[6]=3; chord_type_intervals[6][0]=0; chord_type_intervals[6][1]=3; chord_type_intervals[6][2]=6; strcpy(chord_type_name[7],"Aug"); chord_type_num_notes[7]=3; chord_type_intervals[7][0]=0; chord_type_intervals[7][1]=4; chord_type_intervals[7][2]=8; strcpy(chord_type_name[8],"6th"); chord_type_num_notes[8]=4; chord_type_intervals[8][0]=0; chord_type_intervals[8][1]=4; chord_type_intervals[8][2]=7; chord_type_intervals[8][3]=9; strcpy(chord_type_name[9],"min6th"); chord_type_num_notes[9]=4; chord_type_intervals[9][0]=0; chord_type_intervals[9][1]=3; chord_type_intervals[9][2]=7; chord_type_intervals[9][3]=9; strcpy(chord_type_name[10],"dim6th"); chord_type_num_notes[10]=4; chord_type_intervals[10][0]=0; chord_type_intervals[10][1]=4; chord_type_intervals[10][2]=6; chord_type_intervals[10][3]=9; strcpy(chord_type_name[11],"9th"); chord_type_num_notes[11]=5; chord_type_intervals[11][0]=0; chord_type_intervals[11][1]=4; chord_type_intervals[11][2]=7; chord_type_intervals[11][3]=10; chord_type_intervals[11][4]=14; strcpy(chord_type_name[12],"10th"); chord_type_num_notes[12]=2; chord_type_intervals[12][0]=0; chord_type_intervals[12][1]=9; strcpy(chord_type_name[13],"11th"); chord_type_num_notes[13]=6; chord_type_intervals[13][0]=0; chord_type_intervals[13][1]=4; chord_type_intervals[13][2]=7; chord_type_intervals[13][3]=10; chord_type_intervals[13][4]=14; chord_type_intervals[13][5]=17; strcpy(chord_type_name[14],"13th"); chord_type_num_notes[14]=7; chord_type_intervals[14][0]=0; chord_type_intervals[14][1]=4; chord_type_intervals[14][2]=7; chord_type_intervals[14][3]=10; chord_type_intervals[14][4]=14; chord_type_intervals[14][5]=17; chord_type_intervals[14][6]=21; strcpy(chord_type_name[15],"Quartel"); chord_type_num_notes[15]=4; chord_type_intervals[15][0]=0; chord_type_intervals[15][1]=5; chord_type_intervals[15][2]=10; chord_type_intervals[15][3]=15; strcpy(chord_type_name[16],"Perf5th"); chord_type_num_notes[16]=4; chord_type_intervals[16][0]=0; chord_type_intervals[16][1]=7; chord_type_intervals[16][2]=14; chord_type_intervals[16][3]=21; strcpy(chord_type_name[17],"Scalar"); chord_type_num_notes[17]=3; chord_type_intervals[17][0]=0; chord_type_intervals[17][1]=4; chord_type_intervals[17][2]=7; notes[0]=root_key; } void init_notes() { if (doDebug) DEBUG("init_notes()"); notes[0]=root_key; int nmn=mode_step_intervals[mode][0]; // number of mode notes if (doDebug) DEBUG("notes[%d]=%d %s", 0, notes[0], note_desig[notes[0]%MAX_NOTES]); num_notes=0; for (int i=1;i<127;++i) { notes[i]=notes[i-1]+ mode_step_intervals[mode][((i-1)%nmn)+1]; if (doDebug) DEBUG("notes[%d]=%d %s", i, notes[i], note_desig[notes[i]%MAX_NOTES]); ++num_notes; if (notes[i]>=127) break; } if (doDebug) DEBUG("num_notes=%d", num_notes); for (int j=0;j<12;++j) { if (doDebug) DEBUG("root_key=%s", root_key_names[j]); root_key_notes[j][0]=j; num_root_key_notes[j]=1; int num_mode_notes=10*mode_step_intervals[mode][0]; // the [0] entry is the notes per scale value, times 10 ocatves of midi if (true) { if (doDebug) DEBUG(" num_mode_notes=%d", num_mode_notes); if (doDebug) DEBUG("root_key_notes[%d][0]=%d %s", j, root_key_notes[j][0], note_desig[root_key_notes[j][0]]); } int nmn=mode_step_intervals[mode][0]; // number of mode notes for (int i=1;i<num_mode_notes ;++i) { root_key_notes[j][i]=root_key_notes[j][i-1]+ mode_step_intervals[mode][((i-1)%nmn)+1]; if (doDebug) DEBUG("root_key_notes[%d][%d]=%d %s", j, i, root_key_notes[j][i], note_desig[root_key_notes[j][i]%MAX_NOTES]); ++num_root_key_notes[j]; } if (doDebug) DEBUG(" num_root_key_notes[%d]=%d", j, num_root_key_notes[j]); } char strng[128]; strcpy(strng,""); for (int i=0;i<mode_step_intervals[mode][0];++i) { strcat(strng,note_desig[notes[i]%MAX_NOTES]); } if (doDebug) DEBUG("mode=%d root_key=%d root_key_notes[%d]=%s", mode, root_key, root_key, strng); } void AuditHarmonyData(int source) { if (!Audit_enable) return; if (doDebug) DEBUG("AuditHarmonyData()-begin-source=%d", source); for (int j=1;j<MAX_AVAILABLE_HARMONY_PRESETS;++j) { if ((theHarmonyTypes[j].num_harmony_steps<1)||(theHarmonyTypes[j].num_harmony_steps>MAX_STEPS)) { if (doDebug) DEBUG(" warning-theHarmonyTypes[%d].num_harmony_steps=%d", j, theHarmonyTypes[j].num_harmony_steps); } for (int i=0;i<MAX_STEPS;++i) { if ((theHarmonyTypes[j].harmony_steps[i]<1)||(theHarmonyTypes[j].harmony_steps[i]>MAX_HARMONIC_DEGREES)) { if (doDebug) DEBUG(" warning-theHarmonyTypes[%d].harmony_steps[%d]=%d", j, i, theHarmonyTypes[j].harmony_steps[i]); } } } if (doDebug) DEBUG("AuditHarmonyData()-end"); } void init_harmony() { if (doDebug) DEBUG("init_harmony"); // int i,j; for (int j=0;j<MAX_HARMONY_TYPES;++j) { theHarmonyTypes[j].num_harmony_steps=1; // just so it is initialized theHarmonyTypes[j].min_steps=1; theHarmonyTypes[j].max_steps=theHarmonyTypes[j].num_harmony_steps; strcpy(theHarmonyTypes[j].harmony_type_desc, ""); strcpy(theHarmonyTypes[j].harmony_degrees_desc, ""); for (int i=0;i<MAX_STEPS;++i) { theHarmonyTypes[j].harmony_step_chord_type[i]=0; // set to major as a default, may be overridden by specific types theHarmonyTypes[j].harmony_steps[i]=1; // put a valid step in so that if an out of range value is accessed it will not be invalid } } //semiCircleDegrees[]={1, 5, 2, 6, 3, 7, 4}; // (harmony_type==1) /* typical classical */ // I + n and descend by 4ths strcpy(theHarmonyTypes[1].harmony_type_desc, "50's Classic R&R do-wop and jazz" ); strcpy(theHarmonyTypes[1].harmony_degrees_desc, "I - VI - II - V" ); if (doDebug) DEBUG(theHarmonyTypes[1].harmony_type_desc); theHarmonyTypes[1].num_harmony_steps=4; // 1-7 theHarmonyTypes[1].min_steps=1; theHarmonyTypes[1].max_steps=theHarmonyTypes[1].num_harmony_steps; theHarmonyTypes[1].harmony_steps[0]=1; for (int i=1; i<theHarmonyTypes[1].num_harmony_steps; ++i) theHarmonyTypes[1].harmony_steps[i]=(semiCircleDegrees[theHarmonyTypes[1].num_harmony_steps-i])%7; // (harmony_type==2) /* typical elementary classical */ strcpy(theHarmonyTypes[2].harmony_type_desc, "elem.. classical 1" ); strcpy(theHarmonyTypes[2].harmony_degrees_desc, "I - IV - I - V" ); if (doDebug) DEBUG(theHarmonyTypes[2].harmony_type_desc); theHarmonyTypes[2].num_harmony_steps=4; theHarmonyTypes[2].min_steps=1; theHarmonyTypes[2].max_steps=theHarmonyTypes[2].num_harmony_steps; theHarmonyTypes[2].harmony_steps[0]=1; theHarmonyTypes[2].harmony_steps[1]=4; theHarmonyTypes[2].harmony_steps[2]=1; theHarmonyTypes[2].harmony_steps[3]=5; // (harmony_type==3) /* typical romantic */ // basically alternating between two root_keys, one major and one minor strcpy(theHarmonyTypes[3].harmony_type_desc, "romantic - alt root_keys" ); strcpy(theHarmonyTypes[3].harmony_degrees_desc, "I - IV - V - I - VI - II - III - VI" ); if (doDebug) DEBUG(theHarmonyTypes[3].harmony_type_desc); theHarmonyTypes[3].num_harmony_steps=8; theHarmonyTypes[3].min_steps=1; theHarmonyTypes[3].max_steps=theHarmonyTypes[3].num_harmony_steps; theHarmonyTypes[3].harmony_steps[0]=1; theHarmonyTypes[3].harmony_steps[1]=4; theHarmonyTypes[3].harmony_steps[2]=5; theHarmonyTypes[3].harmony_steps[3]=1; theHarmonyTypes[3].harmony_steps[4]=6; theHarmonyTypes[3].harmony_steps[5]=2; theHarmonyTypes[3].harmony_steps[6]=3; theHarmonyTypes[3].harmony_steps[7]=6; // (harmony_type==4) /* custom */ strcpy(theHarmonyTypes[4].harmony_type_desc, "custom" ); theHarmonyTypes[4].num_harmony_steps=16; theHarmonyTypes[4].min_steps=1; theHarmonyTypes[4].max_steps=theHarmonyTypes[4].num_harmony_steps; for (int i=0;i<theHarmonyTypes[4].num_harmony_steps;++i) theHarmonyTypes[4].harmony_steps[i] = 1; // must not be 0 // (harmony_type==5) /* elementary classical 2 */ strcpy(theHarmonyTypes[5].harmony_type_desc, "the classic I - IV - V" ); strcpy(theHarmonyTypes[5].harmony_degrees_desc, "I - IV - V - I" ); if (doDebug) DEBUG(theHarmonyTypes[5].harmony_type_desc); theHarmonyTypes[5].num_harmony_steps=4; theHarmonyTypes[5].min_steps=1; theHarmonyTypes[5].max_steps=theHarmonyTypes[5].num_harmony_steps; theHarmonyTypes[5].harmony_steps[0]=1; theHarmonyTypes[5].harmony_steps[1]=4; theHarmonyTypes[5].harmony_steps[2]=5; theHarmonyTypes[5].harmony_steps[3]=1; // (harmony_type==6) /* elementary classical 3 */ strcpy(theHarmonyTypes[6].harmony_type_desc, "elem. classical 3" ); strcpy(theHarmonyTypes[6].harmony_degrees_desc, "I - IV - V - IV" ); if (doDebug) DEBUG("theHarmonyTypes[6].harmony_type_desc"); theHarmonyTypes[6].num_harmony_steps=4; theHarmonyTypes[6].min_steps=1; theHarmonyTypes[6].max_steps=theHarmonyTypes[6].num_harmony_steps; theHarmonyTypes[6].harmony_steps[0]=1; theHarmonyTypes[6].harmony_steps[1]=4; theHarmonyTypes[6].harmony_steps[2]=5; theHarmonyTypes[6].harmony_steps[3]=4; // (harmony_type==7) /* strong 1 */ strcpy(theHarmonyTypes[7].harmony_type_desc, "strong return by 4ths" ); strcpy(theHarmonyTypes[7].harmony_degrees_desc, "I - III - VI - IV - V" ); if (doDebug) DEBUG(theHarmonyTypes[7].harmony_type_desc); theHarmonyTypes[7].num_harmony_steps=5; theHarmonyTypes[7].min_steps=1; theHarmonyTypes[7].max_steps=theHarmonyTypes[7].num_harmony_steps; theHarmonyTypes[7].harmony_steps[0]=1; theHarmonyTypes[7].harmony_steps[1]=3; theHarmonyTypes[7].harmony_steps[2]=6 ; theHarmonyTypes[7].harmony_steps[3]=4; theHarmonyTypes[7].harmony_steps[4]=5; // (harmony_type==8) // strong random the harmony chord stays fixed and only the melody varies. Good for checking harmony meander strcpy(theHarmonyTypes[8].harmony_type_desc, "stay on I" ); strcpy(theHarmonyTypes[8].harmony_degrees_desc, "I" ); if (doDebug) DEBUG(theHarmonyTypes[8].harmony_type_desc); theHarmonyTypes[8].num_harmony_steps=1; theHarmonyTypes[8].min_steps=1; theHarmonyTypes[8].max_steps=theHarmonyTypes[8].num_harmony_steps; theHarmonyTypes[8].harmony_steps[0]=1; //semiCircleDegrees[]={1, 5, 2, 6, 3, 7, 4}; // (harmony_type==9) // harmonic+ C, G, D,... CW by 5ths strcpy(theHarmonyTypes[9].harmony_type_desc, "harmonic+ CW 5ths" ); strcpy(theHarmonyTypes[9].harmony_degrees_desc, "I - V - II - VI - III - VII - IV" ); if (doDebug) DEBUG(theHarmonyTypes[9].harmony_type_desc); theHarmonyTypes[9].num_harmony_steps=7; // 1-7 theHarmonyTypes[9].min_steps=1; theHarmonyTypes[9].max_steps=theHarmonyTypes[9].num_harmony_steps; for (int i=0;i<theHarmonyTypes[9].num_harmony_steps;++i) theHarmonyTypes[9].harmony_steps[i] = 1+semiCircleDegrees[i]%7; // (harmony_type==10) // harmonic- C, F#, B,... CCW by 4ths strcpy(theHarmonyTypes[10].harmony_type_desc, "circle- CCW up by 4ths" ); strcpy(theHarmonyTypes[10].harmony_degrees_desc, "I - IV - VII - III - VI - II - V" ); if (doDebug) DEBUG(theHarmonyTypes[10].harmony_type_desc); theHarmonyTypes[10].num_harmony_steps=7; // 1-7 theHarmonyTypes[10].min_steps=1; theHarmonyTypes[10].max_steps=theHarmonyTypes[10].num_harmony_steps; for (int i=0;i<theHarmonyTypes[10].num_harmony_steps;++i) theHarmonyTypes[10].harmony_steps[i] = 1+(semiCircleDegrees[7-i])%7; // (harmony_type==11) // tonal+ // C, D, E, F, ... strcpy(theHarmonyTypes[11].harmony_type_desc, "tonal+" ); strcpy(theHarmonyTypes[11].harmony_degrees_desc, "I - II - III - IV - V - VI - VII" ); if (doDebug) DEBUG(theHarmonyTypes[11].harmony_type_desc); theHarmonyTypes[11].num_harmony_steps=7; // 1-7 theHarmonyTypes[11].min_steps=1; theHarmonyTypes[11].max_steps=theHarmonyTypes[11].num_harmony_steps; for (int i=0;i<theHarmonyTypes[11].num_harmony_steps;++i) theHarmonyTypes[11].harmony_steps[i] = 1+ i%7; // (harmony_type==12) // tonal- // C, B, A, ... strcpy(theHarmonyTypes[12].harmony_type_desc, "tonal-" ); strcpy(theHarmonyTypes[12].harmony_degrees_desc, "I - VII - VI - V - IV - III - II" ); if (doDebug) DEBUG(theHarmonyTypes[12].harmony_type_desc); theHarmonyTypes[12].num_harmony_steps=7; // 1-7 theHarmonyTypes[12].min_steps=1; theHarmonyTypes[12].max_steps=theHarmonyTypes[12].num_harmony_steps; for (int i=0;i<theHarmonyTypes[12].num_harmony_steps;++i) theHarmonyTypes[12].harmony_steps[i] = 1+ (7-i)%7; //semiCircleDegrees[]={1, 5, 2, 6, 3, 7, 4}; // (harmony_type==13) /* 12 bar blues classical*/ strcpy(theHarmonyTypes[13].harmony_type_desc, "12 bar blues 1 traditional" ); strcpy(theHarmonyTypes[13].harmony_degrees_desc, "I - I - I - I - IV - IV - I - I - V - V - I - I" ); if (doDebug) DEBUG(theHarmonyTypes[13].harmony_type_desc); meter_numerator=3; meter_denominator=4; theHarmonyTypes[13].num_harmony_steps=12; theHarmonyTypes[13].min_steps=1; theHarmonyTypes[13].max_steps=theHarmonyTypes[13].num_harmony_steps; theHarmonyTypes[13].harmony_steps[0]=1; theHarmonyTypes[13].harmony_steps[1]=1; theHarmonyTypes[13].harmony_steps[2]=1; theHarmonyTypes[13].harmony_steps[3]=1; theHarmonyTypes[13].harmony_steps[4]=4; theHarmonyTypes[13].harmony_steps[5]=4; theHarmonyTypes[13].harmony_steps[6]=1; theHarmonyTypes[13].harmony_steps[7]=1; theHarmonyTypes[13].harmony_steps[8]=5; theHarmonyTypes[13].harmony_steps[9]=5; theHarmonyTypes[13].harmony_steps[10]=1; theHarmonyTypes[13].harmony_steps[11]=1; // (harmony_type==14) /* shuffle 12 bar blues */ strcpy(theHarmonyTypes[14].harmony_type_desc, "12 bar blues 2 shuffle" ); strcpy(theHarmonyTypes[14].harmony_degrees_desc, "I - I - I - I - IV - IV - I - I - V - IV - I - I" ); if (doDebug) DEBUG(theHarmonyTypes[14].harmony_type_desc); meter_numerator=3; meter_denominator=4; theHarmonyTypes[14]. num_harmony_steps=12; theHarmonyTypes[14].min_steps=1; theHarmonyTypes[14].max_steps=theHarmonyTypes[14].num_harmony_steps; theHarmonyTypes[14].harmony_steps[0]=1; theHarmonyTypes[14].harmony_steps[1]=1; theHarmonyTypes[14].harmony_steps[2]=1; theHarmonyTypes[14].harmony_steps[3]=1; theHarmonyTypes[14].harmony_steps[4]=4; theHarmonyTypes[14].harmony_steps[5]=4; theHarmonyTypes[14].harmony_steps[6]=1; theHarmonyTypes[14].harmony_steps[7]=1; theHarmonyTypes[14].harmony_steps[8]=5; theHarmonyTypes[14].harmony_steps[9]=4; theHarmonyTypes[14].harmony_steps[10]=1; theHarmonyTypes[14].harmony_steps[11]=1; // (harmony_type==15) /* country 1 */ strcpy(theHarmonyTypes[15].harmony_type_desc, "country 1" ); strcpy(theHarmonyTypes[15].harmony_degrees_desc, "I - IV - V - I - I - IV - V - I" ); if (doDebug) DEBUG(theHarmonyTypes[15].harmony_type_desc); meter_numerator=4; meter_denominator=4; theHarmonyTypes[15].num_harmony_steps=8; theHarmonyTypes[15].min_steps=1; theHarmonyTypes[15].max_steps=theHarmonyTypes[15].num_harmony_steps; theHarmonyTypes[15].harmony_steps[0]=1; theHarmonyTypes[15].harmony_steps[1]=4; theHarmonyTypes[15].harmony_steps[2]=5; theHarmonyTypes[15].harmony_steps[3]=1; theHarmonyTypes[15].harmony_steps[4]=1; theHarmonyTypes[15].harmony_steps[5]=4; theHarmonyTypes[15].harmony_steps[6]=5; theHarmonyTypes[15].harmony_steps[7]=1; // (harmony_type==16) /* country 2 */ strcpy(theHarmonyTypes[16].harmony_type_desc, "country 2" ); strcpy(theHarmonyTypes[16].harmony_degrees_desc, "I - I - V - V - IV - IV - I - I" ); if (doDebug) DEBUG(theHarmonyTypes[16].harmony_type_desc); meter_numerator=4; meter_denominator=4; theHarmonyTypes[16].num_harmony_steps=8; theHarmonyTypes[16].min_steps=1; theHarmonyTypes[16].max_steps=theHarmonyTypes[16].num_harmony_steps; theHarmonyTypes[16].harmony_steps[0]=1; theHarmonyTypes[16].harmony_steps[1]=1; theHarmonyTypes[16].harmony_steps[2]=5; theHarmonyTypes[16].harmony_steps[3]=5; theHarmonyTypes[16].harmony_steps[4]=4; theHarmonyTypes[16].harmony_steps[5]=4; theHarmonyTypes[16].harmony_steps[6]=1; theHarmonyTypes[16].harmony_steps[7]=1; // (harmony_type==17) /* country 3 */ strcpy(theHarmonyTypes[17].harmony_type_desc, "country 3" ); strcpy(theHarmonyTypes[17].harmony_degrees_desc, "I - IV - I - V - I - IV - V - I" ); if (doDebug) DEBUG(theHarmonyTypes[17].harmony_type_desc); meter_numerator=4; meter_denominator=4; theHarmonyTypes[17].num_harmony_steps=8; theHarmonyTypes[17].min_steps=1; theHarmonyTypes[17].max_steps=theHarmonyTypes[17].num_harmony_steps; theHarmonyTypes[17].harmony_steps[0]=1; theHarmonyTypes[17].harmony_steps[1]=4; theHarmonyTypes[17].harmony_steps[2]=1; theHarmonyTypes[17].harmony_steps[3]=5; theHarmonyTypes[17].harmony_steps[4]=1; theHarmonyTypes[17].harmony_steps[5]=4; theHarmonyTypes[17].harmony_steps[6]=5; theHarmonyTypes[17].harmony_steps[7]=1; // (harmony_type==18) /* 50's r&r */ strcpy(theHarmonyTypes[18].harmony_type_desc, "50's R&R" ); strcpy(theHarmonyTypes[18].harmony_degrees_desc, "I - VI - IV - V" ); if (doDebug) DEBUG(theHarmonyTypes[18].harmony_type_desc); meter_numerator=4; meter_denominator=4; theHarmonyTypes[18].num_harmony_steps=4; theHarmonyTypes[18].min_steps=1; theHarmonyTypes[18].max_steps=theHarmonyTypes[18].num_harmony_steps; theHarmonyTypes[18].harmony_steps[0]=1; theHarmonyTypes[18].harmony_steps[1]=6; theHarmonyTypes[18].harmony_steps[2]=4; theHarmonyTypes[18].harmony_steps[3]=5; // (harmony_type==19) /* Rock1 */ strcpy(theHarmonyTypes[19].harmony_type_desc, "rock" ); strcpy(theHarmonyTypes[19].harmony_degrees_desc, "I - IV" ); if (doDebug) DEBUG(theHarmonyTypes[19].harmony_type_desc); meter_numerator=4; meter_denominator=4; theHarmonyTypes[19].num_harmony_steps=2; theHarmonyTypes[19].min_steps=1; theHarmonyTypes[19].max_steps=theHarmonyTypes[19].num_harmony_steps; theHarmonyTypes[19].harmony_steps[0]=1; theHarmonyTypes[19].harmony_steps[1]=4; // (harmony_type==20) /* Folk1 */ strcpy(theHarmonyTypes[20].harmony_type_desc, "folk 1" ); strcpy(theHarmonyTypes[20].harmony_degrees_desc, "I - V - I - V" ); if (doDebug) DEBUG(theHarmonyTypes[20].harmony_type_desc); meter_numerator=4; meter_denominator=4; theHarmonyTypes[20].num_harmony_steps=4; theHarmonyTypes[20].min_steps=1; theHarmonyTypes[20].max_steps=theHarmonyTypes[20].num_harmony_steps; theHarmonyTypes[20].harmony_steps[0]=1; theHarmonyTypes[20].harmony_steps[1]=5; theHarmonyTypes[20].harmony_steps[2]=1; theHarmonyTypes[20].harmony_steps[3]=5; // (harmony_type==21) /* folk2 */ strcpy(theHarmonyTypes[21].harmony_type_desc, "folk 2" ); strcpy(theHarmonyTypes[21].harmony_degrees_desc, "I - I - I - V - V - V - I" ); if (doDebug) DEBUG(theHarmonyTypes[21].harmony_type_desc); meter_numerator=4; meter_denominator=4; theHarmonyTypes[21].num_harmony_steps=8; theHarmonyTypes[21].min_steps=1; theHarmonyTypes[21].max_steps=theHarmonyTypes[21].num_harmony_steps; theHarmonyTypes[21].harmony_steps[0]=1; theHarmonyTypes[21].harmony_steps[1]=1; theHarmonyTypes[21].harmony_steps[2]=1; theHarmonyTypes[21].harmony_steps[3]=5; theHarmonyTypes[21].harmony_steps[4]=5; theHarmonyTypes[21].harmony_steps[5]=5; theHarmonyTypes[21].harmony_steps[6]=5; theHarmonyTypes[21].harmony_steps[7]=1; // (harmony_type==22) /* random coming home by 4ths */ // I + n and descend by 4ths strcpy(theHarmonyTypes[22].harmony_type_desc, "random coming home by 4ths" ); strcpy(theHarmonyTypes[22].harmony_degrees_desc, "I - VI - II - V" ); if (doDebug) DEBUG(theHarmonyTypes[22].harmony_type_desc); theHarmonyTypes[22].num_harmony_steps=5; // 1-5 theHarmonyTypes[22].min_steps=1; theHarmonyTypes[22].max_steps=theHarmonyTypes[22].num_harmony_steps; theHarmonyTypes[22].harmony_steps[0]=1; for (int i=1; i<theHarmonyTypes[22].num_harmony_steps; ++i) theHarmonyTypes[22].harmony_steps[i]=(semiCircleDegrees[theHarmonyTypes[22].num_harmony_steps-i])%7; // (harmony_type==23) /* random coming home */ // I + n and descend by 4ths strcpy(theHarmonyTypes[23].harmony_type_desc, "random order" ); strcpy(theHarmonyTypes[23].harmony_degrees_desc, "I - IV - V" ); if (doDebug) DEBUG(theHarmonyTypes[23].harmony_type_desc); theHarmonyTypes[23].num_harmony_steps=3; // 1-7 theHarmonyTypes[23].min_steps=1; theHarmonyTypes[23].max_steps=theHarmonyTypes[23].num_harmony_steps; theHarmonyTypes[23].harmony_steps[0]=1; theHarmonyTypes[23].harmony_steps[1]=4; theHarmonyTypes[23].harmony_steps[2]=5; // (harmony_type==24) /* Hallelujah */ // strcpy(theHarmonyTypes[24].harmony_type_desc, "Hallelujah" ); strcpy(theHarmonyTypes[24].harmony_degrees_desc, "I - VI - I - VI - IV - V - I - I - I - IV - V - VI - IV - V - III - VI" ); if (doDebug) DEBUG(theHarmonyTypes[24].harmony_type_desc); theHarmonyTypes[24].num_harmony_steps=16; // 1-8 theHarmonyTypes[24].min_steps=1; theHarmonyTypes[24].max_steps=theHarmonyTypes[24].num_harmony_steps; theHarmonyTypes[24].harmony_steps[0]=1; theHarmonyTypes[24].harmony_steps[1]=6; theHarmonyTypes[24].harmony_steps[2]=1; theHarmonyTypes[24].harmony_steps[3]=6; theHarmonyTypes[24].harmony_steps[4]=4; theHarmonyTypes[24].harmony_steps[5]=5; theHarmonyTypes[24].harmony_steps[6]=1; theHarmonyTypes[24].harmony_steps[7]=1; theHarmonyTypes[24].harmony_steps[8]=1; theHarmonyTypes[24].harmony_steps[9]=4; theHarmonyTypes[24].harmony_steps[10]=5; theHarmonyTypes[24].harmony_steps[11]=6; theHarmonyTypes[24].harmony_steps[12]=4; theHarmonyTypes[24].harmony_steps[13]=5; theHarmonyTypes[24].harmony_steps[14]=3; theHarmonyTypes[24].harmony_steps[15]=6; // (harmony_type==25) /* Pachelbel Canon*/ // strcpy(theHarmonyTypes[25].harmony_type_desc, "Canon - DMaj" ); strcpy(theHarmonyTypes[25].harmony_degrees_desc, "I - V - VI - III - IV - I - IV - V" ); if (doDebug) DEBUG(theHarmonyTypes[25].harmony_type_desc); theHarmonyTypes[25].num_harmony_steps=8; // 1-8 theHarmonyTypes[25].min_steps=1; theHarmonyTypes[25].max_steps=theHarmonyTypes[25].num_harmony_steps; theHarmonyTypes[25].harmony_steps[0]=1; theHarmonyTypes[25].harmony_steps[1]=5; theHarmonyTypes[25].harmony_steps[2]=6; theHarmonyTypes[25].harmony_steps[3]=3; theHarmonyTypes[25].harmony_steps[4]=4; theHarmonyTypes[25].harmony_steps[5]=1; theHarmonyTypes[25].harmony_steps[6]=4; theHarmonyTypes[25].harmony_steps[7]=5; // (harmony_type==26) /* Pop Rock Classic-1*/ // strcpy(theHarmonyTypes[26].harmony_type_desc, "Pop Rock Classic Sensitive" ); strcpy(theHarmonyTypes[26].harmony_degrees_desc, "I - V - VI - IV" ); if (doDebug) DEBUG(theHarmonyTypes[26].harmony_type_desc); theHarmonyTypes[26].num_harmony_steps=4; // 1-8 theHarmonyTypes[26].min_steps=1; theHarmonyTypes[26].max_steps=theHarmonyTypes[26].num_harmony_steps; theHarmonyTypes[26].harmony_steps[0]=1; theHarmonyTypes[26].harmony_steps[1]=5; theHarmonyTypes[26].harmony_steps[2]=6; theHarmonyTypes[26].harmony_steps[3]=4; // (harmony_type==27) /* Andalusion Cadence 1*/ // strcpy(theHarmonyTypes[27].harmony_type_desc, "Andalusion Cadence 1" ); strcpy(theHarmonyTypes[27].harmony_degrees_desc, "I - VII - VI - V" ); if (doDebug) DEBUG(theHarmonyTypes[27].harmony_type_desc); theHarmonyTypes[27].num_harmony_steps=4; // 1-8 theHarmonyTypes[27].min_steps=1; theHarmonyTypes[27].max_steps=theHarmonyTypes[27].num_harmony_steps; theHarmonyTypes[27].harmony_steps[0]=1; theHarmonyTypes[27].harmony_steps[1]=7; theHarmonyTypes[27].harmony_steps[2]=6; theHarmonyTypes[27].harmony_steps[3]=5; // (harmony_type==28) /* 16 bar blues*/ // strcpy(theHarmonyTypes[28].harmony_type_desc, "16 Bar Blues" ); strcpy(theHarmonyTypes[28].harmony_degrees_desc, "I - I - I - I - I - I - I - I - IV - IV - I - I - V - IV - I - I" ); if (doDebug) DEBUG(theHarmonyTypes[28].harmony_type_desc); theHarmonyTypes[28].num_harmony_steps=16; // 1-8 theHarmonyTypes[28].min_steps=1; theHarmonyTypes[28].max_steps=theHarmonyTypes[28].num_harmony_steps; theHarmonyTypes[28].harmony_steps[0]=1; theHarmonyTypes[28].harmony_steps[1]=1; theHarmonyTypes[28].harmony_steps[2]=1; theHarmonyTypes[28].harmony_steps[3]=1; theHarmonyTypes[28].harmony_steps[4]=1; theHarmonyTypes[28].harmony_steps[5]=1; theHarmonyTypes[28].harmony_steps[6]=1; theHarmonyTypes[28].harmony_steps[7]=1; theHarmonyTypes[28].harmony_steps[8]=4; theHarmonyTypes[28].harmony_steps[9]=4; theHarmonyTypes[28].harmony_steps[10]=1; theHarmonyTypes[28].harmony_steps[11]=1; theHarmonyTypes[28].harmony_steps[12]=5; theHarmonyTypes[28].harmony_steps[13]=4; theHarmonyTypes[28].harmony_steps[14]=1; theHarmonyTypes[28].harmony_steps[15]=1; // (harmony_type==29) /* Black */ // strcpy(theHarmonyTypes[29].harmony_type_desc, "Black Stones" ); strcpy(theHarmonyTypes[29].harmony_degrees_desc, "I - VII - III - VII - I - I - I - I - I - VII - III - VII - IV - IV - V - V" ); if (doDebug) DEBUG(theHarmonyTypes[29].harmony_type_desc); theHarmonyTypes[29].num_harmony_steps=16; // 1-8 theHarmonyTypes[29].min_steps=1; theHarmonyTypes[29].max_steps=theHarmonyTypes[29].num_harmony_steps; theHarmonyTypes[29].harmony_steps[0]=1; theHarmonyTypes[29].harmony_steps[1]=7; theHarmonyTypes[29].harmony_steps[2]=3; theHarmonyTypes[29].harmony_steps[3]=7; theHarmonyTypes[29].harmony_steps[4]=1; theHarmonyTypes[29].harmony_steps[5]=1; theHarmonyTypes[29].harmony_steps[6]=1; theHarmonyTypes[29].harmony_steps[7]=1; theHarmonyTypes[29].harmony_steps[8]=1; theHarmonyTypes[29].harmony_steps[9]=7; theHarmonyTypes[29].harmony_steps[10]=3; theHarmonyTypes[29].harmony_steps[11]=7; theHarmonyTypes[29].harmony_steps[12]=4; theHarmonyTypes[29].harmony_steps[13]=4; theHarmonyTypes[29].harmony_steps[14]=5; theHarmonyTypes[29].harmony_steps[15]=5; // (harmony_type==30) /*V-I */ // strcpy(theHarmonyTypes[30].harmony_type_desc, "V - I" ); strcpy(theHarmonyTypes[30].harmony_degrees_desc, "V - I" ); if (doDebug) DEBUG(theHarmonyTypes[30].harmony_type_desc); theHarmonyTypes[30].num_harmony_steps=2; // 1-8 theHarmonyTypes[30].min_steps=1; theHarmonyTypes[30].max_steps=theHarmonyTypes[30].num_harmony_steps; theHarmonyTypes[30].harmony_steps[0]=5; theHarmonyTypes[30].harmony_steps[1]=1; // (harmony_type==31) /* Markov Chain Bach 1*/ // strcpy(theHarmonyTypes[31].harmony_type_desc, "Markov Chain-Bach 1" ); strcpy(theHarmonyTypes[31].harmony_degrees_desc, "I - II - III - IV - V - VI - VII" ); if (doDebug) DEBUG(theHarmonyTypes[31].harmony_type_desc); theHarmonyTypes[31].num_harmony_steps=7; // 1-8 theHarmonyTypes[31].min_steps=1; theHarmonyTypes[31].max_steps=theHarmonyTypes[31].num_harmony_steps; theHarmonyTypes[31].harmony_steps[0]=1; theHarmonyTypes[31].harmony_steps[1]=2; theHarmonyTypes[31].harmony_steps[2]=3; theHarmonyTypes[31].harmony_steps[3]=4; theHarmonyTypes[31].harmony_steps[4]=5; theHarmonyTypes[31].harmony_steps[5]=6; theHarmonyTypes[31].harmony_steps[6]=7; // (harmony_type==32) /* Pop */ // strcpy(theHarmonyTypes[32].harmony_type_desc, "Pop " ); strcpy(theHarmonyTypes[32].harmony_degrees_desc, "I - II - IV - V" ); if (doDebug) DEBUG(theHarmonyTypes[32].harmony_type_desc); theHarmonyTypes[32].num_harmony_steps=4; // 1-8 theHarmonyTypes[32].min_steps=1; theHarmonyTypes[32].max_steps=theHarmonyTypes[32].num_harmony_steps; theHarmonyTypes[32].harmony_steps[0]=1; theHarmonyTypes[32].harmony_steps[1]=2; theHarmonyTypes[32].harmony_steps[2]=4; theHarmonyTypes[32].harmony_steps[3]=5; // (harmony_type==33) /* Classical */ // strcpy(theHarmonyTypes[33].harmony_type_desc, "Classical" ); strcpy(theHarmonyTypes[33].harmony_degrees_desc, "I - V - I - VI - II - V - I" ); if (doDebug) DEBUG(theHarmonyTypes[33].harmony_type_desc); theHarmonyTypes[33].num_harmony_steps=7; // 1-8 theHarmonyTypes[33].min_steps=1; theHarmonyTypes[33].max_steps=theHarmonyTypes[33].num_harmony_steps; theHarmonyTypes[33].harmony_steps[0]=1; theHarmonyTypes[33].harmony_steps[1]=5; theHarmonyTypes[33].harmony_steps[2]=1; theHarmonyTypes[33].harmony_steps[3]=6; theHarmonyTypes[33].harmony_steps[4]=2; theHarmonyTypes[33].harmony_steps[5]=5; theHarmonyTypes[33].harmony_steps[6]=1; // (harmony_type==34) /*Mozart */ // strcpy(theHarmonyTypes[34].harmony_type_desc, "Mozart " ); strcpy(theHarmonyTypes[34].harmony_degrees_desc, "I - II - V - I" ); if (doDebug) DEBUG(theHarmonyTypes[34].harmony_type_desc); theHarmonyTypes[34].num_harmony_steps=4; // 1-8 theHarmonyTypes[34].min_steps=1; theHarmonyTypes[34].max_steps=theHarmonyTypes[34].num_harmony_steps; theHarmonyTypes[34].harmony_steps[0]=1; theHarmonyTypes[34].harmony_steps[1]=2; theHarmonyTypes[34].harmony_steps[2]=5; theHarmonyTypes[34].harmony_steps[3]=1; // (harmony_type==35) /*Classical Tonal */ // strcpy(theHarmonyTypes[35].harmony_type_desc, "Classical Tonal" ); strcpy(theHarmonyTypes[35].harmony_degrees_desc, "I - V - I - IV" ); if (doDebug) DEBUG(theHarmonyTypes[35].harmony_type_desc); theHarmonyTypes[35].num_harmony_steps=4; // 1-8 theHarmonyTypes[35].min_steps=1; theHarmonyTypes[35].max_steps=theHarmonyTypes[35].num_harmony_steps; theHarmonyTypes[35].harmony_steps[0]=1; theHarmonyTypes[35].harmony_steps[1]=5; theHarmonyTypes[35].harmony_steps[2]=1; theHarmonyTypes[35].harmony_steps[3]=4; // (harmony_type==36) /*Sensitive */ // strcpy(theHarmonyTypes[36].harmony_type_desc, "Sensitive" ); strcpy(theHarmonyTypes[36].harmony_degrees_desc, "VI - IV - I - V" ); if (doDebug) DEBUG(theHarmonyTypes[36].harmony_type_desc); theHarmonyTypes[36].num_harmony_steps=4; // 1-8 theHarmonyTypes[36].min_steps=1; theHarmonyTypes[36].max_steps=theHarmonyTypes[36].num_harmony_steps; theHarmonyTypes[36].harmony_steps[0]=6; theHarmonyTypes[36].harmony_steps[1]=4; theHarmonyTypes[36].harmony_steps[2]=1; theHarmonyTypes[36].harmony_steps[3]=5; // (harmony_type==37) /*Jazz */ // strcpy(theHarmonyTypes[37].harmony_type_desc, "Jazz" ); strcpy(theHarmonyTypes[37].harmony_degrees_desc, "II - V - I" ); if (doDebug) DEBUG(theHarmonyTypes[37].harmony_type_desc); theHarmonyTypes[37].num_harmony_steps=3; // 1-8 theHarmonyTypes[37].min_steps=1; theHarmonyTypes[37].max_steps=theHarmonyTypes[37].num_harmony_steps; theHarmonyTypes[37].harmony_steps[0]=2; theHarmonyTypes[37].harmony_steps[1]=5; theHarmonyTypes[37].harmony_steps[2]=1; // (harmony_type==38) /*Pop */ // strcpy(theHarmonyTypes[38].harmony_type_desc, "Pop and jazz" ); strcpy(theHarmonyTypes[38].harmony_degrees_desc, "I - IV - II - V" ); if (doDebug) DEBUG(theHarmonyTypes[38].harmony_type_desc); theHarmonyTypes[38].num_harmony_steps=4; // 1-8 theHarmonyTypes[38].min_steps=1; theHarmonyTypes[38].max_steps=theHarmonyTypes[38].num_harmony_steps; theHarmonyTypes[38].harmony_steps[0]=1; theHarmonyTypes[38].harmony_steps[1]=4; theHarmonyTypes[38].harmony_steps[2]=2; theHarmonyTypes[38].harmony_steps[3]=5; // (harmony_type==39) /*Pop */ // strcpy(theHarmonyTypes[39].harmony_type_desc, "Pop" ); strcpy(theHarmonyTypes[39].harmony_degrees_desc, "I - II - III - IV - V" ); if (doDebug) DEBUG(theHarmonyTypes[39].harmony_type_desc); theHarmonyTypes[39].num_harmony_steps=5; // 1-8 theHarmonyTypes[39].min_steps=1; theHarmonyTypes[39].max_steps=theHarmonyTypes[39].num_harmony_steps; theHarmonyTypes[39].harmony_steps[0]=1; theHarmonyTypes[39].harmony_steps[1]=2; theHarmonyTypes[39].harmony_steps[2]=3; theHarmonyTypes[39].harmony_steps[3]=4; theHarmonyTypes[39].harmony_steps[4]=5; // (harmony_type==40) /*Pop */ // strcpy(theHarmonyTypes[40].harmony_type_desc, "Pop" ); strcpy(theHarmonyTypes[40].harmony_degrees_desc, "I - III - IV - IV" ); // can't really do a IV and iv together if (doDebug) DEBUG(theHarmonyTypes[40].harmony_type_desc); theHarmonyTypes[40].num_harmony_steps=4; // 1-8 theHarmonyTypes[40].min_steps=1; theHarmonyTypes[40].max_steps=theHarmonyTypes[40].num_harmony_steps; theHarmonyTypes[40].harmony_steps[0]=1; theHarmonyTypes[40].harmony_steps[1]=3; theHarmonyTypes[40].harmony_steps[2]=4; theHarmonyTypes[40].harmony_steps[3]=4; // (harmony_type==41) /*Andalusian Cadence 2 */ // strcpy(theHarmonyTypes[41].harmony_type_desc, "Andalusian Cadence 2" ); strcpy(theHarmonyTypes[41].harmony_degrees_desc, "VI - V - IV - III" ); if (doDebug) DEBUG(theHarmonyTypes[41].harmony_type_desc); theHarmonyTypes[41].num_harmony_steps=4; // 1-8 theHarmonyTypes[41].min_steps=1; theHarmonyTypes[41].max_steps=theHarmonyTypes[41].num_harmony_steps; theHarmonyTypes[41].harmony_steps[0]=6; theHarmonyTypes[41].harmony_steps[1]=5; theHarmonyTypes[41].harmony_steps[2]=4; theHarmonyTypes[41].harmony_steps[3]=3; // (harmony_type==42) /* Markov Chain Bach 2*/ // strcpy(theHarmonyTypes[42].harmony_type_desc, "Markov Chain - Bach 2" ); strcpy(theHarmonyTypes[42].harmony_degrees_desc, "I - II - III - IV - V - VI - VII" ); if (doDebug) DEBUG(theHarmonyTypes[42].harmony_type_desc); theHarmonyTypes[42].num_harmony_steps=7; // 1-8 theHarmonyTypes[42].min_steps=1; theHarmonyTypes[42].max_steps=theHarmonyTypes[42].num_harmony_steps; theHarmonyTypes[42].harmony_steps[0]=1; theHarmonyTypes[42].harmony_steps[1]=2; theHarmonyTypes[42].harmony_steps[2]=3; theHarmonyTypes[42].harmony_steps[3]=4; theHarmonyTypes[42].harmony_steps[4]=5; theHarmonyTypes[42].harmony_steps[5]=6; theHarmonyTypes[42].harmony_steps[6]=7; // (harmony_type==43) /* Markov Chain Mozart 1*/ // strcpy(theHarmonyTypes[43].harmony_type_desc, "Markov Chain-Mozart 1" ); strcpy(theHarmonyTypes[43].harmony_degrees_desc, "I - II - III - IV - V - VI - VII" ); if (doDebug) DEBUG(theHarmonyTypes[43].harmony_type_desc); theHarmonyTypes[43].num_harmony_steps=7; // 1-8 theHarmonyTypes[43].min_steps=1; theHarmonyTypes[43].max_steps=theHarmonyTypes[43].num_harmony_steps; theHarmonyTypes[43].harmony_steps[0]=1; theHarmonyTypes[43].harmony_steps[1]=2; theHarmonyTypes[43].harmony_steps[2]=3; theHarmonyTypes[43].harmony_steps[3]=4; theHarmonyTypes[43].harmony_steps[4]=5; theHarmonyTypes[43].harmony_steps[5]=6; theHarmonyTypes[43].harmony_steps[6]=7; // (harmony_type==44) /* Markov Chain Mozart 2*/ // strcpy(theHarmonyTypes[44].harmony_type_desc, "Markov Chain-Mozart 2" ); strcpy(theHarmonyTypes[44].harmony_degrees_desc, "I - II - III - IV - V - VI - VII" ); if (doDebug) DEBUG(theHarmonyTypes[44].harmony_type_desc); theHarmonyTypes[44].num_harmony_steps=7; // 1 - 8 theHarmonyTypes[44].min_steps=1; theHarmonyTypes[44].max_steps=theHarmonyTypes[44].num_harmony_steps; theHarmonyTypes[44].harmony_steps[0]=1; theHarmonyTypes[44].harmony_steps[1]=2; theHarmonyTypes[44].harmony_steps[2]=3; theHarmonyTypes[44].harmony_steps[3]=4; theHarmonyTypes[44].harmony_steps[4]=5; theHarmonyTypes[44].harmony_steps[5]=6; theHarmonyTypes[44].harmony_steps[6]=7; // (harmony_type==45) /* Markov Chain Palestrina 1*/ // strcpy(theHarmonyTypes[45].harmony_type_desc, "Markov Chain-Palestrina 1" ); strcpy(theHarmonyTypes[45].harmony_degrees_desc, "I - II - III - IV - V - VI - VII" ); if (doDebug) DEBUG(theHarmonyTypes[45].harmony_type_desc); theHarmonyTypes[45].num_harmony_steps=7; // 1-8 theHarmonyTypes[45].min_steps=1; theHarmonyTypes[45].max_steps=theHarmonyTypes[45].num_harmony_steps; theHarmonyTypes[45].harmony_steps[0]=1; theHarmonyTypes[45].harmony_steps[1]=2; theHarmonyTypes[45].harmony_steps[2]=3; theHarmonyTypes[45].harmony_steps[3]=4; theHarmonyTypes[45].harmony_steps[4]=5; theHarmonyTypes[45].harmony_steps[5]=6; theHarmonyTypes[45].harmony_steps[6]=7; // (harmony_type==46) /* Markov Chain Beethoven 1*/ // strcpy(theHarmonyTypes[46].harmony_type_desc, "Markov Chain-Beethoven 1" ); strcpy(theHarmonyTypes[46].harmony_degrees_desc, "I - II - III - IV - V - VI - VII" ); if (doDebug) DEBUG(theHarmonyTypes[46].harmony_type_desc); theHarmonyTypes[46].num_harmony_steps=7; // 1-8 theHarmonyTypes[46].min_steps=1; theHarmonyTypes[46].max_steps=theHarmonyTypes[46].num_harmony_steps; theHarmonyTypes[46].harmony_steps[0]=1; theHarmonyTypes[46].harmony_steps[1]=2; theHarmonyTypes[46].harmony_steps[2]=3; theHarmonyTypes[46].harmony_steps[3]=4; theHarmonyTypes[46].harmony_steps[4]=5; theHarmonyTypes[46].harmony_steps[5]=6; theHarmonyTypes[46].harmony_steps[6]=7; // (harmony_type==47) /* Markov Chain Traditional 1*/ // strcpy(theHarmonyTypes[47].harmony_type_desc, "Markov Chain-Traditional 1" ); strcpy(theHarmonyTypes[47].harmony_degrees_desc, "I - II - III - IV - V - VI - VII" ); if (doDebug) DEBUG(theHarmonyTypes[47].harmony_type_desc); theHarmonyTypes[47].num_harmony_steps=7; // 1-8 theHarmonyTypes[47].min_steps=1; theHarmonyTypes[47].max_steps=theHarmonyTypes[47].num_harmony_steps; theHarmonyTypes[47].harmony_steps[0]=1; theHarmonyTypes[47].harmony_steps[1]=2; theHarmonyTypes[47].harmony_steps[2]=3; theHarmonyTypes[47].harmony_steps[3]=4; theHarmonyTypes[47].harmony_steps[4]=5; theHarmonyTypes[47].harmony_steps[5]=6; theHarmonyTypes[47].harmony_steps[6]=7; // (harmony_type==48) /* Markov Chain I-IV-V*/ // strcpy(theHarmonyTypes[48].harmony_type_desc, "Markov Chain- I - IV - V" ); strcpy(theHarmonyTypes[48].harmony_degrees_desc, "I - II - III - IV - V - VI - VII" ); if (doDebug) DEBUG(theHarmonyTypes[48].harmony_type_desc); theHarmonyTypes[48].num_harmony_steps=7; // 1-8 theHarmonyTypes[48].min_steps=1; theHarmonyTypes[48].max_steps=theHarmonyTypes[48].num_harmony_steps; theHarmonyTypes[48].harmony_steps[0]=1; theHarmonyTypes[48].harmony_steps[1]=2; theHarmonyTypes[48].harmony_steps[2]=3; theHarmonyTypes[48].harmony_steps[3]=4; theHarmonyTypes[48].harmony_steps[4]=5; theHarmonyTypes[48].harmony_steps[5]=6; theHarmonyTypes[48].harmony_steps[6]=7; // (harmony_type==49) /* Jazz 2 */ // strcpy(theHarmonyTypes[49].harmony_type_desc, "Jazz 2" ); strcpy(theHarmonyTypes[49].harmony_degrees_desc, "I - VI - II - V" ); if (doDebug) DEBUG(theHarmonyTypes[49].harmony_type_desc); theHarmonyTypes[49].num_harmony_steps=4; // 1-8 theHarmonyTypes[49].min_steps=1; theHarmonyTypes[49].max_steps=theHarmonyTypes[49].num_harmony_steps; theHarmonyTypes[49].harmony_steps[0]=1; theHarmonyTypes[49].harmony_steps[1]=6; theHarmonyTypes[49].harmony_steps[2]=2; theHarmonyTypes[49].harmony_steps[3]=5; // (harmony_type==50) /*Jazz 3 */ // strcpy(theHarmonyTypes[50].harmony_type_desc, "Jazz 3" ); strcpy(theHarmonyTypes[50].harmony_degrees_desc, "III - VI - II - V" ); if (doDebug) DEBUG(theHarmonyTypes[50].harmony_type_desc); theHarmonyTypes[50].num_harmony_steps=4; // 1-8 theHarmonyTypes[50].min_steps=1; theHarmonyTypes[50].max_steps=theHarmonyTypes[50].num_harmony_steps; theHarmonyTypes[50].harmony_steps[0]=3; theHarmonyTypes[50].harmony_steps[1]=6; theHarmonyTypes[50].harmony_steps[2]=2; theHarmonyTypes[50].harmony_steps[3]=5; // (harmony_type==51) /*Jazz 4 */ // strcpy(theHarmonyTypes[51].harmony_type_desc, "Jazz 4" ); strcpy(theHarmonyTypes[51].harmony_degrees_desc, "I - IV - III - VI" ); if (doDebug) DEBUG(theHarmonyTypes[51].harmony_type_desc); theHarmonyTypes[51].num_harmony_steps=4; // 1-8 theHarmonyTypes[51].min_steps=1; theHarmonyTypes[51].max_steps=theHarmonyTypes[51].num_harmony_steps; theHarmonyTypes[51].harmony_steps[0]=1; theHarmonyTypes[51].harmony_steps[1]=4; theHarmonyTypes[51].harmony_steps[2]=3; theHarmonyTypes[51].harmony_steps[3]=6; // (harmony_type==52) /* I-VI */ // strcpy(theHarmonyTypes[52].harmony_type_desc, "I-VI alt maj/ rel. min" ); strcpy(theHarmonyTypes[52].harmony_degrees_desc, "I - VI" ); if (doDebug) DEBUG(theHarmonyTypes[52].harmony_type_desc); theHarmonyTypes[52].num_harmony_steps=2; // 1-8 theHarmonyTypes[52].min_steps=1; theHarmonyTypes[52].max_steps=theHarmonyTypes[52].num_harmony_steps; theHarmonyTypes[52].harmony_steps[0]=1; theHarmonyTypes[52].harmony_steps[1]=6; // (harmony_type==53) /* 12 bar blues variation 1*/ strcpy(theHarmonyTypes[53].harmony_type_desc, "12 bar blues variation 1" ); strcpy(theHarmonyTypes[53].harmony_degrees_desc, "I - I - I - I - IV - IV - I - I - V - IV - I - V" ); if (doDebug) DEBUG(theHarmonyTypes[53].harmony_type_desc); theHarmonyTypes[53].num_harmony_steps=12; theHarmonyTypes[53].min_steps=1; theHarmonyTypes[53].max_steps=theHarmonyTypes[53].num_harmony_steps; theHarmonyTypes[53].harmony_steps[0]=1; theHarmonyTypes[53].harmony_steps[1]=1; theHarmonyTypes[53].harmony_steps[2]=1; theHarmonyTypes[53].harmony_steps[3]=1; theHarmonyTypes[53].harmony_steps[4]=4; theHarmonyTypes[53].harmony_steps[5]=4; theHarmonyTypes[53].harmony_steps[6]=1; theHarmonyTypes[53].harmony_steps[7]=1; theHarmonyTypes[53].harmony_steps[8]=5; theHarmonyTypes[53].harmony_steps[9]=4; theHarmonyTypes[53].harmony_steps[10]=1; theHarmonyTypes[53].harmony_steps[11]=5; // (harmony_type==54) /* 12 bar blues variation 2*/ strcpy(theHarmonyTypes[54].harmony_type_desc, "12 bar blues variation 2" ); strcpy(theHarmonyTypes[54].harmony_degrees_desc, "I - I - I - I - IV - IV - I - I - IV - V - I - V" ); if (doDebug) DEBUG(theHarmonyTypes[54].harmony_type_desc); theHarmonyTypes[54].num_harmony_steps=12; theHarmonyTypes[54].min_steps=1; theHarmonyTypes[54].max_steps=theHarmonyTypes[54].num_harmony_steps; theHarmonyTypes[54].harmony_steps[0]=1; theHarmonyTypes[54].harmony_steps[1]=1; theHarmonyTypes[54].harmony_steps[2]=1; theHarmonyTypes[54].harmony_steps[3]=1; theHarmonyTypes[54].harmony_steps[4]=4; theHarmonyTypes[54].harmony_steps[5]=4; theHarmonyTypes[54].harmony_steps[6]=1; theHarmonyTypes[54].harmony_steps[7]=1; theHarmonyTypes[54].harmony_steps[8]=4; theHarmonyTypes[54].harmony_steps[9]=5; theHarmonyTypes[54].harmony_steps[10]=1; theHarmonyTypes[54].harmony_steps[11]=5; // (harmony_type==55) /* 12 bar blues turnaround 1*/ strcpy(theHarmonyTypes[55].harmony_type_desc, "12 bar blues turnaround 1" ); strcpy(theHarmonyTypes[55].harmony_degrees_desc, "I - IV - I - I - IV - IV - I - I - V - IV - I - V" ); if (doDebug) DEBUG(theHarmonyTypes[55].harmony_type_desc); theHarmonyTypes[55].num_harmony_steps=12; theHarmonyTypes[55].min_steps=1; theHarmonyTypes[55].max_steps=theHarmonyTypes[55].num_harmony_steps; theHarmonyTypes[55].harmony_steps[0]=1; theHarmonyTypes[55].harmony_steps[1]=4; theHarmonyTypes[55].harmony_steps[2]=1; theHarmonyTypes[55].harmony_steps[3]=1; theHarmonyTypes[55].harmony_steps[4]=4; theHarmonyTypes[55].harmony_steps[5]=4; theHarmonyTypes[55].harmony_steps[6]=1; theHarmonyTypes[55].harmony_steps[7]=1; theHarmonyTypes[55].harmony_steps[8]=5; theHarmonyTypes[55].harmony_steps[9]=4; theHarmonyTypes[55].harmony_steps[10]=1; theHarmonyTypes[55].harmony_steps[11]=5; // (harmony_type==56) /* 8 bar blues traditional*/ strcpy(theHarmonyTypes[56].harmony_type_desc, "8 bar blues traditional" ); strcpy(theHarmonyTypes[56].harmony_degrees_desc, "I - V - IV - IV - I - V - I - V" ); if (doDebug) DEBUG(theHarmonyTypes[56].harmony_type_desc); theHarmonyTypes[56].num_harmony_steps=8; theHarmonyTypes[56].min_steps=1; theHarmonyTypes[56].max_steps=theHarmonyTypes[56].num_harmony_steps; theHarmonyTypes[56].harmony_steps[0]=1; theHarmonyTypes[56].harmony_steps[1]=5; theHarmonyTypes[56].harmony_steps[2]=4; theHarmonyTypes[56].harmony_steps[3]=4; theHarmonyTypes[56].harmony_steps[4]=1; theHarmonyTypes[56].harmony_steps[5]=5; theHarmonyTypes[56].harmony_steps[6]=1; theHarmonyTypes[56].harmony_steps[7]=5; // (harmony_type==57) /* 8 bar blues variation 1*/ strcpy(theHarmonyTypes[57].harmony_type_desc, "8 bar blues variation 1" ); strcpy(theHarmonyTypes[57].harmony_degrees_desc, "I - I - I - I - IV - IV - V - I" ); if (doDebug) DEBUG(theHarmonyTypes[57].harmony_type_desc); theHarmonyTypes[57].num_harmony_steps=8; theHarmonyTypes[57].min_steps=1; theHarmonyTypes[57].max_steps=theHarmonyTypes[57].num_harmony_steps; theHarmonyTypes[57].harmony_steps[0]=1; theHarmonyTypes[57].harmony_steps[1]=1; theHarmonyTypes[57].harmony_steps[2]=1; theHarmonyTypes[57].harmony_steps[3]=1; theHarmonyTypes[57].harmony_steps[4]=4; theHarmonyTypes[57].harmony_steps[5]=4; theHarmonyTypes[57].harmony_steps[6]=5; theHarmonyTypes[57].harmony_steps[7]=1; // (harmony_type==58) /* 8 bar blues variation 2*/ strcpy(theHarmonyTypes[58].harmony_type_desc, "8 bar blues variation 2" ); strcpy(theHarmonyTypes[58].harmony_degrees_desc, "I - I - I - I - IV - IV - V - V" ); if (doDebug) DEBUG(theHarmonyTypes[58].harmony_type_desc); theHarmonyTypes[58].num_harmony_steps=8; theHarmonyTypes[58].min_steps=1; theHarmonyTypes[58].max_steps=theHarmonyTypes[58].num_harmony_steps; theHarmonyTypes[58].harmony_steps[0]=1; theHarmonyTypes[58].harmony_steps[1]=1; theHarmonyTypes[58].harmony_steps[2]=1; theHarmonyTypes[58].harmony_steps[3]=1; theHarmonyTypes[58].harmony_steps[4]=4; theHarmonyTypes[58].harmony_steps[5]=4; theHarmonyTypes[58].harmony_steps[6]=5; theHarmonyTypes[58].harmony_steps[7]=5; // (harmony_type==59) /* ii-V-I */ strcpy(theHarmonyTypes[59].harmony_type_desc, "II - V - I cadential" ); strcpy(theHarmonyTypes[59].harmony_degrees_desc, "II - V - I" ); if (doDebug) DEBUG(theHarmonyTypes[59].harmony_type_desc); theHarmonyTypes[59].num_harmony_steps=3; theHarmonyTypes[59].min_steps=1; theHarmonyTypes[59].max_steps=theHarmonyTypes[59].num_harmony_steps; theHarmonyTypes[59].harmony_steps[0]=2; theHarmonyTypes[59].harmony_steps[1]=5; theHarmonyTypes[59].harmony_steps[2]=1; // End of preset harmony types } void copyHarmonyTypeToActiveHarmonyType(int harmType) { theActiveHarmonyType.harmony_type=harmType; // the parent harmony_type theActiveHarmonyType.num_harmony_steps=theHarmonyTypes[harmType].num_harmony_steps; theActiveHarmonyType.min_steps=theHarmonyTypes[harmType].min_steps; theActiveHarmonyType.max_steps=theHarmonyTypes[harmType].max_steps; strcpy(theActiveHarmonyType.harmony_type_desc, theHarmonyTypes[harmType].harmony_type_desc); strcpy(theActiveHarmonyType.harmony_degrees_desc, theHarmonyTypes[harmType].harmony_degrees_desc); for (int i=0; i<MAX_STEPS; ++i) { theActiveHarmonyType.harmony_steps[i]=theHarmonyTypes[harmType].harmony_steps[i]; theActiveHarmonyType.harmony_step_chord_type[i]=theHarmonyTypes[harmType].harmony_step_chord_type[i]; } } void setup_harmony() { if (doDebug) DEBUG("setup_harmony-begin"); int i,j,k; int circle_position=0; int circleDegree=0; if (doDebug) DEBUG("theHarmonyTypes[%d].num_harmony_steps=%d", harmony_type, theActiveHarmonyType.num_harmony_steps); for(i=0;i<theActiveHarmonyType.num_harmony_steps;++i) /* for each of the harmony steps */ { if (doDebug) DEBUG("step=%d", i); /* build proper chord notes */ num_step_chord_notes[i]=0; //find semicircle degree that matches step degree for (int j=0; j<7; ++j) { if (theCircleOf5ths.theDegreeSemiCircle.degreeElements[j].Degree==theActiveHarmonyType.harmony_steps[i]) { circleDegree=theCircleOf5ths.theDegreeSemiCircle.degreeElements[j].Degree; circle_position=theCircleOf5ths.theDegreeSemiCircle.degreeElements[j].CircleIndex; break; } if (j==7) { if (doDebug) DEBUG(" warning circleposition could not be found 1"); } } if (doDebug) DEBUG(" circle_position=%d num_root_key_notes[circle_position]=%d", circle_position, num_root_key_notes[circle_position]); int thisStepChordType=theCircleOf5ths.Circle5ths[circle_position].chordType; if (true) // attempting to handle 7ths { if ((theMeanderState.theHarmonyParms.enable_all_7ths)|| (theMeanderState.theHarmonyParms.enable_V_7ths)) // override V chord to 7th // ((theMeanderState.theHarmonyParms.enable_V_7ths)&&(circleDegree==5))) // override V chord to 7th { if ((theMeanderState.theHarmonyParms.enable_V_7ths)&&(circleDegree==5)) { if (thisStepChordType==0) // maj thisStepChordType=2; // 7dom . A dom7 sounds better than a maj7 else if (thisStepChordType==1) // min thisStepChordType=4; // 7min else if (thisStepChordType==6) // dim thisStepChordType=5; // dim7 theCircleOf5ths.Circle5ths[circle_position].chordType=thisStepChordType; } else if (theMeanderState.theHarmonyParms.enable_all_7ths) // actually only use most popular 7ths { if (circleDegree==2) // II { if (thisStepChordType==1) // min thisStepChordType=4; // 7thmin } else if (circleDegree==4) // IV { if (thisStepChordType==0) // maj // thisStepChordType=2; // 7thdom thisStepChordType=3; // 7thmaj } else if (circleDegree==5) // V { if (thisStepChordType==0) // maj thisStepChordType=2; // 7thdom } else if (circleDegree==7) // VII { if (thisStepChordType==6) // dim thisStepChordType=5; // 7thdim } theCircleOf5ths.Circle5ths[circle_position].chordType=thisStepChordType; } } } for(j=0;j<num_root_key_notes[circle_position];++j) { int root_key_note=root_key_notes[circle_of_fifths[circle_position]][j]; if (doDebug) DEBUG("root_key_note=%d %s", root_key_note, note_desig[root_key_note%MAX_NOTES]); int thisStepChordType=theCircleOf5ths.Circle5ths[circle_position].chordType; if ((root_key_note%MAX_NOTES)==circle_of_fifths[circle_position]) { if (doDebug) DEBUG(" root_key_note=%d %s", root_key_note, note_desig[root_key_note%MAX_NOTES]); for (k=0;k<chord_type_num_notes[thisStepChordType];++k) { step_chord_notes[i][num_step_chord_notes[i]]=(int)((int)root_key_note+(int)chord_type_intervals[thisStepChordType][k]); if (doDebug) DEBUG(" step_chord_notes[%d][%d]= %d %s", i, num_step_chord_notes[i], step_chord_notes[i][num_step_chord_notes[i]], note_desig[step_chord_notes[i][num_step_chord_notes[i]]%MAX_NOTES]); ++num_step_chord_notes[i]; } } } if (true) // if this is not done, step_chord_notes[0] begins with root note. If done, chord spread is limited but smoother wandering through innversions { if (doDebug) DEBUG("refactor:"); for (j=0;j<num_step_chord_notes[i];++j) { step_chord_notes[i][j]=step_chord_notes[i][j+((11-circle_of_fifths[circle_position])/3)]; if (doDebug) DEBUG("step_chord_notes[%d][%d]= %d %s", i, j, step_chord_notes[i][j], note_desig[step_chord_notes[i][j]%MAX_NOTES]); } num_step_chord_notes[i]-=((11-circle_of_fifths[circle_position])/3); } } AuditHarmonyData(1); if (doDebug) DEBUG("setup_harmony-end"); } void MeanderMusicStructuresInitialize() { if (doDebug) DEBUG("MeanderMusicStructuresInitialize()"); init_vars(); init_notes(); init_harmony(); copyHarmonyTypeToActiveHarmonyType(harmony_type); setup_harmony(); globalsInitialized=true; // prevents process() from doing anything before initialization and also prevents some access by ModuleWidget } void ConstructCircle5ths(int circleRootKey, int mode) { if (doDebug) DEBUG("ConstructCircle5ths()"); for (int i=0; i<MAX_CIRCLE_STATIONS; ++i) { const float rotate90 = (M_PI) / 2.0; // construct root_key annulus sector theCircleOf5ths.Circle5ths[i].startDegree = (M_PI * 2.0 * ((double)i - 0.5) / MAX_CIRCLE_STATIONS) - rotate90; theCircleOf5ths.Circle5ths[i].endDegree = (M_PI * 2.0 * ((double)i + 0.5) / MAX_CIRCLE_STATIONS) - rotate90; double ax1= cos(theCircleOf5ths.Circle5ths[i].startDegree) * theCircleOf5ths.InnerCircleRadius + theCircleOf5ths.CircleCenter.x; double ay1= sin(theCircleOf5ths.Circle5ths[i].startDegree) * theCircleOf5ths.InnerCircleRadius + theCircleOf5ths.CircleCenter.y; double ax2= cos(theCircleOf5ths.Circle5ths[i].endDegree) * theCircleOf5ths.InnerCircleRadius + theCircleOf5ths.CircleCenter.x; double ay2= sin(theCircleOf5ths.Circle5ths[i].endDegree) * theCircleOf5ths.InnerCircleRadius + theCircleOf5ths.CircleCenter.y; double bx1= cos(theCircleOf5ths.Circle5ths[i].startDegree) * theCircleOf5ths.MiddleCircleRadius + theCircleOf5ths.CircleCenter.x; double by1= sin(theCircleOf5ths.Circle5ths[i].startDegree) * theCircleOf5ths.MiddleCircleRadius + theCircleOf5ths.CircleCenter.y; double bx2= cos(theCircleOf5ths.Circle5ths[i].endDegree) * theCircleOf5ths.MiddleCircleRadius + theCircleOf5ths.CircleCenter.x; double by2= sin(theCircleOf5ths.Circle5ths[i].endDegree) * theCircleOf5ths.MiddleCircleRadius + theCircleOf5ths.CircleCenter.y; theCircleOf5ths.Circle5ths[i].pt1=Vec(ax1, ay1); theCircleOf5ths.Circle5ths[i].pt2=Vec(bx1, by1); theCircleOf5ths.Circle5ths[i].pt3=Vec(ax2, ay2); theCircleOf5ths.Circle5ths[i].pt4=Vec(bx2, by2); Vec radialLine1=Vec(ax1,ay1).minus(theCircleOf5ths.CircleCenter); Vec radialLine2=Vec(ax2,ay2).minus(theCircleOf5ths.CircleCenter); Vec centerLine=(radialLine1.plus(radialLine2)).div(2.); theCircleOf5ths.Circle5ths[i].radialDirection=centerLine; theCircleOf5ths.Circle5ths[i].radialDirection=theCircleOf5ths.Circle5ths[i].radialDirection.normalize(); } }; // should only be called after initialization void ConstructDegreesSemicircle(int circleRootKey, int mode) { if (doDebug) DEBUG("ConstructDegreesSemicircle()"); const float rotate90 = (M_PI) / 2.0; float offsetDegree=((circleRootKey-mode+12)%12)*(2.0*M_PI/12.0); theCircleOf5ths.theDegreeSemiCircle.OffsetSteps=(circleRootKey-mode); if (doDebug) DEBUG("theCircleOf5ths.theDegreeSemiCircle.OffsetSteps=%d", theCircleOf5ths.theDegreeSemiCircle.OffsetSteps); theCircleOf5ths.theDegreeSemiCircle.RootKeyCircle5thsPosition=-theCircleOf5ths.theDegreeSemiCircle.OffsetSteps+circle_root_key; if (doDebug) DEBUG("RootKeyCircle5thsPositions=%d", theCircleOf5ths.theDegreeSemiCircle.RootKeyCircle5thsPosition); int chord_type=0; for (int i=0; i<MAX_HARMONIC_DEGREES; ++i) { // construct degree annulus sector theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].startDegree = (M_PI * 2.0 * ((double)i - 0.5) / MAX_CIRCLE_STATIONS) - rotate90 + offsetDegree; theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].endDegree = (M_PI * 2.0 * ((double)i + 0.5) / MAX_CIRCLE_STATIONS) - rotate90 + offsetDegree; double ax1= cos(theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].startDegree) * theCircleOf5ths.MiddleCircleRadius + theCircleOf5ths.CircleCenter.x; double ay1= sin(theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].startDegree) * theCircleOf5ths.MiddleCircleRadius + theCircleOf5ths.CircleCenter.y; double ax2= cos(theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].endDegree) * theCircleOf5ths.MiddleCircleRadius + theCircleOf5ths.CircleCenter.x; double ay2= sin(theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].endDegree) * theCircleOf5ths.MiddleCircleRadius + theCircleOf5ths.CircleCenter.y; double bx1= cos(theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].startDegree) * theCircleOf5ths.OuterCircleRadius + theCircleOf5ths.CircleCenter.x; double by1= sin(theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].startDegree) * theCircleOf5ths.OuterCircleRadius + theCircleOf5ths.CircleCenter.y; double bx2= cos(theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].endDegree) * theCircleOf5ths.OuterCircleRadius + theCircleOf5ths.CircleCenter.x; double by2= sin(theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].endDegree) * theCircleOf5ths.OuterCircleRadius + theCircleOf5ths.CircleCenter.y; theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].pt1=Vec(ax1, ay1); theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].pt2=Vec(bx1, by1); theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].pt3=Vec(ax2, ay2); theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].pt4=Vec(bx2, by2); Vec radialLine1=Vec(ax1,ay1).minus(theCircleOf5ths.CircleCenter); Vec radialLine2=Vec(ax2,ay2).minus(theCircleOf5ths.CircleCenter); Vec centerLine=(radialLine1.plus(radialLine2)).div(2.); theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].radialDirection=centerLine; theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].radialDirection=theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].radialDirection.normalize(); // set circle and degree elements correspondence interlinkage theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].CircleIndex=(theCircleOf5ths.theDegreeSemiCircle.OffsetSteps+i+12)%12; if (doDebug) DEBUG("theCircleOf5ths.theDegreeSemiCircle.degreeElements[%d].CircleIndex=%d", i, theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].CircleIndex); if((i == 0)||(i == 1)||(i == 2)) chord_type=0; // majpr else if((i == 3)||(i == 4)||(i == 5)) chord_type=1; // minor else if(i == 6) chord_type=6; // diminished theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].chordType=chord_type; theCircleOf5ths.Circle5ths[theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].CircleIndex].chordType=chord_type; theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].Degree=semiCircleDegrees[(i - theCircleOf5ths.theDegreeSemiCircle.RootKeyCircle5thsPosition+7)%7]; if (doDebug) DEBUG("theCircleOf5ths.theDegreeSemiCircle.degreeElements[%d].Degree=%d", i, theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].Degree); } // if (doDebug) DEBUG(""); if (doDebug) DEBUG("Map arabic steps to semicircle steps:"); for (int i=1; i<8; ++i) // for arabic steps 1-7 , i=1 for 1 based indexing { if (doDebug) DEBUG("arabic step=%d", i); for (int j=0; j<7; ++j) // for semicircle steps { if (theCircleOf5ths.theDegreeSemiCircle.degreeElements[j].Degree==i) { arabicStepDegreeSemicircleIndex[i]=j; if (doDebug) DEBUG(" arabicStepDegreeSemicircleIndex=%d circleposition=%d", arabicStepDegreeSemicircleIndex[i], theCircleOf5ths.theDegreeSemiCircle.degreeElements[arabicStepDegreeSemicircleIndex[i]].CircleIndex); break; } } } if (doDebug) DEBUG(""); if (doDebug) DEBUG("SemiCircle degrees:"); for (int i=0; i<7; ++i) { if (doDebug) DEBUG("theCircleOf5ths.theDegreeSemiCircle.degreeElements[%d].Degree=%d %s", i, theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].Degree, circle_of_fifths_arabic_degrees[theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].Degree]); } if (doDebug) DEBUG(""); if (doDebug) DEBUG("circle position chord types"); for (int i=0; i<12; ++i) { if (doDebug) DEBUG("theCircleOf5ths.Circle5ths[%d].chordType=%d", i, theCircleOf5ths.Circle5ths[i].chordType); } if (doDebug) DEBUG(""); if (doDebug) DEBUG("circle indices"); for (int i=0; i<MAX_HARMONIC_DEGREES; ++i) { if (doDebug) DEBUG("theCircleOf5ths.theDegreeSemiCircle.degreeElements[%d].CircleIndex=%d", i, theCircleOf5ths.theDegreeSemiCircle.degreeElements[i].CircleIndex); } if (doDebug) DEBUG(""); }; void ConfigureGlobals() { ConstructCircle5ths(circle_root_key, mode); ConstructDegreesSemicircle(circle_root_key, mode); //int circleroot_key, int mode) init_notes(); // depends on mode and root_key init_harmony(); // sets up original progressions AuditHarmonyData(3); setup_harmony(); // calculate harmony notes }
87,366
C++
.h
1,729
44.461538
260
0.659699
knchaffin/Meander
36
5
1
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,009
error.cpp
3096_luxray/launcher/source/error.cpp
#include "error.hpp" ResultError::ResultError(const char* what, Result res) : std::runtime_error(what), m_res(res) {} ResultError::~ResultError() {}
151
C++
.cpp
3
48.666667
96
0.732877
3096/luxray
34
7
2
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,010
main.cpp
3096_luxray/launcher/source/main.cpp
#include <stdio.h> #include <unistd.h> #include <string> #include <switch.h> #include "error.hpp" const uint64_t LUXRAY_DOCKED_TITLE_ID = 0x0100000000000195; const uint64_t LUXRAY_HANDHELD_TITLE_ID = 0x0100000000000405; const char* LUXRAY_DOCKED_EXEFS_PATH = "sdmc:/atmosphere/contents/0100000000000195/exefs.nsp"; const char* LUXRAY_HANDHELD_EXEFS_PATH = "sdmc:/atmosphere/contents/0100000000000405/exefs.nsp"; bool getPID(uint64_t& outPID) { if (R_SUCCEEDED(pmdmntGetProcessId(&outPID, LUXRAY_DOCKED_TITLE_ID)) or R_SUCCEEDED(pmdmntGetProcessId(&outPID, LUXRAY_HANDHELD_TITLE_ID))) { return true; } return false; } uint64_t startLuxray(uint64_t titleID) { uint64_t pid = 0; NcmProgramLocation location = {titleID, NcmStorageId_None}; Result res = pmshellLaunchProgram(0, &location, &pid); if (R_FAILED(res)) { throw ResultError("pmshellLaunchProgram", res); } return pid; } void stopLuxray(uint64_t pid) { Result res = pmshellTerminateProcess(pid); if (R_FAILED(res)) { throw ResultError("pmshellTerminateProcess", res); } } bool showStartOptions() { printf( " A - Launch docked mode\n" " Y - Launch handheld mode\n"); while (appletMainLoop()) { hidScanInput(); u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO); if (kDown & KEY_PLUS) { return false; } if (kDown & KEY_A) { startLuxray(LUXRAY_DOCKED_TITLE_ID); return true; } if (kDown & KEY_Y) { startLuxray(LUXRAY_HANDHELD_TITLE_ID); return true; } // check if luxray is running again just in case something weird happens uint64_t pid; if (getPID(pid)) { return true; } consoleUpdate(NULL); } return false; } bool showRunningOptions(uint64_t pid) { printf( " A - Relaunch docked mode\n" " Y - Relaunch handheld mode\n" " X - Stop Luxray\n\n\n" "Luxray Overlay Controls:\n\n" " R = enter\n" // " L = back\n" " D-pad Up + Right Stick Up = toggle overlay display\n"); while (appletMainLoop()) { hidScanInput(); u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO); if (kDown & KEY_PLUS) { return false; } if (kDown & KEY_A) { stopLuxray(pid); pid = startLuxray(LUXRAY_DOCKED_TITLE_ID); } if (kDown & KEY_Y) { stopLuxray(pid); pid = startLuxray(LUXRAY_HANDHELD_TITLE_ID); } if (kDown & KEY_X) { stopLuxray(pid); return true; } // check if luxray pid is still the same just in case something weird happens uint64_t prevPid = pid; if (not getPID(pid) or pid != prevPid) { return true; } consoleUpdate(NULL); } return false; } void launcherMain() { Result res; res = pmshellInitialize(); if (R_FAILED(res)) { throw ResultError("pmshellInitialize", res); } res = pmdmntInitialize(); if (R_FAILED(res)) { throw ResultError("pmdmntInitialize", res); } while (appletMainLoop()) { printf(CONSOLE_ESC(1;1H) CONSOLE_ESC(2J) // clears console CONSOLE_CYAN "Luxray Launcher\n\n" CONSOLE_RESET); // check files if (access(LUXRAY_DOCKED_EXEFS_PATH, F_OK) != 0) { printf(CONSOLE_RED "WARNING: did not find %s\n\n" CONSOLE_RESET, LUXRAY_DOCKED_EXEFS_PATH); } if (access(LUXRAY_HANDHELD_EXEFS_PATH, F_OK) != 0) { printf(CONSOLE_RED "WARNING: did not find %s\n\n" CONSOLE_RESET, LUXRAY_HANDHELD_EXEFS_PATH); } printf("Press: + - Exit launcher\n"); uint64_t pid; if (getPID(pid)) { if (not showRunningOptions(pid)) { break; } } else { if (not showStartOptions()) { break; } } } pmshellExit(); pmdmntExit(); } int main(int argc, char* argv[]) { consoleInit(NULL); try { launcherMain(); } catch (ResultError& resultError) { printf(CONSOLE_RED "\nResult error %s: 0x%x\n" CONSOLE_RESET, resultError.what(), resultError.getResult()); printf("\nPress + to exit...\n"); while (appletMainLoop()) { consoleUpdate(NULL); hidScanInput(); u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO); if (kDown & KEY_PLUS) break; } } consoleExit(NULL); return 0; }
4,690
C++
.cpp
146
24.356164
115
0.581024
3096/luxray
34
7
2
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,011
main.cpp
3096_luxray/source/main.cpp
#include "lx/debug.hpp" #include "lx/overlay.hpp" #include "lx/ui/controller.hpp" #include "lx/util.hpp" #include "screens/main_screen.hpp" #include "theme.hpp" extern "C" { u32 __nx_applet_type = AppletType_None; TimeServiceType __nx_time_service_type = TimeServiceType_System; char nx_inner_heap[INNER_HEAP_SIZE]; u32 __nx_nv_transfermem_size = 0x15000; void __libnx_initheap(void); void __libnx_init_time(void); void __appInit(void); void __appExit(void); } void __libnx_initheap(void) { extern char* fake_heap_start; extern char* fake_heap_end; fake_heap_start = nx_inner_heap; fake_heap_end = nx_inner_heap + sizeof(nx_inner_heap); } bool g_appInitSuccessful = false; void __appInit(void) { g_appInitSuccessful = true; // assume success if __appInit is called and no fatal // Init services Result rc; if (R_FAILED(smInitialize())) fatalThrow(MAKERESULT(Module_Libnx, LibnxError_InitFail_SM)); if (R_FAILED(hidInitialize())) fatalThrow(MAKERESULT(Module_Libnx, LibnxError_InitFail_HID)); if (R_FAILED(fsInitialize())) fatalThrow(MAKERESULT(Module_Libnx, LibnxError_InitFail_FS)); if (R_FAILED(rc = timeInitialize())) { // TimeServiceType_System only has 2 available session normally, // so we switch to TimeServiceType_User and flag the failure without fatal timeExit(); g_appInitSuccessful = false; __nx_time_service_type = TimeServiceType_User; if (R_FAILED(rc = timeInitialize())) fatalThrow(rc); } if (R_FAILED(rc = apmInitialize())) fatalThrow(rc); if (R_FAILED(rc = setsysInitialize())) fatalThrow(rc); if (R_FAILED(rc = nifmInitialize(NifmServiceType_User))) fatalThrow(rc); if (R_FAILED(rc = viInitialize(ViServiceType_Manager))) fatalThrow(rc); __libnx_init_time(); if (R_FAILED(fsdevMountSdmc())) fatalThrow(0x5D); auto socketConfig = SocketInitConfig{.bsdsockets_version = 1, .tcp_tx_buf_size = 0x800, .tcp_rx_buf_size = 0x1000, .tcp_tx_buf_max_size = 0, .tcp_rx_buf_max_size = 0, .udp_tx_buf_size = 0x2400, .udp_rx_buf_size = 0xA500, .sb_efficiency = 1}; TRY_FATAL(socketInitialize(&socketConfig)); lx::debugInit(); lx::Overlay::initialize(); theme::initialize(); } void __appExit(void) { // Cleanup services. lx::debugExit(); socketExit(); fsdevUnmountAll(); viExit(); nifmExit(); setsysExit(); apmExit(); timeExit(); fsExit(); hidExit(); smExit(); } int main(int argc, char* argv[]) { if (g_appInitSuccessful) { LOG("services initialized"); } else { LOG("__appInit failed"); return -1; } LOG("Main start"); try { lx::ui::Controller::show(MainScreen::getInstance()); } catch (std::runtime_error& e) { LOG("runtime_error: %s", e.what()); } LOG("Main exit"); return 0; }
3,153
C++
.cpp
87
28.735632
97
0.609636
3096/luxray
34
7
2
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,012
theme.cpp
3096_luxray/source/theme.cpp
#include "theme.hpp" namespace theme { constexpr auto LUXRAY_BLUE = 0x1976D2; constexpr auto LUXRAY_GOLD = 0xFFD600; constexpr auto LUXRAY_GREY = 0x263238; constexpr auto BORDER_GREY = 0x707070; constexpr auto PRESSED_GREY = 0x607D8B; constexpr auto CHECKED_GREY = 0x455A64; constexpr auto DISABLED_GREY = 0x424242; lv_style_t luxrayBlueStyle; lv_style_t btnmatrixBgStyle; lv_style_t btnmatrixBtnStyle; void initialize() { LOGSL("Initializing... "); lx::ui::lv::initBgColorStyle(luxrayBlueStyle, lv_color_hex(LUXRAY_BLUE)); lx::ui::lv::initBgColorStyle(btnmatrixBgStyle, lv_color_hex(LUXRAY_GREY)); lv_style_set_border_color(&btnmatrixBgStyle, LV_STATE_DEFAULT, lv_color_hex(BORDER_GREY)); lv_style_set_border_color(&btnmatrixBgStyle, LV_STATE_FOCUSED, lv_color_hex(BORDER_GREY)); lv_style_set_border_color(&btnmatrixBgStyle, LV_STATE_CHECKED, lv_color_hex(LUXRAY_BLUE)); lx::ui::lv::initBgColorStyle(btnmatrixBtnStyle, lv_color_hex(LUXRAY_GREY)); lv_style_set_border_color(&btnmatrixBtnStyle, LV_STATE_DEFAULT, lv_color_hex(BORDER_GREY)); lv_style_set_bg_color(&btnmatrixBtnStyle, LV_STATE_PRESSED, lv_color_hex(PRESSED_GREY)); lv_style_set_bg_color(&btnmatrixBtnStyle, LV_STATE_CHECKED, lv_color_hex(CHECKED_GREY)); lv_style_set_bg_color(&btnmatrixBtnStyle, LV_STATE_DISABLED, lv_color_hex(CHECKED_GREY)); lv_style_set_text_color(&btnmatrixBtnStyle, LV_STATE_DISABLED, lv_color_hex(DISABLED_GREY)); lv_style_set_border_color(&btnmatrixBtnStyle, LV_STATE_FOCUSED, lv_color_hex(LUXRAY_GOLD)); lv_style_set_border_color(&btnmatrixBtnStyle, LV_STATE_FOCUSED | LV_STATE_PRESSED, lv_color_hex(LUXRAY_GOLD)); lv_style_set_border_color(&btnmatrixBtnStyle, LV_STATE_FOCUSED | LV_STATE_CHECKED, lv_color_hex(LUXRAY_BLUE)); lv_style_set_border_color(&btnmatrixBtnStyle, LV_STATE_FOCUSED | LV_STATE_DISABLED, lv_color_hex(LUXRAY_GOLD)); lv_style_set_bg_color(&btnmatrixBtnStyle, LV_STATE_FOCUSED | LV_STATE_PRESSED, lv_color_hex(PRESSED_GREY)); lv_style_set_bg_color(&btnmatrixBtnStyle, LV_STATE_FOCUSED | LV_STATE_CHECKED, lv_color_hex(LUXRAY_GOLD)); lv_style_set_bg_color(&btnmatrixBtnStyle, LV_STATE_FOCUSED | LV_STATE_DISABLED, lv_color_hex(CHECKED_GREY)); // lv_style_set_text_color(&btnmatrixBtnStyle, LV_STATE_FOCUSED | LV_STATE_DISABLED, lv_color_hex(DISABLED_GREY)); LOGEL("done"); } auto createWindow(lv_obj_t* p_parent) -> lv_obj_t* { auto result = lx::ui::lv_win::create(p_parent); lv_obj_add_style(result, LV_WIN_PART_HEADER, &luxrayBlueStyle); lv_obj_add_style(result, LV_WIN_PART_BG, lx::ui::Controller::getScreenStyle()); return result; } auto createBtnmatrix(lv_obj_t* p_parent) -> lv_obj_t* { auto result = lx::ui::lv_btnmatrix::create(p_parent); lv_obj_add_style(result, LV_BTNMATRIX_PART_BG, &btnmatrixBgStyle); lv_obj_add_style(result, LV_BTNMATRIX_PART_BTN, &btnmatrixBtnStyle); return result; } } // namespace theme
2,961
C++
.cpp
48
57.958333
118
0.746377
3096/luxray
34
7
2
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,013
system.cpp
3096_luxray/source/core/system.cpp
#include "system.hpp" #include <switch.h> #include <stdexcept> #include <string> #include "lx/util.hpp" bool os::nifmInternetIsConnected() { NifmInternetConnectionStatus nifmICS; Result rs = nifmGetInternetConnectionStatus(NULL, NULL, &nifmICS); if (R_FAILED(rs)) { return false; } return nifmICS == NifmInternetConnectionStatus_Connected; } bool os::setsysInternetTimeSyncIsOn() { bool internetTimeSyncIsOn; Result rs = setsysIsUserSystemClockAutomaticCorrectionEnabled(&internetTimeSyncIsOn); if (R_FAILED(rs)) { std::string msg = "Unable to detect if Internet time sync is enabled: " + std::to_string(rs); throw std::runtime_error(msg); } return internetTimeSyncIsOn; }
744
C++
.cpp
22
29.590909
101
0.732867
3096/luxray
34
7
2
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,014
ntp.cpp
3096_luxray/source/core/ntp.cpp
/* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to <https://unlicense.org> Additionally, the ntp_packet struct uses code licensed under the BSD 3-clause. See LICENSE-THIRD-PARTY for more information. */ #define _BSD_SOURCE #include "ntp.hpp" #include <arpa/inet.h> #include <netdb.h> #include <netinet/in.h> #include <switch.h> #include <sys/socket.h> #include <cstring> #include <stdexcept> #include <string> #include "lx/debug.hpp" time_t ntpGetTime() { static const char* SERVER_NAME = "0.pool.ntp.org"; static const uint16_t PORT = 123; int sockfd = -1; sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sockfd < 0) { std::string msg = "Failed to open socket with error code " + std::to_string(errno); throw std::runtime_error(msg); } LOG("Opened socket\nAttempting to connect to %s", SERVER_NAME); struct hostent* server; errno = 0; if ((server = gethostbyname(SERVER_NAME)) == NULL) { std::string msg = "Gethostbyname failed: " + std::to_string(errno); throw std::runtime_error(msg); } struct sockaddr_in serv_addr; memset(&serv_addr, 0, sizeof(struct sockaddr_in)); serv_addr.sin_family = AF_INET; memcpy((char*)&serv_addr.sin_addr.s_addr, (char*)server->h_addr_list[0], 4); serv_addr.sin_port = htons(PORT); errno = 0; int res = 0; if ((res = connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) < 0) { std::string msg = "Connect failed: " + std::to_string(res); msg += " errno: " + std::to_string(errno); throw std::runtime_error(msg); } LOG("Connected to 0.pool.ntp.org with result: %x %x\nSending time request...", res, errno); ntp_packet packet; memset(&packet, 0, sizeof(ntp_packet)); packet.li_vn_mode = (0 << 6) | (4 << 3) | 3; // LI 0 | Client version 4 | Mode 3 packet.txTm_s = htonl(NTP_TIMESTAMP_DELTA + time(NULL)); // Current networktime on the console errno = 0; if ((res = send(sockfd, (char*)&packet, sizeof(ntp_packet), 0)) < 0) { std::string msg = "Error writing to socket: " + std::to_string(res); msg += " errno: " + std::to_string(errno); throw std::runtime_error(msg); } LOG("Sent time request with result: %x %x, waiting for response...", res, errno); errno = 0; if ((size_t)(res = recv(sockfd, (char*)&packet, sizeof(ntp_packet), 0)) < sizeof(ntp_packet)) { std::string msg = "Error reading from socket: " + std::to_string(res); msg += " errno: " + std::to_string(errno); throw std::runtime_error(msg); } packet.txTm_s = ntohl(packet.txTm_s); return (time_t)(packet.txTm_s - NTP_TIMESTAMP_DELTA); }
3,856
C++
.cpp
82
42.878049
111
0.689297
3096/luxray
34
7
2
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,015
time.cpp
3096_luxray/source/core/time.cpp
#include "time.hpp" #include <switch.h> #include <stdexcept> #include "lx/debug.hpp" #include "ntp.hpp" TimeTaskHandler::TimeTaskHandler() : STEP_INTERVAL_TICKS(STEP_INTERVAL * armGetSystemTickFreq()), m_curDaysLeftToStep(-1), m_isInStep(false), m_isAbortingStep(false), m_lastStepTick(0) { handleTask(); m_resetTargetTm = *localtime(&m_curTime); } TimeTaskHandler::~TimeTaskHandler() {} void TimeTaskHandler::handleTask() { Result rs = timeGetCurrentTime(TimeType_UserSystemClock, (u64*)&m_curTime); if (R_FAILED(rs)) { std::string err_msg = "timeGetCurrentTime failed with " + rs; throw std::runtime_error(err_msg); } if (m_isInStep) { u64 curSystemTick = armGetSystemTick(); if (curSystemTick - m_lastStepTick > STEP_INTERVAL_TICKS) { if (m_isAbortingStep or m_curDaysLeftToStep <= 0) { if (m_resetAfterStep) { resetTime(); } m_isAbortingStep = m_isInStep = false; } else { setTime_(m_curTime + m_curStepDirection * 60 * 60 * 24, false); m_curDaysLeftToStep--; } m_lastStepTick = curSystemTick; } } } void TimeTaskHandler::startStepDaysTask(int8_t stepDirection, int daysToStep, bool resetAfterStep) { m_curStepDirection = stepDirection; m_curDaysLeftToStep = daysToStep; m_resetAfterStep = resetAfterStep; m_isInStep = true; } std::string TimeTaskHandler::getCurDateStr() { struct tm* p_tm = localtime(&m_curTime); char dateStr[11]; strftime(dateStr, sizeof(dateStr), "%F", p_tm); return std::string(dateStr); } void TimeTaskHandler::setTime_(time_t time, bool updateResetTarget) { Result rs = timeSetCurrentTime(TimeType_NetworkSystemClock, (uint64_t)time); if (R_FAILED(rs)) { std::string err_msg = "timeSetCurrentTime failed with " + rs; throw std::runtime_error(err_msg); } if (updateResetTarget) { m_resetTargetTm = *localtime(&time); } } void TimeTaskHandler::setDayChange(int dayChange) { setTime_(m_curTime + (time_t)dayChange * 60 * 60 * 24); } void TimeTaskHandler::setTimeNTP() { setTime_(ntpGetTime()); } void TimeTaskHandler::resetTime() { // use current HMS so only the date is reset struct tm curTimeTm = *localtime(&m_curTime); struct tm timeToSetTm = m_resetTargetTm; timeToSetTm.tm_hour = curTimeTm.tm_hour; timeToSetTm.tm_min = curTimeTm.tm_min; timeToSetTm.tm_sec = curTimeTm.tm_sec; setTime_(mktime(&timeToSetTm)); }
2,604
C++
.cpp
70
31.028571
109
0.661111
3096/luxray
34
7
2
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,016
main_screen.cpp
3096_luxray/source/screens/main_screen.cpp
#include "main_screen.hpp" #include <switch.h> #include "../core/system.hpp" #include "lx/ui/controller.hpp" #include "time_error_screen.hpp" #include "time_screen.hpp" MainScreen MainScreen::s_instance; MainScreen::MainScreen() : LOGCONSTRUCTSL m_screenToShow(NO_SUB_SCREEN), m_shouldExit(false) { // list of buttons to different screens mp_screenListObj = lv_list_create(getLvScreenObj(), nullptr); lv_obj_align(mp_screenListObj, nullptr, LV_ALIGN_CENTER, 0, 0); m_basicScreen.addLvObjPositionUpdater(mp_screenListObj, lv_obj_realign); // TODO: refactor the strings here lv_obj_set_event_cb(lv_list_add_btn(mp_screenListObj, nullptr, "Date Advance"), handleShowTimeScreen_); lv_obj_set_event_cb(lv_list_add_btn(mp_screenListObj, nullptr, "Exit"), handleExit_); lv_group_add_obj(getLvInputGroup(), mp_screenListObj); LOGEL("done"); } MainScreen::~MainScreen() {} void MainScreen::renderScreen() { m_basicScreen.renderScreen(); } void MainScreen::procFrame() { switch (m_screenToShow) { case TIME_SCREEN: if (os::setsysInternetTimeSyncIsOn()) { showScreen_(TimeScreen::getInstance()); } else { showScreen_(TimeErrorScreen::getInstance()); } break; default: break; } if (m_shouldExit) { lx::ui::Controller::stop(); } } void MainScreen::showScreen_(lx::ui::IScreen& screenToShow) { lx::ui::Controller::show(screenToShow); // remove m_screenToShow to show main screen again m_screenToShow = NO_SUB_SCREEN; } void MainScreen::handleShowScreen_(lv_event_t event, SubScreen screenToShow) { if (event == LV_EVENT_CLICKED) { m_screenToShow = screenToShow; } } void MainScreen::handleExit_(lv_obj_t* obj, lv_event_t event) { if (event == LV_EVENT_CLICKED) { s_instance.m_shouldExit = true; } }
1,911
C++
.cpp
51
32.039216
107
0.678223
3096/luxray
34
7
2
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,017
time_error_screen.cpp
3096_luxray/source/screens/time_error_screen.cpp
#include "time_error_screen.hpp" #include "lx/debug.hpp" #include "lx/ui/controller.hpp" #include "main_screen.hpp" TimeErrorScreen TimeErrorScreen::s_instance; TimeErrorScreen::TimeErrorScreen() { LOGSL("constructing... "); mp_errorMsgLabel = lv_label_create(getLvScreenObj(), nullptr); lv_label_set_text(mp_errorMsgLabel, "To use the Date Advance\n" "feature, turn on\n" "\"Synchronize Clock via\n" "Internet\" in System Settings."); lv_obj_align(mp_errorMsgLabel, nullptr, LV_ALIGN_CENTER, 0, 0); m_basicScreen.addLvObjPositionUpdater(mp_errorMsgLabel, lv_obj_realign); LOGEL("done"); } TimeErrorScreen::~TimeErrorScreen() {} void TimeErrorScreen::renderScreen() { m_basicScreen.renderScreen(); } void TimeErrorScreen::procFrame() { if (m_basicScreen.returnButtonPressed()) { lx::ui::Controller::show(MainScreen::getInstance()); } }
972
C++
.cpp
24
33.833333
76
0.671277
3096/luxray
34
7
2
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,018
time_screen.cpp
3096_luxray/source/screens/time_screen.cpp
#include "time_screen.hpp" #include <cstring> #include <stdexcept> #include "../core/system.hpp" #include "../screens/main_screen.hpp" #include "../theme.hpp" #include "lx/ui/controller.hpp" #include "lx/ui/lv_helper.hpp" TimeScreen TimeScreen::s_instance; TimeScreen::TimeScreen() : LOGCONSTRUCT mp_timeTaskHandler(std::make_unique<TimeTaskHandler>()), m_doAutoReset(true), m_isInStepDays(false), m_isAlreadyNTP(false), m_disableNTP(false), m_internetIsConnected(false), m_curTargetChange(0), m_curTargetSign(1) { // lv_obj_t* p_window = theme::createWindow(getLvScreenObj()); m_basicScreen.addLvObjPositionUpdater(p_window, lx::ui::lv_win::updateFitParent); lv_win_set_title(p_window, " Date Advance"); mp_promptLabel = lx::ui::lv_label::create(p_window); m_basicScreen.addLvObjPositionUpdater(mp_promptLabel, [](lv_obj_t* mp_promptLabel) { lv_obj_align(mp_promptLabel, nullptr, LV_ALIGN_IN_TOP_LEFT, lx::ui::size::MARGIN(), lx::ui::size::MARGIN()); }); mp_valueLabel = lx::ui::lv_label::create(p_window); lv_label_set_align(mp_valueLabel, LV_LABEL_ALIGN_RIGHT); m_basicScreen.addLvObjPositionUpdater(mp_valueLabel, [](lv_obj_t* mp_valueLabel) { lv_obj_align(mp_valueLabel, nullptr, LV_ALIGN_IN_TOP_RIGHT, -lx::ui::size::MARGIN(), lx::ui::size::MARGIN()); }); mp_buttonMatrix = theme::createBtnmatrix(p_window); m_basicScreen.addLvObjPositionUpdater(mp_buttonMatrix, [p_window](lv_obj_t* mp_buttonMatrix) { lv_obj_set_size(mp_buttonMatrix, lx::ui::BasicScreenProvider::coord(BUTTON_MATRIX_WIDTH), lx::ui::BasicScreenProvider::coord(BUTTON_MATRIX_HEIGHT)); lv_obj_align(mp_buttonMatrix, p_window, LV_ALIGN_IN_BOTTOM_MID, 0, -lx::ui::size::MARGIN()); }); std::memcpy(m_buttonMap, INITIAL_BUTTON_MAP, sizeof(INITIAL_BUTTON_MAP)); lv_btnmatrix_set_map(mp_buttonMatrix, static_cast<const char**>(m_buttonMap)); lv_btnmatrix_set_btn_ctrl(mp_buttonMatrix, BUTTON_NEGATIVE, LV_BTNMATRIX_CTRL_CHECKABLE); lv_btnmatrix_set_btn_ctrl(mp_buttonMatrix, BUTTON_AUTORESET, LV_BTNMATRIX_CTRL_CHECKABLE); if (m_doAutoReset) lv_btnmatrix_set_btn_ctrl(mp_buttonMatrix, BUTTON_AUTORESET, LV_BTNMATRIX_CTRL_CHECK_STATE); lv_btnmatrix_set_btn_ctrl(mp_buttonMatrix, BUTTON_NTP, LV_BTNMATRIX_CTRL_DISABLED); lv_obj_set_event_cb(mp_buttonMatrix, handleButtonEvent_); lv_group_add_obj(getLvInputGroup(), mp_buttonMatrix); LOG("constructed"); } TimeScreen::~TimeScreen() {} void TimeScreen::renderScreen() { m_basicScreen.renderScreen(); updateLabels_(); } void TimeScreen::procFrame() { // lx::Overlay::pauseRendering(); // lv tries to draw text before it knows where, smh // handle task, needed every frame mp_timeTaskHandler->handleTask(); if (m_isInStepDays) { if (mp_timeTaskHandler->isStepping()) { m_curTargetChange = mp_timeTaskHandler->daysLeftToStep(); } else { handleStepDaysEnd_(); } } updateLabels_(); // stuffs that can run less than every frame, might refactor if (not m_disableNTP and m_internetIsConnected != os::nifmInternetIsConnected()) { if (m_internetIsConnected) { lv_btnmatrix_set_btn_ctrl(mp_buttonMatrix, BUTTON_NTP, LV_BTNMATRIX_CTRL_DISABLED); } else { lv_btnmatrix_clear_btn_ctrl(mp_buttonMatrix, BUTTON_NTP, LV_BTNMATRIX_CTRL_DISABLED); } m_internetIsConnected = !m_internetIsConnected; } // lx::Overlay::resumeRendering(); if (m_basicScreen.returnButtonPressed() and not m_isInStepDays) { lx::ui::Controller::show(MainScreen::getInstance()); } } void TimeScreen::handleButtonEventImpl_() { Button button = (Button)lv_btnmatrix_get_active_btn(mp_buttonMatrix); if (m_isInStepDays) { // all other buttons are disabled if (button == BUTTON_STEP) { mp_timeTaskHandler->stopStepDaysTask(); // disable step button in case need to wait for auto reset lv_btnmatrix_set_btn_ctrl(mp_buttonMatrix, BUTTON_STEP, LV_BTNMATRIX_CTRL_DISABLED); } return; } switch (button) { case BUTTON_RESET: mp_timeTaskHandler->resetTime(); m_curTargetChange = 0; if (m_curTargetSign != 1) { m_curTargetSign = 1; lv_btnmatrix_clear_btn_ctrl(mp_buttonMatrix, BUTTON_NEGATIVE, LV_BTNMATRIX_CTRL_CHECK_STATE); } return; case BUTTON_AUTORESET: m_doAutoReset = !m_doAutoReset; return; case BUTTON_SET: mp_timeTaskHandler->setDayChange(m_curTargetSign * m_curTargetChange); break; case BUTTON_STEP: if (m_curTargetChange == 0) { return; } handleStepDaysStart_(m_curTargetSign, m_curTargetChange); break; case BUTTON_PLUS_ONE: handleStepDaysStart_(1, 1); break; case BUTTON_PLUS_TWO: handleStepDaysStart_(1, 2); break; case BUTTON_PLUS_THREE: handleStepDaysStart_(1, 3); break; case BUTTON_NEGATIVE: m_curTargetSign *= -1; return; case BUTTON_BACKSPACE: m_curTargetChange /= 10; return; case BUTTON_NTP: if (m_internetIsConnected and not m_isAlreadyNTP) { try { mp_timeTaskHandler->setTimeNTP(); lv_btnmatrix_set_btn_ctrl(mp_buttonMatrix, BUTTON_NTP, LV_BTNMATRIX_CTRL_CHECK_STATE); m_isAlreadyNTP = true; } catch (std::runtime_error& e) { lv_btnmatrix_set_btn_ctrl(mp_buttonMatrix, BUTTON_NTP, LV_BTNMATRIX_CTRL_DISABLED); m_disableNTP = true; LOG("NTP runtime_error: %s", e.what()); } } return; default: // number button m_curTargetChange = m_curTargetChange * 10 + (lv_btnmatrix_get_active_btn_text(mp_buttonMatrix)[0] - '0'); if (m_curTargetChange > MAX_TARGET_CHANGE) { m_curTargetChange = MAX_TARGET_CHANGE; } return; } // time is changed from last NTP call lv_btnmatrix_clear_btn_ctrl(mp_buttonMatrix, BUTTON_NTP, LV_BTNMATRIX_CTRL_CHECK_STATE); m_isAlreadyNTP = false; } void TimeScreen::handleButtonEvent_(lv_obj_t* btnm, lv_event_t event) { if (event == LV_EVENT_CLICKED) { s_instance.handleButtonEventImpl_(); } } void TimeScreen::handleStepDaysStart_(int8_t stepDirection, int daysToStep) { mp_timeTaskHandler->startStepDaysTask(stepDirection, daysToStep, m_doAutoReset); m_buttonMap[STEP_MAP_IDX] = STRING_STEP_CANCEL; // inactive all buttons lv_btnmatrix_ext_t* btnmExt = (lv_btnmatrix_ext_t*)lv_obj_get_ext_attr(mp_buttonMatrix); for (uint16_t i = 0; i < btnmExt->btn_cnt; i++) { btnmExt->ctrl_bits[i] |= LV_BTNMATRIX_CTRL_DISABLED; } btnmExt->ctrl_bits[BUTTON_STEP] = LV_BTNMATRIX_CTRL_CHECK_STATE; lv_obj_invalidate(mp_buttonMatrix); m_isInStepDays = true; } void TimeScreen::handleStepDaysEnd_() { m_buttonMap[STEP_MAP_IDX] = STRING_STEP; // active all buttons lv_btnmatrix_ext_t* btnmExt = (lv_btnmatrix_ext_t*)lv_obj_get_ext_attr(mp_buttonMatrix); for (uint16_t i = 0; i < btnmExt->btn_cnt; i++) { btnmExt->ctrl_bits[i] &= ~LV_BTNMATRIX_CTRL_DISABLED; } // except NTP button if it's inactive if (m_disableNTP or not m_internetIsConnected) { btnmExt->ctrl_bits[BUTTON_NTP] |= LV_BTNMATRIX_CTRL_DISABLED; } btnmExt->ctrl_bits[BUTTON_STEP] = 0; // clear step button's toggle lv_obj_invalidate(mp_buttonMatrix); m_isInStepDays = false; } void TimeScreen::updateLabels_() { // generate label strings m_promptLabelStr = STRING_CUR_DATE; m_promptLabelStr += "\n"; m_promptLabelStr += m_isInStepDays ? STRING_STEPPING : STRING_TARGET_CHANGE; m_valueLabelStr = mp_timeTaskHandler->getCurDateStr() + "\n"; m_valueLabelStr += std::to_string(m_curTargetSign * m_curTargetChange); m_valueLabelStr += STRING_DAYS; // render new text lv_label_set_text(mp_promptLabel, m_promptLabelStr.c_str()); lv_label_set_text(mp_valueLabel, m_valueLabelStr.c_str()); lv_obj_realign(mp_valueLabel); }
8,495
C++
.cpp
193
36.124352
118
0.648005
3096/luxray
34
7
2
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,019
error.hpp
3096_luxray/launcher/source/error.hpp
#pragma once #include <stdexcept> #include <switch.h> class ResultError : public std::runtime_error { private: Result m_res; public: ResultError(const char* what, Result res); ~ResultError(); inline Result getResult() { return m_res; } };
266
C++
.h
11
20.727273
47
0.7
3096/luxray
34
7
2
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,020
lv_config.h
3096_luxray/source/lv_config.h
/** * @file lv_conf.h * */ /* * COPY THIS FILE AS `lv_conf.h` NEXT TO the `lvgl` FOLDER */ #if 1 /*Set it to "1" to enable content*/ #ifndef LV_CONF_H #define LV_CONF_H /* clang-format off */ #include <stdint.h> #include "lx/layer_info.h" /*==================== Graphical settings *====================*/ /* Maximal horizontal and vertical resolution to support by the library.*/ #define LV_HOR_RES_MAX LAYER_BUFFER_WIDTH #define LV_VER_RES_MAX LAYER_BUFFER_HEIGHT /* Color depth: * - 1: 1 byte per pixel * - 8: RGB233 * - 16: RGB565 * - 32: ARGB8888 */ #define LV_COLOR_DEPTH 32 /* Swap the 2 bytes of RGB565 color. * Useful if the display has a 8 bit interface (e.g. SPI)*/ #define LV_COLOR_16_SWAP 0 /* 1: Enable screen transparency. * Useful for OSD or other overlapping GUIs. * Requires `LV_COLOR_DEPTH = 32` colors and the screen's style should be modified: `style.body.opa = ...`*/ #define LV_COLOR_SCREEN_TRANSP 1 /*Images pixels with this color will not be drawn (with chroma keying)*/ #define LV_COLOR_TRANSP LV_COLOR_LIME /*LV_COLOR_LIME: pure green*/ /* Enable chroma keying for indexed images. */ #define LV_INDEXED_CHROMA 1 /* Enable anti-aliasing (lines, and radiuses will be smoothed) */ #define LV_ANTIALIAS 1 /* Default display refresh period. * Can be changed in the display driver (`lv_disp_drv_t`).*/ #define LV_DISP_DEF_REFR_PERIOD 16 /*[ms]*/ /* Dot Per Inch: used to initialize default sizes. * E.g. a button with width = LV_DPI / 2 -> half inch wide * (Not so important, you can adjust it to modify default sizes and spaces)*/ #define LV_DPI 100 /*[px]*/ /* The the real width of the display changes some default values: * default object sizes, layout of examples, etc. * According to the width of the display (hor. res. / dpi) * the displays fall in 4 categories. * The 4th is extra large which has no upper limit so not listed here * The upper limit of the categories are set below in 0.1 inch unit. */ // #define LV_DISP_SMALL_LIMIT 30 // #define LV_DISP_MEDIUM_LIMIT 50 // #define LV_DISP_LARGE_LIMIT 70 /* Type of coordinates. Should be `int16_t` (or `int32_t` for extreme cases) */ typedef int16_t lv_coord_t; /*========================= Memory manager settings *=========================*/ /* LittelvGL's internal memory manager's settings. * The graphical objects and other related data are stored here. */ /* 1: use custom malloc/free, 0: use the built-in `lv_mem_alloc` and `lv_mem_free` */ #define LV_MEM_CUSTOM 1 #if LV_MEM_CUSTOM == 0 /* Size of the memory used by `lv_mem_alloc` in bytes (>= 2kB)*/ # define LV_MEM_SIZE (32U * 1024U) /* Complier prefix for a big array declaration */ # define LV_MEM_ATTR /* Set an address for the memory pool instead of allocating it as an array. * Can be in external SRAM too. */ # define LV_MEM_ADR 0 /* Automatically defrag. on free. Defrag. means joining the adjacent free cells. */ # define LV_MEM_AUTO_DEFRAG 1 #else /*LV_MEM_CUSTOM*/ # define LV_MEM_CUSTOM_INCLUDE <stdlib.h> /*Header for the dynamic memory function*/ # define LV_MEM_CUSTOM_ALLOC malloc /*Wrapper to malloc*/ # define LV_MEM_CUSTOM_FREE free /*Wrapper to free*/ #endif /*LV_MEM_CUSTOM*/ /* Garbage Collector settings * Used if lvgl is binded to higher level language and the memory is managed by that language */ #define LV_ENABLE_GC 0 #if LV_ENABLE_GC != 0 # define LV_GC_INCLUDE "gc.h" /*Include Garbage Collector related things*/ # define LV_MEM_CUSTOM_REALLOC your_realloc /*Wrapper to realloc*/ # define LV_MEM_CUSTOM_GET_SIZE your_mem_get_size /*Wrapper to lv_mem_get_size*/ #endif /* LV_ENABLE_GC */ /*======================= Input device settings *=======================*/ /* Input device default settings. * Can be changed in the Input device driver (`lv_indev_drv_t`)*/ /* Input device read period in milliseconds */ #define LV_INDEV_DEF_READ_PERIOD 30 /* Drag threshold in pixels */ #define LV_INDEV_DEF_DRAG_LIMIT 10 /* Drag throw slow-down in [%]. Greater value -> faster slow-down */ #define LV_INDEV_DEF_DRAG_THROW 10 /* Long press time in milliseconds. * Time to send `LV_EVENT_LONG_PRESSSED`) */ #define LV_INDEV_DEF_LONG_PRESS_TIME 400 /* Repeated trigger period in long press [ms] * Time between `LV_EVENT_LONG_PRESSED_REPEAT */ #define LV_INDEV_DEF_LONG_PRESS_REP_TIME 100 /* Gesture threshold in pixels */ #define LV_INDEV_DEF_GESTURE_LIMIT 50 /* Gesture min velocity at release before swipe (pixels)*/ #define LV_INDEV_DEF_GESTURE_MIN_VELOCITY 3 /*================== * Feature usage *==================*/ /*1: Enable the Animations */ #define LV_USE_ANIMATION 1 #if LV_USE_ANIMATION /*Declare the type of the user data of animations (can be e.g. `void *`, `int`, `struct`)*/ typedef void * lv_anim_user_data_t; #endif /* 1: Enable shadow drawing*/ #define LV_USE_SHADOW 1 #if LV_USE_SHADOW /* Allow buffering some shadow calculation * LV_SHADOW_CACHE_SIZE is the max. shadow size to buffer, * where shadow size is `shadow_width + radius` * Caching has LV_SHADOW_CACHE_SIZE^2 RAM cost*/ #define LV_SHADOW_CACHE_SIZE 0 #endif /* 1: Use other blend modes than normal (`LV_BLEND_MODE_...`)*/ #define LV_USE_BLEND_MODES 1 /* 1: Use the `opa_scale` style property to set the opacity of an object and its children at once*/ #define LV_USE_OPA_SCALE 1 /* 1: Use image zoom and rotation*/ #define LV_USE_IMG_TRANSFORM 1 /* 1: Enable object groups (for keyboard/encoder navigation) */ #define LV_USE_GROUP 1 #if LV_USE_GROUP typedef void * lv_group_user_data_t; #endif /*LV_USE_GROUP*/ /* 1: Enable GPU interface*/ #define LV_USE_GPU 0 /*Only enables `gpu_fill_cb` and `gpu_blend_cb` in the disp. drv- */ #define LV_USE_GPU_STM32_DMA2D 0 /*If enabling LV_USE_GPU_STM32_DMA2D, LV_GPU_DMA2D_CMSIS_INCLUDE must be defined to include path of CMSIS header of target processor e.g. "stm32f769xx.h" or "stm32f429xx.h" */ #define LV_GPU_DMA2D_CMSIS_INCLUDE /* 1: Enable file system (might be required for images */ #define LV_USE_FILESYSTEM 1 #if LV_USE_FILESYSTEM /*Declare the type of the user data of file system drivers (can be e.g. `void *`, `int`, `struct`)*/ typedef void * lv_fs_drv_user_data_t; #endif /*1: Add a `user_data` to drivers and objects*/ #define LV_USE_USER_DATA 0 /*1: Show CPU usage and FPS count in the right bottom corner*/ #define LV_USE_PERF_MONITOR 0 /*1: Use the functions and types from the older API if possible */ #define LV_USE_API_EXTENSION_V6 0 /*======================== * Image decoder and cache *========================*/ /* 1: Enable indexed (palette) images */ #define LV_IMG_CF_INDEXED 1 /* 1: Enable alpha indexed images */ #define LV_IMG_CF_ALPHA 1 /* Default image cache size. Image caching keeps the images opened. * If only the built-in image formats are used there is no real advantage of caching. * (I.e. no new image decoder is added) * With complex image decoders (e.g. PNG or JPG) caching can save the continuous open/decode of images. * However the opened images might consume additional RAM. * LV_IMG_CACHE_DEF_SIZE must be >= 1 */ #define LV_IMG_CACHE_DEF_SIZE 1 /*Declare the type of the user data of image decoder (can be e.g. `void *`, `int`, `struct`)*/ typedef void * lv_img_decoder_user_data_t; /*===================== * Compiler settings *====================*/ /* For big endian systems set to 1 */ #define LV_BIG_ENDIAN_SYSTEM 0 /* Define a custom attribute to `lv_tick_inc` function */ #define LV_ATTRIBUTE_TICK_INC /* Define a custom attribute to `lv_task_handler` function */ #define LV_ATTRIBUTE_TASK_HANDLER /* Define a custom attribute to `lv_disp_flush_ready` function */ #define LV_ATTRIBUTE_FLUSH_READY /* With size optimization (-Os) the compiler might not align data to * 4 or 8 byte boundary. This alignment will be explicitly applied where needed. * E.g. __attribute__((aligned(4))) */ #define LV_ATTRIBUTE_MEM_ALIGN /* Attribute to mark large constant arrays for example * font's bitmaps */ #define LV_ATTRIBUTE_LARGE_CONST /* Prefix performance critical functions to place them into a faster memory (e.g RAM) * Uses 15-20 kB extra memory */ #define LV_ATTRIBUTE_FAST_MEM /* Export integer constant to binding. * This macro is used with constants in the form of LV_<CONST> that * should also appear on lvgl binding API such as Micropython * * The default value just prevents a GCC warning. */ #define LV_EXPORT_CONST_INT(int_value) struct _silence_gcc_warning /* Prefix variables that are used in GPU accelerated operations, often these need to be * placed in RAM sections that are DMA accessible */ #define LV_ATTRIBUTE_DMA /*=================== * HAL settings *==================*/ /* 1: use a custom tick source. * It removes the need to manually update the tick with `lv_tick_inc`) */ #define LV_TICK_CUSTOM 1 #if LV_TICK_CUSTOM == 1 #define LV_TICK_CUSTOM_INCLUDE <switch.h> /*Header for the sys time function*/ #define LV_TICK_CUSTOM_SYS_TIME_EXPR ((uint32_t)((armGetSystemTick()*1000ul)/armGetSystemTickFreq())) /*Expression evaluating to current systime in ms*/ #endif /*LV_TICK_CUSTOM*/ typedef void * lv_disp_drv_user_data_t; /*Type of user data in the display driver*/ typedef void * lv_indev_drv_user_data_t; /*Type of user data in the input device driver*/ /*================ * Log settings *===============*/ /*1: Enable the log module*/ #define LV_USE_LOG 1 #if LV_USE_LOG /* How important log should be added: * LV_LOG_LEVEL_TRACE A lot of logs to give detailed information * LV_LOG_LEVEL_INFO Log important events * LV_LOG_LEVEL_WARN Log if something unwanted happened but didn't cause a problem * LV_LOG_LEVEL_ERROR Only critical issue, when the system may fail * LV_LOG_LEVEL_NONE Do not log anything */ # define LV_LOG_LEVEL LV_LOG_LEVEL_WARN /* 1: Print the log with 'printf'; * 0: user need to register a callback with `lv_log_register_print_cb`*/ # define LV_LOG_PRINTF 0 #endif /*LV_USE_LOG*/ /*================= * Debug settings *================*/ /* If Debug is enabled LittelvGL validates the parameters of the functions. * If an invalid parameter is found an error log message is printed and * the MCU halts at the error. (`LV_USE_LOG` should be enabled) * If you are debugging the MCU you can pause * the debugger to see exactly where the issue is. * * The behavior of asserts can be overwritten by redefining them here. * E.g. #define LV_ASSERT_MEM(p) <my_assert_code> */ #define LV_USE_DEBUG 1 #if LV_USE_DEBUG /*Check if the parameter is NULL. (Quite fast) */ #define LV_USE_ASSERT_NULL 1 /*Checks is the memory is successfully allocated or no. (Quite fast)*/ #define LV_USE_ASSERT_MEM 1 /*Check the integrity of `lv_mem` after critical operations. (Slow)*/ #define LV_USE_ASSERT_MEM_INTEGRITY 0 /* Check the strings. * Search for NULL, very long strings, invalid characters, and unnatural repetitions. (Slow) * If disabled `LV_USE_ASSERT_NULL` will be performed instead (if it's enabled) */ #define LV_USE_ASSERT_STR 0 /* Check NULL, the object's type and existence (e.g. not deleted). (Quite slow) * If disabled `LV_USE_ASSERT_NULL` will be performed instead (if it's enabled) */ #define LV_USE_ASSERT_OBJ 0 /*Check if the styles are properly initialized. (Fast)*/ #define LV_USE_ASSERT_STYLE 1 #endif /*LV_USE_DEBUG*/ /*================== * FONT USAGE *===================*/ /* The built-in fonts contains the ASCII range and some Symbols with 4 bit-per-pixel. * The symbols are available via `LV_SYMBOL_...` defines * More info about fonts: https://docs.lvgl.io/v7/en/html/overview/font.html * To create a new font go to: https://lvgl.com/ttf-font-to-c-array */ /* Montserrat fonts with bpp = 4 * https://fonts.google.com/specimen/Montserrat */ #define LV_FONT_MONTSERRAT_12 0 #define LV_FONT_MONTSERRAT_14 1 #define LV_FONT_MONTSERRAT_16 0 #define LV_FONT_MONTSERRAT_18 0 #define LV_FONT_MONTSERRAT_20 1 #define LV_FONT_MONTSERRAT_22 0 #define LV_FONT_MONTSERRAT_24 1 #define LV_FONT_MONTSERRAT_26 0 #define LV_FONT_MONTSERRAT_28 0 #define LV_FONT_MONTSERRAT_30 0 #define LV_FONT_MONTSERRAT_32 0 #define LV_FONT_MONTSERRAT_34 0 #define LV_FONT_MONTSERRAT_36 0 #define LV_FONT_MONTSERRAT_38 0 #define LV_FONT_MONTSERRAT_40 0 #define LV_FONT_MONTSERRAT_42 0 #define LV_FONT_MONTSERRAT_44 0 #define LV_FONT_MONTSERRAT_46 0 #define LV_FONT_MONTSERRAT_48 0 /* Demonstrate special features */ #define LV_FONT_MONTSERRAT_12_SUBPX 0 #define LV_FONT_MONTSERRAT_28_COMPRESSED 0 /*bpp = 3*/ #define LV_FONT_DEJAVU_16_PERSIAN_HEBREW 0 /*Hebrew, Arabic, PErisan letters and all their forms*/ #define LV_FONT_SIMSUN_16_CJK 0 /*1000 most common CJK radicals*/ /*Pixel perfect monospace font * http://pelulamu.net/unscii/ */ #define LV_FONT_UNSCII_8 0 /* Optionally declare your custom fonts here. * You can use these fonts as default font too * and they will be available globally. E.g. * #define LV_FONT_CUSTOM_DECLARE LV_FONT_DECLARE(my_font_1) \ * LV_FONT_DECLARE(my_font_2) */ #define LV_FONT_CUSTOM_DECLARE /*Always set a default font from the built-in fonts*/ #define LV_FONT_DEFAULT &lv_font_montserrat_20 /* Enable it if you have fonts with a lot of characters. * The limit depends on the font size, font face and bpp * but with > 10,000 characters if you see issues probably you need to enable it.*/ #define LV_FONT_FMT_TXT_LARGE 0 /* Set the pixel order of the display. * Important only if "subpx fonts" are used. * With "normal" font it doesn't matter. */ #define LV_FONT_SUBPX_BGR 0 /*Declare the type of the user data of fonts (can be e.g. `void *`, `int`, `struct`)*/ typedef void * lv_font_user_data_t; /*================ * THEME USAGE *================*/ /*Always enable at least on theme*/ /* No theme, you can apply your styles as you need * No flags. Set LV_THEME_DEFAULT_FLAG 0 */ #define LV_USE_THEME_EMPTY 0 /*Simple to the create your theme based on it * No flags. Set LV_THEME_DEFAULT_FLAG 0 */ #define LV_USE_THEME_TEMPLATE 0 /* A fast and impressive theme. * Flags: * LV_THEME_MATERIAL_FLAG_LIGHT: light theme * LV_THEME_MATERIAL_FLAG_DARK: dark theme*/ #define LV_USE_THEME_MATERIAL 1 /* Mono-color theme for monochrome displays. * If LV_THEME_DEFAULT_COLOR_PRIMARY is LV_COLOR_BLACK the * texts and borders will be black and the background will be * white. Else the colors are inverted. * No flags. Set LV_THEME_DEFAULT_FLAG 0 */ #define LV_USE_THEME_MONO 0 #define LV_THEME_DEFAULT_INCLUDE <stdint.h> /*Include a header for the init. function*/ #define LV_THEME_DEFAULT_INIT lv_theme_material_init #define LV_THEME_DEFAULT_COLOR_PRIMARY lv_color_hex(0xFFD600) #define LV_THEME_DEFAULT_COLOR_SECONDARY lv_color_hex(0x1976D2) #define LV_THEME_DEFAULT_FLAG LV_THEME_MATERIAL_FLAG_DARK #define LV_THEME_DEFAULT_FONT_SMALL LV_FONT_DEFAULT #define LV_THEME_DEFAULT_FONT_NORMAL LV_FONT_DEFAULT #define LV_THEME_DEFAULT_FONT_SUBTITLE LV_FONT_DEFAULT #define LV_THEME_DEFAULT_FONT_TITLE LV_FONT_DEFAULT /*================= * Text settings *=================*/ /* Select a character encoding for strings. * Your IDE or editor should have the same character encoding * - LV_TXT_ENC_UTF8 * - LV_TXT_ENC_ASCII * */ #define LV_TXT_ENC LV_TXT_ENC_UTF8 /*Can break (wrap) texts on these chars*/ #define LV_TXT_BREAK_CHARS " ,.;:-_" /* If a word is at least this long, will break wherever "prettiest" * To disable, set to a value <= 0 */ #define LV_TXT_LINE_BREAK_LONG_LEN 0 /* Minimum number of characters in a long word to put on a line before a break. * Depends on LV_TXT_LINE_BREAK_LONG_LEN. */ #define LV_TXT_LINE_BREAK_LONG_PRE_MIN_LEN 3 /* Minimum number of characters in a long word to put on a line after a break. * Depends on LV_TXT_LINE_BREAK_LONG_LEN. */ #define LV_TXT_LINE_BREAK_LONG_POST_MIN_LEN 3 /* The control character to use for signalling text recoloring. */ #define LV_TXT_COLOR_CMD "#" /* Support bidirectional texts. * Allows mixing Left-to-Right and Right-to-Left texts. * The direction will be processed according to the Unicode Bidirectioanl Algorithm: * https://www.w3.org/International/articles/inline-bidi-markup/uba-basics*/ #define LV_USE_BIDI 0 #if LV_USE_BIDI /* Set the default direction. Supported values: * `LV_BIDI_DIR_LTR` Left-to-Right * `LV_BIDI_DIR_RTL` Right-to-Left * `LV_BIDI_DIR_AUTO` detect texts base direction */ #define LV_BIDI_BASE_DIR_DEF LV_BIDI_DIR_AUTO #endif /* Enable Arabic/Persian processing * In these languages characters should be replaced with * an other form based on their position in the text */ #define LV_USE_ARABIC_PERSIAN_CHARS 0 /*Change the built in (v)snprintf functions*/ #define LV_SPRINTF_CUSTOM 0 #if LV_SPRINTF_CUSTOM # define LV_SPRINTF_INCLUDE <stdio.h> # define lv_snprintf snprintf # define lv_vsnprintf vsnprintf #else /*!LV_SPRINTF_CUSTOM*/ # define LV_SPRINTF_DISABLE_FLOAT 1 #endif /*LV_SPRINTF_CUSTOM*/ /*=================== * LV_OBJ SETTINGS *==================*/ #if LV_USE_USER_DATA /*Declare the type of the user data of object (can be e.g. `void *`, `int`, `struct`)*/ typedef void * lv_obj_user_data_t; /*Provide a function to free user data*/ #define LV_USE_USER_DATA_FREE 0 #if LV_USE_USER_DATA_FREE # define LV_USER_DATA_FREE_INCLUDE "something.h" /*Header for user data free function*/ /* Function prototype : void user_data_free(lv_obj_t * obj); */ # define LV_USER_DATA_FREE (user_data_free) /*Invoking for user data free function*/ #endif #endif /*1: enable `lv_obj_realign()` based on `lv_obj_align()` parameters*/ #define LV_USE_OBJ_REALIGN 1 /* Enable to make the object clickable on a larger area. * LV_EXT_CLICK_AREA_OFF or 0: Disable this feature * LV_EXT_CLICK_AREA_TINY: The extra area can be adjusted horizontally and vertically (0..255 px) * LV_EXT_CLICK_AREA_FULL: The extra area can be adjusted in all 4 directions (-32k..+32k px) */ #define LV_USE_EXT_CLICK_AREA LV_EXT_CLICK_AREA_TINY /*================== * LV OBJ X USAGE *================*/ /* * Documentation of the object types: https://docs.lvgl.com/#Object-types */ /*Arc (dependencies: -)*/ #define LV_USE_ARC 0 /*Bar (dependencies: -)*/ #define LV_USE_BAR 0 /*Button (dependencies: lv_cont*/ #define LV_USE_BTN 1 #if LV_USE_BTN != 0 /*Enable button-state animations - draw a circle on click (dependencies: LV_USE_ANIMATION)*/ # define LV_BTN_INK_EFFECT 0 #endif /*Button matrix (dependencies: -)*/ #define LV_USE_BTNMATRIX 1 /*Calendar (dependencies: -)*/ #define LV_USE_CALENDAR 0 /*Canvas (dependencies: lv_img)*/ #define LV_USE_CANVAS 0 /*Check box (dependencies: lv_btn, lv_label)*/ #define LV_USE_CHECKBOX 0 /*Chart (dependencies: -)*/ #define LV_USE_CHART 0 #if LV_USE_CHART # define LV_CHART_AXIS_TICK_LABEL_MAX_LEN 256 #endif /*Container (dependencies: -*/ #define LV_USE_CONT 1 /*Color picker (dependencies: -*/ #define LV_USE_CPICKER 0 /*Drop down list (dependencies: lv_page, lv_label, lv_symbol_def.h)*/ #define LV_USE_DROPDOWN 0 #if LV_USE_DROPDOWN != 0 /*Open and close default animation time [ms] (0: no animation)*/ # define LV_DROPDOWN_DEF_ANIM_TIME 200 #endif /*Gauge (dependencies:lv_bar, lv_linemeter)*/ #define LV_USE_GAUGE 0 /*Image (dependencies: lv_label*/ #define LV_USE_IMG 1 /*Image Button (dependencies: lv_btn*/ #define LV_USE_IMGBTN 0 #if LV_USE_IMGBTN /*1: The imgbtn requires left, mid and right parts and the width can be set freely*/ # define LV_IMGBTN_TILED 0 #endif /*Keyboard (dependencies: lv_btnm)*/ #define LV_USE_KEYBOARD 0 /*Label (dependencies: -*/ #define LV_USE_LABEL 1 #if LV_USE_LABEL != 0 /*Hor, or ver. scroll speed [px/sec] in 'LV_LABEL_LONG_ROLL/ROLL_CIRC' mode*/ # define LV_LABEL_DEF_SCROLL_SPEED 25 /* Waiting period at beginning/end of animation cycle */ # define LV_LABEL_WAIT_CHAR_COUNT 3 /*Enable selecting text of the label */ # define LV_LABEL_TEXT_SEL 0 /*Store extra some info in labels (12 bytes) to speed up drawing of very long texts*/ # define LV_LABEL_LONG_TXT_HINT 0 #endif /*LED (dependencies: -)*/ #define LV_USE_LED 0 #if LV_USE_LED # define LV_LED_BRIGHT_MIN 120 /*Minimal brightness*/ # define LV_LED_BRIGHT_MAX 255 /*Maximal brightness*/ #endif /*Line (dependencies: -*/ #define LV_USE_LINE 0 /*List (dependencies: lv_page, lv_btn, lv_label, (lv_img optionally for icons ))*/ #define LV_USE_LIST 1 #if LV_USE_LIST != 0 /*Default animation time of focusing to a list element [ms] (0: no animation) */ # define LV_LIST_DEF_ANIM_TIME 100 #endif /*Line meter (dependencies: *;)*/ #define LV_USE_LMETER 0 #if LV_USE_LINEMETER /* Draw line more precisely at cost of performance. * Useful if there are lot of lines any minor are visible * 0: No extra precision * 1: Some extra precision * 2: Best precision */ # define LV_LINEMETER_PRECISE 0 #endif /*Mask (dependencies: -)*/ #define LV_USE_OBJMASK 0 /*Message box (dependencies: lv_rect, lv_btnm, lv_label)*/ #define LV_USE_MSGBOX 0 /*Page (dependencies: lv_cont)*/ #define LV_USE_PAGE 1 #if LV_USE_PAGE != 0 /*Focus default animation time [ms] (0: no animation)*/ # define LV_PAGE_DEF_ANIM_TIME 400 #endif /*Preload (dependencies: lv_arc, lv_anim)*/ #define LV_USE_SPINNER 0 #if LV_USE_SPINNER != 0 # define LV_SPINNER_DEF_ARC_LENGTH 60 /*[deg]*/ # define LV_SPINNER_DEF_SPIN_TIME 1000 /*[ms]*/ # define LV_SPINNER_DEF_ANIM LV_SPINNER_TYPE_SPINNING_ARC #endif /*Roller (dependencies: lv_ddlist)*/ #define LV_USE_ROLLER 0 #if LV_USE_ROLLER != 0 /*Focus animation time [ms] (0: no animation)*/ # define LV_ROLLER_DEF_ANIM_TIME 200 /*Number of extra "pages" when the roller is infinite*/ # define LV_ROLLER_INF_PAGES 7 #endif /*Slider (dependencies: lv_bar)*/ #define LV_USE_SLIDER 0 /*Spinbox (dependencies: lv_ta)*/ #define LV_USE_SPINBOX 0 /*Switch (dependencies: lv_slider)*/ #define LV_USE_SWITCH 0 /*Text area (dependencies: lv_label, lv_page)*/ #define LV_USE_TEXTAREA 0 #if LV_USE_TEXTAREA != 0 # define LV_TEXTAREA_DEF_CURSOR_BLINK_TIME 400 /*ms*/ # define LV_TEXTAREA_DEF_PWD_SHOW_TIME 1500 /*ms*/ #endif /*Table (dependencies: lv_label)*/ #define LV_USE_TABLE 0 #if LV_USE_TABLE # define LV_TABLE_COL_MAX 12 #endif /*Tab (dependencies: lv_page, lv_btnm)*/ #define LV_USE_TABVIEW 0 # if LV_USE_TABVIEW != 0 /*Time of slide animation [ms] (0: no animation)*/ # define LV_TABVIEW_DEF_ANIM_TIME 300 #endif /*Tileview (dependencies: lv_page) */ #define LV_USE_TILEVIEW 0 #if LV_USE_TILEVIEW /*Time of slide animation [ms] (0: no animation)*/ # define LV_TILEVIEW_DEF_ANIM_TIME 300 #endif /*Window (dependencies: lv_cont, lv_btn, lv_label, lv_img, lv_page)*/ #define LV_USE_WIN 1 /*================== * Non-user section *==================*/ #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) /* Disable warnings for Visual Studio*/ # define _CRT_SECURE_NO_WARNINGS #endif /*--END OF LV_CONF_H--*/ /*Be sure every define has a default value*/ // #include "lvgl/src/lv_conf_checker.h" #endif /*LV_CONF_H*/ #endif /*End of "Content enable"*/
23,851
C++
.h
574
40.012195
156
0.686919
3096/luxray
34
7
2
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
1,536,021
lx_config.h
3096_luxray/source/lx_config.h
#pragma once #define INNER_HEAP_SIZE 0x300000 // docked params #define OVERLAY_BASE_WIDTH_DOCKED 320 #define OVERLAY_BASE_HEIGHT_DOCKED 384 #define OVERLAY_UPSCALE_DOCKED 1 #define OVERLAY_POS_X_DOCKED 0 #define OVERLAY_POS_Y_DOCKED OVERLAY_BASE_HEIGHT_DOCKED #define OVERLAY_FONT_DOCKED { .normal = &lv_font_montserrat_20, .small = &lv_font_montserrat_14 } // handheld params #define OVERLAY_BASE_WIDTH_HANDHELD 336 #define OVERLAY_BASE_HEIGHT_HANDHELD 384 #define OVERLAY_UPSCALE_HANDHELD 2 #define OVERLAY_POS_X_HANDHELD 0 #define OVERLAY_POS_Y_HANDHELD 0 #define OVERLAY_FONT_HANDHELD { .normal = &lv_font_montserrat_24, .small = &lv_font_montserrat_20 } // debug options // #define DEBUG_LOG_FILE #define DEBUG_NX_LINK
842
C++
.h
19
43
109
0.685435
3096/luxray
34
7
2
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,022
theme.hpp
3096_luxray/source/theme.hpp
#pragma once #include "lx/ui/lv_helper.hpp" namespace theme { void initialize(); auto createWindow(lv_obj_t* p_parent) -> lv_obj_t*; auto createBtnmatrix(lv_obj_t* p_parent) -> lv_obj_t*; } // namespace theme
215
C++
.h
7
29
54
0.724138
3096/luxray
34
7
2
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,023
system.hpp
3096_luxray/source/core/system.hpp
#pragma once namespace os { bool nifmInternetIsConnected(); bool setsysInternetTimeSyncIsOn(); } // namespace os
118
C++
.h
5
21.8
34
0.816514
3096/luxray
34
7
2
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,024
time.hpp
3096_luxray/source/core/time.hpp
#pragma once #include <time.h> #include <cstdint> #include <string> class TimeTaskHandler { private: // TODO: STEP_INTERVAL should be configurable/adaptive static constexpr float STEP_INTERVAL = 0.36; const uint64_t STEP_INTERVAL_TICKS; time_t m_curTime; struct tm m_resetTargetTm; // step days members int m_curDaysLeftToStep; int m_curStepDirection; bool m_isInStep; bool m_isAbortingStep; bool m_resetAfterStep; uint64_t m_lastStepTick; void setTime_(time_t time, bool updateResetTarget = true); public: TimeTaskHandler(); ~TimeTaskHandler(); void handleTask(); void startStepDaysTask(int8_t sign, int daysToStep, bool resetAfterStep); inline void stopStepDaysTask() { m_isAbortingStep = true; } inline bool isStepping() { return m_isInStep; } inline int daysLeftToStep() { return m_curDaysLeftToStep; } std::string getCurDateStr(); void setDayChange(int dayChange); void setTimeNTP(); void resetTime(); };
1,021
C++
.h
32
27.4375
77
0.720408
3096/luxray
34
7
2
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,026
time_screen.hpp
3096_luxray/source/screens/time_screen.hpp
#pragma once #include <memory> #include "../core/time.hpp" #include "lx/debug.hpp" #include "lx/ui/basic_screen_provider.hpp" #include "lx/ui/i_screen.hpp" class TimeScreen : public lx::ui::IScreen { LOGCONSTRUCTM; private: TimeScreen(); TimeScreen(const TimeScreen&) = delete; ~TimeScreen(); static TimeScreen s_instance; // consts static constexpr auto BUTTON_MATRIX_WIDTH = 300; static constexpr auto BUTTON_MATRIX_HEIGHT = 200; static constexpr const char* STRING_CUR_DATE = "Current Date:"; static constexpr const char* STRING_TARGET_CHANGE = "Target:"; static constexpr const char* STRING_STEPPING = "Remaining:"; static constexpr const char* STRING_DAYS = " days"; // clang-format off static constexpr const char* INITIAL_BUTTON_MAP[] = { "1", "2", "3", "Set", "+1", "\n", "4", "5", "6", "Step", "+2", "\n", "7", "8", "9", "NTP", "+3", "\n", "-", "0", "<-", "Return", "Reset", "" }; // clang-format on static constexpr const uint16_t STEP_MAP_IDX = 9; static constexpr const char* STRING_STEP = INITIAL_BUTTON_MAP[STEP_MAP_IDX]; static constexpr const char* STRING_STEP_CANCEL = "Cancel"; /* Button IDs: "1"= 0, "2"= 1, "3"= 2, "Set"= 3, "+1"= 4, "4"= 5, "5"= 6, "6"= 7, "Step"= 8, "+2"= 9, "7"= 10, "8"= 11, "9"= 12, "NTP"= 13, "+3"= 14, "-"= 15, "0"= 16, "<-"= 17, "Auto"= 18, "Reset"= 19 */ enum Button { BUTTON_SET = 3, BUTTON_PLUS_ONE = 4, BUTTON_STEP = 8, BUTTON_PLUS_TWO = 9, BUTTON_NTP = 13, BUTTON_PLUS_THREE = 14, BUTTON_NEGATIVE = 15, BUTTON_BACKSPACE = 17, BUTTON_AUTORESET = 18, BUTTON_RESET = 19 }; static constexpr int MAX_TARGET_CHANGE = 999999; // composition lx::ui::BasicScreenProvider m_basicScreen; // ui std::unique_ptr<TimeTaskHandler> mp_timeTaskHandler; lv_obj_t* mp_promptLabel; lv_obj_t* mp_valueLabel; lv_obj_t* mp_buttonMatrix; const char* m_buttonMap[24]; // flags bool m_doAutoReset; bool m_isInStepDays; bool m_isAlreadyNTP; bool m_disableNTP; bool m_internetIsConnected; // values int m_curTargetChange; int8_t m_curTargetSign; std::string m_promptLabelStr; std::string m_valueLabelStr; // helpers void handleButtonEventImpl_(); static void handleButtonEvent_(lv_obj_t* obj, lv_event_t event); void handleStepDaysStart_(int8_t stepDirection, int daysToStep); void handleStepDaysEnd_(); void updateLabels_(); // interface virtual void renderScreen() override; virtual void procFrame() override; virtual inline lv_obj_t* getLvScreenObj() override { return m_basicScreen.getLvScreenObj(); } virtual inline lv_group_t* getLvInputGroup() override { return m_basicScreen.getLvInputGroup(); } public: static inline TimeScreen& getInstance() { return s_instance; } };
3,020
C++
.h
83
30.73494
101
0.620678
3096/luxray
34
7
2
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,027
main_screen.hpp
3096_luxray/source/screens/main_screen.hpp
#pragma once #include "lx/debug.hpp" #include "lx/ui/basic_screen_provider.hpp" class MainScreen : public lx::ui::IScreen { LOGCONSTRUCTM; private: MainScreen(); MainScreen(const MainScreen&) = delete; ~MainScreen(); static MainScreen s_instance; enum SubScreen { TIME_SCREEN = 0, NO_SUB_SCREEN }; lv_obj_t* mp_screenListObj; SubScreen m_screenToShow; bool m_shouldExit; lx::ui::BasicScreenProvider m_basicScreen; virtual void renderScreen() override; virtual void procFrame() override; virtual inline lv_obj_t* getLvScreenObj() override { return m_basicScreen.getLvScreenObj(); } virtual inline lv_group_t* getLvInputGroup() override { return m_basicScreen.getLvInputGroup(); } // helpers void showScreen_(lx::ui::IScreen& screenToShow); void handleShowScreen_(lv_event_t event, SubScreen screenToShow); // callbacks static void handleShowTimeScreen_(lv_obj_t* obj, lv_event_t event) { s_instance.handleShowScreen_(event, TIME_SCREEN); } static void handleExit_(lv_obj_t* obj, lv_event_t event); public: static inline MainScreen& getInstance() { return s_instance; } };
1,185
C++
.h
30
34.7
101
0.71741
3096/luxray
34
7
2
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,536,028
time_error_screen.hpp
3096_luxray/source/screens/time_error_screen.hpp
#pragma once #include "lx/ui/basic_screen_provider.hpp" #include "lx/ui/i_screen.hpp" class TimeErrorScreen : public lx::ui::IScreen { private: TimeErrorScreen(); TimeErrorScreen(const TimeErrorScreen&) = delete; ~TimeErrorScreen(); static TimeErrorScreen s_instance; lx::ui::BasicScreenProvider m_basicScreen; lv_obj_t* mp_errorMsgLabel; virtual void renderScreen() override; virtual void procFrame() override; virtual inline lv_obj_t* getLvScreenObj() override { return m_basicScreen.getLvScreenObj(); } virtual inline lv_group_t* getLvInputGroup() override { return m_basicScreen.getLvInputGroup(); } public: static inline TimeErrorScreen& getInstance() { return s_instance; } };
739
C++
.h
18
36.944444
101
0.745455
3096/luxray
34
7
2
GPL-3.0
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false