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,541,424
JsonReader.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/streams/concrete/readers/JsonReader.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_STREAMS_TEXT_READER_HPP #define BS_IO_STREAMS_TEXT_READER_HPP #include <bs/io/streams/primitive/Reader.hpp> #include <bs/io/utils/synthetic-generators/interface/MetaDataGenerator.hpp> #include <bs/io/utils/synthetic-generators/interface/ReflectorDataGenerator.hpp> namespace bs { namespace io { namespace streams { /** * @brief */ class JsonReader : public Reader { public: /** * @brief Constructor */ explicit JsonReader(bs::base::configurations::ConfigurationMap *apConfigurationMap); /** * @brief Default destructor. */ ~JsonReader() override; void AcquireConfiguration() override; std::string GetExtension() override; int Initialize(std::vector<std::string> &aGatherKeys, std::vector<std::pair<std::string, dataunits::Gather::SortDirection>> &aSortingKeys, std::vector<std::string> &aPaths) override; int Initialize(std::vector<dataunits::TraceHeaderKey> &aGatherKeys, std::vector<std::pair<dataunits::TraceHeaderKey, dataunits::Gather::SortDirection>> &aSortingKeys, std::vector<std::string> &aPaths) override; int Finalize() override; void SetHeaderOnlyMode(bool aEnableHeaderOnly) override; unsigned int GetNumberOfGathers() override; std::vector<std::vector<std::string>> GetIdentifiers() override; std::vector<dataunits::Gather *> ReadAll() override; std::vector<dataunits::Gather *> Read(std::vector<std::vector<std::string>> aHeaderValues) override; io::dataunits::Gather * Read(std::vector<std::string> aHeaderValues) override; io::dataunits::Gather * Read(unsigned int aIndex) override; private: /** * @brief * Generate the different generators and components used for the generation of data. */ void GenerateComponents(); /** * @brief * Fill the traces of a given gather with actual data. * * @param[in] aGathers * List of gathers to fill with data. */ void FillTraceData(std::vector<io::dataunits::Gather *> &aGathers); private: /// Files path std::string mFilePath; /// mGatherKeys: vector of keys to gather on std::vector<dataunits::TraceHeaderKey> mGatherKeys; /// mSortingKeys: Keys to sort gathers on, and sorting direction of each key /// Optional to have file(s) gathers sorted std::vector<std::pair<dataunits::TraceHeaderKey, dataunits::Gather::SortDirection>> mSortingKeys; /// Enable header only mode boolean bool mEnableHeaderOnly; /// The meta data generator. io::generators::MetaDataGenerator *mpMetaGenerator; /// The reflector generators. std::vector<io::generators::ReflectorDataGenerator *> mReflectorGenerators; }; } //streams } //thoth } //namespace bs #endif //BS_IO_STREAMS_TEXT_READER_HPP
4,450
C++
.h
99
31.89899
125
0.57321
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,425
InStreamHelper.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/streams/helpers/InStreamHelper.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_STREAMS_HELPERS_IN_FILE_HELPER_HPP #define BS_IO_STREAMS_HELPERS_IN_FILE_HELPER_HPP #include <fstream> #include <cstring> #include <bs/io/data-units/concrete/Trace.hpp> #include <bs/io/data-units/concrete/Gather.hpp> #include <bs/io/lookups/tables/TextHeaderLookup.hpp> #include <bs/io/lookups/tables/TraceHeaderLookup.hpp> #include <bs/io/lookups/tables/BinaryHeaderLookup.hpp> namespace bs { namespace io { namespace streams { namespace helpers { /** * @brief File helper to take any stream and helps manipulate or get any regarded * meta data from it. */ class InStreamHelper { public: /** * @brief Explicit constructor. * @param[in] aFilePath */ explicit InStreamHelper(std::string &aFilePath); /** * @brief Destructor. */ ~InStreamHelper(); /** * @brief Opens stream for the file regarded. * @return File size. */ size_t Open(); /** * @brief Release all resources and close everything. */ int Close(); /** * @brief Gets file size for a given file path. * @return size_t */ size_t GetFileSize(); /** * @brief Get current position for a given file path. * @return size_t */ size_t GetCurrentPosition(); /** * @brief Reads a block of bytes from current stream. * * @param[in] aStartPosition * @param[in] aBlockSize * @return unsigned char * */ unsigned char * ReadBytesBlock(size_t aStartPosition, size_t aBlockSize); /** * @brief Reads a text header, be it the original text header or the extended text header * from a given SEG-Y file, by passing the start byte position of it. * * @param[in] aStartPosition * @return unsigned char * */ unsigned char * ReadTextHeader(size_t aStartPosition); /** * @brief Reads a binary header from a given SEG-Y file, by passing the start byte position of it. * @param[in] aStartPosition * @return BinaryHeaderLookup */ lookups::BinaryHeaderLookup ReadBinaryHeader(size_t aStartPosition); /** * @brief Reads a trace header from a given SEG-Y file, by passing the start byte position of it. * @param[in] aStartPosition * @return TraceHeaderLookup */ lookups::TraceHeaderLookup ReadTraceHeader(size_t aStartPosition); /** * @brief Reads a single trace from a given SEG-Y file, by passing the start byte position * of the desired trace, the trace header for allocation purposes and the binary header for * data formats purposes. * * @param[in] aStartPosition * @param[in] aTraceHeaderLookup * @param[in] aBinaryHeaderLookup * @return Trace * */ dataunits::Trace * ReadFormattedTraceData(size_t aStartPosition, io::lookups::TraceHeaderLookup &aTraceHeaderLookup, io::lookups::BinaryHeaderLookup &aBinaryHeaderLookup); public: /** * @brief Gets trace data size given its header and binary header to * determine whether to take NS or BHS and deduce data format. * * @param[in] aTraceHeaderLookup * @param[in] aBinaryHeaderLookup * @return */ static size_t GetTraceDataSize(const io::lookups::TraceHeaderLookup &aTraceHeaderLookup, const io::lookups::BinaryHeaderLookup &aBinaryHeaderLookup); /** * @brief Gets samples number in a trace given its header and binary header to * determine whether to take NS or BHS. * * @param[in] aTraceHeaderLookup * @param[in] aBinaryHeaderLookup * @return */ static size_t GetSamplesNumber(const lookups::TraceHeaderLookup &aTraceHeaderLookup, const lookups::BinaryHeaderLookup &aBinaryHeaderLookup); private: /// File path. std::string mFilePath; /// File input stream. std::ifstream mInStream; /// File size. size_t mFileSize; }; } //namespace helpers } //namespace streams } //namespace io } //namespace bs #endif //BS_IO_STREAMS_HELPERS_IN_FILE_HELPER_HPP
6,748
C++
.h
151
27.192053
118
0.486544
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,426
OutStreamHelper.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/streams/helpers/OutStreamHelper.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_STREAMS_HELPERS_OUT_FILE_HELPER_HPP #define BS_IO_STREAMS_HELPERS_OUT_FILE_HELPER_HPP #include <fstream> namespace bs { namespace io { namespace streams { namespace helpers { /** * @brief File helper to take any stream and helps manipulate or write any regarded * data to it. */ class OutStreamHelper { public: /** * @brief Explicit constructor. * @param[in] aFilePath */ explicit OutStreamHelper(std::string &aFilePath, bool aModify = false); /** * @brief Destructor. */ ~OutStreamHelper(); /** * @brief Opens stream for the file regarded. * @return File size. */ size_t Open(); /** * @brief Release all resources and close everything. */ int Close(); /** * @brief Gets file size for a given file path. * @return size_t */ size_t GetFileSize(); /** * @brief Writes a block of bytes in current stream. * * @param[in] aData * @param[in] aStartPosition * @param[in] aBlockSize * @return Status flag. */ size_t WriteBytesBlock(const char *aData, size_t aBlockSize); /** * @brief * Writes a block of bytes in current stream. * * @param[in] aData * The data to write into the file. * * @param[in] aBlockSize * The size of the data to write. * * @param[in] aStartingPosition * The starting position in the file to write to. * * @return Status flag. * The appropriate exit code. */ size_t WriteBytesBlock(const char *aData, size_t aBlockSize, size_t aStartingPosition); private: /// File path. std::string mFilePath; /// File output stream. std::ofstream mOutStream; /// File size. size_t mFileSize; /// Modify file if true or overwrite. bool mModify; }; } //namespace helpers } //namespace streams } //namespace io } //namespace bs #endif //BS_IO_STREAMS_HELPERS_OUT_FILE_HELPER_HPP
3,928
C++
.h
101
22.841584
99
0.456476
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,427
Stream.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/streams/interface/Stream.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_STREAMS_STREAM_HPP #define BS_IO_STREAMS_STREAM_HPP #include <string> #include <bs/base/configurations/interface/Configurable.hpp> namespace bs { namespace io { namespace streams { /** * @brief */ class Stream : public bs::base::configurations::Configurable { public: /** * @brief Destructor */ ~Stream() override = default; /** * @brief Returns the file format extension of the current stream. */ virtual std::string GetExtension() = 0; protected: /// Configurations Map bs::base::configurations::ConfigurationMap *mpConfigurationMap; }; } //streams } //thoth } //namespace bs #endif //BS_IO_STREAMS_STREAM_HPP
1,642
C++
.h
46
28.195652
82
0.625945
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,428
Writer.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/streams/primitive/Writer.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_STREAMS_WRITER_HPP #define BS_IO_STREAMS_WRITER_HPP #include <unordered_map> #include <vector> #include <bs/base/configurations/interface/Configurable.hpp> #include <bs/io/streams/interface/Stream.hpp> #include <bs/io/data-units/concrete/Trace.hpp> #include <bs/io/data-units/concrete/Gather.hpp> #include <bs/io/data-units/data-types/TraceHeaderKey.hpp> namespace bs { namespace io { namespace streams { /** * @brief * Writer interface for seismic data. * This should be configurable to allow each reader to extract its unique additional properties. * A simple flow should be like the following: * Writer.AcquireConfiguration(...); * Writer.Initialize(...); * Do all other operations afterwards. */ class Writer : public Stream { public: /** * @brief * Virtual destructor to allow correct destruction of concrete classes. */ virtual ~Writer() = default; /** * @brief * Initializes the writer with the appropriate settings applied * to the writer, and any preparations needed are done. * Should be called once at the start. * * @param[in] aFilePath * The path to be used, either directly or as a seed, for writing. */ virtual int Initialize(std::string &aFilePath) = 0; /** * @brief * Does any final updates needed for consistency of the writer. * Release all resources and close everything. * Should be initialized again afterwards to be able to reuse it again. */ virtual int Finalize() = 0; /** * @brief * Writes a group of gathers to the output stream of the writer. * * @param[in] aGathers * List of gathers to be written. * * @return * An error flag, if 0 that means operation was successful, otherwise indicate an error. */ virtual int Write(std::vector<dataunits::Gather *> aGathers) = 0; /** * @brief * Writes a gather to the output stream of the writer. * * @param[in] aGather * The gather to be written. * * @return * An error flag, if 0 that means operation was successful, otherwise indicate an error. */ virtual int Write(io::dataunits::Gather *aGather) = 0; }; } //namespace streams } //namespace io } //namespace bs #endif //BS_IO_STREAMS_WRITER_HPP
3,803
C++
.h
94
28.755319
108
0.559221
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,429
Reader.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/streams/primitive/Reader.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_STREAMS_READER_HPP #define BS_IO_STREAMS_READER_HPP #include <unordered_map> #include <vector> #include <bs/base/configurations/interface/Configurable.hpp> #include <bs/io/streams/interface/Stream.hpp> #include <bs/io/data-units/concrete/Trace.hpp> #include <bs/io/data-units/concrete/Gather.hpp> #include <bs/io/data-units/data-types/TraceHeaderKey.hpp> namespace bs { namespace io { namespace streams { /** * @brief * Reader interface for seismic data. * This should be configurable to allow each reader to extract its unique additional properties. * A simple flow should be like the following: * Reader.AcquireConfiguration(...); * Reader.Initialize(...); * Do all other operations afterwards. */ class Reader : public Stream { public: /** * @brief * Virtual destructor to allow correct destruction of concrete classes. */ virtual ~Reader() override = default; /** * @brief * Initializes the reader with the appropriate settings applied * to the reader, and any preparations needed are done. * Should be called once at the start. * * @param[in] aGatherKeys * A vector containing the strings of the headers to utilize as the gathers in reading. * If provided an empty vector, will not gather on any key and will return all data. * * @param[in] aSortingKeys * A vector of pairs with each pair containing a string representing the header to sort on, and the sorting direction. * The vector is treated with the first element being the most major decider, and the last the most minor one. * If empty, no sorting is applied. * * @param[in] aPaths * List of paths to be processed by the the reader. */ virtual int Initialize(std::vector<std::string> &aGatherKeys, std::vector<std::pair<std::string, dataunits::Gather::SortDirection>> &aSortingKeys, std::vector<std::string> &aPaths) = 0; /** * @brief * Initializes the reader with the appropriate settings applied * to the reader, and any preparations needed are done. * Should be called once at the start. * * @param[in] aGatherKeys * A vector containing the trace header keys of the headers to utilize as the gathers in reading. * If provided an empty vector, will not gather on any key and will return all data. * * @param[in] aSortingKeys * A vector of pairs with each pair containing a string representing the header to sort on, and the sorting direction. * The vector is treated with the first element being the most major decider, and the last the most minor one. * If empty, no sorting is applied. * * @param[in] aPaths * List of paths to be processed by the the reader. */ virtual int Initialize(std::vector<dataunits::TraceHeaderKey> &aGatherKeys, std::vector<std::pair<dataunits::TraceHeaderKey, dataunits::Gather::SortDirection>> &aSortingKeys, std::vector<std::string> &aPaths) = 0; /** * @brief * Release all resources and close everything. * Should be initialized again afterwards to be able to reuse it again. */ virtual int Finalize() = 0; /** * @brief * Sets the reader to only read and set the headers in the gather read functionalities. * This will reduce the time needed, however won't populate the data in the traces at all. * You should be able to enable and disable as you want during the runs. * By default, this mode is considered false unless explicitly called and set. * * @param[in] aEnableHeaderOnly * If true, make all gather read functions read and set the headers only. * If false, will make all gather read functions read headers and data. */ virtual void SetHeaderOnlyMode(bool aEnableHeaderOnly) = 0; /** * @brief * Return the total number of gathers available for reading. * * @return * An unsigned int representing how many unique gathers are available for the reader. */ virtual unsigned int GetNumberOfGathers() = 0; /** * @brief * Get the unique values of gathers available to be read. * * @return * A list of sub-lists. * Each sublist represent one gather unique value combination. * The sublist length is equal to the number of keys that the reader is set to gather on. * The list length is equal to the value returned by GetNumberOfGathers(). * The order of values in the sublist matches the same order given in the initialize. */ virtual std::vector<std::vector<std::string>> GetIdentifiers() = 0; /** * @brief * Get all the gathers that can be read by the reader. * * @return * A vector of all possible gathers. * The gather pointers returned should be deleted by the user to avoid memory leaks. */ virtual std::vector<dataunits::Gather *> ReadAll() = 0; /** * @brief * Get a group of gathers with the requested unique values. * * @param[in] aHeaderValues * Each sublist represent one gather unique value combination. * The sublist length is equal to the number of keys that the reader is set to gather on. * The order of values in the sublist matches the same order given in the initialize. * * @return * A vector of the gathers matching the given request. * The gather pointers returned should be deleted by the user to avoid memory leaks. */ virtual std::vector<dataunits::Gather *> Read(std::vector<std::vector<std::string>> aHeaderValues) = 0; /** * @brief * Get a group of gathers with the requested unique values. * * @param[in] aHeaderValues * Each list represent one gather unique value combination. * The list length is equal to the number of keys that the reader is set to gather on. * The order of values in the list matches the same order given in the initialize. * * @return * The gather matching the given request. * The gather pointer returned should be deleted by the user to avoid memory leaks. */ virtual io::dataunits::Gather * Read(std::vector<std::string> aHeaderValues) = 0; /** * @brief * Get a gather by its index. * * @param[in] aIndex * The index of the gather to be read. Must be between 0 and * the number returned by GetNumberOfGathers(). * It should return the gather with the unique value equivalent to * the entry of GetUniqueGatherValues() at index aIndex. * * @return * The requested gather if possible, nullptr otherwise. * The gather pointer returned should be deleted by the user to avoid memory leaks. */ virtual io::dataunits::Gather * Read(unsigned int aIndex) = 0; }; } //streams } //thoth } //namespace bs #endif //BS_IO_STREAMS_READER_HPP
9,623
C++
.h
193
34.782383
134
0.55094
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,430
TraceHeaderKey.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/data-units/data-types/TraceHeaderKey.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_DATA_UNITS_DATA_TYPES_TRACE_HEADER_HPP #define BS_IO_DATA_UNITS_DATA_TYPES_TRACE_HEADER_HPP #include <string> #include <unordered_map> #include <map> #include <cctype> #include <cstring> #include <cstdio> #include <vector> #include <sstream> namespace bs { namespace io { namespace dataunits { /** * @brief Trace Header */ class TraceHeaderKey { public: /** * @brief Enum with the different Trace Headers. */ enum Key : char { TRACL, TRACR, FLDR, TRACF, EP, CDP, CDPT, TRACE_CODE, NVS, NHS, DUSE, OFFSET, GELEV, SELEV, SDEPTH, GDEL, SDEL, SWDEP, GWDEP, SCALEL, SCALCO, SX, SY, GX, GY, COINTIT, WEVEL, SWEVEL, SUT, GUT, SSTAT, GSTAT, TSTAT, LAGA, LAGB, DELRT, MUTS, MUTE, NS, DT, GAIN, IGC, IGI, CORR, SFS, SFE, SLEN, STYP, STAS, STAE, TATYP, AFILF, AFILS, NOFILF, NOFILS, LCF, HCF, LCS, HCS, YEAR, DAY, HOUR, MINUTE, SEC, TIMBAS, TRWF, GRNORS, GRNOFR, GRNLOF, GAPS, OTRAV, /* EXTENDED. */ ENSX, ENSY, INLINE, CROSS, SHOOTPOINT, SHOOTPOINT_SCALE, TRACE_UNIT, TRANSD_CONST, TRANSD_UNIT, TRID, SCALE_TIME, SRC_ORIENT, SRC_DIRECTION, SRC_MEASUREMT, SRC_UNIT, UNASSIGNED1, D1, F1, D2, F2, UNGPOW, UNSCALE, NTR, MARK, SHORTPAD, /** INTERNALLY USED TRACE HEADERS **/ SYN_X_IND, SYN_Y_IND, DATA_BYTE_OFFSET, }; public: /** * @brief Trace Header constructor. */ TraceHeaderKey(Key aKey) { this->mKey = aKey; } /** * @brief Copy constructor, to copy char representing one of the enum to the class. * * @param[in] aType * The char mValue representing one of the enums. */ explicit constexpr TraceHeaderKey(char aValue) : mKey(static_cast<TraceHeaderKey::Key>(aValue)) {} /** * @brief Trace Header Destructor. */ ~TraceHeaderKey() = default; Key GetKey() const { return mKey; } /** * @brief Equality operator overloading. * * @param[in] aType * Comparison target. * * @return True if they contain the same type. */ constexpr bool operator==(TraceHeaderKey aTraceHeaderAttribute) const { return this->mKey == aTraceHeaderAttribute.mKey; } /** * @brief Inequality operator overloading. * * @param[in] aTraceHeaderAttribute * Comparison target. * * @return True if they do not contain the same type. */ constexpr bool operator!=(TraceHeaderKey aTraceHeaderAttribute) const { return this->mKey != aTraceHeaderAttribute.mKey; } /** * @brief Greater equality operator overloading. * * @param[in] aTraceHeaderAttribute * Comparison target. * * @return True if aTraceHeaderAttribute is greater than current object. */ constexpr bool operator>(TraceHeaderKey aTraceHeaderAttribute) const { return this->mKey > aTraceHeaderAttribute.mKey; } /** * @brief Smaller equality operator overloading. * * @param[in] aTraceHeaderAttribute * Comparison target. * * @return True if aTraceHeaderAttribute is smaller than current object. */ constexpr bool operator<(TraceHeaderKey aTraceHeaderAttribute) const { return this->mKey < aTraceHeaderAttribute.mKey; } /** * @brief Allow switch and comparisons. * @return The enum mValue. */ explicit operator Key() const { return this->mKey; } // Allow switch and comparisons. /** * @brief Prevent usage of if (aTraceHeaderAttribute) * @return Nothing as it's deleted. */ explicit operator bool() = delete; static std::string GatherKeysToString(const std::vector<TraceHeaderKey> &aGatherKeys) { std::string key; for (const auto &it : aGatherKeys) { key += it.ToString() + "_"; } return key; } static std::string GatherValuesToString(const std::vector<std::string> &aGatherValues) { std::string values; for (const auto &it : aGatherValues) { values += it + "_"; } return values; } static std::vector<std::string> StringToGatherValues(const std::string &aKey) { std::vector<std::string> values; std::stringstream check1(aKey); std::string temp; while (getline(check1, temp, '_')) { values.push_back(temp); } return values; } /** * @brief Convert trace header to string. * @return A string representation of the trace header. */ std::string ToString() const { static const std::unordered_map<TraceHeaderKey::Key, std::string> ENUM_TO_STRING = { {TRACL, "TRACL"}, {TRACR, "TRACR"}, {FLDR, "FLDR"}, {TRACF, "TRACF"}, {EP, "EP"}, {CDP, "CDP"}, {CDPT, "CDPT"}, {NVS, "NVS"}, {NHS, "NHS"}, {DUSE, "DUSE"}, {OFFSET, "OFFSET"}, {GELEV, "GELEV"}, {SELEV, "SELEV"}, {SDEPTH, "SDEPTH"}, {GDEL, "GDEL"}, {SDEL, "SDEL"}, {SWDEP, "SWDEP"}, {GWDEP, "DWDEP"}, {SCALEL, "SCALEL"}, {SCALCO, "SCALCO"}, {SX, "SX"}, {SY, "SY"}, {GX, "GX"}, {GY, "GY"}, {COINTIT, "COINTIT"}, {WEVEL, "WEVEL"}, {SWEVEL, "SWEVEL"}, {SUT, "SUT"}, {GUT, "GUT"}, {SSTAT, "SSTAT"}, {GSTAT, "GSTAT"}, {TSTAT, "TSTAT"}, {LAGA, "LAGA"}, {LAGB, "LAGB"}, {DELRT, "DELRT"}, {MUTS, "MUTS"}, {MUTE, "MUTE"}, {NS, "NS"}, {DT, "DT"}, {GAIN, "GAIN"}, {IGC, "IGC"}, {IGI, "IGI"}, {CORR, "CORR"}, {SFS, "SFS"}, {SFE, "SFE"}, {SLEN, "SLEN"}, {STYP, "STYP"}, {STAS, "STAS"}, {STAE, "STAE"}, {TATYP, "TATYP"}, {AFILF, "AFILF"}, {AFILS, "AFILS"}, {NOFILF, "NOFILF"}, {NOFILS, "NOFILS"}, {LCF, "LCF"}, {HCF, "HCF"}, {LCS, "LCS"}, {HCS, "HCS"}, {YEAR, "YEAR"}, {DAY, "DAY"}, {HOUR, "HOUR"}, {MINUTE, "MINUTE"}, {SEC, "SEC"}, {TIMBAS, "TIMBAS"}, {TRWF, "TRWF"}, {GRNORS, "GRNORS"}, {GRNOFR, "GRNOFR"}, {GRNLOF, "GRNLOF"}, {GAPS, "GAPS"}, {OTRAV, "OTRAV"}, /* EXTENDED. */ {ENSX, "ENSX"}, {ENSY, "ENSY"}, {INLINE, "INLINE"}, {CROSS, "CROSS"}, {SHOOTPOINT, "SHOOTPOINT"}, {SHOOTPOINT_SCALE, "SHOOTPOINT_SCALE"}, {TRACE_UNIT, "TRACE_UNIT"}, {TRANSD_CONST, "TRANSD_CONST"}, {TRANSD_UNIT, "TRANSD_UNIT"}, {TRID, "TRID"}, {SCALE_TIME, "SCALE_TIME"}, {SRC_ORIENT, "SRC_ORIENT"}, {SRC_DIRECTION, "SRC_DIRECTION"}, {SRC_MEASUREMT, "SRC_MEASUREMT"}, {SRC_UNIT, "SRC_UNIT"}, {UNASSIGNED1, "UNASSIGNED1"}, {DATA_BYTE_OFFSET, "DATA_BYTE_OFFSET"} }; return ENUM_TO_STRING.find(this->mKey)->second; } /** * @brief Convert trace header type to char. * @return A char representation of the trace header. */ inline char ToChar() const { return this->mKey; } /** * @brief Provides the hash for TraceHeaderKey object. * * @return A hash representation of this object. */ size_t hash() const { return std::hash<Key>()(this->mKey); } private: /// @brief Key for trace header. /// @see {TraceHeaderKey::Key} Key mKey; }; }//namespace dataunits } //namespace io } //namespace bs namespace std { /** * @brief The hash function used by the STL containers for TraceHeaderKey class. */ template<> struct hash<bs::io::dataunits::TraceHeaderKey> { std::size_t operator()(const bs::io::dataunits::TraceHeaderKey &f) const { return f.hash(); } }; } //namespace std #endif //BS_IO_DATA_UNITS_DATA_TYPES_TRACE_HEADER_HPP
15,035
C++
.h
371
20.827493
104
0.336431
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,431
Gather.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/data-units/concrete/Gather.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_DATA_UNITS_GATHER_HPP #define BS_IO_DATA_UNITS_GATHER_HPP #include <vector> #include <utility> #include <unordered_map> #include <algorithm> #include <bs/base/common/assertions.h> #include <bs/io/data-units/concrete/Trace.hpp> #include <bs/io/data-units/data-types/TraceHeaderKey.hpp> namespace bs { namespace io { namespace dataunits { /** * @brief */ class Gather { public: /** * @brief Sorting Direction enum. Either ascending or descending. */ enum SortDirection : char { ASC, DES }; public: explicit Gather(); /** * @brief Constructor. * * @param[in] TraceHeaderKey * map (key value pairs) gathered on, and vector of gather traces. */ explicit Gather(std::unordered_map<TraceHeaderKey, std::string> &aUniqueKeys, const std::vector<Trace *> &aTraces); /** * * @brief Constructor. * * @param[in] aUniqueKey * Unique Key gathered on, its value, and vector of gather traces. * */ explicit Gather(TraceHeaderKey aUniqueKey, const std::string &aUniqueKeyValue, const std::vector<Trace *> &aTraces); /** * * @brief Constructor. * * @param aUniqueKeys map. * */ explicit Gather(std::unordered_map<TraceHeaderKey, std::string> &aUniqueKeys); /** * @brief Destructor. */ ~Gather() = default; /** *@brief Unique Key value getter. * * @param aTraceHeaderKey. */ template<typename T> inline T GetUniqueKeyValue(TraceHeaderKey aTraceHeaderKey) { ASSERT_T_TEMPLATE(T); std::stringstream ss; ss << this->mUniqueKeys[aTraceHeaderKey]; T unique_trace_header_value; ss >> unique_trace_header_value; return unique_trace_header_value; } /** * @brief Unique Key value setter. * * @param[in] aTraceHeaderKey * @param[in] aTraceHeaderKeyValue. */ inline void SetUniqueKeyValue(TraceHeaderKey aTraceHeaderKey, std::string &aTraceHeaderKeyValue) { this->mUniqueKeys[aTraceHeaderKey] = aTraceHeaderKeyValue; } /** * @brief AddTrace function, adds a trace to gather traces. * * @param[in] apTrace. */ inline void AddTrace(Trace *apTrace) { this->mTraces.push_back(apTrace); } /** * @brief AddTrace function, adds a trace to gather traces. * * @param[in] aTrace. */ inline void AddTrace(const std::vector<Trace *> &aTraceVector) { for (auto const trace : aTraceVector) { this->mTraces.push_back(trace); } } /** * @brief GetNumberTraces function, gets the number of traces in a gather. * * @return Number of traces in a gather. */ inline size_t GetNumberTraces() { return this->mTraces.size(); } /** * @brief GetTrace function, gets a trace at a given index. * * @param[in] aTraceIdx. * * @return Trace at the given index. */ inline Trace * GetTrace(unsigned int aTraceIdx) { return this->mTraces.at(aTraceIdx); } /** * @brief Gets all traces in the gather internal vector. * * @return All traces in the gather internal vector. */ inline std::vector<Trace *> GetAllTraces() { return this->mTraces; } /** * @brief RemoveTrace function, removes a trace at a given index. * * @param[in] aTraceIdx. */ inline void RemoveTrace(unsigned int aTraceIdx) { delete this->mTraces[aTraceIdx]; this->mTraces.erase(this->mTraces.begin() + aTraceIdx); } /** * @brief Sort Gather function, using custom compare function. */ void SortGather(const std::vector<std::pair<TraceHeaderKey, Gather::SortDirection>> &aSortingKeys); /** * @brief * Set the sampling rate of the gather. * * @param[in] aSamplingRate * A floating number indicating the sampling rate between each sample. * Microseconds (μs) for time data, Hertz (Hz) for frequency data, * meters (m) or feet (ft) for depth data */ void SetSamplingRate(float aSamplingRate) { this->mSamplingRate = aSamplingRate; } /** * @brief * Get the sampling rate for the traces. * * @return * A floating number indicating the sampling rate between each sample. * Microseconds (μs) for time data, Hertz (Hz) for frequency data, * meters (m) or feet (ft) for depth data */ inline float GetSamplingRate() const { return this->mSamplingRate; } private: /// Unique Key-Value map. std::unordered_map<TraceHeaderKey, std::string> mUniqueKeys; /// Traces container. std::vector<Trace *> mTraces; /// The sampling rate for the traces in the gather. float mSamplingRate; }; }//namespace dataunits } //namespace io namespace io { namespace dataunits { /** * @brief Sorting compare trace struct. Used to send parameters to the compare function. */ struct trace_compare_t { /** * @brief Constructor. * * @param[in] aSortingKeys * Sorting keys vector and Sorting Direction enum * either ASC or DESC */ explicit trace_compare_t( const std::vector<std::pair<TraceHeaderKey, Gather::SortDirection>> &aSortingKeys); bool operator()(Trace *aTrace_1, Trace *aTrace_2) const; private: std::vector<std::pair<TraceHeaderKey, Gather::SortDirection>> mSortingKeys; int mKeysSize; }; }//namespace dataunits } //namespace io } //namespace bs #endif //BS_IO_DATA_UNITS_GATHER_HPP
8,741
C++
.h
224
23.486607
110
0.473672
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,432
Trace.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/data-units/concrete/Trace.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_DATA_UNITS_TRACE_HPP #define BS_IO_DATA_UNITS_TRACE_HPP #include <unordered_map> #include <memory> #include <sstream> #include <bs/base/common/assertions.h> #include <bs/io/data-units/data-types/TraceHeaderKey.hpp> namespace bs { namespace io { namespace dataunits { /** * @brief Trace Object contains TraceHeaderKey represented as a map. */ class Trace { public: /** * @brief Constructor */ explicit Trace(unsigned short aNS); /** * @brief Move constructor, to move ownership of TraceData. * * @param aTrace */ Trace(Trace &&aTrace) noexcept; /** * @brief Copy constructor. */ Trace(const Trace &aTrace); /** * @brief Destructor */ ~Trace(); /** * @brief Assigment operator overloading. */ Trace &operator=(Trace &&aTrace) noexcept; /** * @brief Getter for the Trace Header Value. * * @param[in] aTraceHeaderKey. * * @return Trace Header Value if available, else find() will * point to the end of map. */ template<typename T> inline T GetTraceHeaderKeyValue(TraceHeaderKey aTraceHeaderKey) { ASSERT_T_TEMPLATE(T); std::stringstream ss; ss << this->mTraceHeaderMap[aTraceHeaderKey]; T trace_header_value; ss >> trace_header_value; return trace_header_value; } /** * @brief * Check if a given trace header key exists. * * @param[in] aTraceHeaderKey * The trace header key to check. * * @return * True if an entry exists for it. */ bool HasTraceHeader(TraceHeaderKey aTraceHeaderKey) { return this->mTraceHeaderMap.find(aTraceHeaderKey) != this->mTraceHeaderMap.end(); } const std::unordered_map<TraceHeaderKey, std::string> * GetTraceHeaders() { return &this->mTraceHeaderMap; } /** * @brief Setter for the Trace Header Value. * * @param[in] aTraceHeaderKey * Trace Header Key argument. * * @param[in] aValue * Value to set for the corresponding key */ template<typename T> inline void SetTraceHeaderKeyValue(TraceHeaderKey aTraceHeaderKey, T aValue) { ASSERT_T_TEMPLATE(T); this->mTraceHeaderMap[aTraceHeaderKey] = std::to_string(aValue); } /** * @brief Setter for trace data. */ inline void SetTraceData(float *apTraceData) { return this->mpTraceData.reset(apTraceData); } /** * @brief Getter for trace data. * * @return Pointer to trace data. */ inline float * GetTraceData() { return this->mpTraceData.get(); } /** * @brief Getter for number of samples trace header. * * @return Number of samples value. */ inline unsigned short GetNumberOfSamples() { TraceHeaderKey trace_header_key(TraceHeaderKey::NS); return this->GetTraceHeaderKeyValue<unsigned short>(trace_header_key); } /** * @brief Setter for any coordinate location. * This will scale the given float based on the SCALCO header. */ void SetScaledCoordinateHeader(TraceHeaderKey aKey, float aLocation); /** * @brief Getter for source location. Should hide all the preprocessing from the user. * * @return Source Location. */ float GetScaledCoordinateHeader(TraceHeaderKey aKey); private: /// @brief TraceHeaderKey, containing trace headers and their corresponding value. /// @key TraceHeaderKey /// @value string std::unordered_map<TraceHeaderKey, std::string> mTraceHeaderMap; /// @brief TraceData, containing trace data. std::unique_ptr<float[]> mpTraceData; }; }//namespace dataunits } //namespace io } //namespace bs #endif //BS_IO_DATA_UNITS_TRACE_HPP
6,095
C++
.h
157
24.159236
102
0.496366
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,433
TraceHelper.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/data-units/helpers/TraceHelper.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_DATA_UNITS_HELPERS_TRACE_HELPER_HPP #define BS_IO_DATA_UNITS_HELPERS_TRACE_HELPER_HPP #include <bs/io/data-units/concrete/Trace.hpp> #include <bs/io/lookups/tables/TraceHeaderLookup.hpp> #include <bs/io/lookups/tables/BinaryHeaderLookup.hpp> namespace bs { namespace io { namespace dataunits { namespace helpers { /** * @brief Trace helper to take any trace data unit and helps manipulate * or get any regarded meta data from it. */ class TraceHelper { public: static int Weight(Trace *&apTrace, lookups::TraceHeaderLookup &aTraceHeaderLookup, lookups::BinaryHeaderLookup &aBinaryHeaderLookup); static int WeightData(Trace *&apTrace, lookups::TraceHeaderLookup &aTraceHeaderLookup, lookups::BinaryHeaderLookup &aBinaryHeaderLookup); }; } //namespace helpers } //namespace dataunits } //namespace io } //namespace bs #endif //BS_IO_DATA_UNITS_HELPERS_TRACE_HELPER_HPP
1,980
C++
.h
47
33
87
0.637779
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,434
Displayer.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/utils/displayers/Displayer.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_UTILS_DISPLAYERS_DISPLAYER_H #define BS_IO_UTILS_DISPLAYERS_DISPLAYER_H namespace bs { namespace io { namespace utils { namespace displayers { class Displayer { public: /** * @brief Prints the text header extracted from the given SEG-Y file in the * SEG-Y community format. * * @param apTextHeader */ static void PrintTextHeader(unsigned char *apTextHeader); private: Displayer() = default; }; } //namespace displayers } //namespace utils } //namespace io } //namespace bs #endif //BS_IO_UTILS_DISPLAYERS_DISPLAYER_H
1,568
C++
.h
42
28.714286
95
0.615132
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,435
ExecutionTimer.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/utils/timer/ExecutionTimer.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_UTILS_TIMER_EXECUTION_TIMER_HPP #define BS_IO_UTILS_TIMER_EXECUTION_TIMER_HPP #include <chrono> #include <iostream> namespace bs { namespace io { namespace utils { namespace timer { /** * @brief Function execution timer. */ class ExecutionTimer { public: /** * @brief Function execution timer. Takes a block of code as parameter and evaluate * it's run time. Takes a flag that determines whether to print put the execution * time or not. * * @note Time of execution is return as microseconds. */ template<typename T> static long Evaluate(T f, bool aShowExecutionTime = false) { auto start = std::chrono::high_resolution_clock::now(); f(); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); auto count = duration.count(); if (aShowExecutionTime) { ExecutionTimer::ShowResult(count); } return count; } /** * @brief Takes execution time in micro seconds and shows it in seconds, */ static int ShowResult(long aTime) { return printf("Execution Time: %.4f SEC\n", aTime / (1.0 * 1e6)); } }; } } } } #endif //BS_IO_UTILS_TIMER_EXECUTION_TIMER_HPP
2,622
C++
.h
64
28.078125
108
0.53605
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,436
EntryRange.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/utils/range/EntryRange.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_RANGE_BYTE_RANGE_HPP #define BS_IO_RANGE_BYTE_RANGE_HPP namespace bs { namespace io { namespace utils { namespace range { class EntryRange { public: enum Type : char { SHORT = 'h', USHORT = 'u', INT = 'i', UINT = 'p', LONG = 'l', ULONG = 'v', FLOAT = 'f', DOUBLE = 'd', CHAR = 's' }; public: EntryRange() = default; EntryRange(char aOffsetLength, int aStartPosition, int aConsecutiveBlocks = 1) { this->mOffsetLength = aOffsetLength; this->mStartPosition = aStartPosition; this->mConsecutiveBlocks = aConsecutiveBlocks; } EntryRange(const EntryRange &aBR) { mOffsetLength = aBR.mOffsetLength; mStartPosition = aBR.mStartPosition; mConsecutiveBlocks = aBR.mConsecutiveBlocks; } inline int GetStartPosition() const { return this->mStartPosition; } inline char GetOffsetLength() const { return this->mOffsetLength; } inline int GetConsecutiveBlocks() const { return this->mConsecutiveBlocks; } private: char mOffsetLength; int mStartPosition; int mConsecutiveBlocks; }; } //namespace ranges } //namespace utils } //namespace io } //namespace bs #endif //BS_IO_RANGE_BYTE_RANGE_HPP
2,586
C++
.h
62
28.177419
100
0.537022
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,437
FloatingPointFormatter.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/utils/convertors/FloatingPointFormatter.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_UTILS_CONVERTORS_FLOATING_POINT_FORMATTER_HPP #define BS_IO_UTILS_CONVERTORS_FLOATING_POINT_FORMATTER_HPP #include <cstring> namespace bs { namespace io { namespace utils { namespace convertors { /** * @brief Floating point formatter that work as a convertor from any floating type * representation to another. */ class FloatingPointFormatter { public: /** * @brief Trace size in bytes given the NS from trace header and format code from * binary header. * * @param[int] aSamplesNumber * @param[int] aFormatCode * @return Trace Size */ static int GetFloatArrayRealSize(unsigned short int aSamplesNumber, unsigned short int aFormatCode); static int Format(const char *apSrc, char *apDest, size_t aSrcSize, size_t aSamplesNumber, short aFormat, bool aFromFormat); private: FloatingPointFormatter() = default; private: /** * @brief Converts between 32 bit IBM floating numbers to native floating number. * @param[in] apSrc * @param[out] apDest * @param[in] aSrcSize * @return Flag. 1 if success and 0 if conversion failed. */ static int FromIBM(const char *apSrc, char *apDest, size_t aSrcSize, size_t aSamplesNumber); /** * @brief Converts between native floating number to 32 bit IBM floating numbers. * @param[in] apSrc * @param[out] apDest * @param[in] aSrcSize * @return Flag. 1 if success and 0 if conversion failed. */ static int ToIBM(const char *apSrc, char *apDest, size_t aSrcSize, size_t aSamplesNumber); /** * @brief Converts between 64 bit IBM floating numbers to native floating number. * @param[in] apSrc * @param[out] apDest * @param[in] aSize * @return Flag. 1 if success and 0 if conversion failed. */ static int FromLong(const char *apSrc, char *apDest, size_t aSize, size_t aSamplesNumber); /** * @brief Converts between 8 bit IBM floating numbers to native floating number. * @param[in] apSrc * @param[out] apDest * @param[in] aSize * @return Flag. 1 if success and 0 if conversion failed. */ static int FromShort(const char *apSrc, char *apDest, size_t aSize, size_t aSamplesNumber); /** * @brief Converts between 8 bit IEEE and IEEE floating numbers. * @param[in] apSrc * @param[out] apDest * @param[in] aSize * @return Flag. 1 if success and 0 if conversion failed. */ static int FromIEEE(const char *apSrc, char *apDest, size_t aSize, size_t aSamplesNumber); /** * @brief Converts between 8 bit character and IEEE floating numbers. * @param[in] apSrc * @param[out] apDest * @param[in] aSize * @return Flag. 1 if success and 0 if conversion failed. */ static int FromChar(const char *apSrc, char *apDest, size_t aSize, size_t aSamplesNumber); }; } //namespace convertors } //namespace utils } //namespace io } //namespace bs #endif //BS_IO_UTILS_CONVERTORS_FLOATING_POINT_FORMATTER_HPP
5,101
C++
.h
108
30.842593
109
0.514458
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,438
StringsConvertor.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/utils/convertors/StringsConvertor.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_UTILS_CONVERTORS_STRINGS_CONVERTOR_HPP #define BS_IO_UTILS_CONVERTORS_STRINGS_CONVERTOR_HPP #include <string> namespace bs { namespace io { namespace utils { namespace convertors { /** * @brief Strings convertor that work as a convertor from any representation type * to another, be it byte format, or endianness for example. */ class StringsConvertor { public: /** * @brief Takes a string and converts its content to short. * * @param[in] aStr * @return Converted string to short. */ static short ToShort(const std::string &aStr); /** * @brief Takes a string and converts its content to unsigned short. * * @param[in] aStr * @return Converted string to unsigned short. */ static unsigned short ToUShort(const std::string &aStr); /** * @brief Takes a string and converts its content to int. * * @param[in] aStr * @return Converted string to int. */ static int ToInt(const std::string &aStr); /** * @brief Takes a string and converts its content to unsigned int. * * @param[in] aStr * @return Converted string to unsigned int. */ static unsigned int ToUInt(const std::string &aStr); /** * @brief Takes a string and converts its content to long. * * @param[in] aStr * @return Converted string to long. */ static long ToLong(const std::string &aStr); /** * @brief Takes a string and converts its content to unsigned long. * * @param[in] aStr * @return Converted string to unsigned long. */ static unsigned long ToULong(const std::string &aStr); /** * @brief Takes pointer to unsigned char array and converts each * element from EBCDIC to ASCII. * * @param[in] apSrc * @param[in] aSize * @return Converted unsigned char array pointer */ static unsigned char * E2A(unsigned char *apSrc, size_t aSize); /** * @brief Takes char element and converts it from EBCDIC to ASCII. * * @param[in] aSrc * @return Converted char element. */ static unsigned char E2A(unsigned char aSrc); private: /** * @brief Private constructor for preventing objects creation. */ StringsConvertor() = default; private: static unsigned char mE2ATable[256]; }; } //namespace convertors } //namespace utils } //namespace io } //namespace bs #endif //BS_IO_UTILS_CONVERTORS_STRINGS_CONVERTOR_HPP
4,581
C++
.h
110
25.281818
97
0.477227
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,439
KeysConvertor.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/utils/convertors/KeysConvertor.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_UTILS_CONVERTORS_KEYS_CONVERTOR_HPP #define BS_IO_UTILS_CONVERTORS_KEYS_CONVERTOR_HPP #include <string> #include <unordered_map> #include <bs/io/data-units/data-types/TraceHeaderKey.hpp> namespace bs { namespace io { namespace utils { namespace convertors { /** * @brief Keys convertor that work as a convertor from string representation * to HeaderKey object(s) and vice versa. */ class KeysConvertor { public: /** * @brief Converts string representation for trace header key to TraceHeaderKey object. */ static dataunits::TraceHeaderKey ToTraceHeaderKey(std::string &aKey); private: /** * @brief Private constructor for preventing objects creation. */ KeysConvertor() = default; private: static const std::unordered_map<std::string, dataunits::TraceHeaderKey::Key> mTraceKeyMap; }; } //namespace convertors } //namespace utils } //namespace io } //namespace bs #endif //BS_IO_UTILS_CONVERTORS_KEYS_CONVERTOR_HPP
2,070
C++
.h
51
31.254902
110
0.621393
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,440
NumbersConvertor.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/utils/convertors/NumbersConvertor.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_UTILS_CONVERTORS_NUMBERS_CONVERTOR_HPP #define BS_IO_UTILS_CONVERTORS_NUMBERS_CONVERTOR_HPP #include <cstring> namespace bs { namespace io { namespace utils { namespace convertors { /** * @brief Numbers convertor that work as a convertor from any representation type * to another, be it byte format, or endianness for example. */ class NumbersConvertor { public: /** * @brief Takes pointer to char array (i.e. byte array) and converts each * element of it to little endian according to the provided format. * * @param apSrc * @param aSize * @param aFormat * @return Formatted array pointer. */ static char * ToLittleEndian(char *apSrc, size_t aSize, short aFormat); /** * @brief Takes pointer to short array and converts each * element of it to little endian. * * @param[in] apSrc * @param[in] aSize * @return Converted short array pointer */ static short * ToLittleEndian(short *apSrc, size_t aSize); /** * @brief Takes short element and converts it to little endian. * * @param[in] aSrc * @return Converted short element. */ static short ToLittleEndian(short aSrc); /** * @brief Takes pointer to unsigned short array and converts each * element of it to little endian. * * @param[in] apSrc * @param[in] aSize * @return Converted unsigned short array pointer */ static unsigned short * ToLittleEndian(unsigned short *apSrc, size_t aSize); /** * @brief Takes unsigned short element and converts it to little endian. * * @param[in] aSrc * @return Converted unsigned short element. */ static unsigned short ToLittleEndian(unsigned short aSrc); /** * @brief Takes pointer to int array and converts each * element of it to little endian. * * @param[in] apSrc * @param[in] aSize * @return Converted int array pointer */ static int * ToLittleEndian(int *apSrc, size_t aSize); /** * @brief Takes int element and converts it to little endian. * * @param[in] aSrc * @return Converted int element. */ static int ToLittleEndian(int aSrc); /** * @brief Takes pointer to float array and converts each * element of it to little endian. * * @param[in] apSrc * @param[in] aSize * @return Converted float array pointer */ static float * ToLittleEndian(float *apSrc, size_t aSize); /** * @brief Takes float element and converts it to little endian. * * @param[in] aSrc * @return Converted float element. */ static float ToLittleEndian(float aSrc); /** * @brief Takes pointer to int array and converts each * element of it to little endian. * * @param[in] apSrc * @param[in] aSize * @return Converted int array pointer */ static unsigned int * ToLittleEndian(unsigned int *apSrc, size_t aSize); /** * @brief Takes unsigned int element and converts it to little endian. * * @param[in] aSrc * @return Converted unsigned int element. */ static unsigned int ToLittleEndian(unsigned int aSrc); /** * @brief Takes pointer to signed char array and converts each * element of it to little endian. * * @param[in] apSrc * @param[in] aSize * @return Converted signed char array pointer */ static signed char * ToLittleEndian(signed char *apSrc, size_t aSize); /** * @brief Takes signed char element and converts it to little endian. * * @param[in] aSrc * @return Converted signed char element. */ static signed char ToLittleEndian(signed char aSrc); private: /** * @brief Private constructor for preventing objects creation. */ NumbersConvertor() = default; }; } //namespace convertors } //namespace utils } //namespace io } //namespace bs #endif //BS_IO_UTILS_CONVERTORS_NUMBERS_CONVERTOR_HPP
6,951
C++
.h
161
25.055901
97
0.457177
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,441
Checker.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/utils/checkers/Checker.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_UTILS_CHECKERS_CHECKER_HPP #define BS_IO_UTILS_CHECKERS_CHECKER_HPP namespace bs { namespace io { namespace utils { namespace checkers { class Checker { public: /** * @brief Return 0 for big endian, 1 for little endian. */ static bool IsLittleEndianMachine(); private: Checker() = default; }; } //namespace checkers } //namespace utils } //namespace io } //namespace bs #endif //BS_IO_UTILS_CHECKERS_CHECKER_HPP
1,400
C++
.h
39
28.307692
75
0.626568
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,442
ShotsMetaDataGenerator.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/utils/synthetic-generators/concrete/ShotsMetaDataGenerator.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_UTILS_SYNTHETIC_GENERATORS_SHOTS_META_DATA_GENERATOR_HPP #define BS_IO_UTILS_SYNTHETIC_GENERATORS_SHOTS_META_DATA_GENERATOR_HPP #include <prerequisites/libraries/nlohmann/json.hpp> #include <bs/io/utils/synthetic-generators/interface/MetaDataGenerator.hpp> namespace bs { namespace io { namespace generators { /** * @brief * Struct used to contain 3D points used for the generation. */ struct Point3D { int x; int y; int z; }; /** * @brief * Meta data trace generator for the given shots. */ class ShotsMetaDataGenerator : public MetaDataGenerator { public: /** * @brief * Constructor. * * @param[in] aJsonNode * JSON node containing the information needed for the generation. */ explicit ShotsMetaDataGenerator(nlohmann::json aJsonNode); ~ShotsMetaDataGenerator() override; void SetGenerationKey(std::vector<io::dataunits::TraceHeaderKey> &aHeaderKeys) override; std::vector<io::dataunits::Gather *> GetAllTraces() override; std::vector<io::dataunits::Gather *> GetTraces(std::vector<std::vector<std::string>> aHeaderValues) override; std::vector<std::vector<std::string>> GetGatherUniqueValues() override; uint GetGatherNumber() override; private: /** * @brief * Return the total number of sources. * * @return * The total number of sources to be generated. */ uint GetSourceNumber() const; /** * @brief * Return the total number of receivers per source. * * @return * The total number of receiver per each shot. */ uint GetReceiverNumber() const; private: /// The shots sampling. float mSamplingX; float mSamplingY; float mTimeSampling; /// The number of samples. uint mSampleNumber; /// The source settings. Point3D mSourceStart; Point3D mSourceEnd; Point3D mSourceIncrement; /// The receiver settings. Point3D mReceiverRelStart; Point3D mReceiverNumber; Point3D mReceiverIncrement; /// The origin coordinates in space. float mOriginX; float mOriginY; /// The gather key used. io::dataunits::TraceHeaderKey mGatherKey; }; } } } #endif //BS_IO_UTILS_SYNTHETIC_GENERATORS_SHOTS_META_DATA_GENERATOR_HPP
3,923
C++
.h
102
25.813725
99
0.547294
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,443
ParameterMetaDataGenerator.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/utils/synthetic-generators/concrete/ParameterMetaDataGenerator.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_UTILS_SYNTHETIC_GENERATORS_PARAMETER_META_DATA_GENERATOR_HPP #define BS_IO_UTILS_SYNTHETIC_GENERATORS_PARAMETER_META_DATA_GENERATOR_HPP #include <prerequisites/libraries/nlohmann/json.hpp> #include <bs/io/utils/synthetic-generators/interface/MetaDataGenerator.hpp> namespace bs { namespace io { namespace generators { class ParameterMetaDataGenerator : public MetaDataGenerator { public: explicit ParameterMetaDataGenerator(nlohmann::json aJsonNode); ~ParameterMetaDataGenerator() override = default; void SetGenerationKey(std::vector<io::dataunits::TraceHeaderKey> &aHeaderKeys) override; std::vector<io::dataunits::Gather *> GetAllTraces() override; std::vector<io::dataunits::Gather *> GetTraces(std::vector<std::vector<std::string>> aHeaderValues) override; std::vector<std::vector<std::string>> GetGatherUniqueValues() override; uint GetGatherNumber() override; private: /// The parameter model sampling. float mSamplingX; float mSamplingY; float mSamplingZ; /// The number of points uint mPointsX; uint mPointsY; uint mPointsZ; /// The origin coordinates in space. float mOriginX; float mOriginY; /// The gather key used. io::dataunits::TraceHeaderKey mGatherKey; }; } } } #endif //BS_IO_UTILS_SYNTHETIC_GENERATORS_PARAMETER_META_DATA_GENERATOR_HPP
2,487
C++
.h
58
33.241379
99
0.64005
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,444
PlaneReflectorGenerator.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/utils/synthetic-generators/concrete/PlaneReflectorGenerator.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_UTILS_SYNTHETIC_GENERATORS_PLANE_REFLECTOR_GENERATOR_HPP #define BS_IO_UTILS_SYNTHETIC_GENERATORS_PLANE_REFLECTOR_GENERATOR_HPP #include <bs/io/utils/synthetic-generators/interface/ReflectorDataGenerator.hpp> namespace bs { namespace io { namespace generators { class PlaneReflectorGenerator : public ReflectorDataGenerator { public: PlaneReflectorGenerator(); ~PlaneReflectorGenerator() override; void ParseValues(nlohmann::json &aJsonNode) override; float GetReflectorDepth(float x, float y) override; float GetBeforeValue() override; float GetAfterValue() override; private: /// The values before and after the reflector. float mValueBefore; float mValueAfter; /// Origin points. float mOriginX; float mOriginY; float mOriginZ; /// The slope angles of the plane. float mXSlopeAngle; float mYSlopeAngle; }; } } } #endif //BS_IO_UTILS_SYNTHETIC_GENERATORS_PLANE_REFLECTOR_GENERATOR_HPP
2,037
C++
.h
52
30.115385
80
0.639494
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,445
ReflectorDataGenerator.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/utils/synthetic-generators/interface/ReflectorDataGenerator.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_UTILS_SYNTHETIC_GENERATORS_REFLECTOR_DATA_GENERATOR_HPP #define BS_IO_UTILS_SYNTHETIC_GENERATORS_REFLECTOR_DATA_GENERATOR_HPP #include <prerequisites/libraries/nlohmann/json.hpp> namespace bs { namespace io { namespace generators { /** * @brief * Interface for all the reflector data generators. */ class ReflectorDataGenerator { public: /** * @brief * Default constructor. */ ReflectorDataGenerator() = default; /** * @brief * Destructor. */ virtual ~ReflectorDataGenerator() = default; /** * @brief * Acquire the values from a given json node. * * @param[in] aJsonNode * The json node to parse properties from. */ virtual void ParseValues(nlohmann::json &aJsonNode) = 0; /** * @brief * Calculate the reflector depth at a given point in space. * * @param[in] x * The point in x. * * @param[in] y * The point in y. * * @return * The depth calculated of the reflector. */ virtual float GetReflectorDepth(float x, float y) = 0; /** * @brief * Get the value that is below the reflector. * * @return * The value right below the reflector. */ virtual float GetAfterValue() = 0; /** * @brief * Get the value that is above the reflector. * * @return * The value right above the reflector. */ virtual float GetBeforeValue() = 0; }; } } } #endif //BS_IO_UTILS_SYNTHETIC_GENERATORS_REFLECTOR_DATA_GENERATOR_HPP
3,037
C++
.h
87
22.356322
75
0.50357
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,446
MetaDataGenerator.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/utils/synthetic-generators/interface/MetaDataGenerator.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_UTILS_SYNTHETIC_GENERATORS_META_DATA_GENERATOR_HPP #define BS_IO_UTILS_SYNTHETIC_GENERATORS_META_DATA_GENERATOR_HPP #include <vector> #include <bs/io/data-units/concrete/Gather.hpp> #define IO_K_SYN_CELL_SAMP "cell-dimension" /* string. */ #define IO_K_SYN_CELL_SAMP_X "dx" /* string. */ #define IO_K_SYN_CELL_SAMP_Y "dy" /* string. */ #define IO_K_SYN_CELL_SAMP_Z "dz" /* string. */ #define IO_K_SYN_GRIZ_SIZE "grid-size" /* string. */ #define IO_K_SYN_NX "nx" /* string. */ #define IO_K_SYN_NY "ny" /* string. */ #define IO_K_SYN_NZ "nz" /* string. */ #define IO_K_SYN_ORIGIN "origin-coordinates" /* string. */ #define IO_K_SYN_X "x" /* string. */ #define IO_K_SYN_Y "y" /* string. */ #define IO_K_SYN_Z "z" /* string. */ #define IO_K_SYN_X_INDEX "x-index" /* string. */ #define IO_K_SYN_Y_INDEX "y-index" /* string. */ #define IO_K_SYN_Z_INDEX "z-index" /* string. */ #define IO_K_SYN_X_OFFSET "x-offset" /* string. */ #define IO_K_SYN_Y_OFFSET "y-offset" /* string. */ #define IO_K_SYN_Z_OFFSET "z-offset" /* string. */ #define IO_K_SYN_SOURCE "source" /* string. */ #define IO_K_SYN_START "start" /* string. */ #define IO_K_SYN_END "end" /* string. */ #define IO_K_SYN_INCREMENT "increment" /* string. */ #define IO_K_SYN_NUMBER "number" /* string. */ #define IO_K_SYN_SHOTS "shots" /* string. */ #define IO_K_SYN_DT "time-sampling" /* string. */ #define IO_K_SYN_NS "sample-number" /* string. */ #define IO_K_SYN_REC_REL "source-relative-receivers" /* string. */ namespace bs { namespace io { namespace generators { /** * @brief * Interface for all meta-data generators to generate traces with correct meta-data. */ class MetaDataGenerator { public: /** * @brief * Default constructor. */ MetaDataGenerator() = default; /** * @brief * Default destructor. */ virtual ~MetaDataGenerator() = default; /** * @brief * Set the generation keys used for the gather generation of meta-data. * * @param[in] aHeaderKeys * The header keys to use for generation. */ virtual void SetGenerationKey(std::vector<io::dataunits::TraceHeaderKey> &aHeaderKeys) = 0; /** * @brief * Get all the possible gathers to be generated. * * @return * Vector of gathers. */ virtual std::vector<io::dataunits::Gather *> GetAllTraces() = 0; /** * @brief * Get all the traces following a given subset of values. * * @param[in] aHeaderValues * The header values to generate for. * * @return * The gathers generated. */ virtual std::vector<io::dataunits::Gather *> GetTraces(std::vector<std::vector<std::string>> aHeaderValues) = 0; /** * @brief * Return all the possible identifiers based on the gather key provided. * * @return * List of identifiers. */ virtual std::vector<std::vector<std::string>> GetGatherUniqueValues() = 0; /** * @brief * Get the total number of gathers that can be generated. * * @return * The total number of gathers. */ virtual uint GetGatherNumber() = 0; }; } } } #endif //BS_IO_UTILS_SYNTHETIC_GENERATORS_META_DATA_GENERATOR_HPP
5,692
C++
.h
121
36.892562
96
0.455478
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,447
Definitions.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/common/Definitions.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_COMMON_DEFINITIONS_HPP #define BS_IO_COMMON_DEFINITIONS_HPP namespace bs { namespace io { namespace common { namespace definitions { #define IO_DEF_BRIGHTSKIES_COPY_WRITES "Written by Brightskies INC. I/O Library" /* Copyrights. */ } //namespace definitions } //namespace common } //namespace io } //namespace bs #endif //BS_IO_COMMON_DEFINITIONS_HPP
1,158
C++
.h
30
35.266667
104
0.723063
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,448
MapKeys.h
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/configurations/MapKeys.h
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_CONFIGURATIONS_MAP_KEYS_HPP #define BS_IO_CONFIGURATIONS_MAP_KEYS_HPP namespace bs { namespace io { namespace configuration { /* * EXTENSIONS */ #define IO_K_EXT_BIN ".bin" /* Binary file format */ #define IO_K_EXT_CSV ".csv" /* CSV file format */ #define IO_K_EXT_IMG ".png" /* Image (i.e. PNG) file format */ #define IO_K_EXT_SGY ".segy" /* SEG-Y file format */ #define IO_K_EXT_JSON ".json" /* JSON file format */ #define IO_K_EXT_SU ".su" /* SU format */ /* * INDEX EXTENSIONS */ #define IO_K_EXT_SGY_INDEX ".bs.io.idx.segy" /* SEG-Y index file format */ /* * CONFIGURATIONS MAP ATTRIBUTES */ #define IO_K_PROPERTIES "properties" #define IO_K_WRITE_PATH "write-path" #define IO_K_READ_PATH "read-path" #define IO_K_READ_INDEXED_PATH "read-indexed-path" #define IO_K_WRITE_LITTLE_ENDIAN "write-little-endian" #define IO_K_FLOAT_FORMAT "floating-point-format" #define IO_K_PERCENTILE "percentile" #define IO_K_SYNTHETIC_METADATA "synthetic-meta-data" #define IO_K_TEXT_HEADERS_ONLY "text-headers-only" #define IO_K_TEXT_HEADERS_STORE "text-headers-store" #define IO_K_POOL_UUID "pool-uuid" #define IO_K_CONTAINER_UUID "container-uuid" #define IO_K_INDEX_KEYS "index-keys" } //namespace configurations } //namespace io } //namespace bs #endif //BS_IO_CONFIGURATIONS_MAP_KEYS_HPP
2,387
C++
.h
56
40.607143
94
0.630444
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,449
BSIO.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/api/cpp/BSIO.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_BS_IO_HPP #define BS_IO_BS_IO_HPP /* DATA UNITS. */ #include <bs/io/data-units/concrete/Trace.hpp> #include <bs/io/data-units/concrete/Gather.hpp> /* READERS/WRITERS. */ #include <bs/io/streams/primitive/Reader.hpp> #include <bs/io/streams/primitive/Writer.hpp> #include <bs/io/streams/concrete/readers/SeismicReader.hpp> #include <bs/io/streams/concrete/writers/SeismicWriter.hpp> #include <bs/io/streams/concrete/readers/SegyReader.hpp> #include <bs/io/streams/concrete/writers/SegyWriter.hpp> /* CONFIGURATIONS. */ #include <bs/io/configurations/MapKeys.h> #endif //BS_IO_BS_IO_HPP
1,339
C++
.h
33
38.878788
73
0.761538
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,450
IndexMap.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/indexers/IndexMap.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_INDEXERS_INDEX_MAP_HPP #define BS_IO_INDEXERS_INDEX_MAP_HPP #include <vector> #include <bs/io/data-units/data-types/TraceHeaderKey.hpp> namespace bs { namespace io { namespace indexers { class IndexMap { public: /** * @brief Constructor. */ IndexMap(); /** * @brief Destructor. */ ~IndexMap(); /** * @brief Resets current map for reusable purposes. * @return Status flag. */ int Reset(); /** * @brief Adds a byte position to the vector corresponding to the desired trace header key. * @param[in] aTraceHeaderKey * @param[in] aTraceHeaderValue * @param[in] aBytePosition * @return Status flag. */ int Add(const std::string &aTraceHeaderKey, const std::string &aTraceHeaderValue, const size_t &aBytePosition); /** * @brief Adds a byte position vector corresponding to the desired trace header key. * @param[in] aTraceHeaderKey * @param[in] aTraceHeaderValue * @param[in] aBytePositions * @return Status flag. */ int Add(const std::string &aTraceHeaderKey, const std::string &aTraceHeaderValue, const std::vector<size_t> &aBytePositions); /** * @brief Gets vector of byte positions corresponding to the desired trace header key and value. * @param[in] aTraceHeaderKey * @param[in] aTraceHeaderValue * @return Byte positions vector. */ inline std::vector<size_t> & Get(const std::string &aTraceHeaderKey, const std::string &aTraceHeaderValue) { return this->mIndexMap[aTraceHeaderKey][aTraceHeaderValue]; } /** * @brief Gets map of byte positions corresponding to the desired trace header key and value. * @param[in] aTraceHeaderKey * @param[in] aTraceHeaderValue * @return Byte positions map. */ std::map<std::string, std::vector<size_t>> Get(const std::string &aTraceHeaderKey, std::vector<std::string> &aTraceHeaderValues); /** * @brief Gets map of trace header values as keys and byte positions as values, * corresponding to the desired trace header key. * * @param[in] aTraceHeaderKey * @return Byte positions vector. */ inline std::map<std::string, std::vector<size_t>> & Get(const std::string &aTraceHeaderKey) { return this->mIndexMap[aTraceHeaderKey]; } /** * @brief Gets complete map. (i.e. Each trace header key and it's corresponding byte positions vector.) * @return Complete map. */ inline std::unordered_map<std::string, std::map<std::string, std::vector<size_t>>> & Get() { return this->mIndexMap; } inline bool IsEmpty() { return this->mIndexMap.empty(); } private: /// Index map, having trace header key as key and vector of byte positions /// in file corresponding to this trace header key. std::unordered_map<std::string, std::map<std::string, std::vector<size_t>>> mIndexMap; }; } //namespace indexers } //namespace io } //namespace bs #endif //BS_IO_INDEXERS_INDEX_MAP_HPP
4,810
C++
.h
109
30.394495
119
0.54035
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,451
FileIndexer.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/indexers/FileIndexer.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_INDEXERS_FILE_INDEXER_HPP #define BS_IO_INDEXERS_FILE_INDEXER_HPP #include <string> #include <bs/io/streams/helpers/InStreamHelper.hpp> #include <bs/io/streams/helpers/OutStreamHelper.hpp> #include <bs/io/indexers/IndexMap.hpp> namespace bs { namespace io { namespace indexers { class FileIndexer { public: /** * @brief Explicit constructor. * @param aFilePath */ explicit FileIndexer(std::string &aFilePath, std::string &aKey); /** * @brief Destructor. */ ~FileIndexer(); /** * @brief * Initializes the indexer with the appropriate settings to be applied. * * @return File initial size (i.e. Zero value). */ size_t Initialize(); /** * @brief * Release all resources and close everything. * Should be initialized again afterwards to be able to reuse it again. * * @return Status flag. */ int Finalize(); /** * @brief Do the actual indexing upon the given file. Takes trace header keys vector to index upon it * @param[in] aTraceHeaderKeys * @return Index Map. */ indexers::IndexMap Index(const std::vector<dataunits::TraceHeaderKey> &aTraceHeaderKeys); /** * @brief Index Map getter. * @return IndexMap object. */ inline indexers::IndexMap GetIndexMap() { return this->mIndexMap; } /** * @brief Indexed file path getter. */ inline std::string GetIndexedFilePath() { return this->mOutFilePath; } private: static std::string GenerateOutFilePathName(std::string &aInFileName, std::string &aKey); void StoreMapToFile(const std::vector<dataunits::TraceHeaderKey> &aTraceHeaderKeys); void LoadMapFromFile(streams::helpers::InStreamHelper *aInStreamHelper, const std::vector<dataunits::TraceHeaderKey> &aTraceHeaderKeys); private: /// Input ile path. std::string mInFilePath; /// Output file path. std::string mOutFilePath; /// File input stream helper. streams::helpers::InStreamHelper *mInStreamHelper; /// Index map, having trace header key as key and vector of byte positions /// in file corresponding to this trace header key. indexers::IndexMap mIndexMap; }; } //namespace indexers } //namespace io } //namespace bs #endif //BS_IO_INDEXERS_FILE_INDEXER_HPP
3,906
C++
.h
96
28.03125
117
0.551542
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,452
SeismicFilesHeaders.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/lookups/SeismicFilesHeaders.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_LOOKUPS_SEISMIC_FILES_HEADERS_HPP #define BS_IO_LOOKUPS_SEISMIC_FILES_HEADERS_HPP #include <map> #include <bs/io/data-units/data-types/TraceHeaderKey.hpp> #include <bs/io/utils/range/EntryRange.hpp> namespace bs { namespace io { namespace lookups { class SeismicFilesHeaders { public: static utils::range::EntryRange GetEntryRange(dataunits::TraceHeaderKey aTraceHeaderKey) { return SeismicFilesHeaders::mTraceHeadersMap.find(aTraceHeaderKey)->second; } static std::map<dataunits::TraceHeaderKey, utils::range::EntryRange> GetTraceHeadersMap() { return SeismicFilesHeaders::mTraceHeadersMap; } private: static const std::map<dataunits::TraceHeaderKey, utils::range::EntryRange> mTraceHeadersMap; static const std::map<dataunits::TraceHeaderKey, utils::range::EntryRange> mBinaryHeadersMap; }; } } } //namespace bs #endif //BS_IO_LOOKUPS_SEISMIC_FILES_HEADERS_HPP
1,826
C++
.h
42
36.952381
109
0.696117
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,453
SegyHeaderMapper.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/lookups/mappers/SegyHeaderMapper.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_LOOKUPS_MAPPERS_TRACE_HEADER_MAPPER_HPP #define BS_IO_LOOKUPS_MAPPERS_TRACE_HEADER_MAPPER_HPP #include <unordered_map> #include <cstdio> #include <bs/io/data-units/data-types/TraceHeaderKey.hpp> #include <bs/io/lookups/mappers/HeaderMapper.hpp> namespace bs { namespace io { namespace lookups { class SegyHeaderMapper { public: static std::unordered_map<dataunits::TraceHeaderKey::Key, std::pair<size_t, NATIVE_TYPE>> mLocationTable; }; } //namespace lookups } //namespace io } //namespace bs #endif //BS_IO_LOOKUPS_MAPPERS_TRACE_HEADER_MAPPER_HPP
1,403
C++
.h
36
34.527778
73
0.713235
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,454
PSGHeaderMapper.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/lookups/mappers/PSGHeaderMapper.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_LOOKUPS_MAPPERS_PSG_HEADER_MAPPER_HPP #define BS_IO_LOOKUPS_MAPPERS_PSG_HEADER_MAPPER_HPP #include <cstdio> #include <unordered_map> #include <bs/io/data-units/data-types/TraceHeaderKey.hpp> #include <bs/io/lookups/mappers/HeaderMapper.hpp> namespace bs { namespace io { namespace lookups { class PSGHeaderMapper { public: static std::unordered_map<dataunits::TraceHeaderKey::Key, std::pair<size_t, NATIVE_TYPE>> mLocationTable; }; } //namespace lookups } //namespace io } //namespace bs #endif //BS_IO_LOOKUPS_MAPPERS_PSG_HEADER_MAPPER_HPP
1,396
C++
.h
36
34.333333
73
0.711752
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,455
HeaderMapper.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/lookups/mappers/HeaderMapper.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_LOOKUPS_MAPPERS_HEADER_MAPPER_HPP #define BS_IO_LOOKUPS_MAPPERS_HEADER_MAPPER_HPP #include <cstdio> #include <unordered_map> #include <bs/io/data-units/data-types/TraceHeaderKey.hpp> #include <bs/io/data-units/concrete/Trace.hpp> namespace bs { namespace io { namespace lookups { /** * @brief * Enum representing the native type of different entries. */ enum class NATIVE_TYPE { CHAR, UNSIGNED_CHAR, SHORT, UNSIGNED_SHORT, LONG, UNSIGNED_LONG, INT, UNSIGNED_INT, FLOAT, DOUBLE }; size_t native_type_to_size(NATIVE_TYPE native_type); /** * @brief * Utility class for header mapping between raw byte pointers, and the trace object. */ class HeaderMapper { public: /** * @brief * Map data from a raw byte pointer to a trace object according to a given map. * * @param[in] apRawData * The byte pointer containing the raw data. * * @param[in] aTrace * The trace to set the headers in. * * @param[in] aLocationTable * The location table used, keys being trace header key enums, * values are pairs of offsets in the raw data and their native type. * * @param[in] aSwap * Whether to swap bytes or not(Transform endianness). */ static void MapHeaderToTrace( const char *apRawData, io::dataunits::Trace &aTrace, std::unordered_map<dataunits::TraceHeaderKey::Key, std::pair<size_t, NATIVE_TYPE>> &aLocationTable, bool aSwap = true); /** * @brief * Map data from a trace object to a raw byte pointer according to a given map. * * @param[in] apRawData * The byte pointer containing the raw data. * * @param[in] aTrace * The trace to set the headers in. * * @param[in] aLocationTable * The location table used, keys being trace header key enums, * values are pairs of offsets in the raw data and their native type. * * @param[in] aSwap * Whether to swap bytes or not(Transform endianness). */ static void MapTraceToHeader( char *apRawData, io::dataunits::Trace &aTrace, std::unordered_map<dataunits::TraceHeaderKey::Key, std::pair<size_t, NATIVE_TYPE>> &aLocationTable, bool aSwap = true); }; } //namespace lookups } //namespace io } //namespace bs #endif //BS_IO_LOOKUPS_MAPPERS_TRACE_HEADER_MAPPER_HPP
4,069
C++
.h
101
26.930693
96
0.528669
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,456
TextHeaderLookup.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/lookups/tables/TextHeaderLookup.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_LOOKUPS_TEXT_HEADERS_LOOKUP_HPP #define BS_IO_LOOKUPS_TEXT_HEADERS_LOOKUP_HPP namespace bs { namespace io { namespace lookups { #define IO_SIZE_TEXT_HEADER 3200 /* Size of the text header in SEG-Y files */ #define IO_SIZE_EXT_TEXT_HEADER 3200 /* Size of the extended (i.e. If available) text header in SEG-Y files */ #define IO_POS_S_TEXT_HEADER 0 /* Start position of text header in SEG-Y and SU files */ #define IO_POS_E_TEXT_HEADER 3200 /* End position of text header in SEG-Y and SU files */ #define IO_POS_S_EXT_TEXT_HEADER 3600 /* Start position of extended text header in SEG-Y and SU files */ #define IO_POS_E_EXT_TEXT_HEADER 6800 /* End position of extended text header in SEG-Y and SU files */ } //namespace lookups } //namespace io } //namespace bs #endif //BS_IO_LOOKUPS_TEXT_HEADERS_LOOKUP_HPP
1,661
C++
.h
33
47.939394
121
0.702403
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,457
TraceHeaderLookup.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/lookups/tables/TraceHeaderLookup.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_LOOKUPS_TRACE_HEADERS_LOOKUP_HPP #define BS_IO_LOOKUPS_TRACE_HEADERS_LOOKUP_HPP namespace bs { namespace io { namespace lookups { #define IO_SIZE_TRACE_HEADER 240 /* Size of the trace header in SEG-Y and SU files */ #define IO_POS_S_TRACE_HEADER 3600 /* Start position of trace header in SEG-Y and SU files */ /** * @brief SEG-Y and SU trace header lookup. Variable types corresponds to * the number of allocated byte(s) for this variable internally in the SEG-Y or SU file * according to the general format. * * @note All variables are stored as big endian, if the machine used is little endian * big endian to little endian conversion should take place. */ struct TraceHeaderLookup { int32_t TRACL; int32_t TRACR; int32_t FLDR; int32_t TRACF; int32_t EP; int32_t CDP; int32_t CDPT; int16_t TRACE_CODE; int16_t NVS; int16_t NHS; int16_t DUSE; int32_t OFFSET; int32_t GELEV; int32_t SELEV; int32_t SDEPTH; int32_t GDEL; int32_t SDEL; int32_t SWDEP; int32_t GWDEP; int16_t SCALEL; int16_t SCALCO; int32_t SX; int32_t SY; int32_t GX; int32_t GY; int16_t COINTIT; int16_t WEVEL; int16_t SWEVEL; int16_t SUT; int16_t GUT; int16_t SSTAT; int16_t GSTAT; int16_t TSTAT; int16_t LAGA; int16_t LAGB; int16_t DELRT; int16_t MUTS; int16_t MUTE; uint16_t NS; uint16_t DT; int16_t GAIN; int16_t IGC; int16_t IGI; int16_t CORR; int16_t SFS; int16_t SFE; int16_t SLEN; int16_t STYP; int16_t STAS; int16_t STAE; int16_t TATYP; int16_t AFILF; int16_t AFILS; int16_t NOFILF; int16_t NOFILS; int16_t LCF; int16_t HCF; int16_t LCS; int16_t HCS; int16_t YEAR; int16_t DAY; int16_t HOUR; int16_t MINUTE; int16_t SEC; int16_t TIMBAS; int16_t TRWF; int16_t GRNORS; int16_t GRNOFR; int16_t GRNLOF; int16_t GAPS; int16_t OTRAV; /* * Extended. */ int32_t ENSX; int32_t ENSY; int32_t INLINE; int32_t CROSS; int32_t SHOOTPOINT; int16_t SHOOTPOINT_SCALE; int16_t TRACE_UNIT; uint8_t TRANSD_CONST[6]; int16_t TRANSD_UNIT; int16_t TRID; int16_t SCALE_TIME; int16_t SRC_ORIENT; uint8_t SRC_DIRECTION[6]; uint8_t SRC_MEASUREMT[6]; int16_t SRC_UNIT; uint8_t UNASSIGNED1[6]; }; } //namespace lookups } //namespace io } //namespace bs #endif //BS_IO_LOOKUPS_TRACE_HEADERS_LOOKUP_HPP
4,516
C++
.h
129
21.472868
103
0.484018
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,458
BinaryHeaderLookup.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/include/bs/io/lookups/tables/BinaryHeaderLookup.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_IO_LOOKUPS_BINARY_HEADERS_LOOKUP_HPP #define BS_IO_LOOKUPS_BINARY_HEADERS_LOOKUP_HPP namespace bs { namespace io { namespace lookups { #define IO_SIZE_BINARY_HEADER 400 /* Size of the binary header in SEG-Y and SU files */ #define IO_POS_S_BINARY_HEADER 3200 /* Start position of binary header in SEG-Y and SU files */ #define IO_POS_E_BINARY_HEADER 3600 /* End position of binary header in SEG-Y and SU files */ /** * @brief SEG-Y and SU binary header lookup. Variable types corresponds to * the number of allocated byte(s) for this variable internally in the SEG-Y or SU file * according to the general format. * * @note All variables are stored as big endian, if the machine used is little endian * big endian to little endian conversion should take place. */ struct BinaryHeaderLookup { int32_t JOBID; int32_t LINO; int32_t RENO; int16_t NTRPR; int16_t NART; uint16_t HDT; int16_t DTO; uint16_t HNS; uint16_t NSO; int16_t FORMAT; int16_t FOLD; int16_t TSORT; int16_t VSCODE; int16_t HSFS; int16_t HSFE; int16_t HSLEN; int16_t HSTYP; int16_t SCHN; int16_t HSTAS; int16_t HSTAE; int16_t HTATYP; int16_t HCORR; int16_t BGRCV; int16_t RCVM; int16_t MFEET; int16_t POLYT; int16_t VPOL; uint8_t UNASSIGNED1[240]; int16_t SEGY_REV_NUM; int16_t FIXED_LEN; int16_t EXT_HEAD; uint8_t UNASSIGNED2[94]; }; } //namespace lookups } //namespace io } //namespace bs #endif //BS_IO_LOOKUPS_BINARY_HEADERS_LOOKUP_HPP
2,845
C++
.h
72
29
104
0.574061
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,459
DataGenerator.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSIO/tests/test-utils/include/bs/io/test-utils/DataGenerator.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS I/O. * * BS I/O is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS I/O 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef TIMER_TESTS_UTILS_FUNCTIONS_GENERATOR_HPP #define TIMER_TESTS_UTILS_FUNCTIONS_GENERATOR_HPP #include <vector> #include <bs/io/data-units/concrete/Gather.hpp> namespace bs { namespace io { namespace testutils { /** * @brief Data generator class to generate dummy traces and gathers * for testing purposes. */ class DataGenerator { public: /** * @brief Generates single dummy trace. * @param aNS * @param aFLDR * @return Generated trace */ static dataunits::Trace * GenerateTrace(uint16_t aNS, int32_t aFLDR); /** * @brief Generates vector of dummy traces, by giving number of generated * traces and a starting FLDR value. * @param aNS * @param aCount * @param aStartFLDR * @return Generated trace vector */ static std::vector<dataunits::Trace *> GenerateTraceVector(uint16_t aNS, int aCount, int32_t aStartFLDR); /** * @brief Generates vector of dummy traces, by giving vector of FLDRs. * @param aNS * @param aFLDR * @return Generated trace vector */ static std::vector<dataunits::Trace *> GenerateTraceVector(uint16_t aNS, const std::vector<int32_t> &aFLDR); /** * @brief Generates single dummy gather, by giving number of generated * traces inside and a starting FLDR value. * @param aNS * @param aCount * @param aStartFLDR * @return Generated gather. */ static dataunits::Gather * GenerateGather(uint16_t aNS, int aCount, int32_t aStartFLDR); private: DataGenerator(); }; } //namespace testutils } //namespace io } //namespace bs #endif //TIMER_TESTS_UTILS_FUNCTIONS_GENERATOR_HPP
2,975
C++
.h
74
28.837838
89
0.57128
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,460
GenericSnapshot.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSTimer/include/bs/timer/core/snapshots/helpers/GenericSnapshot.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS Timer. * * BS Timer is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS Timer 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_TIMER_CORE_SNAPSHOTS_SNAPSHOT_FACTORY_HPP #define BS_TIMER_CORE_SNAPSHOTS_SNAPSHOT_FACTORY_HPP #include <bs/timer/core/snapshots/interface/Snapshot.hpp> namespace bs { namespace timer { namespace core { namespace snapshots { /** * @brief Generic Snapshot class used as an abstraction for all kinds of snapshots. * */ class GenericSnapshot : public Snapshot { public: explicit GenericSnapshot(SnapshotTarget aSnapshotTarget = SnapshotTarget::HOST); ~GenericSnapshot() override; double Start() override; double End() override; double Resolve() override; private: Snapshot *mpSnapshot; }; }//namespace snapshot }//namespace core }//namespace timer }//namespace bs #endif // BS_TIMER_CORE_SNAPSHOTS_SNAPSHOT_FACTORY_HPP
1,837
C++
.h
47
29.851064
100
0.626194
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,461
Snapshot.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSTimer/include/bs/timer/core/snapshots/interface/Snapshot.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS Timer. * * BS Timer is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS Timer 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_TIMER_CORE_SNAPSHOT_HPP #define BS_TIMER_CORE_SNAPSHOT_HPP namespace bs { namespace timer { namespace core { namespace snapshots { enum SnapshotTarget { HOST, DEVICE }; /** * @brief Snapshot class used to hold start and end points of execution timer, * until time of resolving and runtime calculation. */ class Snapshot { public: /** * @brief Default destructor. */ virtual ~Snapshot() = default; /** * @brief Updates start state of snapshot at start time of execution timer. * */ virtual double Start() = 0; /** * @brief Updates end state of snapshot at end time of execution timer. * */ virtual double End() = 0; /** * @brief Calculates runtime using start and end points. * @return Runtime */ virtual double Resolve() = 0; }; }//namespace snapshot }//namespace core }//namespace timer }//namespace bs #endif // BS_TIMER_CORE_SNAPSHOT_HPP
2,287
C++
.h
62
24.403226
95
0.523014
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,462
ScopeTimer.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSTimer/include/bs/timer/core/timers/concrete/ScopeTimer.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS Timer. * * BS Timer is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS Timer 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_TIMER_CORE_SCOPE_TIMER_HPP #define BS_TIMER_CORE_SCOPE_TIMER_HPP #include <bs/timer/core/timers/concrete/ElasticTimer.hpp> namespace bs { namespace timer { /** * @brief Traditional execution timer. Takes a channel or channel name to get * constructed. Supports starting ending and pausing the running timer. */ class ScopeTimer : public Timer { public: /** * @brief Constructor that takes a channel object to construct a timer. * @param apChannel * @param aSnapshotTarget */ explicit ScopeTimer(const TimerChannel::Pointer &apChannel, core::snapshots::SnapshotTarget aSnapshotTarget = core::snapshots::SnapshotTarget::HOST); /** * @brief Constructor that takes a channel name to construct a timer. * @param apChannelName * @param aSnapshotTarget */ explicit ScopeTimer(const char *apChannelName, core::snapshots::SnapshotTarget aSnapshotTarget = core::snapshots::SnapshotTarget::HOST); /** * @brief Constructor that takes a channel name and kernel data to construct a timer. * @param apChannelName * @param aGridSize * @param aArrays * @param aSinglePrecision * @param aOperations * @param aSnapshotTarget */ ScopeTimer(const char *apChannelName, int aGridSize, int aArrays, bool aSinglePrecision, int aOperations, core::snapshots::SnapshotTarget aSnapshotTarget = core::snapshots::SnapshotTarget::HOST); /** * @brief Destructor. */ ~ScopeTimer() override; private: int Start() override; int Stop() override; void FlushSnapshot() override; bool IsActive() const override; private: /// Elastic timer instance for internal usage. ElasticTimer *mElasticTimer; }; }//namespace timer } #endif // BS_TIMER_CORE_SCOPE_TIMER_HPP
3,104
C++
.h
80
28.4375
112
0.600332
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,463
LazyTimer.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSTimer/include/bs/timer/core/timers/concrete/LazyTimer.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS Timer. * * BS Timer is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS Timer 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_TIMER_CORE_LAZY_TIMER #define BS_TIMER_CORE_LAZY_TIMER #include <chrono> #include <iostream> #include <iomanip> #include <bs/timer/core/snapshots/helpers/GenericSnapshot.hpp> #include <bs/timer/reporter/TimerReporter.hpp> #include <bs/timer/common/Definitions.hpp> namespace bs { namespace timer { namespace core { /** * @brief Function execution timer. */ class LazyTimer { public: /** * @brief Function execution timer. Takes a block of code as parameter and evaluate * it's run time. Takes a flag that determines whether to print put the execution * time or not. */ template<typename T> static double Evaluate(T f, bool aShowExecutionTime = false, double aPrecision = BS_TIMER_TU_MICRO, core::snapshots::SnapshotTarget aSnapshotTarget = core::snapshots::SnapshotTarget::HOST) { core::snapshots::GenericSnapshot s(aSnapshotTarget); s.Start(); f(); s.End(); auto duration = s.Resolve(); if (aShowExecutionTime) { std::stringstream os; os.precision(5); os << std::left << std::setfill(' ') << std::setw(20) << "Lazy Timer Runtime" << ": " << std::left << std::setfill(' ') << std::setw(12) << std::scientific << duration / aPrecision << reporter::TimerReporter::PrecisionToUnit(aPrecision) << std::endl; std::cout << os.str(); } return duration; } }; }//namespace core }//namespace timer }//namespace bs #endif // BS_TIMER_CORE_LAZY_TIMER
2,783
C++
.h
67
29.940299
115
0.561669
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,464
ElasticTimer.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSTimer/include/bs/timer/core/timers/concrete/ElasticTimer.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS Timer. * * BS Timer is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS Timer 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_TIMER_CORE_ELASTIC_TIMER_HPP #define BS_TIMER_CORE_ELASTIC_TIMER_HPP #include <bs/timer/core/timers/interface/Timer.hpp> #include <bs/timer/core/snapshots/interface/Snapshot.hpp> #include <bs/timer/configurations/TimerChannel.hpp> namespace bs { namespace timer { /** * @brief Traditional execution timer. Takes a channel or channel name to get * constructed. Supports starting ending and pausing the running timer. */ class ElasticTimer : public Timer { public: /** * @brief Constructor that takes a channel object to construct a timer. * @param apChannel * @param aSnapshotTarget */ explicit ElasticTimer(const TimerChannel::Pointer &apChannel, core::snapshots::SnapshotTarget aSnapshotTarget = core::snapshots::SnapshotTarget::HOST); /** * @brief Constructor that takes a channel name to construct a timer. * @param apChannelName * @param aSnapshotTarget */ explicit ElasticTimer(const char *apChannelName, core::snapshots::SnapshotTarget aSnapshotTarget = core::snapshots::SnapshotTarget::HOST); /** * @brief Constructor that takes a channel name and kernel data to construct a timer. * @param apChannelName * @param aGridSize * @param aArrays * @param aSinglePrecision * @param aOperations * @param aSnapshotTarget */ ElasticTimer(const char *apChannelName, int aGridSize, int aArrays, bool aSinglePrecision, int aOperations, core::snapshots::SnapshotTarget aSnapshotTarget = core::snapshots::SnapshotTarget::HOST); /** * @brief Destructor. */ ~ElasticTimer() override; /** * @brief Starts the timer for the corresponding channel accompanied with this timer. * @return Status flag. */ int Start() override; /** * @brief Ends the timer for the corresponding channel accompanied with this timer. * @return Status flag. */ int Stop() override; /** * @brief * Flushes data object of this timer object to the accompanied TimerChannel object. */ void FlushSnapshot() override; /** * * @return * Flag to indicate if this timer object is currently active. */ bool IsActive() const override; private: /// The corresponding channel accompanied with this timer. TimerChannel::Pointer mpChannel; /// Activation flag bool mIsActive; ///Snapshot handler object. core::snapshots::Snapshot *mpSnapshot; }; }//namespace timer }//namespace bs #endif // BS_TIMER_CORE_ELASTIC_TIMER_HPP
4,026
C++
.h
102
28.470588
114
0.58798
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,465
Timer.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSTimer/include/bs/timer/core/timers/interface/Timer.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS Timer. * * BS Timer is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS Timer 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_TIMER_CORE_TIMER_HPP #define BS_TIMER_CORE_TIMER_HPP namespace bs { namespace timer { /** * @brief Traditional execution timer. Takes a channel or channel name to get * constructed. Supports starting ending and pausing the running timer. */ class Timer { public: /** * @brief Destructor. */ virtual ~Timer() = default; /** * @brief Starts the timer for the corresponding channel accompanied with this timer. * @return Status flag. */ virtual int Start() = 0; /** * @brief Ends the timer for the corresponding channel accompanied with this timer. * @return Status flag. */ virtual int Stop() = 0; /** * @brief * Flushes data object of this timer object to the accompanied TimerChannel object. */ virtual void FlushSnapshot() = 0; /** * * @return * Flag to indicate if this timer object is currently active. */ virtual bool IsActive() const = 0; }; }//namespace timer }//namespace bs #endif // BS_TIMER_CORE_TIMER_HPP
2,106
C++
.h
61
26.04918
97
0.595776
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,466
ChannelStats.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSTimer/include/bs/timer/data-units/ChannelStats.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS Timer. * * BS Timer is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS Timer 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_TIMER_DATA_UNITS_CHANNEL_STATS_HPP #define BS_TIMER_DATA_UNITS_CHANNEL_STATS_HPP #include <map> #include <bs/timer/utils/stats/StatisticsHelper.hpp> #include <bs/timer/common/Definitions.hpp> #include <bs/timer/core/snapshots/interface/Snapshot.hpp> namespace bs { namespace timer { namespace dataunits { /** * @brief Class to hold all data and statistics accompanied with a channel. * */ class ChannelStats { public: /** * @brief Constructor. */ ChannelStats(); /** * @brief Destructor. */ ~ChannelStats(); /** * @brief Adds a runtime value to the vector of runtimes accompanied to channel. * @param aRuntime */ void AddRuntime(double aRuntime); /** * @brief Adds a snapshot object to channel. * @param apSnapshot */ void AddSnapshot(core::snapshots::Snapshot *apSnapshot); /** * @brief Calls all resolve functions of current snapshots */ void Resolve(); /** * @brief Setter * @param aGridSize */ void SetGridSize(int aGridSize); /** * @brief Setter * @param aDataSize */ void SetDataSize(int aDataSize); /** * @brief Setter * @param aFLOPS */ void SetFLOPS(int aFLOPS); /** * @brief Returns a map of all statistics of the channel object. */ std::map<std::string, double> GetMap(); /** * @brief Calculates maximum runtime. */ double GetMaxRuntime(); /** * @brief Calculates minimum runtime. */ double GetMinRuntime(); /** * @brief Calculates average runtime. */ double GetAverageRuntime(); /** * @brief Calculates variance in runtimes. */ double GetVariance(); /** * @brief Calculates deviation in runtimes. * */ double GetDeviation(); /** * @brief Calculates total runtime. */ double GetTotal(); /** * @return Vector of runtimes. */ std::vector<double> GetRuntimes(); /** * @return Vector of bandwidths. */ std::vector<double> GetBandwidths(); /** * @return Number of calls for a function. */ unsigned int GetNumberOfCalls() const; /** * @brief Grid size getter. */ int GetGridSize() const; /** * @brief Data size getter. */ int GetDataSize() const; /** * @brief Maximum bandwidth getter. * @note Returned value is in Byte. */ double GetMaxBandwidth(); /** * @brief Minimum bandwidth getter. * @note Returned value is in Byte. */ double GetMinBandwidth(); /** * @brief Average bandwidth getter. * @note Returned value is in Byte. */ double GetAverageBandwidth(); /** * @brief Maximum throughput getter. */ double GetMaxThroughput(); /** * @brief Minimum throughput getter. */ double GetMinThroughput(); /** * @brief Average throughput getter. */ double GetAverageThroughput(); /** * @brief Minimum GFLOPS getter. * @note Returned value is in Giga unit. */ double GetMinGFLOPS(); /** * @brief Maximum GFLOPS getter. * @note Returned value is in Giga unit. */ double GetMaxGFLOPS(); /** * @brief Average GFLOPS getter. * @note Returned value is in Giga unit. */ double GetAverageGFLOPS(); /** * @brief Number of operations getter. */ int GetNumberOfOperations() const; private: /// A map that holds all statistics of a channel object. std::map<std::string, double> mStatisticsMap; /// Vector of runtimes accompanied with a channel object. std::vector<double> mRuntimes; /// Vector of bandwidths std::vector<double> mBandwidths; /// Number of times the function is called. unsigned int mNumberOfCalls; /// Vector of snapshots accompanied with this timer. std::vector<core::snapshots::Snapshot *> mSnapshots; /// Grid size int mGridSize; /// Size of data int mDataSize; /// Number of floating point operations per iteration int mFLOPS; /// Flag to determine if this channel has been resolved bool mResolved = false; }; }//namespace data }//namespace timer }//namespace bs #endif // BS_TIMER_DATA_UNITS_CHANNEL_STATS_HPP
7,447
C++
.h
217
19.0553
96
0.438777
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,467
StatisticsHelper.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSTimer/include/bs/timer/utils/stats/StatisticsHelper.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS Timer. * * BS Timer is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS Timer 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_TIMER_UTILS_STATISTICS_HELPER_HPP #define BS_TIMER_UTILS_STATISTICS_HELPER_HPP #include <vector> #include <cmath> #include <type_traits> #include <bs/base/common/assertions.h> namespace bs { namespace timer { namespace utils { namespace stats { /** * @brief Statistics helper class. Serves all statistical methods, like min, max, * variance, deviation and so on. */ class StatisticsHelper { public: /** * @brief Takes a vector of longs/doubles and returns its maximum. */ template<typename T> static T GetMax(const std::vector<T> aNums) { T max = 0; if (!aNums.empty()) { ASSERT_IS_POD(T); max = aNums.at(0); for (auto element: aNums) { if (element > max) max = element; } } return max; } /** * @brief Takes a vector of longs/doubles and returns its minimum. */ template<typename T> static T GetMin(const std::vector<T> aNums) { T min = 0; if (!aNums.empty()) { ASSERT_IS_POD(T); min = aNums.at(0); for (auto element: aNums) { if (element < min) { min = element; } } } return min; } /** * @brief Takes a vector of longs/doubles and returns its total. */ template<typename T> static T GetTotal(const std::vector<T> aNums) { T total = 0; if (!aNums.empty()) { ASSERT_IS_POD(T); for (auto element: aNums) { total += element; } } return total; } /** * @brief Takes a vector of longs/doubles and returns its average. */ template<typename T> static double GetAverage(const std::vector<T> &aNums) { double average = 0; if (!aNums.empty()) { ASSERT_IS_POD(T); double total = 0; for (auto element : aNums) { total += element; } average = total / aNums.size(); } return average; } /** * @brief Takes a vector of longs/doubles and returns its variance. */ template<typename T> static double GetVariance(const std::vector<T> &aNums) { double variance = 0; if (!aNums.empty()) { ASSERT_IS_POD(T); auto mean = GetAverage(aNums); double total = 0; for (auto element : aNums) { total += pow((element - mean), 2); } variance = total / aNums.size(); } return variance; } /** * @brief Takes a vector of longs/doubles and returns its deviation. */ template<typename T> static double GetDeviation(const std::vector<T> &aNums) { double deviation = 0; if (!aNums.empty()) { deviation = sqrt(GetVariance(aNums)); } return deviation; } private: /** * @brief Private constructor for preventing objects creation. */ StatisticsHelper() = default; }; }//namespace stats }//namespace utils }//namespace timer }//namespace bs #endif // BS_TIMER_UTILS_STATISTICS_HELPER_HPP
5,802
C++
.h
142
21.366197
97
0.399327
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,468
Definitions.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSTimer/include/bs/timer/common/Definitions.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS Timer. * * BS Timer is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS Timer 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_TIMER_LIB_VARS_DEFINITIONS_HPP #define BS_TIMER_LIB_VARS_DEFINITIONS_HPP namespace bs { namespace timer { namespace libvars { namespace definitions { #define BS_TIMER_EXT ".bs.timer" /* Extension used for flushed files.*/ #define BS_TIMER_TU_MILLI 1e-3 /* The conversion unit used for converting seconds to milliseconds. */ #define BS_TIMER_TU_MICRO 1e-6 /* The conversion unit used for converting seconds to microseconds. */ #define BS_TIMER_TU_NANO 1e-9 /* The conversion unit used for converting seconds to nanoseconds. */ #define BS_TIMER_TU_STR_MILLI "msec" #define BS_TIMER_TU_STR_MICRO "μsec" #define BS_TIMER_TU_STR_NANO "nsec" #define BS_TIMER_TU_STR_SEC "sec" #define BS_TIMER_K_TIME_UNIT "precision" /* Key for time unit. */ #define BS_TIMER_K_PROPERTIES "properties" /* Key for properties. */ #define BS_TIMER_K_MAX_RUNTIME "max_runtime" /* Key for maximum runtime. */ #define BS_TIMER_K_MAX_BANDWIDTH "max_bandwidth" /* Key for maximum bandwidth. */ #define BS_TIMER_K_MAX_THROUGHPUT "max_throughput" /* Key for maximum throughput. */ #define BS_TIMER_K_MAX_GFLOPS "max_gflops" /* Key for maximum GFLOPS. */ #define BS_TIMER_K_MIN_RUNTIME "min_runtime" /* Key for minimum runtime. */ #define BS_TIMER_K_MIN_BANDWIDTH "min_bandwidth" /* Key for minimum bandwidth. */ #define BS_TIMER_K_MIN_THROUGHPUT "min_throughput" /* Key for minimum throughput. */ #define BS_TIMER_K_MIN_GFLOPS "min_gflops" /* Key for minimum GFLOPS. */ #define BS_TIMER_K_AVERAGE_RUNTIME "average_runtime" /* Key for average runtime. */ #define BS_TIMER_K_AVERAGE_BANDWIDTH "average_bandwidth" /* Key for average runtime. */ #define BS_TIMER_K_AVERAGE_THROUGHPUT "average_throughput" /* Key for average throughput. */ #define BS_TIMER_K_AVERAGE_GFLOPS "average_gflops" /* Key for average GFLOPS. */ #define BS_TIMER_K_VARIANCE "variance" /* Key for variance in runtimes. */ #define BS_TIMER_K_DEVIATION "deviation" /* Key for deviation in runtimes. */ #define BS_TIMER_K_TOTAL "total" /* Key for total runtime. */ #define BS_TIMER_K_OPERATIONS "operations" /* Key for number of operations. */ } //namespace definitions } //namespace libvars } //namespace timer }//namespace bs #endif // BS_TIMER_LIB_VARS_DEFINITIONS_HPP
3,529
C++
.h
55
61.836364
135
0.627525
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,469
TimerManager.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSTimer/include/bs/timer/configurations/TimerManager.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS Timer. * * BS Timer is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS Timer 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_TIMER_CONFIGURATIONS_MANGER_HPP #define BS_TIMER_CONFIGURATIONS_MANGER_HPP #include <bs/base//common/Singleton.tpp> #include <bs/base/configurations/interface/ConfigurationMap.hpp> #include <bs/base/configurations/interface/Configurable.hpp> #include <bs/timer/configurations/TimerChannel.hpp> #include <bs/timer/core/timers/interface/Timer.hpp> #include <bs/timer/reporter/TimerReporter.hpp> namespace bs { namespace timer { namespace configurations { /** * @brief * The singleton class that manage the registered channels and outputs * <br> * The TimerManager keeps a map of all the named TimerChannel objects * and share them on demand by new Timer objects created with the same name. * <br> * Thus the TimerManager is able to change the Severity Level of selected TimerChannel object, * impacting all the Timer objects using it. * <br> * The TimerManager also keeps a list of all configured output object to output the Timer objects. */ class TimerManager : public bs::base::common::Singleton<TimerManager>, public bs::base::configurations::Configurable { public: friend class bs::base::common::Singleton<TimerManager>; public: /** * @brief Setting the configuration to manipulate all configurable objects. * @param apConfigurationList * */ void Configure(bs::base::configurations::ConfigurationMap *apConfigurationMap); /** * @brief Terminates all active timers. * @param aCleanup * Boolean to indicate whether cleanup is to be performed after termination. */ void Terminate(bool aCleanup = false); /** * * @param apChannelName * @return Pointer to channel object with the input name. * */ TimerChannel::Pointer Get(const char *apChannelName); /** * @brief * Free all channel objects kept by manager. */ void Cleanup(); /** * * @return * A list of all active timers registered to all channel objects kept by manager. */ std::vector<Timer *> GetActiveTimers(); /** * @brief Reporting using a collection of output streams. * @param aStreams * @param aChannelName * @return Status flag. */ int Report(const std::vector<std::ostream *> &aStreams, const std::string &aChannelName = " "); /** * @brief Uses reporter module to generate report for a given channel, or all * managed channels(default), and flushes report using given output stream. * @param aOutputStream * @param aChannelName * @return Status flag. */ std::string Report(std::ostream &aOutputStream, const std::string &aChannelName = " "); TimerChannel::Map GetMap(); void RegisterChannel(const TimerChannel::Pointer &apChannel); /** * @brief Getter for time precision. * */ double GetPrecision(); private: /** * @brief Default constructor. * @note Private constructor for Singleton purposes. */ TimerManager() = default; /** * @brief Acquires timer configuration from configuration map. */ void AcquireConfiguration() override; private: /// Map of all TimerChannel objects. TimerChannel::Map mChannelMap; /// Configuration map. bs::base::configurations::ConfigurationMap *mpConfigurationMap; /// Time precision. double mTimePrecision = 1; }; } //namespace configurations } //namespace timer }//namespace bs #endif // BS_TIMER_CONFIGURATIONS_MANGER_HPP
5,419
C++
.h
128
29.078125
109
0.554775
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,470
TimerChannel.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSTimer/include/bs/timer/configurations/TimerChannel.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS Timer. * * BS Timer is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS Timer 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_TIMER_CORE_CHANNEL_HPP #define BS_TIMER_CORE_CHANNEL_HPP #include <memory> #include <bs/timer/core/timers/interface/Timer.hpp> #include <bs/timer/data-units/ChannelStats.hpp> #include <bs/timer/core/snapshots/interface/Snapshot.hpp> namespace bs { namespace timer { /** * @brief TimerChannel shared by Timer objects using the same name * <br> * A TimerChannel is the underlying object used by one or many Timer objects to * associate a named prefix. * <br> */ class Timer; class TimerChannel { public: typedef std::shared_ptr<TimerChannel> Pointer; typedef std::map<const std::string, TimerChannel::Pointer> Map; public: /** * @brief Default constructor. */ TimerChannel() = default; /** * @brief Constructor that takes a name for this TimerChannel. */ explicit TimerChannel(std::string apName, int aGridSize = -1, int aDataSize = -1, int aFLOPS = -1) : mName(std::move(apName)) { this->mChannelStats.SetDataSize(aDataSize); this->mChannelStats.SetGridSize(aGridSize); this->mChannelStats.SetFLOPS(aFLOPS); } /** * Destructor. */ ~TimerChannel(); /** * @return TimerChannel name. */ inline std::string GetName() const { return this->mName; } /** * @return Vector of pointers to Timer objects registered to this channel. */ std::vector<Timer *> GetTimers() const { return this->mTimers; } /** * @brief * Registers a timer object to this channel. * * @param apTimer * Pointer to Timer object to add. */ void AddTimer(Timer *apTimer); /** * @brief Removes a timer object from channel. * @param apTimer: Pointer to timer object to be removed. */ void RemoveTimer(Timer *apTimer); /** * * @param apSnapshot * Pointer to Snapshot accompanied to this channel to be added. */ void AddSnapshot(core::snapshots::Snapshot *apSnapshot); /** * @brief Returns a ChannelStats object holding all data regarding this channel. * @return ChannelStats */ dataunits::ChannelStats & GetChannelStats(); private: /// TimerChannel name. const std::string mName; /// Timer objects registered to this channel. std::vector<Timer *> mTimers; /// Data objects accompanied with this channel. dataunits::ChannelStats mChannelStats; }; }//namespace timer }//namespace bs #endif // BS_TIMER_CORE_CHANNEL_HPP
3,966
C++
.h
108
25.944444
92
0.562093
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,471
BSTimer.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSTimer/include/bs/timer/api/cpp/BSTimer.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS Timer. * * BS Timer is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS Timer 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_TIMER_API_CPP_BS_TIMER_H #define BS_TIMER_API_CPP_BS_TIMER_H /// COMMON #include <bs/timer/common/Definitions.hpp> /// CONFIGURATIONS #include <bs/timer/configurations/TimerManager.hpp> /// TIMERS #include <bs/timer/core/timers/concrete/ElasticTimer.hpp> #include <bs/timer/core/timers/concrete/ScopeTimer.hpp> #include <bs/timer/core/timers/concrete/LazyTimer.hpp> /// SNAPSHOTS #include <bs/timer/core/snapshots/helpers/GenericSnapshot.hpp> /// UTILS #include <bs/timer/utils/stats/StatisticsHelper.hpp> #endif // BS_TIMER_API_CPP_BS_TIMER_H
1,302
C++
.h
33
37.727273
73
0.770206
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,472
TimerReporter.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSTimer/include/bs/timer/reporter/TimerReporter.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS Timer. * * BS Timer is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS Timer 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_TIMER_REPORTER_REPORTER_HPP #define BS_TIMER_REPORTER_REPORTER_HPP #include <bs/timer/configurations/TimerChannel.hpp> #include <bs/timer/configurations/TimerManager.hpp> #include <bs/timer/utils/stats/StatisticsHelper.hpp> namespace bs { namespace timer { namespace reporter { /** * @brief Reporter interface to be implemented by all reporters. */ class TimerReporter { public: /** * @brief * Constructor. */ TimerReporter(); /** * @brief Default destructor. */ ~TimerReporter() = default; /** * @brief * Generates a report stream for certain channel. * @param aChannelName * @return String generated. * */ std::string GenerateStream(std::ostream &aOutputStream, const std::string &aChannelName = " "); /** * @brief Flushes report for all channels to be used by Python loader. * @return */ int FlushReport(const std::string &aFilePath); /** * @param aChannelName * @return Report map of given channel. */ std::map<std::string, double> GetMap(const std::string &aChannelName); /** * @brief Channel Statistics getter. */ std::map<std::string, dataunits::ChannelStats> GetStats(); /** * @brief Resolves all snapshots for reporting. */ void Resolve(); /** * @brief Precision given as number to unit given as string. */ static std::string PrecisionToUnit(double aPrecision); private: static int HandleFilePath(const std::string &aFilePath); private: ///Map of channels and their accompanied stats. std::map<std::string, dataunits::ChannelStats> mDataMap; }; } //namespace reporter }//namespace timer }//namespace bs #endif // BS_TIMER_REPORTER_REPORTER_HPP
3,247
C++
.h
87
25.298851
99
0.540515
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,473
FunctionsGenerator.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSTimer/tests/test-utils/include/bs/timer/test-utils/FunctionsGenerator.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS Timer. * * BS Timer is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS Timer 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_TIMER_TESTS_UTILS_FUNCTIONS_GENERATOR_HPP #define BS_TIMER_TESTS_UTILS_FUNCTIONS_GENERATOR_HPP namespace bs { namespace timer { namespace testutils { void target_technology_test_function(); void test_function(); } //namespace testutils } //namespace timer } //namespace bs #endif // BS_TIMER_TESTS_UTILS_FUNCTIONS_GENERATOR_HPP
1,157
C++
.h
31
33.258065
73
0.722321
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,474
OmpFunctionsGenerator.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSTimer/tests/test-utils/src/concrete/omp/OmpFunctionsGenerator.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS Timer. * * BS Timer is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS Timer 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_TIMER_TESTS_UTILS_OMP_FUNCTIONS_GENERATOR_HPP #define BS_TIMER_TESTS_UTILS_OMP_FUNCTIONS_GENERATOR_HPP namespace bs { namespace timer { namespace testutils { void omp_test_function(); } //namespace testutils } //namespace timer } //namespace bs #endif //BS_TIMER_TESTS_UTILS_OMP_FUNCTIONS_GENERATOR_HPP
1,107
C++
.h
29
34.758621
73
0.735322
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,475
SerialFunctionsGenerator.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSTimer/tests/test-utils/src/concrete/serial/SerialFunctionsGenerator.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS Timer. * * BS Timer is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS Timer 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_TIMER_TESTS_UTILS_SERIAL_FUNCTIONS_GENERATOR_HPP #define BS_TIMER_TESTS_UTILS_SERIAL_FUNCTIONS_GENERATOR_HPP namespace bs { namespace timer { namespace testutils { void serial_test_function(); } //namespace testutils } //namespace timer } //namespace bs #endif //BS_TIMER_TESTS_UTILS_SERIAL_FUNCTIONS_GENERATOR_HPP
1,119
C++
.h
29
35.172414
73
0.738249
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,476
OmpSnapshot.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSTimer/src/core/snapshots/concrete/omp/OmpSnapshot.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS Timer. * * BS Timer is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS Timer 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_TIMER_CORE_SNAPSHOT_OMP_SNAPSHOT_HPP #define BS_TIMER_CORE_SNAPSHOT_OMP_SNAPSHOT_HPP #include <omp.h> #include <bs/timer/core/snapshots/interface/Snapshot.hpp> namespace bs { namespace timer { namespace core { namespace snapshots { /** * @brief The snapshot class for timers timing OpenMp backends. * */ class OmpSnapshot : public Snapshot { public: explicit OmpSnapshot(SnapshotTarget aSnapshotTarget = SnapshotTarget::HOST); ~OmpSnapshot() override; double Start() override; double End() override; double Resolve() override; private: /// Starting time. double mStart; /// End time. double mEnd; }; }//namespace snapshot }//namespace core }//namespace timer }//namespace bs #endif // BS_TIMER_CORE_SNAPSHOT_OMP_SNAPSHOT_HPP
1,907
C++
.h
51
27.607843
96
0.599241
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,477
SerialSnapshot.hpp
brightskiesinc_Reverse_Time_Migration/libs/BSTimer/src/core/snapshots/concrete/serial/SerialSnapshot.hpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS Timer. * * BS Timer is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS Timer 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_TIMER_SNAPSHOT_SERIAL_SNAPSHOT_HPP #define BS_TIMER_SNAPSHOT_SERIAL_SNAPSHOT_HPP #include <chrono> #include <bs/timer/core/snapshots/interface/Snapshot.hpp> namespace bs { namespace timer { namespace core { namespace snapshots { /** * @brief The snapshot class for timers timing serial execution of code. * */ class SerialSnapshot : public Snapshot { public: explicit SerialSnapshot(SnapshotTarget aSnapshotTarget = SnapshotTarget::HOST); ~SerialSnapshot() override; double Start() override; double End() override; double Resolve() override; private: /// Start time std::chrono::high_resolution_clock::time_point mStartPoint; /// End time std::chrono::high_resolution_clock::time_point mEndPoint; }; }//namespace snapshot }//namespace core }//namespace timer }//namespace bs #endif // BS_TIMER_SNAPSHOT_SERIAL_SNAPSHOT_HPP
2,003
C++
.h
51
29.529412
99
0.612255
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,478
utils.h
brightskiesinc_Reverse_Time_Migration/tests/test-utils/include/stbx/test-utils/utils.h
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of SeismicToolbox. * * SeismicToolbox is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SeismicToolbox 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SEISMIC_TOOLBOX_TESTS_TEST_UTILS_UTILS_H #define SEISMIC_TOOLBOX_TESTS_TEST_UTILS_UTILS_H #include <string> namespace stbx { namespace testutils { template<typename Base, typename T> inline bool instanceof(const T *) { return std::is_base_of<Base, T>::value; } } //namespace testutils } //namespace stbx #endif //SEISMIC_TOOLBOX_TESTS_TEST_UTILS_UTILS_H
1,168
C++
.h
30
35.766667
76
0.741623
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,479
Singleton.tpp
brightskiesinc_Reverse_Time_Migration/libs/BSBase/include/bs/base/common/Singleton.tpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of BS Base Package. * * BS Base Package is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BS Base Package 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BS_BASE_COMMON_SINGLETON_TPP #define BS_BASE_COMMON_SINGLETON_TPP namespace bs { namespace base { namespace common { /** * @brief Template class for any singleton class to inherit. * @tparam[in] T The type for the singleton pattern to be applied to. */ template<typename T> class Singleton { public: /** * @brief Static function to obtain the instance of the singleton to use. * @return An instance of the singleton. */ static T *GetInstance() { if (_INSTANCE == nullptr) { _INSTANCE = new T; } return _INSTANCE; } /** * @brief Destroy the active instance of the singleton. */ static void Kill() { if (_INSTANCE != nullptr) { delete _INSTANCE; _INSTANCE = nullptr; } } protected: /** * @brief Default constructor. */ Singleton() = default; /** * @brief Default Destructor. */ ~Singleton() = default; private: /// The instance to utilize in the class. static T *_INSTANCE; }; template<typename T> T *Singleton<T>::_INSTANCE = nullptr; } //common } //namespace base } //namespace bs #endif //BS_BASE_COMMON_SINGLETON_TPP
2,473
C++
.tpp
67
25.432836
89
0.536921
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,480
ComponentsMap.tpp
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/include/operations/components/dependency/helpers/ComponentsMap.tpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of SeismicToolbox. * * SeismicToolbox is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SeismicToolbox 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef OPERATIONS_LIB_COMPONENTS_DEPENDENT_COMPONENTS_MAP_TPP #define OPERATIONS_LIB_COMPONENTS_DEPENDENT_COMPONENTS_MAP_TPP #include <vector> #include <map> #include <bs/base/exceptions/Exceptions.hpp> #include <operations/components/dependents/interface/DependentComponent.hpp> namespace operations { namespace helpers { template<typename T> class ComponentsMap { public: ~ComponentsMap() = default; void Set(uint key, T *apDependentComponent) { this->mComponentsMap[key] = apDependentComponent; } T *Get(uint key) { if (this->mComponentsMap.find(key) == this->mComponentsMap.end()) { throw bs::base::exceptions::NO_KEY_FOUND_EXCEPTION(); } return this->mComponentsMap[key]; } std::vector<T *> ExtractValues() { std::vector<T *> values; for (auto const &dependent_components : this->mComponentsMap) { values.push_back(dependent_components.second); } return values; } private: std::map<uint, T *> mComponentsMap; }; /* * Indices. */ #define MEMORY_HANDLER 0 #define MODEL_HANDLER 1 #define COMPUTATION_KERNEL 2 #define MIGRATION_ACCOMMODATOR 3 #define BOUNDARY_MANAGER 4 #define SOURCE_INJECTOR 5 #define TRACE_MANAGER 6 #define FORWARD_COLLECTOR 11 #define TRACE_WRITER 12 #define MODELLING_CONFIG_PARSER 13 }//namespace helpers }//namespace operations #endif //OPERATIONS_LIB_COMPONENTS_DEPENDENT_COMPONENTS_MAP_TPP
2,427
C++
.tpp
66
30.227273
79
0.676897
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,481
Singleton.tpp
brightskiesinc_Reverse_Time_Migration/libs/SeismicOperations/include/operations/common/Singleton.tpp
/** * Copyright (C) 2021 by Brightskies inc * * This file is part of SeismicToolbox. * * SeismicToolbox is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SeismicToolbox 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEDLIB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef OPERATIONS_LIB_BASE_SINGLETON_HPP #define OPERATIONS_LIB_BASE_SINGLETON_HPP #include <iostream> namespace operations { namespace common { /** * @brief Template class for any singleton class to inherit. * @tparam[in] T The type for the singleton pattern to be applied to. */ template<typename T> class Singleton { public: /** * @brief Static function to obtain the instance of the singleton to use. * @return An instance of the singleton. */ static T *GetInstance() { if (INSTANCE == nullptr) { INSTANCE = new T; } return INSTANCE; } /** * @brief Destroy the active instance of the singleton. */ static T *Kill() { if (INSTANCE != nullptr) { delete INSTANCE; INSTANCE = nullptr; } return INSTANCE; } protected: /** * @brief Default constructor. */ Singleton() = default; /** * @brief Default Destructor. */ ~Singleton() = default; private: /// The instance to utilize in the class. static T *INSTANCE; }; template<typename T> T *Singleton<T>::INSTANCE = nullptr; }//namespace common }//namespace operations #endif //OPERATIONS_LIB_BASE_SINGLETON_HPP
2,310
C++
.tpp
67
25.835821
85
0.595878
brightskiesinc/Reverse_Time_Migration
36
6
0
LGPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,482
BSchaffl.cpp
sjaehn_BSchaffl/src/BSchaffl.cpp
/* B.Schaffl * MIDI Pattern Delay Plugin * * Copyright (C) 2018 - 2020 by Sven Jähnichen * * 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, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "BSchaffl.hpp" #include <cstdio> #include <string> #include <ctime> #include <stdexcept> #include <algorithm> #include "BUtilities/stof.hpp" #include "SharedData.hpp" #define LIM(g , min, max) ((g) > (max) ? (max) : ((g) < (min) ? (min) : (g))) static SharedData sharedData[4] = {SharedData(), SharedData(), SharedData(), SharedData()}; BSchaffl::BSchaffl (double samplerate, const LV2_Feature* const* features) : map(NULL), rate(samplerate), bpm(120.0f), speed(1), bar (0), barBeat (0), beatsPerBar (4), beatUnit (4), positionSeq (0.0), latencySeq (0.0), latencyFr (0), refFrame(0), uiOn (false), actStep (-1), mcg (time (0)), distribution (0.0, 1.0), midiData (), input(NULL), output(NULL), sharedDataNr (0), controllerPtrs {nullptr}, controllers {0.0f}, stepPositions {0.0}, shape {Shape<MAXNODES>()}, message (), notify_shape (true), notify_sharedData (false), notify_controllers {false} { // Init array members std::fill (stepAutoPositions, stepAutoPositions + MAXSTEPS - 1, true); std::fill (stepRnds, stepRnds + MAXSTEPS - 1, 1.0); shape.setDefaultShape (); //Scan host features for URID map LV2_URID_Map* m = NULL; for (int i = 0; features[i]; ++i) { if (strcmp(features[i]->URI, LV2_URID__map) == 0) { m = (LV2_URID_Map*) features[i]->data; } } if (!m) throw std::invalid_argument ("Host does not support urid:map"); //Map URIS map = m; getURIs (m, &uris); // Initialize forge lv2_atom_forge_init (&forge,map); recalculateAutoPositions (); } BSchaffl::~BSchaffl () { if ((sharedDataNr > 0) && (sharedDataNr <= 4)) sharedData[sharedDataNr - 1].unlink (this); } void BSchaffl::connect_port(uint32_t port, void *data) { switch (port) { case INPUT: input = (LV2_Atom_Sequence*) data; break; case OUTPUT: output = (LV2_Atom_Sequence*) data; break; default: if ((port >= CONTROLLERS) && (port < CONTROLLERS + NR_CONTROLLERS)) { controllerPtrs[port - CONTROLLERS] = (float*) data; } } } void BSchaffl::run (uint32_t n_samples) { // Check ports if ((!input) || (!output)) return; for (int i = 0; i < NR_CONTROLLERS; ++i) { if (!controllerPtrs[i]) return; } // Update controller values for (int i = 0; i < LATENCY; ++i) { float newValue = getControllerInput (sharedDataNr, i); if (newValue != controllers[i]) { setController (i, newValue); if ((sharedDataNr >= 1) && (sharedDataNr <= 4)) notify_controllers[i] = true; } } // Update shape if ((sharedDataNr > 0) && (sharedDataNr <= 4) && (shape != sharedData[sharedDataNr - 1].shape)) { shape = sharedData[sharedDataNr - 1].shape; notify_shape = true; } recalculateLatency(); *controllerPtrs[LATENCY] = latencyFr; if (latencyFr > 192000) message.setMessage (LATENCY_MAX_MSG); else message.deleteMessage (LATENCY_MAX_MSG); // Prepare forge buffer and initialize atom sequence const uint32_t space = output->atom.size; lv2_atom_forge_set_buffer(&forge, (uint8_t*) output, space); lv2_atom_forge_sequence_head(&forge, &frame, 0); uint32_t last_t =0; // Process audio data LV2_ATOM_SEQUENCE_FOREACH (input, ev) { if ((ev->body.type == uris.atom_Object) || (ev->body.type == uris.atom_Blank)) { bool scheduleUpdatePosition = false; const LV2_Atom_Object* obj = (const LV2_Atom_Object*)&ev->body; // GUI on if (obj->body.otype == uris.bschaffl_uiOn) { uiOn = true; notify_shape = true; notify_sharedData = true; std::fill (notify_controllers, notify_controllers + NR_CONTROLLERS, true); } // GUI off else if (obj->body.otype == uris.bschaffl_uiOff) uiOn = false; // Linked / unlinked to shared data else if (obj->body.otype == uris.bschaffl_sharedDataLinkEvent) { LV2_Atom *oNr = NULL; lv2_atom_object_get ( obj, uris.bschaffl_sharedDataNr, &oNr, NULL ); if (oNr && (oNr->type == uris.atom_Int)) { const int nr = ((LV2_Atom_Int*)oNr)->body; if ((nr >= 0) && (nr <= 4) && (nr != sharedDataNr)) { if (sharedDataNr != 0) sharedData[sharedDataNr - 1].unlink (this); if ((nr != 0) && sharedData[nr - 1].empty()) { for (int i = 0; i < NR_CONTROLLERS; ++i) sharedData[nr - 1].set (i, controllers[i]); } if (nr != 0) sharedData[nr - 1].link (this); sharedDataNr = nr; notify_sharedData = true; for (int i = 0; i < NR_CONTROLLERS; ++i) { float newValue = getControllerInput (sharedDataNr, i); if (newValue != controllers[i]) { setController (i, newValue); notify_controllers[i] = true; } } } } } // Controller changed else if ((obj->body.otype == uris.bschaffl_controllerEvent) && (sharedDataNr != 0)) { LV2_Atom *oNr = NULL, *oVal = NULL; lv2_atom_object_get ( obj, uris.bschaffl_controllerNr, &oNr, uris.bschaffl_controllerValue, &oVal, NULL ); if (oNr && (oNr->type == uris.atom_Int) && oVal && (oVal->type == uris.atom_Float)) { const int nr = ((LV2_Atom_Int*)oNr)->body; if ((nr >= 0) && (nr < NR_CONTROLLERS)) { const float val = controllerLimits[nr].validate(((LV2_Atom_Float*)oVal)->body); if ((sharedDataNr > 0) && (sharedDataNr <= 4)) sharedData[sharedDataNr - 1].set (nr, val); setController (nr, val); } } } // Update time/position data else if (obj->body.otype == uris.time_Position) { LV2_Atom *oBbeat = NULL, *oBpm = NULL, *oSpeed = NULL, *oBpb = NULL, *oBu = NULL, *oBar = NULL; lv2_atom_object_get ( obj, uris.time_barBeat, &oBbeat, uris.time_beatsPerMinute, &oBpm, uris.time_beatsPerBar, &oBpb, uris.time_beatUnit, &oBu, uris.time_bar, &oBar, uris.time_speed, &oSpeed, NULL); // BPM changed? if (oBpm && (oBpm->type == uris.atom_Float) && (((LV2_Atom_Float*)oBpm)->body != bpm)) { bpm = ((LV2_Atom_Float*)oBpm)->body; scheduleUpdatePosition = true; if (bpm < 1.0) message.setMessage (JACK_STOP_MSG); else message.deleteMessage (JACK_STOP_MSG); } // Beats per bar changed? if (oBpb && (oBpb->type == uris.atom_Float) && (((LV2_Atom_Float*)oBpb)->body > 0) && (((LV2_Atom_Float*)oBpb)->body != beatsPerBar)) { beatsPerBar = ((LV2_Atom_Float*)oBpb)->body; scheduleUpdatePosition = true; } // BeatUnit changed? if (oBu && (oBu->type == uris.atom_Int) && (((LV2_Atom_Int*)oBu)->body > 0) && (((LV2_Atom_Int*)oBu)->body != beatUnit)) { beatUnit = ((LV2_Atom_Int*)oBu)->body; scheduleUpdatePosition = true; } // Speed changed? if (oSpeed && (oSpeed->type == uris.atom_Float) && (((LV2_Atom_Float*)oSpeed)->body != speed)) { speed = ((LV2_Atom_Float*)oSpeed)->body; if (speed == 0.0) message.setMessage (JACK_STOP_MSG); else message.deleteMessage (JACK_STOP_MSG); } // Bar position changed if (oBar && (oBar->type == uris.atom_Long) && (bar != (((LV2_Atom_Long*)oBar)->body))) { bar = ((LV2_Atom_Long*)oBar)->body; scheduleUpdatePosition = true; } // Beat position changed ? if (oBbeat && (oBbeat->type == uris.atom_Float) && (((LV2_Atom_Float*)oBbeat)->body != barBeat)) { barBeat = ((LV2_Atom_Float*)oBbeat)->body; scheduleUpdatePosition = true; } if (scheduleUpdatePosition) { // Hard set new position if new data received //fprintf(stderr, "BSchaffl.lv2: Change position %f -> ", positionSeq); positionSeq = getSequenceFromBeats (barBeat + beatsPerBar * bar); //fprintf(stderr, "%f\n", positionSeq); refFrame = ev->time.frames; } recalculateLatency(); } // Shape changed notifications else if (obj->body.otype == uris.bschaffl_shapeEvent) { LV2_Atom *oData = NULL; lv2_atom_object_get (obj, uris.bschaffl_shapeData, &oData, NULL); if (oData && (oData->type == uris.atom_Vector)) { const LV2_Atom_Vector* vec = (const LV2_Atom_Vector*) oData; if (vec->body.child_type == uris.atom_Float) { shape.clearShape (); const uint32_t vecSize = (uint32_t) ((oData->size - sizeof(LV2_Atom_Vector_Body)) / (7 * sizeof (float))); float* data = (float*) (&vec->body + 1); for (unsigned int i = 0; (i < vecSize) && (i < MAXNODES); ++i) { Node node; node.nodeType = NodeType (int (data[i * 7])); node.point.x = data[i * 7 + 1]; node.point.y = data[i * 7 + 2]; node.handle1.x = data[i * 7 + 3]; node.handle1.y = data[i * 7 + 4]; node.handle2.x = data[i * 7 + 5]; node.handle2.y = data[i * 7 + 6]; shape.appendRawNode (node); } shape.validateShape(); if ((sharedDataNr > 0) && (sharedDataNr <=4)) sharedData[sharedDataNr - 1].shape = shape; } } } } // Read incoming MIDI events else if (ev->body.type == uris.midi_Event) { const uint8_t* const msg = (const uint8_t*)(ev + 1); MidiData midi = {{0, 0, 0}, 0, 0, 0, 0, false}; midi.size = LIM (ev->body.size, 0, 3); memcpy (midi.msg, msg, midi.size); // Filter channel and message bool process = filterMsg (midi.msg[0]) && (controllers[MIDI_CH_FILTER + (midi.msg[0] & 0x0F)] != 0.0f); // Calculate position within sequence const double inputSeq = positionSeq + getSequenceFromFrame (ev->time.frames - refFrame, speed) + (controllers[TIME_COMPENS] != 1.0f ? latencySeq : 0); const float inputSeqPos = MODFL (inputSeq); // Calulate step const int nrOfSteps = controllers[NR_OF_STEPS]; const int step = LIM (double (nrOfSteps) * inputSeqPos, 0, nrOfSteps - 1); // Update step if ((actStep < 0) || (step != actStep)) { // Sequence just started: Re-randomize sequence if (step < actStep) { for (int i = 0; i < nrOfSteps; ++i) randomizeStep (i); } actStep = step; } // Calulate fractional position within step const float iprev = float (step) / float (nrOfSteps); const float inext = (step >= nrOfSteps - 1 ? 1.0f : float (step + 1) / float (nrOfSteps)); const float ifrac = (iprev != inext ? (inputSeqPos - iprev) / (inext - iprev) : 0.0f); // Calculate output position const float qrange = (controllers[QUANT_POS] != 0.0f ? controllers[QUANT_RANGE] : 0.0); const float oprev = getStepStart (step); const float onext = getStepEnd (step); const float ofrac = (ifrac <= qrange ? 0.0f : (1.0f - ifrac < qrange ? 1.0f : ifrac)); const float outputSeqPos = oprev + ofrac * (onext - oprev); const float origin = inputSeq + latencySeq; const float shift = (outputSeqPos - inputSeqPos) * controllers[SWING_PROCESS]; midi.shiftSeq = (process? shift : 0); // Garbage collection // Removes data from queue which are scheduled to a time point later than the latest possible time point const float maxProcSeq = origin + onext - inputSeqPos; const float maxSeq = (origin > maxProcSeq ? origin : maxProcSeq); clearMidiData (maxSeq); // MIDI NOTE_ON and NOTE_OFF if ( ( ((midi.msg[0] & 0xF0) == 0x80) || ((midi.msg[0] & 0xF0) == 0x90) ) && process ) { // Map step (smart quantization) const float mrange = (controllers[QUANT_MAP] != 0.0f ? controllers[QUANT_RANGE] : 0.0); const int map = ( (midi.msg[0] & 0xF0) == 0x80 ? (ifrac < mrange ? ((step + nrOfSteps - 1) % nrOfSteps) : step) : (1.0 - ifrac < mrange ? ((step + 1) % nrOfSteps) : step) ); // Calculate and set amp float aswing = ((map % 2) == 0 ? controllers[AMP_SWING] : 1.0 / controllers[AMP_SWING]); aswing = LIM (aswing, 0, 1); const float rnd = 1.0f + controllers[AMP_RANDOM] * (2.0f * distribution (mcg) - 1.0f); float amp = ( controllers[AMP_MODE] == 0.0f ? controllers[STEP_LEV + map] * rnd * aswing : LIM (shape.getMapValue (inputSeqPos), 0.0, 1.0) * rnd ); // NOTE_OFF if ((midi.msg[0] & 0xF0) == 0x80) { const int nr = ( (controllers[NOTE_OFF_AMP] == 0) || controllers[NOTE_POSITION_STR] || controllers[NOTE_VALUE_STR] ? getNoteOnMsg (midi.msg[0] & 0x0F, midi.msg[1]) : -1 ); const float s1 = (nr >= 0 ? midiData[nr].shiftSeq : shift); // Use note on amp ? Look for corresponding NOTE_ON if (controllers[NOTE_OFF_AMP] == 0) { if (nr >= 0) amp = midiData[nr].amp; } // Calculate shift midi.positionSeq = origin + ( controllers[NOTE_POSITION_STR] ? (controllers[NOTE_VALUE_STR] ? 0 : shift - s1) : (controllers[NOTE_VALUE_STR] ? s1 : shift) ); // Handle overlapping notes if ( (nr >= 0) && (controllers[NOTE_POSITION_STR] || controllers[NOTE_VALUE_STR]) && (controllers[NOTE_OVERLAP] == OVERLAP_MERGE) ) { const int noteOffNr = getNoteOffMsg (midi.msg[0] & 0x0F, midi.msg[1], nr); if (noteOffNr >= 0) { // Nested notes: Ignore inner NOTE_OFF if (midi.positionSeq <= midiData[noteOffNr].positionSeq) { midi.msg[0] = 0; } // Overlapping notes: Remove inner NOTE_OFF else { /*fprintf ( stderr, "BSchaffl.lv2: Remove MIDI signal from #%i %i (%i,%i) to %f (shift = %f, latency = %f)\n", noteOffNr, midiData[noteOffNr].msg[0], midiData[noteOffNr].msg[1], midiData[noteOffNr].msg[2], midiData[noteOffNr].positionSeq, midiData[noteOffNr].shiftSeq, latencySeq );*/ midiData.erase (&midiData.iterator[noteOffNr]); } } } } // NOTE_ON ? else { //Store amp midi.amp = amp; // Calculate shift if (controllers[NOTE_POSITION_STR]) midi.positionSeq = origin; else midi.positionSeq = origin + shift; // Handle overlapping notes if (controllers[NOTE_POSITION_STR] || controllers[NOTE_VALUE_STR]) { // Split: Insert or move NOTE_OFF just before new NOTE_ON if (controllers[NOTE_OVERLAP] == OVERLAP_SPLIT) { const int noteOnNr = getNoteOnMsg (midi.msg[0] & 0x0F, midi.msg[1]); if (noteOnNr >= 0) { const int noteOffNr = getNoteOffMsg (midi.msg[0] & 0x0F, midi.msg[1], noteOnNr); const MidiData noteOff = ( noteOffNr >= 0 ? MidiData { {0x80 || (midi.msg[0] & 0x0F), midi.msg[1], midiData[noteOffNr].msg[2]}, midiData[noteOffNr].size, midi.positionSeq, midi.shiftSeq, midiData[noteOffNr].amp, midiData[noteOffNr].inactive } : MidiData { {0x80 || (midi.msg[0] & 0x0F), midi.msg[1], midi.msg[2]}, midi.size, midi.positionSeq, midi.shiftSeq, midi.amp, midi.inactive } ); if ((noteOffNr >= 0) && (midi.positionSeq < midiData[noteOffNr].positionSeq)) { // Remome old NOTE_OFF /*fprintf ( stderr, "BSchaffl.lv2: Remove MIDI signal from #%i %i (%i,%i) to %f (shift = %f, latency = %f)\n", noteOffNr, midiData[noteOffNr].msg[0], midiData[noteOffNr].msg[1], midiData[noteOffNr].msg[2], midiData[noteOffNr].positionSeq, midiData[noteOffNr].shiftSeq, latencySeq );*/ midiData.erase (&midiData.iterator[noteOffNr]); // Insert NOTE_OFF queueMidiData (noteOff); } } } // Merge: Ignore new NOTE_ON else if (controllers[NOTE_OVERLAP] == OVERLAP_MERGE) { const int nr = getNoteOnMsg (midi.msg[0] & 0x0F, midi.msg[1]); if (nr >= 0) { const int noteOffNr = getNoteOffMsg (midi.msg[0] & 0x0F, midi.msg[1], nr); if ((noteOffNr < 0) || (midi.positionSeq < midiData[noteOffNr].positionSeq)) { midi.msg[0] = 0; } } } } } // Apply amp const float proc = controllers[AMP_PROCESS]; const float invel = float (midi.msg[2]); const float outvel = invel + (invel * amp - invel) * proc; midi.msg[2] = LIM (outvel, 0, 127); } else midi.positionSeq = origin + midi.shiftSeq; // Store MIDI data if (midi.msg[0]) queueMidiData (midi); } play (last_t, ev->time.frames); last_t = ev->time.frames; } // Play remaining samples if (last_t < n_samples) play (last_t, n_samples); // Update position in case of no new barBeat submitted on next call double relSeq = getSequenceFromFrame (n_samples - refFrame, speed); positionSeq += relSeq; refFrame = 0; // Send collected data to GUI if (uiOn) { if (message.isScheduled ()) notifyMessageToGui(); notifyStatusToGui(); if (notify_sharedData) notifySharedDataNrToGui(); for (int i = 0; i < NR_CONTROLLERS; ++i) if (notify_controllers[i]) notifyControllerToGui (i); if (notify_shape) notifyShapeToGui(); } // Close off sequence lv2_atom_forge_pop(&forge, &frame); } void BSchaffl::play (uint32_t start, uint32_t end) { const double startSeq = positionSeq + getSequenceFromFrame (start - refFrame, speed) + (controllers[TIME_COMPENS] != 1.0f ? latencySeq : 0); const double endSeq = positionSeq + getSequenceFromFrame (end - refFrame, speed) + (controllers[TIME_COMPENS] != 1.0f ? latencySeq : 0); // Send midi data to output for (unsigned int i = 0; i < midiData.size; ++i) { if ((midiData[i].positionSeq <= endSeq) && (!midiData[i].inactive)) { // Calculate frame int64_t frame = start; double seq = midiData[i].positionSeq; if (seq >= startSeq) { frame = start + getFrameFromSequence (seq - startSeq, speed); //frame = LIM (frame, 0, end); } // Send MIDI LV2_Atom midiatom; midiatom.type = uris.midi_Event; midiatom.size = midiData[i].size; lv2_atom_forge_frame_time (&forge, frame); lv2_atom_forge_raw (&forge, &midiatom, sizeof (LV2_Atom)); lv2_atom_forge_raw (&forge, &midiData[i].msg, midiatom.size); lv2_atom_forge_pad (&forge, sizeof (LV2_Atom) + midiatom.size); midiData[i].inactive = true; /*fprintf ( stderr, "BSchaffl.lv2 @ %f: Send Midi #%i %i (%i, %i) (frame = %li) \n", seq, i, midiData[i].msg[0], midiData[i].msg[1], midiData[i].msg[2], frame );*/ } } // Remove sent data for (MidiData** it = midiData.begin(); (it < midiData.end()) && ((**it).positionSeq <= endSeq); ) { if ((**it).inactive) { // NOTE_OFF ? if (((**it).msg[0] & 0xF0) == 0x80) { // Erase corresponding NOTE_ON uint8_t ch = (**it).msg[0] & 0x0F; uint8_t note = (**it).msg[1]; for (MidiData** nit = midiData.begin(); nit < it; ) { if ( (((**nit).msg[0] & 0xF0) == 0x90) && (((**nit).msg[0] & 0x0F) == ch) && ((**nit).msg[1] == note) ) { nit = midiData.erase (nit); --it; } else ++nit; } // Erase NOTE_OFF and go to next it it = midiData.erase (it); } // NOTE_ON ? Next it else if (((**it).msg[0] & 0xF0) == 0x90) ++it; // Otherwise erase and go to next it else it = midiData.erase (it); } // Otherwise next it else ++it; } } float BSchaffl::getControllerInput (const int sdNr, const int ctrlNr) { // Sync with control ports if ((sdNr == 0) && controllerPtrs[ctrlNr]) return controllerLimits[ctrlNr].validate (*controllerPtrs[ctrlNr]); // Otherwise sync with globally shared data if (sdNr <= 4) return controllerLimits[ctrlNr].validate (sharedData[sdNr - 1].get (ctrlNr)); return controllerLimits[ctrlNr].min; } void BSchaffl::setController (const int ctrlNr, const float value) { controllers[ctrlNr] = value; if (ctrlNr == SWING) recalculateAutoPositions(); else if (ctrlNr == NR_OF_STEPS) recalculateAutoPositions(); else if ((ctrlNr >= STEP_POS) && (ctrlNr < STEP_POS + MAXSTEPS - 1)) { const int step = ctrlNr - STEP_POS; if (value == 0.0f) { if (!stepAutoPositions[step]) { stepAutoPositions[step] = true; recalculateAutoPositions(); } } else if (stepPositions[step] != value) { stepAutoPositions[step] = false; stepPositions[step] = value; recalculateAutoPositions(); } } } void BSchaffl::randomizeStep (const int step) { const int nrOfSteps = controllers[NR_OF_STEPS]; if ((step < nrOfSteps - 1) && (step >= 0)) { // Randomize 0.0 .. 2.0 float rnd = 1.0f + controllers[SWING_RANDOM] * (2.0f * float (rand()) / float (RAND_MAX) - 1.0f); // Prevent overlap with antecessor if ((step >= 1) && (rnd < stepRnds[step - 1] - 1.0f)) rnd = stepRnds[step - 1] - 1.0f; stepRnds[step] = rnd; } } double BSchaffl::getStepStart (const int step) { const int nrOfSteps = controllers[NR_OF_STEPS]; const int s = step % nrOfSteps; if (s == 0) return 0.0; else { const float rnd = stepRnds[s - 1]; return ( rnd < 1.0f ? ( s - 1 > 0 ? stepPositions[s - 1] - (1.0f - rnd) * (stepPositions[s - 1] - stepPositions[s - 2]) : stepPositions[s - 1] - (1.0f - rnd) * stepPositions[s - 1] ) : ( s - 1 < nrOfSteps - 2 ? stepPositions[s - 1] + (rnd - 1.0f) * (stepPositions[s] - stepPositions[s - 1]) : stepPositions[s - 1] + (rnd - 1.0f) * (1.0f - stepPositions[s - 1]) ) ); } } double BSchaffl::getStepEnd (const int step) { const int nrOfSteps = controllers[NR_OF_STEPS]; const int s = step % nrOfSteps; if (s == nrOfSteps - 1) return 1.0; else return getStepStart (s + 1); } int BSchaffl::getNoteOnMsg (const uint8_t ch, const uint8_t note, int start) const { for (int i = ((start >= 0) && (start < int (midiData.size)) ? start : midiData.size - 1); i >= 0; --i) { if ( ((midiData[i].msg[0] & 0xF0) == 0x90) && ((midiData[i].msg[0] & 0x0F) == ch) && (midiData[i].msg[1] == note) ) return i; } return -1; } int BSchaffl::getNoteOffMsg (const uint8_t ch, const uint8_t note, int start) const { for (int i = ((start >= 0) && (start < int (midiData.size)) ? start : 0); i < int (midiData.size); ++i) { if ( ((midiData[i].msg[0] & 0xF0) == 0x80) && ((midiData[i].msg[0] & 0x0F) == ch) && (midiData[i].msg[1] == note) ) return i; } return -1; } void BSchaffl::clearMidiData (const float maxSeq) { while ((!midiData.empty()) && (midiData.back().positionSeq > maxSeq)) { /*fprintf ( stderr, "BSchaffl.lv2 @: Remove MIDI signal %i (%i,%i) from %f (maxSeq = %f)\n", midiData.back().msg[0], midiData.back().msg[1], midiData.back().msg[2], midiData.back().positionSeq, maxSeq );*/ midiData.pop_back(); } } void BSchaffl::queueMidiData (const MidiData& midi) { for (MidiData** m = midiData.end(); m >= midiData.begin(); --m) { if ((m == midiData.begin()) || ((**(m - 1)).positionSeq <= midi.positionSeq)) { midiData.insert (m, midi); break; } } /*fprintf ( stderr, "BSchaffl.lv2: Schedule MIDI signal #%li %i (%i,%i) to %f (shift = %f, latency = %f)\n", midiData.size, midi.msg[0], midi.msg[1], midi.msg[2], midi.positionSeq, midi.shiftSeq, latencySeq );*/ } double BSchaffl::getSequenceFromBeats (const double beats) { if (controllers[SEQ_LEN_VALUE] == 0.0) return 0.0; switch (int (controllers[SEQ_LEN_BASE])) { case SECONDS: return (bpm ? beats / (controllers[SEQ_LEN_VALUE] * (bpm / 60.0)) : 0.0); case BEATS: return beats / controllers[SEQ_LEN_VALUE]; case BARS: return (beatsPerBar ? beats / (controllers[SEQ_LEN_VALUE] * beatsPerBar) : 0.0); default: return 0.0; } } double BSchaffl::getBeatsFromSequence (const double sequence) { if (controllers[SEQ_LEN_VALUE] == 0.0) return 0.0; switch (int (controllers[SEQ_LEN_BASE])) { case SECONDS: return (bpm ? sequence * (controllers[SEQ_LEN_VALUE] * (bpm / 60.0)) : 0.0); case BEATS: return sequence * controllers[SEQ_LEN_VALUE]; case BARS: return (beatsPerBar ? sequence * (controllers[SEQ_LEN_VALUE] * beatsPerBar) : 0.0); default: return 0.0; } } double BSchaffl::getSequenceFromFrame (const int64_t frames, float speed) { if (controllers[SEQ_LEN_VALUE] == 0.0) return 0.0; switch (int (controllers[SEQ_LEN_BASE])) { case SECONDS: return (rate ? frames * (1.0 / rate) / controllers[SEQ_LEN_VALUE] : 0.0); case BEATS: return (rate ? frames * speed * bpm / (60.0 * rate * controllers[SEQ_LEN_VALUE]) : 0.0); case BARS: return (rate && beatsPerBar ? frames * speed * bpm / (60.0 * rate * controllers[SEQ_LEN_VALUE] * beatsPerBar) : 0.0); default: return 0.0; } } int64_t BSchaffl::getFrameFromSequence (const double sequence, float speed) { if (controllers[SEQ_LEN_VALUE] == 0.0) return 0.0; switch (int (controllers[SEQ_LEN_BASE])) { case SECONDS: return sequence * rate * controllers[SEQ_LEN_VALUE]; case BEATS: return (speed && bpm ? 60 * sequence * rate * controllers[SEQ_LEN_VALUE] / (speed * bpm) : 0.0); case BARS: return (speed && bpm ? 60.0 * sequence * beatsPerBar * rate * controllers[SEQ_LEN_VALUE] / (speed * bpm) : 0.0); default: return 0.0; } } bool BSchaffl::filterMsg (const uint8_t msg) { uint8_t msgGroup = msg / 16; return ( msgGroup < 8 ? false : ( msgGroup == 8 ? (controllers[MSG_FILTER_NOTE] != 0.0f) : (controllers[MSG_FILTER_NOTE + msgGroup - 9] != 0.0f) ) ); } void BSchaffl::recalculateLatency () { if (controllers[USR_LATENCY] != 0.0f) { latencyFr = controllers[USR_LATENCY_FR]; latencySeq = getSequenceFromFrame (latencyFr); } else { double qLatencySeq = (controllers[QUANT_POS] != 0.0f ? controllers[QUANT_RANGE] / controllers[NR_OF_STEPS] : 0.0); latencySeq = 0; const int nrSteps = controllers[NR_OF_STEPS]; for (int i = 0; i < nrSteps - 1; ++i) { const double inStartSeq = double (i) / double (nrSteps); const double outStartSeq = (i == 0 ? 0.0 : stepPositions[i - 1]); const double rndSeq = (i == 0 ? 0.0 : controllers[SWING_RANDOM] * (stepPositions[i - 1] - (i == 1 ? 0.0 : stepPositions[i - 2]))); const double diffSeq = inStartSeq - (outStartSeq - rndSeq); if (diffSeq > latencySeq) latencySeq = diffSeq; } latencySeq += qLatencySeq; latencyFr = getFrameFromSequence (latencySeq); } } void BSchaffl::recalculateAutoPositions () { int nrMarkers = controllers[NR_OF_STEPS] - 1; int start = 0; for (int i = 0; i < nrMarkers; ++i) { if (stepAutoPositions[i]) { if ((i == nrMarkers - 1) || (!stepAutoPositions[i + 1])) { double s = 2.0 * controllers[SWING] / (controllers[SWING] + 1.0); double anc = (start == 0 ? 0 : stepPositions[start - 1]); double suc = (i == nrMarkers - 1 ? 1 : stepPositions[i + 1]); double diff = suc - anc; double dist = i - start + 1.0 + (int (i - start) & 1 ? ((start & 1) ? 2.0 - s : s) : 1.0); double step = (diff < 0 ? 0 : diff / dist); for (int j = start; j <= i; ++j) { double f = ((j & 1) ? 2.0 - s : s); anc += f * step; stepPositions[j] = anc; } } } else start = i + 1; } } void BSchaffl::notifyControllerToGui (const int nr) { // Send notifications LV2_Atom_Forge_Frame frame; lv2_atom_forge_frame_time (&forge, 0); lv2_atom_forge_object (&forge, &frame, 0, uris.bschaffl_controllerEvent); lv2_atom_forge_key (&forge, uris.bschaffl_controllerNr); lv2_atom_forge_int (&forge, nr); lv2_atom_forge_key (&forge, uris.bschaffl_controllerValue); lv2_atom_forge_float (&forge, controllers[nr]); lv2_atom_forge_pop (&forge, &frame); notify_controllers[nr] = false; } void BSchaffl::notifySharedDataNrToGui () { // Send notifications LV2_Atom_Forge_Frame frame; lv2_atom_forge_frame_time (&forge, 0); lv2_atom_forge_object (&forge, &frame, 0, uris.bschaffl_sharedDataLinkEvent); lv2_atom_forge_key (&forge, uris.bschaffl_sharedDataNr); lv2_atom_forge_int (&forge, sharedDataNr); lv2_atom_forge_pop (&forge, &frame); notify_sharedData = false; } void BSchaffl::notifyStatusToGui () { // Calculate step int outStep = 0; const double seqPos = fmod (positionSeq - (controllers[TIME_COMPENS] == 1.0f ? latencySeq : 0), 1.0); while ((outStep < controllers[NR_OF_STEPS] - 1) && (seqPos > getStepEnd (outStep))) ++outStep; // Calculate latency in ms const float latencyMs = float (latencyFr) * 1000.0f / rate; // Send notifications LV2_Atom_Forge_Frame frame; lv2_atom_forge_frame_time (&forge, 0); lv2_atom_forge_object (&forge, &frame, 0, uris.bschaffl_statusEvent); lv2_atom_forge_key (&forge, uris.bschaffl_step); lv2_atom_forge_int (&forge, outStep); lv2_atom_forge_key (&forge, uris.bschaffl_latency); lv2_atom_forge_float (&forge, latencyMs); lv2_atom_forge_key (&forge, uris.bschaffl_rate); lv2_atom_forge_double (&forge, rate); lv2_atom_forge_pop (&forge, &frame); } void BSchaffl::notifyShapeToGui () { size_t size = shape.size (); // Load shapeBuffer float shapeBuffer[MAXNODES * 7]; for (unsigned int i = 0; i < size; ++i) { Node node = shape.getRawNode (i); shapeBuffer[i * 7] = (float)node.nodeType; shapeBuffer[i * 7 + 1] = (float)node.point.x; shapeBuffer[i * 7 + 2] = (float)node.point.y; shapeBuffer[i * 7 + 3] = (float)node.handle1.x; shapeBuffer[i * 7 + 4] = (float)node.handle1.y; shapeBuffer[i * 7 + 5] = (float)node.handle2.x; shapeBuffer[i * 7 + 6] = (float)node.handle2.y; } // Notify shapeBuffer LV2_Atom_Forge_Frame frame; lv2_atom_forge_frame_time(&forge, 0); lv2_atom_forge_object(&forge, &frame, 0, uris.bschaffl_shapeEvent); lv2_atom_forge_key(&forge, uris.bschaffl_shapeData); lv2_atom_forge_vector(&forge, sizeof(float), uris.atom_Float, (uint32_t) (7 * size), &shapeBuffer); lv2_atom_forge_pop(&forge, &frame); notify_shape = false; } void BSchaffl::notifyMessageToGui () { uint32_t messageNr = message.loadMessage (); // Send notifications LV2_Atom_Forge_Frame frame; lv2_atom_forge_frame_time(&forge, 0); lv2_atom_forge_object(&forge, &frame, 0, uris.notify_messageEvent); lv2_atom_forge_key(&forge, uris.notify_message); lv2_atom_forge_int(&forge, messageNr); lv2_atom_forge_pop(&forge, &frame); } LV2_State_Status BSchaffl::state_save (LV2_State_Store_Function store, LV2_State_Handle handle, uint32_t flags, const LV2_Feature* const* features) { // Save shared data store (handle, uris.bschaffl_sharedDataNr, &sharedDataNr, sizeof(sharedDataNr), uris.atom_Int, LV2_STATE_IS_POD); if (sharedDataNr != 0) { Atom_Controllers atom; for (int i = 0; i < NR_CONTROLLERS; ++i) atom.data[i] = sharedData[sharedDataNr - 1].get (i); atom.body.child_type = uris.atom_Float; atom.body.child_size = sizeof(float); store (handle, uris.bschaffl_controllers, &atom, NR_CONTROLLERS * sizeof (float) + sizeof(LV2_Atom_Vector_Body), uris.atom_Vector, LV2_STATE_IS_POD); } // Save shape char shapesDataString[0x8010] = "Shape data:\n"; for (unsigned int nd = 0; nd < shape.size (); ++nd) { char valueString[160]; Node node = shape.getNode (nd); snprintf ( valueString, 126, "typ:%d; ptx:%f; pty:%f; h1x:%f; h1y:%f; h2x:%f; h2y:%f", int (node.nodeType), node.point.x, node.point.y, node.handle1.x, node.handle1.y, node.handle2.x, node.handle2.y ); if (nd < shape.size ()) strcat (valueString, ";\n"); else strcat (valueString, "\n"); strcat (shapesDataString, valueString); } store (handle, uris.bschaffl_shapeData, shapesDataString, strlen (shapesDataString) + 1, uris.atom_String, LV2_STATE_IS_POD); return LV2_STATE_SUCCESS; } LV2_State_Status BSchaffl::state_restore (LV2_State_Retrieve_Function retrieve, LV2_State_Handle handle, uint32_t flags, const LV2_Feature* const* features) { size_t size; uint32_t type; uint32_t valflags; // Restore sharedData if (sharedDataNr != 0) sharedData[sharedDataNr - 1].unlink (this); sharedDataNr = 0; const void* sharedDataNrData = retrieve (handle, uris.bschaffl_sharedDataNr, &size, &type, &valflags); if (sharedDataNrData && (type == uris.atom_Int)) { const int nr = *(int*)sharedDataNrData; sharedDataNr = nr; if (nr != 0) sharedData[nr - 1].link (this); } if ((sharedDataNr >= 0) && (sharedDataNr <= 4)) { const void* controllersData = retrieve (handle, uris.bschaffl_controllers, &size, &type, &valflags); if (controllersData && (type == uris.atom_Vector) && (sharedDataNr > 0)) { const Atom_Controllers* atom = (const Atom_Controllers*) controllersData; if (atom->body.child_type == uris.atom_Float) { for (int i = 0; i < NR_CONTROLLERS; ++i) sharedData[sharedDataNr - 1].set (i, atom->data[i]); } } } notify_sharedData = true; for (int i = 0; i < NR_CONTROLLERS; ++i) { float newValue = getControllerInput (sharedDataNr, i); if (newValue != controllers[i]) { setController (i, newValue); notify_controllers[i] = true; } } // Restore shape const void* shapesData = retrieve (handle, uris.bschaffl_shapeData, &size, &type, &valflags); if (shapesData && (type == uris.atom_String)) { // Clear old shape first shape.clearShape(); // Parse retrieved data std::string shapesDataString = (char*) shapesData; const std::string keywords[7] = {"typ:", "ptx:", "pty:", "h1x:", "h1y:", "h2x:", "h2y:"}; while (!shapesDataString.empty()) { // Look for next "typ:" size_t strPos = shapesDataString.find ("typ:"); size_t nextPos = 0; if (strPos == std::string::npos) break; // No "typ:" found => end if (strPos + 4 > shapesDataString.length()) break; // Nothing more after id => end shapesDataString.erase (0, strPos + 4); int typ; try {typ = BUtilities::stof (shapesDataString, &nextPos);} catch (const std::exception& e) { fprintf (stderr, "BSchaffl.lv2: Restore shape incomplete. Can't parse shape node type from \"%s...\"", shapesDataString.substr (0, 63).c_str()); break; } if (nextPos > 0) shapesDataString.erase (0, nextPos); // Look for shape data Node node = {(NodeType) typ, {0, 0}, {0, 0}, {0, 0}}; for (int i = 1; i < 7; ++i) { strPos = shapesDataString.find (keywords[i]); if (strPos == std::string::npos) continue; // Keyword not found => next keyword if (strPos + 4 >= shapesDataString.length()) // Nothing more after keyword => end { shapesDataString =""; break; } if (strPos > 0) shapesDataString.erase (0, strPos + 4); float val; try {val = BUtilities::stof (shapesDataString, &nextPos);} catch (const std::exception& e) { fprintf (stderr, "BSchaffl.lv2: Restore shape incomplete. Can't parse %s from \"%s...\"", keywords[i].substr(0,3).c_str(), shapesDataString.substr (0, 63).c_str()); break; } if (nextPos > 0) shapesDataString.erase (0, nextPos); switch (i) { case 1: node.point.x = val; break; case 2: node.point.y = val; break; case 3: node.handle1.x = val; break; case 4: node.handle1.y = val; break; case 5: node.handle2.x = val; break; case 6: node.handle2.y = val; break; default:break; } } // Set data shape.appendNode (node); } // Validate shape if ((shape.size () < 2) || (!shape.validateShape ())) shape.setDefaultShape (); if ((sharedDataNr > 0) && (sharedDataNr <=4)) sharedData[sharedDataNr - 1].shape = shape; // Force GUI notification notify_shape = true; } return LV2_STATE_SUCCESS; } static LV2_Handle instantiate (const LV2_Descriptor* descriptor, double samplerate, const char* bundle_path, const LV2_Feature* const* features) { // New instance BSchaffl* instance; try {instance = new BSchaffl(samplerate, features);} catch (std::exception& exc) { fprintf (stderr, "BSchaffl.lv2: Plugin instantiation failed. %s\n", exc.what ()); return NULL; } if (!instance) { fprintf(stderr, "BSchaffl.lv2: Plugin instantiation failed.\n"); return NULL; } if (!instance->map) { fprintf(stderr, "BSchaffl.lv2: Host does not support urid:map.\n"); delete (instance); return NULL; } return (LV2_Handle)instance; } static void connect_port (LV2_Handle instance, uint32_t port, void *data) { BSchaffl* inst = (BSchaffl*) instance; if (inst) inst->connect_port (port, data); } static void run (LV2_Handle instance, uint32_t n_samples) { BSchaffl* inst = (BSchaffl*) instance; if (inst) inst->run (n_samples); } static LV2_State_Status state_save(LV2_Handle instance, LV2_State_Store_Function store, LV2_State_Handle handle, uint32_t flags, const LV2_Feature* const* features) { BSchaffl* inst = (BSchaffl*)instance; if (!inst) return LV2_STATE_SUCCESS; return inst->state_save (store, handle, flags, features); } static LV2_State_Status state_restore(LV2_Handle instance, LV2_State_Retrieve_Function retrieve, LV2_State_Handle handle, uint32_t flags, const LV2_Feature* const* features) { BSchaffl* inst = (BSchaffl*)instance; if (!inst) return LV2_STATE_SUCCESS; return inst->state_restore (retrieve, handle, flags, features); } static void cleanup (LV2_Handle instance) { BSchaffl* inst = (BSchaffl*) instance; if (inst) delete inst; } static const void* extension_data(const char* uri) { static const LV2_State_Interface state = {state_save, state_restore}; if (!strcmp(uri, LV2_STATE__interface)) return &state; return NULL; } static const LV2_Descriptor descriptor = { BSCHAFFL_URI, instantiate, connect_port, NULL, //activate, run, NULL, //deactivate, cleanup, extension_data }; // LV2 Symbol Export LV2_SYMBOL_EXPORT const LV2_Descriptor* lv2_descriptor(uint32_t index) { switch (index) { case 0: return &descriptor; default: return NULL; } }
38,251
C++
.cpp
1,164
28.79811
156
0.639782
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,483
ShapeWidget.cpp
sjaehn_BSchaffl/src/ShapeWidget.cpp
/* B.Shapr * Beat / envelope shaper LV2 plugin * * Copyright (C) 2019 by Sven Jähnichen * * 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, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "ShapeWidget.hpp" #include <cmath> #include <string> #include "BUtilities/to_string.hpp" ShapeWidget::ShapeWidget () : ShapeWidget (0, 0, 0, 0, "") {} ShapeWidget::ShapeWidget (const double x, const double y, const double width, const double height, const std::string& name) : Shape (), ValueWidget (x, y, width, height, name, 0), Focusable (std::chrono::milliseconds (2000), std::chrono::milliseconds (10000)), clickMode (NEW_NODE), selection (), tool (NO_TOOL), grabbedNode (-1), grabbedHandle (-1), valueEnabled (false), scaleAnchorYPos (0), scaleAnchorValue (0), scaleRatio (1), minorXSteps (1), majorXSteps (1), loLimit (-1000000), hiLimit (1000000), hardLoLimit (false), hardHiLimit (false), gridVisible (true), gridSnap (true), prefix (""), unit (""), fgColors (BColors::reds), bgColors (BColors::darks), lbfont (BWIDGETS_DEFAULT_FONT), focusText (0, 0, 400, 80, name + "/focus", "<CLICK>: Set, select, or remove node.\n<DRAG>: Drag selected node or handle or drag grid pattern.\n<SCROLL>: Resize grid pattern.\n<SHIFT><SCROLL>: Resize input / output signal monitor.") { setDraggable (true); setScrollable (true); focusText.setStacking (BWidgets::STACKING_OVERSIZE); focusText.setYResizable (true); focusText.hide (); add (focusText); } ShapeWidget::ShapeWidget (const ShapeWidget& that) : Shape (that), ValueWidget (that), Focusable (that), clickMode (that.clickMode), selection (that.selection), tool (that.tool), grabbedNode (that.grabbedNode), grabbedHandle (that.grabbedHandle), valueEnabled (that.valueEnabled), scaleAnchorYPos (that.scaleAnchorYPos), scaleAnchorValue (that.scaleAnchorValue), scaleRatio (that.scaleRatio), minorXSteps (that.minorXSteps), majorXSteps (that.majorXSteps), loLimit (that.loLimit), hiLimit (that.hiLimit), hardLoLimit (that.hardLoLimit), hardHiLimit (that.hardHiLimit), gridVisible (that.gridVisible), gridSnap (that.gridSnap), prefix (that.prefix), unit (that.unit), fgColors (that.fgColors), bgColors (that.bgColors), lbfont (that.lbfont), focusText (that.focusText) { add (focusText); } BWidgets::Widget* ShapeWidget::clone () const {return new ShapeWidget (*this);} void ShapeWidget::update () { Widget::update (); focusText.resize (); } void ShapeWidget::setTool (const ToolType tool) {this->tool = tool;} void ShapeWidget::setValueEnabled (const bool status) {valueEnabled = status;} void ShapeWidget::setScaleParameters (double anchorYPos, double anchorValue, double ratio) { if ((scaleAnchorYPos != anchorYPos) || (scaleAnchorValue != anchorValue) || (scaleRatio != ratio)) { scaleAnchorYPos = anchorYPos; scaleAnchorValue = anchorValue; scaleRatio = ratio; update (); } } void ShapeWidget::setMinorXSteps (double stepSize) { if (minorXSteps != stepSize) { minorXSteps = stepSize; update (); } } void ShapeWidget::setMajorXSteps (double stepSize) { if (majorXSteps != stepSize) { majorXSteps = stepSize; update (); } } void ShapeWidget::setPrefix (std::string text) { if (prefix != text) { prefix = text; update (); } } void ShapeWidget::setUnit (std::string text) { if (unit != text) { unit = text; update (); } } void ShapeWidget::setLowerLimit (double value, bool hard) { if ((value != loLimit) || (hard != hardLoLimit)) { loLimit = value; hardLoLimit = hard; update (); } } void ShapeWidget::setHigherLimit (double value, bool hard) { if ((value != hiLimit) || (hard != hardHiLimit)) { hiLimit = value; hardHiLimit = hard; update (); } } void ShapeWidget::showGrid () { gridVisible = true; update (); } void ShapeWidget::hideGrid () { gridVisible = false; update (); } void ShapeWidget::setSnap (const bool status) { gridSnap = status; } std::vector<Node> ShapeWidget::cutSelection () { std::vector<Node> selectedNodes = copySelection (); deleteSelection (); return selectedNodes; } std::vector<Node> ShapeWidget::copySelection () { std::vector<Node> selectedNodes; for (size_t i = 0; i < nodes_.size; ++i) { if (selection[i]) selectedNodes.push_back (nodes_[i]); } return selectedNodes; } void ShapeWidget::pasteSelection (const std::vector<Node>& newNodes) { selection.clear (); for (Node const& n : newNodes) { Node node = n; // END_NODEs: Overwrite if (node.nodeType == END_NODE) { if (nodes_.size >= 2) { if (node.point.x == 0.0) selection[0] = true; else selection[nodes_.size - 1] = true; node.point.x = nodes_[0].point.x; changeRawNode (0, node); node.point.x = nodes_[nodes_.size - 1].point.x; changeRawNode (nodes_.size - 1, node); } } // Other nodes: Insert else { // Find insert position size_t pos = 0; for (size_t i = 0; i < nodes_.size; ++i) { if (node.point.x < nodes_[i].point.x) { // Add if not redundant if ((i > 0) && (node != nodes_[i - 1])) { pos = i; break; } else break; } } // Insert and select if ((pos != 0) && (nodes_.size < MAXNODES)) { insertRawNode (pos, node); selection[pos] = true; } } } undoSnapshots.push (*this); update(); } void ShapeWidget::deleteSelection () { grabbedNode = -1; bool selected = false; for (int i = nodes_.size; i >= 0; --i) { if (selection[i]) { selected = true; deleteNode (i); } } if (selected) { selection.clear (); update (); } undoSnapshots.push (*this); update(); } void ShapeWidget::unselect () { grabbedNode = -1; selection.clear (); update(); } void ShapeWidget::reset () { unselect (); Shape::setDefaultShape (); undoSnapshots.push (*this); } void ShapeWidget::undo () { unselect (); clearShape (); this->Shape::operator= (undoSnapshots.undo ()); validateShape (); update(); } void ShapeWidget::redo () { unselect (); clearShape (); this->Shape::operator= (undoSnapshots.redo ()); validateShape (); update(); } void ShapeWidget::pushToSnapshots () { undoSnapshots.push (*this); } void ShapeWidget::resetSnapshots () { undoSnapshots.clear (); undoSnapshots.push (*this); } void ShapeWidget::setDefaultShape () { unselect (); Shape::setDefaultShape (); resetSnapshots (); update(); } void ShapeWidget::onButtonPressed (BEvents::PointerEvent* event) { double x0 = getXOffset (); double y0 = getYOffset (); double w = getEffectiveWidth (); double h = getEffectiveHeight (); double ymin = scaleAnchorValue - scaleRatio * scaleAnchorYPos; double ymax = ymin + scaleRatio; double px; double py; if ((w == 0) || (h == 0) || (ymax == ymin)) return; // Left button: select / deselect nodes or handles if (event->getButton() == BDevices::LEFT_BUTTON) { // Node already activated => Select handles if ((grabbedNode >= 0) && (grabbedNode < MAXNODES)) { Node node = getNode (grabbedNode); // Handle2 => Select px = x0 + w * (node.point.x + node.handle2.x); py = y0 + h - h * (node.point.y + node.handle2.y - ymin) / (ymax - ymin); if ((node.nodeType != NodeType::END_NODE) && // No END_NODEs (node.nodeType != NodeType::POINT_NODE) && // No POINT_NODEs (node.nodeType != NodeType::AUTO_SMOOTH_NODE) && // No AUTO_SMOOTH_NODEs (event->getPosition().x >= px - 3) && // Within the handle2 position (event->getPosition().x <= px + 3) && (event->getPosition().y >= py - 3) && (event->getPosition().y <= py + 3)) { clickMode = DRAG_HANDLE; grabbedHandle = 2; selection[grabbedNode] = true; update (); return; } // Handle1 => Select px = x0 + w * (node.point.x + node.handle1.x); py = y0 + h - h * (node.point.y + node.handle1.y - ymin) / (ymax - ymin); if ((node.nodeType != NodeType::END_NODE) && // No END_NODEs (node.nodeType != NodeType::POINT_NODE) && // No POINT_NODEs (node.nodeType != NodeType::AUTO_SMOOTH_NODE) && // No AUTO_SMOOTH_NODEs (event->getPosition().x >= px - 3) && // Within the handle1 position (event->getPosition().x <= px + 3) && (event->getPosition().y >= py - 3) && (event->getPosition().y <= py + 3)) { clickMode = DRAG_HANDLE; grabbedHandle = 1; selection[grabbedNode] = true; update (); return; } } // Point => Select for (unsigned int i = 0; i < nodes_.size; ++i) { Node node = getNode (i); px = x0 + w * node.point.x; py = y0 + h - h * (node.point.y - ymin) / (ymax - ymin); if ((event->getPosition().x >= px - 6) && // Within the point position (event->getPosition().x <= px + 6) && (event->getPosition().y >= py - 6) && (event->getPosition().y <= py + 6)) { clickMode = DRAG_NODE; grabbedNode = i; grabbedHandle = -1; // Click on not selected point => clear selection if (!selection[i]) { selection.clear (); selection[i] = true; selection.setOrigin ({px, py}); } update (); return; } } // New selection box in edit mode if (tool == EDIT_TOOL) { clickMode = DRAG_SELECTION; grabbedNode = -1; selection.clear (); py = ((y0 + h - event->getPosition().y) / h) * scaleRatio + ymin; px = (event->getPosition().x - x0) / w; selection.setOrigin ({px, py}); update (); return; } else { clickMode = NEW_NODE; grabbedNode = -1; } } } void ShapeWidget::onButtonReleased (BEvents::PointerEvent* event) { if (event->getButton() == BDevices::LEFT_BUTTON) { double x0 = getXOffset (); double y0 = getYOffset (); double w = getEffectiveWidth (); double h = getEffectiveHeight (); double ymin = scaleAnchorValue - scaleRatio * scaleAnchorYPos; if ((w == 0) || (h == 0)) return; double px = (event->getPosition().x - x0) / w; double py = ((y0 + h - event->getPosition().y) / h) * scaleRatio + ymin; // Snap to grid if (gridSnap) { px = snapX (px); py = snapY (py); } // Add new nodes, but not on top of a selected node or handle if (clickMode == NEW_NODE) { selection.clear (); switch (tool) { case ToolType::POINT_NODE_TOOL: { Node node = Node(NodeType::POINT_NODE, BUtilities::Point (px, py), BUtilities::Point (0, 0), BUtilities::Point (0, 0)); insertNode (node); } break; case ToolType::AUTO_SMOOTH_NODE_TOOL: { Node node = Node(NodeType::AUTO_SMOOTH_NODE, BUtilities::Point (px, py), BUtilities::Point (0, 0), BUtilities::Point (0, 0)); insertNode (node); } break; case ToolType::SYMMETRIC_SMOOTH_NODE_TOOL: { Node node = Node(NodeType::SYMMETRIC_SMOOTH_NODE, BUtilities::Point (px, py), BUtilities::Point (-0.1, 0), BUtilities::Point (0.1, 0)); insertNode (node); } break; case ToolType::CORNER_NODE_TOOL: { Node node = Node(NodeType::CORNER_NODE, BUtilities::Point (px, py), BUtilities::Point (-0.1, 0), BUtilities::Point (0.1, 0)); insertNode (node); } break; default: break; } undoSnapshots.push (*this); update(); } else if (clickMode == DRAG_SELECTION) { selection.setOrigin ({0, 0}); selection.setExtend ({0, 0}); undoSnapshots.push (*this); update (); } } } void ShapeWidget::onPointerDragged (BEvents::PointerEvent* event) { if (event->getButton() == BDevices::LEFT_BUTTON) { double x0 = getXOffset (); double y0 = getYOffset (); double w = getEffectiveWidth (); double h = getEffectiveHeight (); double ymin = scaleAnchorValue - scaleRatio * scaleAnchorYPos; if ((w == 0) || (h == 0)) return; double py = ((y0 + h - event->getPosition().y) / h) * scaleRatio + ymin; double px = (event->getPosition().x - x0) / w; // Node or handle dragged if ((grabbedNode >= 0) && (grabbedNode < int (nodes_.size))) { Node node = getNode (grabbedNode); // Snap to grid if (gridSnap) { px = snapX (px); py = snapY (py); } // Handle: Drag only grabbed handle if ((clickMode == DRAG_HANDLE) && (grabbedHandle > 0)) { // Drag right handle if (grabbedHandle == 2) { node.handle2.x = px - node.point.x; node.handle2.y = py - node.point.y; if (node.nodeType == SYMMETRIC_SMOOTH_NODE) node.handle1 = BUtilities::Point (0, 0) - node.handle2; changeNode (grabbedNode, node); } // Drag left handle else if (grabbedHandle == 1) { node.handle1.x = px - node.point.x; node.handle1.y = py - node.point.y; changeNode (grabbedNode, node); } update(); } // Point: Drag all selected points else if (clickMode == DRAG_NODE) { double dpy = py - node.point.y; double dpx = px - node.point.x; // Get sure that selected points are not moved over their unselected antecessors / successors for (int i = 0; (i < int (nodes_.size)) && (dpx != 0.0); ++i) { if (selection[i]) { Node iNode = getNode (i); // END_NODEs: No X movement allowed if (iNode.nodeType == NodeType::END_NODE) dpx = 0; // Find antecessor else if (dpx < 0) { size_t ant = selection.getUnselectedAntecessor (i); if (ant < nodes_.size) { Node antNode = getNode (ant); if (iNode.point.x + dpx < antNode.point.x) dpx = antNode.point.x - iNode.point.x; } } // Find successor else if (dpx > 0) { size_t suc = selection.getUnselectedSuccessor (i); if (suc < nodes_.size) { Node sucNode = getNode (suc); if (iNode.point.x + dpx > sucNode.point.x) dpx = sucNode.point.x - iNode.point.x; } } } } // Move selected points for (size_t i = 0; i < nodes_.size; ++i) { if (selection[i]) { Node iNode = getNode (i); //Y drag both END_NODEs if (iNode.nodeType == NodeType::END_NODE) { if (nodes_.size >= 2) { Node startNode = getNode (0); startNode.point.y += dpy; changeNode (0, startNode); Node endNode = getNode (nodes_.size - 1); endNode.point.y = startNode.point.y; changeNode (nodes_.size - 1, endNode); } } else { iNode.point.x += dpx; iNode.point.y += dpy; changeNode (i, iNode); } } } } update(); } // Drag selection box in edit mode else if (clickMode == DRAG_SELECTION) { BUtilities::Point p1 = selection.getOrigin (); selection.setExtend ({px - p1.x, py - p1.y}); BUtilities::Point p2 = p1 + selection.getExtend (); if (p2.x < p1.x) std::swap (p1.x, p2.x); if (p2.y < p1.y) std::swap (p1.y, p2.y); // Select / deselect selection[i] selection.fill (false); for (int i = 0; i < int (nodes_.size); ++i) { BUtilities::Point p = getNode(i).point; if ((p.x >= p1.x) && (p.x <= p2.x) && (p.y >= p1.y) && (p.y <= p2.y)) { selection[i] = true; } } update (); return; } // Scale dragged else { clickMode = DRAG_SCREEN; scaleAnchorYPos += (-event->getDelta().y) / h; update (); } } } void ShapeWidget::onWheelScrolled (BEvents::WheelEvent* event) { double ygrid = pow (10, floor (log10 (scaleRatio))); scaleRatio += 0.1 * ygrid * event->getDelta().y; if (scaleRatio < 0.01) scaleRatio = 0.01; update (); } void ShapeWidget::onValueChanged (BEvents::ValueChangedEvent* event) { if (event->getValue() == 1) { update (); cbfunction_[BEvents::EventType::VALUE_CHANGED_EVENT] (event); setValue (0); } } void ShapeWidget::onFocusIn (BEvents::FocusEvent* event) { if (event && event->getWidget()) { BUtilities::Point pos = event->getPosition(); focusText.moveTo (pos.x - 0.5 * focusText.getWidth(), pos.y - focusText.getHeight()); focusText.show(); } Widget::onFocusIn (event); } void ShapeWidget::onFocusOut (BEvents::FocusEvent* event) { if (event && event->getWidget()) focusText.hide(); Widget::onFocusOut (event); } void ShapeWidget::applyTheme (BStyles::Theme& theme) {applyTheme (theme, name_);} void ShapeWidget::applyTheme (BStyles::Theme& theme, const std::string& name) { focusText.applyTheme (theme, name + "/focus"); Widget::applyTheme (theme, name); // Foreground colors (curve) void* fgPtr = theme.getStyle(name, BWIDGETS_KEYWORD_FGCOLORS); if (fgPtr) fgColors = *((BColors::ColorSet*) fgPtr); // Foreground colors (curve) void* syPtr = theme.getStyle(name, "symbolcolors"); if (syPtr) syColors = *((BColors::ColorSet*) syPtr); // Background colors (grid) void* bgPtr = theme.getStyle(name, BWIDGETS_KEYWORD_BGCOLORS); if (bgPtr) bgColors = *((BColors::ColorSet*) bgPtr); // Font void* fontPtr = theme.getStyle(name, BWIDGETS_KEYWORD_FONT); if (fontPtr) lbfont = *((BStyles::Font*) fontPtr); if (fgPtr || bgPtr || syPtr || fontPtr) update (); } double ShapeWidget::snapX (const double x) { if (minorXSteps == 0) return x; double nrXDashes = (minorXSteps < 0.1 ? 4 : (minorXSteps < 0.2 ? 8 : 16)); double xDash = minorXSteps / nrXDashes; return round (x / xDash) * xDash; } double ShapeWidget::snapY (const double y) { if (scaleRatio == 0.0) return y; double ymin = scaleAnchorValue - scaleRatio * scaleAnchorYPos; double ymax = ymin + scaleRatio; double ygrid = pow (10, floor (log10 (scaleRatio / 1.5))); double nrYDashes = (ygrid / (ymax - ymin) < 0.2 ? 2 : 4); double yDash = ygrid / nrYDashes; return round (y / yDash) * yDash; } void ShapeWidget::drawLineOnMap (BUtilities::Point p1, BUtilities::Point p2) { Shape::drawLineOnMap (p1, p2); if (valueEnabled) setValue (1); // Value changed } void ShapeWidget::draw (const BUtilities::RectArea& area) { if ((!widgetSurface_) || (cairo_surface_status (widgetSurface_) != CAIRO_STATUS_SUCCESS)) return; ValueWidget::draw (area); double x0 = getXOffset (); double y0 = getYOffset (); double w = getEffectiveWidth (); double h = getEffectiveHeight (); double ymin = scaleAnchorValue - scaleRatio * scaleAnchorYPos; double ymax = ymin + scaleRatio; BColors::Color lineColor = *fgColors.getColor (BColors::NORMAL); BColors::Color fillColor = *fgColors.getColor (BColors::NORMAL); BColors::Color nodeColor = *syColors.getColor (BColors::NORMAL); BColors::Color activeNodeColor = *syColors.getColor (BColors::ACTIVE); BColors::Color gridColor = *bgColors.getColor (BColors::NORMAL); if (ymin == ymax) return; cairo_t* cr = cairo_create (widgetSurface_); if (cairo_status (cr) == CAIRO_STATUS_SUCCESS) { // Limit cairo-drawing area cairo_rectangle (cr, area.getX(), area.getY(), area.getWidth(), area.getHeight()); cairo_clip (cr); double ygrid = pow (10, floor (log10 (scaleRatio / 1.5))); int ldYgrid = log10 (ygrid); std::string nrformat = "%" + ((ygrid < 1) ? ("1." + std::to_string (-ldYgrid)) : (std::to_string (ldYgrid + 1) + ".0")) + "f"; cairo_text_extents_t ext; cairo_select_font_face (cr, lbfont.getFontFamily ().c_str (), lbfont.getFontSlant (), lbfont.getFontWeight ()); cairo_set_font_size (cr, lbfont.getFontSize ()); // Draw Y steps for (double yp = ceil (ymin / ygrid) * ygrid; yp <= ymax; yp += ygrid) { cairo_move_to (cr, x0, y0 + h - h * (yp - ymin) / (ymax - ymin)); cairo_line_to (cr, x0 + 0.02 * w, y0 + h - h * (yp - ymin) / (ymax - ymin)); std::string label = prefix + BUtilities::to_string (yp, nrformat) + ((unit != "") ? (" " + unit) : ""); cairo_text_extents (cr, label.c_str(), &ext); cairo_move_to (cr, x0 + 0.025 * w - ext.x_bearing, y0 + h - h * (yp - ymin) / (ymax - ymin) - ext.height / 2 - ext.y_bearing); cairo_set_source_rgba (cr, CAIRO_RGBA (lineColor)); cairo_show_text (cr, label.c_str ()); cairo_move_to (cr, x0 + 0.03 * w + ext.width, y0 + h - h * (yp - ymin) / (ymax - ymin)); cairo_line_to (cr, x0 + w, y0 + h - h * (yp - ymin) / (ymax - ymin)); } cairo_set_source_rgba (cr, CAIRO_RGBA (gridColor)); cairo_set_line_width (cr, 1); cairo_stroke (cr); // Draw lower Y limits if ((loLimit >= ymin) && (loLimit <= ymax)) { std::string label = "Lower limit"; cairo_text_extents (cr, label.c_str(), &ext); cairo_move_to (cr, x0 + 0.5 * w - 0.5 * ext.width - ext.x_bearing, y0 + h - h * (loLimit - ymin) / (ymax - ymin) - ext.height / 2 - ext.y_bearing); cairo_set_source_rgba (cr, CAIRO_RGBA (lineColor)); cairo_show_text (cr, label.c_str ()); cairo_move_to (cr, x0 + 0.1 * w, y0 + h - h * (loLimit - ymin) / (ymax - ymin)); cairo_line_to (cr, x0 + 0.48 * w - 0.5 * ext.width - ext.x_bearing, y0 + h - h * (loLimit - ymin) / (ymax - ymin)); cairo_move_to (cr, x0 + 0.52 * w + 0.5 * ext.width - ext.x_bearing, y0 + h - h * (loLimit - ymin) / (ymax - ymin)); cairo_line_to (cr, x0 + 0.9 * w, y0 + h - h * (loLimit - ymin) / (ymax - ymin)); cairo_set_source_rgba (cr, CAIRO_RGBA (lineColor)); cairo_set_line_width (cr, 1); cairo_stroke (cr); } // Draw upper Y limits if ((hiLimit >= ymin) && (hiLimit <= ymax)) { std::string label = "Upper limit"; cairo_text_extents (cr, label.c_str(), &ext); cairo_move_to (cr, x0 + 0.5 * w - 0.5 * ext.width - ext.x_bearing, y0 + h - h * (hiLimit - ymin) / (ymax - ymin) - ext.height / 2 - ext.y_bearing); cairo_set_source_rgba (cr, CAIRO_RGBA (lineColor)); cairo_show_text (cr, label.c_str ()); cairo_move_to (cr, x0 + 0.1 * w, y0 + h - h * (hiLimit - ymin) / (ymax - ymin)); cairo_line_to (cr, x0 + 0.48 * w - 0.5 * ext.width - ext.x_bearing, y0 + h - h * (hiLimit - ymin) / (ymax - ymin)); cairo_move_to (cr, x0 + 0.52 * w + 0.5 * ext.width - ext.x_bearing, y0 + h - h * (hiLimit - ymin) / (ymax - ymin)); cairo_line_to (cr, x0 + 0.9 * w, y0 + h - h * (hiLimit - ymin) / (ymax - ymin)); cairo_set_source_rgba (cr, CAIRO_RGBA (lineColor)); cairo_set_line_width (cr, 1); cairo_stroke (cr); } // Draw X steps for (double x = 0; x < 1; x += minorXSteps) { cairo_move_to (cr, x * w, 0); cairo_line_to (cr, x * w, h); } cairo_set_source_rgba (cr, CAIRO_RGBA (gridColor)); cairo_set_line_width (cr, 1.0); cairo_stroke (cr); for (double x = 0; x < 1; x += majorXSteps) { cairo_move_to (cr, x * w, 0); cairo_line_to (cr, x * w, h); } cairo_set_source_rgba (cr, CAIRO_RGBA (gridColor)); cairo_set_line_width (cr, 2.0); cairo_stroke (cr); // Draw grid if (gridVisible) { if (w * minorXSteps > 16) { cairo_save (cr); double nrXDashes = (minorXSteps < 0.1 ? 4 : (minorXSteps < 0.2 ? 8 : 16)); double xDash = minorXSteps / nrXDashes; double nrYDashes = (ygrid / (ymax - ymin) < 0.2 ? 2 : 4); double yDash = ygrid / nrYDashes; double dashes[2] = {GRIDSIZE, w * xDash - GRIDSIZE}; cairo_set_dash (cr, dashes, 2, 0.0); for (double yp = ceil (ymin / yDash) * yDash; yp <= ymax; yp += yDash) { double y = (yp - ymin) / (ymax - ymin) * h; cairo_move_to (cr, x0, y0 + h - y); cairo_line_to (cr, x0 + w, y0 + h - y); } cairo_set_source_rgba (cr, CAIRO_RGBA (gridColor)); cairo_set_line_width (cr, GRIDSIZE); cairo_stroke (cr); cairo_restore (cr); } } // Draw curve cairo_move_to (cr, x0, y0 + h - h * (retransform (map_[0]) - ymin) / (ymax - ymin)); for (int i = 1; i < MAPRES; ++i) cairo_line_to (cr, x0 + w * i / MAPRES, y0 + h - h * (retransform (map_[i]) - ymin) / (ymax - ymin)); cairo_set_line_width (cr, 2); cairo_set_source_rgba (cr, CAIRO_RGBA (lineColor)); cairo_stroke_preserve (cr); // Fill area under the curve cairo_line_to (cr, x0 + w, y0 + h); cairo_line_to (cr, x0, y0 + h); cairo_close_path (cr); cairo_set_line_width (cr, 0); cairo_pattern_t* pat = cairo_pattern_create_linear (0, y0 + h, 0, y0); cairo_pattern_add_color_stop_rgba (pat, 0, fillColor.getRed (), fillColor.getGreen (), fillColor.getBlue (), 0); cairo_pattern_add_color_stop_rgba (pat, 1, fillColor.getRed (), fillColor.getGreen (), fillColor.getBlue (), 0.5 * fillColor.getAlpha ()); cairo_set_source (cr, pat); cairo_fill (cr); cairo_pattern_destroy (pat); // Draw nodes for (unsigned int i = 0; i < nodes_.size; ++i) { Node iNode = getNode (i); double xp = iNode.point.x; double yp = iNode.point.y; if ((iNode.nodeType == NodeType::END_NODE) || (iNode.nodeType == NodeType::POINT_NODE)) { cairo_move_to (cr, x0 + xp * w - 6, y0 + h - h * (yp - ymin) / (ymax - ymin)); cairo_line_to (cr, x0 + xp * w, y0 + h - h * (yp - ymin) / (ymax - ymin) - 6); cairo_line_to (cr, x0 + xp * w + 6, y0 + h - h * (yp - ymin) / (ymax - ymin)); cairo_line_to (cr, x0 + xp * w, y0 + h - h * (yp - ymin) / (ymax - ymin) + 6); cairo_close_path (cr); } else cairo_rectangle (cr, x0 + xp * w - 6, y0 + h - h * (yp - ymin) / (ymax - ymin) - 6, 12, 12); if (selection[i]) { cairo_set_source_rgba (cr, CAIRO_RGBA (activeNodeColor)); cairo_set_line_width (cr, 2); cairo_stroke (cr); } else { cairo_set_source_rgba (cr, CAIRO_RGBA (nodeColor)); cairo_set_line_width (cr, 1); cairo_stroke (cr); } if (int (i) == grabbedNode) { // Draw handles if ((nodes_[i].nodeType == SYMMETRIC_SMOOTH_NODE) || (nodes_[i].nodeType == CORNER_NODE)) { if (i != 0) { double nx = iNode.handle1.x; double ny = iNode.handle1.y; cairo_move_to (cr, x0 + xp * w, y0 + h - h * (yp - ymin) / (ymax - ymin)); cairo_line_to (cr, x0 + (xp + nx) * w, y0 + h - h * (yp + ny - ymin) / (ymax - ymin)); cairo_arc (cr, x0 + (xp + nx) * w, y0 + h - h * (yp + ny - ymin) / (ymax - ymin), 3.0, 0.0, 2 * M_PI); cairo_set_line_width (cr, 1); cairo_stroke (cr); } if (i != nodes_.size - 1) { double nx = iNode.handle2.x; double ny = iNode.handle2.y; cairo_move_to (cr, x0 + xp * w, y0 + h - h * (yp - ymin) / (ymax - ymin)); cairo_line_to (cr, x0 + (xp + nx) * w, y0 + h - h * (yp + ny - ymin) / (ymax - ymin)); cairo_arc (cr, x0 + (xp + nx) * w, y0 + h - h * (yp + ny - ymin) / (ymax - ymin), 3.0, 0.0, 2 * M_PI); cairo_set_line_width (cr, 1); cairo_stroke (cr); } } } } // Draw selection box if (selection.getExtend () != BUtilities::Point (0, 0)) { BUtilities::Point p1 = selection.getOrigin (); BUtilities::Point ext = selection.getExtend (); cairo_rectangle (cr, x0 + p1.x * w, y0 + h - h * (p1.y - ymin) / (ymax - ymin), ext.x * w, - h * ext.y / (ymax - ymin)); cairo_set_source_rgba (cr, CAIRO_RGBA (lineColor)); cairo_set_line_width (cr, 1); double dashes[2] = {2.0, 2.0}; cairo_set_dash (cr, dashes, 2, 0); cairo_stroke (cr); } cairo_destroy (cr); } }
27,187
C++
.cpp
840
28.785714
233
0.627413
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,484
BSchafflGUI.cpp
sjaehn_BSchaffl/src/BSchafflGUI.cpp
/* B.Schaffl * MIDI Pattern Delay Plugin * * Copyright (C) 2018 - 2020 by Sven Jähnichen * * 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, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "BSchafflGUI.hpp" #include "BUtilities/stof.hpp" #include "BUtilities/to_string.hpp" #include "Ports.hpp" #include "screen.h" #include "BUtilities/vsystem.hpp" #include <exception> BSchafflGUI::BSchafflGUI (const char *bundle_path, const LV2_Feature *const *features, PuglNativeView parentWindow) : Window (1020, 480, "B.Schaffl", parentWindow, true, PUGL_MODULE, 0), controller (NULL), write_function (NULL), pluginPath (bundle_path ? std::string (bundle_path) : std::string ("")), mContainer (0, 0, 1020, 480, "main"), helpButton (950, 60, 24, 24, "halobutton", BSCHAFFL_LABEL_HELP), ytButton (980, 60, 24, 24, "halobutton", BSCHAFFL_LABEL_TUTORIAL), toolbox (380, 330, 620, 30, "scontainer"), toolIcon (4, 2 , 40, 26, "widget", pluginPath + "inc/tools.png"), convertToShapeIcon (50, 5, 50, 20, "widget", pluginPath + "inc/convert_to_linear_shape.png"), convertToStepsIcon (50, 5, 50, 20, "widget", pluginPath + "inc/convert_to_steps.png"), convertToShapeButton (48, 3, 54, 24, "halobutton", BSCHAFFL_LABEL_CONVERT_TO_SHAPE), convertToStepsButton (48, 3, 54, 24, "halobutton", BSCHAFFL_LABEL_CONVERT_TO_STEPS), markersToolbox (120, 5, 50, 20, "widget", pluginPath + "inc/markers_tb.png"), shapeToolbox (190, 5, 140, 20, "widget", pluginPath + "inc/shape_tools_tb.png"), editToolbox (360, 5, 80, 20, "widget", pluginPath + "inc/edit_tb.png"), historyToolbox (460, 5, 80, 20, "widget", pluginPath + "inc/history_tb.png"), gridToolbox (560, 5, 50, 20, "widget", pluginPath + "inc/grid_tb.png"), markersAutoButton (118, 3, 24, 24, "halobutton", BSCHAFFL_LABEL_ALL_MARKERS_AUTO), markersManualButton (148, 3, 24, 24, "halobutton", BSCHAFFL_LABEL_ALL_MARKERS_MANUAL), shapeToolButtons { HaloToggleButton (188, 3, 24, 24, "halobutton", BSCHAFFL_LABEL_SELECT), HaloToggleButton (218, 3, 24, 24, "halobutton", BSCHAFFL_LABEL_POINT_NODE), HaloToggleButton (248, 3, 24, 24, "halobutton", BSCHAFFL_LABEL_AUTO_NODE), HaloToggleButton (278, 3, 24, 24, "halobutton", BSCHAFFL_LABEL_SYMMETRIC_NODE), HaloToggleButton (308, 3, 24, 24, "halobutton", BSCHAFFL_LABEL_ASYMMETRIC_NODE) }, editToolButtons { HaloButton (358, 3, 24, 24, "halobutton", BSCHAFFL_LABEL_CUT), HaloButton (388, 3, 24, 24, "halobutton", BSCHAFFL_LABEL_COPY), HaloButton (418, 3, 24, 24, "halobutton", BSCHAFFL_LABEL_PASTE) }, historyToolButtons { HaloButton (458, 3, 24, 24, "halobutton", BSCHAFFL_LABEL_RESET), HaloButton (488, 3, 24, 24, "halobutton", BSCHAFFL_LABEL_UNDO), HaloButton (518, 3, 24, 24, "halobutton", BSCHAFFL_LABEL_REDO) }, gridShowButton (558, 3, 24, 24, "halobutton", BSCHAFFL_LABEL_SHOW_GRID), gridSnapButton (588, 3, 24, 24, "halobutton", BSCHAFFL_LABEL_SNAP_GRID), convertToShapeMessage ( 560, 100, 300, 150, "menu", BSCHAFFL_LABEL_CONVERT_TO_SHAPE_TITLE, BSCHAFFL_LABEL_CONVERT_TO_SHAPE_TEXT, std::vector<std::string>{BSCHAFFL_LABEL_OK, BSCHAFFL_LABEL_CANCEL} ), convertToShapeToLinearButton (20, 70, 12, 12, "slider", 0.0), convertToShapeToLinearText (60, 70, 200, 20, "menu/text", BSCHAFFL_LABEL_CONVERT_TO_SHAPE_LINEAR_TEXT), convertToShapeToConstButton (20, 90, 12, 12, "slider", 0.0), convertToShapeToConstText (60, 90, 200, 20, "menu/text", BSCHAFFL_LABEL_CONVERT_TO_SHAPE_CONST_TEXT), convertToStepsMessage ( 560, 100, 300, 110, "menu", BSCHAFFL_LABEL_CONVERT_TO_STEPS_TITLE, BSCHAFFL_LABEL_CONVERT_TO_STEPS_TEXT, std::vector<std::string>{BSCHAFFL_LABEL_OK, BSCHAFFL_LABEL_CANCEL} ), midiChFilterIcon (0, 0, 300, 20, "widget", pluginPath + BSCHAFFL_FILENAME_MIDI_CH_FILTER), midiChFilterContainer (0, 0, 340, 140, "screen"), midiChFilterText (10, 10, 320, 50, "text", BSCHAFFL_LABEL_MIDI_CH), midiChFilterAllSwitch (10, 36, 28, 14, "slider", 1), midiChFilterAllLabel (44, 33, 120, 20, "lflabel", BSCHAFFL_LABEL_ALL), midiMsgFilterIcon (0, 0, 300, 20, "widget", pluginPath + BSCHAFFL_FILENAME_MIDI_MSG_FILTER), midiMsgFilterContainer (0, 0, 340, 200, "screen"), midiMsgFilterText (10, 10, 320, 20, "text", BSCHAFFL_LABEL_MIDI_MSG), midiMsgFilterAllSwitch (10, 36, 28, 14, "slider", 1), midiMsgFilterAllLabel (50, 33, 120, 20, "lflabel", BSCHAFFL_LABEL_ALL), midiNoteOptionsIcon (0, 0, 300, 20, "widget", pluginPath + BSCHAFFL_FILENAME_MIDI_NOTE_OPTIONS), midiNoteOptionsContainer (0, 0, 340, 210, "screen"), midiNoteText (10, 10, 320, 50, "text", BSCHAFFL_LABEL_NOTE_TEXT), midiNotePositionSwitch (10, 68, 28, 14, "slider", 0.0), midiNotePositionLabel (50, 65, 240, 20, "lflabel", BSCHAFFL_LABEL_NOTE_KEEP_POSITION), midiNoteValueSwitch (10, 88, 28, 14, "slider", 0.0), midiNoteValueLabel (50, 85, 180, 20, "lflabel", BSCHAFFL_LABEL_NOTE_KEEP_DURATION), midiNoteOverlapListbox ( 160, 110, 100, 20, 0, 20, 100, 80, "menu", BItems::ItemList ({{0, BSCHAFFL_LABEL_DO_NOTHING}, {1, BSCHAFFL_LABEL_SPLIT}, {2, BSCHAFFL_LABEL_MERGE}}), 0 ), midiNoteOverlapLabel (10, 110, 150, 20, "lflabel", BSCHAFFL_LABEL_IF_NOTES_OVERLAP_TITLE), midiNoteText2 (10, 140, 320, 30, "text", BSCHAFFL_LABEL_IF_NOTES_OVERLAP_TEXT), midiNoteOffAmpLabel (10, 180, 110, 20, "lflabel", BSCHAFFL_LABEL_NOTE_OFF_AMP), midiNoteOffAmpListbox ( 120, 180, 220, 20, 0, 20, 220, 60, "menu", BItems::ItemList ({{0, BSCHAFFL_LABEL_USE_NOTE_ON_AMP}, {1, BSCHAFFL_LABEL_CALCULATE_FROM_END}}), 0 ), smartQuantizationIcon (0, 0, 300, 20, "widget", pluginPath + BSCHAFFL_FILENAME_SMART_QUANTIZATION), smartQuantizationContainer (0, 0, 340, 200, "screen"), smartQuantizationRangeSlider (10, 80, 110, 28, "slider", 0.25, 0.0, 0.5, 0.0, "%1.2f"), smartQuantizationMappingSwitch (10, 156, 28, 14, "slider", 1.0), smartQuantizationPositioningSwitch (10, 176, 28, 14, "slider", 0.0), smartQuantizationText1 (10, 10, 320, 70, "text", BSCHAFFL_LABEL_SMART_QUANTIZATION_TEXT_1), smartQuantizationRangeLabel (130, 90, 150, 20, "lflabel", BSCHAFFL_LABEL_RANGE_STEPS), smartQuantizationText2 (10, 120, 320, 30, "text", BSCHAFFL_LABEL_SMART_QUANTIZATION_TEXT_2), smartQuantizationMappingLabel (50, 153, 180, 20, "lflabel", BSCHAFFL_LABEL_ASSIGN_TO_STEP), smartQuantizationPositionLabel (50, 173, 180, 20, "lflabel", BSCHAFFL_LABEL_FIT_TO_STEP), userLatencyIcon (0, 0, 300, 20, "widget", pluginPath + BSCHAFFL_FILENAME_LATENCY), userLatencyContainer (0, 0, 340, 180, "screen"), timeCompensText (10, 10, 320, 30, "text", BSCHAFFL_LABEL_LATENCY_COMPENSATION_TEXT), timeCompensLabel (50, 45, 230, 20, "lflabel", BSCHAFFL_LABEL_LATENCY_COMPENSATION_TITLE), timeCompensSwitch (10, 48, 28, 14, "slider", 0.0), userLatencyText (10, 80, 320, 30, "text", BSCHAFFL_LABEL_LATENCY_USER_TEXT), userLatencySwitch (10, 118, 28, 14, "slider", 0.0), userLatencyLabel (50, 115, 180, 20, "lflabel", BSCHAFFL_LABEL_LATENCY_USER_TITLE), userLatencyValue (0, 0, 0, 0, "widget", 0.0, 0.0, 192000, 1.0), userLatencySlider (10, 140, 160, 28, "slider", 0, 0, 192000, 1, "%6.0f"), userLatencyUnitListbox ( 180, 150, 90, 20, 0, 20, 90, 60, "menu", BItems::ItemList ({{1, BSCHAFFL_LABEL_FRAMES}, {2, BSCHAFFL_LABEL_MS}}), 1 ), selectMenu ( 20, 90, 340, 350, "selectmenu", std::list<std::pair<Widget*, Widget*>> ({ {&midiChFilterIcon, &midiChFilterContainer}, {&midiMsgFilterIcon, &midiMsgFilterContainer}, {&midiNoteOptionsIcon, &midiNoteOptionsContainer}, {&smartQuantizationIcon, &smartQuantizationContainer}, {&userLatencyIcon, &userLatencyContainer} }) ), sharedDataSelection (58, 448, 304, 24, "widget", 0, 0, 4, 1), sContainer (380, 90, 620, 240, "scontainer"), modeSwitch (426, 71, 28, 14, "slider", 0.0), seqLenValueListbox ( 380, 380, 50, 20, 0, -220, 50, 220, "menu", BItems::ItemList ({ {0.125, "1/8"}, {0.25, "1/4"}, {0.333333, "1/3"}, {0.5, "1/2"}, {0.666667, "2/3"}, {0.75, "3/4"}, {1, "1"}, {2, "2"}, {3, "3"}, {4, "4"}, {6, "6"}, {8, "8"}, {12, "12"}, {16, "16"} }), 1.0 ), seqLenBaseListbox ( 440, 380, 90, 20, 0, -80, 90, 80, "menu", BItems::ItemList ({{0, BSCHAFFL_LABEL_SECONDS}, {1, BSCHAFFL_LABEL_BEATS}, {2, BSCHAFFL_LABEL_BARS}}), 2.0 ), ampSwingControl ( 565, 372, 120, 28, "slider", 1.0, 0.0078125, 128.0, 0.0, "%3.1f", [] (const double val, const double min, const double max) {return (val >= 1.0 ? 1.0 - 0.5 / LIMIT (val, min, max) : 0.5 * LIMIT (val, min, max));}, [] (const double frac, const double min, const double max) {return (frac >= 0.5 ? 0.5 / (1.0 - LIMIT (frac, 0, 1)) : 2 * LIMIT (frac, 0, 1));} ), ampRandomControl (720, 372, 120, 28, "slider", 0.0, 0.0, 1.0, 0.0, "%1.2f"), ampProcessControl (875, 372, 120, 28, "procslider", 1.0, -1.0, 2.0, 0.0, "%1.2f"), swingControl (565, 422, 120, 28, "slider", 1.0, 1.0 / 3.0, 3.0, 0.0), swingRandomControl (720, 422, 120, 28, "slider", 0.0, 0.0, 1.0, 0.0, "%1.2f"), swingProcessControl (875, 422, 120, 28, "procslider", 0.0, 0.0, 1.0, 0.0, "%1.2f"), nrStepsControl (380, 422, 155, 28, "slider", 1.0, 1.0, MAXSTEPS, 1.0, "%2.0f"), seqLenIcon (385, 405, 140, 12, "widget", pluginPath + BSCHAFFL_FILENAME_SEQUENCE_SIZE), ampSwingIcon (555, 405, 140, 12, "widget", pluginPath + BSCHAFFL_FILENAME_AMP_SWING), ampRandomIcon (710, 405, 140, 12, "widget", pluginPath + BSCHAFFL_FILENAME_AMP_RANDOM), ampProcessIcon (865, 405, 140, 12, "widget", pluginPath + BSCHAFFL_FILENAME_AMP_PROCESS), nrStepsIcon (385, 455, 140, 12, "widget", pluginPath + BSCHAFFL_FILENAME_NR_OF_STEPS), swingIcon (555, 455, 140, 12, "widget", pluginPath + BSCHAFFL_FILENAME_STEPS_SWING), swingRandomIcon (710, 455, 140, 12, "widget", pluginPath + BSCHAFFL_FILENAME_STEPS_RANDOM), swingProcessIcon (865, 455, 140, 12, "widget", pluginPath + BSCHAFFL_FILENAME_STEPS_PROCESS), stepControlContainer (40, 40, 580, 130, "widget", 0.0), shapeWidget (40, 40, 580, 130, "shape"), markerListBox (12, -88, 86, 86, "listbox", BItems::ItemList ({BSCHAFFL_LABEL_AUTO, BSCHAFFL_LABEL_MANUAL, BSCHAFFL_LABEL_ENTER})), enterFrame (86, 40, 320, 70, "menu"), enterPositionPopup (10, 10, 120, 20, 110, 60, "menu", BItems::ItemList ({BSCHAFFL_LABEL_NEW_POSITION, BSCHAFFL_LABEL_NEW_LENGTH}), 1), enterEdit (140, 10, 60, 20, "lflabel", "0.000"), enterSequencesPopup (210, 10, 100, 20, 80, 60, "menu", BItems::ItemList ({BSCHAFFL_LABEL_SEQUENCES, BSCHAFFL_LABEL_STEPS}), 1), enterOkButton (120, 40, 80, 20, "button", BSCHAFFL_LABEL_APPLY), latencyValue (0, 0, 0, 0, "widget", 0), latencyDisplay (900, 10, 120, 10, "smlabel", ""), controllers{nullptr}, messageLabel (480, 63, 465, 20, "hilabel", ""), inIcon (4, 14, 32, 12, "widget", pluginPath + BSCHAFFL_FILENAME_IN), ampIcon (4, 100, 32, 20, "widget", pluginPath + BSCHAFFL_FILENAME_AMP), delIcon (2, 185, 36, 12, "widget", pluginPath + BSCHAFFL_FILENAME_STR), outIcon (4, 214, 32, 12, "widget", pluginPath + BSCHAFFL_FILENAME_OUT), clipboard (), sz (1.0), bgImageSurface (nullptr), map (NULL), rate (48000.0) { // Init for (unsigned int i = 0; i < midiMsgFilterSwitches.size(); ++i) { midiMsgFilterSwitches[i] = BWidgets::HSwitch (10, 56 + i * 20, 28, 14, "slider", 1); midiMsgFilterLabels[i] = BWidgets::Label (50, 53 + i * 20, 180, 20, "lflabel", midiMsgGroupTexts[i]); } for (unsigned int i = 0; i < midiChFilterSwitches.size(); ++i) { midiChFilterSwitches[i] = BWidgets::HSwitch (10 + 80.0 * int (i / 4), 56 + int (i % 4) * 20, 28, 14, "slider", 1); midiChFilterLabels[i] = BWidgets::Label (44 + 80.0 * int (i / 4), 53 + int (i % 4) * 20, 36, 20, "lflabel", "#" + std::to_string (i + 1)); } for (int i = 0; i < 4; ++i) sharedDataButtons[i] = HaloToggleButton (80 * i, 0, 64, 24, "halobutton", BSCHAFFL_LABEL_SHARED_DATA " " + std::to_string (i + 1)); // Link widgets to controllers controllers[SEQ_LEN_VALUE] = &seqLenValueListbox; controllers[SEQ_LEN_BASE] = &seqLenBaseListbox; controllers[AMP_SWING] = &ampSwingControl; controllers[AMP_RANDOM] = &ampRandomControl; controllers[AMP_PROCESS] = &ampProcessControl; controllers[SWING] = &swingControl; controllers[SWING_RANDOM] = &swingRandomControl; controllers[SWING_PROCESS] = &swingProcessControl; controllers[NR_OF_STEPS] = &nrStepsControl; controllers[AMP_MODE] = &modeSwitch; controllers[NOTE_POSITION_STR] = &midiNotePositionSwitch; controllers[NOTE_VALUE_STR] = &midiNoteValueSwitch; controllers[NOTE_OVERLAP] = &midiNoteOverlapListbox; controllers[NOTE_OFF_AMP] = &midiNoteOffAmpListbox; controllers[QUANT_RANGE] = &smartQuantizationRangeSlider; controllers[QUANT_MAP] = &smartQuantizationMappingSwitch; controllers[QUANT_POS] = &smartQuantizationPositioningSwitch; controllers[TIME_COMPENS] = &timeCompensSwitch; controllers[USR_LATENCY] = &userLatencySwitch; controllers[USR_LATENCY_FR] = &userLatencyValue; for (unsigned int i = 0; i < midiChFilterSwitches.size(); ++i) controllers[MIDI_CH_FILTER + i] = &midiChFilterSwitches[i]; for (unsigned int i = 0; i < midiMsgFilterSwitches.size(); ++i) controllers[MSG_FILTER_NOTE + i] = &midiMsgFilterSwitches[i]; for (int i = 0; i < MAXSTEPS - 1; ++i) controllers[STEP_POS + i] = &markerWidgets[i]; for (int i = 0; i < MAXSTEPS; ++i) controllers[STEP_LEV + i] = &stepControl[i]; controllers[LATENCY] = &latencyValue; // Set callbacks for (BWidgets::ValueWidget* v : controllers) v->setCallbackFunction (BEvents::EventType::VALUE_CHANGED_EVENT, BSchafflGUI::valueChangedCallback); midiChFilterAllSwitch.setCallbackFunction (BEvents::EventType::VALUE_CHANGED_EVENT, BSchafflGUI::valueChangedCallback); midiMsgFilterAllSwitch.setCallbackFunction (BEvents::EventType::VALUE_CHANGED_EVENT, BSchafflGUI::valueChangedCallback); userLatencySlider.setCallbackFunction (BEvents::EventType::VALUE_CHANGED_EVENT, BSchafflGUI::valueChangedCallback); userLatencyUnitListbox.setCallbackFunction (BEvents::EventType::VALUE_CHANGED_EVENT, BSchafflGUI::valueChangedCallback); for (HaloToggleButton& s: sharedDataButtons) s.setCallbackFunction (BEvents::EventType::BUTTON_PRESS_EVENT, BSchafflGUI::sharedDataClickedCallback); sharedDataSelection.setCallbackFunction (BEvents::EventType::VALUE_CHANGED_EVENT, BSchafflGUI::valueChangedCallback); markerListBox.setCallbackFunction (BEvents::EventType::VALUE_CHANGED_EVENT, BSchafflGUI::listBoxChangedCallback); enterPositionPopup.setCallbackFunction (BEvents::EventType::VALUE_CHANGED_EVENT, BSchafflGUI::enterListBoxChangedCallback); enterSequencesPopup.setCallbackFunction (BEvents::EventType::VALUE_CHANGED_EVENT, BSchafflGUI::enterListBoxChangedCallback); enterOkButton.setCallbackFunction(BEvents::BUTTON_CLICK_EVENT, enterOkClickedCallback); convertToShapeButton.setCallbackFunction (BEvents::EventType::BUTTON_PRESS_EVENT, BSchafflGUI::convertButtonClickedCallback); convertToStepsButton.setCallbackFunction (BEvents::EventType::BUTTON_PRESS_EVENT, BSchafflGUI::convertButtonClickedCallback); convertToShapeToLinearButton.setCallbackFunction (BEvents::EventType::VALUE_CHANGED_EVENT, BSchafflGUI::lightButtonClickedCallback); convertToShapeToConstButton.setCallbackFunction (BEvents::EventType::VALUE_CHANGED_EVENT, BSchafflGUI::lightButtonClickedCallback); markersAutoButton.setCallbackFunction (BEvents::EventType::VALUE_CHANGED_EVENT, BSchafflGUI::markersAutoClickedCallback); markersManualButton.setCallbackFunction (BEvents::EventType::VALUE_CHANGED_EVENT, BSchafflGUI::markersAutoClickedCallback); for (HaloToggleButton& s: shapeToolButtons) s.setCallbackFunction (BEvents::EventType::BUTTON_PRESS_EVENT, BSchafflGUI::shapeToolClickedCallback); for (HaloButton& e: editToolButtons) e.setCallbackFunction (BEvents::EventType::BUTTON_PRESS_EVENT, BSchafflGUI::editToolClickedCallback); for (HaloButton& h: historyToolButtons) h.setCallbackFunction (BEvents::EventType::BUTTON_PRESS_EVENT, BSchafflGUI::historyToolClickedCallback); gridShowButton.setCallbackFunction (BEvents::EventType::BUTTON_PRESS_EVENT, BSchafflGUI::gridToolClickedCallback); gridSnapButton.setCallbackFunction (BEvents::EventType::BUTTON_PRESS_EVENT, BSchafflGUI::gridToolClickedCallback); helpButton.setCallbackFunction(BEvents::BUTTON_PRESS_EVENT, helpButtonClickedCallback); ytButton.setCallbackFunction(BEvents::BUTTON_PRESS_EVENT, ytButtonClickedCallback); shapeWidget.setCallbackFunction (BEvents::VALUE_CHANGED_EVENT, shapeChangedCallback); stepControlContainer.setCallbackFunction (BEvents::VALUE_CHANGED_EVENT, valueChangedCallback); // Configure widgets bgImageSurface = cairo_image_surface_create_from_png ((pluginPath + BSCHAFFL_FILENAME_BG).c_str()); widgetBg.loadFillFromCairoSurface (bgImageSurface); userLatencySlider.hide(); userLatencyUnitListbox.hide(); nrStepsControl.setScrollable (true); nrStepsControl.getDisplayLabel ()->setState (BColors::ACTIVE); swingControl.getDisplayLabel ()->setState (BColors::ACTIVE); markerListBox.setStacking (BWidgets::STACKING_OVERSIZE); enterFrame.setStacking (BWidgets::STACKING_OVERSIZE); enterFrame.hide(); enterEdit.setEditable (true); shapeWidget.hide(); shapeWidget.setMergeable (BEvents::POINTER_DRAG_EVENT, false); shapeWidget.setTool (ToolType::POINT_NODE_TOOL); shapeWidget.setDefaultShape (); shapeWidget.setScaleParameters (0.05, 0, 1.1); shapeWidget.setMajorXSteps (1.0); shapeWidget.setMinorXSteps (1.0/16.0); shapeWidget.setLowerLimit (0.0); shapeWidget.setHigherLimit (1.0); shapeToolButtons[1].setValue (1.0); gridSnapButton.setValue (1.0); shapeToolbox.hide(); editToolbox.hide(); //historyToolbox.hide(); gridToolbox.hide(); for (HaloToggleButton& s : shapeToolButtons) s.hide(); for (HaloButton& e : editToolButtons) e.hide(); //for (HaloButton& h : historyToolButtons) h.hide(); gridShowButton.hide(); gridSnapButton.hide(); convertToShapeIcon.hide(); convertToShapeMessage.setStacking (BWidgets::STACKING_OVERSIZE); //Initialialize and configure stepControllers double sw = sContainer.getEffectiveWidth() - 40; double sx = sContainer.getXOffset() + 40; for (int i = 0; i < MAXSTEPS; ++i) { stepControl[i] = BWidgets::VSlider ((i + 0.5) * sw / MAXSTEPS + sx - 7, 20, 14, 80, "slider", 1.0, 0.0, 1.0, 0.01); stepControl[i].setHardChangeable (false); stepControl[i].setScrollable (true); stepControl[i].setCallbackFunction (BEvents::EventType::VALUE_CHANGED_EVENT, BSchafflGUI::valueChangedCallback); stepControl[i].applyTheme (theme, "slider"); stepControlContainer.add (stepControl[i]); stepControlLabel[i] = BWidgets::Label ((i + 0.5) * sw / MAXSTEPS + sx - 14, 0, 28, 20, "mlabel", "1.00"); stepControlLabel[i].applyTheme (theme, "mlabel"); stepControlLabel[i].setState (BColors::ACTIVE); stepControlLabel[i].setEditable (true); stepControlLabel[i].setCallbackFunction(BEvents::EventType::MESSAGE_EVENT, stepControlLabelMessageCallback); stepControlContainer.add (stepControlLabel[i]); inputStepLabel[i] = BWidgets::Label (sx + (i + 0.1) * sw / MAXSTEPS, 10, 0.8 * sw / MAXSTEPS, 20, "steplabel", "#" + std::to_string (i + 1)); sContainer.add (inputStepLabel[i]); outputStepLabel[i] = BWidgets::Label (sx + (i + 0.1) * sw / MAXSTEPS, 180, 0.8 * sw / MAXSTEPS, 20, "steplabel", "#" + std::to_string (i + 1)); sContainer.add (outputStepLabel[i]); } //Initialialize and configure markers for (int i = 0; i < MAXSTEPS - 1; ++i) { markerWidgets[i] = Marker ((i + 1) * sw / MAXSTEPS + sx - 5, 154, 10, 16, "marker", (double(i) + 1.0) / MAXSTEPS, 0.0, 1.0, 0.0); markerWidgets[i].setHasValue (false); markerWidgets[i].setDraggable (true); markerWidgets[i].setCallbackFunction (BEvents::EventType::BUTTON_PRESS_EVENT, BSchafflGUI::markerClickedCallback); markerWidgets[i].setCallbackFunction (BEvents::EventType::POINTER_DRAG_EVENT, BSchafflGUI::markerDraggedCallback); markerWidgets[i].setCallbackFunction (BEvents::EventType::VALUE_CHANGED_EVENT, BSchafflGUI::valueChangedCallback); markerWidgets[i].applyTheme (theme, "slider"); sContainer.add (markerWidgets[i]); } setAutoMarkers (); rearrange_controllers (); redrawSContainer (); applyTheme (theme); // Pack widgets midiChFilterContainer.add (midiChFilterText); midiChFilterContainer.add (midiChFilterAllSwitch); midiChFilterContainer.add (midiChFilterAllLabel); for (unsigned int i = 0; i < midiChFilterSwitches.size(); ++i) { midiChFilterContainer.add (midiChFilterSwitches[i]); midiChFilterContainer.add (midiChFilterLabels[i]); } midiMsgFilterContainer.add (midiMsgFilterText); midiMsgFilterContainer.add (midiMsgFilterAllSwitch); midiMsgFilterContainer.add (midiMsgFilterAllLabel); for (unsigned int i = 0; i < midiMsgFilterSwitches.size(); ++i) { midiMsgFilterContainer.add (midiMsgFilterSwitches[i]); midiMsgFilterContainer.add (midiMsgFilterLabels[i]); } midiNoteOptionsContainer.add (midiNoteText); midiNoteOptionsContainer.add (midiNotePositionSwitch); midiNoteOptionsContainer.add (midiNotePositionLabel); midiNoteOptionsContainer.add (midiNoteValueSwitch); midiNoteOptionsContainer.add (midiNoteValueLabel); midiNoteOptionsContainer.add (midiNoteOverlapListbox); midiNoteOptionsContainer.add (midiNoteOverlapLabel); midiNoteOptionsContainer.add (midiNoteText2); midiNoteOptionsContainer.add (midiNoteOffAmpLabel); midiNoteOptionsContainer.add (midiNoteOffAmpListbox); smartQuantizationContainer.add (smartQuantizationRangeSlider); smartQuantizationContainer.add (smartQuantizationMappingSwitch); smartQuantizationContainer.add (smartQuantizationPositioningSwitch); smartQuantizationContainer.add (smartQuantizationText1); smartQuantizationContainer.add (smartQuantizationRangeLabel); smartQuantizationContainer.add (smartQuantizationText2); smartQuantizationContainer.add (smartQuantizationMappingLabel); smartQuantizationContainer.add (smartQuantizationPositionLabel); userLatencyContainer.add (timeCompensText); userLatencyContainer.add (timeCompensLabel); userLatencyContainer.add (timeCompensSwitch); userLatencyContainer.add (userLatencyText); userLatencyContainer.add (userLatencySwitch); userLatencyContainer.add (userLatencyLabel); userLatencyContainer.add (userLatencyValue); userLatencyContainer.add (userLatencySlider); userLatencyContainer.add (userLatencyUnitListbox); for (HaloToggleButton& s : sharedDataButtons) sharedDataSelection.add (s); mContainer.add (sharedDataSelection); sContainer.add (inIcon); sContainer.add (ampIcon); sContainer.add (delIcon); sContainer.add (outIcon); sContainer.add (stepControlContainer); sContainer.add (shapeWidget); mContainer.add (selectMenu); mContainer.add (sContainer); mContainer.add (helpButton); mContainer.add (ytButton); toolbox.add (toolIcon); toolbox.add (convertToShapeIcon); toolbox.add (convertToStepsIcon); toolbox.add (convertToShapeButton); toolbox.add (convertToStepsButton); toolbox.add (markersToolbox); toolbox.add (shapeToolbox); toolbox.add (editToolbox); toolbox.add (historyToolbox); toolbox.add (gridToolbox); toolbox.add (markersAutoButton); toolbox.add (markersManualButton); for (HaloToggleButton& s : shapeToolButtons) toolbox.add (s); for (HaloButton& e : editToolButtons) toolbox.add (e); for (HaloButton& h : historyToolButtons) toolbox.add (h); toolbox.add (gridShowButton); toolbox.add (gridSnapButton); mContainer.add (toolbox); enterFrame.add (enterPositionPopup); enterFrame.add (enterEdit); enterFrame.add (enterSequencesPopup); enterFrame.add (enterOkButton); markerListBox.add (enterFrame); mContainer.add (modeSwitch); mContainer.add (seqLenValueListbox); mContainer.add (seqLenBaseListbox); mContainer.add (ampSwingControl); mContainer.add (ampRandomControl); mContainer.add (ampProcessControl); mContainer.add (swingControl); mContainer.add (swingRandomControl); mContainer.add (swingProcessControl); mContainer.add (nrStepsControl); mContainer.add (latencyValue); mContainer.add (latencyDisplay); mContainer.add (messageLabel); mContainer.add (seqLenIcon); mContainer.add (ampSwingIcon); mContainer.add (ampRandomIcon); mContainer.add (ampProcessIcon); mContainer.add (nrStepsIcon); mContainer.add (swingIcon); mContainer.add (swingRandomIcon); mContainer.add (swingProcessIcon); convertToShapeMessage.add (convertToShapeToLinearButton); convertToShapeMessage.add (convertToShapeToLinearText); convertToShapeMessage.add (convertToShapeToConstButton); convertToShapeMessage.add (convertToShapeToConstText); add (mContainer); std::array<double, MAXSTEPS> s; s.fill (1.0); sliderHistory.setDefault (s); sliderHistory.clear(); //Scan host features for URID map LV2_URID_Map* m = NULL; for (int i = 0; features[i]; ++i) { if (strcmp(features[i]->URI, LV2_URID__map) == 0) m = (LV2_URID_Map*) features[i]->data; } if (!m) throw std::invalid_argument ("Host does not support urid:map"); //Map URIS map = m; getURIs (map, &uris); // Initialize forge lv2_atom_forge_init (&forge,map); } BSchafflGUI::~BSchafflGUI() {} void BSchafflGUI::portEvent(uint32_t port_index, uint32_t buffer_size, uint32_t format, const void* buffer) { // Notify port if ((format == uris.atom_eventTransfer) && (port_index == OUTPUT)) { const LV2_Atom* atom = (const LV2_Atom*) buffer; if ((atom->type == uris.atom_Blank) || (atom->type == uris.atom_Object)) { const LV2_Atom_Object* obj = (const LV2_Atom_Object*) atom; // Linked / unlinked to shared data if (obj->body.otype == uris.bschaffl_sharedDataLinkEvent) { LV2_Atom *oNr = NULL; lv2_atom_object_get ( obj, uris.bschaffl_sharedDataNr, &oNr, NULL ); if (oNr && (oNr->type == uris.atom_Int)) { const int nr = ((LV2_Atom_Int*)oNr)->body; if ((nr >= 0) && (nr <= 4) && (nr != sharedDataSelection.getValue())) { sharedDataSelection.setValueable (false); sharedDataSelection.setValue (nr); sharedDataSelection.setValueable (true); for (int i = 0; i < 4; ++i) { sharedDataButtons[i].setValueable (false); sharedDataButtons[i].setValue (i == nr - 1 ? 1 : 0); sharedDataButtons[i].setValueable (true); } } } } // Controller changed else if (obj->body.otype == uris.bschaffl_controllerEvent) { LV2_Atom *oNr = NULL, *oVal = NULL; lv2_atom_object_get ( obj, uris.bschaffl_controllerNr, &oNr, uris.bschaffl_controllerValue, &oVal, NULL ); if (oNr && (oNr->type == uris.atom_Int) && oVal && (oVal->type == uris.atom_Float)) { const int nr = ((LV2_Atom_Int*)oNr)->body; const float val = ((LV2_Atom_Float*)oVal)->body; if ((nr >= STEP_POS) && (nr < STEP_POS + MAXSTEPS - 1)) { setMarker (nr - STEP_POS, val); setAutoMarkers (); rearrange_controllers (); redrawSContainer (); } else setController (nr, val); } } // Status notification if (obj->body.otype == uris.bschaffl_statusEvent) { const LV2_Atom *oPos = NULL, *oLat = NULL, *oRate = NULL; lv2_atom_object_get ( obj, uris.bschaffl_step, &oPos, uris.bschaffl_latency, &oLat, uris.bschaffl_rate, &oRate, 0 ); if (oPos && (oPos->type == uris.atom_Int)) { const int step = LIMIT (((LV2_Atom_Int*)oPos)->body, 0, MAXSTEPS - 1); if (inputStepLabel[step].getName() != "actsteplabel") { for (int i = 0; i < MAXSTEPS; ++i) { if (i == step) { inputStepLabel[i].rename ("actsteplabel"); outputStepLabel[i].rename ("actsteplabel"); } else { inputStepLabel[i].rename ("steplabel"); outputStepLabel[i].rename ("steplabel"); } inputStepLabel[i].applyTheme (theme); outputStepLabel[i].applyTheme (theme); } } } if (oLat && (oLat->type == uris.atom_Float)) { const float latencyMs = ((LV2_Atom_Float*)oLat)->body; latencyDisplay.setText ((latencyMs > 0) ? BSCHAFFL_LABEL_LATENCY ": " + BUtilities::to_string (latencyMs, "%5.1f") + " " BSCHAFFL_LABEL_MS : ""); } if (oRate && (oRate->type == uris.atom_Double)) { rate = ((LV2_Atom_Double*)oRate)->body; const float latencyFr = ( userLatencyUnitListbox.getValue() == 2.0 ? userLatencySlider.getValue() * rate / 1000.0 : userLatencySlider.getValue() ); userLatencyValue.setValue (latencyFr); } } // Shape notification else if (obj->body.otype == uris.bschaffl_shapeEvent) { LV2_Atom *oData = NULL; lv2_atom_object_get ( obj, uris.bschaffl_shapeData, &oData, NULL ); if (oData && (oData->type == uris.atom_Vector)) { const LV2_Atom_Vector* vec = (const LV2_Atom_Vector*) oData; if (vec->body.child_type == uris.atom_Float) { int32_t size = (int32_t) ((oData->size - sizeof(LV2_Atom_Vector_Body)) / (7 * sizeof (float))); float* data = (float*) (&vec->body + 1); shapeWidget.setValueEnabled (false); shapeWidget.clearShape (); for (int i = 0; (i < size) && (i < MAXNODES); ++i) { Node node; node.nodeType = NodeType (int (data[i * 7])); node.point.x = data[i * 7 + 1]; node.point.y = data[i * 7 + 2]; node.handle1.x = data[i * 7 + 3]; node.handle1.y = data[i * 7 + 4]; node.handle2.x = data[i * 7 + 5]; node.handle2.y = data[i * 7 + 6]; shapeWidget.appendRawNode (node); } shapeWidget.validateShape(); shapeWidget.pushToSnapshots (); shapeWidget.update (); shapeWidget.setValueEnabled (true); } } } // Message notification if (obj->body.otype == uris.notify_messageEvent) { const LV2_Atom* data = NULL; lv2_atom_object_get(obj, uris.notify_message, &data, 0); if (data && (data->type == uris.atom_Int)) { const int messageNr = ((LV2_Atom_Int*)data)->body; std::string msg = ((messageNr >= NO_MSG) && (messageNr <= MAX_MSG) ? messageStrings[messageNr] : ""); messageLabel.setText (msg); } } } } // Scan controller ports else if ((format == 0) && (port_index >= CONTROLLERS) && (port_index < CONTROLLERS + NR_CONTROLLERS) && (sharedDataSelection.getValue() == 0)) { float* pval = (float*) buffer; const int controllerNr = port_index - CONTROLLERS; if ((controllerNr >= STEP_POS) && (controllerNr < STEP_POS + MAXSTEPS - 1)) { setMarker (controllerNr - STEP_POS, *pval); setAutoMarkers (); rearrange_controllers (); redrawSContainer (); } else setController (controllerNr, *pval); } } void BSchafflGUI::resizeGUI() { hide (); // Resize Fonts defaultFont.setFontSize (12 * sz); lfFont.setFontSize (12 * sz); txFont.setFontSize (12 * sz); mdFont.setFontSize (10 * sz); smFont.setFontSize (8 * sz); // Resize Background cairo_surface_t* surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, 1020 * sz, 480 * sz); cairo_t* cr = cairo_create (surface); cairo_scale (cr, sz, sz); cairo_set_source_surface(cr, bgImageSurface, 0, 0); cairo_paint(cr); widgetBg.loadFillFromCairoSurface(surface); cairo_destroy (cr); cairo_surface_destroy (surface); // Resize widgets RESIZE (mContainer, 0, 0, 1020, 480, sz); RESIZE (helpButton, 950, 60, 24, 24, sz); RESIZE (ytButton, 980, 60, 24, 24, sz); RESIZE (toolbox, 380, 330, 620, 40, sz); RESIZE (toolIcon, 4, 2, 40, 26, sz); RESIZE (convertToShapeIcon, 50, 5, 50, 20, sz); RESIZE (convertToStepsIcon, 50, 5, 50, 20, sz); RESIZE (convertToShapeButton, 48, 3, 54, 24, sz); RESIZE (convertToStepsButton, 48, 3, 54, 24, sz); RESIZE (markersToolbox, 120, 5, 50, 20, sz); RESIZE (shapeToolbox, 190, 5, 140, 20, sz); RESIZE (editToolbox, 360, 5, 80, 20, sz); RESIZE (historyToolbox, 460, 5, 80, 20, sz); RESIZE (gridToolbox, 560, 5, 50, 20, sz); RESIZE (markersAutoButton, 118, 3, 24, 24, sz); RESIZE (markersManualButton, 148, 3, 24, 24, sz); for (size_t i = 0; i < shapeToolButtons.size(); ++i) {RESIZE (shapeToolButtons[i], 188 + i * 30, 3, 24, 24, sz);} for (size_t i = 0; i < editToolButtons.size(); ++i) {RESIZE (editToolButtons[i], 358 + i * 30, 3, 24, 24, sz);} for (size_t i = 0; i < historyToolButtons.size(); ++i) {RESIZE (historyToolButtons[i], 458 + i * 30, 3, 24, 24, sz);} RESIZE (gridShowButton, 588, 3, 24, 24, sz); RESIZE (gridSnapButton, 588, 3, 24, 24, sz); RESIZE (midiChFilterIcon, 0, 0, 300, 20, sz); RESIZE (midiChFilterContainer, 0, 0, 340, 140, sz); RESIZE (midiChFilterText, 10, 10, 320, 50, sz); RESIZE (midiChFilterAllSwitch, 10, 36, 28, 14, sz); RESIZE (midiChFilterAllLabel, 44, 33, 120, 20, sz); for (unsigned int i = 0; i < midiChFilterSwitches.size(); ++i) { RESIZE (midiChFilterSwitches[i], 10 + 80.0 * int (i / 4), 56 + int (i % 4) * 20, 28, 14, sz); RESIZE (midiChFilterLabels[i], 44 + 80.0 * int (i / 4), 53 + int (i % 4) * 20, 36, 20, sz); } RESIZE (midiMsgFilterIcon, 0, 0, 300, 20, sz); RESIZE (midiMsgFilterContainer, 0, 0, 340, 200, sz); RESIZE (midiMsgFilterText, 10, 10, 320, 20, sz); RESIZE (midiMsgFilterAllSwitch, 10, 36, 28, 14, sz); RESIZE (midiMsgFilterAllLabel, 50, 33, 120, 20, sz); for (unsigned int i = 0; i < midiMsgFilterSwitches.size(); ++i) { RESIZE (midiMsgFilterSwitches[i], 10, 56 + i * 20, 28, 14, sz); RESIZE (midiMsgFilterLabels[i], 50, 53 + i * 20, 180, 20, sz); } RESIZE (midiNoteOptionsIcon, 0, 0, 300, 20, sz); RESIZE (midiNoteOptionsContainer, 0, 0, 340, 210, sz); RESIZE (midiNoteText, 10, 10, 320, 50, sz); RESIZE (midiNotePositionSwitch, 10, 68, 28, 14, sz); RESIZE (midiNotePositionLabel, 50, 65, 240, 20, sz); RESIZE (midiNoteValueSwitch, 10, 88, 28, 14, sz); RESIZE (midiNoteValueLabel, 50, 85, 180, 20, sz); RESIZE (midiNoteOverlapListbox, 160, 110, 100, 20, sz); midiNoteOverlapListbox.resizeListBox (BUtilities::Point (100 * sz, 80 * sz)); midiNoteOverlapListbox.moveListBox (BUtilities::Point (0, 20 * sz)); midiNoteOverlapListbox.resizeListBoxItems (BUtilities::Point (100 * sz, 20 * sz)); RESIZE (midiNoteOverlapLabel, 10, 110, 150, 20, sz); RESIZE (midiNoteText2, 10, 140, 320, 30, sz); RESIZE (midiNoteOffAmpLabel, 10, 180, 110, 20, sz); RESIZE (midiNoteOffAmpListbox, 120, 180, 220, 20, sz); midiNoteOffAmpListbox.resizeListBox (BUtilities::Point (220 * sz, 60 * sz)); midiNoteOffAmpListbox.moveListBox (BUtilities::Point (0, 20 * sz)); midiNoteOffAmpListbox.resizeListBoxItems (BUtilities::Point (220 * sz, 20 * sz)); RESIZE (smartQuantizationIcon, 0, 0, 300, 20, sz); RESIZE (smartQuantizationContainer, 0, 0, 340, 200, sz); RESIZE (smartQuantizationRangeSlider, 10, 80, 110, 28, sz); RESIZE (smartQuantizationMappingSwitch, 10, 156, 28, 14, sz); RESIZE (smartQuantizationPositioningSwitch, 10, 176, 28, 14, sz); RESIZE (smartQuantizationText1, 10, 10, 320, 70, sz); RESIZE (smartQuantizationRangeLabel, 130, 90, 150, 20, sz); RESIZE (smartQuantizationText2, 10, 120, 320, 30, sz); RESIZE (smartQuantizationMappingLabel, 50, 153, 180, 20, sz); RESIZE (smartQuantizationPositionLabel, 50, 173, 180, 20, sz); RESIZE (userLatencyIcon, 0, 0, 300, 20, sz); RESIZE (userLatencyContainer, 0, 0, 340, 180, sz); RESIZE (timeCompensText, 10, 10, 320, 30, sz); RESIZE (timeCompensLabel, 50, 45, 230, 20, sz); RESIZE (timeCompensSwitch, 10, 48, 28, 14, sz); RESIZE (userLatencyText, 10, 80, 320, 30, sz); RESIZE (userLatencySwitch, 10, 118, 28, 14, sz); RESIZE (userLatencyLabel, 50, 115, 180, 20, sz); RESIZE (userLatencySlider, 10, 140, 160, 28, sz); RESIZE (userLatencyUnitListbox, 180, 150, 90, 20, sz); userLatencyUnitListbox.resizeListBox (BUtilities::Point (90 * sz, 60 * sz)); userLatencyUnitListbox.moveListBox (BUtilities::Point (0, 20 * sz)); userLatencyUnitListbox.resizeListBoxItems (BUtilities::Point (40 * sz, 20 * sz)); RESIZE (selectMenu, 20, 90, 340, 350, sz); RESIZE (sharedDataSelection, 58, 448, 304, 24, sz); for (int i = 0; i < 4; ++i) {RESIZE (sharedDataButtons[i], 80 * i, 0, 64, 24, sz);} RESIZE (sContainer, 380, 90, 620, 240, sz); RESIZE (modeSwitch, 426, 71, 28, 14, sz); RESIZE (seqLenValueListbox, 380, 380, 50, 20, sz); seqLenValueListbox.resizeListBox (BUtilities::Point (50 * sz, 220 * sz)); seqLenValueListbox.moveListBox (BUtilities::Point (0, -220 * sz)); seqLenValueListbox.resizeListBoxItems (BUtilities::Point (50 * sz, 20 * sz)); RESIZE (seqLenBaseListbox, 440, 380, 90, 20, sz); seqLenBaseListbox.resizeListBox (BUtilities::Point (90 * sz, 80 * sz)); seqLenBaseListbox.moveListBox (BUtilities::Point (0, -80 * sz)); seqLenBaseListbox.resizeListBoxItems (BUtilities::Point (90 * sz, 20 * sz)); RESIZE (ampSwingControl, 565, 372, 120, 28, sz); RESIZE (ampRandomControl, 720, 372, 120, 28, sz); RESIZE (ampProcessControl, 875, 372, 120, 28, sz); RESIZE (swingControl, 565, 422, 120, 28, sz); RESIZE (swingRandomControl, 720, 422, 120, 28, sz); RESIZE (swingProcessControl, 875, 422, 120, 28, sz); RESIZE (nrStepsControl, 380, 422, 155, 28, sz); RESIZE (stepControlContainer, 40, 40, 580, 130, sz); RESIZE (shapeWidget, 40, 40, 580, 130, sz); RESIZE (markerListBox, 12, -88, 86, 86, sz); markerListBox.resizeItems (BUtilities::Point (80 * sz, 20 * sz)); enterFrame.resize (320 * sz, 70 * sz); if (markerListBox.getAbsolutePosition().x / sz > 600) enterFrame.moveTo (-320 * sz, 40 * sz); else enterFrame.moveTo (86 * sz, 40 * sz); RESIZE (enterPositionPopup, 10, 10, 120, 20, sz); enterPositionPopup.resizeListBox (BUtilities::Point (120 * sz, 60 * sz)); enterPositionPopup.moveListBox (BUtilities::Point (0, 20 * sz)); enterPositionPopup.resizeListBoxItems (BUtilities::Point (120 * sz, 20 * sz)); RESIZE (enterEdit, 140, 10, 70, 20, sz); RESIZE (enterSequencesPopup, 210, 10, 100, 20, sz); enterSequencesPopup.resizeListBox (BUtilities::Point (100 * sz, 60 * sz)); enterSequencesPopup.moveListBox (BUtilities::Point (0, 20 * sz)); enterSequencesPopup.resizeListBoxItems (BUtilities::Point (100 * sz, 20 * sz)); RESIZE (enterOkButton, 120, 40, 80, 20, sz); RESIZE (seqLenIcon, 385, 405, 140, 12, sz); RESIZE (ampSwingIcon, 555, 405, 140, 12, sz); RESIZE (ampRandomIcon, 710, 405, 140, 12, sz); RESIZE (ampProcessIcon, 865, 405, 140, 12, sz); RESIZE (nrStepsIcon, 385, 455, 140, 12, sz); RESIZE (swingIcon, 555, 455, 140, 12, sz); RESIZE (swingRandomIcon, 710, 455, 140, 12, sz); RESIZE (swingProcessIcon, 865, 455, 140, 12, sz); RESIZE (messageLabel, 480, 63, 465, 20, sz); RESIZE (latencyDisplay, 900, 10, 120, 10, sz); RESIZE (inIcon, 4, 14, 32, 12, sz); RESIZE (ampIcon, 4, 100, 32, 20, sz); RESIZE (delIcon, 2, 185, 36, 12, sz); RESIZE (outIcon, 4, 214, 32, 12, sz); // Update monitors rearrange_controllers (); redrawSContainer (); // Apply changes applyTheme (theme); show (); } void BSchafflGUI::applyTheme (BStyles::Theme& theme) { mContainer.applyTheme (theme); midiChFilterIcon.applyTheme (theme); midiChFilterContainer.applyTheme (theme); midiChFilterText.applyTheme (theme); midiChFilterAllSwitch.applyTheme (theme); midiChFilterAllLabel.applyTheme (theme); for (unsigned int i = 0; i < midiChFilterSwitches.size(); ++i) { midiChFilterSwitches[i].applyTheme (theme); midiChFilterLabels[i].applyTheme (theme); } midiMsgFilterIcon.applyTheme (theme); midiMsgFilterContainer.applyTheme (theme); midiMsgFilterText.applyTheme (theme); midiMsgFilterAllSwitch.applyTheme (theme); midiMsgFilterAllLabel.applyTheme (theme); for (unsigned int i = 0; i < midiMsgFilterSwitches.size(); ++i) { midiMsgFilterSwitches[i].applyTheme (theme); midiMsgFilterLabels[i].applyTheme (theme); } midiNoteOptionsIcon.applyTheme (theme); midiNoteOptionsContainer.applyTheme (theme); midiNoteText.applyTheme (theme); midiNotePositionSwitch.applyTheme (theme); midiNotePositionLabel.applyTheme (theme); midiNoteValueSwitch.applyTheme (theme); midiNoteValueLabel.applyTheme (theme); midiNoteOverlapListbox.applyTheme (theme); midiNoteOverlapLabel.applyTheme (theme); midiNoteText2.applyTheme (theme); midiNoteOffAmpLabel.applyTheme (theme); midiNoteOffAmpListbox.applyTheme (theme); smartQuantizationIcon.applyTheme (theme); smartQuantizationContainer.applyTheme (theme); smartQuantizationRangeSlider.applyTheme (theme); smartQuantizationMappingSwitch.applyTheme (theme); smartQuantizationPositioningSwitch.applyTheme (theme); smartQuantizationText1.applyTheme (theme); smartQuantizationRangeLabel.applyTheme (theme); smartQuantizationText2.applyTheme (theme); smartQuantizationMappingLabel.applyTheme (theme); smartQuantizationPositionLabel.applyTheme (theme); userLatencyIcon.applyTheme (theme); userLatencyContainer.applyTheme (theme); timeCompensText.applyTheme (theme); timeCompensLabel.applyTheme (theme); timeCompensSwitch.applyTheme (theme); userLatencyText.applyTheme (theme); userLatencySwitch.applyTheme (theme); userLatencyLabel.applyTheme (theme); userLatencyValue.applyTheme (theme); userLatencySlider.applyTheme (theme); userLatencyUnitListbox.applyTheme (theme); selectMenu.applyTheme (theme); sharedDataSelection.applyTheme (theme); for (HaloToggleButton& s : sharedDataButtons) s.applyTheme (theme); sContainer.applyTheme (theme); helpButton.applyTheme (theme); ytButton.applyTheme (theme); toolbox.applyTheme (theme); toolIcon.applyTheme (theme); convertToShapeIcon.applyTheme (theme); convertToStepsIcon.applyTheme (theme); convertToShapeButton.applyTheme (theme); convertToStepsButton.applyTheme (theme); markersToolbox.applyTheme (theme); shapeToolbox.applyTheme (theme); editToolbox.applyTheme (theme); historyToolbox.applyTheme (theme); gridToolbox.applyTheme (theme); markersAutoButton.applyTheme (theme); markersManualButton.applyTheme (theme); for (HaloToggleButton& s : shapeToolButtons) s.applyTheme (theme); for (HaloButton& e : editToolButtons) e.applyTheme (theme); for (HaloButton& h : historyToolButtons) h.applyTheme (theme); gridShowButton.applyTheme (theme); gridSnapButton.applyTheme (theme); convertToShapeMessage.applyTheme (theme); convertToShapeToLinearButton.applyTheme (theme); convertToShapeToLinearText.applyTheme (theme); convertToShapeToConstButton.applyTheme (theme); convertToShapeToConstText.applyTheme (theme); convertToStepsMessage.applyTheme (theme); seqLenIcon.applyTheme (theme); ampSwingIcon.applyTheme (theme); ampRandomIcon.applyTheme (theme); ampProcessIcon.applyTheme (theme); nrStepsIcon.applyTheme (theme); swingIcon.applyTheme (theme); swingRandomIcon.applyTheme (theme); swingProcessIcon.applyTheme (theme); modeSwitch.applyTheme (theme); seqLenValueListbox.applyTheme (theme); seqLenBaseListbox.applyTheme (theme); ampSwingControl.applyTheme (theme); ampRandomControl.applyTheme (theme); ampProcessControl.applyTheme (theme); swingControl.applyTheme (theme); swingRandomControl.applyTheme (theme); swingProcessControl.applyTheme (theme); stepControlContainer.applyTheme (theme); shapeWidget.applyTheme (theme); nrStepsControl.applyTheme (theme); latencyValue.applyTheme (theme); latencyDisplay.applyTheme (theme); messageLabel.applyTheme (theme); sContainer.applyTheme (theme); markerListBox.applyTheme (theme); enterFrame.applyTheme (theme); enterPositionPopup.applyTheme (theme); enterEdit.applyTheme (theme); enterSequencesPopup.applyTheme (theme); enterOkButton.applyTheme (theme); inIcon.applyTheme (theme); ampIcon.applyTheme (theme); delIcon.applyTheme (theme); outIcon.applyTheme (theme); for (int i = 0; i < MAXSTEPS; ++i) { stepControl[i].applyTheme (theme); stepControlLabel[i].applyTheme (theme); inputStepLabel[i].applyTheme (theme); outputStepLabel[i].applyTheme (theme); } } void BSchafflGUI::onConfigureRequest (BEvents::ExposeEvent* event) { Window::onConfigureRequest (event); sz = (getWidth() / 1020 > getHeight() / 480 ? getHeight() / 480 : getWidth() / 1020); resizeGUI (); } void BSchafflGUI::onCloseRequest (BEvents::WidgetEvent* event) { if (event) { Widget* requestWidget = event->getRequestWidget (); if (requestWidget) { if (requestWidget == (Widget*) &convertToShapeMessage) { if (convertToShapeMessage.getValue() == 1.0) { if (convertToShapeToLinearButton.getValue() != 0.0) { int nrSteps = nrStepsControl.getValue(); shapeWidget.setValueEnabled (false); shapeWidget.clearShape (); shapeWidget.appendRawNode ( Node ( END_NODE, {0.0, (getStepValue (0) + getStepValue (nrSteps - 1)) /2}, {0.0, 0.0}, {0.0, 0.0} ) ); for (int i = 0; i < nrSteps; ++i) { shapeWidget.appendRawNode ( Node ( POINT_NODE, {(double (i) + 0.5) / double (nrSteps), getStepValue (i)}, {0.0, 0.0}, {0.0, 0.0} ) ); } shapeWidget.appendRawNode ( Node ( END_NODE, {1.0, (getStepValue (0) + getStepValue (nrSteps - 1)) /2}, {0.0, 0.0}, {0.0, 0.0} ) ); shapeWidget.validateShape(); shapeWidget.pushToSnapshots (); shapeWidget.update (); shapeWidget.setValueEnabled (true); shapeWidget.setValue (1.0); } else if (convertToShapeToConstButton.getValue() != 0.0) { int nrSteps = nrStepsControl.getValue(); shapeWidget.setValueEnabled (false); shapeWidget.clearShape (); shapeWidget.appendRawNode (Node (END_NODE, {0.0, (getStepValue (0))}, {0.0, 0.0}, {0.0, 0.0})); for (int i = 0; i < nrSteps; ++i) { if (i != 0) { shapeWidget.appendRawNode ( Node ( POINT_NODE, {double (i) / double (nrSteps), getStepValue (i)}, {0.0, 0.0}, {0.0, 0.0} ) ); } shapeWidget.appendRawNode ( Node ( POINT_NODE, {double (i + 1) / double (nrSteps) - 1.0 / double (MAPRES), getStepValue (i)}, {0.0, 0.0}, {0.0, 0.0} ) ); } shapeWidget.appendRawNode (Node (END_NODE, {1.0, (getStepValue (0))}, {0.0, 0.0}, {0.0, 0.0})); shapeWidget.validateShape(); shapeWidget.pushToSnapshots (); shapeWidget.update (); shapeWidget.setValueEnabled (true); shapeWidget.setValue (1.0); } } if (requestWidget->getMainWindow()) release (requestWidget); } else if (requestWidget == (Widget*) &convertToStepsMessage) { if (convertToStepsMessage.getValue() == 1.0) { // Convert to sliders int nrSteps = nrStepsControl.getValue(); for (int i = 0; i < nrSteps; ++i) { stepControl[i].setValue (shapeWidget.getMapValue ((double (i) + 0.5) / double (nrSteps))); } } if (requestWidget->getMainWindow()) release (requestWidget); } else Window::onCloseRequest (event); } } } double BSchafflGUI::getStepValue (const int stepNr) const { const float aswing = ((stepNr % 2) == 0 ? ampSwingControl.getValue() : 1.0 / ampSwingControl.getValue()); return stepControl[stepNr].getValue() * LIM (aswing, 0, 1); } void BSchafflGUI::sendUiStatus (const bool on) { uint8_t obj_buf[64]; lv2_atom_forge_set_buffer(&forge, obj_buf, sizeof(obj_buf)); LV2_Atom_Forge_Frame frame; LV2_Atom* msg = (LV2_Atom*)lv2_atom_forge_object(&forge, &frame, 0, (on ? uris.bschaffl_uiOn : uris.bschaffl_uiOff)); lv2_atom_forge_pop(&forge, &frame); write_function(controller, INPUT, lv2_atom_total_size(msg), uris.atom_eventTransfer, msg); } void BSchafflGUI::sendShape () { size_t size = shapeWidget.size (); uint8_t obj_buf[4096]; lv2_atom_forge_set_buffer(&forge, obj_buf, sizeof(obj_buf)); // Load shapeBuffer float shapeBuffer[MAXNODES * 7]; for (unsigned int i = 0; i < size; ++i) { Node node = shapeWidget.getRawNode (i); shapeBuffer[i * 7 + 0] = (float)node.nodeType; shapeBuffer[i * 7 + 1] = (float)node.point.x; shapeBuffer[i * 7 + 2] = (float)node.point.y; shapeBuffer[i * 7 + 3] = (float)node.handle1.x; shapeBuffer[i * 7 + 4] = (float)node.handle1.y; shapeBuffer[i * 7 + 5] = (float)node.handle2.x; shapeBuffer[i * 7 + 6] = (float)node.handle2.y; } // Notify shapeBuffer LV2_Atom_Forge_Frame frame; LV2_Atom* msg = (LV2_Atom*)lv2_atom_forge_object (&forge, &frame, 0, uris.bschaffl_shapeEvent); lv2_atom_forge_key(&forge, uris.bschaffl_shapeData); lv2_atom_forge_vector(&forge, sizeof(float), uris.atom_Float, (uint32_t) (7 * size), &shapeBuffer); lv2_atom_forge_pop(&forge, &frame); write_function (controller, INPUT, lv2_atom_total_size(msg), uris.atom_eventTransfer, msg); } void BSchafflGUI::sendSharedDataNr () { uint8_t obj_buf[64]; lv2_atom_forge_set_buffer(&forge, obj_buf, sizeof(obj_buf)); LV2_Atom_Forge_Frame frame; LV2_Atom* msg = (LV2_Atom*)lv2_atom_forge_object(&forge, &frame, 0, uris.bschaffl_sharedDataLinkEvent); lv2_atom_forge_key (&forge, uris.bschaffl_sharedDataNr); lv2_atom_forge_int (&forge, sharedDataSelection.getValue()); lv2_atom_forge_pop(&forge, &frame); write_function(controller, INPUT, lv2_atom_total_size(msg), uris.atom_eventTransfer, msg); } void BSchafflGUI::sendController (const int nr, const float value) { uint8_t obj_buf[64]; lv2_atom_forge_set_buffer(&forge, obj_buf, sizeof(obj_buf)); LV2_Atom_Forge_Frame frame; LV2_Atom* msg = (LV2_Atom*)lv2_atom_forge_object(&forge, &frame, 0, uris.bschaffl_controllerEvent); lv2_atom_forge_key (&forge, uris.bschaffl_controllerNr); lv2_atom_forge_int (&forge, nr); lv2_atom_forge_key (&forge, uris.bschaffl_controllerValue); lv2_atom_forge_float (&forge, value); lv2_atom_forge_pop(&forge, &frame); write_function(controller, INPUT, lv2_atom_total_size(msg), uris.atom_eventTransfer, msg); } float BSchafflGUI::setController (const int nr, const double value) { controllers[nr]->setValueable (false); controllers[nr]->setValue (value); controllers[nr]->setValueable (true); if (nr == AMP_MODE) { if (value == 0.0f) { stepControlContainer.show(); shapeWidget.hide(); shapeToolbox.hide(); editToolbox.hide(); gridToolbox.hide(); for (HaloToggleButton& s : shapeToolButtons) s.hide(); for (HaloButton& e : editToolButtons) e.hide(); gridShowButton.hide(); gridSnapButton.hide(); ampSwingControl.setState (BColors::NORMAL); convertToShapeIcon.hide(); convertToStepsIcon.show(); convertToShapeButton.hide(); convertToStepsButton.show(); if (convertToShapeMessage.getParent()) release (&convertToShapeMessage); } else { stepControlContainer.hide(); shapeWidget.show(); shapeToolbox.show(); editToolbox.show(); gridToolbox.show(); for (HaloToggleButton& s : shapeToolButtons) s.show(); for (HaloButton& e : editToolButtons) e.show(); gridShowButton.show(); gridSnapButton.show(); ampSwingControl.setState (BColors::INACTIVE); convertToShapeIcon.show(); convertToStepsIcon.hide(); convertToShapeButton.show(); convertToStepsButton.hide(); if (convertToStepsMessage.getParent()) release (&convertToStepsMessage); } } else if ((nr >= MIDI_CH_FILTER) && (nr < MIDI_CH_FILTER + NR_MIDI_CHS)) { int count = 0; for (BWidgets::HSwitch& s : midiChFilterSwitches) { if (s.getValue() != 0.0) ++count; } if (count == 0) { midiChFilterAllSwitch.setState (BColors::NORMAL); midiChFilterAllLabel.setState (BColors::NORMAL); midiChFilterAllSwitch.setValue (0.0); } else if (count == NR_MIDI_CHS) { midiChFilterAllSwitch.setState (BColors::NORMAL); midiChFilterAllLabel.setState (BColors::NORMAL); midiChFilterAllSwitch.setValue (1.0); } else { midiChFilterAllSwitch.setState (BColors::INACTIVE); midiChFilterAllLabel.setState (BColors::INACTIVE); } } else if ((nr >= MSG_FILTER_NOTE) && (nr < MSG_FILTER_NOTE + NR_MIDI_MSG_FILTERS)) { int count = 0; for (BWidgets::HSwitch& s : midiMsgFilterSwitches) { if (s.getValue() != 0.0) ++count; } if (count == 0) { midiMsgFilterAllSwitch.setState (BColors::NORMAL); midiMsgFilterAllLabel.setState (BColors::NORMAL); midiMsgFilterAllSwitch.setValue (0.0); } else if (count == NR_MIDI_MSG_FILTERS) { midiMsgFilterAllSwitch.setState (BColors::NORMAL); midiMsgFilterAllLabel.setState (BColors::NORMAL); midiMsgFilterAllSwitch.setValue (1.0); } else { midiMsgFilterAllSwitch.setState (BColors::INACTIVE); midiMsgFilterAllLabel.setState (BColors::INACTIVE); } } else if (nr == USR_LATENCY) { if (value == 0.0) { userLatencySlider.hide(); userLatencyUnitListbox.hide(); } else { userLatencySlider.show(); userLatencyUnitListbox.show(); } } else if ((nr >= STEP_POS) && (nr < STEP_POS + MAXSTEPS - 1)) return (((Marker*)controllers[nr])->hasValue() ? value : 0.0f); else if ((nr >= STEP_LEV) && (nr < STEP_LEV + MAXSTEPS)) { int stepNr = nr - STEP_LEV; stepControlLabel[stepNr].setText (BUtilities::to_string (value, "%1.2f")); std::array<double, MAXSTEPS> u = sliderHistory.undo(); for (int i = 0; i < MAXSTEPS; ++i) { if ((i != stepNr) && (float (u[i]) != float (stepControl[i].getValue()))) { sliderHistory.redo(); break; } } stepControlContainer.setValue (1.0); } else if (nr == AMP_SWING) rearrange_controllers(); else if (nr == AMP_PROCESS) { if ((value >= 0.0) && (value <= 1.0)) ampProcessControl.setState (BColors::NORMAL); else ampProcessControl.setState (BColors::ACTIVE); } else if (nr == SWING) { setAutoMarkers(); rearrange_controllers(); redrawSContainer(); } else if (nr == NR_OF_STEPS) { shapeWidget.setMinorXSteps (1.0 / value); setAutoMarkers(); rearrange_controllers(); redrawSContainer(); } return value; } void BSchafflGUI::setMarker (const int markerNr, double value) { if ((markerNr < 0) || (markerNr >= MAXSTEPS - 1)) return; // Value 0.0: Automatic if (value == 0.0) { markerWidgets[markerNr].setHasValue (false); } else { // Set value and switch off automatic value = LIMIT (value, MINMARKERVALUE, 1.0); markerWidgets[markerNr].setHasValue (true); markerWidgets[markerNr].setValue (value); // Validate ancessors for (int i = markerNr - 1; i >= 0; --i) { if (markerWidgets[i].hasValue()) { if (markerWidgets[i].getValue() > value) markerWidgets[i].setValue (value); else break; } } // Validate successors for (int i = markerNr + 1; i < MAXSTEPS - 1; ++i) { if (markerWidgets[i].hasValue()) { if (markerWidgets[i].getValue() < value) markerWidgets[i].setValue (value); else break; } } } } void BSchafflGUI::setAutoMarkers () { int nrMarkers = controllers[NR_OF_STEPS]->getValue() - 1; int start = 0; for (int i = 0; i < nrMarkers; ++i) { if (!markerWidgets[i].hasValue()) { if ((i == nrMarkers - 1) || (markerWidgets[i + 1].hasValue())) { double swing = 2.0 * swingControl.getValue() / (swingControl.getValue() + 1.0); double anc = (start == 0 ? 0 : markerWidgets[start - 1].getValue()); double suc = (i == nrMarkers - 1 ? 1 : markerWidgets[i + 1].getValue()); double diff = suc - anc; double dist = i - start + 1.0 + (int (i - start) & 1 ? ((start & 1) ? 2.0 - swing : swing) : 1.0); double step = (diff < 0 ? 0 : diff / dist); for (int j = start; j <= i; ++j) { double f = ((j & 1) ? 2.0 - swing : swing); anc += f * step; markerWidgets[j].setValue (anc); } } } else start = i + 1; } } void BSchafflGUI::rearrange_controllers () { const int nrStepsi = controllers[NR_OF_STEPS]->getValue(); if ((nrStepsi < 1) || (nrStepsi > MAXSTEPS)) return; const double sw = sContainer.getWidth() - 40 * sz; const double sx = 40 * sz; const double sccw = stepControlContainer.getWidth(); const double oddf = (ampSwingControl.getValue() >= 1.0 ? 1.0 : ampSwingControl.getValue()); const double evenf = (ampSwingControl.getValue() >= 1.0 ? 1.0 / ampSwingControl.getValue() : 1.0); for (int i = 0; i < MAXSTEPS; ++i) { if (i < nrStepsi) { stepControl[i].resize (14 * sz, (14 + LIMIT (96 * ((i % 2) == 0 ? oddf : evenf), 0, 96 )) * sz); stepControl[i].moveTo ((i + 0.5) * sccw / nrStepsi - 7 * sz, 130 * sz - stepControl[i].getHeight()); stepControl[i].show(); if (i < nrStepsi - 1) markerWidgets[i].resize (10 * sz, 16 * sz); stepControlLabel[i].moveTo ((i + 0.5) * sccw / nrStepsi - 14 * sz, 0); stepControlLabel[i].resize (28 * sz, 20 * sz); stepControlLabel[i].show(); inputStepLabel[i].moveTo (sx + (i + 0.1) * sw / nrStepsi, 10 * sz); inputStepLabel[i].resize (0.8 * (sw / nrStepsi), 20 * sz); inputStepLabel[i].show(); const double outx = (i == 0 ? 0.0 : markerWidgets[i - 1].getValue() * sw); const double outw = ( i == 0 ? markerWidgets[i].getValue() * sw : ( i < nrStepsi - 1 ? (markerWidgets[i].getValue() - markerWidgets[i - 1].getValue()) * sw : (1 - markerWidgets[i - 1].getValue()) * sw ) ); outputStepLabel[i].moveTo (sx + outx + 0.1 * outw, 210 * sz); outputStepLabel[i].resize (0.8 * outw, 20 * sz); outputStepLabel[i].show(); } else { stepControl[i].hide (); stepControlLabel[i].hide(); inputStepLabel[i].hide(); outputStepLabel[i].hide(); } } for (int i = 0; i < MAXSTEPS - 1; ++i) { if (i < nrStepsi - 1) { markerWidgets[i].moveTo (markerWidgets[i].getValue() * sw + sx - 5 * sz, 184 * sz); markerWidgets[i].show (); } else markerWidgets[i].hide (); } } void BSchafflGUI::valueChangedCallback (BEvents::Event* event) { if ((event) && (event->getWidget ())) { BWidgets::ValueWidget* widget = (BWidgets::ValueWidget*) event->getWidget (); const double value = widget->getValue(); if (widget->getMainWindow ()) { BSchafflGUI* ui = (BSchafflGUI*) widget->getMainWindow (); // Get controller nr int controllerNr = -1; for (int i = 0; i < NR_CONTROLLERS; ++i) { if (widget == ui->controllers[i]) { controllerNr = i; break; } } if (controllerNr >= 0) { if (controllerNr != LATENCY) { const float v = ui->setController (controllerNr, value); if (ui->sharedDataSelection.getValue()) ui->sendController (controllerNr, v); else ui->write_function (ui->controller, CONTROLLERS + controllerNr, sizeof (float), 0, &v); } } else if (widget == &ui->stepControlContainer) { if (value != 0.0) { std::array<double, MAXSTEPS> steps; for (int i = 0; i < MAXSTEPS; ++i) steps[i] = ui->stepControl[i].getValue(); ui->sliderHistory.push (steps); ui->stepControlContainer.setValue (0.0); } } else if (widget == &ui->midiChFilterAllSwitch) { for (BWidgets::HSwitch& s : ui->midiChFilterSwitches) s.setValue (value); } else if (widget == &ui->midiMsgFilterAllSwitch) { for (BWidgets::HSwitch& s : ui->midiMsgFilterSwitches) s.setValue (value); } else if (widget == &ui->userLatencySlider) { const double latencyFr = ( ui->userLatencyUnitListbox.getValue() == 2.0 ? ui->userLatencySlider.getValue() * ui->rate / 1000.0 : ui->userLatencySlider.getValue() ); ui->userLatencyValue.setValue (latencyFr); } else if (widget == &ui->userLatencyUnitListbox) { // Translate slider value const double val = ( ui->userLatencyUnitListbox.getValue() == 2.0 ? ui->userLatencySlider.getValue() * 1000.0 / ui->rate : ui->userLatencySlider.getValue() * ui->rate / 1000.0 ); // Set new slider limits const double max = (ui->userLatencyUnitListbox.getValue() == 2.0 ? 192000000.0 / ui->rate : 192000.0); ui->userLatencySlider.setValueable (false); ui->userLatencySlider.setMax (max); ui->userLatencySlider.setValueable (true); ui->userLatencySlider.setValue (val); } else if (widget == &ui->sharedDataSelection) { const int val = ui->sharedDataSelection.getValue() - 1; for (int i = 0; i < 4; ++i) { ui->sharedDataButtons[i].setValueable (false); ui->sharedDataButtons[i].setValue (i == val ? 1 : 0); ui->sharedDataButtons[i].setValueable (true); } ui->sendSharedDataNr(); } } } } void BSchafflGUI::shapeChangedCallback (BEvents::Event* event) { if (!event) return; ShapeWidget* widget = (ShapeWidget*) event->getWidget (); if (!widget) return; float value = widget->getValue(); if (value != 1.0) return; BSchafflGUI* ui = (BSchafflGUI*) widget->getMainWindow(); if (!ui) return; ui->sendShape (); } void BSchafflGUI::markerClickedCallback (BEvents::Event* event) { if (!event) return; BEvents::PointerEvent* pev = (BEvents::PointerEvent*) event; if (pev->getButton() != BDevices::RIGHT_BUTTON) return; Marker* marker = (Marker*)event->getWidget(); if (!marker) return; marker->raiseToTop(); BSchafflGUI* ui = (BSchafflGUI*)marker->getMainWindow(); if (!ui) return; int nrSteps = ui->controllers[NR_OF_STEPS]->getValue(); for (int i = 0; i < nrSteps - 1; ++i) { if (marker == &ui->markerWidgets[i]) { Marker* oldMarker = (Marker*) ui->markerListBox.getParent(); ui->markerListBox.setValue (UNSELECTED); if (oldMarker && (oldMarker == marker)) { if (ui->markerListBox.isVisible()) ui->markerListBox.hide(); else { ui->markerListBox.show (); ui->enterFrame.hide(); } } else if (oldMarker && (oldMarker != marker)) { oldMarker->release (&ui->markerListBox); marker->add (ui->markerListBox); ui->markerListBox.show(); ui->enterFrame.hide(); } else { marker->add (ui->markerListBox); ui->markerListBox.show(); ui->enterFrame.hide(); } } } } void BSchafflGUI::markerDraggedCallback (BEvents::Event* event) { if (!event) return; BEvents::PointerEvent* pev = (BEvents::PointerEvent*) event; if (pev->getButton() != BDevices::LEFT_BUTTON) return; Marker* marker = (Marker*)event->getWidget(); if (!marker) return; marker->raiseToTop(); BSchafflGUI* ui = (BSchafflGUI*)marker->getMainWindow(); if (!ui) return; int nrSteps = ui->controllers[NR_OF_STEPS]->getValue(); for (int i = 0; i < nrSteps - 1; ++i) { if (marker == &ui->markerWidgets[i]) { double x0 = ui->sContainer.getXOffset() + 40 * ui->sz; double w = ui->sContainer. getEffectiveWidth() - 40 * ui->sz; double frac = (w > 0 ? (pev->getPosition().x + marker->getPosition().x - x0) / w : MINMARKERVALUE); frac = LIMIT (frac, MINMARKERVALUE, 1.0); // Limit to antecessors value for (int j = i - 1; j >= 0; --j) { if (ui->markerWidgets[j].hasValue()) { if (frac < ui->markerWidgets[j].getValue()) frac = ui->markerWidgets[j].getValue(); break; } } // Limit to successors value for (int j = i + 1; j < nrSteps - 1; ++j) { if (ui->markerWidgets[j].hasValue()) { if (frac > ui->markerWidgets[j].getValue()) frac = ui->markerWidgets[j].getValue(); break; } } ui->setMarker (i, frac); ui->setAutoMarkers(); ui->rearrange_controllers(); ui->redrawSContainer(); break; } } } void BSchafflGUI::listBoxChangedCallback (BEvents::Event* event) { if (!event) return; BEvents::ValueChangedEvent* vev = (BEvents::ValueChangedEvent*) event; BWidgets::ListBox* lb = (BWidgets::ListBox*) vev->getWidget(); if (!lb) return; Marker* m = (Marker*) lb->getParent(); if (!m) return; BSchafflGUI* ui = (BSchafflGUI*)m->getMainWindow(); if (!ui) return; int value = vev->getValue(); switch (value) { case 1: // Auto m->setHasValue (false); ui->enterFrame.hide(); lb->hide(); ui->setAutoMarkers(); ui->rearrange_controllers(); ui->redrawSContainer(); break; case 2: // Manual m->setHasValue (true); ui->enterFrame.hide(); lb->hide(); ui->setAutoMarkers(); ui->rearrange_controllers(); ui->redrawSContainer(); break; case 3: // Enter m->setHasValue (true); ui->recalculateEnterEdit(); if (ui->markerListBox.getAbsolutePosition().x / ui->sz > 600) ui->enterFrame.moveTo (-320 * ui->sz, ui->enterFrame.getPosition().y); else ui->enterFrame.moveTo (86 * ui->sz, ui->enterFrame.getPosition().y); ui->enterFrame.show(); break; default: return; } } void BSchafflGUI::enterListBoxChangedCallback (BEvents::Event* event) { if (!event) return; BEvents::ValueChangedEvent* vev = (BEvents::ValueChangedEvent*) event; BWidgets::ListBox* lb = (BWidgets::ListBox*) vev->getWidget(); if (!lb) return; Marker* m = (Marker*) lb->getParent(); if (!m) return; BSchafflGUI* ui = (BSchafflGUI*)m->getMainWindow(); if (!ui) return; ui->recalculateEnterEdit(); } void BSchafflGUI::enterOkClickedCallback (BEvents::Event* event) { if (!event) return; BEvents::PointerEvent* pev = (BEvents::PointerEvent*) event; if (pev->getButton() != BDevices::LEFT_BUTTON) return; BWidgets::TextButton* button = (BWidgets::TextButton*)event->getWidget(); if (!button) return; BSchafflGUI* ui = (BSchafflGUI*)button->getMainWindow(); if (!ui) return; Marker* marker = (Marker*)ui->markerListBox.getParent(); if (!marker) return; int nrSteps = ui->controllers[NR_OF_STEPS]->getValue(); for (int i = 0; i < nrSteps - 1; ++i) { if (marker == &ui->markerWidgets[i]) { double frac = marker->getValue(); double val = 0.0; try { val = BUtilities::stof (ui->enterEdit.getText()); if (ui->enterPositionPopup.getValue() == 1.0) { if (ui->enterSequencesPopup.getValue() == 1.0) frac = val; else frac = val / nrSteps; } else { const double prec = (i > 0 ? ui->markerWidgets[i - 1].getValue() : 0.0); if (i > 0) ui->markerWidgets[i - 1].setHasValue (true); if (ui->enterSequencesPopup.getValue() == 1.0) frac = val + prec; else frac = val / nrSteps + prec; } } catch (std::exception &exc) {std::cerr << "BSchaffl.lv2#GUI: " << exc.what() << "\n";} frac = LIMIT (frac, MINMARKERVALUE, 1.0); // Limit to antecessors value for (int j = i - 1; j >= 0; --j) { if (ui->markerWidgets[j].hasValue()) { if (frac < ui->markerWidgets[j].getValue()) frac = ui->markerWidgets[j].getValue(); break; } } // Limit to successors value for (int j = i + 1; j < nrSteps - 1; ++j) { if (ui->markerWidgets[j].hasValue()) { if (frac > ui->markerWidgets[j].getValue()) frac = ui->markerWidgets[j].getValue(); break; } } ui->enterFrame.hide(); ui->markerListBox.hide(); ui->setMarker (i, frac); ui->setAutoMarkers(); ui->rearrange_controllers(); ui->redrawSContainer(); break; } } } void BSchafflGUI::markersAutoClickedCallback (BEvents::Event* event) { if (!event) return; BEvents::ValueChangedEvent* vev = (BEvents::ValueChangedEvent*) event; if (vev->getValue() == 0.0) return; HaloButton* hb = (HaloButton*) vev->getWidget(); if (!hb) return; BSchafflGUI* ui = (BSchafflGUI*)hb->getMainWindow(); if (!ui) return; if (hb == &ui->markersAutoButton) { for (int i = 0; i < MAXSTEPS - 1; ++i) { const float v = 0; ui->markerWidgets[i].setHasValue (false); if (ui->sharedDataSelection.getValue()) ui->sendController (STEP_POS + i, v); else ui->write_function (ui->controller, CONTROLLERS + STEP_POS + i, sizeof (float), 0, &v); } } else if (hb == &ui->markersManualButton) { for (int i = 0; i < MAXSTEPS - 1; ++i) { const float v = ui->markerWidgets[i].getValue(); ui->markerWidgets[i].setHasValue (true); if (ui->sharedDataSelection.getValue()) ui->sendController (STEP_POS + i, v); else ui->write_function (ui->controller, CONTROLLERS + STEP_POS + i, sizeof (float), 0, &v); } } ui->setAutoMarkers(); ui->rearrange_controllers(); ui->redrawSContainer(); } void BSchafflGUI::shapeToolClickedCallback(BEvents::Event* event) { if (!event) return; HaloToggleButton* widget = (HaloToggleButton*) event->getWidget (); if (!widget) return; float value = widget->getValue(); BSchafflGUI* ui = (BSchafflGUI*) widget->getMainWindow(); if (!ui) return; // Identify tool int widgetNr = 0; if (value) { for (int i = 1; i < NR_TOOLS; ++i) { if (widget == &ui->shapeToolButtons[i - 1]) { widgetNr = i; break; } } } ui->shapeWidget.setTool (ToolType (widgetNr)); // Allow only one button pressed for (HaloToggleButton& s : ui->shapeToolButtons) { if (&s != widget) s.setValue (0.0); } } void BSchafflGUI::editToolClickedCallback(BEvents::Event* event) { if (!event) return; HaloButton* widget = (HaloButton*) event->getWidget (); if (!widget) return; float value = widget->getValue(); if (value != 1.0) return; BSchafflGUI* ui = (BSchafflGUI*) widget->getMainWindow(); if (!ui) return; // Identify editButtons int widgetNr = -1; for (size_t i = 0; i < ui->editToolButtons.size(); ++i) { if (widget == &ui->editToolButtons[i]) { widgetNr = i; break; } } // Action switch (widgetNr) { case 0: ui->clipboard = ui->shapeWidget.cutSelection(); break; case 1: ui->clipboard = ui->shapeWidget.copySelection(); break; case 2: ui->shapeWidget.pasteSelection (ui->clipboard); break; default: break; } } void BSchafflGUI::historyToolClickedCallback(BEvents::Event* event) { if (!event) return; HaloButton* widget = (HaloButton*) event->getWidget (); if (!widget) return; float value = widget->getValue(); if (value != 1.0) return; BSchafflGUI* ui = (BSchafflGUI*) widget->getMainWindow(); if (!ui) return; // Identify editButtons int widgetNr = -1; for (size_t i = 0; i < ui->historyToolButtons.size(); ++i) { if (widget == &ui->historyToolButtons[i]) { widgetNr = i; break; } } // Action if (ui->modeSwitch.getValue() == 0.0) { std::array<double, MAXSTEPS> values; switch (widgetNr) { case 0: values.fill (1.0); ui->sliderHistory.push (values); break; case 1: values = ui->sliderHistory.undo(); break; case 2: values = ui->sliderHistory.redo(); break; default: break; } for (int i = 0; i < MAXSTEPS; ++i) { float value = values[i]; ui->stepControl[i].setValueable (false); ui->stepControl[i].setValue (value); ui->stepControl[i].setValueable (true); ui->stepControlLabel[i].setText (BUtilities::to_string (value, "%1.2f")); if (ui->sharedDataSelection.getValue()) ui->sendController (STEP_LEV + i, value); else ui->write_function (ui->controller, CONTROLLERS + STEP_LEV + i, sizeof (float), 0, &value); } } else { switch (widgetNr) { case 0: ui->shapeWidget.reset(); break; case 1: ui->shapeWidget.undo(); break; case 2: ui->shapeWidget.redo(); break; default: break; } } } void BSchafflGUI::gridToolClickedCallback (BEvents::Event* event) { if (!event) return; HaloToggleButton* widget = (HaloToggleButton*) event->getWidget (); if (!widget) return; float value = widget->getValue(); BSchafflGUI* ui = (BSchafflGUI*) widget->getMainWindow(); if (!ui) return; if (widget == &ui->gridShowButton) { if (value) ui->shapeWidget.showGrid(); else ui->shapeWidget.hideGrid(); ui->shapeWidget.setSnap (false); ui->gridSnapButton.setValue (0.0); } else if (widget == &ui->gridSnapButton) { if (value) { ui->shapeWidget.showGrid(); ui->shapeWidget.setSnap (true); } else { ui->shapeWidget.hideGrid(); ui->shapeWidget.setSnap (false); } ui->gridShowButton.setValue (0.0); } } void BSchafflGUI::convertButtonClickedCallback (BEvents::Event* event) { if (!event) return; HaloButton* widget = (HaloButton*) event->getWidget (); if (!widget) return; BSchafflGUI* ui = (BSchafflGUI*) widget->getMainWindow(); if (!ui) return; if (widget == &ui->convertToShapeButton) { if (!ui->convertToShapeMessage.getParent()) { ui->add (ui->convertToShapeMessage); ui->convertToShapeToLinearButton.setValue (1.0); } } else if (widget == &ui->convertToStepsButton) { if (!ui->convertToStepsMessage.getParent()) ui->add (ui->convertToStepsMessage); } } void BSchafflGUI::lightButtonClickedCallback (BEvents::Event* event) { if (!event) return; LightButton* widget = (LightButton*) event->getWidget (); if (!widget) return; double value = widget->getValue(); if (!value) return; BWidgets::Widget* parent = widget->getParent(); if (!parent) return; std::vector<BWidgets::Widget*> children = parent->getChildren(); BSchafflGUI* ui = (BSchafflGUI*) widget->getMainWindow(); if (!ui) return; // Un-toggle all other LightButtons for (BWidgets::Widget* w : children) { LightButton* l = dynamic_cast<LightButton*> (w); if ((l) && (l != widget)) l->setValue (0.0); } } void BSchafflGUI::sharedDataClickedCallback (BEvents::Event* event) { if (!event) return; HaloToggleButton* widget = (HaloToggleButton*) event->getWidget (); if (!widget) return; double value = widget->getValue(); BSchafflGUI* ui = (BSchafflGUI*) widget->getMainWindow(); if (!ui) return; if (value) { for (int i = 0; i < 4; ++i) { if (widget == &ui->sharedDataButtons[i]) { ui->sharedDataSelection.setValue (i + 1); return; } } } ui->sharedDataSelection.setValue (0); } void BSchafflGUI::helpButtonClickedCallback (BEvents::Event* event) { char cmd[] = WWW_BROWSER_CMD; char param[] = HELP_URL; char* argv[] = {cmd, param, NULL}; std::cerr << "BSchaffl.lv2#GUI: Call " << HELP_URL << " for help.\n"; if (BUtilities::vsystem (argv) == -1) std::cerr << "BSchaffl.lv2#GUI: Couldn't fork.\n"; } void BSchafflGUI::ytButtonClickedCallback (BEvents::Event* event) { char cmd[] = WWW_BROWSER_CMD; char param[] = YT_URL; char* argv[] = {cmd, param, NULL}; std::cerr << "BSchaffl.lv2#GUI: Call " << YT_URL << " for tutorial video.\n"; if (BUtilities::vsystem (argv) == -1) std::cerr << "BSchaffl.lv2#GUI: Couldn't fork.\n"; } void BSchafflGUI::stepControlLabelMessageCallback (BEvents::Event* event) { if (event && event->getWidget()) { BWidgets::Label* l = (BWidgets::Label*)event->getWidget(); BSchafflGUI* ui = (BSchafflGUI*)l->getMainWindow(); if (ui) { for (int i = 0; i < MAXSTEPS; ++i) { if (l == &ui->stepControlLabel[i]) { double val = ui->stepControl[i].getValue(); try {val = BUtilities::stof (l->getText());} catch (std::invalid_argument &ia) { fprintf (stderr, "%s\n", ia.what()); l->setText (BUtilities::to_string (val, "%1.2f")); return; } ui->stepControl[i].setValue (val); l->setText (BUtilities::to_string (ui->stepControl[i].getValue(), "%1.2f")); break; } } } } } void BSchafflGUI::redrawSContainer () { double width = sContainer.getWidth (); double x0 = sContainer.getXOffset(); double y0 = sContainer.getYOffset(); double height = sContainer.getHeight (); cairo_surface_clear (sContainer.getDrawingSurface ()); cairo_t* cr = cairo_create (sContainer.getDrawingSurface ()); if (cairo_status (cr) != CAIRO_STATUS_SUCCESS) return; cairo_pattern_t* pat = cairo_pattern_create_linear (0, 0, 0, height); cairo_pattern_add_color_stop_rgba (pat, 0.0, CAIRO_RGBA (BColors::black)); cairo_pattern_add_color_stop_rgba (pat, 1.0, 0.0, 0.0, 0.0, 0.5); cairo_rectangle (cr, 0, 0, width, height); cairo_set_source (cr, pat); cairo_fill (cr); cairo_pattern_destroy (pat); int nrSteps = controllers[NR_OF_STEPS]->getValue(); // Step lines cairo_set_line_width (cr, 1.0); cairo_set_source_rgba (cr, CAIRO_RGBA (BColors::grey)); cairo_move_to (cr, 40 * sz - x0, -y0); cairo_rel_line_to (cr, 0, 240 * sz); for (int i = 0; i < nrSteps - 1; ++i) { cairo_move_to (cr, double (i + 1) / double (nrSteps) * (width - 40 * sz) + 40 * sz - x0, -y0); cairo_rel_line_to (cr, 0, 170 * sz); cairo_line_to (cr, markerWidgets[i].getValue() * (width - 40 * sz) + 40 * sz - x0, 180 * sz - y0); cairo_rel_line_to (cr, 0, 60 * sz); cairo_stroke (cr); } cairo_destroy (cr); sContainer.update(); } void BSchafflGUI::recalculateEnterEdit () { Marker* marker = (Marker*)markerListBox.getParent(); if (!marker) return; int nrSteps = controllers[NR_OF_STEPS]->getValue(); for (int i = 0; i < nrSteps - 1; ++i) { if (marker == &markerWidgets[i]) { const double rpos = marker->getValue(); double val = rpos; if (enterPositionPopup.getValue() == 1.0) { if (enterSequencesPopup.getValue() == 2.0) { val = rpos * nrSteps; // TODO rounding } } else { const double prpos = (i > 0 ? markerWidgets[i - 1].getValue() : 0.0); if (enterSequencesPopup.getValue() == 1.0) val = rpos - prpos; else { val = (rpos - prpos) * nrSteps; // TODO rounding } } enterEdit.setText (BUtilities::to_string (val, "%1.6f")); break; } } } static LV2UI_Handle instantiate (const LV2UI_Descriptor *descriptor, const char *plugin_uri, const char *bundle_path, LV2UI_Write_Function write_function, LV2UI_Controller controller, LV2UI_Widget *widget, const LV2_Feature *const *features) { PuglNativeView parentWindow = 0; LV2UI_Resize* resize = NULL; if (strcmp(plugin_uri, BSCHAFFL_URI) != 0) { std::cerr << "BSchaffl.lv2#GUI: GUI does not support plugin with URI " << plugin_uri << std::endl; return NULL; } for (int i = 0; features[i]; ++i) { if (!strcmp(features[i]->URI, LV2_UI__parent)) parentWindow = (PuglNativeView) features[i]->data; else if (!strcmp(features[i]->URI, LV2_UI__resize)) resize = (LV2UI_Resize*)features[i]->data; } if (parentWindow == 0) std::cerr << "BSchaffl.lv2#GUI: No parent window.\n"; // New instance BSchafflGUI* ui; try {ui = new BSchafflGUI (bundle_path, features, parentWindow);} catch (std::exception& exc) { std::cerr << "BSchaffl.lv2#GUI: Instantiation failed. " << exc.what () << std::endl; return NULL; } ui->controller = controller; ui->write_function = write_function; // Reduce min GUI size for small displays double sz = 1.0; int screenWidth = getScreenWidth (); int screenHeight = getScreenHeight (); if ((screenWidth < 1060) || (screenHeight < 520)) sz = 0.66; if (resize) resize->ui_resize(resize->handle, 1020 * sz, 480 * sz); *widget = (LV2UI_Widget) puglGetNativeWindow (ui->getPuglView ()); ui->sendUiStatus (true); return (LV2UI_Handle) ui; } static void cleanup(LV2UI_Handle ui) { BSchafflGUI* pluginGui = (BSchafflGUI*) ui; if (pluginGui) delete pluginGui; } static void portEvent(LV2UI_Handle ui, uint32_t port_index, uint32_t buffer_size, uint32_t format, const void* buffer) { BSchafflGUI* pluginGui = (BSchafflGUI*) ui; if (pluginGui) pluginGui->portEvent(port_index, buffer_size, format, buffer); } static int callIdle (LV2UI_Handle ui) { BSchafflGUI* pluginGui = (BSchafflGUI*) ui; if (pluginGui) pluginGui->handleEvents (); return 0; } static int callResize (LV2UI_Handle ui, int width, int height) { BSchafflGUI* self = (BSchafflGUI*) ui; if (!self) return 0; BEvents::ExposeEvent* ev = new BEvents::ExposeEvent (self, self, BEvents::CONFIGURE_REQUEST_EVENT, self->getPosition().x, self->getPosition().y, width, height); self->addEventToQueue (ev); return 0; } static const LV2UI_Idle_Interface idle = {callIdle}; static const LV2UI_Resize resize = {nullptr, callResize}; static const void* extensionData(const char* uri) { if (!strcmp(uri, LV2_UI__idleInterface)) return &idle; else if(!strcmp(uri, LV2_UI__resize)) return &resize; else return NULL; } static const LV2UI_Descriptor guiDescriptor = { BSCHAFFLGUI_URI, instantiate, cleanup, portEvent, extensionData }; // LV2 Symbol Export LV2_SYMBOL_EXPORT const LV2UI_Descriptor *lv2ui_descriptor(uint32_t index) { switch (index) { case 0: return &guiDescriptor; default:return NULL; } }
80,674
C++
.cpp
2,124
34.399718
161
0.690696
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,485
Label.cpp
sjaehn_BSchaffl/src/BWidgets/Label.cpp
/* Label.cpp * Copyright (C) 2018, 2019 Sven Jähnichen * * 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 <https://www.gnu.org/licenses/>. */ #include "Label.hpp" #include "Window.hpp" #include "pugl/pugl/pugl.h" #include <locale> #include <codecvt> namespace BWidgets { Label::Label () : Label (0.0, 0.0, 0.0, 0.0, "label", "") {} Label::Label (const double x, const double y, const double width, const double height, const std::string& text) : Label (x, y, width, height, text, text) {} Label::Label (const double x, const double y, const double width, const double height, const std::string& name, const std::string& text) : Widget (x, y, width, height, name), labelColors (BWIDGETS_DEFAULT_TEXT_COLORS), labelFont (BWIDGETS_DEFAULT_FONT), labelText (text), oldText (text), u32labelText (), editable (false), editMode (false), cursorFrom (0), cursorTo () { cbfunction_[BEvents::EventType::POINTER_DRAG_EVENT] = Widget::defaultCallback; setDraggable (true); labelFont.setTextAlign (BWIDGETS_DEFAULT_LABEL_ALIGN); labelFont.setTextVAlign (BWIDGETS_DEFAULT_LABEL_VALIGN); std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert; u32labelText = convert.from_bytes (labelText); } Label& Label::operator= (const Label& that) { labelColors = that.labelColors; labelFont = that.labelFont; labelText = that.labelText; u32labelText = that.u32labelText; editable = that.editable; editMode = that.editMode; cursorFrom = that.cursorFrom; cursorTo = that.cursorTo; Widget::operator= (that); oldText = labelText; return *this; } Widget* Label::clone () const {return new Label (*this);} void Label::setText (const std::string& text) { if (text != labelText) { setEditMode (false); labelText = text; std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert; u32labelText = convert.from_bytes (labelText); size_t sz = u32labelText.length (); if (cursorFrom < sz) cursorFrom = sz; if (cursorTo < sz) cursorTo = sz; update (); oldText = labelText; } } std::string Label::getText () const {return labelText;} void Label::setTextColors (const BColors::ColorSet& colorset) { if (labelColors != colorset) { labelColors = colorset; update (); } } BColors::ColorSet* Label::getTextColors () {return &labelColors;} void Label::setFont (const BStyles::Font& font) { labelFont = font; update (); } BStyles::Font* Label::getFont () {return &labelFont;} double Label::getTextWidth (std::string& text) { double textwidth = 0.0; cairo_t* cr = cairo_create (widgetSurface_); cairo_text_extents_t ext = labelFont.getTextExtents(cr, text.c_str ()); textwidth = ext.width; cairo_destroy (cr); return textwidth; } void Label::resize () { // Get label text size cairo_t* cr = cairo_create (widgetSurface_); cairo_text_extents_t ext = labelFont.getTextExtents(cr, labelText.c_str ()); double w = ext.width; double h = (ext.height > labelFont.getFontSize() ? ext.height : labelFont.getFontSize()); BUtilities::Point contExt = BUtilities::Point (w + 2 * getXOffset () + 2, h + 2 * getYOffset () + 2); cairo_destroy (cr); // Or use embedded widgets size, if bigger for (Widget* w : children_) { if (w->getPosition ().x + w->getWidth () > contExt.x) contExt.x = w->getPosition ().x + w->getWidth(); if (w->getPosition ().y + w->getHeight () > contExt.y) contExt.y = w->getPosition ().y + w->getHeight(); } Label::resize (contExt); } void Label::resize (const double width, const double height) {Label::resize (BUtilities::Point (width, height));} void Label::resize (const BUtilities::Point extends) {Widget::resize (extends);} void Label::applyTheme (BStyles::Theme& theme) {applyTheme (theme, name_);} void Label::applyTheme (BStyles::Theme& theme, const std::string& name) { Widget::applyTheme (theme, name); // Color void* colorsPtr = theme.getStyle(name, BWIDGETS_KEYWORD_TEXTCOLORS); if (colorsPtr) labelColors = *((BColors::ColorSet*) colorsPtr); // Font void* fontPtr = theme.getStyle(name, BWIDGETS_KEYWORD_FONT); if (fontPtr) labelFont = *((BStyles::Font*) fontPtr); if (colorsPtr || fontPtr) update (); } void Label::setEditable (const bool status) { editable = status; if (editMode) update (); } bool Label::isEditable () const {return editable;} void Label::setEditMode (const bool mode) { if (mode != editMode) { editMode = mode; update (); } } bool Label::getEditMode () const {return editMode;} void Label::setCursor (const size_t pos) {setCursor (pos, pos);} void Label::setCursor (const size_t from, const size_t to) { size_t cf = from; size_t ct = to; // Check limits size_t s32 = u32labelText.length (); if (cf > s32) cf = s32; if (ct > s32) ct = s32; // Apply changes if ((cf != cursorFrom) || (ct != cursorTo)) { cursorFrom = cf; cursorTo = ct; update (); } } void Label::applyEdit () { if (main_) main_->getKeyGrabStack()->remove (this); setEditMode (false); if (labelText != oldText) { postMessage (BWIDGETS_LABEL_TEXT_CHANGED_MESSAGE, BUtilities::makeAny<std::string> (labelText)); oldText = labelText; } } void Label::discardEdit () { if (main_) main_->getKeyGrabStack()->remove (this); setEditMode (false); if (labelText != oldText) setText (oldText); } void Label::onKeyPressed (BEvents::KeyEvent* event) { if ( editable && event && (event->getWidget () == this) && main_ && (main_->getKeyGrabStack()->getGrab(0)->getWidget() == this) ) { uint32_t key = event->getKey (); switch (key) { case 8: // Backspace { size_t cf = cursorFrom; size_t ct = cursorTo; if (ct < cf) { cf = cursorTo; ct = cursorFrom; } if (cf != ct) u32labelText.erase (cf, ct - cf); else if (cf > 0) { u32labelText.erase (cf - 1, 1); --cf; } std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert; labelText = convert.to_bytes (u32labelText); setCursor (cf); } break; case 13: // Enter applyEdit (); break; case 27: // Escape discardEdit (); break; case 127: // Delete { size_t cf = cursorFrom; size_t ct = cursorTo; if (ct < cf) { cf = cursorTo; ct = cursorFrom; } if (cf != ct) u32labelText.erase (cf, ct - cf); else if (cf < u32labelText.size ()) u32labelText.erase (cf, 1); std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert; labelText = convert.to_bytes (u32labelText); setCursor (cf); update (); } break; case PUGL_KEY_LEFT : if (cursorFrom > 0) setCursor (cursorFrom - 1); break; case PUGL_KEY_RIGHT : setCursor (cursorFrom + 1); break; case PUGL_KEY_HOME : setCursor (0); break; case PUGL_KEY_END: setCursor (u32labelText.length ()); break; default: { if ((key >= 0x20) && (key < 0x7F)) { size_t cf = cursorFrom; size_t ct = cursorTo; if (ct < cf) { cf = cursorTo; ct = cursorFrom; } if (cf != ct) u32labelText.erase (cf, ct - cf); u32labelText.insert (u32labelText.begin () + cf, key); std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert; labelText = convert.to_bytes (u32labelText); setCursor (cf + 1); } } break; } } cbfunction_[BEvents::EventType::KEY_PRESS_EVENT] (event); } void Label::onKeyReleased (BEvents::KeyEvent* event) {cbfunction_[BEvents::EventType::KEY_RELEASE_EVENT] (event);} void Label::onButtonClicked (BEvents::PointerEvent* event) { if (editable && (event) && (event->getWidget () == this) && (main_)) { main_->getKeyGrabStack()->add (this); setEditMode (true); size_t cursor = getCursorFromCoords (event->getPosition ()); setCursor (cursor, cursor); } cbfunction_[BEvents::EventType::BUTTON_PRESS_EVENT] (event); } void Label::onPointerDragged (BEvents::PointerEvent* event) { if ( editable && editMode && (event) && (event->getWidget () == this) && (main_) && (main_->getKeyGrabStack()->getGrab(0)->getWidget() == this) ) { size_t cursor = getCursorFromCoords (event->getPosition ()); setCursor (cursorFrom, cursor); } cbfunction_[BEvents::EventType::POINTER_DRAG_EVENT] (event); } size_t Label::getCursorFromCoords (const BUtilities::Point& position) { size_t cursor = u32labelText.length (); if ((!widgetSurface_) || (cairo_surface_status (widgetSurface_) != CAIRO_STATUS_SUCCESS)) return 0; cairo_t* cr = cairo_create (widgetSurface_); if (cairo_status (cr) == CAIRO_STATUS_SUCCESS) { std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert; double xoff = getXOffset (); //double yoff = getYOffset (); double w = getEffectiveWidth (); //double h = getEffectiveHeight (); cairo_text_extents_t ext = labelFont.getTextExtents (cr, "|" + labelText + "|"); cairo_text_extents_t ext0 = labelFont.getTextExtents(cr, "|"); double x0; switch (labelFont.getTextAlign ()) { case BStyles::TEXT_ALIGN_LEFT: x0 = - ext.x_bearing; break; case BStyles::TEXT_ALIGN_CENTER: x0 = w / 2 - (ext.width - 2 * ext0.width - 2 * ext0.x_bearing) / 2; break; case BStyles::TEXT_ALIGN_RIGHT: x0 = w - (ext.width - 2 * ext0.width - 2 * ext0.x_bearing); break; default: x0 = 0; } std::u32string u32fragment = U""; for (size_t i = 0; i < u32labelText.length (); ++i) { u32fragment += u32labelText[i]; std::string fragment = convert.to_bytes (u32fragment); cairo_text_extents_t ext1 = labelFont.getTextExtents(cr, "|" + fragment + "|"); if (position.x < xoff + x0 + ext1.width - 2 * ext0.width - 2 * ext0.x_bearing) { cursor = i; break; } } cairo_destroy (cr); } return cursor; } void Label::draw (const BUtilities::RectArea& area) { if ((!widgetSurface_) || (cairo_surface_status (widgetSurface_) != CAIRO_STATUS_SUCCESS)) return; // Draw super class widget elements first Widget::draw (area); cairo_t* cr = cairo_create (widgetSurface_); if (cairo_status (cr) == CAIRO_STATUS_SUCCESS) { // Limit cairo-drawing area cairo_rectangle (cr, area.getX (), area.getY (), area.getWidth (), area.getHeight ()); cairo_clip (cr); double xoff = getXOffset (); double yoff = getYOffset (); double w = getEffectiveWidth (); double h = getEffectiveHeight (); cairo_text_extents_t ext = labelFont.getTextExtents(cr, "|" + labelText + "|"); cairo_text_extents_t ext0 = labelFont.getTextExtents(cr, "|"); cairo_select_font_face (cr, labelFont.getFontFamily ().c_str (), labelFont.getFontSlant (), labelFont.getFontWeight ()); cairo_set_font_size (cr, labelFont.getFontSize ()); double x0, y0; switch (labelFont.getTextAlign ()) { case BStyles::TEXT_ALIGN_LEFT: x0 = 0; break; case BStyles::TEXT_ALIGN_CENTER: x0 = w / 2 - (ext.width - 2 * ext0.width - 2 * ext0.x_bearing) / 2; break; case BStyles::TEXT_ALIGN_RIGHT: x0 = w - (ext.width - 2 * ext0.width - 2 * ext0.x_bearing); break; default: x0 = 0; } switch (labelFont.getTextVAlign ()) { case BStyles::TEXT_VALIGN_TOP: y0 = - ext.y_bearing; break; case BStyles::TEXT_VALIGN_MIDDLE: y0 = h / 2 - ext.height / 2 - ext.y_bearing; break; case BStyles::TEXT_VALIGN_BOTTOM: y0 = h - ext.height - ext.y_bearing; break; default: y0 = 0; } if (editable && editMode) { std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert; size_t cf = cursorFrom; size_t ct = cursorTo; if (ct < cf) { cf = cursorTo; ct = cursorFrom; } std::string s1 = convert.to_bytes (u32labelText.substr (0, cf)); std::string s2 = convert.to_bytes (u32labelText.substr (cf, ct - cf)); std::string s3 = convert.to_bytes (u32labelText.substr (ct, std::u32string::npos)); cairo_text_extents_t ext1 = labelFont.getTextExtents(cr, "|" + s1 + "|"); cairo_text_extents_t ext2 = labelFont.getTextExtents(cr, "|" + s2 + "|"); double w1 = ext1.width - 2 * ext0.width - 2 * ext0.x_bearing; double w2 = ext2.width - 2 * ext0.width - 2 * ext0.x_bearing; BColors::Color lc = *labelColors.getColor (BColors::ACTIVE); cairo_set_source_rgba (cr, lc.getRed (), lc.getGreen (), lc.getBlue (), lc.getAlpha ()); cairo_set_line_width (cr, 1.0); cairo_rectangle (cr, xoff + x0 + w1, yoff + y0, w2, -ext0.height); cairo_stroke_preserve (cr); cairo_fill (cr); cairo_set_source_rgba (cr, lc.getRed (), lc.getGreen (), lc.getBlue (), lc.getAlpha ()); cairo_move_to (cr, xoff + x0, yoff + y0); cairo_show_text (cr, s1.c_str ()); cairo_set_source_rgba (cr, 1 - lc.getRed (), 1 - lc.getGreen (), 1 - lc.getBlue (), lc.getAlpha ()); cairo_move_to (cr, xoff + x0 + w1, yoff + y0); cairo_show_text (cr, s2.c_str ()); cairo_set_source_rgba (cr, lc.getRed (), lc.getGreen (), lc.getBlue (), lc.getAlpha ()); cairo_move_to (cr, xoff + x0 + w1 + w2, yoff + y0); cairo_show_text (cr, s3.c_str ()); } else { BColors::Color lc = *labelColors.getColor (getState ()); cairo_set_source_rgba (cr, lc.getRed (), lc.getGreen (), lc.getBlue (), lc.getAlpha ()); cairo_move_to (cr, xoff + x0, yoff + y0); cairo_show_text (cr, labelText.c_str ()); } } cairo_destroy (cr); } }
13,672
C++
.cpp
409
30.415648
138
0.673472
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,486
Snapshots.hpp
sjaehn_BSchaffl/src/Snapshots.hpp
/* B.Shapr * Beat / envelope shaper LV2 plugin * * Copyright (C) 2019 by Sven Jähnichen * * 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, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef SNAPSHOTS_HPP_ #define SNAPSHOTS_HPP_ #include <cstddef> #include <array> #include <iostream> template <class T, size_t sz> class Snapshots { protected: std::array<T, sz> store_; size_t pos_ = 0; size_t horizon_ = 0; size_t size_ = 0; T default_ = T (); public: void clear () { store_.fill (default_); pos_ = 0; horizon_ = 0; size_ = 0; } void setDefault (const T& value) { default_ = value; } void push (const T& value) { horizon_ = ((pos_ + 1) % sz); store_[horizon_] = value; pos_ = horizon_; size_ = (size_ < sz ? size_ + 1 : sz); } T undo () { pos_ = (size_ == 0 ? 0 : (((size_ < sz) && (pos_ == 0)) ? 0 : ((horizon_ == ((pos_ + sz - 1) % sz)) ? pos_ : ((pos_ + sz - 1) % sz)))); return store_[pos_]; } T redo () { pos_ = (size_ == 0 ? 0 : ((horizon_ == pos_) ? pos_ : ((pos_ + 1) % sz))); return store_[pos_]; } }; #endif /* SNAPSHOTS_HPP_ */
2,033
C++
.h
64
24.578125
151
0.539051
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,487
Urids.hpp
sjaehn_BSchaffl/src/Urids.hpp
/* B.Schaffl * MIDI Pattern Delay Plugin * * Copyright (C) 2018 - 2020 by Sven Jähnichen * * 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, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef URIDS_HPP_ #define URIDS_HPP_ #include <lv2/lv2plug.in/ns/lv2core/lv2.h> #include <lv2/lv2plug.in/ns/ext/atom/util.h> #include <lv2/lv2plug.in/ns/ext/urid/urid.h> #include <lv2/lv2plug.in/ns/ext/time/time.h> #include <lv2/lv2plug.in/ns/ext/midi/midi.h> #include "definitions.hpp" struct BSchafflURIs { LV2_URID atom_Float; LV2_URID atom_Double; LV2_URID atom_Int; LV2_URID atom_Long; LV2_URID atom_String; LV2_URID atom_Object; LV2_URID atom_Blank; LV2_URID atom_eventTransfer; LV2_URID atom_Vector; LV2_URID time_Position; LV2_URID time_bar; LV2_URID time_barBeat; LV2_URID time_beatsPerMinute; LV2_URID time_beatsPerBar; LV2_URID time_beatUnit; LV2_URID time_speed; LV2_URID midi_Event; LV2_URID bschaffl_uiOn; LV2_URID bschaffl_uiOff; LV2_URID bschaffl_statusEvent; LV2_URID bschaffl_step; LV2_URID bschaffl_latency; LV2_URID bschaffl_rate; LV2_URID bschaffl_shapeEvent; LV2_URID bschaffl_shapeData; LV2_URID notify_event; LV2_URID notify_key; LV2_URID notify_messageEvent; LV2_URID notify_message; LV2_URID bschaffl_controllerEvent; LV2_URID bschaffl_controllerNr; LV2_URID bschaffl_controllerValue; LV2_URID bschaffl_controllers; LV2_URID bschaffl_sharedDataLinkEvent; LV2_URID bschaffl_sharedDataNr; }; void getURIs (LV2_URID_Map* m, BSchafflURIs* uris) { uris->atom_Float = m->map(m->handle, LV2_ATOM__Float); uris->atom_Double = m->map(m->handle, LV2_ATOM__Double); uris->atom_Int = m->map(m->handle, LV2_ATOM__Int); uris->atom_Long = m->map(m->handle, LV2_ATOM__Long); uris->atom_String = m->map(m->handle, LV2_ATOM__String); uris->atom_Object = m->map(m->handle, LV2_ATOM__Object); uris->atom_Blank = m->map(m->handle, LV2_ATOM__Blank); uris->atom_eventTransfer = m->map(m->handle, LV2_ATOM__eventTransfer); uris->atom_Vector = m->map(m->handle, LV2_ATOM__Vector); uris->time_Position = m->map(m->handle, LV2_TIME__Position); uris->time_bar = m->map(m->handle, LV2_TIME__bar); uris->time_barBeat = m->map(m->handle, LV2_TIME__barBeat); uris->time_beatsPerMinute = m->map(m->handle, LV2_TIME__beatsPerMinute); uris->time_beatUnit = m->map(m->handle, LV2_TIME__beatUnit); uris->time_beatsPerBar = m->map(m->handle, LV2_TIME__beatsPerBar); uris->time_speed = m->map(m->handle, LV2_TIME__speed); uris->midi_Event = m->map(m->handle, LV2_MIDI__MidiEvent); uris->bschaffl_uiOn = m->map(m->handle, BSCHAFFL_URI "#BSchafflUiOn"); uris->bschaffl_uiOff = m->map(m->handle, BSCHAFFL_URI "#BSchafflUiOff"); uris->bschaffl_statusEvent = m->map(m->handle, BSCHAFFL_URI "#BSchafflStatusEvent"); uris->bschaffl_step = m->map(m->handle, BSCHAFFL_URI "#BSchafflStep"); uris->bschaffl_latency = m->map(m->handle, BSCHAFFL_URI "#BSchafflLatency"); uris->bschaffl_rate = m->map(m->handle, BSCHAFFL_URI "#BSchafflRate"); uris->bschaffl_shapeEvent = m->map(m->handle, BSCHAFFL_URI "#bschafflShapeEvent"); uris->bschaffl_shapeData = m->map(m->handle, BSCHAFFL_URI "#bschafflShapeData"); uris->notify_event = m->map(m->handle, BSCHAFFL_URI "#NOTIFYev"); uris->notify_key = m->map(m->handle, BSCHAFFL_URI "#NOTIFYkey"); uris->notify_messageEvent = m->map(m->handle, BSCHAFFL_URI "#NOTIFYmessageEvent"); uris->notify_message = m->map(m->handle, BSCHAFFL_URI "#NOTIFYmessage"); uris->bschaffl_controllerEvent = m->map(m->handle, BSCHAFFL_URI "#BSchafflControllerEvent"); uris->bschaffl_controllerNr = m->map(m->handle, BSCHAFFL_URI "#BSchafflControllerNr"); uris->bschaffl_controllerValue = m->map(m->handle, BSCHAFFL_URI "#BSchafflControllerValue"); uris->bschaffl_controllers = m->map(m->handle, BSCHAFFL_URI "#BSchafflControllers"); uris->bschaffl_sharedDataLinkEvent = m->map(m->handle, BSCHAFFL_URI "#BSchafflSharedDataLinkEvent"); uris->bschaffl_sharedDataNr = m->map(m->handle, BSCHAFFL_URI "#BSchafflSharedDataNr"); } #endif /* URIDS_HPP_ */
4,614
C++
.h
104
42.471154
101
0.742064
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,488
definitions.hpp
sjaehn_BSchaffl/src/definitions.hpp
/* B.Schaffl * MIDI Pattern Delay Plugin * * Copyright (C) 2018 - 2020 by Sven Jähnichen * * 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, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef DEFINITIONS_HPP_ #define DEFINITIONS_HPP_ #define NOTIFYBUFFERSIZE 64 #define MONITORBUFFERSIZE 64 #define MIDIBUFFERSIZE 256 #define NR_MIDI_MSG_FILTERS 7 #define NR_MIDI_CHS 16 #define MAXINSTANCES 256 #define MAXSTEPS 16 #define MAXNODES 64 #define MAXUNDO 20 #define GRIDSIZE 2.0 #define MINMARKERVALUE 0.000001 #define BSCHAFFL_URI "https://www.jahnichen.de/plugins/lv2/BSchaffl" #define BSCHAFFLGUI_URI "https://www.jahnichen.de/plugins/lv2/BSchaffl#gui" #endif /* DEFINITIONS_HPP_ */
1,301
C++
.h
35
35.571429
75
0.779889
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,489
Locale_EN.hpp
sjaehn_BSchaffl/src/Locale_EN.hpp
#ifndef BSCHAFFL_LOCALE #define BSCHAFFL_LOCALE #define BSCHAFFL_LABEL_HELP "Help" #define BSCHAFFL_LABEL_TUTORIAL "Tutorial" #define BSCHAFFL_LABEL_ALL_MARKERS_AUTO "All markers: Auto" #define BSCHAFFL_LABEL_ALL_MARKERS_MANUAL "All markers: Manual" #define BSCHAFFL_LABEL_SELECT "Select" #define BSCHAFFL_LABEL_POINT_NODE "Point node" #define BSCHAFFL_LABEL_AUTO_NODE "Auto Bezier node" #define BSCHAFFL_LABEL_SYMMETRIC_NODE "Symmetric Bezier node" #define BSCHAFFL_LABEL_ASYMMETRIC_NODE "Asymmetric Bezier node" #define BSCHAFFL_LABEL_CUT "Cut" #define BSCHAFFL_LABEL_COPY "Copy" #define BSCHAFFL_LABEL_PASTE "Paste" #define BSCHAFFL_LABEL_RESET "Reset" #define BSCHAFFL_LABEL_UNDO "Undo" #define BSCHAFFL_LABEL_REDO "Redo" #define BSCHAFFL_LABEL_SHOW_GRID "Show grid" #define BSCHAFFL_LABEL_SNAP_GRID "Snap to grid" #define BSCHAFFL_LABEL_CONVERT_TO_SHAPE "Convert step sliders to shape" #define BSCHAFFL_LABEL_CONVERT_TO_SHAPE_TITLE "Shape-controlled amp mode" #define BSCHAFFL_LABEL_CONVERT_TO_SHAPE_TEXT "Do you want to convert the amp data from the sliders-controlled mode to this shape ?" #define BSCHAFFL_LABEL_CONVERT_TO_SHAPE_LINEAR_TEXT "Convert sliders to linear fading" #define BSCHAFFL_LABEL_CONVERT_TO_SHAPE_CONST_TEXT "Convert sliders to steps" #define BSCHAFFL_LABEL_OK "OK" #define BSCHAFFL_LABEL_APPLY "Apply" #define BSCHAFFL_LABEL_CANCEL "Cancel" #define BSCHAFFL_LABEL_CONVERT_TO_STEPS "Convert shape to step sliders" #define BSCHAFFL_LABEL_CONVERT_TO_STEPS_TITLE "Sliders-controlled amp mode" #define BSCHAFFL_LABEL_CONVERT_TO_STEPS_TEXT "Do you want to convert the amp data from the shape-controlled mode to sliders ?" #define BSCHAFFL_LABEL_MIDI_CH "MIDI channels to be processed by the plugin:" #define BSCHAFFL_LABEL_ALL "All" #define BSCHAFFL_LABEL_MIDI_MSG "MIDI messages to be processed by the plugin:" #define BSCHAFFL_LABEL_NOTE_TEXT "Note position and duration can be excluded from processing (stretch). Take care, this may result in overlaps!" #define BSCHAFFL_LABEL_NOTE_KEEP_POSITION "Keep note position" #define BSCHAFFL_LABEL_NOTE_KEEP_DURATION "Keep note duration" #define BSCHAFFL_LABEL_DO_NOTHING "Do nothing" #define BSCHAFFL_LABEL_SPLIT "Split" #define BSCHAFFL_LABEL_MERGE "Merge" #define BSCHAFFL_LABEL_IF_NOTES_OVERLAP_TITLE "If notes overlap:" #define BSCHAFFL_LABEL_IF_NOTES_OVERLAP_TEXT "MIDI note off velocity can be amplified with data either from the start or the end of the note." #define BSCHAFFL_LABEL_NOTE_OFF_AMP "NOTE_OFF amp:" #define BSCHAFFL_LABEL_USE_NOTE_ON_AMP "Use NOTE_ON amp" #define BSCHAFFL_LABEL_CALCULATE_FROM_END "Calculate from end step/position" #define BSCHAFFL_LABEL_SMART_QUANTIZATION_TEXT_1 "Synchronizes not exactly fitting MIDI signals (e.g., notes) with the step pattern if the signal is within a range from the step start or end of the respective step." #define BSCHAFFL_LABEL_SMART_QUANTIZATION_TEXT_2 "MIDI signals can be synchronized just by assignment to a step or by fitting into a step or both." #define BSCHAFFL_LABEL_RANGE_STEPS "Range (steps)" #define BSCHAFFL_LABEL_ASSIGN_TO_STEP "Assign to a step" #define BSCHAFFL_LABEL_FIT_TO_STEP "Fit into a step" #define BSCHAFFL_LABEL_LATENCY_COMPENSATION_TEXT "Some hosts already compensate time/position by the plugin's latency. Otherwise the plugin can do it." #define BSCHAFFL_LABEL_LATENCY_COMPENSATION_TITLE "Latency-compensate time/position" #define BSCHAFFL_LABEL_LATENCY_USER_TEXT "The plugin itself calculates the latency by default. Alternatively, you may define a fixed latency." #define BSCHAFFL_LABEL_LATENCY_USER_TITLE "User-defined latency" #define BSCHAFFL_LABEL_FRAMES "Frames" #define BSCHAFFL_LABEL_MS "ms" #define BSCHAFFL_LABEL_SECONDS "Second(s)" #define BSCHAFFL_LABEL_BEATS "Beat(s)" #define BSCHAFFL_LABEL_BARS "Bar(s)" #define BSCHAFFL_LABEL_AUTO "Auto" #define BSCHAFFL_LABEL_MANUAL "Manual" #define BSCHAFFL_LABEL_ENTER "Enter" #define BSCHAFFL_LABEL_NEW_POSITION "New position:" #define BSCHAFFL_LABEL_NEW_LENGTH "New length:" #define BSCHAFFL_LABEL_SEQUENCES "sequence(s)" #define BSCHAFFL_LABEL_STEPS "step(s)" #define BSCHAFFL_LABEL_SHARED_DATA "Shared data" #define BSCHAFFL_LABEL_JACK_OFF "Jack transport off or halted." #define BSCHAFFL_LABEL_LATENCY_EXCEEDS "Latency exceeds maximum of 192000 frames." #define BSCHAFFL_LABEL_MIDI_NO "Note" #define BSCHAFFL_LABEL_MIDI_KP "Key pressure" #define BSCHAFFL_LABEL_MIDI_CC "Control change" #define BSCHAFFL_LABEL_MIDI_PC "Program change" #define BSCHAFFL_LABEL_MIDI_CP "Channel pressure" #define BSCHAFFL_LABEL_MIDI_PB "Pitch bend" #define BSCHAFFL_LABEL_MIDI_SE "System exclusive" #define BSCHAFFL_LABEL_LATENCY "Latency" #define BSCHAFFL_FILENAME_IN "inc/in.png" #define BSCHAFFL_FILENAME_OUT "inc/out.png" #define BSCHAFFL_FILENAME_AMP "inc/amp.png" #define BSCHAFFL_FILENAME_STR "inc/del.png" #define BSCHAFFL_FILENAME_SEQUENCE_SIZE "inc/sequence_size.png" #define BSCHAFFL_FILENAME_AMP_SWING "inc/amp_swing.png" #define BSCHAFFL_FILENAME_AMP_RANDOM "inc/amp_random.png" #define BSCHAFFL_FILENAME_AMP_PROCESS "inc/amp_process.png" #define BSCHAFFL_FILENAME_NR_OF_STEPS "inc/number_of_steps.png" #define BSCHAFFL_FILENAME_STEPS_SWING "inc/steps_swing.png" #define BSCHAFFL_FILENAME_STEPS_RANDOM "inc/steps_random.png" #define BSCHAFFL_FILENAME_STEPS_PROCESS "inc/steps_process.png" #define BSCHAFFL_FILENAME_MIDI_CH_FILTER "inc/midi_ch_filter.png" #define BSCHAFFL_FILENAME_MIDI_MSG_FILTER "inc/midi_msg_filter.png" #define BSCHAFFL_FILENAME_MIDI_NOTE_OPTIONS "inc/midi_note_options.png" #define BSCHAFFL_FILENAME_SMART_QUANTIZATION "inc/smart_quantization.png" #define BSCHAFFL_FILENAME_LATENCY "inc/latency.png" #endif
5,643
C++
.h
94
58.989362
215
0.806312
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,490
BSchaffl.hpp
sjaehn_BSchaffl/src/BSchaffl.hpp
/* B.Schaffl * MIDI Pattern Delay Plugin * * Copyright (C) 2018 - 2020 by Sven Jähnichen * * 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, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef BSCHAFFL_H_ #define BSCHAFFL_H_ #define MODFL(x) (x - floorf (x)) #include <cmath> #include <array> #include <random> #include <lv2/lv2plug.in/ns/ext/atom/atom.h> #include <lv2/lv2plug.in/ns/ext/atom/forge.h> #include <lv2/lv2plug.in/ns/ext/state/state.h> #include "definitions.hpp" #include "Urids.hpp" #include "Ports.hpp" #include "Message.hpp" #include "Limit.hpp" #include "StaticArrayList.hpp" #include "Shape.hpp" struct MidiData { uint8_t msg[3]; size_t size; double positionSeq; double shiftSeq; double amp; bool inactive; }; struct Atom_Ptr { LV2_Atom atom; int nr; void* ptr; }; const Limit controllerLimits [NR_CONTROLLERS] = { {0.125, 16.0, 0}, // SEQ_LEN_VALUE {0, 2, 1}, // SEQ_LEN_BASE {0.0078125, 128.0, 0.0},// AMP_SWING {0.0, 1.0, 0.0}, // AMP_RANDOM {-1.0, 2.0, 0.0}, // AMP_PROCESS {0.333333, 3.0, 0.0}, // SWING {0.0, 1.0, 0.0}, // SWING_RANDOM {0.0, 1.0, 0.0}, // SWING_PROCESS {1, 16, 1}, // NR_OF_STEPS {0, 1, 1}, // AMP_MODE {0, 1, 1}, // MIDI_CH_FILTER {0, 1, 1}, {0, 1, 1}, {0, 1, 1}, {0, 1, 1}, {0, 1, 1}, {0, 1, 1}, {0, 1, 1}, {0, 1, 1}, {0, 1, 1}, {0, 1, 1}, {0, 1, 1}, {0, 1, 1}, {0, 1, 1}, {0, 1, 1}, {0, 1, 1}, {0, 1, 1}, // MSG_FILTER_NOTE {0, 1, 1}, // MSG_FILTER_KEYPR {0, 1, 1}, // MSG_FILTER_CC {0, 1, 1}, // MSG_FILTER_PROG {0, 1, 1}, // MSG_FILTER_CHPR {0, 1, 1}, // MSG_FILTER_PITCH {0, 1, 1}, // MSG_FILTER_SYS {0, 1, 1}, // NOTE_POSITION_STR {0, 1, 1}, // NOTE_VALUE_STR {0, 2, 1}, // NOTE_OVERLAP {0, 1, 1}, // NOTE_OFF_AMP {0.0, 0.5, 0}, // QUANT_RANGE {0, 1, 1}, // QUANT_MAP {0, 1, 1}, // QUANT_POS {0, 1, 1}, // TIME_COMPENS {0, 1, 1}, // USR_LATENCY {0, 192000, 1}, // USR_LATENCY_FR {0.0, 1.0, 0.0}, // STEP_POS {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, // STEP_LEV {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0, 192000, 1} // LATENCY }; class BSchaffl { public: BSchaffl (double samplerate, const LV2_Feature* const* features); ~BSchaffl (); void connect_port (uint32_t port, void *data); void run (uint32_t n_samples); LV2_State_Status state_save(LV2_State_Store_Function store, LV2_State_Handle handle, uint32_t flags, const LV2_Feature* const* features); LV2_State_Status state_restore(LV2_State_Retrieve_Function retrieve, LV2_State_Handle handle, uint32_t flags, const LV2_Feature* const* features); LV2_URID_Map* map; private: double rate; float bpm; float speed; int64_t bar; float barBeat; float beatsPerBar; int beatUnit; double positionSeq; double latencySeq; int64_t latencyFr; uint32_t refFrame; bool uiOn; int actStep; std::minstd_rand mcg; std::uniform_real_distribution<float> distribution; StaticArrayList<MidiData, MIDIBUFFERSIZE> midiData; // Data ports LV2_Atom_Sequence* input; LV2_Atom_Sequence* output; // Controllers int sharedDataNr; float* controllerPtrs[NR_CONTROLLERS]; float controllers[NR_CONTROLLERS]; float stepPositions[MAXSTEPS - 1]; bool stepAutoPositions[MAXSTEPS - 1]; float stepRnds[MAXSTEPS - 1]; Shape<MAXNODES> shape; BSchafflURIs uris; LV2_Atom_Forge forge; LV2_Atom_Forge_Frame frame; Message message; bool notify_shape; bool notify_sharedData; bool notify_controllers[NR_CONTROLLERS]; struct Atom_Controllers { LV2_Atom_Vector_Body body; float data[NR_CONTROLLERS]; }; float getControllerInput (const int sdNr, const int ctrlNr); void setController (const int ctrlNr, const float value); void randomizeStep (const int step); double getStepStart (const int step); double getStepEnd (const int step); int getNoteOnMsg (const uint8_t ch, const uint8_t note, int start = -1) const; int getNoteOffMsg (const uint8_t ch, const uint8_t note, int start = 0) const; void clearMidiData (const float maxSeq); void queueMidiData (const MidiData& midi); double getSequenceFromBeats (const double beats); double getBeatsFromSequence (const double sequence); double getSequenceFromFrame (const int64_t frames, float speed = 1.0f); int64_t getFrameFromSequence (const double sequence, float speed = 1.0f); bool filterMsg (const uint8_t msg); void recalculateLatency(); void recalculateAutoPositions (); void play (uint32_t start, uint32_t end); void notifyControllerToGui (const int nr); void notifySharedDataNrToGui (); void notifyStatusToGui (); void notifyShapeToGui (); void notifyMessageToGui (); }; #endif /* BSCHAFFL_H_ */
5,637
C++
.h
202
25.955446
147
0.672207
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,491
Shape.hpp
sjaehn_BSchaffl/src/Shape.hpp
/* B.Shapr * Beat / envelope shaper LV2 plugin * * Copyright (C) 2019 by Sven Jähnichen * * 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, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef SHAPE_HPP_ #define SHAPE_HPP_ #include <cstddef> #include <cstdio> #include <cstdint> #include <cmath> // #include <iostream> #include "BUtilities/Point.hpp" #include "Node.hpp" #include "StaticArrayList.hpp" #define MAPRES 1024 template<size_t sz> class Shape { public: Shape (); Shape (const StaticArrayList<Node, sz> nodes, double transformFactor = 1.0, double transformOffset = 0.0); virtual ~Shape (); bool operator== (const Shape<sz>& rhs); bool operator!= (const Shape<sz>& rhs); void setTransformation (const double transformFactor, const double transformOffset); virtual void clearShape (); virtual void setDefaultShape (); bool isDefault () const; size_t size () const; Node getRawNode (const size_t nr) const; Node getNode (const size_t nr) const; size_t findRawNode (const Node& node); bool validateNode (const size_t nr); bool validateShape (); bool appendRawNode (const Node& node); bool appendNode (const Node& node); bool insertRawNode (const size_t pos, const Node& node); bool insertNode (const size_t pos, const Node& node); bool insertRawNode (const Node& node); bool insertNode (const Node& node); bool changeRawNode (const size_t pos, const Node& newnode); bool changeNode (const size_t pos, const Node& newnode); bool deleteNode (const size_t pos); double getMapRawValue (const double x) const; double getMapValue (const double x) const; double* getMap (); protected: double transform (const double value) const; double retransform (const double value) const; Node transformNode (const Node& node) const; Node retransformNode (const Node& node) const; virtual void drawLineOnMap (const BUtilities::Point p1, const BUtilities::Point p2); BUtilities::Point getPointPerc (const BUtilities::Point p1, const BUtilities::Point p2, const double perc) const; virtual void renderBezier (const Node& n1, const Node& n2); StaticArrayList<Node, sz> nodes_; double map_[MAPRES]; double factor_; double offset_; }; template<size_t sz> Shape<sz>::Shape () : nodes_ (), map_ {0.0}, factor_ (1.0), offset_ (0.0) {} template<size_t sz> Shape<sz>::Shape (const StaticArrayList<Node, sz> nodes, double transformFactor, double transformOffset) : nodes_ (nodes), map_ {0.0}, factor_ (transformFactor), offset_ (transformFactor) {} template<size_t sz> Shape<sz>::~Shape () {} template<size_t sz> bool Shape<sz>::operator== (const Shape<sz>& rhs) { if (size () != rhs.size ()) return false; for (unsigned int i = 0; i < size (); ++i) if (nodes_[i] != rhs.nodes_[i]) return false; return true; } template<size_t sz> bool Shape<sz>::operator!= (const Shape<sz>& rhs) {return !(*this == rhs);} template<size_t sz> void Shape<sz>::setTransformation (const double transformFactor, const double transformOffset) { // Prevent div by zero if (transformFactor == 0.0) return; factor_ = transformFactor; offset_ = transformOffset; } template<size_t sz> void Shape<sz>::clearShape () { while (!nodes_.empty ()) nodes_.pop_back (); for (int i = 0; i < MAPRES; ++i) map_[i] = 0; } template<size_t sz> void Shape<sz>::setDefaultShape () { clearShape (); nodes_.push_back ({NodeType::END_NODE, {0, 0}, {0, 0}, {0, 0}}); nodes_.push_back ({NodeType::END_NODE, {1, 0}, {0, 0}, {0, 0}}); renderBezier (nodes_[0], nodes_[1]); } template<size_t sz>bool Shape<sz>::isDefault () const { return ((nodes_.size == 2) && (nodes_[0] == Node {NodeType::END_NODE, {0, 0}, {0, 0}, {0, 0}})); } template<size_t sz>size_t Shape<sz>::size () const {return nodes_.size;} template<size_t sz>Node Shape<sz>::getRawNode (const size_t nr) const {return nodes_[nr];} template<size_t sz>Node Shape<sz>::getNode (const size_t nr) const {return retransformNode (getRawNode (nr));} template<size_t sz>size_t Shape<sz>::findRawNode (const Node& node) { for (int i = 0; i < nodes_.size; ++i) { if (nodes_[i] == node) return i; } return nodes_.size; } template<size_t sz> bool Shape<sz>::appendRawNode (const Node& node) { if (nodes_.size < sz) { nodes_.push_back (node); return true; } return false; } template<size_t sz> bool Shape<sz>::appendNode (const Node& node) { return appendRawNode (transformNode (node)); } template<size_t sz> bool Shape<sz>::insertRawNode (const size_t pos, const Node& node) { // Nodes full => errorNode if (nodes_.size >= sz) return false; size_t p = pos; // Insert if (p < nodes_.size) nodes_.insert (nodes_.begin() + p, node); // Otherwise append else { p = nodes_.size; nodes_.push_back (node); } // Validate node and its neighbors if (!validateNode (p)) return false; if ((p > 0) && (!validateNode (p - 1))) return false; if ((p + 1 < nodes_.size) && (!validateNode (p + 1))) return false; // Update map for (unsigned int i = (p >= 2 ? p - 2 : 0); (i <= p + 1) && (i + 1 < nodes_.size); ++ i) renderBezier (nodes_[i], nodes_[i + 1]); return true; } template<size_t sz> bool Shape<sz>::insertNode (const size_t pos, const Node& node) { return insertRawNode (pos, transformNode (node)); } template<size_t sz> bool Shape<sz>::insertRawNode (const Node& node) { // Find position size_t pos = nodes_.size; for (unsigned int i = 0; i < nodes_.size; ++i) { if (node.point.x < nodes_[i].point.x) { // Add if not redundant if ((i > 0) && (node != nodes_[i - 1])) { pos = i; break; } else return false; } } // Insert return insertRawNode (pos, node); } template<size_t sz> bool Shape<sz>::insertNode (const Node& node) { return insertRawNode (transformNode (node)); } template<size_t sz> bool Shape<sz>::changeRawNode (const size_t pos, const Node& node) { if (pos >= nodes_.size) return false; nodes_[pos] = node; // Validate node and its neighbors if (!validateNode (pos)) return false; if ((pos > 0) && (!validateNode (pos - 1))) return false; if ((pos + 1 < nodes_.size) && (!validateNode (pos + 1))) return false; // Update map for (unsigned int i = (pos >= 2 ? pos - 2 : 0); (i <= pos + 1) && (i + 1 < nodes_.size); ++i) renderBezier (nodes_[i], nodes_[i + 1]); return true; } template<size_t sz> bool Shape<sz>::changeNode (const size_t pos, const Node& node) { return changeRawNode (pos, transformNode (node)); } template<size_t sz> bool Shape<sz>::deleteNode (const size_t pos) { // Only deletion of middle nodes allowed if ((pos == 0) || (pos >= nodes_.size - 1)) return false; nodes_.erase (nodes_.begin() + pos); // Validate neighbor nodes if (!validateNode (pos - 1)) return false; if (!validateNode (pos)) return false; // Update map for (unsigned int i = (pos >= 2 ? pos - 2 : 0); (i <= pos) && (i + 1 < nodes_.size); ++ i) renderBezier (nodes_[i], nodes_[i + 1]); return true; } template<size_t sz> bool Shape<sz>::validateNode (const size_t nr) { // Exception: Invalid parameters if (nr >= nodes_.size) { fprintf (stderr, "BSchaffl.lv2: Node validation called with invalid parameters (node: %li).\n", nr); return false; } // Exception: Invalid node order if ((nodes_.size >= 3) && (nr > 1) && (nr < nodes_.size - 1) && (nodes_[nr-1].point.x > nodes_[nr+1].point.x)) { fprintf (stderr, "BSchaffl.lv2: Corrupt node data at node %li (%f, %f). Reset shape.\n", nr, nodes_[nr].point.x, nodes_[nr].point.y); setDefaultShape (); return false; } // Start node if (nr == 0) { // Check: Only end nodes on start position if (nodes_[0].nodeType != NodeType::END_NODE) nodes_[0] = {NodeType::END_NODE, {0, 0}, {0, 0}, {0, 0}}; // Check: Start position if (nodes_[0].point.x != 0) nodes_[0].point.x = 0; // Check: No handles nodes_[0].handle1 = BUtilities::Point (0, 0); nodes_[0].handle2 = BUtilities::Point (0, 0); } // End node else if (nr == nodes_.size - 1) { // Check: Only end nodes on end position if (nodes_[nr].nodeType != NodeType::END_NODE) { nodes_[nr] = {NodeType::END_NODE, {1, nodes_[0].point.y}, {0, 0}, {0, 0}}; } // Check: No handles nodes_[nr].handle1 = BUtilities::Point (0, 0); nodes_[nr].handle2 = BUtilities::Point (0, 0); } // Middle nodes else { // Check: No end nodes in the middle if (nodes_[nr].nodeType == NodeType::END_NODE) nodes_[nr].nodeType = NodeType::CORNER_NODE; // Check: Nodes point order if (nodes_[nr].point.x < nodes_[nr - 1].point.x) nodes_[nr].point.x = nodes_[nr - 1].point.x; if (nodes_[nr].point.x > nodes_[nr + 1].point.x) nodes_[nr].point.x = nodes_[nr + 1].point.x; // Check: POINT_NODE without handles if (nodes_[nr].nodeType == NodeType::POINT_NODE) { nodes_[nr].handle1 = BUtilities::Point (0, 0); nodes_[nr].handle2 = BUtilities::Point (0, 0); } // Check: Handles order if (nodes_[nr].handle1.x > 0) nodes_[nr].handle1.x = 0; if (nodes_[nr].handle2.x < 0) nodes_[nr].handle2.x = 0; // Check: AUTO_SMOOTH_NODE with symmetric handles with the half size of the distance to the closest neighbor point if (nodes_[nr].nodeType == NodeType::AUTO_SMOOTH_NODE) { double dist = (nodes_[nr].point.x - nodes_[nr-1].point.x > nodes_[nr+1].point.x - nodes_[nr].point.x ? nodes_[nr+1].point.x - nodes_[nr].point.x : nodes_[nr].point.x - nodes_[nr-1].point.x); double ydist = (nodes_[nr + 1].point.y - nodes_[nr - 1].point.y); double yamp = (fabs (nodes_[nr - 1].point.y != 0) && fabs (nodes_[nr + 1].point.y != 0) ? (fabs (nodes_[nr - 1].point.y) < fabs (nodes_[nr + 1].point.y) ? fabs (nodes_[nr - 1].point.y) / (fabs (nodes_[nr - 1].point.y) + fabs (nodes_[nr + 1].point.y)) : fabs (nodes_[nr + 1].point.y) / (fabs (nodes_[nr - 1].point.y) + fabs (nodes_[nr + 1].point.y))) : 0); nodes_[nr].handle1.x = -dist / 2; nodes_[nr].handle1.y = -ydist * yamp; nodes_[nr].handle2.x = dist / 2; nodes_[nr].handle2.y = ydist * yamp; } // Check: SYMMETRIC_SMOOTH_NODE must be symmetric else if (nodes_[nr].nodeType == NodeType::SYMMETRIC_SMOOTH_NODE) { //Check if handle1 overlaps neighbor point if (nodes_[nr].point.x + nodes_[nr].handle1.x < nodes_[nr-1].point.x) { double f = (nodes_[nr-1].point.x - nodes_[nr].point.x) / nodes_[nr].handle1.x; nodes_[nr].handle1.x *= f; nodes_[nr].handle1.y *= f; } // Make handele2 symmetric to handle1 nodes_[nr].handle2 = BUtilities::Point (0, 0) - nodes_[nr].handle1; //Check if handle2 overlaps neighbor point if (nodes_[nr].point.x + nodes_[nr].handle2.x > nodes_[nr+1].point.x) { double f = (nodes_[nr+1].point.x - nodes_[nr].point.x) / nodes_[nr].handle2.x; nodes_[nr].handle2.x *= f; nodes_[nr].handle2.y *= f; nodes_[nr].handle1 = BUtilities::Point (0, 0) - nodes_[nr].handle2; } } // Check: SMOOTH_NODE handles point to opposite directions else if (nodes_[nr].nodeType == NodeType::SMOOTH_NODE) { //Check if handle1 overlaps neighbor point if (nodes_[nr].point.x + nodes_[nr].handle1.x < nodes_[nr-1].point.x) { double f = (nodes_[nr-1].point.x - nodes_[nr].point.x) / nodes_[nr].handle1.x; nodes_[nr].handle1.x *= f; nodes_[nr].handle1.y *= f; } // Calculate handle distances double dist1 = sqrt (nodes_[nr].handle1.x * nodes_[nr].handle1.x + nodes_[nr].handle1.y * nodes_[nr].handle1.y); double dist2 = sqrt (nodes_[nr].handle2.x * nodes_[nr].handle2.x + nodes_[nr].handle2.y * nodes_[nr].handle2.y); // Recalculate handle2 if ((dist1 != 0) && (dist2 != 0)) { nodes_[nr].handle2.x = -(nodes_[nr].handle1.x * dist2 / dist1); nodes_[nr].handle2.y = -(nodes_[nr].handle1.y * dist2 / dist1); } //Check if handle2 overlaps neighbor point if (nodes_[nr].point.x + nodes_[nr].handle2.x > nodes_[nr+1].point.x) { double f = (nodes_[nr+1].point.x - nodes_[nr].point.x) / nodes_[nr].handle2.x; nodes_[nr].handle2.x *= f; nodes_[nr].handle2.y *= f; } } // Check: CORNER_NODE else if (nodes_[nr].nodeType == NodeType::CORNER_NODE) { //Check if handle1 overlaps neighbor point if (nodes_[nr].point.x + nodes_[nr].handle1.x < nodes_[nr-1].point.x) { double f = (nodes_[nr-1].point.x - nodes_[nr].point.x) / nodes_[nr].handle1.x; nodes_[nr].handle1.x *= f; nodes_[nr].handle1.y *= f; } //Check if handle2 overlaps neighbor point if (nodes_[nr].point.x + nodes_[nr].handle2.x > nodes_[nr+1].point.x) { double f = (nodes_[nr+1].point.x - nodes_[nr].point.x) / nodes_[nr].handle2.x; nodes_[nr].handle2.x *= f; nodes_[nr].handle2.y *= f; } } } return true; } template<size_t sz> bool Shape<sz>::validateShape () { // TODO Sort ??? // Validate nodes bool status = true; for (unsigned int i = 0; i < nodes_.size; ++i) { if (!validateNode (i)) status = false; } // Update map for (unsigned int i = 0; i + 1 < nodes_.size; ++i) renderBezier (nodes_[i], nodes_[i+1]); return status; } template<size_t sz> double Shape<sz>::transform (const double value) const { return (value - offset_) / factor_; } template<size_t sz> double Shape<sz>::retransform (const double value) const { return factor_ * value + offset_; } template<size_t sz> Node Shape<sz>::transformNode (const Node& node) const { return Node ( node.nodeType, BUtilities::Point (node.point.x, transform (node.point.y)), BUtilities::Point (node.handle1.x, node.handle1.y / factor_), BUtilities::Point (node.handle2.x, node.handle2.y / factor_) ); } template<size_t sz> Node Shape<sz>::retransformNode (const Node& node) const { return Node ( node.nodeType, BUtilities::Point (node.point.x, retransform (node.point.y)), BUtilities::Point (node.handle1.x, node.handle1.y * factor_), BUtilities::Point (node.handle2.x, node.handle2.y * factor_) ); } template<size_t sz> void Shape<sz>::drawLineOnMap (BUtilities::Point p1, BUtilities::Point p2) { if (p1.x < p2.x) { for (double x = p1.x; (x <= p2.x) && (x <= 1.0); x += (1.0 / MAPRES)) { uint32_t i = ((uint32_t) (x * MAPRES)) % MAPRES; map_[i] = p1.y + (p2.y - p1.y) * (x - p1.x) / (p2.x - p1.x); } } else { uint32_t i = ((uint32_t) (p2.x * MAPRES)) % MAPRES; map_ [i] = p2.y; } } template<size_t sz> BUtilities::Point Shape<sz>::getPointPerc (const BUtilities::Point p1, const BUtilities::Point p2 , const double perc) const { BUtilities::Point p; p.x = p1.x + (p2.x - p1.x) * perc; p.y = p1.y + (p2.y - p1.y) * perc; return p; } template<size_t sz> void Shape<sz>::renderBezier (const Node& n1, const Node& n2) { // Interpolate Bezier curve BUtilities::Point p1 = n1.point; BUtilities::Point p2 = n1.point + n1.handle2; BUtilities::Point p4 = n2.point; BUtilities::Point p3 = n2.point + n2.handle1; BUtilities::Point py = p1; double step = 1 / (fabs (n2.point.x - n1.point.x) * MAPRES + 1); for (double t = 0; t < 1; t += step) { BUtilities::Point pa = getPointPerc (p1, p2, t); BUtilities::Point pb = getPointPerc (p2, p3, t); BUtilities::Point pc = getPointPerc (p3, p4, t); BUtilities::Point pm = getPointPerc (pa, pb, t); BUtilities::Point pn = getPointPerc (pb, pc, t); BUtilities::Point pz = getPointPerc (pm, pn, t); drawLineOnMap (py, pz); py = pz; } drawLineOnMap (py,p4); } template<size_t shapesize> double Shape<shapesize>::getMapRawValue (const double x) const { double mapx = fmod (x * MAPRES, MAPRES); double xmod = mapx - int (mapx); return (1 - xmod) * map_[int (mapx)] + xmod * map_[int (mapx + 1) % MAPRES]; } template<size_t shapesize> double Shape<shapesize>::getMapValue (const double x) const { return retransform (getMapRawValue (x)); } template<size_t sz> double* Shape<sz>::getMap () {return &map_[0];} /* template<size_t sz> std::ostream &operator<<(std::ostream &output, Shape<sz>& shape) { output << shape.nodes; return output; } */ #endif /* SHAPE_HPP_ */
16,474
C++
.h
455
33.553846
144
0.658798
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,492
SharedData.hpp
sjaehn_BSchaffl/src/SharedData.hpp
/* B.Schaffl * MIDI Pattern Delay Plugin * * Copyright (C) 2018 - 2020 by Sven Jähnichen * * 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, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef SHAREDDATA_HPP #define SHAREDDATA_HPP #include "definitions.hpp" #include "Ports.hpp" #include "Shape.hpp" #include <vector> #include <algorithm> class BSchaffl; // Forward declaration class SharedData { protected: float controllers_[NR_CONTROLLERS]; BSchaffl* instances_[MAXINSTANCES]; public: SharedData () : controllers_ {0}, instances_ {0}, shape () {} bool isLinked (const BSchaffl* inst) const {return std::find (instances_, instances_ + MAXINSTANCES, inst) != instances_ + MAXINSTANCES;} bool empty() const { for (int i = 0; i < MAXINSTANCES ; ++i) { if (instances_[i] != nullptr) return false; } return true; } void link (BSchaffl* inst) { if (isLinked (inst)) return; BSchaffl** it = std::find (instances_, instances_ + MAXINSTANCES, nullptr); if (it != instances_ + MAXINSTANCES) *it = inst; } void unlink (BSchaffl* inst) { BSchaffl** it = std::find (instances_, instances_ + MAXINSTANCES, inst); if (it != instances_ + MAXINSTANCES) *it = nullptr; } void set (const int nr, const float value) {controllers_[nr] = value;} float get (const int nr) const {return controllers_[nr];} Shape<MAXNODES> shape; }; #endif /* SHAREDDATA_HPP */
2,261
C++
.h
59
31.779661
145
0.640018
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,493
Locale_DE.hpp
sjaehn_BSchaffl/src/Locale_DE.hpp
#ifndef BSCHAFFL_LOCALE #define BSCHAFFL_LOCALE #define BSCHAFFL_LABEL_HELP "Hilfe" #define BSCHAFFL_LABEL_TUTORIAL "Tutorial" #define BSCHAFFL_LABEL_ALL_MARKERS_AUTO "Alle Marker: Auto" #define BSCHAFFL_LABEL_ALL_MARKERS_MANUAL "Alle Marker: Manuell" #define BSCHAFFL_LABEL_SELECT "Auswahl" #define BSCHAFFL_LABEL_POINT_NODE "Punkt" #define BSCHAFFL_LABEL_AUTO_NODE "Auto Bezierknoten" #define BSCHAFFL_LABEL_SYMMETRIC_NODE "Symmetrischer Bezierknoten" #define BSCHAFFL_LABEL_ASYMMETRIC_NODE "Asymmetrischer Bezierknoten" #define BSCHAFFL_LABEL_CUT "Ausschneiden" #define BSCHAFFL_LABEL_COPY "Kopieren" #define BSCHAFFL_LABEL_PASTE "Einfügen" #define BSCHAFFL_LABEL_RESET "Reset" #define BSCHAFFL_LABEL_UNDO "Rückgängig" #define BSCHAFFL_LABEL_REDO "Wiederherstellen" #define BSCHAFFL_LABEL_SHOW_GRID "Raster anzeigen" #define BSCHAFFL_LABEL_SNAP_GRID "Einrasten" #define BSCHAFFL_LABEL_CONVERT_TO_SHAPE "Konvertiere Regler zu Kurve" #define BSCHAFFL_LABEL_CONVERT_TO_SHAPE_TITLE "Kurvengesteuerter Verstärker" #define BSCHAFFL_LABEL_CONVERT_TO_SHAPE_TEXT "Du möchtest die diskreten Reglerdaten zu einer Kurve konvertieren ?" #define BSCHAFFL_LABEL_CONVERT_TO_SHAPE_LINEAR_TEXT "Konvertiere linear" #define BSCHAFFL_LABEL_CONVERT_TO_SHAPE_CONST_TEXT "Konvertiere stufenförmig" #define BSCHAFFL_LABEL_OK "OK" #define BSCHAFFL_LABEL_APPLY "Anwenden" #define BSCHAFFL_LABEL_CANCEL "Abbruch" #define BSCHAFFL_LABEL_CONVERT_TO_STEPS "Konvertiere Kurve zu Regler" #define BSCHAFFL_LABEL_CONVERT_TO_STEPS_TITLE "Reglergesteuerter Verstärker" #define BSCHAFFL_LABEL_CONVERT_TO_STEPS_TEXT "Du möchtest die Kurve zu diskreten Reglerdaten konvertieren ?" #define BSCHAFFL_LABEL_MIDI_CH "Kontrollierte MIDI-Kanäle:" #define BSCHAFFL_LABEL_ALL "Alle" #define BSCHAFFL_LABEL_MIDI_MSG "Kontrollierte MIDI-Nachrichten:" #define BSCHAFFL_LABEL_NOTE_TEXT "Notenpositionen und -längen können von Veränderungen ausgeschlossen werden. Achtung, Überlappungen sind möglich!" #define BSCHAFFL_LABEL_NOTE_KEEP_POSITION "Behalte Notenposition" #define BSCHAFFL_LABEL_NOTE_KEEP_DURATION "Behalte Notenlänge" #define BSCHAFFL_LABEL_DO_NOTHING "Ignorieren" #define BSCHAFFL_LABEL_SPLIT "Splitten" #define BSCHAFFL_LABEL_MERGE "Verschmelzen" #define BSCHAFFL_LABEL_IF_NOTES_OVERLAP_TITLE "Falls Noten überlappen:" #define BSCHAFFL_LABEL_IF_NOTES_OVERLAP_TEXT "MIDI NOTE_OFF kann entweder mit den Daten vom Notenstart oder -ende verstärkt werden." #define BSCHAFFL_LABEL_NOTE_OFF_AMP "NOTE_OFF Verst.:" #define BSCHAFFL_LABEL_USE_NOTE_ON_AMP "Nutze NOTE_ON-Verstärkung" #define BSCHAFFL_LABEL_CALCULATE_FROM_END "Berechne von akt. Position" #define BSCHAFFL_LABEL_SMART_QUANTIZATION_TEXT_1 "Synchronisation von nicht genau in die Schrittfolge passenden Signalen (z. B. Noten). Dazu muss das Signal in einem bestimmten Bereich um den Start oder das Ende des Schrittes liegen." #define BSCHAFFL_LABEL_SMART_QUANTIZATION_TEXT_2 "MIDI-Signale können einem Schritt zugewiesen oder in diesen eingepasst werden." #define BSCHAFFL_LABEL_RANGE_STEPS "Reichweite (Schritte)" #define BSCHAFFL_LABEL_ASSIGN_TO_STEP "Einem Schritt zuweisen" #define BSCHAFFL_LABEL_FIT_TO_STEP "In einen Schritt einpassen" #define BSCHAFFL_LABEL_LATENCY_COMPENSATION_TEXT "Einige Pluginhosts führen eine Latenzkompensation durch. Falls nicht, so kannst du es manuell tun." #define BSCHAFFL_LABEL_LATENCY_COMPENSATION_TITLE "Latenzkompensation" #define BSCHAFFL_LABEL_LATENCY_USER_TEXT "Normalerweise berechnet das Plugin die Latenz. Alternativ kannst du eine feste Latenz setzen." #define BSCHAFFL_LABEL_LATENCY_USER_TITLE "Benutzerdefinierte Latenz" #define BSCHAFFL_LABEL_FRAMES "Frames" #define BSCHAFFL_LABEL_MS "ms" #define BSCHAFFL_LABEL_SECONDS "Sekunde(n)" #define BSCHAFFL_LABEL_BEATS "Beat(s)" #define BSCHAFFL_LABEL_BARS "Takt(e)" #define BSCHAFFL_LABEL_AUTO "Auto" #define BSCHAFFL_LABEL_MANUAL "Manuell" #define BSCHAFFL_LABEL_ENTER "Eingabe" #define BSCHAFFL_LABEL_NEW_POSITION "Neue Position:" #define BSCHAFFL_LABEL_NEW_LENGTH "Neue Länge:" #define BSCHAFFL_LABEL_SEQUENCES "Sequenz(en)" #define BSCHAFFL_LABEL_STEPS "Schritt(e)" #define BSCHAFFL_LABEL_SHARED_DATA "Gemeinsame Daten" #define BSCHAFFL_LABEL_JACK_OFF "Jack-Transport angehalten." #define BSCHAFFL_LABEL_LATENCY_EXCEEDS "Latenz überschreitet Maximum von 192000 Frames." #define BSCHAFFL_LABEL_MIDI_NO "Note" #define BSCHAFFL_LABEL_MIDI_KP "Key pressure" #define BSCHAFFL_LABEL_MIDI_CC "Control change" #define BSCHAFFL_LABEL_MIDI_PC "Program change" #define BSCHAFFL_LABEL_MIDI_CP "Channel pressure" #define BSCHAFFL_LABEL_MIDI_PB "Pitch bend" #define BSCHAFFL_LABEL_MIDI_SE "System exclusive" #define BSCHAFFL_LABEL_LATENCY "Latenz" #define BSCHAFFL_FILENAME_IN "inc/in.png" #define BSCHAFFL_FILENAME_OUT "inc/out.png" #define BSCHAFFL_FILENAME_AMP "inc/amp.png" #define BSCHAFFL_FILENAME_STR "inc/del.png" #define BSCHAFFL_FILENAME_SEQUENCE_SIZE "inc/sequence_size_de.png" #define BSCHAFFL_FILENAME_AMP_SWING "inc/amp_swing_de.png" #define BSCHAFFL_FILENAME_AMP_RANDOM "inc/amp_random_de.png" #define BSCHAFFL_FILENAME_AMP_PROCESS "inc/amp_process_de.png" #define BSCHAFFL_FILENAME_NR_OF_STEPS "inc/number_of_steps_de.png" #define BSCHAFFL_FILENAME_STEPS_SWING "inc/steps_swing_de.png" #define BSCHAFFL_FILENAME_STEPS_RANDOM "inc/steps_random_de.png" #define BSCHAFFL_FILENAME_STEPS_PROCESS "inc/steps_process_de.png" #define BSCHAFFL_FILENAME_MIDI_CH_FILTER "inc/midi_ch_filter_de.png" #define BSCHAFFL_FILENAME_MIDI_MSG_FILTER "inc/midi_msg_filter_de.png" #define BSCHAFFL_FILENAME_MIDI_NOTE_OPTIONS "inc/midi_note_options_de.png" #define BSCHAFFL_FILENAME_SMART_QUANTIZATION "inc/smart_quantization.png" #define BSCHAFFL_FILENAME_LATENCY "inc/latency_de.png" #endif
5,716
C++
.h
94
59.531915
234
0.818978
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,494
BSchafflGUI.hpp
sjaehn_BSchaffl/src/BSchafflGUI.hpp
/* B.Schaffl * MIDI Pattern Delay Plugin * * Copyright (C) 2018 - 2020 by Sven Jähnichen * * 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, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef BSCHAFFLGUI_HPP_ #define BSCHAFFLGUI_HPP_ #include <lv2/lv2plug.in/ns/extensions/ui/ui.h> #include <lv2/lv2plug.in/ns/ext/atom/atom.h> #include <lv2/lv2plug.in/ns/ext/atom/forge.h> #include "BWidgets/Widget.hpp" #include "BWidgets/Window.hpp" #include "BWidgets/Label.hpp" #include "BWidgets/DrawingSurface.hpp" #include "BWidgets/HSwitch.hpp" #include "BWidgets/VSlider.hpp" #include "BWidgets/VSliderValue.hpp" #include "BWidgets/HSliderValue.hpp" #include "BWidgets/DialValue.hpp" #include "BWidgets/ListBox.hpp" #include "BWidgets/ToggleButton.hpp" #include "BWidgets/TextButton.hpp" #include "BWidgets/PopupListBox.hpp" #include "BWidgets/ImageIcon.hpp" #include "BWidgets/Text.hpp" #include "BWidgets/MessageBox.hpp" #include "Marker.hpp" #include "LightButton.hpp" #include "SwingHSlider.hpp" #include "HaloButton.hpp" #include "HaloToggleButton.hpp" #include "SelectMenu.hpp" #include "ShapeWidget.hpp" #include "definitions.hpp" #include "Ports.hpp" #include "Urids.hpp" #ifndef MESSAGENR_ #define MESSAGENR_ #ifdef LOCALEFILE #include LOCALEFILE #else #include "Locale_EN.hpp" #endif enum MessageNr { NO_MSG = 0, JACK_STOP_MSG = 1, LATENCY_MAX_MSG = 2, MAX_MSG = 2 }; #endif /* MESSAGENR_ */ #define BSCHAFFL_FILENAME_BG "inc/surface.png" #define HELP_URL "https://github.com/sjaehn/BSchaffl/blob/master/README.md" #define YT_URL " https://youtu.be/CBwkYDk5reU" #define WWW_BROWSER_CMD "x-www-browser" #define LIM(g , min, max) ((g) > (max) ? (max) : ((g) < (min) ? (min) : (g))) #define RESIZE(widget, x, y, w, h, sz) (widget).moveTo ((x) * (sz), (y) * (sz)); (widget).resize ((w) * (sz), (h) * (sz)); const std::string messageStrings[MAX_MSG + 1] = { "", "*** " BSCHAFFL_LABEL_JACK_OFF " ***", "*** " BSCHAFFL_LABEL_LATENCY_EXCEEDS " ***" }; const std::array<std::string, NR_MIDI_MSG_FILTERS> midiMsgGroupTexts = {{ BSCHAFFL_LABEL_MIDI_NO, BSCHAFFL_LABEL_MIDI_KP, BSCHAFFL_LABEL_MIDI_CC, BSCHAFFL_LABEL_MIDI_PC, BSCHAFFL_LABEL_MIDI_CP, BSCHAFFL_LABEL_MIDI_PB, BSCHAFFL_LABEL_MIDI_SE }}; class BSchafflGUI : public BWidgets::Window { public: BSchafflGUI (const char *bundle_path, const LV2_Feature *const *features, PuglNativeView parentWindow); ~BSchafflGUI (); void portEvent (uint32_t port_index, uint32_t buffer_size, uint32_t format, const void *buffer); virtual void onConfigureRequest (BEvents::ExposeEvent* event) override; virtual void onCloseRequest (BEvents::WidgetEvent* event) override; void applyTheme (BStyles::Theme& theme) override; void sendUiStatus (const bool on); void sendShape (); void sendSharedDataNr (); void sendController (const int nr, const float value); LV2UI_Controller controller; LV2UI_Write_Function write_function; private: double getStepValue (const int stepNr) const; void resizeGUI (); float setController (const int nr, const double value); void setMarker (const int markerNr, double value); void setAutoMarkers (); void rearrange_controllers (); void redrawSContainer (); void recalculateEnterEdit (); static void valueChangedCallback (BEvents::Event* event); static void shapeChangedCallback (BEvents::Event* event); static void markerClickedCallback (BEvents::Event* event); static void markerDraggedCallback (BEvents::Event* event); static void listBoxChangedCallback (BEvents::Event* event); static void enterListBoxChangedCallback (BEvents::Event* event); static void enterOkClickedCallback (BEvents::Event* event); static void markersAutoClickedCallback (BEvents::Event* event); static void shapeToolClickedCallback (BEvents::Event* event); static void editToolClickedCallback (BEvents::Event* event); static void historyToolClickedCallback (BEvents::Event* event); static void gridToolClickedCallback (BEvents::Event* event); static void convertButtonClickedCallback (BEvents::Event* event); static void lightButtonClickedCallback (BEvents::Event* event); static void sharedDataClickedCallback (BEvents::Event* event); static void helpButtonClickedCallback (BEvents::Event* event); static void ytButtonClickedCallback (BEvents::Event* event); static void stepControlLabelMessageCallback (BEvents::Event* event); std::string pluginPath; BWidgets::Widget mContainer; HaloButton helpButton; HaloButton ytButton; BWidgets::Widget toolbox; BWidgets::ImageIcon toolIcon; BWidgets::ImageIcon convertToShapeIcon; BWidgets::ImageIcon convertToStepsIcon; HaloButton convertToShapeButton; HaloButton convertToStepsButton; BWidgets::ImageIcon markersToolbox; BWidgets::ImageIcon shapeToolbox; BWidgets::ImageIcon editToolbox; BWidgets::ImageIcon historyToolbox; BWidgets::ImageIcon gridToolbox; HaloButton markersAutoButton; HaloButton markersManualButton; std::array<HaloToggleButton, 5> shapeToolButtons; std::array<HaloButton, 3> editToolButtons; std::array<HaloButton, 3> historyToolButtons; HaloToggleButton gridShowButton; HaloToggleButton gridSnapButton; BWidgets::MessageBox convertToShapeMessage; LightButton convertToShapeToLinearButton; BWidgets::Text convertToShapeToLinearText; LightButton convertToShapeToConstButton; BWidgets::Text convertToShapeToConstText; BWidgets::MessageBox convertToStepsMessage; BWidgets::ImageIcon midiChFilterIcon; BWidgets::Widget midiChFilterContainer; BWidgets::Text midiChFilterText; BWidgets::HSwitch midiChFilterAllSwitch; BWidgets::Label midiChFilterAllLabel; std::array<BWidgets::HSwitch, NR_MIDI_CHS> midiChFilterSwitches; std::array<BWidgets::Label, NR_MIDI_CHS> midiChFilterLabels; BWidgets::ImageIcon midiMsgFilterIcon; BWidgets::Widget midiMsgFilterContainer; BWidgets::Text midiMsgFilterText; BWidgets::HSwitch midiMsgFilterAllSwitch; BWidgets::Label midiMsgFilterAllLabel; std::array<BWidgets::HSwitch, NR_MIDI_MSG_FILTERS> midiMsgFilterSwitches; std::array<BWidgets::Label, NR_MIDI_MSG_FILTERS> midiMsgFilterLabels; BWidgets::ImageIcon midiNoteOptionsIcon; BWidgets::Widget midiNoteOptionsContainer; BWidgets::Text midiNoteText; BWidgets::HSwitch midiNotePositionSwitch; BWidgets::Label midiNotePositionLabel; BWidgets::HSwitch midiNoteValueSwitch; BWidgets::Label midiNoteValueLabel; BWidgets::PopupListBox midiNoteOverlapListbox; BWidgets::Label midiNoteOverlapLabel; BWidgets::Text midiNoteText2; BWidgets::Label midiNoteOffAmpLabel; BWidgets::PopupListBox midiNoteOffAmpListbox; BWidgets::ImageIcon smartQuantizationIcon; BWidgets::Widget smartQuantizationContainer; BWidgets::HSliderValue smartQuantizationRangeSlider; BWidgets::HSwitch smartQuantizationMappingSwitch; BWidgets::HSwitch smartQuantizationPositioningSwitch; BWidgets::Text smartQuantizationText1; BWidgets::Label smartQuantizationRangeLabel; BWidgets::Text smartQuantizationText2; BWidgets::Label smartQuantizationMappingLabel; BWidgets::Label smartQuantizationPositionLabel; BWidgets::ImageIcon userLatencyIcon; BWidgets::Widget userLatencyContainer; BWidgets::Text timeCompensText; BWidgets::Label timeCompensLabel; BWidgets::HSwitch timeCompensSwitch; BWidgets::Text userLatencyText; BWidgets::HSwitch userLatencySwitch; BWidgets::Label userLatencyLabel; BWidgets::RangeWidget userLatencyValue; BWidgets::HSliderValue userLatencySlider; BWidgets::PopupListBox userLatencyUnitListbox; SelectMenu selectMenu; BWidgets::RangeWidget sharedDataSelection; std::array<HaloToggleButton, 4> sharedDataButtons; BWidgets::DrawingSurface sContainer; BWidgets::HSwitch modeSwitch; BWidgets::PopupListBox seqLenValueListbox; BWidgets::PopupListBox seqLenBaseListbox; SwingHSlider ampSwingControl; BWidgets::HSliderValue ampRandomControl; BWidgets::HSliderValue ampProcessControl; SwingHSlider swingControl; BWidgets::HSliderValue swingRandomControl; BWidgets::HSliderValue swingProcessControl; BWidgets::HSliderValue nrStepsControl; BWidgets::ImageIcon seqLenIcon; BWidgets::ImageIcon ampSwingIcon; BWidgets::ImageIcon ampRandomIcon; BWidgets::ImageIcon ampProcessIcon; BWidgets::ImageIcon nrStepsIcon; BWidgets::ImageIcon swingIcon; BWidgets::ImageIcon swingRandomIcon; BWidgets::ImageIcon swingProcessIcon; BWidgets::ValueWidget stepControlContainer; ShapeWidget shapeWidget; std::array<BWidgets::VSlider, MAXSTEPS> stepControl; std::array<BWidgets::Label, MAXSTEPS> stepControlLabel; std::array<Marker, MAXSTEPS - 1> markerWidgets; BWidgets::ListBox markerListBox; BWidgets::Widget enterFrame; BWidgets::PopupListBox enterPositionPopup; BWidgets::Label enterEdit; BWidgets::PopupListBox enterSequencesPopup; BWidgets::TextButton enterOkButton; BWidgets::ValueWidget latencyValue; // Dummy BWidgets::Label latencyDisplay; std::array<BWidgets::ValueWidget*, NR_CONTROLLERS> controllers; BWidgets::Label messageLabel; BWidgets::ImageIcon inIcon; BWidgets::ImageIcon ampIcon; BWidgets::ImageIcon delIcon; BWidgets::ImageIcon outIcon; std::array<BWidgets::Label, MAXSTEPS> inputStepLabel; std::array<BWidgets::Label, MAXSTEPS> outputStepLabel; std::vector<Node> clipboard; Snapshots<std::array<double, MAXSTEPS>, MAXUNDO> sliderHistory; double sz; cairo_surface_t* bgImageSurface; LV2_Atom_Forge forge; BSchafflURIs uris; LV2_URID_Map* map; double rate; // Definition of styles BColors::ColorSet fgColors = {{{0.75, 0.75, 0.75, 1.0}, {1.0, 1.0, 1.0, 1.0}, {0.2, 0.2, 0.2, 1.0}, {0.0, 0.0, 0.0, 0.0}}}; BColors::ColorSet procColors = {{{0.75, 0.75, 0.75, 1.0}, {0.75, 0.0, 0.0, 1.0}, {0.2, 0.2, 0.2, 1.0}, {0.0, 0.0, 0.0, 0.0}}}; BColors::ColorSet txColors = {{BColors::lightgrey, BColors::white, BColors::darkgrey, {0.0, 0.0, 0.0, 0.0}}}; BColors::ColorSet bgColors = {{{0.15, 0.15, 0.15, 1.0}, {0.3, 0.3, 0.3, 1.0}, {0.05, 0.05, 0.05, 1.0}, {0.0, 0.0, 0.0, 0.0}}}; BColors::ColorSet procBgColors = {{{0.15, 0.15, 0.15, 1.0}, {0.15, 0.15, 0.15, 1.0}, {0.05, 0.05, 0.05, 1.0}, {0.0, 0.0, 0.0, 0.0}}}; BStyles::Border border = {{BColors::darkgrey, 1.0}, 0.0, 2.0, 0.0}; BStyles::Border menuborder = {{BColors::darkgrey, 1.0}, 0.0, 0.0, 0.0}; BStyles::Border stepborder = {{BColors::darkgrey, 1.0}, 0.0, 2.0, 3.0}; BStyles::Border labelBorder = BStyles::Border (BStyles::noLine, 0.0, 4.0); BStyles::Border focusborder = BStyles::Border (BStyles::Line (BColors::Color (0.0, 0.0, 0.0, 0.5), 2.0)); BStyles::Fill widgetBg = BStyles::noFill; BStyles::Fill screenBg = BStyles::Fill (BColors::Color (0.0, 0.0, 0.0, 0.75)); BStyles::Fill actBg = BStyles::Fill (BColors::lightgrey); BStyles::Border screenBorder = BStyles::Border (BStyles::Line (BColors::Color (0.0, 0.0, 0.0, 0.75), 4.0)); BStyles::Font defaultFont = BStyles::Font ("Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL, 12.0, BStyles::TEXT_ALIGN_CENTER, BStyles::TEXT_VALIGN_MIDDLE); BStyles::Font mdFont = BStyles::Font ("Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL, 10.0, BStyles::TEXT_ALIGN_CENTER, BStyles::TEXT_VALIGN_MIDDLE); BStyles::Font smFont = BStyles::Font ("Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL, 8.0, BStyles::TEXT_ALIGN_CENTER, BStyles::TEXT_VALIGN_MIDDLE); BStyles::Font lfFont = BStyles::Font ("Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL, 12.0, BStyles::TEXT_ALIGN_LEFT, BStyles::TEXT_VALIGN_MIDDLE); BStyles::Font txFont = BStyles::Font ("Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL, 12.0, BStyles::TEXT_ALIGN_LEFT, BStyles::TEXT_VALIGN_TOP); BStyles::StyleSet defaultStyles = {"default", {{"background", STYLEPTR (&BStyles::noFill)}, {"border", STYLEPTR (&BStyles::noBorder)}}}; BStyles::StyleSet labelStyles = {"labels", {{"background", STYLEPTR (&BStyles::noFill)}, {"border", STYLEPTR (&BStyles::noBorder)}, {"textcolors", STYLEPTR (&txColors)}, {"font", STYLEPTR (&defaultFont)}}}; BStyles::StyleSet mlStyles = {"labels", {{"background", STYLEPTR (&BStyles::noFill)}, {"border", STYLEPTR (&BStyles::noBorder)}, {"textcolors", STYLEPTR (&txColors)}, {"font", STYLEPTR (&mdFont)}}}; BStyles::StyleSet smStyles = {"labels", {{"background", STYLEPTR (&BStyles::noFill)}, {"border", STYLEPTR (&BStyles::noBorder)}, {"textcolors", STYLEPTR (&txColors)}, {"font", STYLEPTR (&smFont)}}}; BStyles::StyleSet lfStyles = {"labels", {{"background", STYLEPTR (&BStyles::noFill)}, {"border", STYLEPTR (&BStyles::noBorder)}, {"textcolors", STYLEPTR (&txColors)}, {"font", STYLEPTR (&lfFont)}}}; BStyles::StyleSet txStyles = {"labels", {{"background", STYLEPTR (&BStyles::noFill)}, {"border", STYLEPTR (&BStyles::noBorder)}, {"textcolors", STYLEPTR (&txColors)}, {"font", STYLEPTR (&txFont)}}}; BStyles::StyleSet focusStyles = {"labels", {{"background", STYLEPTR (&screenBg)}, {"border", STYLEPTR (&focusborder)}, {"textcolors", STYLEPTR (&txColors)}, {"font", STYLEPTR (&defaultFont)}}}; BStyles::Theme theme = BStyles::Theme ({ defaultStyles, {"B.Schaffl", {{"background", STYLEPTR (&BStyles::blackFill)}, {"border", STYLEPTR (&BStyles::noBorder)}}}, {"main", {{"background", STYLEPTR (&widgetBg)}, {"border", STYLEPTR (&BStyles::noBorder)}}}, {"widget", {{"uses", STYLEPTR (&defaultStyles)}}}, {"screen", {{"background", STYLEPTR (&screenBg)}, {"border", STYLEPTR (&BStyles::noBorder)}}}, {"scontainer", {{"background", STYLEPTR (&BStyles::noFill)}, {"border", STYLEPTR (&border)}}}, {"listbox", {{"border", STYLEPTR (&menuborder)}, {"background", STYLEPTR (&BStyles::blackFill)}}}, {"listbox/item",{{"uses", STYLEPTR (&defaultStyles)}, {"border", STYLEPTR (&labelBorder)}, {"textcolors", STYLEPTR (&BColors::whites)}, {"font", STYLEPTR (&defaultFont)}}}, {"listbox/button",{{"border", STYLEPTR (&BColors::darks)}, {"background", STYLEPTR (&BStyles::blackFill)}, {"bgcolors", STYLEPTR (&BColors::darks)}}}, {"menu", {{"border", STYLEPTR (&menuborder)}, {"background", STYLEPTR (&BStyles::blackFill)}}}, {"menu/item", {{"background", STYLEPTR (&BStyles::blackFill)}, {"border", STYLEPTR (&BStyles::noBorder)}, {"textcolors", STYLEPTR (&BColors::whites)}, {"font", STYLEPTR (&lfFont)}}}, {"menu/button", {{"border", STYLEPTR (&menuborder)}, {"background", STYLEPTR (&BStyles::blackFill)}, {"bgcolors", STYLEPTR (&bgColors)}}}, {"menu/listbox",{{"border", STYLEPTR (&menuborder)}, {"background", STYLEPTR (&BStyles::blackFill)}}}, {"menu/listbox/item",{{"background", STYLEPTR (&BStyles::blackFill)}, {"border", STYLEPTR (&BStyles::noBorder)}, {"textcolors", STYLEPTR (&BColors::whites)}, {"font", STYLEPTR (&lfFont)}}}, {"menu/listbox/button",{{"border", STYLEPTR (&BStyles::noBorder)}, {"background", STYLEPTR (&BStyles::blackFill)}, {"bgcolors", STYLEPTR (&bgColors)}}}, {"shape", {{"background", STYLEPTR (&BStyles::noFill)}, {"border", STYLEPTR (&BStyles::noBorder)}, {"fgcolors", STYLEPTR (&fgColors)}, {"symbolcolors", STYLEPTR (&fgColors)}, {"font", STYLEPTR (&smFont)}, {"bgcolors", STYLEPTR (&bgColors)}}}, {"shape/focus", {{"background", STYLEPTR (&screenBg)}, {"border", STYLEPTR (&screenBorder)}, {"font", STYLEPTR (&smFont)}, {"textcolors", STYLEPTR (&txColors)}}}, {"selectmenu", {{"uses", STYLEPTR (&defaultStyles)}, {"bgcolors", STYLEPTR (&fgColors)}}}, {"halobutton", {{"uses", STYLEPTR (&defaultStyles)}, {"fgcolors", STYLEPTR (&bgColors)}}}, {"halobutton/focus", {{"uses", STYLEPTR (&focusStyles)}}}, {"slider", {{"uses", STYLEPTR (&defaultStyles)}, {"fgcolors", STYLEPTR (&fgColors)}, {"bgcolors", STYLEPTR (&bgColors)}, {"textcolors", STYLEPTR (&fgColors)}, {"font", STYLEPTR (&defaultFont)}}}, {"slider/focus",{{"background", STYLEPTR (&screenBg)}, {"border", STYLEPTR (&screenBorder)}, {"textcolors", STYLEPTR (&txColors)}, {"font", STYLEPTR (&defaultFont)}}}, {"procslider",{{"uses", STYLEPTR (&defaultStyles)}, {"fgcolors", STYLEPTR (&procColors)}, {"bgcolors", STYLEPTR (&procBgColors)}, {"textcolors", STYLEPTR (&fgColors)}, {"font", STYLEPTR (&defaultFont)}}}, {"procslider/focus",{{"background", STYLEPTR (&screenBg)}, {"border", STYLEPTR (&screenBorder)}, {"textcolors", STYLEPTR (&txColors)}, {"font", STYLEPTR (&defaultFont)}}}, {"label", {{"uses", STYLEPTR (&labelStyles)}}}, {"mlabel", {{"uses", STYLEPTR (&mlStyles)}}}, {"lflabel", {{"uses", STYLEPTR (&lfStyles)}}}, {"text", {{"uses", STYLEPTR (&txStyles)}}}, {"steplabel", {{"uses", STYLEPTR (&smStyles)}, {"border", STYLEPTR (&stepborder)}}}, {"actsteplabel",{{"uses", STYLEPTR (&smStyles)}, {"background", STYLEPTR (&actBg)}, {"textcolors", STYLEPTR (&BColors::darks)}}}, {"smlabel", {{"uses", STYLEPTR (&smStyles)}}}, {"hilabel", {{"uses", STYLEPTR (&labelStyles)}, {"textcolors", STYLEPTR (&BColors::whites)}}}, }); }; #endif /* BSCHAFFLGUI_HPP_ */
19,935
C++
.h
386
42.860104
174
0.645346
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,495
Message.hpp
sjaehn_BSchaffl/src/Message.hpp
/* B.Schaffl * MIDI Pattern Delay Plugin * * Copyright (C) 2018 - 2020 by Sven Jähnichen * * 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, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef MESSAGE_HPP_ #define MESSAGE_HPP_ #include <cstdint> #ifndef MESSAGENR_ #define MESSAGENR_ enum MessageNr { NO_MSG = 0, JACK_STOP_MSG = 1, LATENCY_MAX_MSG = 2, MAX_MSG = 2 }; #endif /* MESSAGENR_ */ class Message { public: Message (); void clearMessages (); void setMessage (MessageNr messageNr); void deleteMessage (MessageNr messageNr); bool isMessage (MessageNr messageNr); MessageNr loadMessage (); bool isScheduled (); private: uint32_t messageBits; bool scheduled; }; #endif /* MESSAGE_HPP_*/
1,326
C++
.h
47
26.446809
74
0.752747
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,496
Ports.hpp
sjaehn_BSchaffl/src/Ports.hpp
/* B.Schaffl * MIDI Pattern Delay Plugin * * Copyright (C) 2018 - 2020 by Sven Jähnichen * * 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, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef PORTS_HPP_ #define PORTS_HPP_ enum BSchafflPortIndex { INPUT = 0, OUTPUT = 1, CONTROLLERS = 2, SEQ_LEN_VALUE = 0, SEQ_LEN_BASE = 1, AMP_SWING = 2, AMP_RANDOM = 3, AMP_PROCESS = 4, SWING = 5, SWING_RANDOM = 6, SWING_PROCESS = 7, NR_OF_STEPS = 8, AMP_MODE = 9, MIDI_CH_FILTER = 10, MSG_FILTER_NOTE = 26, MSG_FILTER_KEYPR = 27, MSG_FILTER_CC = 28, MSG_FILTER_PROG = 29, MSG_FILTER_CHPR = 30, MSG_FILTER_PITCH = 31, MSG_FILTER_SYS = 32, NOTE_POSITION_STR = 33, NOTE_VALUE_STR = 34, NOTE_OVERLAP = 35, NOTE_OFF_AMP = 36, QUANT_RANGE = 37, QUANT_MAP = 38, QUANT_POS = 39, TIME_COMPENS = 40, USR_LATENCY = 41, USR_LATENCY_FR = 42, STEP_POS = 43, STEP_LEV = 58, LATENCY = 74, NR_CONTROLLERS = 75 }; enum BSchafflSeqLenBaseIndex { SECONDS = 0, BEATS = 1, BARS = 2 }; enum BSchafflNoteOverlaps { OVERLAP_DO_NOTHING = 0, OVERLAP_SPLIT = 1, OVERLAP_MERGE = 2 }; #endif /* PORTS_HPP_ */
1,769
C++
.h
72
22.666667
74
0.696629
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,497
SelectMenu.hpp
sjaehn_BSchaffl/src/SelectMenu.hpp
/* B.Schaffl * MIDI Pattern Delay Plugin * * Copyright (C) 2018 - 2020 by Sven Jähnichen * * 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, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef SELECTMENU_HPP_ #define SELECTMENU_HPP_ #include "BWidgets/Widget.hpp" #include <list> #include <utility> #include "UpDownButton.hpp" class SelectMenu : public BWidgets::Widget { public: SelectMenu () : SelectMenu (0, 0, 0, 0, "widget", std::list<std::pair<Widget*, Widget*>>{}) {} SelectMenu (const double x, const double y, const double width, const double height, const std::string& name, const std::list<std::pair<Widget*, Widget*>>& menuList) : Widget (x, y, width, height, name), menuList_ (), activeItem_ (nullptr) { for (std::pair<Widget*, Widget*> const& p : menuList) { if (p.first && p.second) { menuList_.push_back ( MenuItem { UpDownButton (0, 0, p.first->getHeight(), p.first->getHeight(), name), p.first, p.second } ); add (menuList_.back().button); add (*p.first); add (*p.second); menuList_.back().button.setCallbackFunction (BEvents::EventType::BUTTON_PRESS_EVENT, SelectMenu::buttonPressedCallback); menuList_.back().title->setCallbackFunction (BEvents::EventType::BUTTON_PRESS_EVENT, SelectMenu::buttonPressedCallback); } } activate (nullptr); } virtual void update () override { Widget::update(); activate (activeItem_); } virtual void applyTheme (BStyles::Theme& theme) override {applyTheme (theme, name_);} virtual void applyTheme (BStyles::Theme& theme, const std::string& name) override { Widget::applyTheme (theme, name); for (MenuItem& mi : menuList_) mi.button.applyTheme (theme, name); } protected: struct MenuItem { UpDownButton button; Widget* title; Widget* content; }; void activate (MenuItem* newActiveItem) { double y = 0.0; activeItem_ = newActiveItem; for (MenuItem& mi : menuList_) { if (mi.title && mi.content) { mi.button.moveTo (0, y); mi.button.setValue (1.0); mi.title->moveTo (1.25 * mi.title->getHeight(), y); y += mi.title->getHeight() + 10.0; if (newActiveItem == &mi) { mi.content->moveTo (0, y - 10.0); y += mi.content->getHeight(); mi.content->raiseToTop(); mi.content->show(); } else { mi.button.setValue (0.0); mi.content->hide(); } } } } static void buttonPressedCallback (BEvents::Event* event) { if (!event) return; BEvents::PointerEvent* pev = (BEvents::PointerEvent*) event; if (pev->getButton() != BDevices::LEFT_BUTTON) return; Widget* w = event->getWidget(); if (!w) return; SelectMenu* s = (SelectMenu*)w->getParent(); if (!s) return; for (MenuItem& mi : s->menuList_) { if (mi.title && mi.content && ((mi.title == w) || (&mi.button == w))) { if (s->activeItem_ != &mi) s->activate (&mi); else s->activate (nullptr); break; } } } std::list<MenuItem> menuList_; MenuItem* activeItem_; }; #endif /* SELECTMENU_HPP_ */
5,370
C++
.h
124
26.193548
152
0.454285
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,498
UpDownButton.hpp
sjaehn_BSchaffl/src/UpDownButton.hpp
/* B.Schaffl * MIDI Pattern Delay Plugin * * Copyright (C) 2018 - 2020 by Sven Jähnichen * * 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, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef UPDOWNBUTTON_HPP_ #define UPDOWNBUTTON_HPP_ #include "BWidgets/ToggleButton.hpp" class UpDownButton : public BWidgets::ToggleButton { public: UpDownButton () : UpDownButton (0.0, 0.0, BWIDGETS_DEFAULT_BUTTON_WIDTH, BWIDGETS_DEFAULT_BUTTON_HEIGHT, "button", 0.0) {} UpDownButton (const double x, const double y, const double width, const double height, const std::string& name, double defaultValue = 0) : ToggleButton (x, y, width, height, name, defaultValue) {} protected: virtual void draw (const BUtilities::RectArea& area) override { if ((!widgetSurface_) || (cairo_surface_status (widgetSurface_) != CAIRO_STATUS_SUCCESS)) return; if ((area.getWidth() >= 6) && (area.getHeight() >= 6)) { // Draw super class widget elements first Widget::draw (area); cairo_t* cr = cairo_create (widgetSurface_); if (cairo_status (cr) == CAIRO_STATUS_SUCCESS) { // Limit cairo-drawing area cairo_rectangle (cr, area.getX(), area.getY(), area.getWidth(), area.getHeight()); cairo_clip (cr); double x0 = getXOffset (); double y0 = getYOffset (); double w = getEffectiveWidth (); double h = getEffectiveHeight (); BColors::Color butColor = *bgColors.getColor (value == 1 ? BColors::ACTIVE : BColors::NORMAL); if (value) { cairo_move_to (cr, x0 + 0.2 * w, y0 + 0.65 * h); cairo_line_to (cr, x0 + 0.5 * w, y0 + 0.35 * h); cairo_line_to (cr, x0 + 0.8 * w, y0 + 0.65 * h); } else { cairo_move_to (cr, x0 + 0.2 * w, y0 + 0.35 * h); cairo_line_to (cr, x0 + 0.5 * w, y0 + 0.65 * h); cairo_line_to (cr, x0 + 0.8 * w, y0 + 0.35 * h); } cairo_set_line_width (cr, 2); cairo_set_source_rgba (cr, CAIRO_RGBA (butColor)); cairo_stroke (cr); cairo_destroy (cr); } } } }; #endif /* UPDOWNBUTTON_HPP_ */
2,626
C++
.h
68
35.176471
139
0.674391
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,499
SwingHSlider.hpp
sjaehn_BSchaffl/src/SwingHSlider.hpp
/* B.Schaffl * MIDI Pattern Delay Plugin * * Copyright (C) 2018 - 2020 by Sven Jähnichen * * 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 <https://www.gnu.org/licenses/>. */ #ifndef SWINGHSLIDER_HPP_ #define SWINGHSLIDER_HPP_ #include "BWidgets/HSliderValue.hpp" #include "BUtilities/to_string.hpp" #include "BUtilities/stof.hpp" class SwingHSlider : public BWidgets::HSliderValue { public: SwingHSlider (); SwingHSlider (const double x, const double y, const double width, const double height, const std::string& name, const double value, const double min, const double max, const double step, std::string format = "%1.2f", std::function<double (const double val, const double min, const double max)> valfunc = [] (const double val, const double min, const double max) {return (val >= 1.0 ? 0.5 + 0.5 * (val - 1.0) / (max - 1.0) : 0.5 - 0.5 * (1.0 / val - 1.0) / (1.0 / min - 1.0));}, std::function<double (const double frac, const double min, const double max)> fracfunc = [] (const double frac, const double min, const double max) { return ( frac >= 0.5 ? (2.0 * frac - 1.0) * (max - 1.0) + 1.0 : 1.0 / ((1.0 - 2.0 * frac) * (1.0 / min - 1.0) + 1.0) ); }) : HSliderValue ( x, y, width, height, name, value, min, max, step, format), valueToFraction_ (valfunc), fractionToValue_ (fracfunc) { valueDisplay.setCallbackFunction(BEvents::EventType::MESSAGE_EVENT, displayMessageCallback); } virtual Widget* clone () const override {return new SwingHSlider (*this);} virtual void setValue (const double val) override { { HSlider::setValue (val); std::string valstr = ( val < 1.0 ? "1 : " + BUtilities::to_string (1.0 / getValue(), valFormat) : ( val == 1.0 ? "1 : 1" : BUtilities::to_string (getValue(), valFormat) + " : 1" ) ); valueDisplay.setText (valstr); focusLabel.setText (valstr); } } virtual void onButtonPressed (BEvents::PointerEvent* event) override { if ( main_ && isVisible () && (getHeight () >= 1) && (getWidth () >= 1) && (scaleArea.getWidth () > 0) && (event->getButton() == BDevices::LEFT_BUTTON) ) { double min = getMin (); double max = getMax (); // Use pointer coords directly if hardSetable , otherwise apply only // X movement (drag mode) if (hardChangeable) { double frac = (event->getPosition ().x - scaleArea.getX ()) / scaleArea.getWidth (); if (getStep () < 0) frac = 1 - frac; double hardValue = fractionToValue_ (frac, getMin(), getMax()); softValue = 0; setValue (hardValue); } else { if (min != max) { double deltaFrac = event->getDelta ().x / scaleArea.getWidth (); if (getStep () < 0) deltaFrac = -deltaFrac; softValue += deltaFrac; double newValue = fractionToValue_ (valueToFraction_ (getValue(), getMin(), getMax()) + softValue, getMin(), getMax()); setValue (newValue); } } } } virtual void onWheelScrolled (BEvents::WheelEvent* event) override { double min = getMin (); double max = getMax (); if (min != max) { double step = (getStep () != 0.0 ? getStep () : 1.0 / scaleArea.getWidth ()); double frac = valueToFraction_ (getValue(), getMin(), getMax()) + event->getDelta ().y * step; double newValue = fractionToValue_ (frac, getMin(), getMax()); setValue (newValue); } } virtual void update () override { HSliderValue::update(); std::string valstr = ( value < 1.0 ? "1 : " + BUtilities::to_string (1/value, valFormat) : ( value == 1.0 ? "1 : 1" : BUtilities::to_string (value, valFormat) + " : 1" ) ); valueDisplay.setText (valstr); focusLabel.setText (valstr); } protected: std::function<double (const double val, const double min, const double max)> valueToFraction_; std::function<double (const double frac, const double min, const double max)> fractionToValue_; virtual void updateCoords () override { double w = getEffectiveWidth (); double h = getEffectiveHeight () / 2; knobRadius = (h < w / 2 ? h / 2 : w / 4); scaleArea = BUtilities::RectArea ( getXOffset () + knobRadius, getYOffset () + h + knobRadius / 2, w - 2 * knobRadius, knobRadius ); scaleXValue = scaleArea.getX() + valueToFraction_ (getValue(), getMin(), getMax()) * scaleArea.getWidth(); knobPosition = BUtilities::Point (scaleXValue, scaleArea.getY() + scaleArea.getHeight() / 2); double dh = knobRadius * 2; double dw = 3.6 * dh; double dy = getYOffset () + h - dh; double dx = LIMIT (scaleXValue - dw / 2, getXOffset (), getXOffset () + getEffectiveWidth () - dw); displayArea = BUtilities::RectArea (dx, dy, dw, dh); } static void displayMessageCallback (BEvents::Event* event) { if (event && event->getWidget()) { BWidgets::Label* l = (BWidgets::Label*)event->getWidget(); SwingHSlider* d = (SwingHSlider*)l->getParent(); if (d) { const std::string s = l->getText(); const size_t p = s.find (":"); if ((p == std::string::npos) || (p >= s.size() - 1)) { fprintf (stderr, "Invalid ratio format for %s\n", s.c_str()); d->update(); return; } double v1; try {v1 = BUtilities::stof (s);} catch (std::invalid_argument &ia) { fprintf (stderr, "%s\n", ia.what()); d->update(); return; } double v2; try {v2 = BUtilities::stof (s.substr (p + 2));} catch (std::invalid_argument &ia) { fprintf (stderr, "%s\n", ia.what()); d->update(); return; } if (v2 == 0) { fprintf (stderr, "Division by zero\n"); d->update(); return; } d->setValue (v1 / v2); d->update(); } } } }; #endif /* SWINGHSLIDER_HPP_ */
6,374
C++
.h
198
28.075758
161
0.632862
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,500
ShapeWidget.hpp
sjaehn_BSchaffl/src/ShapeWidget.hpp
/* B.Shapr * Beat / envelope shaper LV2 plugin * * Copyright (C) 2019 by Sven Jähnichen * * 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, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef SHAPEWIDGET_HPP_ #define SHAPEWIDGET_HPP_ #include "definitions.hpp" #include "StaticArrayList.hpp" #include "BWidgets/ValueWidget.hpp" #include "BWidgets/Focusable.hpp" #include "BWidgets/Text.hpp" #include "Shape.hpp" #include "Selection.hpp" #include "Snapshots.hpp" enum ToolType { NO_TOOL = 0, EDIT_TOOL = 1, POINT_NODE_TOOL = 2, AUTO_SMOOTH_NODE_TOOL = 3, SYMMETRIC_SMOOTH_NODE_TOOL = 4, CORNER_NODE_TOOL = 5, NR_TOOLS = 6, }; class ShapeWidget : public Shape<MAXNODES>, public BWidgets::ValueWidget, public BWidgets::Focusable { public: ShapeWidget (); ShapeWidget (const double x, const double y, const double width, const double height, const std::string& name); ShapeWidget (const ShapeWidget& that); virtual BWidgets::Widget* clone () const override; virtual void update () override; void setTool (const ToolType tool); void setValueEnabled (const bool status); void setScaleParameters (double anchorYPos, double anchorValue, double ratio); void setMinorXSteps (double stepSize); void setMajorXSteps (double stepSize); void setPrefix (std::string text); void setUnit (std::string text); void setLowerLimit (double value, bool hard = false); void setHigherLimit (double value, bool hard = false); void showGrid (); void hideGrid (); void setSnap (const bool status); std::vector<Node> cutSelection (); std::vector<Node> copySelection (); void pasteSelection (const std::vector<Node>& newNodes); void deleteSelection (); void unselect (); void reset (); void undo (); void redo (); void pushToSnapshots (); void resetSnapshots (); virtual void setDefaultShape () override; virtual void onButtonPressed (BEvents::PointerEvent* event) override; virtual void onButtonReleased (BEvents::PointerEvent* event) override; virtual void onPointerDragged (BEvents::PointerEvent* event) override; virtual void onWheelScrolled (BEvents::WheelEvent* event) override; virtual void onValueChanged (BEvents::ValueChangedEvent* event) override; virtual void onFocusIn (BEvents::FocusEvent* event) override; virtual void onFocusOut (BEvents::FocusEvent* event) override; virtual void applyTheme (BStyles::Theme& theme) override; virtual void applyTheme (BStyles::Theme& theme, const std::string& name) override; protected: enum ClickMode { NEW_NODE = 0, DRAG_NODE = 1, DRAG_HANDLE = 2, DRAG_SELECTION = 3, DRAG_SCREEN = 4 }; ClickMode clickMode; Selection selection; ToolType tool; int grabbedNode; int grabbedHandle; bool valueEnabled; double scaleAnchorYPos; double scaleAnchorValue; double scaleRatio; double minorXSteps; double majorXSteps; double loLimit, hiLimit; bool hardLoLimit, hardHiLimit; // TODO, not in use yet bool gridVisible; bool gridSnap; std::string prefix; std::string unit; BColors::ColorSet fgColors; BColors::ColorSet syColors; BColors::ColorSet bgColors; BStyles::Font lbfont; BWidgets::Text focusText; double snapX (const double x); double snapY (const double y); Snapshots<Shape<MAXNODES>, MAXUNDO> undoSnapshots; virtual void drawLineOnMap (BUtilities::Point p1, BUtilities::Point p2) override; virtual void draw (const BUtilities::RectArea& area) override; }; #endif /* SHAPEWIDGET_HPP_ */
4,021
C++
.h
117
32.401709
112
0.771641
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,501
Marker.hpp
sjaehn_BSchaffl/src/Marker.hpp
/* B.Schaffl * MIDI Pattern Delay Plugin * * Copyright (C) 2018 - 2020 by Sven Jähnichen * * 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, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef MARKER_HPP_ #define MARKER_HPP_ #include "BWidgets/RangeWidget.hpp" #include "BWidgets/Focusable.hpp" #include "BWidgets/Label.hpp" #include "BUtilities/to_string.hpp" class Marker : public BWidgets::RangeWidget, public BWidgets::Focusable { protected: BColors::ColorSet bgColors; bool noValue; BWidgets::Label focusLabel; public: Marker () : Marker (0.0, 0.0, BWIDGETS_DEFAULT_WIDTH, BWIDGETS_DEFAULT_HEIGHT, "marker", BWIDGETS_DEFAULT_VALUE, BWIDGETS_DEFAULT_RANGE_MIN, BWIDGETS_DEFAULT_RANGE_MAX, BWIDGETS_DEFAULT_RANGE_STEP) {} Marker (const double x, const double y, const double width, const double height, const std::string& name, const double value, const double min, const double max, const double step) : RangeWidget (x, y, width, height, name, value, min, max, step), Focusable (std::chrono::milliseconds (BWIDGETS_DEFAULT_FOCUS_IN_MS), std::chrono::milliseconds (BWIDGETS_DEFAULT_FOCUS_OUT_MS)), bgColors (BWIDGETS_DEFAULT_BGCOLORS), noValue (false), focusLabel (0 ,0, 40, 20, name_ + BWIDGETS_DEFAULT_FOCUS_NAME, "") { std::string valstr = BUtilities::to_string (getValue()); focusLabel.setText (valstr); focusLabel.setStacking (BWidgets::STACKING_OVERSIZE); focusLabel.resize (); focusLabel.hide (); add (focusLabel); } Marker (const Marker& that) : RangeWidget (that), Focusable (that), bgColors (that.bgColors), noValue (that.noValue), focusLabel (that.focusLabel) { focusLabel.hide(); add (focusLabel); } Marker& operator= (const Marker& that) { release (&focusLabel); bgColors = that.bgColors; focusLabel = that.focusLabel; focusLabel.hide(); RangeWidget::operator= (that); Focusable::operator= (that); add (focusLabel); return *this; } virtual Widget* clone () const override {return new Marker (*this);} virtual void setValue (const double val) override { RangeWidget::setValue (val); std::string valstr = (noValue ? "Auto" : BUtilities::to_string (value)); focusLabel.setText(valstr); focusLabel.resize (); } void setHasValue (const bool hasValue) { noValue = !hasValue; std::string valstr = (noValue ? "Auto" : BUtilities::to_string (value)); focusLabel.setText(valstr); update (); } bool hasValue () const {return !noValue;} virtual void update () override { RangeWidget::update (); focusLabel.resize (); } virtual void onFocusIn (BEvents::FocusEvent* event) override { if (event && event->getWidget()) { BUtilities::Point pos = event->getPosition(); focusLabel.moveTo (pos.x - 0.5 * focusLabel.getWidth(), pos.y - focusLabel.getHeight()); focusLabel.show(); } Widget::onFocusIn (event); } virtual void onFocusOut (BEvents::FocusEvent* event) override { if (event && event->getWidget()) focusLabel.hide(); Widget::onFocusOut (event); } virtual void applyTheme (BStyles::Theme& theme) override {applyTheme (theme, name_);} virtual void applyTheme (BStyles::Theme& theme, const std::string& name) override { Widget::applyTheme (theme, name); focusLabel.applyTheme (theme, name + BWIDGETS_DEFAULT_FOCUS_NAME); void* bgPtr = theme.getStyle(name, BWIDGETS_KEYWORD_BGCOLORS); if (bgPtr) { bgColors = *((BColors::ColorSet*) bgPtr); update (); } } virtual void draw (const BUtilities::RectArea& area) override { if ((!widgetSurface_) || (cairo_surface_status (widgetSurface_) != CAIRO_STATUS_SUCCESS)) return; // Draw super class widget elements first Widget::draw (area); double heff = getEffectiveHeight (); double weff = getEffectiveWidth (); // Draw knob // only if minimum requirements satisfied if ((getHeight () >= 1) && (getWidth () >= 1)) { cairo_surface_clear (widgetSurface_); cairo_t* cr = cairo_create (widgetSurface_); if (cairo_status (cr) == CAIRO_STATUS_SUCCESS) { // Limit cairo-drawing area cairo_rectangle (cr, area.getX (), area.getY (), area.getWidth (), area.getHeight ()); cairo_clip (cr); // Colors uses within this method BColors::Color cLo = *bgColors.getColor (getState ()); cLo.applyBrightness (noValue ? BWIDGETS_DEFAULT_NORMALLIGHTED : 2 * BWIDGETS_DEFAULT_ILLUMINATED); BColors::Color cMid = *bgColors.getColor (getState ()); cMid.applyBrightness ((BWIDGETS_DEFAULT_ILLUMINATED + BWIDGETS_DEFAULT_NORMALLIGHTED) / 2); BColors::Color cHi = *bgColors.getColor (getState ()); cHi.applyBrightness (BWIDGETS_DEFAULT_ILLUMINATED); cairo_set_line_width (cr, 0.0); cairo_set_source_rgba (cr, CAIRO_RGBA (cMid)); cairo_move_to (cr, 0.5 * weff, 0); cairo_line_to (cr, 0, 0.25 * heff); cairo_line_to (cr, 0, heff); cairo_line_to (cr, weff, heff); cairo_line_to (cr, weff, 0.25 * heff); cairo_close_path (cr); cairo_fill (cr); cairo_set_line_width (cr, 1.0); cairo_set_source_rgba (cr, CAIRO_RGBA (cLo)); cairo_move_to (cr, 0.25 * weff, 0.5 * heff); cairo_line_to (cr, 0.75 * weff, 0.5 * heff); cairo_move_to (cr, 0.25 * weff, 0.6 * heff); cairo_line_to (cr, 0.75 * weff, 0.6 * heff); cairo_move_to (cr, 0.25 * weff, 0.7 * heff); cairo_line_to (cr, 0.75 * weff, 0.7 * heff); cairo_stroke (cr); cairo_set_line_width (cr, 2.0); cairo_set_source_rgba (cr, CAIRO_RGBA (cHi)); cairo_move_to (cr, 0, heff); cairo_line_to (cr, weff, heff); cairo_line_to (cr, weff, 0.25 * heff); cairo_stroke (cr); } cairo_destroy (cr); } } }; #endif /* MARKER_HPP_ */
7,900
C++
.h
171
33.321637
130
0.55013
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,502
HaloButton.hpp
sjaehn_BSchaffl/src/HaloButton.hpp
/* B.Harvestr * LV2 Plugin * * Copyright (C) 2018 - 2020 by Sven Jähnichen * * 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, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef HALOBUTTON_HPP_ #define HALOBUTTON_HPP_ #include "BWidgets/ValueWidget.hpp" #include "BWidgets/Focusable.hpp" #include "BWidgets/Label.hpp" class HaloButton : public BWidgets::ValueWidget, public BWidgets::Focusable { public: HaloButton () : HaloButton (0, 0, 0, 0, "halobutton", "") {} HaloButton (const double x, const double y, const double width, const double height, const std::string& name, const std::string& focusText) : ValueWidget (x, y, width, height, name, 0.0), Focusable (std::chrono::milliseconds (BWIDGETS_DEFAULT_FOCUS_IN_MS), std::chrono::milliseconds (BWIDGETS_DEFAULT_FOCUS_OUT_MS)), focusLabel_ (0, 0, 40, 20, name_ + BWIDGETS_DEFAULT_FOCUS_NAME, focusText) { focusLabel_.setStacking (BWidgets::STACKING_OVERSIZE); focusLabel_.resize (); focusLabel_.hide (); add (focusLabel_); } HaloButton (const HaloButton& that) : ValueWidget (that), Focusable (that), focusLabel_ (that.focusLabel_) { focusLabel_.hide(); add (focusLabel_); } HaloButton& operator= (const HaloButton& that) { release (&focusLabel_); focusLabel_ = that.focusLabel_; focusLabel_.hide(); Widget::operator= (that); Focusable::operator= (that); add (focusLabel_); return *this; } virtual BWidgets::Widget* clone () const override {return new HaloButton (*this);} virtual void applyTheme (BStyles::Theme& theme) override {applyTheme (theme, name_);} virtual void applyTheme (BStyles::Theme& theme, const std::string& name) override { Widget::applyTheme (theme, name); focusLabel_.applyTheme (theme, name + BWIDGETS_DEFAULT_FOCUS_NAME); focusLabel_.resize(); } virtual void onButtonPressed (BEvents::PointerEvent* event) override { setValue (1.0); Widget::cbfunction_[BEvents::EventType::BUTTON_PRESS_EVENT] (event); } virtual void onButtonReleased (BEvents::PointerEvent* event) override { setValue (0.0); Widget::cbfunction_[BEvents::EventType::BUTTON_RELEASE_EVENT] (event); } virtual void onFocusIn (BEvents::FocusEvent* event) override { if (event && event->getWidget()) { BUtilities::Point pos = event->getPosition(); focusLabel_.moveTo (pos.x - 0.5 * focusLabel_.getWidth(), pos.y - focusLabel_.getHeight()); focusLabel_.show(); } Widget::onFocusIn (event); } virtual void onFocusOut (BEvents::FocusEvent* event) override { if (event && event->getWidget()) focusLabel_.hide(); Widget::onFocusOut (event); } protected: BWidgets::Label focusLabel_; virtual void draw (const BUtilities::RectArea& area) override { if ((!widgetSurface_) || (cairo_surface_status (widgetSurface_) != CAIRO_STATUS_SUCCESS)) return; if ((getWidth () >= 1) && (getHeight () >= 1)) { // Draw super class widget elements first Widget::draw (area); if (value == 1.0) { cairo_t* cr = cairo_create (widgetSurface_); if (cairo_status (cr) == CAIRO_STATUS_SUCCESS) { // Limit cairo-drawing area cairo_rectangle (cr, area.getX (), area.getY (), area.getWidth (), area.getHeight ()); cairo_clip (cr); double x0 = getXOffset (); double y0 = getYOffset (); double w = getEffectiveWidth (); double h = getEffectiveHeight (); cairo_rectangle (cr, x0, y0, w, h); cairo_set_line_width (cr, 1.0); cairo_set_source_rgba (cr, CAIRO_RGBA (BColors::white)); cairo_stroke (cr); cairo_destroy (cr); } } } } }; #endif /* HALOBUTTON_HPP_ */
4,228
C++
.h
121
31.710744
142
0.703722
sjaehn/BSchaffl
35
2
5
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,503
benchmark.cpp
CoffeeBeforeArch_mmul/src/baseline/benchmark.cpp
// Main benchmark function of MMul // By: Nick from CoffeeBeforeArch #include "benchmark/benchmark.h" #include <algorithm> #include <cstdlib> #include <random> #include <thread> #include <vector> // Serial implementation void serial_mmul(const float *A, const float *B, float *C, std::size_t N) { // For each row... for (std::size_t row = 0; row < N; row++) // For each col... for (std::size_t col = 0; col < N; col++) // For each element in the row/col pair... for (std::size_t idx = 0; idx < N; idx++) // Accumulate the partial results C[row * N + col] += A[row * N + idx] * B[idx * N + col]; } // Parallel implementation void parallel_mmul(const float *A, const float *B, float *C, std::size_t N, std::size_t start_row, std::size_t end_row) { // For each row assigned to this thread... for (std::size_t row = start_row; row < end_row; row++) // For each column... for (std::size_t col = 0; col < N; col++) // For each element in the row-col pair... for (std::size_t idx = 0; idx < N; idx++) // Accumulate the partial results C[row * N + col] += A[row * N + idx] * B[idx * N + col]; } // Serial MMul benchmark static void serial_mmul_bench(benchmark::State &s) { // Number Dimensions of our matrix std::size_t N = s.range(0); // Create our random number generators std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_real_distribution<float> dist(-10, 10); // Create input matrices float *A = new float[N * N]; float *B = new float[N * N]; float *C = new float[N * N]; // Initialize them with random values (and C to 0) std::generate(A, A + N * N, [&] { return dist(rng); }); std::generate(B, B + N * N, [&] { return dist(rng); }); std::generate(C, C + N * N, [&] { return 0.0f; }); // Main benchmark loop for (auto _ : s) { serial_mmul(A, B, C, N); } // Free memory delete[] A; delete[] B; delete[] C; } BENCHMARK(serial_mmul_bench) ->Arg(384) ->Arg(768) ->Arg(1152) ->Unit(benchmark::kMillisecond); // Parallel MMul benchmark static void parallel_mmul_bench(benchmark::State &s) { // Number Dimensions of our matrix std::size_t N = s.range(0); // Create our random number generators std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_real_distribution<float> dist(-10, 10); // Create input matrices float *A = new float[N * N]; float *B = new float[N * N]; float *C = new float[N * N]; // Initialize them with random values (and C to 0) std::generate(A, A + N * N, [&] { return dist(rng); }); std::generate(B, B + N * N, [&] { return dist(rng); }); std::generate(C, C + N * N, [&] { return 0.0f; }); // Set up for launching threads std::size_t num_threads = std::thread::hardware_concurrency(); std::vector<std::thread> threads; threads.reserve(num_threads); // Calculate values to pass to threads // Assumed to be divisable by num_threads (evenly) std::size_t n_rows = N / num_threads; // Main benchmark loop for (auto _ : s) { // Launch threads std::size_t end_row = 0; for (std::size_t i = 0; i < num_threads - 1; i++) { auto start_row = i * n_rows; end_row = start_row + n_rows; threads.emplace_back( [&] { parallel_mmul(A, B, C, N, start_row, end_row); }); } // Wait for all threads to complete for (auto &t : threads) t.join(); // Clear the threads each iteration of the benchmark threads.clear(); } // Free memory free(A); free(B); free(C); } BENCHMARK(parallel_mmul_bench) ->Arg(384) ->Arg(768) ->Arg(1152) ->Unit(benchmark::kMillisecond) ->UseRealTime(); BENCHMARK_MAIN();
3,731
C++
.cpp
111
29.747748
75
0.614059
CoffeeBeforeArch/mmul
34
6
2
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,504
benchmark.cpp
CoffeeBeforeArch_mmul/src/blocked_column/benchmark.cpp
// Main benchmark function of MMul #include "benchmark/benchmark.h" #include <algorithm> #include <atomic> #include <cstdlib> #include <random> #include <thread> #include <vector> // Blocked column serial implementation void blocked_column_mmul(const float *A, const float *B, float *C, std::size_t N) { // For each chunk of columns for (std::size_t col_chunk = 0; col_chunk < N; col_chunk += 16) // For each row in that chunk of columns... for (std::size_t row = 0; row < N; row++) // For each block of elements in this row of this column chunk // Solve for 16 elements at a time for (std::size_t tile = 0; tile < N; tile += 16) // For each row in the tile for (std::size_t tile_row = 0; tile_row < 16; tile_row++) // Solve for each element in this tile row for (std::size_t idx = 0; idx < 16; idx++) C[row * N + col_chunk + idx] += A[row * N + tile + tile_row] * B[tile * N + tile_row * N + col_chunk + idx]; } // Blocked serial implementation void blocked_column_parallel_mmul(const float *A, const float *B, float *C, std::size_t N, std::size_t start_col, std::size_t end_col) { for (auto col_chunk = start_col; col_chunk < end_col; col_chunk += 16) // For each row in that chunk of columns... for (std::size_t row = 0; row < N; row++) // For each block of elements in this row of this column chunk // Solve for 16 elements at a time for (std::size_t tile = 0; tile < N; tile += 16) // For each row in the tile for (std::size_t tile_row = 0; tile_row < 16; tile_row++) // Solve for each element in this tile row for (std::size_t idx = 0; idx < 16; idx++) C[row * N + col_chunk + idx] += A[row * N + tile + tile_row] * B[tile * N + tile_row * N + col_chunk + idx]; } // Blocked column MMul with aligned memory benchmark static void blocked_column_aligned_mmul_bench(benchmark::State &s) { // Number Dimensions of our matrix std::size_t N = s.range(0); // Create our random number generators std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_real_distribution<float> dist(-10, 10); // Create input matrices float *A = static_cast<float *>(aligned_alloc(64, N * N * sizeof(float))); float *B = static_cast<float *>(aligned_alloc(64, N * N * sizeof(float))); float *C = static_cast<float *>(aligned_alloc(64, N * N * sizeof(float))); // Initialize them with random values (and C to 0) std::generate(A, A + N * N, [&] { return dist(rng); }); std::generate(B, B + N * N, [&] { return dist(rng); }); std::generate(C, C + N * N, [&] { return 0.0f; }); // Main benchmark loop for (auto _ : s) { blocked_column_mmul(A, B, C, N); } // Free memory free(A); free(B); free(C); } BENCHMARK(blocked_column_aligned_mmul_bench) ->Arg(384) ->Arg(768) ->Arg(1152) ->Unit(benchmark::kMillisecond); // Parallel MMul benchmark static void parallel_blocked_column_mmul_bench(benchmark::State &s) { // Number Dimensions of our matrix std::size_t N = s.range(0); // Create our random number generators std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_real_distribution<float> dist(-10, 10); // Create input matrices float *A = static_cast<float *>(aligned_alloc(64, N * N * sizeof(float))); float *B = static_cast<float *>(aligned_alloc(64, N * N * sizeof(float))); float *C = static_cast<float *>(aligned_alloc(64, N * N * sizeof(float))); // Initialize them with random values (and C to 0) std::generate(A, A + N * N, [&] { return dist(rng); }); std::generate(B, B + N * N, [&] { return dist(rng); }); std::generate(C, C + N * N, [&] { return 0.0f; }); // Set up for launching threads std::size_t num_threads = std::thread::hardware_concurrency(); std::vector<std::thread> threads; threads.reserve(num_threads); // Calculate values to pass to threads // Assumed to be divisable by num_threads (evenly) std::size_t n_cols = N / num_threads; // Main benchmark loop for (auto _ : s) { // Launch threads std::size_t start_col = 0; for (std::size_t i = 0; i < num_threads; i++) { auto end_col = start_col + n_cols; threads.emplace_back([&] { blocked_column_parallel_mmul(A, B, C, N, start_col, end_col); }); start_col += n_cols; } // Wait for all threads to complete for (auto &t : threads) t.join(); // Clear the threads each iteration of the benchmark threads.clear(); } // Free memory free(A); free(B); free(C); } BENCHMARK(parallel_blocked_column_mmul_bench) ->Arg(384) ->Arg(768) ->Arg(1152) ->Unit(benchmark::kMillisecond) ->UseRealTime(); BENCHMARK_MAIN();
4,904
C++
.cpp
125
33.96
76
0.608449
CoffeeBeforeArch/mmul
34
6
2
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,505
benchmark.cpp
CoffeeBeforeArch_mmul/src/blocked_column_multi_output/benchmark.cpp
// Main benchmark function of MMul #include "benchmark/benchmark.h" #include <algorithm> #include <cstdlib> #include <random> #include <thread> #include <vector> // Blocked column multi-output serial implementation void blocked_column_multi_output_mmul(const float *A, const float *B, float *C, std::size_t N) { // For each chunk of columns for (std::size_t col_chunk = 0; col_chunk < N; col_chunk += 16) // For each chunk of rows for (std::size_t row_chunk = 0; row_chunk < N; row_chunk += 16) // For each block of elements in this row of this column chunk // Solve for 16 elements at a time for (std::size_t tile = 0; tile < N; tile += 16) // Apply that tile to each row of the row chunk for (std::size_t row = 0; row < 16; row++) // For each row in the tile for (std::size_t tile_row = 0; tile_row < 16; tile_row++) // Solve for each element in this tile row for (std::size_t idx = 0; idx < 16; idx++) C[(row + row_chunk) * N + col_chunk + idx] += A[(row + row_chunk) * N + tile + tile_row] * B[tile * N + tile_row * N + col_chunk + idx]; } // Blocked column parallel implementation w/o atomic void blocked_column_multi_output_parallel_mmul(const float *A, const float *B, float *C, std::size_t N, std::size_t start_col, std::size_t end_col) { // For each chunk of columns for (std::size_t col_chunk = start_col; col_chunk < end_col; col_chunk += 16) // For each chunk of rows for (std::size_t row_chunk = 0; row_chunk < N; row_chunk += 16) // For each block of elements in this row of this column chunk // Solve for 16 elements at a time for (std::size_t tile = 0; tile < N; tile += 16) // For apply that tile to each row of the row chunk for (std::size_t row = 0; row < 16; row++) // For each row in the tile for (std::size_t tile_row = 0; tile_row < 16; tile_row++) // Solve for each element in this tile row for (std::size_t idx = 0; idx < 16; idx++) C[(row + row_chunk) * N + col_chunk + idx] += A[(row + row_chunk) * N + tile + tile_row] * B[tile * N + tile_row * N + col_chunk + idx]; } // Blocked column multi-output MMul with aligned memory benchmark static void blocked_column_multi_output_aligned_mmul_bench( benchmark::State &s) { // Dimensions of our matrix std::size_t N = s.range(0); // Create our random number generators std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_real_distribution<float> dist(-10, 10); // Create input matrices float *A = static_cast<float *>(aligned_alloc(64, N * N * sizeof(float))); float *B = static_cast<float *>(aligned_alloc(64, N * N * sizeof(float))); float *C = static_cast<float *>(aligned_alloc(64, N * N * sizeof(float))); // Initialize them with random values (and C to 0) std::generate(A, A + N * N, [&] { return dist(rng); }); std::generate(B, B + N * N, [&] { return dist(rng); }); std::generate(C, C + N * N, [&] { return 0.0f; }); // Main benchmark loop for (auto _ : s) { blocked_column_multi_output_mmul(A, B, C, N); } // Free memory free(A); free(B); free(C); } BENCHMARK(blocked_column_multi_output_aligned_mmul_bench) ->Arg(384) ->Arg(768) ->Arg(1152) ->Unit(benchmark::kMillisecond); // Parallel blocked column multi-output MMul benchmark static void parallel_blocked_column_multi_output_mmul_bench( benchmark::State &s) { // Dimensions of our matrix std::size_t N = s.range(0); // Create our random number generators std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_real_distribution<float> dist(-10, 10); // Create input matrices float *A = static_cast<float *>(aligned_alloc(64, N * N * sizeof(float))); float *B = static_cast<float *>(aligned_alloc(64, N * N * sizeof(float))); float *C = static_cast<float *>(aligned_alloc(64, N * N * sizeof(float))); // Initialize them with random values (and C to 0) std::generate(A, A + N * N, [&] { return dist(rng); }); std::generate(B, B + N * N, [&] { return dist(rng); }); std::generate(C, C + N * N, [&] { return 0.0f; }); // Set up for launching threads std::size_t num_threads = std::thread::hardware_concurrency(); std::vector<std::thread> threads; threads.reserve(num_threads); // Calculate values to pass to threads // Assumed to be divisable by num_threads (evenly) std::size_t n_cols = N / num_threads; // Main benchmark loop for (auto _ : s) { // Launch threads std::size_t start_col = 0; for (std::size_t i = 0; i < num_threads; i++) { auto end_col = start_col + n_cols; threads.emplace_back([&] { blocked_column_multi_output_parallel_mmul(A, B, C, N, start_col, end_col); }); start_col += n_cols; } // Wait for all threads to complete for (auto &t : threads) t.join(); // Clear the threads each iteration of the benchmark threads.clear(); } // Free memory free(A); free(B); free(C); } BENCHMARK(parallel_blocked_column_multi_output_mmul_bench) ->Arg(384) ->Arg(768) ->Arg(1152) ->Unit(benchmark::kMillisecond) ->UseRealTime(); BENCHMARK_MAIN();
5,544
C++
.cpp
133
35.120301
79
0.594805
CoffeeBeforeArch/mmul
34
6
2
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,506
benchmark.cpp
CoffeeBeforeArch_mmul/src/blocked/benchmark.cpp
// Main benchmark function of MMul #include "benchmark/benchmark.h" #include <algorithm> #include <cstdlib> #include <random> #include <thread> #include <vector> // Blocked serial implementation void blocked_mmul(const float *A, const float *B, float *C, std::size_t N) { // For each row... for (std::size_t row = 0; row < N; row++) // For each block in the row... // Solve for 16 elements at a time for (std::size_t block = 0; block < N; block += 16) // For each chunk of A/B for this block for (std::size_t chunk = 0; chunk < N; chunk += 16) // For each row in the chunk for (std::size_t sub_chunk = 0; sub_chunk < 16; sub_chunk++) // Go through all the elements in the sub chunk for (std::size_t idx = 0; idx < 16; idx++) C[row * N + block + idx] += A[row * N + chunk + sub_chunk] * B[chunk * N + sub_chunk * N + block + idx]; } // Blocked parallel implementation void blocked_parallel_mmul(const float *A, const float *B, float *C, std::size_t N, std::size_t start_row, std::size_t end_row) { // For each row... for (std::size_t row = start_row; row < end_row; row++) // For each block in the row... // Solve for 16 elements at a time for (std::size_t block = 0; block < N; block += 16) // For each chunk of A/B for this block for (std::size_t chunk = 0; chunk < N; chunk += 16) // For each row in the chunk for (std::size_t sub_chunk = 0; sub_chunk < 16; sub_chunk++) // Go through all the elements in the sub chunk for (std::size_t idx = 0; idx < 16; idx++) C[row * N + block + idx] += A[row * N + chunk + sub_chunk] * B[chunk * N + sub_chunk * N + block + idx]; } // Blocked MMul benchmark static void blocked_mmul_bench(benchmark::State &s) { // Dimensions of our matrix std::size_t N = s.range(0); // Create our random number generators std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_real_distribution<float> dist(-10, 10); // Create input matrices float *A = new float[N * N]; float *B = new float[N * N]; float *C = new float[N * N]; // Initialize them with random values (and C to 0) std::generate(A, A + N * N, [&] { return dist(rng); }); std::generate(B, B + N * N, [&] { return dist(rng); }); std::generate(C, C + N * N, [&] { return 0.0f; }); // Main benchmark loop for (auto _ : s) { blocked_mmul(A, B, C, N); } // Free memory delete[] A; delete[] B; delete[] C; } BENCHMARK(blocked_mmul_bench) ->Arg(384) ->Arg(768) ->Arg(1152) ->Unit(benchmark::kMillisecond); // Blocked MMul with aligned memory benchmark static void blocked_aligned_mmul_bench(benchmark::State &s) { // Dimensions of our matrix std::size_t N = s.range(0); // Create our random number generators std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_real_distribution<float> dist(-10, 10); // Create input matrices float *A = static_cast<float *>(aligned_alloc(64, N * N * sizeof(float))); float *B = static_cast<float *>(aligned_alloc(64, N * N * sizeof(float))); float *C = static_cast<float *>(aligned_alloc(64, N * N * sizeof(float))); // Initialize them with random values (and C to 0) std::generate(A, A + N * N, [&] { return dist(rng); }); std::generate(B, B + N * N, [&] { return dist(rng); }); std::generate(C, C + N * N, [&] { return 0.0f; }); // Main benchmark loop for (auto _ : s) { blocked_mmul(A, B, C, N); } // Free memory free(A); free(B); free(C); } BENCHMARK(blocked_aligned_mmul_bench) ->Arg(384) ->Arg(768) ->Arg(1152) ->Unit(benchmark::kMillisecond); // Parallel blocked MMul benchmark static void parallel_blocked_mmul_bench(benchmark::State &s) { // Dimensions of our matrix std::size_t N = s.range(0); // Create our random number generators std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_real_distribution<float> dist(-10, 10); // Create input matrices float *A = static_cast<float *>(aligned_alloc(64, N * N * sizeof(float))); float *B = static_cast<float *>(aligned_alloc(64, N * N * sizeof(float))); float *C = static_cast<float *>(aligned_alloc(64, N * N * sizeof(float))); // Initialize them with random values (and C to 0) std::generate(A, A + N * N, [&] { return dist(rng); }); std::generate(B, B + N * N, [&] { return dist(rng); }); std::generate(C, C + N * N, [&] { return 0.0f; }); // Set up for launching threads std::size_t num_threads = std::thread::hardware_concurrency(); std::vector<std::thread> threads; threads.reserve(num_threads); // Calculate values to pass to threads // Assumed to be divisable by num_threads (evenly) std::size_t n_rows = N / num_threads; // Main benchmark loop for (auto _ : s) { // Launch threads std::size_t end_row = 0; for (std::size_t i = 0; i < num_threads; i++) { auto start_row = i * n_rows; end_row = start_row + n_rows; threads.emplace_back( [&] { blocked_parallel_mmul(A, B, C, N, start_row, end_row); }); } // Wait for all threads to complete for (auto &t : threads) t.join(); // Clear the threads each iteration of the benchmark threads.clear(); } // Free memory free(A); free(B); free(C); } BENCHMARK(parallel_blocked_mmul_bench) ->Arg(384) ->Arg(768) ->Arg(1152) ->Unit(benchmark::kMillisecond) ->UseRealTime(); BENCHMARK_MAIN();
5,601
C++
.cpp
153
31.96732
76
0.60653
CoffeeBeforeArch/mmul
34
6
2
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,507
mkl_sgemm.cpp
CoffeeBeforeArch_mmul/src/mkl/mkl_sgemm.cpp
// A DMMul reference implementation using MKL #include <algorithm> #include <random> #include "benchmark/benchmark.h" #include "mkl/mkl.h" // Blocked MMul benchmark static void blocked_mmul_bench(benchmark::State &s) { // Number Dimensions of our matrix std::size_t N = s.range(0); // Create our random number generators std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_real_distribution<float> dist(-10, 10); // Create input matrices float *A = (float *)mkl_malloc(N * N * sizeof(float), 64); float *B = (float *)mkl_malloc(N * N * sizeof(float), 64); float *C = (float *)mkl_malloc(N * N * sizeof(float), 64); // MMul scaling constants float alpha = 1.0; float beta = 0.0; // Initialize them with random values (and C to 0) std::generate(A, A + N * N, [&] { return dist(rng); }); std::generate(B, B + N * N, [&] { return dist(rng); }); std::generate(C, C + N * N, [&] { return 0; }); // Main benchmark loop for (auto _ : s) { cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, N, N, N, alpha, A, N, B, N, beta, C, N); } // Free memory mkl_free(A); mkl_free(B); mkl_free(C); } BENCHMARK(blocked_mmul_bench) ->Arg(384) ->Arg(768) ->Arg(1152) ->Unit(benchmark::kMillisecond); BENCHMARK_MAIN();
1,307
C++
.cpp
40
29.325
80
0.638823
CoffeeBeforeArch/mmul
34
6
2
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,520
entry.cpp
decimaldreamer_x64-vm/entry.cpp
// STD #include <iostream> // VM #include "vm_test.hpp" int main() { global::console.log("Testing x86-64 virtual machine"); constexpr std::uint8_t buffer[] = { 0x49, 0x81, 0x81, 0x20, 0x04, 0x00, 0x00, 0x37, 0x13, 0x00, 0x00, // ADD [R9+0x420], 1337 0x66, 0x48, 0x81, 0xC3, 0x00, 0x00, 0x05, 0x00, // ADD RBX, 50000 }; auto test_engine = vm_tester(buffer); test_engine.prepare_test(); test_engine.run(); return 0; }
954
C++
.cpp
16
25.3125
92
0.645833
decimaldreamer/x64-vm
31
8
0
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,549
adb.cpp
MCJack123_ArduinoADB/adb_to_usb/adb.cpp
/* Copyright 2011-19 Jun WAKO <wakojun@gmail.com> Copyright 2013 Shay Green <gblargg@gmail.com> This software is licensed with a Modified BSD License. All of this is supposed to be Free Software, Open Source, DFSG-free, GPL-compatible, and OK to use in both free and proprietary applications. Additions and corrections to this file are welcome. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holders nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdbool.h> #include <util/delay.h> #include <avr/io.h> #include <avr/interrupt.h> #include "adb.h" //#include "print.h" // GCC doesn't inline functions normally #define data_lo() (ADB_DDR |= (1<<ADB_DATA_BIT)) #define data_hi() (ADB_DDR &= ~(1<<ADB_DATA_BIT)) #define data_in() (ADB_PIN & (1<<ADB_DATA_BIT)) #ifdef ADB_PSW_BIT static inline void psw_lo(void); static inline void psw_hi(void); static inline bool psw_in(void); #endif static inline void attention(void); static inline void place_bit0(void); static inline void place_bit1(void); static inline void send_byte(uint8_t data); static inline uint16_t wait_data_lo(uint16_t us); static inline uint16_t wait_data_hi(uint16_t us); void adb_host_init(void) { ADB_PORT &= ~(1<<ADB_DATA_BIT); data_hi(); #ifdef ADB_PSW_BIT psw_hi(); #endif } #ifdef ADB_PSW_BIT bool adb_host_psw(void) { return psw_in(); } #endif /* * Don't call this in a row without the delay, otherwise it makes some of poor controllers * overloaded and misses strokes. Recommended interval is 12ms. * * Thanks a lot, blargg! * <http://geekhack.org/index.php?topic=14290.msg1068919#msg1068919> * <http://geekhack.org/index.php?topic=14290.msg1070139#msg1070139> */ uint16_t adb_host_kbd_recv(uint8_t addr) { return adb_host_talk(addr, ADB_REG_0); } #ifdef ADB_MOUSE_ENABLE __attribute__ ((weak)) void adb_mouse_init(void) { return; } __attribute__ ((weak)) void adb_mouse_task(void) { return; } #endif // This sends Talk command to read data from register and returns length of the data. uint8_t adb_host_talk_buf(uint8_t addr, uint8_t reg, uint8_t *buf, uint8_t len) { for (int8_t i =0; i < len; i++) buf[i] = 0; cli(); attention(); send_byte((addr<<4) | ADB_CMD_TALK | reg); place_bit0(); // Stopbit(0) // TODO: Service Request(Srq): // Device holds low part of comannd stopbit for 140-260us // // Command: // ......._ ______________________ ___ ............_ ------- // | | | | | | | // Command | | | | | Data bytes | | // ........|___| | 140-260 |__| |_............|___| // |stop0 | Tlt Stop-to-Start |start1| |stop0 | // // Command without data: // ......._ __________________________ // | | // Command | | // ........|___| | 140-260 | // |stop0 | Tlt Stop-to-Start | // // Service Request: // ......._ ______ ___ ............_ ------- // | 140-260 | | | | | | // Command | Service Request | | | | Data bytes | | // ........|___________________| |__| |_............|___| // |stop0 | |start1| |stop0 | // ......._ __________ // | 140-260 | // Command | Service Request | // ........|___________________| // |stop0 | // This can be happened? // ......._ ______________________ ___ ............_ ----- // | | | | | | 140-260 | // Command | | | | | Data bytes | Service Request | // ........|___| | 140-260 |__| |_............|_________________| // |stop0 | Tlt Stop-to-Start |start1| |stop0 | // // "Service requests are issued by the devices during a very specific time at the // end of the reception of the command packet. // If a device in need of service issues a service request, it must do so within // the 65 µs of the Stop Bit’s low time and maintain the line low for a total of 300 µs." // // "A device sends a Service Request signal by holding the bus low during the low // portion of the stop bit of any command or data transaction. The device must lengthen // the stop by a minimum of 140 J.lS beyond its normal duration, as shown in Figure 8-15." // http://ww1.microchip.com/downloads/en/AppNotes/00591b.pdf if (!wait_data_hi(500)) { // Service Request(310us Adjustable Keyboard): just ignored //xprintf("R"); sei(); return 0; } if (!wait_data_lo(500)) { // Tlt/Stop to Start(140-260us) sei(); return 0; // No data from device(not error); } // start bit(1) if (!wait_data_hi(40)) { //xprintf("S"); sei(); return 0; } if (!wait_data_lo(100)) { //xprintf("s"); sei(); return 0; } uint8_t n = 0; // bit count do { // // |<- bit_cell_max(130) ->| // | |<- lo ->| // | | |<-hi->| // _______ // | | | // | 130-lo | lo-hi | // |________| | // uint8_t lo = (uint8_t) wait_data_hi(130); if (!lo) goto error; // no more bit or after stop bit uint8_t hi = (uint8_t) wait_data_lo(lo); if (!hi) goto error; // stop bit extedned by Srq? if (n/8 >= len) continue; // can't store in buf buf[n/8] <<= 1; if ((130 - lo) < (lo - hi)) { buf[n/8] |= 1; } } while ( ++n ); error: sei(); return n/8; } uint16_t adb_host_talk(uint8_t addr, uint8_t reg) { uint8_t len; uint8_t buf[8]; len = adb_host_talk_buf(addr, reg, buf, 8); if (len != 2) return 0; return (buf[0]<<8 | buf[1]); } void adb_host_listen_buf(uint8_t addr, uint8_t reg, uint8_t *buf, uint8_t len) { cli(); attention(); send_byte((addr<<4) | ADB_CMD_LISTEN | reg); place_bit0(); // Stopbit(0) // TODO: Service Request _delay_us(200); // Tlt/Stop to Start place_bit1(); // Startbit(1) for (int8_t i = 0; i < len; i++) { send_byte(buf[i]); //xprintf("%02X ", buf[i]); } place_bit0(); // Stopbit(0); sei(); } void adb_host_listen(uint8_t addr, uint8_t reg, uint8_t data_h, uint8_t data_l) { uint8_t buf[2] = { data_h, data_l }; adb_host_listen_buf(addr, reg, buf, 2); } void adb_host_flush(uint8_t addr) { cli(); attention(); send_byte((addr<<4) | ADB_CMD_FLUSH); place_bit0(); // Stopbit(0) _delay_us(200); // Tlt/Stop to Start sei(); } // send state of LEDs void adb_host_kbd_led(uint8_t addr, uint8_t led) { // Listen Register2 // upper byte: not used // lower byte: bit2=ScrollLock, bit1=CapsLock, bit0=NumLock adb_host_listen(addr, 2, 0, led & 0x07); } #ifdef ADB_PSW_BIT static inline void psw_lo() { ADB_DDR |= (1<<ADB_PSW_BIT); ADB_PORT &= ~(1<<ADB_PSW_BIT); } static inline void psw_hi() { ADB_PORT |= (1<<ADB_PSW_BIT); ADB_DDR &= ~(1<<ADB_PSW_BIT); } static inline bool psw_in() { ADB_PORT |= (1<<ADB_PSW_BIT); ADB_DDR &= ~(1<<ADB_PSW_BIT); return ADB_PIN&(1<<ADB_PSW_BIT); } #endif static inline void attention(void) { data_lo(); _delay_us(800-35); // bit1 holds lo for 35 more place_bit1(); } static inline void place_bit0(void) { data_lo(); _delay_us(65); data_hi(); _delay_us(35); } static inline void place_bit1(void) { data_lo(); _delay_us(35); data_hi(); _delay_us(65); } static inline void send_byte(uint8_t data) { for (int i = 0; i < 8; i++) { if (data&(0x80>>i)) place_bit1(); else place_bit0(); } } // These are carefully coded to take 6 cycles of overhead. // inline asm approach became too convoluted static inline uint16_t wait_data_lo(uint16_t us) { do { if ( !data_in() ) break; _delay_us(1 - (6 * 1000000.0 / F_CPU)); } while ( --us ); return us; } static inline uint16_t wait_data_hi(uint16_t us) { do { if ( data_in() ) break; _delay_us(1 - (6 * 1000000.0 / F_CPU)); } while ( --us ); return us; } /* ADB Protocol ============ Resources --------- ADB - The Untold Story: Space Aliens Ate My Mouse http://developer.apple.com/legacy/mac/library/#technotes/hw/hw_01.html ADB Manager http://developer.apple.com/legacy/mac/library/documentation/mac/pdf/Devices/ADB_Manager.pdf Service request(5-17) Apple IIgs Hardware Reference Second Edition [Chapter6 p121] ftp://ftp.apple.asimov.net/pub/apple_II/documentation/Apple%20IIgs%20Hardware%20Reference.pdf ADB Keycode http://72.0.193.250/Documentation/macppc/adbkeycodes/ http://m0115.web.fc2.com/m0115.jpg [Inside Macintosh volume V, pages 191-192] http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-421.18.3/IOHIDFamily/Cosmo_USB2ADB.c ADB Signaling http://kbdbabel.sourceforge.net/doc/kbd_signaling_pcxt_ps2_adb.pdf ADB Overview & History http://en.wikipedia.org/wiki/Apple_Desktop_Bus Microchip Application Note: ADB device(with code for PIC16C) http://www.microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=1824&appnote=en011062 AVR ATtiny2131 ADB to PS/2 converter(Japanese) http://hp.vector.co.jp/authors/VA000177/html/KeyBoardA5DEA5CBA5A2II.html Pinouts ------- ADB female socket from the front: __________ | | <--- top | 4o o3 | |2o o1| | == | |________| <--- bottom | | <--- 4pins ADB female socket from bottom: ========== <--- front | | | | |2o o1| |4o o3| ---------- <--- back 1: Data 2: Power SW(low when press Power key) 3: Vcc(5V) 4: GND Commands -------- ADB command is 1byte and consists of 4bit-address, 2bit-command type and 2bit-register. The commands are always sent by Host. Command format: 7 6 5 4 3 2 1 0 | | | |------------ address | |-------- command type | |---- register bits commands ------------------------------------------------------ - - - - 0 0 0 0 Send Reset(reset all devices) A A A A 0 0 0 1 Flush(reset a device) - - - - 0 0 1 0 Reserved - - - - 0 0 1 1 Reserved - - - - 0 1 - - Reserved A A A A 1 0 R R Listen(write to a device) A A A A 1 1 R R Talk(read from a device) The command to read keycodes from keyboard is 0x2C which consist of keyboard address 2 and Talk against register 0. Address: 2: keyboard 3: mice Registers: 0: application(keyboard uses this to store its data.) 1: application 2: application(keyboard uses this for LEDs and state of modifiers) 3: status and command Communication ------------- This is a minimum information for keyboard communication. See "Resources" for detail. Signaling: ~~~~____________~~||||||||||||__~~~~~_~~|||||||||||||||__~~~~ |800us | |7 Command 0| | | |15-64 Data 0|Stopbit(0) +Attention | | | +Startbit(1) +Startbit(1) | +Tlt(140-260us) +stopbit(0) Bit cells: bit0: ______~~~ 65 :35us bit1: ___~~~~~~ 35 :65us bit0 low time: 60-70% of bit cell(42-91us) bit1 low time: 30-40% of bit cell(21-52us) bit cell time: 70-130us [from Apple IIgs Hardware Reference Second Edition] Criterion for bit0/1: After 55us if line is low/high then bit is 0/1. Attention & start bit: Host asserts low in 560-1040us then places start bit(1). Tlt(Stop to Start): Bus stays high in 140-260us then device places start bit(1). Global reset: Host asserts low in 2.8-5.2ms. All devices are forced to reset. Service request from device(Srq): Device can request to send at commad(Global only?) stop bit. Requesting device keeps low for 140-260us at stop bit of command. Keyboard Data(Register0) This 16bit data can contains two keycodes and two released flags. First keycode is palced in upper byte. When one keyocode is sent, lower byte is 0xFF. Release flag is 1 when key is released. 1514 . . . . . 8 7 6 . . . . . 0 | | | | | | | | | +-+-+-+-+-+-+- Keycode2 | | | | | | | | +--------------- Released2(1 when the key is released) | +-+-+-+-+-+-+----------------- Keycode1 +------------------------------- Released1(1 when the key is released) Keycodes: Scancode consists of 7bit keycode and 1bit release flag. Device can send two keycodes at once. If just one keycode is sent keycode1 contains it and keyocode2 is 0xFF. Power switch: You can read the state from PSW line(active low) however the switch has a special scancode 0x7F7F, so you can also read from Data line. It uses 0xFFFF for release scancode. Keyboard LEDs & state of keys(Register2) This register hold current state of three LEDs and nine keys. The state of LEDs can be changed by sending Listen command. 1514 . . . . . . 7 6 5 . 3 2 1 0 | | | | | | | | | | | | | | | +- LED1(NumLock) | | | | | | | | | | | | | | +--- LED2(CapsLock) | | | | | | | | | | | | | +----- LED3(ScrollLock) | | | | | | | | | | +-+-+------- Reserved | | | | | | | | | +------------- ScrollLock | | | | | | | | +--------------- NumLock | | | | | | | +----------------- Apple/Command | | | | | | +------------------- Option | | | | | +--------------------- Shift | | | | +----------------------- Control | | | +------------------------- Reset/Power | | +--------------------------- CapsLock | +----------------------------- Delete +------------------------------- Reserved Address, Handler ID and bits(Register3) 1514131211 . . 8 7 . . . . . . 0 | | | | | | | | | | | | | | | | | | | | | | | | +-+-+-+-+-+-+-+- Handler ID | | | | +-+-+-+----------------- Address | | | +------------------------- 0 | | +--------------------------- Service request enable(1 = enabled) | +----------------------------- Exceptional event(alwyas 1 if not used) +------------------------------- 0 ADB Bit Cells bit cell time: 70-130us low part of bit0: 60-70% of bit cell low part of bit1: 30-40% of bit cell bit cell time 70us 130us -------------------------------------------- low part of bit0 42-49 78-91 high part of bit0 21-28 39-52 low part of bit1 21-28 39-52 high part of bit1 42-49 78-91 bit0: 70us bit cell: ____________~~~~~~ 42-49 21-28 130us bit cell: ____________~~~~~~ 78-91 39-52 bit1: 70us bit cell: ______~~~~~~~~~~~~ 21-28 42-49 130us bit cell: ______~~~~~~~~~~~~ 39-52 78-91 [from Apple IIgs Hardware Reference Second Edition] Keyboard Handle ID Apple Standard Keyboard M0116: 0x01 Apple Extended Keyboard M0115: 0x02 Apple Extended Keyboard II M3501: 0x02 Apple Adjustable Keybaord: 0x10 http://lxr.free-electrons.com/source/drivers/macintosh/adbhid.c?v=4.4#L802 END_OF_ADB */
17,807
C++
.cpp
484
30.896694
104
0.531937
MCJack123/ArduinoADB
30
5
0
GPL-2.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,550
adb.h
MCJack123_ArduinoADB/adb_to_usb/adb.h
/* Copyright 2011-19 Jun WAKO <wakojun@gmail.com> This software is licensed with a Modified BSD License. All of this is supposed to be Free Software, Open Source, DFSG-free, GPL-compatible, and OK to use in both free and proprietary applications. Additions and corrections to this file are welcome. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holders nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ADB_H #define ADB_H #include <stdint.h> #include <stdbool.h> #define ADB_PORT PORTB #define ADB_PIN PINB #define ADB_DDR DDRB #define ADB_DATA_BIT 0 #if !(defined(ADB_PORT) && \ defined(ADB_PIN) && \ defined(ADB_DDR) && \ defined(ADB_DATA_BIT)) # error "ADB port setting is required in config.h" #endif #define ADB_POWER 0x7F #define ADB_CAPS 0x39 /* ADB commands */ // Default Address #define ADB_ADDR_0 0 #define ADB_ADDR_DONGLE 1 #define ADB_ADDR_KEYBOARD 2 #define ADB_ADDR_MOUSE 3 #define ADB_ADDR_TABLET 4 #define ADB_ADDR_APPLIANCE 7 #define ADB_ADDR_8 8 #define ADB_ADDR_9 9 #define ADB_ADDR_10 10 #define ADB_ADDR_11 11 #define ADB_ADDR_12 12 #define ADB_ADDR_13 13 #define ADB_ADDR_14 14 #define ADB_ADDR_15 15 // for temporary purpose, do not use for polling #define ADB_ADDR_TMP 15 #define ADB_ADDR_MOUSE_POLL 10 // Command Type #define ADB_CMD_RESET 0 #define ADB_CMD_FLUSH 1 #define ADB_CMD_LISTEN 8 #define ADB_CMD_TALK 12 // Register #define ADB_REG_0 0 #define ADB_REG_1 1 #define ADB_REG_2 2 #define ADB_REG_3 3 /* ADB keyboard handler id */ #define ADB_HANDLER_M0116 0x01 #define ADB_HANDLER_IIGS 0x01 #define ADB_HANDLER_M0115 0x02 #define ADB_HANDLER_M3501 0x02 #define ADB_HANDLER_M1242_ANSI 0x10 #define ADB_HANDLER_EXTENDED_KEYBOARD 0x03 #define ADB_HANDLER_CLASSIC1_MOUSE 0x01 #define ADB_HANDLER_CLASSIC2_MOUSE 0x02 #define ADB_HANDLER_EXTENDED_MOUSE 0x04 #define ADB_HANDLER_TURBO_MOUSE 0x32 // ADB host void adb_host_init(void); bool adb_host_psw(void); uint16_t adb_host_kbd_recv(uint8_t addr); uint16_t adb_host_talk(uint8_t addr, uint8_t reg); uint8_t adb_host_talk_buf(uint8_t addr, uint8_t reg, uint8_t *buf, uint8_t len); void adb_host_listen(uint8_t addr, uint8_t reg, uint8_t data_h, uint8_t data_l); void adb_host_listen_buf(uint8_t addr, uint8_t reg, uint8_t *buf, uint8_t len); void adb_host_flush(uint8_t addr); void adb_host_kbd_led(uint8_t addr, uint8_t led); void adb_mouse_task(void); void adb_mouse_init(void); #endif
4,159
C++
.h
98
39.744898
85
0.711161
MCJack123/ArduinoADB
30
5
0
GPL-2.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,551
keymap.h
MCJack123_ArduinoADB/adb_to_usb/keymap.h
uint8_t adb_to_usb[128] = { 0x04, 0x16, 0x07, 0x09, 0x0B, 0x0A, 0x1D, 0x1B, 0x06, 0x19, 0x03, 0x05, 0x14, 0x1A, 0x08, 0x15, 0x1C, 0x17, 0x1E, 0x1F, 0x20, 0x21, 0x23, 0x22, 0x2E, 0x26, 0x24, 0x2D, 0x25, 0x27, 0x30, 0x12, 0x18, 0x2F, 0x0C, 0x13, 0x28, 0x0F, 0x0D, 0x34, 0x0E, 0x33, 0x31, 0x36, 0x38, 0x11, 0x10, 0x37, 0x2B, 0x2C, 0x35, 0x2A, 0x03, 0x29, 0x03, 0x03, 0x03, 0x39, 0x03, 0x50, 0x4F, 0x51, 0x52, 0x03, 0x03, 0x63, 0x03, 0x55, 0x03, 0x57, 0x03, 0x53, 0x03, 0x03, 0x03, 0x54, 0x58, 0x03, 0x56, 0x03, 0x03, 0x67, 0x62, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x03, 0x60, 0x61, 0x03, 0x03, 0x03, 0x3E, 0x3F, 0x40, 0x3C, 0x41, 0x42, 0x03, 0x44, 0x03, 0x68, 0x03, 0x69, 0x03, 0x43, 0x03, 0x45, 0x03, 0x6A, 0x75, 0x4A, 0x4B, 0x4C, 0x3D, 0x4D, 0x3B, 0x4E, 0x3A, 0x03, 0x03, 0x03, 0x03, 0x66 };
1,438
C++
.h
130
5.138462
28
0.404125
MCJack123/ArduinoADB
30
5
0
GPL-2.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,552
ram_handling.cpp
pinknetworkx_atomicpacks-contract/src/ram_handling.cpp
#include <atomicpacks.hpp> /** * Sells RAM bytes from the from the collection's ram balance and transfers the proceeds to recipient * * @required_auth authorized_account, who needs to be an authorized account in the specified collection */ ACTION atomicpacks::withdrawram( name authorized_account, name collection_name, name recipient, int64_t bytes ) { require_auth(authorized_account); check_has_collection_auth(authorized_account, collection_name); check(is_account(recipient), "recipient account does not exist"); decrease_collection_ram_balance(collection_name, bytes, "The collection does not have a sufficient ram balance"); asset payout = ram::get_sell_ram_quantity(bytes); action( permission_level{get_self(), name("active")}, name("eosio"), name("sellram"), std::make_tuple( get_self(), bytes ) ).send(); action( permission_level{get_self(), name("active")}, name("eosio.token"), name("transfer"), std::make_tuple( get_self(), recipient, payout, string("Sold RAM") ) ).send(); } /** * Refunds RAM bytes to a set of collections. This is meant to be used to refund bytes that get freed without being caught automatically, * e.g. for when minted NFTs get burned * * @required_auth The contract itself */ ACTION atomicpacks::refundram( name refund_type, uint64_t from_block, uint64_t to_block, vector<RAM_REFUND_DATA> ram_refund_data ) { require_auth(get_self()); check(to_block > from_block, "to_block needs to be larger than from_block"); auto ramrefund_itr = ramrefunds.find(refund_type.value); if (ramrefund_itr == ramrefunds.end()) { check(from_block == 0, "For a new ramrefund type, the from_block needs to be 0"); ramrefunds.emplace(get_self(), [&](auto &_ramrefund) { _ramrefund.refund_type = refund_type; _ramrefund.to_block = to_block; }); } else { check(from_block == ramrefund_itr->to_block + 1, "For an existing ramrefund type, the from block needs to be the current to block + 1"); ramrefunds.modify(ramrefund_itr, get_self(), [&](auto &_ramrefund) { _ramrefund.to_block = to_block; }); } for (RAM_REFUND_DATA &ram_refund_element : ram_refund_data) { increase_collection_ram_balance(ram_refund_element.collection_name, ram_refund_element.bytes); } } /* * Action that can only be called by the contract itself. * * Having this in an extra action rather than directly in the on transfer notify is needed in order to * prevent a reentrency attack that would otherwise open up due to the execution order of notifications * and inline actions */ ACTION atomicpacks::buyramproxy( name collection_to_credit, asset quantity ) { require_auth(get_self()); increase_collection_ram_balance(collection_to_credit, ram::get_purchase_ram_bytes(quantity)); action( permission_level{get_self(), name("active")}, name("eosio"), name("buyram"), std::make_tuple( get_self(), get_self(), quantity ) ).send(); } /** * Internal function to increase the ram balance of a collection */ void atomicpacks::increase_collection_ram_balance( name collection_name, int64_t bytes ) { check(bytes > 0, "increase balance bytes must be positive"); auto itr = rambalances.find(collection_name.value); if (itr == rambalances.end()) { check(bytes >= 128, "Must inrease the collection ram balance by at least 128 to pay for the table entry"); rambalances.emplace(get_self(), [&](auto &_colbalance) { _colbalance.collection_name = collection_name; _colbalance.byte_balance = bytes - 128; }); } else { rambalances.modify(itr, same_payer, [&](auto &_colbalance) { _colbalance.byte_balance += bytes; }); } } /** * Internal function to decrease the ram balance of a collection * Throws if the collection does not have enough balance */ void atomicpacks::decrease_collection_ram_balance( name collection_name, int64_t bytes, string error_message ) { check(bytes > 0, "decrease balance bytes must be positive"); auto itr = rambalances.find(collection_name.value); check(itr != rambalances.end() && itr->byte_balance >= bytes, error_message); rambalances.modify(itr, same_payer, [&](auto &_colbalance) { _colbalance.byte_balance -= bytes; }); }
4,632
C++
.cpp
130
29.9
144
0.660934
pinknetworkx/atomicpacks-contract
30
29
0
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,553
unboxing.cpp
pinknetworkx_atomicpacks-contract/src/unboxing.cpp
#include <atomicpacks.hpp> #include "randomness_provider.cpp" /** * Claims one or more rolls from an unboxed pack. * Claiming a roll can either mean that a new asset is minted if the template id is not -1 * or simply removing the row from the unboxassets table if the template id is -1 * * @required_auth The unboxer of the pack */ ACTION atomicpacks::claimunboxed( uint64_t pack_asset_id, vector <uint64_t> origin_roll_ids ) { auto unboxpack_itr = unboxpacks.require_find(pack_asset_id, "No unboxpack with this pack asset id exists"); check(has_auth(unboxpack_itr->unboxer) || has_auth(get_self()), "The transaction needs to be authorized either by the unboxer or by the contract itself"); check(origin_roll_ids.size() != 0, "The original roll ids vector can't be empty"); auto pack_itr = packs.find(unboxpack_itr->pack_id); atomicassets::templates_t col_templates = atomicassets::get_templates(pack_itr->collection_name); unboxassets_t unboxassets = get_unboxassets(pack_asset_id); int64_t ram_cost_delta = 0; bool mint_at_least_one = false; for (uint64_t roll_id : origin_roll_ids) { auto unboxasset_itr = unboxassets.require_find(roll_id, ("No unbox asset with the origin roll id " + to_string(roll_id) + " exists").c_str()); //Template -1 means no asset will be created if (unboxasset_itr->template_id != -1) { auto template_itr = col_templates.find(unboxasset_itr->template_id); //Templates with maximum supply are not supported //Templates are guaranteed not to have a maximum supply when the packs are created //however the template could be locked later, in which case it is skipped here if (template_itr->max_supply == 0) { action( permission_level{get_self(), name("active")}, atomicassets::ATOMICASSETS_ACCOUNT, name("mintasset"), make_tuple( get_self(), pack_itr->collection_name, template_itr->schema_name, template_itr->template_id, unboxpack_itr->unboxer, (atomicassets::ATTRIBUTE_MAP) {}, (atomicassets::ATTRIBUTE_MAP) {}, (vector <asset>) {} ) ).send(); mint_at_least_one = true; //Minimum size asset = 151 ram_cost_delta += 151; } } unboxassets.erase(unboxasset_itr); ram_cost_delta -= 124; } if (mint_at_least_one) { atomicassets::assets_t unboxer_assets = atomicassets::get_assets(unboxpack_itr->unboxer); if (unboxer_assets.begin() == unboxer_assets.end()) { //Asset table scope ram_cost_delta += 112; } } if (unboxassets.begin() == unboxassets.end()) { unboxpacks.erase(unboxpack_itr); //Unboxassets table scope 112 + unboxpacks entry 264 ram_cost_delta -= 376; } if (ram_cost_delta > 0) { decrease_collection_ram_balance(pack_itr->collection_name, ram_cost_delta, "The collection does not have enough RAM to mint the assets"); } else if (ram_cost_delta < 0) { increase_collection_ram_balance(pack_itr->collection_name, -ram_cost_delta); } } /** * This action is called by the rng oracle and provides the randomness for unboxing a pack * The assoc id is equal to the asset id of the pack that is being unboxed * * The unboxed assets are not immediately minted but instead placed in the unboxassets table with * the scope <asset id of the pack that is being unboxed> and need to be claimed using the claimunboxed action * This functionality is split in an effort to prevent transaction timeouts * * @required_auth rng oracle account */ ACTION atomicpacks::receiverand( uint64_t assoc_id, checksum256 random_value ) { require_auth(orng::ORNG_CONTRACT); RandomnessProvider randomness_provider(random_value); auto unboxpack_itr = unboxpacks.find(assoc_id); auto pack_itr = packs.find(unboxpack_itr->pack_id); //job table entry in the rng oracle contract has been erased increase_collection_ram_balance(pack_itr->collection_name, 144); packrolls_t packrolls = get_packrolls(unboxpack_itr->pack_id); unboxassets_t unboxassets = get_unboxassets(unboxpack_itr->pack_asset_id); vector <int32_t> result_template_ids = {}; for (auto roll_itr = packrolls.begin(); roll_itr != packrolls.end(); roll_itr++) { uint32_t rand = randomness_provider.get_rand(roll_itr->total_odds); uint32_t summed_odds = 0; for (const OUTCOME &outcome : roll_itr->outcomes) { summed_odds += outcome.odds; if (summed_odds > rand) { //RAM has already been paid when the pack was received / burned with the reserved_ram_bytes unboxassets.emplace(get_self(), [&](auto &_unboxasset) { _unboxasset.origin_roll_id = roll_itr->roll_id; _unboxasset.template_id = outcome.template_id; }); result_template_ids.push_back(outcome.template_id); break; } } } action( permission_level{get_self(), name("active")}, atomicassets::ATOMICASSETS_ACCOUNT, name("burnasset"), std::make_tuple( get_self(), assoc_id ) ).send(); action( permission_level{get_self(), name("active")}, get_self(), name("logresult"), std::make_tuple( assoc_id, unboxpack_itr->pack_id, result_template_ids ) ).send(); } /** * This function is called when AtomicAssets assets are transferred to the pack contract * This is used to unbox packs, by transferring exactly one pack to the pack contract * The pack asset is then burned and the rng oracle is called to request a random value */ void atomicpacks::receive_asset_transfer( name from, name to, vector <uint64_t> asset_ids, string memo ) { if (to != get_self()) { return; } check(asset_ids.size() == 1, "Only one pack can be opened at a time"); check(memo == "unbox", "Invalid memo"); atomicassets::assets_t own_assets = atomicassets::get_assets(get_self()); auto asset_itr = own_assets.find(asset_ids[0]); check(asset_itr->template_id != -1, "The transferred asset does not belong to a template"); auto packs_by_template_id = packs.get_index<name("templateid")>(); auto pack_itr = packs_by_template_id.require_find(asset_itr->template_id, "The transferred asset's template does not belong to any pack"); check(pack_itr->unlock_time <= current_time_point().sec_since_epoch(), "The pack has not unlocked yet"); //Get signing value from transaction id //As this is only used as the signing value for the randomness oracle, it does not matter that this //signing value is not truly random size_t size = transaction_size(); char buf[size]; uint32_t read = read_transaction(buf, size); check(size == read, "Signing value generation: read_transaction() has failed."); checksum256 tx_id = eosio::sha256(buf, read); uint64_t signing_value; memcpy(&signing_value, tx_id.data(), sizeof(signing_value)); //Check if the signing_value was already used. //If that is the case, increment the signing_value until a non-used value is found while (orng::signvals.find(signing_value) != orng::signvals.end()) { signing_value++; } //This amount of RAM will be needed to fill the packrolls table when the randomness is received //112 for the unboxassets scope //124 for each unboxassets row (112 for pk + 8 + 4) packrolls_t packrolls = get_packrolls(pack_itr->pack_id); int64_t reserved_ram_bytes = 112 + std::distance(packrolls.begin(), packrolls.end()) * 124; //264 for the unboxpacks entry (112 for pk + 3 x 8 for data + 128 for sk) //120 for the signvals entry in the rng oracle contract (112 pk + 8 for data) //144 for the jobs entry in the rng oracle contract (112 pk + 4 x 8 for data) decrease_collection_ram_balance(pack_itr->collection_name, reserved_ram_bytes + 264 + 120 + 144, "The collection does not have enough RAM to pay for the reserved bytes"); unboxpacks.emplace(get_self(), [&](auto &_unboxpack) { _unboxpack.pack_asset_id = asset_ids[0]; _unboxpack.pack_id = pack_itr->pack_id; _unboxpack.unboxer = from; }); action( permission_level{get_self(), name("active")}, orng::ORNG_CONTRACT, name("requestrand"), std::make_tuple( asset_ids[0], //used as assoc id signing_value, get_self() ) ).send(); } ACTION atomicpacks::logresult( uint64_t pack_asset_id, uint64_t pack_id, vector<int32_t> template_ids ) { require_auth(get_self()); }
9,195
C++
.cpp
206
36.495146
109
0.636811
pinknetworkx/atomicpacks-contract
30
29
0
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,554
randomness_provider.cpp
pinknetworkx_atomicpacks-contract/src/randomness_provider.cpp
class RandomnessProvider { public: RandomnessProvider(checksum256 random_seed) { raw_values = random_seed.extract_as_byte_array(); offset = 0; } uint64_t get_uint64() { if (offset > 24) { regenerate_raw_values(); } uint64_t value = 0; for (int i = 0; i < 8; i++) { value = (value << 8) + raw_values[offset]; offset++; } return value; } uint32_t get_rand(uint32_t max_value) { return get_uint64() % ((uint64_t) max_value); } private: void regenerate_raw_values() { checksum256 new_hash = eosio::sha256((char *) raw_values.data(), 32); raw_values = new_hash.extract_as_byte_array(); offset = 0; } array<uint8_t, 32> raw_values; int offset; };
817
C++
.cpp
29
21.103448
77
0.552296
pinknetworkx/atomicpacks-contract
30
29
0
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
1,541,555
atomicpacks.cpp
pinknetworkx_atomicpacks-contract/src/atomicpacks.cpp
#include <atomicpacks.hpp> #include "ram_handling.cpp" #include "pack_creation.cpp" #include "unboxing.cpp" /** * Sets the identifier singleton * * @required_auth The contract itself */ ACTION atomicpacks::setident( string contract_type, string version ) { require_auth(get_self()); identifier.set({.contract_type = contract_type, .version = version}, get_self()); } /** * Requests new randomness for a given assoc_id * This is supposed to be used in the rare case that the RNG oracle kills a job for a pack unboxing * due to issues with the finisher script. * * @required_auth The contract itself */ ACTION atomicpacks::retryrand( uint64_t pack_asset_id ) { require_auth(get_self()); unboxpacks.require_find(pack_asset_id, "No open unboxpacks entry with the specified pack asset id exists"); unboxassets_t unboxassets = get_unboxassets(pack_asset_id); check(unboxassets.begin() == unboxassets.end(), "The specified pack asset id already has results"); //Get signing value from transaction id //As this is only used as the signing value for the randomness oracle, it does not matter that this //signing value is not truly random size_t size = transaction_size(); char buf[size]; uint32_t read = read_transaction(buf, size); check(size == read, "Signing value generation: read_transaction() has failed."); checksum256 tx_id = eosio::sha256(buf, read); uint64_t signing_value; memcpy(&signing_value, tx_id.data(), sizeof(signing_value)); //Check if the signing_value was already used. //If that is the case, increment the signing_value until a non-used value is found while (orng::signvals.find(signing_value) != orng::signvals.end()) { signing_value++; } action( permission_level{get_self(), name("active")}, orng::ORNG_CONTRACT, name("requestrand"), std::make_tuple( pack_asset_id, signing_value, get_self() ) ).send(); } /** * This function is called when the contract receives an eosio.token transfer * Any core token transferred to the contract is automatically converted to RAM and added * to the sender's RAM balance */ void atomicpacks::receive_token_transfer( name from, name to, asset quantity, string memo ) { const set <name> ignore = set < name > { atomicassets::ATOMICASSETS_ACCOUNT, // EOSIO system accounts name("eosio.stake"), name("eosio.names"), name("eosio.ram"), name("eosio.rex"), name("eosio") }; if (to != get_self() || ignore.find(from) != ignore.end()) { return; } if (memo.find("deposit_collection_ram:") == 0) { check(get_first_receiver() == CORE_TOKEN_ACCOUNT && quantity.symbol == CORE_TOKEN_SYMBOL, "Must transfer core token when depositing RAM"); name parsed_collection_name = name(memo.substr(23)); atomicassets::collections.require_find(parsed_collection_name.value, ("No collection with this name exists: " + parsed_collection_name.to_string()).c_str()); action( permission_level{get_self(), name("active")}, get_self(), name("buyramproxy"), std::make_tuple( parsed_collection_name, quantity ) ).send(); } else { check(false, "invalid memo"); } } /** * Checks if the account_to_check is in the authorized_accounts vector of the specified collection */ void atomicpacks::check_has_collection_auth( name account_to_check, name collection_name ) { auto collection_itr = atomicassets::collections.require_find(collection_name.value, "No collection with this name exists"); check(std::find( collection_itr->authorized_accounts.begin(), collection_itr->authorized_accounts.end(), account_to_check ) != collection_itr->authorized_accounts.end(), "The account " + account_to_check.to_string() + " is not authorized within the collection"); } atomicpacks::packrolls_t atomicpacks::get_packrolls(uint64_t pack_id) { return packrolls_t(get_self(), pack_id); } atomicpacks::unboxassets_t atomicpacks::get_unboxassets(uint64_t pack_asset_id) { return unboxassets_t(get_self(), pack_asset_id); }
4,386
C++
.cpp
122
30.270492
103
0.665093
pinknetworkx/atomicpacks-contract
30
29
0
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,556
pack_creation.cpp
pinknetworkx_atomicpacks-contract/src/pack_creation.cpp
#include <atomicpacks.hpp> /** * Announces a new pack * The possible outcomes packed in rolls must be provided afterwards with the addpackroll action * * @required_auth authorized_account, who must be authorized within the specfied collection */ ACTION atomicpacks::announcepack( name authorized_account, name collection_name, uint32_t unlock_time, string display_data ) { require_auth(authorized_account); check_has_collection_auth(authorized_account, collection_name); check_has_collection_auth(get_self(), collection_name); uint64_t pack_id = packs.available_primary_key(); if (pack_id == 0) { pack_id = 1; } packs.emplace(authorized_account, [&](auto &_pack) { _pack.pack_id = pack_id; _pack.collection_name = collection_name; _pack.unlock_time = unlock_time; _pack.pack_template_id = -1; _pack.roll_counter = 0; _pack.display_data = display_data; }); action( permission_level{get_self(), name("active")}, get_self(), name("lognewpack"), std::make_tuple( pack_id, collection_name, unlock_time ) ).send(); } /** * Adds a roll to a pack * A roll is a vector of outcomes, each of which have a probabilitiy (odds) * The summed odds must equal 1 * * Each roll can be seen at one random chance at unboxing an NFT * * @required_auth authorized_account, who must be authorized within the collection that the pack belongs to */ ACTION atomicpacks::addpackroll( name authorized_account, uint64_t pack_id, vector <OUTCOME> outcomes, uint32_t total_odds ) { require_auth(authorized_account); auto pack_itr = packs.require_find(pack_id, "No pack with this id exists"); check_has_collection_auth(authorized_account, pack_itr->collection_name); check(pack_itr->pack_template_id == -1, "The pack has already been completed"); check(outcomes.size() != 0, "A roll must include at least one outcome"); atomicassets::templates_t col_templates = atomicassets::get_templates(pack_itr->collection_name); uint32_t total_counted_odds = 0; uint32_t last_odds = UINT_MAX; for (OUTCOME outcome : outcomes) { check(outcome.odds > 0, "Each outcome must have positive odds"); check(outcome.odds <= last_odds, "The outcomes must be sorted in descending order based on their odds"); last_odds = outcome.odds; total_counted_odds += outcome.odds; check(total_counted_odds >= outcome.odds, "Overflow: Total odds can't be more than 2^32 - 1"); if (outcome.template_id != -1) { auto template_itr = col_templates.require_find(outcome.template_id, ("At least one template id of an outcome does not exist within the collection: " + to_string(outcome.template_id)).c_str()); check(template_itr->max_supply == 0, "Can only use templates without a max supply"); } } check(total_counted_odds == total_odds, "The total odds of the outcomes deos not equal the provided total odds"); uint64_t roll_id = pack_itr->roll_counter; packs.modify(pack_itr, same_payer, [&](auto &_pack) { _pack.roll_counter++; }); packrolls_t packrolls = get_packrolls(pack_id); packrolls.emplace(authorized_account, [&](auto &_roll) { _roll.roll_id = roll_id; _roll.outcomes = outcomes; _roll.total_odds = total_odds; }); action( permission_level{get_self(), name("active")}, get_self(), name("lognewroll"), std::make_tuple( pack_id, roll_id ) ).send(); } /** * Deletes a roll * * @required_auth authorized_account, who must be authorized within the collection that the pack belongs to */ ACTION atomicpacks::delpackroll( name authorized_account, uint64_t pack_id, uint64_t roll_id ) { require_auth(authorized_account); auto pack_itr = packs.require_find(pack_id, "No pack with this id exists"); check_has_collection_auth(authorized_account, pack_itr->collection_name); check(pack_itr->pack_template_id == -1, "The pack has already been completed"); packrolls_t packrolls = get_packrolls(pack_id); auto roll_itr = packrolls.require_find(roll_id, "No roll with this id exists for the specified pack"); packrolls.erase(roll_itr); } /** * Completes a pack * By completing a pack, it is linked to the specified template id, which means that every asset belonging * to this template is then viewed as a pack that can be unboxed * * After a pack is completed, no new rolls can be added and no existing rolls can be erased * * @required_auth authorized_account, who must be authorized within the collection that the pack belongs to */ ACTION atomicpacks::completepack( name authorized_account, uint64_t pack_id, int32_t pack_template_id ) { require_auth(authorized_account); auto pack_itr = packs.require_find(pack_id, "No pack with this id exists"); check_has_collection_auth(authorized_account, pack_itr->collection_name); check(pack_itr->pack_template_id == -1, "The pack has already been completed"); packrolls_t packrolls = get_packrolls(pack_id); check(packrolls.begin() != packrolls.end(), "The pack does not have any rolls"); check(pack_template_id > 0, "The tempalte id must be positive"); atomicassets::templates_t col_templates = atomicassets::get_templates(pack_itr->collection_name); auto template_itr = col_templates.require_find(pack_template_id, "No template with this id exists within the collection taht the pack belongs to"); check(template_itr->burnable, "The template with this id is not burnable."); check(template_itr->transferable, "The template with this id is not transferable."); auto packs_by_template_id = packs.get_index<name("templateid")>(); check(packs_by_template_id.find(pack_template_id) == packs_by_template_id.end(), "Another pack is already using this template id"); packs.modify(pack_itr, same_payer, [&](auto &_pack) { _pack.pack_template_id = pack_template_id; }); } ACTION atomicpacks::setpacktime( name authorized_account, uint64_t pack_id, uint32_t new_unlock_time ) { require_auth(authorized_account); auto pack_itr = packs.require_find(pack_id, "No pack with this id exists"); check_has_collection_auth(authorized_account, pack_itr->collection_name); check(pack_itr->pack_template_id != -1, "The pack has not been completed yet"); check(new_unlock_time > current_time_point().sec_since_epoch(), "The new unlock time can't be in the past"); packs.modify(pack_itr, same_payer, [&](auto &_pack) { _pack.unlock_time = new_unlock_time; }); } ACTION atomicpacks::setpackdata( name authorized_account, uint64_t pack_id, string display_data ) { require_auth(authorized_account); auto pack_itr = packs.require_find(pack_id, "No pack with this id exists"); check_has_collection_auth(authorized_account, pack_itr->collection_name); check(pack_itr->pack_template_id != -1, "The pack has not been completed yet"); packs.modify(pack_itr, authorized_account, [&](auto &_pack) { _pack.display_data = display_data; }); } ACTION atomicpacks::lognewpack( uint64_t pack_id, name collection_name, uint32_t unlock_time ) { require_auth(get_self()); } ACTION atomicpacks::lognewroll( uint64_t pack_id, uint64_t roll_id ) { require_auth(get_self()); }
7,647
C++
.cpp
190
34.794737
106
0.682273
pinknetworkx/atomicpacks-contract
30
29
0
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,558
wax-orng-interface.hpp
pinknetworkx_atomicpacks-contract/include/wax-orng-interface.hpp
#include <eosio/eosio.hpp> using namespace eosio; namespace orng { static constexpr name ORNG_CONTRACT = name("orng.wax"); TABLE signvals_a { uint64_t signing_value; auto primary_key() const { return signing_value; } }; typedef multi_index <name("signvals.a"), signvals_a> signvals_t; signvals_t signvals = signvals_t(ORNG_CONTRACT, ORNG_CONTRACT.value); }
402
C++
.h
11
31.454545
73
0.698953
pinknetworkx/atomicpacks-contract
30
29
0
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
1,541,559
atomicpacks.hpp
pinknetworkx_atomicpacks-contract/include/atomicpacks.hpp
#pragma once #include <eosio/eosio.hpp> #include <eosio/asset.hpp> #include <eosio/crypto.hpp> #include <eosio/transaction.hpp> #include <atomicassets-interface.hpp> #include <ram-interface.hpp> #include <wax-orng-interface.hpp> using namespace std; using namespace eosio; static constexpr name CORE_TOKEN_ACCOUNT = name("eosio.token"); static constexpr symbol CORE_TOKEN_SYMBOL = symbol("WAX", 8); CONTRACT atomicpacks : public contract { public: using contract::contract; struct OUTCOME { uint32_t odds; int32_t template_id; //-1 is equal to no NFT being minted }; struct RAM_REFUND_DATA { name collection_name; uint64_t bytes; }; ACTION setident( string contract_type, string version ); ACTION retryrand( uint64_t pack_asset_id ); ACTION announcepack( name authorized_account, name collection_name, uint32_t unlock_time, string display_data ); ACTION addpackroll( name authorized_account, uint64_t pack_id, vector <OUTCOME> outcomes, uint32_t total_odds ); ACTION delpackroll( name authorized_account, uint64_t pack_id, uint64_t roll_id ); ACTION completepack( name authorized_account, uint64_t pack_id, int32_t pack_template_id ); ACTION setpacktime( name authorized_account, uint64_t pack_id, uint32_t new_unlock_time ); ACTION setpackdata( name authorized_account, uint64_t pack_id, string display_data ); ACTION claimunboxed( uint64_t pack_asset_id, vector <uint64_t> origin_roll_ids ); ACTION lognewpack( uint64_t pack_id, name collection_name, uint32_t unlock_time ); ACTION lognewroll( uint64_t pack_id, uint64_t roll_id ); ACTION logresult( uint64_t pack_asset_id, uint64_t pack_id, vector<int32_t> template_ids ); ACTION withdrawram( name authorized_account, name collection_name, name recipient, int64_t bytes ); ACTION refundram( name refund_type, uint64_t from_block, uint64_t to_block, vector<RAM_REFUND_DATA> ram_refund_data ); ACTION buyramproxy( name collection_to_credit, asset quantity ); ACTION receiverand( uint64_t assoc_id, checksum256 random_value ); [[eosio::on_notify("eosio.token::transfer")]] void receive_token_transfer( name from, name to, asset quantity, string memo ); [[eosio::on_notify("atomicassets::transfer")]] void receive_asset_transfer( name from, name to, vector <uint64_t> asset_ids, string memo ); private: TABLE packs_s { uint64_t pack_id; name collection_name; uint32_t unlock_time; int32_t pack_template_id = -1; //-1 if the pack has not been activated yet uint64_t roll_counter = 0; string display_data; uint64_t primary_key() const { return pack_id; } uint64_t by_template_id() const { return (uint64_t) pack_template_id; }; }; typedef multi_index<name("packs"), packs_s, indexed_by < name("templateid"), const_mem_fun < packs_s, uint64_t, &packs_s::by_template_id>>> packs_t; //Scope pack id TABLE packrolls_s { uint64_t roll_id; vector <OUTCOME> outcomes; uint32_t total_odds; uint64_t primary_key() const { return roll_id; } }; typedef multi_index<name("packrolls"), packrolls_s> packrolls_t; TABLE unboxpacks_s { uint64_t pack_asset_id; uint64_t pack_id; name unboxer; uint64_t primary_key() const { return pack_asset_id; } uint64_t by_unboxer() const { return unboxer.value; } }; typedef multi_index<name("unboxpacks"), unboxpacks_s, indexed_by < name("unboxer"), const_mem_fun < unboxpacks_s, uint64_t, &unboxpacks_s::by_unboxer>>> unboxpacks_t; //Scope asset id of pack opened TABLE unboxassets_s { uint64_t origin_roll_id; int32_t template_id; uint64_t primary_key() const { return origin_roll_id; } }; typedef multi_index<name("unboxassets"), unboxassets_s> unboxassets_t; TABLE rambalances_s { name collection_name; int64_t byte_balance; uint64_t primary_key() const { return collection_name.value; } }; typedef multi_index<name("rambalances"), rambalances_s> rambalances_t; TABLE ramrefunds_s { name refund_type; int64_t to_block; uint64_t primary_key() const { return refund_type.value; } }; typedef multi_index<name("ramrefunds"), ramrefunds_s> ramrefunds_t; TABLE identifier_s { string contract_type = "atomicpacks"; string version = "1.2.0"; }; typedef singleton <name("identifier"), identifier_s> identifier_t; // https://github.com/EOSIO/eosio.cdt/issues/280 typedef multi_index <name("identifier"), identifier_s> identifier_t_for_abi; packs_t packs = packs_t(get_self(), get_self().value); unboxpacks_t unboxpacks = unboxpacks_t(get_self(), get_self().value); rambalances_t rambalances = rambalances_t(get_self(), get_self().value); ramrefunds_t ramrefunds = ramrefunds_t(get_self(), get_self().value); identifier_t identifier = identifier_t(get_self(), get_self().value); packrolls_t get_packrolls(uint64_t pack_id); unboxassets_t get_unboxassets(uint64_t pack_asset_id); void check_has_collection_auth(name account_to_check, name collection_name); //RAM Handlling void increase_ram_balance(name account, int64_t bytes); void decrease_ram_balance(name account, int64_t bytes, string error_message); void increase_collection_ram_balance(name collection_name, int64_t bytes); void decrease_collection_ram_balance(name collection_name, int64_t bytes, string error_message); };
6,194
C++
.h
184
26.717391
106
0.639825
pinknetworkx/atomicpacks-contract
30
29
0
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,560
ram-interface.hpp
pinknetworkx_atomicpacks-contract/include/ram-interface.hpp
#include <eosio/eosio.hpp> #include <eosio/asset.hpp> using namespace eosio; namespace ram { static const symbol RAMCORE_SYMBOL = symbol("RAMCORE", 4); struct connector { asset balance; double weight = .5; }; struct rammarket_s { asset supply; connector base; connector quote; auto primary_key() const { return supply.symbol.raw(); } }; typedef eosio::multi_index<name("rammarket"), rammarket_s> rammarket_t; rammarket_t rammarket = rammarket_t(name("eosio"), name("eosio").value); //From exchange_state.cpp in eosio.system contract source int64_t get_bancor_output( int64_t inp_reserve, int64_t out_reserve, int64_t inp ) { const double ib = inp_reserve; const double ob = out_reserve; const double in = inp; int64_t out = int64_t( (in * ob) / (ib + in) ); if ( out < 0 ) out = 0; return out; } int64_t get_purchase_ram_bytes(const asset &purchase_quantity) { auto itr = rammarket.find(RAMCORE_SYMBOL.raw()); const int64_t ram_reserve = itr->base.balance.amount; const int64_t core_reserve = itr->quote.balance.amount; int64_t fee_amount = (purchase_quantity.amount + 199) / 200; int64_t purchase_amount_after_fee = purchase_quantity.amount - fee_amount; return get_bancor_output(core_reserve, ram_reserve, purchase_amount_after_fee); } asset get_sell_ram_quantity(int64_t bytes_to_sell) { auto itr = rammarket.find(RAMCORE_SYMBOL.raw()); const int64_t ram_reserve = itr->base.balance.amount; const int64_t core_reserve = itr->quote.balance.amount; int64_t full_amount = get_bancor_output(ram_reserve, core_reserve, bytes_to_sell); int64_t fee_amount = (full_amount + 199) / 200; return asset(full_amount - fee_amount, itr->quote.balance.symbol); } }
1,947
C++
.h
47
34.148936
90
0.643806
pinknetworkx/atomicpacks-contract
30
29
0
GPL-3.0
9/20/2024, 10:45:17 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
1,541,563
trackfile.cpp
missdeer_hannah/desktop/trackfile.cpp
#include "trackfile.h" QString TrackFile::freshCanonicalLocation() { // Note: We return here the cached value, that was calculated just after // init this TrackFile object. This will avoid repeated use of the time // consuming file IO. QString loc = canonicalLocation(); if (loc.isEmpty()) { // Refresh the cached file info and try again m_fileInfo.refresh(); loc = canonicalLocation(); } return loc; }
460
C++
.cpp
15
25.866667
76
0.677928
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,564
externalreverseproxyrunner.cpp
missdeer_hannah/desktop/externalreverseproxyrunner.cpp
#include <QProcess> #include <QSettings> #if defined(Q_OS_WIN) # include <Windows.h> #else # include <signal.h> #endif #include "externalreverseproxyrunner.h" ExternalReverseProxyRunner::ExternalReverseProxyRunner(QObject *parent) : m_process(new QProcess) {} ExternalReverseProxyRunner::~ExternalReverseProxyRunner() { m_process->terminate(); delete m_process; } void ExternalReverseProxyRunner::start() { m_process->start(); } void ExternalReverseProxyRunner::stop() { #if defined(Q_OS_WIN) // Send Ctrl+C GenerateConsoleCtrlEvent(CTRL_C_EVENT, m_process->processId()); #else // Send SIGINT kill(m_process->processId(), SIGINT); #endif } void ExternalReverseProxyRunner::restart() { stop(); start(); } void ExternalReverseProxyRunner::applySettings(QSettings &settings) { m_process->setProgram(settings.value("externalReverseProxyPath").toString()); QStringList args; bool ok = false; int state = settings.value("reverseProxyAutoRedirect", 2).toInt(&ok); if (ok && state == Qt::Checked) { args << "--auto-redirect"; } state = settings.value("reverseProxyRedirect", 2).toInt(&ok); if (ok) { args << "--redirect"; } #if !defined(Q_OS_WIN) auto networkInterface = settings.value("reverseProxyBindNetworkInterface").toString(); if (!networkInterface.isEmpty()) { args << "-i" << networkInterface; } #endif auto port = settings.value("reverseProxyListenPort", 8090).toInt(&ok); if (ok) { args << "-b" << QStringLiteral("localhost:%1").arg(port); } auto proxyType = settings.value("reverseProxyProxyType").toString(); if (proxyType == QStringLiteral("Http")) { auto proxyAddr = settings.value("reverseProxyProxyAddress").toString(); args << "-t" << proxyAddr; } if (proxyType == QStringLiteral("Socks5")) { auto proxyAddr = settings.value("reverseProxyProxyAddress").toString(); args << "-s" << proxyAddr; } m_process->setArguments(args); } bool ExternalReverseProxyRunner::isRunning() { return m_process->state() == QProcess::Running; }
2,179
C++
.cpp
77
24.428571
100
0.67893
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,565
main.cpp
missdeer_hannah/desktop/main.cpp
#include <QApplication> #include <QCommandLineParser> #include <QDir> #include <QFileOpenEvent> #include <QMessageBox> #include <QQmlApplicationEngine> #include <QQmlContext> #include <QSettings> #include <QtCore> #include "BeastServerRunner.h" #include "bass.h" #include "bassplayer.h" #include "configurationwindow.h" #include "externalreverseproxyrunner.h" #include "playlistmanagewindow.h" #include "qmlplayer.h" #if defined(Q_OS_MACOS) # include "application.h" # include "serviceslots.h" #else # if defined(Q_OS_WIN) # include <Windows.h> # include <shellapi.h> # include <tchar.h> # if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) # include <QtPlatformHeaders/QWindowsWindowFunctions> # endif # endif # include "qtsingleapplication.h" #endif #if defined(Q_OS_MACOS) void serviceSearch(const QString &s) { if (configurationWindow) { configurationWindow->onSearch(s); } } void serviceOpenUrl(const QString &s) { if (configurationWindow) { configurationWindow->onSearch(s); } } void serviceOpenLink(const QString &s) { if (configurationWindow) { configurationWindow->onOpenLink(s); } } void serviceAppendToPlaylist(const QStringList &s) { if (playlistManageWindow) { playlistManageWindow->onAppendToPlaylist(s); } } void serviceClearAndAddToPlaylist(const QStringList &s) { if (playlistManageWindow) { playlistManageWindow->onClearAndAddToPlaylist(s); } } void serviceAppendToPlaylistFile(const QStringList &s) { if (playlistManageWindow) { playlistManageWindow->onAppendToPlaylistFile(s); } } void serviceClearAndAddToPlaylistFile(const QStringList &s) { if (playlistManageWindow) { playlistManageWindow->onClearAndAddToPlaylistFile(s); } } #endif void i18n(QTranslator &translator, QTranslator &qtTranslator) { QString locale = "zh_CN"; // main application and dynamic linked library locale QString localeDirPath = QCoreApplication::applicationDirPath() + #if defined(Q_OS_MACOS) "/../Resources/translations"; #else "/translations"; #endif if (translator.load("Hannah_" + locale, localeDirPath)) { qDebug() << "loading Hannah" << locale << " from " << localeDirPath << " success"; if (QCoreApplication::installTranslator(&translator)) { qDebug() << "installing translator success "; } } if (qtTranslator.load("qt_" + locale, localeDirPath)) { qDebug() << "loading qt" << locale << " from " << localeDirPath << " success"; if (QCoreApplication::installTranslator(&qtTranslator)) { qDebug() << "installing qt translator success "; } } } int main(int argc, char *argv[]) { #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #endif QCoreApplication::setApplicationName("Hannah"); QCoreApplication::setApplicationVersion("2.0"); QCoreApplication::setOrganizationName("Minidump.Info"); QCoreApplication::setOrganizationDomain("Minidump.Info"); QTranslator translator; QTranslator qtTranslator; // check the correct BASS was loaded if (HIWORD(BASS_GetVersion()) != BASSVERSION) { QMessageBox::critical(nullptr, QObject::tr("Critical Error"), QObject::tr("An incorrect version of BASS.DLL was loaded")); return -1; } BASS_SetConfig(BASS_CONFIG_UNICODE, TRUE); QIcon::setThemeName("musicplayer"); BeastServerRunner builtinReverseProxyRunner; ExternalReverseProxyRunner externalReverseProxyRunner; #if defined(Q_OS_MACOS) Application app(argc, argv); i18n(translator, qtTranslator); ConfigurationWindow configWin(builtinReverseProxyRunner, externalReverseProxyRunner); configWin.connect(&app, &Application::openUrl, &configWin, qOverload<const QUrl &>(&ConfigurationWindow::onOpenUrl)); configurationWindow = &configWin; void registerHannahService(); registerHannahService(); #else QtSingleApplication app(argc, argv); QCommandLineParser parser; parser.setApplicationDescription("Hannah"); parser.addHelpOption(); parser.addVersionOption(); parser.process(app); const QStringList args = parser.positionalArguments(); if (app.isRunning()) { if (args.length() > 0) { app.sendMessage(args.join("~")); } return 0; } # if defined(Q_OS_WIN) && (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) QWindowsWindowFunctions::setWindowActivationBehavior(QWindowsWindowFunctions::AlwaysActivateWindow); # endif i18n(translator, qtTranslator); ConfigurationWindow configWin(builtinReverseProxyRunner, externalReverseProxyRunner); QObject::connect(&app, &QtSingleApplication::messageReceived, &configWin, &ConfigurationWindow::onApplicationMessageReceived); configurationWindow = &configWin; if (args.length() > 0) { configWin.onApplicationMessageReceived(args.join("~")); } # if defined(Q_OS_WIN) else { QSettings mxKey("HKEY_CLASSES_ROOT\\hannah", QSettings::NativeFormat); QString v1 = mxKey.value(".").toString(); QSettings mxOpenKey(R"(HKEY_CLASSES_ROOT\hannah\shell\open\command)", QSettings::NativeFormat); QString v2 = mxOpenKey.value(".").toString(); if (v1 != "URL:hannah Protocol" || v2 != QChar('"') + QDir::toNativeSeparators(QCoreApplication::applicationFilePath()) + QStringLiteral(R"(" "%1")")) { auto cmd = QDir::toNativeSeparators(QCoreApplication::applicationDirPath() + "/registerProtocolHandler.exe"); auto workingDir = QDir::toNativeSeparators(QCoreApplication::applicationDirPath()); SHELLEXECUTEINFO execInfo; ZeroMemory(&execInfo, sizeof(execInfo)); execInfo.lpFile = (const wchar_t *)cmd.utf16(); execInfo.lpDirectory = (const wchar_t *)workingDir.utf16(); execInfo.cbSize = sizeof(execInfo); execInfo.lpVerb = L"runas"; execInfo.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI; execInfo.nShow = SW_HIDE; ShellExecuteEx(&execInfo); } } # endif #endif gQmlApplicationEngine = new QQmlApplicationEngine; QQmlContext *context = gQmlApplicationEngine->rootContext(); gBassPlayer = new BassPlayer; gQmlPlayer = new QmlPlayer; context->setContextProperty("playerCore", gQmlPlayer); gQmlApplicationEngine->load(QUrl("qrc:/rc/qml/musicplayer.qml")); gQmlPlayer->setTaskbarButtonWindow(); PlaylistManageWindow pmw; playlistManageWindow = &pmw; QtSingleApplication::setQuitOnLastWindowClosed(false); QSettings settings(QSettings::IniFormat, QSettings::UserScope, "minidump.info", "Hannah"); if (settings.value("useExternalReverseProxy", 2).toInt() == Qt::Checked) { externalReverseProxyRunner.applySettings(settings); externalReverseProxyRunner.start(); } else { builtinReverseProxyRunner.applySettings(settings); builtinReverseProxyRunner.start(); } QObject::connect(&app, &QCoreApplication::aboutToQuit, [&builtinReverseProxyRunner, &externalReverseProxyRunner]() { if (externalReverseProxyRunner.isRunning()) { externalReverseProxyRunner.stop(); } builtinReverseProxyRunner.stop(); builtinReverseProxyRunner.wait(); }); return QtSingleApplication::exec(); }
7,775
C++
.cpp
221
29.809955
140
0.689862
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,567
shadowlabel.cpp
missdeer_hannah/desktop/player/shadowlabel.cpp
#include <QPaintEvent> #include <QPainter> #include "shadowlabel.h" ShadowLabel::ShadowLabel(QWidget *parent) : QLabel(parent) {} void ShadowLabel::paintEvent(QPaintEvent * /*event*/) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing, true); painter.setFont(font()); painter.setPen(shadowColor); switch (shadowMode) { case 0: painter.drawText(2, 2, width() - 1, height() - 1, alignment(), text()); break; case 1: painter.drawText(0, 0, width() - 1, height() - 1, alignment(), text()); painter.drawText(0, 1, width() - 1, height() - 1, alignment(), text()); painter.drawText(0, 2, width() - 1, height() - 1, alignment(), text()); painter.drawText(1, 0, width() - 1, height() - 1, alignment(), text()); painter.drawText(1, 2, width() - 1, height() - 1, alignment(), text()); painter.drawText(2, 0, width() - 1, height() - 1, alignment(), text()); painter.drawText(2, 1, width() - 1, height() - 1, alignment(), text()); painter.drawText(2, 2, width() - 1, height() - 1, alignment(), text()); break; default: painter.drawText(1, 1, width(), height(), alignment(), text()); break; } painter.setPen(palette().color(QPalette::WindowText)); painter.drawText(1, 1, width() - 1, height() - 1, alignment(), text()); } void ShadowLabel::setShadowColor(QColor color) { shadowColor = color; } void ShadowLabel::setShadowMode(int mode) { shadowMode = mode; }
1,531
C++
.cpp
40
33.125
79
0.614141
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false